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.

281567 lines
7.6MB

  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 (JUCE_ANDROID)
  45. #undef JUCE_ANDROID
  46. #define JUCE_ANDROID 1
  47. #elif defined (LINUX) || defined (__linux__)
  48. #define JUCE_LINUX 1
  49. #elif defined (__APPLE_CPP__) || defined(__APPLE_CC__)
  50. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  51. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  52. #define JUCE_IPHONE 1
  53. #define JUCE_IOS 1
  54. #else
  55. #define JUCE_MAC 1
  56. #endif
  57. #else
  58. #error "Unknown platform!"
  59. #endif
  60. #if JUCE_WINDOWS
  61. #ifdef _MSC_VER
  62. #ifdef _WIN64
  63. #define JUCE_64BIT 1
  64. #else
  65. #define JUCE_32BIT 1
  66. #endif
  67. #endif
  68. #ifdef _DEBUG
  69. #define JUCE_DEBUG 1
  70. #endif
  71. #ifdef __MINGW32__
  72. #define JUCE_MINGW 1
  73. #endif
  74. /** If defined, this indicates that the processor is little-endian. */
  75. #define JUCE_LITTLE_ENDIAN 1
  76. #define JUCE_INTEL 1
  77. #endif
  78. #if JUCE_MAC || JUCE_IOS
  79. #if defined (DEBUG) || defined (_DEBUG) || ! (defined (NDEBUG) || defined (_NDEBUG))
  80. #define JUCE_DEBUG 1
  81. #endif
  82. #if ! (defined (DEBUG) || defined (_DEBUG) || defined (NDEBUG) || defined (_NDEBUG))
  83. #warning "Neither NDEBUG or DEBUG has been defined - you should set one of these to make it clear whether this is a release build,"
  84. #endif
  85. #ifdef __LITTLE_ENDIAN__
  86. #define JUCE_LITTLE_ENDIAN 1
  87. #else
  88. #define JUCE_BIG_ENDIAN 1
  89. #endif
  90. #endif
  91. #if JUCE_MAC
  92. #if defined (__ppc__) || defined (__ppc64__)
  93. #define JUCE_PPC 1
  94. #else
  95. #define JUCE_INTEL 1
  96. #endif
  97. #ifdef __LP64__
  98. #define JUCE_64BIT 1
  99. #else
  100. #define JUCE_32BIT 1
  101. #endif
  102. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  103. #error "Building for OSX 10.3 is no longer supported!"
  104. #endif
  105. #ifndef MAC_OS_X_VERSION_10_5
  106. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  107. #endif
  108. #endif
  109. #if JUCE_LINUX || JUCE_ANDROID
  110. #ifdef _DEBUG
  111. #define JUCE_DEBUG 1
  112. #endif
  113. // Allow override for big-endian Linux platforms
  114. #if defined (__LITTLE_ENDIAN__) || ! defined (JUCE_BIG_ENDIAN)
  115. #define JUCE_LITTLE_ENDIAN 1
  116. #undef JUCE_BIG_ENDIAN
  117. #else
  118. #undef JUCE_LITTLE_ENDIAN
  119. #define JUCE_BIG_ENDIAN 1
  120. #endif
  121. #if defined (__LP64__) || defined (_LP64)
  122. #define JUCE_64BIT 1
  123. #else
  124. #define JUCE_32BIT 1
  125. #endif
  126. #if __MMX__ || __SSE__ || __amd64__
  127. #define JUCE_INTEL 1
  128. #endif
  129. #endif
  130. // Compiler type macros.
  131. #ifdef __GNUC__
  132. #define JUCE_GCC 1
  133. #elif defined (_MSC_VER)
  134. #define JUCE_MSVC 1
  135. #if _MSC_VER < 1500
  136. #define JUCE_VC8_OR_EARLIER 1
  137. #if _MSC_VER < 1400
  138. #define JUCE_VC7_OR_EARLIER 1
  139. #if _MSC_VER < 1300
  140. #define JUCE_VC6 1
  141. #endif
  142. #endif
  143. #endif
  144. #if ! JUCE_VC7_OR_EARLIER && ! defined (__INTEL_COMPILER)
  145. #define JUCE_USE_INTRINSICS 1
  146. #endif
  147. #else
  148. #error unknown compiler
  149. #endif
  150. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  151. /*** End of inlined file: juce_TargetPlatform.h ***/
  152. // FORCE_AMALGAMATOR_INCLUDE
  153. /*** Start of inlined file: juce_Config.h ***/
  154. #ifndef __JUCE_CONFIG_JUCEHEADER__
  155. #define __JUCE_CONFIG_JUCEHEADER__
  156. /*
  157. This file contains macros that enable/disable various JUCE features.
  158. */
  159. /** The name of the namespace that all Juce classes and functions will be
  160. put inside. If this is not defined, no namespace will be used.
  161. */
  162. #ifndef JUCE_NAMESPACE
  163. #define JUCE_NAMESPACE juce
  164. #endif
  165. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  166. project settings, but if you define this value, you can override this to force
  167. it to be true or false.
  168. */
  169. #ifndef JUCE_FORCE_DEBUG
  170. //#define JUCE_FORCE_DEBUG 0
  171. #endif
  172. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  173. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  174. Enabling it will also leave this turned on in release builds. When it's disabled,
  175. however, the jassert and jassertfalse macros will not be compiled in a
  176. release build.
  177. @see jassert, jassertfalse, Logger
  178. */
  179. #ifndef JUCE_LOG_ASSERTIONS
  180. #define JUCE_LOG_ASSERTIONS 0
  181. #endif
  182. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  183. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  184. on your Windows build machine.
  185. See the comments in the ASIOAudioIODevice class's header file for more
  186. info about this.
  187. */
  188. #ifndef JUCE_ASIO
  189. #define JUCE_ASIO 0
  190. #endif
  191. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  192. */
  193. #ifndef JUCE_WASAPI
  194. #define JUCE_WASAPI 0
  195. #endif
  196. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  197. */
  198. #ifndef JUCE_DIRECTSOUND
  199. #define JUCE_DIRECTSOUND 1
  200. #endif
  201. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  202. #ifndef JUCE_ALSA
  203. #define JUCE_ALSA 1
  204. #endif
  205. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  206. #ifndef JUCE_JACK
  207. #define JUCE_JACK 0
  208. #endif
  209. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  210. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  211. installed, and its header files will need to be on your include path.
  212. */
  213. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IOS || JUCE_ANDROID || (JUCE_WINDOWS && ! JUCE_MSVC))
  214. #define JUCE_QUICKTIME 0
  215. #endif
  216. #if (JUCE_IOS || JUCE_LINUX) && JUCE_QUICKTIME
  217. #undef JUCE_QUICKTIME
  218. #endif
  219. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  220. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  221. */
  222. #if ! (defined (JUCE_OPENGL) || JUCE_ANDROID)
  223. #define JUCE_OPENGL 1
  224. #endif
  225. /** JUCE_DIRECT2D: Enables the Windows 7 Direct2D renderer.
  226. If you're building on a platform older than Vista, you won't be able to compile with this feature.
  227. */
  228. #ifndef JUCE_DIRECT2D
  229. #define JUCE_DIRECT2D 0
  230. #endif
  231. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  232. If your app doesn't need to read FLAC files, you might want to disable this to
  233. reduce the size of your codebase and build time.
  234. */
  235. #ifndef JUCE_USE_FLAC
  236. #define JUCE_USE_FLAC 1
  237. #endif
  238. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  239. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  240. reduce the size of your codebase and build time.
  241. */
  242. #ifndef JUCE_USE_OGGVORBIS
  243. #define JUCE_USE_OGGVORBIS 1
  244. #endif
  245. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  246. Unless you're using CD-burning, you should probably turn this flag off to
  247. reduce code size.
  248. */
  249. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  250. #define JUCE_USE_CDBURNER 1
  251. #endif
  252. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  253. Unless you're using CD-reading, you should probably turn this flag off to
  254. reduce code size.
  255. */
  256. #ifndef JUCE_USE_CDREADER
  257. #define JUCE_USE_CDREADER 1
  258. #endif
  259. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  260. */
  261. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  262. #define JUCE_USE_CAMERA 0
  263. #endif
  264. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  265. gets repainted will flash in a random colour, so that you can check exactly how much and how
  266. often your components are being drawn.
  267. */
  268. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  269. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  270. #endif
  271. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  272. Unless you specifically want to disable this, it's best to leave this option turned on.
  273. */
  274. #ifndef JUCE_USE_XINERAMA
  275. #define JUCE_USE_XINERAMA 1
  276. #endif
  277. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  278. turned on unless you have a good reason to disable it.
  279. */
  280. #ifndef JUCE_USE_XSHM
  281. #define JUCE_USE_XSHM 1
  282. #endif
  283. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  284. */
  285. #ifndef JUCE_USE_XRENDER
  286. #define JUCE_USE_XRENDER 0
  287. #endif
  288. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  289. unless you have a good reason to disable it.
  290. */
  291. #ifndef JUCE_USE_XCURSOR
  292. #define JUCE_USE_XCURSOR 1
  293. #endif
  294. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  295. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  296. you're building a plugin hosting app.
  297. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  298. */
  299. #ifndef JUCE_PLUGINHOST_VST
  300. #define JUCE_PLUGINHOST_VST 0
  301. #endif
  302. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  303. of course, and should only be enabled if you're building a plugin hosting app.
  304. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  305. */
  306. #ifndef JUCE_PLUGINHOST_AU
  307. #define JUCE_PLUGINHOST_AU 0
  308. #endif
  309. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  310. This should be enabled if you're writing a console application.
  311. */
  312. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  313. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  314. #endif
  315. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  316. If you're not using any embedded web-pages, turning this off may reduce your code size.
  317. */
  318. #ifndef JUCE_WEB_BROWSER
  319. #define JUCE_WEB_BROWSER 1
  320. #endif
  321. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  322. Carbon isn't required for a normal app, but may be needed by specialised classes like
  323. plugin-hosts, which support older APIs.
  324. */
  325. #if ! (defined (JUCE_SUPPORT_CARBON) || defined (__LP64__))
  326. #define JUCE_SUPPORT_CARBON 1
  327. #endif
  328. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  329. You might need to tweak this if you're linking to an external zlib library in your app,
  330. but for normal apps, this option should be left alone.
  331. */
  332. #ifndef JUCE_INCLUDE_ZLIB_CODE
  333. #define JUCE_INCLUDE_ZLIB_CODE 1
  334. #endif
  335. #ifndef JUCE_INCLUDE_FLAC_CODE
  336. #define JUCE_INCLUDE_FLAC_CODE 1
  337. #endif
  338. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  339. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  340. #endif
  341. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  342. #define JUCE_INCLUDE_PNGLIB_CODE 1
  343. #endif
  344. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  345. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  346. #endif
  347. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check for certain objects when
  348. the app terminates. See the LeakedObjectDetector class and the JUCE_LEAK_DETECTOR
  349. macro for more details about enabling leak checking for specific classes.
  350. */
  351. #if JUCE_DEBUG && ! defined (JUCE_CHECK_MEMORY_LEAKS)
  352. #define JUCE_CHECK_MEMORY_LEAKS 1
  353. #endif
  354. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  355. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  356. are passed to the JUCEApplication::unhandledException() callback for logging.
  357. */
  358. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  359. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  360. #endif
  361. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  362. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  363. #undef JUCE_QUICKTIME
  364. #define JUCE_QUICKTIME 0
  365. #undef JUCE_OPENGL
  366. #define JUCE_OPENGL 0
  367. #undef JUCE_USE_CDBURNER
  368. #define JUCE_USE_CDBURNER 0
  369. #undef JUCE_USE_CDREADER
  370. #define JUCE_USE_CDREADER 0
  371. #undef JUCE_WEB_BROWSER
  372. #define JUCE_WEB_BROWSER 0
  373. #undef JUCE_PLUGINHOST_AU
  374. #define JUCE_PLUGINHOST_AU 0
  375. #undef JUCE_PLUGINHOST_VST
  376. #define JUCE_PLUGINHOST_VST 0
  377. #endif
  378. #endif
  379. /*** End of inlined file: juce_Config.h ***/
  380. // FORCE_AMALGAMATOR_INCLUDE
  381. #ifndef JUCE_BUILD_CORE
  382. #define JUCE_BUILD_CORE 1
  383. #endif
  384. #ifndef JUCE_BUILD_MISC
  385. #define JUCE_BUILD_MISC 1
  386. #endif
  387. #ifndef JUCE_BUILD_GUI
  388. #define JUCE_BUILD_GUI 1
  389. #endif
  390. #ifndef JUCE_BUILD_NATIVE
  391. #define JUCE_BUILD_NATIVE 1
  392. #endif
  393. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  394. #undef JUCE_BUILD_MISC
  395. #undef JUCE_BUILD_GUI
  396. #endif
  397. //==============================================================================
  398. #if JUCE_BUILD_NATIVE || JUCE_BUILD_CORE || (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU))
  399. #if JUCE_WINDOWS
  400. /*** Start of inlined file: juce_win32_NativeIncludes.h ***/
  401. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  402. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  403. #ifndef STRICT
  404. #define STRICT 1
  405. #endif
  406. #undef WIN32_LEAN_AND_MEAN
  407. #define WIN32_LEAN_AND_MEAN 1
  408. #if JUCE_MSVC
  409. #pragma warning (push)
  410. #pragma warning (disable : 4100 4201 4514 4312 4995)
  411. #endif
  412. #define _WIN32_WINNT 0x0500
  413. #define _UNICODE 1
  414. #define UNICODE 1
  415. #ifndef _WIN32_IE
  416. #define _WIN32_IE 0x0400
  417. #endif
  418. #include <windows.h>
  419. #include <windowsx.h>
  420. #include <commdlg.h>
  421. #include <shellapi.h>
  422. #include <mmsystem.h>
  423. #include <vfw.h>
  424. #include <tchar.h>
  425. #include <stddef.h>
  426. #include <ctime>
  427. #include <wininet.h>
  428. #include <nb30.h>
  429. #include <iphlpapi.h>
  430. #include <mapi.h>
  431. #include <float.h>
  432. #include <process.h>
  433. #include <Exdisp.h>
  434. #include <exdispid.h>
  435. #include <shlobj.h>
  436. #include <shlwapi.h>
  437. #if ! JUCE_MINGW
  438. #include <crtdbg.h>
  439. #include <comutil.h>
  440. #endif
  441. #if JUCE_OPENGL
  442. #include <gl/gl.h>
  443. #endif
  444. #undef PACKED
  445. #if JUCE_ASIO && JUCE_BUILD_NATIVE
  446. /*
  447. This is very frustrating - we only need to use a handful of definitions from
  448. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  449. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  450. implementation...
  451. ..unfortunately that would break Steinberg's license agreement for use of
  452. their SDK, so I'm not allowed to do this.
  453. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  454. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  455. (see www.steinberg.net/Steinberg/Developers.asp).
  456. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  457. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  458. if you prefer). Make sure that your header search path will find the
  459. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  460. files are actually needed - so to simplify things, you could just copy
  461. these into your JUCE directory).
  462. If you're compiling and you get an error here because you don't have the
  463. ASIO SDK installed, you can disable ASIO support by commenting-out the
  464. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  465. */
  466. #include <iasiodrv.h>
  467. #endif
  468. #if JUCE_USE_CDBURNER && JUCE_BUILD_NATIVE
  469. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  470. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  471. flag in juce_Config.h to avoid these includes.
  472. */
  473. #include <imapi.h>
  474. #include <imapierror.h>
  475. #endif
  476. #if JUCE_USE_CAMERA && JUCE_BUILD_NATIVE
  477. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  478. These files are provided in the normal Windows SDK, but some Microsoft plonker
  479. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK..
  480. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  481. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  482. .. which is a bit of a bodge, but a lot less hassle than installing the full DShow SDK.
  483. An alternative workaround is to create a dummy dxtrans.h file and put it in your include path.
  484. The dummy file just needs to contain the following content:
  485. #define __IDxtCompositor_INTERFACE_DEFINED__
  486. #define __IDxtAlphaSetter_INTERFACE_DEFINED__
  487. #define __IDxtJpeg_INTERFACE_DEFINED__
  488. #define __IDxtKey_INTERFACE_DEFINED__
  489. ..and that should be enough to convince qedit.h that you have the SDK!
  490. */
  491. #include <dshow.h>
  492. #include <qedit.h>
  493. #include <dshowasf.h>
  494. #endif
  495. #if JUCE_WASAPI && JUCE_BUILD_NATIVE
  496. #include <MMReg.h>
  497. #include <mmdeviceapi.h>
  498. #include <Audioclient.h>
  499. #include <Avrt.h>
  500. #include <functiondiscoverykeys.h>
  501. #endif
  502. #if JUCE_QUICKTIME
  503. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  504. add its header directory to your include path.
  505. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  506. flag in juce_Config.h
  507. */
  508. #include <Movies.h>
  509. #include <QTML.h>
  510. #include <QuickTimeComponents.h>
  511. #include <MediaHandlers.h>
  512. #include <ImageCodec.h>
  513. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  514. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  515. your include search path to make these import statements work.
  516. */
  517. #import <QTOLibrary.dll>
  518. #import <QTOControl.dll>
  519. #endif
  520. #if JUCE_MSVC
  521. #pragma warning (pop)
  522. #endif
  523. #if JUCE_DIRECT2D && JUCE_BUILD_NATIVE
  524. #include <d2d1.h>
  525. #include <dwrite.h>
  526. #endif
  527. /** A simple COM smart pointer.
  528. Avoids having to include ATL just to get one of these.
  529. */
  530. template <class ComClass>
  531. class ComSmartPtr
  532. {
  533. public:
  534. ComSmartPtr() throw() : p (0) {}
  535. ComSmartPtr (ComClass* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  536. ComSmartPtr (const ComSmartPtr<ComClass>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  537. ~ComSmartPtr() { release(); }
  538. operator ComClass*() const throw() { return p; }
  539. ComClass& operator*() const throw() { return *p; }
  540. ComClass* operator->() const throw() { return p; }
  541. ComSmartPtr& operator= (ComClass* const newP)
  542. {
  543. if (newP != 0) newP->AddRef();
  544. release();
  545. p = newP;
  546. return *this;
  547. }
  548. ComSmartPtr& operator= (const ComSmartPtr<ComClass>& newP) { return operator= (newP.p); }
  549. // Releases and nullifies this pointer and returns its address
  550. ComClass** resetAndGetPointerAddress()
  551. {
  552. release();
  553. p = 0;
  554. return &p;
  555. }
  556. HRESULT CoCreateInstance (REFCLSID classUUID, DWORD dwClsContext = CLSCTX_INPROC_SERVER)
  557. {
  558. #ifndef __MINGW32__
  559. return ::CoCreateInstance (classUUID, 0, dwClsContext, __uuidof (ComClass), (void**) resetAndGetPointerAddress());
  560. #else
  561. return E_NOTIMPL;
  562. #endif
  563. }
  564. template <class OtherComClass>
  565. HRESULT QueryInterface (REFCLSID classUUID, ComSmartPtr<OtherComClass>& destObject) const
  566. {
  567. if (p == 0)
  568. return E_POINTER;
  569. return p->QueryInterface (classUUID, (void**) destObject.resetAndGetPointerAddress());
  570. }
  571. private:
  572. ComClass* p;
  573. void release() { if (p != 0) p->Release(); }
  574. ComClass** operator&() throw(); // private to avoid it being used accidentally
  575. };
  576. /** Handy base class for writing COM objects, providing ref-counting and a basic QueryInterface method.
  577. */
  578. template <class ComClass>
  579. class ComBaseClassHelper : public ComClass
  580. {
  581. public:
  582. ComBaseClassHelper() : refCount (1) {}
  583. virtual ~ComBaseClassHelper() {}
  584. HRESULT __stdcall QueryInterface (REFIID refId, void** result)
  585. {
  586. #ifndef __MINGW32__
  587. if (refId == __uuidof (ComClass)) { AddRef(); *result = dynamic_cast <ComClass*> (this); return S_OK; }
  588. #endif
  589. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  590. *result = 0;
  591. return E_NOINTERFACE;
  592. }
  593. ULONG __stdcall AddRef() { return ++refCount; }
  594. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  595. protected:
  596. int refCount;
  597. };
  598. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  599. /*** End of inlined file: juce_win32_NativeIncludes.h ***/
  600. #elif JUCE_LINUX
  601. /*** Start of inlined file: juce_linux_NativeIncludes.h ***/
  602. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  603. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  604. /*
  605. This file wraps together all the linux-specific headers, so
  606. that we can include them all just once, and compile all our
  607. platform-specific stuff in one big lump, keeping it out of the
  608. way of the rest of the codebase.
  609. */
  610. #include <sched.h>
  611. #include <pthread.h>
  612. #include <sys/time.h>
  613. #include <errno.h>
  614. #include <sys/stat.h>
  615. #include <sys/dir.h>
  616. #include <sys/ptrace.h>
  617. #include <sys/vfs.h>
  618. #include <sys/wait.h>
  619. #include <fnmatch.h>
  620. #include <utime.h>
  621. #include <pwd.h>
  622. #include <fcntl.h>
  623. #include <dlfcn.h>
  624. #include <netdb.h>
  625. #include <arpa/inet.h>
  626. #include <netinet/in.h>
  627. #include <sys/types.h>
  628. #include <sys/ioctl.h>
  629. #include <sys/socket.h>
  630. #include <net/if.h>
  631. #include <sys/sysinfo.h>
  632. #include <sys/file.h>
  633. #include <sys/prctl.h>
  634. #include <signal.h>
  635. /* Got a build error here? You'll need to install the freetype library...
  636. The name of the package to install is "libfreetype6-dev".
  637. */
  638. #include <ft2build.h>
  639. #include FT_FREETYPE_H
  640. #include <X11/Xlib.h>
  641. #include <X11/Xatom.h>
  642. #include <X11/Xresource.h>
  643. #include <X11/Xutil.h>
  644. #include <X11/Xmd.h>
  645. #include <X11/keysym.h>
  646. #include <X11/cursorfont.h>
  647. #if JUCE_USE_XINERAMA
  648. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  649. #include <X11/extensions/Xinerama.h>
  650. #endif
  651. #if JUCE_USE_XSHM
  652. #include <X11/extensions/XShm.h>
  653. #include <sys/shm.h>
  654. #include <sys/ipc.h>
  655. #endif
  656. #if JUCE_USE_XRENDER
  657. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  658. #include <X11/extensions/Xrender.h>
  659. #include <X11/extensions/Xcomposite.h>
  660. #endif
  661. #if JUCE_USE_XCURSOR
  662. // If you're missing this header, try installing the libxcursor-dev package
  663. #include <X11/Xcursor/Xcursor.h>
  664. #endif
  665. #if JUCE_OPENGL
  666. /* Got an include error here?
  667. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  668. and "freeglut3-dev".
  669. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  670. want to disable it.
  671. */
  672. #include <GL/glx.h>
  673. #endif
  674. #undef KeyPress
  675. #if JUCE_ALSA
  676. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  677. not got your paths set up correctly to find its header files.
  678. The package you need to install to get ASLA support is "libasound2-dev".
  679. If you don't have the ALSA library and don't want to build Juce with audio support,
  680. just disable the JUCE_ALSA flag in juce_Config.h
  681. */
  682. #include <alsa/asoundlib.h>
  683. #endif
  684. #if JUCE_JACK
  685. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  686. installed, or you've not got your paths set up correctly to find its header files.
  687. The package you need to install to get JACK support is "libjack-dev".
  688. If you don't have the jack-audio-connection-kit library and don't want to build
  689. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  690. */
  691. #include <jack/jack.h>
  692. //#include <jack/transport.h>
  693. #endif
  694. #undef SIZEOF
  695. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  696. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  697. #elif JUCE_MAC || JUCE_IOS
  698. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  699. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  700. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  701. #define USE_COREGRAPHICS_RENDERING 1
  702. #if JUCE_IOS
  703. #import <Foundation/Foundation.h>
  704. #import <UIKit/UIKit.h>
  705. #import <AudioToolbox/AudioToolbox.h>
  706. #import <AVFoundation/AVFoundation.h>
  707. #import <CoreData/CoreData.h>
  708. #import <MobileCoreServices/MobileCoreServices.h>
  709. #import <QuartzCore/QuartzCore.h>
  710. #include <sys/fcntl.h>
  711. #if JUCE_OPENGL
  712. #include <OpenGLES/ES1/gl.h>
  713. #include <OpenGLES/ES1/glext.h>
  714. #endif
  715. #else
  716. #import <Cocoa/Cocoa.h>
  717. #import <CoreAudio/HostTime.h>
  718. #if JUCE_BUILD_NATIVE
  719. #import <CoreAudio/AudioHardware.h>
  720. #import <CoreMIDI/MIDIServices.h>
  721. #import <QTKit/QTKit.h>
  722. #import <WebKit/WebKit.h>
  723. #import <DiscRecording/DiscRecording.h>
  724. #import <IOKit/IOKitLib.h>
  725. #import <IOKit/IOCFPlugIn.h>
  726. #import <IOKit/hid/IOHIDLib.h>
  727. #import <IOKit/hid/IOHIDKeys.h>
  728. #import <IOKit/pwr_mgt/IOPMLib.h>
  729. #endif
  730. #if (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU)) \
  731. || ! (defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6)
  732. #include <Carbon/Carbon.h>
  733. #endif
  734. #include <sys/dir.h>
  735. #endif
  736. #include <sys/socket.h>
  737. #include <sys/sysctl.h>
  738. #include <sys/stat.h>
  739. #include <sys/param.h>
  740. #include <sys/mount.h>
  741. #include <fnmatch.h>
  742. #include <utime.h>
  743. #include <dlfcn.h>
  744. #include <ifaddrs.h>
  745. #include <net/if_dl.h>
  746. #include <mach/mach_time.h>
  747. #include <mach-o/dyld.h>
  748. #if MACOS_10_4_OR_EARLIER
  749. #include <GLUT/glut.h>
  750. #endif
  751. #if ! CGFLOAT_DEFINED
  752. #define CGFloat float
  753. #endif
  754. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  755. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  756. #elif JUCE_ANDROID
  757. /*** Start of inlined file: juce_android_NativeIncludes.h ***/
  758. #ifndef __JUCE_ANDROID_NATIVEINCLUDES_JUCEHEADER__
  759. #define __JUCE_ANDROID_NATIVEINCLUDES_JUCEHEADER__
  760. #include <jni.h>
  761. #include <pthread.h>
  762. #include <sched.h>
  763. #include <sys/time.h>
  764. #include <utime.h>
  765. #include <errno.h>
  766. #include <fcntl.h>
  767. #include <dlfcn.h>
  768. #include <sys/stat.h>
  769. #include <sys/statfs.h>
  770. #include <sys/ptrace.h>
  771. #include <sys/sysinfo.h>
  772. #include <pwd.h>
  773. #include <dirent.h>
  774. #include <fnmatch.h>
  775. #if JUCE_OPENGL
  776. #include <GLES/gl.h>
  777. #endif
  778. #endif // __JUCE_ANDROID_NATIVEINCLUDES_JUCEHEADER__
  779. /*** End of inlined file: juce_android_NativeIncludes.h ***/
  780. #else
  781. #error "Unknown platform!"
  782. #endif
  783. #endif
  784. //==============================================================================
  785. #define DONT_SET_USING_JUCE_NAMESPACE 1
  786. #undef max
  787. #undef min
  788. #define NO_DUMMY_DECL
  789. #define JUCE_AMALGAMATED_TEMPLATE 1
  790. #if JUCE_BUILD_NATIVE
  791. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  792. #endif
  793. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  794. #pragma warning (disable: 4309 4305)
  795. #endif
  796. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  797. BEGIN_JUCE_NAMESPACE
  798. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  799. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  800. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  801. /**
  802. Creates a floating carbon window that can be used to hold a carbon UI.
  803. This is a handy class that's designed to be inlined where needed, e.g.
  804. in the audio plugin hosting code.
  805. */
  806. class CarbonViewWrapperComponent : public Component,
  807. public ComponentMovementWatcher,
  808. public Timer
  809. {
  810. public:
  811. CarbonViewWrapperComponent()
  812. : ComponentMovementWatcher (this),
  813. wrapperWindow (0),
  814. carbonWindow (0),
  815. embeddedView (0),
  816. recursiveResize (false)
  817. {
  818. }
  819. virtual ~CarbonViewWrapperComponent()
  820. {
  821. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  822. }
  823. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  824. virtual void removeView (HIViewRef embeddedView) = 0;
  825. virtual void mouseDown (int, int) {}
  826. virtual void paint() {}
  827. virtual bool getEmbeddedViewSize (int& w, int& h)
  828. {
  829. if (embeddedView == 0)
  830. return false;
  831. HIRect bounds;
  832. HIViewGetBounds (embeddedView, &bounds);
  833. w = jmax (1, roundToInt (bounds.size.width));
  834. h = jmax (1, roundToInt (bounds.size.height));
  835. return true;
  836. }
  837. void createWindow()
  838. {
  839. if (wrapperWindow == 0)
  840. {
  841. Rect r;
  842. r.left = getScreenX();
  843. r.top = getScreenY();
  844. r.right = r.left + getWidth();
  845. r.bottom = r.top + getHeight();
  846. CreateNewWindow (kDocumentWindowClass,
  847. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  848. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  849. &r, &wrapperWindow);
  850. jassert (wrapperWindow != 0);
  851. if (wrapperWindow == 0)
  852. return;
  853. carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  854. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  855. [ownerWindow addChildWindow: carbonWindow
  856. ordered: NSWindowAbove];
  857. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  858. EventTypeSpec windowEventTypes[] =
  859. {
  860. { kEventClassWindow, kEventWindowGetClickActivation },
  861. { kEventClassWindow, kEventWindowHandleDeactivate },
  862. { kEventClassWindow, kEventWindowBoundsChanging },
  863. { kEventClassMouse, kEventMouseDown },
  864. { kEventClassMouse, kEventMouseMoved },
  865. { kEventClassMouse, kEventMouseDragged },
  866. { kEventClassMouse, kEventMouseUp},
  867. { kEventClassWindow, kEventWindowDrawContent },
  868. { kEventClassWindow, kEventWindowShown },
  869. { kEventClassWindow, kEventWindowHidden }
  870. };
  871. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  872. InstallWindowEventHandler (wrapperWindow, upp,
  873. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  874. windowEventTypes, this, &eventHandlerRef);
  875. setOurSizeToEmbeddedViewSize();
  876. setEmbeddedWindowToOurSize();
  877. creationTime = Time::getCurrentTime();
  878. }
  879. }
  880. void deleteWindow()
  881. {
  882. removeView (embeddedView);
  883. embeddedView = 0;
  884. if (wrapperWindow != 0)
  885. {
  886. RemoveEventHandler (eventHandlerRef);
  887. DisposeWindow (wrapperWindow);
  888. wrapperWindow = 0;
  889. }
  890. }
  891. void setOurSizeToEmbeddedViewSize()
  892. {
  893. int w, h;
  894. if (getEmbeddedViewSize (w, h))
  895. {
  896. if (w != getWidth() || h != getHeight())
  897. {
  898. startTimer (50);
  899. setSize (w, h);
  900. if (getParentComponent() != 0)
  901. getParentComponent()->setSize (w, h);
  902. }
  903. else
  904. {
  905. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  906. }
  907. }
  908. else
  909. {
  910. stopTimer();
  911. }
  912. }
  913. void setEmbeddedWindowToOurSize()
  914. {
  915. if (! recursiveResize)
  916. {
  917. recursiveResize = true;
  918. if (embeddedView != 0)
  919. {
  920. HIRect r;
  921. r.origin.x = 0;
  922. r.origin.y = 0;
  923. r.size.width = (float) getWidth();
  924. r.size.height = (float) getHeight();
  925. HIViewSetFrame (embeddedView, &r);
  926. }
  927. if (wrapperWindow != 0)
  928. {
  929. Rect wr;
  930. wr.left = getScreenX();
  931. wr.top = getScreenY();
  932. wr.right = wr.left + getWidth();
  933. wr.bottom = wr.top + getHeight();
  934. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  935. ShowWindow (wrapperWindow);
  936. }
  937. recursiveResize = false;
  938. }
  939. }
  940. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  941. {
  942. setEmbeddedWindowToOurSize();
  943. }
  944. void componentPeerChanged()
  945. {
  946. deleteWindow();
  947. createWindow();
  948. }
  949. void componentVisibilityChanged()
  950. {
  951. if (isShowing())
  952. createWindow();
  953. else
  954. deleteWindow();
  955. setEmbeddedWindowToOurSize();
  956. }
  957. static void recursiveHIViewRepaint (HIViewRef view)
  958. {
  959. HIViewSetNeedsDisplay (view, true);
  960. HIViewRef child = HIViewGetFirstSubview (view);
  961. while (child != 0)
  962. {
  963. recursiveHIViewRepaint (child);
  964. child = HIViewGetNextView (child);
  965. }
  966. }
  967. void timerCallback()
  968. {
  969. setOurSizeToEmbeddedViewSize();
  970. // To avoid strange overpainting problems when the UI is first opened, we'll
  971. // repaint it a few times during the first second that it's on-screen..
  972. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  973. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  974. }
  975. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/, EventRef event)
  976. {
  977. switch (GetEventKind (event))
  978. {
  979. case kEventWindowHandleDeactivate:
  980. ActivateWindow (wrapperWindow, TRUE);
  981. return noErr;
  982. case kEventWindowGetClickActivation:
  983. {
  984. getTopLevelComponent()->toFront (false);
  985. [carbonWindow makeKeyAndOrderFront: nil];
  986. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  987. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  988. sizeof (ClickActivationResult), &howToHandleClick);
  989. HIViewSetNeedsDisplay (embeddedView, true);
  990. return noErr;
  991. }
  992. }
  993. return eventNotHandledErr;
  994. }
  995. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef, EventRef event, void* userData)
  996. {
  997. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  998. }
  999. protected:
  1000. WindowRef wrapperWindow;
  1001. NSWindow* carbonWindow;
  1002. HIViewRef embeddedView;
  1003. bool recursiveResize;
  1004. Time creationTime;
  1005. EventHandlerRef eventHandlerRef;
  1006. };
  1007. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  1008. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  1009. END_JUCE_NAMESPACE
  1010. #endif
  1011. //==============================================================================
  1012. #if JUCE_BUILD_CORE
  1013. /*** Start of inlined file: juce_FileLogger.cpp ***/
  1014. BEGIN_JUCE_NAMESPACE
  1015. FileLogger::FileLogger (const File& logFile_,
  1016. const String& welcomeMessage,
  1017. const int maxInitialFileSizeBytes)
  1018. : logFile (logFile_)
  1019. {
  1020. if (maxInitialFileSizeBytes >= 0)
  1021. trimFileSize (maxInitialFileSizeBytes);
  1022. if (! logFile_.exists())
  1023. {
  1024. // do this so that the parent directories get created..
  1025. logFile_.create();
  1026. }
  1027. String welcome;
  1028. welcome << newLine
  1029. << "**********************************************************" << newLine
  1030. << welcomeMessage << newLine
  1031. << "Log started: " << Time::getCurrentTime().toString (true, true) << newLine;
  1032. logMessage (welcome);
  1033. }
  1034. FileLogger::~FileLogger()
  1035. {
  1036. }
  1037. void FileLogger::logMessage (const String& message)
  1038. {
  1039. DBG (message);
  1040. const ScopedLock sl (logLock);
  1041. FileOutputStream out (logFile, 256);
  1042. out << message << newLine;
  1043. }
  1044. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  1045. {
  1046. if (maxFileSizeBytes <= 0)
  1047. {
  1048. logFile.deleteFile();
  1049. }
  1050. else
  1051. {
  1052. const int64 fileSize = logFile.getSize();
  1053. if (fileSize > maxFileSizeBytes)
  1054. {
  1055. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  1056. jassert (in != 0);
  1057. if (in != 0)
  1058. {
  1059. in->setPosition (fileSize - maxFileSizeBytes);
  1060. String content;
  1061. {
  1062. MemoryBlock contentToSave;
  1063. contentToSave.setSize (maxFileSizeBytes + 4);
  1064. contentToSave.fillWith (0);
  1065. in->read (contentToSave.getData(), maxFileSizeBytes);
  1066. in = 0;
  1067. content = contentToSave.toString();
  1068. }
  1069. int newStart = 0;
  1070. while (newStart < fileSize
  1071. && content[newStart] != '\n'
  1072. && content[newStart] != '\r')
  1073. ++newStart;
  1074. logFile.deleteFile();
  1075. logFile.appendText (content.substring (newStart), false, false);
  1076. }
  1077. }
  1078. }
  1079. }
  1080. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1081. const String& logFileName,
  1082. const String& welcomeMessage,
  1083. const int maxInitialFileSizeBytes)
  1084. {
  1085. #if JUCE_MAC
  1086. File logFile ("~/Library/Logs");
  1087. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1088. .getChildFile (logFileName);
  1089. #else
  1090. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1091. if (logFile.isDirectory())
  1092. {
  1093. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1094. .getChildFile (logFileName);
  1095. }
  1096. #endif
  1097. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1098. }
  1099. END_JUCE_NAMESPACE
  1100. /*** End of inlined file: juce_FileLogger.cpp ***/
  1101. /*** Start of inlined file: juce_Logger.cpp ***/
  1102. BEGIN_JUCE_NAMESPACE
  1103. Logger::Logger()
  1104. {
  1105. }
  1106. Logger::~Logger()
  1107. {
  1108. }
  1109. Logger* Logger::currentLogger = 0;
  1110. void Logger::setCurrentLogger (Logger* const newLogger,
  1111. const bool deleteOldLogger)
  1112. {
  1113. Logger* const oldLogger = currentLogger;
  1114. currentLogger = newLogger;
  1115. if (deleteOldLogger)
  1116. delete oldLogger;
  1117. }
  1118. void Logger::writeToLog (const String& message)
  1119. {
  1120. if (currentLogger != 0)
  1121. currentLogger->logMessage (message);
  1122. else
  1123. outputDebugString (message);
  1124. }
  1125. #if JUCE_LOG_ASSERTIONS
  1126. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1127. {
  1128. String m ("JUCE Assertion failure in ");
  1129. m << filename << ", line " << lineNum;
  1130. Logger::writeToLog (m);
  1131. }
  1132. #endif
  1133. END_JUCE_NAMESPACE
  1134. /*** End of inlined file: juce_Logger.cpp ***/
  1135. /*** Start of inlined file: juce_Random.cpp ***/
  1136. BEGIN_JUCE_NAMESPACE
  1137. Random::Random (const int64 seedValue) throw()
  1138. : seed (seedValue)
  1139. {
  1140. }
  1141. Random::~Random() throw()
  1142. {
  1143. }
  1144. void Random::setSeed (const int64 newSeed) throw()
  1145. {
  1146. seed = newSeed;
  1147. }
  1148. void Random::combineSeed (const int64 seedValue) throw()
  1149. {
  1150. seed ^= nextInt64() ^ seedValue;
  1151. }
  1152. void Random::setSeedRandomly()
  1153. {
  1154. combineSeed ((int64) (pointer_sized_int) this);
  1155. combineSeed (Time::getMillisecondCounter());
  1156. combineSeed (Time::getHighResolutionTicks());
  1157. combineSeed (Time::getHighResolutionTicksPerSecond());
  1158. combineSeed (Time::currentTimeMillis());
  1159. }
  1160. int Random::nextInt() throw()
  1161. {
  1162. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1163. return (int) (seed >> 16);
  1164. }
  1165. int Random::nextInt (const int maxValue) throw()
  1166. {
  1167. jassert (maxValue > 0);
  1168. return (nextInt() & 0x7fffffff) % maxValue;
  1169. }
  1170. int64 Random::nextInt64() throw()
  1171. {
  1172. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1173. }
  1174. bool Random::nextBool() throw()
  1175. {
  1176. return (nextInt() & 0x80000000) != 0;
  1177. }
  1178. float Random::nextFloat() throw()
  1179. {
  1180. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1181. }
  1182. double Random::nextDouble() throw()
  1183. {
  1184. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1185. }
  1186. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1187. {
  1188. BigInteger n;
  1189. do
  1190. {
  1191. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1192. }
  1193. while (n >= maximumValue);
  1194. return n;
  1195. }
  1196. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1197. {
  1198. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1199. while ((startBit & 31) != 0 && numBits > 0)
  1200. {
  1201. arrayToChange.setBit (startBit++, nextBool());
  1202. --numBits;
  1203. }
  1204. while (numBits >= 32)
  1205. {
  1206. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1207. startBit += 32;
  1208. numBits -= 32;
  1209. }
  1210. while (--numBits >= 0)
  1211. arrayToChange.setBit (startBit + numBits, nextBool());
  1212. }
  1213. Random& Random::getSystemRandom() throw()
  1214. {
  1215. static Random sysRand (1);
  1216. return sysRand;
  1217. }
  1218. END_JUCE_NAMESPACE
  1219. /*** End of inlined file: juce_Random.cpp ***/
  1220. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1221. BEGIN_JUCE_NAMESPACE
  1222. RelativeTime::RelativeTime (const double seconds_) throw()
  1223. : seconds (seconds_)
  1224. {
  1225. }
  1226. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1227. : seconds (other.seconds)
  1228. {
  1229. }
  1230. RelativeTime::~RelativeTime() throw()
  1231. {
  1232. }
  1233. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw() { return RelativeTime (milliseconds * 0.001); }
  1234. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw() { return RelativeTime (milliseconds * 0.001); }
  1235. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw() { return RelativeTime (numberOfMinutes * 60.0); }
  1236. const RelativeTime RelativeTime::hours (const double numberOfHours) throw() { return RelativeTime (numberOfHours * (60.0 * 60.0)); }
  1237. const RelativeTime RelativeTime::days (const double numberOfDays) throw() { return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0)); }
  1238. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw() { return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0)); }
  1239. int64 RelativeTime::inMilliseconds() const throw() { return (int64) (seconds * 1000.0); }
  1240. double RelativeTime::inMinutes() const throw() { return seconds / 60.0; }
  1241. double RelativeTime::inHours() const throw() { return seconds / (60.0 * 60.0); }
  1242. double RelativeTime::inDays() const throw() { return seconds / (60.0 * 60.0 * 24.0); }
  1243. double RelativeTime::inWeeks() const throw() { return seconds / (60.0 * 60.0 * 24.0 * 7.0); }
  1244. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const
  1245. {
  1246. if (seconds < 0.001 && seconds > -0.001)
  1247. return returnValueForZeroTime;
  1248. String result;
  1249. result.preallocateStorage (16);
  1250. if (seconds < 0)
  1251. result << '-';
  1252. int fieldsShown = 0;
  1253. int n = std::abs ((int) inWeeks());
  1254. if (n > 0)
  1255. {
  1256. result << n << (n == 1 ? TRANS(" week ")
  1257. : TRANS(" weeks "));
  1258. ++fieldsShown;
  1259. }
  1260. n = std::abs ((int) inDays()) % 7;
  1261. if (n > 0)
  1262. {
  1263. result << n << (n == 1 ? TRANS(" day ")
  1264. : TRANS(" days "));
  1265. ++fieldsShown;
  1266. }
  1267. if (fieldsShown < 2)
  1268. {
  1269. n = std::abs ((int) inHours()) % 24;
  1270. if (n > 0)
  1271. {
  1272. result << n << (n == 1 ? TRANS(" hr ")
  1273. : TRANS(" hrs "));
  1274. ++fieldsShown;
  1275. }
  1276. if (fieldsShown < 2)
  1277. {
  1278. n = std::abs ((int) inMinutes()) % 60;
  1279. if (n > 0)
  1280. {
  1281. result << n << (n == 1 ? TRANS(" min ")
  1282. : TRANS(" mins "));
  1283. ++fieldsShown;
  1284. }
  1285. if (fieldsShown < 2)
  1286. {
  1287. n = std::abs ((int) inSeconds()) % 60;
  1288. if (n > 0)
  1289. {
  1290. result << n << (n == 1 ? TRANS(" sec ")
  1291. : TRANS(" secs "));
  1292. ++fieldsShown;
  1293. }
  1294. if (fieldsShown == 0)
  1295. {
  1296. n = std::abs ((int) inMilliseconds()) % 1000;
  1297. if (n > 0)
  1298. result << n << TRANS(" ms");
  1299. }
  1300. }
  1301. }
  1302. }
  1303. return result.trimEnd();
  1304. }
  1305. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1306. {
  1307. seconds = other.seconds;
  1308. return *this;
  1309. }
  1310. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1311. {
  1312. seconds += timeToAdd.seconds;
  1313. return *this;
  1314. }
  1315. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1316. {
  1317. seconds -= timeToSubtract.seconds;
  1318. return *this;
  1319. }
  1320. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1321. {
  1322. seconds += secondsToAdd;
  1323. return *this;
  1324. }
  1325. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1326. {
  1327. seconds -= secondsToSubtract;
  1328. return *this;
  1329. }
  1330. bool operator== (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() == t2.inSeconds(); }
  1331. bool operator!= (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() != t2.inSeconds(); }
  1332. bool operator> (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() > t2.inSeconds(); }
  1333. bool operator< (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() < t2.inSeconds(); }
  1334. bool operator>= (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() >= t2.inSeconds(); }
  1335. bool operator<= (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() <= t2.inSeconds(); }
  1336. const RelativeTime operator+ (const RelativeTime& t1, const RelativeTime& t2) throw() { RelativeTime t (t1); return t += t2; }
  1337. const RelativeTime operator- (const RelativeTime& t1, const RelativeTime& t2) throw() { RelativeTime t (t1); return t -= t2; }
  1338. END_JUCE_NAMESPACE
  1339. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1340. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1341. BEGIN_JUCE_NAMESPACE
  1342. SystemStats::CPUFlags SystemStats::cpuFlags;
  1343. const String SystemStats::getJUCEVersion()
  1344. {
  1345. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1346. + "." + String (JUCE_MINOR_VERSION)
  1347. + "." + String (JUCE_BUILDNUMBER);
  1348. }
  1349. #ifdef JUCE_DLL
  1350. void* juce_Malloc (int size) { return malloc (size); }
  1351. void* juce_Calloc (int size) { return calloc (1, size); }
  1352. void* juce_Realloc (void* block, int size) { return realloc (block, size); }
  1353. void juce_Free (void* block) { free (block); }
  1354. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1355. void* juce_DebugMalloc (int size, const char* file, int line) { return _malloc_dbg (size, _NORMAL_BLOCK, file, line); }
  1356. void* juce_DebugCalloc (int size, const char* file, int line) { return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line); }
  1357. void* juce_DebugRealloc (void* block, int size, const char* file, int line) { return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line); }
  1358. void juce_DebugFree (void* block) { _free_dbg (block, _NORMAL_BLOCK); }
  1359. #endif
  1360. #endif
  1361. END_JUCE_NAMESPACE
  1362. /*** End of inlined file: juce_SystemStats.cpp ***/
  1363. /*** Start of inlined file: juce_Time.cpp ***/
  1364. #if JUCE_MSVC
  1365. #pragma warning (push)
  1366. #pragma warning (disable: 4514)
  1367. #endif
  1368. #ifndef JUCE_WINDOWS
  1369. #include <sys/time.h>
  1370. #else
  1371. #include <ctime>
  1372. #endif
  1373. #include <sys/timeb.h>
  1374. #if JUCE_MSVC
  1375. #pragma warning (pop)
  1376. #ifdef _INC_TIME_INL
  1377. #define USE_NEW_SECURE_TIME_FNS
  1378. #endif
  1379. #endif
  1380. BEGIN_JUCE_NAMESPACE
  1381. namespace TimeHelpers
  1382. {
  1383. static struct tm millisToLocal (const int64 millis) throw()
  1384. {
  1385. struct tm result;
  1386. const int64 seconds = millis / 1000;
  1387. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1388. {
  1389. // use extended maths for dates beyond 1970 to 2037..
  1390. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1391. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1392. const int days = (int) (jdm / literal64bit (86400));
  1393. const int a = 32044 + days;
  1394. const int b = (4 * a + 3) / 146097;
  1395. const int c = a - (b * 146097) / 4;
  1396. const int d = (4 * c + 3) / 1461;
  1397. const int e = c - (d * 1461) / 4;
  1398. const int m = (5 * e + 2) / 153;
  1399. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1400. result.tm_mon = m + 2 - 12 * (m / 10);
  1401. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1402. result.tm_wday = (days + 1) % 7;
  1403. result.tm_yday = -1;
  1404. int t = (int) (jdm % literal64bit (86400));
  1405. result.tm_hour = t / 3600;
  1406. t %= 3600;
  1407. result.tm_min = t / 60;
  1408. result.tm_sec = t % 60;
  1409. result.tm_isdst = -1;
  1410. }
  1411. else
  1412. {
  1413. time_t now = static_cast <time_t> (seconds);
  1414. #if JUCE_WINDOWS
  1415. #ifdef USE_NEW_SECURE_TIME_FNS
  1416. if (now >= 0 && now <= 0x793406fff)
  1417. localtime_s (&result, &now);
  1418. else
  1419. zeromem (&result, sizeof (result));
  1420. #else
  1421. result = *localtime (&now);
  1422. #endif
  1423. #else
  1424. // more thread-safe
  1425. localtime_r (&now, &result);
  1426. #endif
  1427. }
  1428. return result;
  1429. }
  1430. static int extendedModulo (const int64 value, const int modulo) throw()
  1431. {
  1432. return (int) (value >= 0 ? (value % modulo)
  1433. : (value - ((value / modulo) + 1) * modulo));
  1434. }
  1435. static uint32 lastMSCounterValue = 0;
  1436. }
  1437. Time::Time() throw()
  1438. : millisSinceEpoch (0)
  1439. {
  1440. }
  1441. Time::Time (const Time& other) throw()
  1442. : millisSinceEpoch (other.millisSinceEpoch)
  1443. {
  1444. }
  1445. Time::Time (const int64 ms) throw()
  1446. : millisSinceEpoch (ms)
  1447. {
  1448. }
  1449. Time::Time (const int year,
  1450. const int month,
  1451. const int day,
  1452. const int hours,
  1453. const int minutes,
  1454. const int seconds,
  1455. const int milliseconds,
  1456. const bool useLocalTime) throw()
  1457. {
  1458. jassert (year > 100); // year must be a 4-digit version
  1459. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1460. {
  1461. // use extended maths for dates beyond 1970 to 2037..
  1462. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1463. : 0;
  1464. const int a = (13 - month) / 12;
  1465. const int y = year + 4800 - a;
  1466. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1467. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1468. - 32045;
  1469. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1470. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1471. + milliseconds;
  1472. }
  1473. else
  1474. {
  1475. struct tm t;
  1476. t.tm_year = year - 1900;
  1477. t.tm_mon = month;
  1478. t.tm_mday = day;
  1479. t.tm_hour = hours;
  1480. t.tm_min = minutes;
  1481. t.tm_sec = seconds;
  1482. t.tm_isdst = -1;
  1483. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1484. if (millisSinceEpoch < 0)
  1485. millisSinceEpoch = 0;
  1486. else
  1487. millisSinceEpoch += milliseconds;
  1488. }
  1489. }
  1490. Time::~Time() throw()
  1491. {
  1492. }
  1493. Time& Time::operator= (const Time& other) throw()
  1494. {
  1495. millisSinceEpoch = other.millisSinceEpoch;
  1496. return *this;
  1497. }
  1498. int64 Time::currentTimeMillis() throw()
  1499. {
  1500. static uint32 lastCounterResult = 0xffffffff;
  1501. static int64 correction = 0;
  1502. const uint32 now = getMillisecondCounter();
  1503. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1504. if (now < lastCounterResult)
  1505. {
  1506. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1507. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1508. {
  1509. // get the time once using normal library calls, and store the difference needed to
  1510. // turn the millisecond counter into a real time.
  1511. #if JUCE_WINDOWS
  1512. struct _timeb t;
  1513. #ifdef USE_NEW_SECURE_TIME_FNS
  1514. _ftime_s (&t);
  1515. #else
  1516. _ftime (&t);
  1517. #endif
  1518. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1519. #else
  1520. struct timeval tv;
  1521. struct timezone tz;
  1522. gettimeofday (&tv, &tz);
  1523. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1524. #endif
  1525. }
  1526. }
  1527. lastCounterResult = now;
  1528. return correction + now;
  1529. }
  1530. uint32 juce_millisecondsSinceStartup() throw();
  1531. uint32 Time::getMillisecondCounter() throw()
  1532. {
  1533. const uint32 now = juce_millisecondsSinceStartup();
  1534. if (now < TimeHelpers::lastMSCounterValue)
  1535. {
  1536. // in multi-threaded apps this might be called concurrently, so
  1537. // make sure that our last counter value only increases and doesn't
  1538. // go backwards..
  1539. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1540. TimeHelpers::lastMSCounterValue = now;
  1541. }
  1542. else
  1543. {
  1544. TimeHelpers::lastMSCounterValue = now;
  1545. }
  1546. return now;
  1547. }
  1548. uint32 Time::getApproximateMillisecondCounter() throw()
  1549. {
  1550. jassert (TimeHelpers::lastMSCounterValue != 0);
  1551. return TimeHelpers::lastMSCounterValue;
  1552. }
  1553. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1554. {
  1555. for (;;)
  1556. {
  1557. const uint32 now = getMillisecondCounter();
  1558. if (now >= targetTime)
  1559. break;
  1560. const int toWait = targetTime - now;
  1561. if (toWait > 2)
  1562. {
  1563. Thread::sleep (jmin (20, toWait >> 1));
  1564. }
  1565. else
  1566. {
  1567. // xxx should consider using mutex_pause on the mac as it apparently
  1568. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1569. for (int i = 10; --i >= 0;)
  1570. Thread::yield();
  1571. }
  1572. }
  1573. }
  1574. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1575. {
  1576. return ticks / (double) getHighResolutionTicksPerSecond();
  1577. }
  1578. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1579. {
  1580. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1581. }
  1582. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1583. {
  1584. return Time (currentTimeMillis());
  1585. }
  1586. const String Time::toString (const bool includeDate,
  1587. const bool includeTime,
  1588. const bool includeSeconds,
  1589. const bool use24HourClock) const throw()
  1590. {
  1591. String result;
  1592. if (includeDate)
  1593. {
  1594. result << getDayOfMonth() << ' '
  1595. << getMonthName (true) << ' '
  1596. << getYear();
  1597. if (includeTime)
  1598. result << ' ';
  1599. }
  1600. if (includeTime)
  1601. {
  1602. const int mins = getMinutes();
  1603. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1604. << (mins < 10 ? ":0" : ":") << mins;
  1605. if (includeSeconds)
  1606. {
  1607. const int secs = getSeconds();
  1608. result << (secs < 10 ? ":0" : ":") << secs;
  1609. }
  1610. if (! use24HourClock)
  1611. result << (isAfternoon() ? "pm" : "am");
  1612. }
  1613. return result.trimEnd();
  1614. }
  1615. const String Time::formatted (const String& format) const
  1616. {
  1617. String buffer;
  1618. int bufferSize = 128;
  1619. buffer.preallocateStorage (bufferSize);
  1620. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1621. while (CharacterFunctions::ftime (buffer.getCharPointer().getAddress(), bufferSize, format.getCharPointer(), &t) <= 0)
  1622. {
  1623. bufferSize += 128;
  1624. buffer.preallocateStorage (bufferSize);
  1625. }
  1626. return buffer;
  1627. }
  1628. int Time::getYear() const throw()
  1629. {
  1630. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1631. }
  1632. int Time::getMonth() const throw()
  1633. {
  1634. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1635. }
  1636. int Time::getDayOfMonth() const throw()
  1637. {
  1638. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1639. }
  1640. int Time::getDayOfWeek() const throw()
  1641. {
  1642. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1643. }
  1644. int Time::getHours() const throw()
  1645. {
  1646. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1647. }
  1648. int Time::getHoursInAmPmFormat() const throw()
  1649. {
  1650. const int hours = getHours();
  1651. if (hours == 0)
  1652. return 12;
  1653. else if (hours <= 12)
  1654. return hours;
  1655. else
  1656. return hours - 12;
  1657. }
  1658. bool Time::isAfternoon() const throw()
  1659. {
  1660. return getHours() >= 12;
  1661. }
  1662. int Time::getMinutes() const throw()
  1663. {
  1664. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1665. }
  1666. int Time::getSeconds() const throw()
  1667. {
  1668. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1669. }
  1670. int Time::getMilliseconds() const throw()
  1671. {
  1672. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1673. }
  1674. bool Time::isDaylightSavingTime() const throw()
  1675. {
  1676. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1677. }
  1678. const String Time::getTimeZone() const throw()
  1679. {
  1680. String zone[2];
  1681. #if JUCE_WINDOWS
  1682. _tzset();
  1683. #ifdef USE_NEW_SECURE_TIME_FNS
  1684. {
  1685. char name [128];
  1686. size_t length;
  1687. for (int i = 0; i < 2; ++i)
  1688. {
  1689. zeromem (name, sizeof (name));
  1690. _get_tzname (&length, name, 127, i);
  1691. zone[i] = name;
  1692. }
  1693. }
  1694. #else
  1695. const char** const zonePtr = (const char**) _tzname;
  1696. zone[0] = zonePtr[0];
  1697. zone[1] = zonePtr[1];
  1698. #endif
  1699. #else
  1700. tzset();
  1701. const char** const zonePtr = (const char**) tzname;
  1702. zone[0] = zonePtr[0];
  1703. zone[1] = zonePtr[1];
  1704. #endif
  1705. if (isDaylightSavingTime())
  1706. {
  1707. zone[0] = zone[1];
  1708. if (zone[0].length() > 3
  1709. && zone[0].containsIgnoreCase ("daylight")
  1710. && zone[0].contains ("GMT"))
  1711. zone[0] = "BST";
  1712. }
  1713. return zone[0].substring (0, 3);
  1714. }
  1715. const String Time::getMonthName (const bool threeLetterVersion) const
  1716. {
  1717. return getMonthName (getMonth(), threeLetterVersion);
  1718. }
  1719. const String Time::getWeekdayName (const bool threeLetterVersion) const
  1720. {
  1721. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1722. }
  1723. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  1724. {
  1725. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1726. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1727. monthNumber %= 12;
  1728. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1729. : longMonthNames [monthNumber]);
  1730. }
  1731. const String Time::getWeekdayName (int day, const bool threeLetterVersion)
  1732. {
  1733. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1734. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1735. day %= 7;
  1736. return TRANS (threeLetterVersion ? shortDayNames [day]
  1737. : longDayNames [day]);
  1738. }
  1739. Time& Time::operator+= (const RelativeTime& delta) { millisSinceEpoch += delta.inMilliseconds(); return *this; }
  1740. Time& Time::operator-= (const RelativeTime& delta) { millisSinceEpoch -= delta.inMilliseconds(); return *this; }
  1741. const Time operator+ (const Time& time, const RelativeTime& delta) { Time t (time); return t += delta; }
  1742. const Time operator- (const Time& time, const RelativeTime& delta) { Time t (time); return t -= delta; }
  1743. const Time operator+ (const RelativeTime& delta, const Time& time) { Time t (time); return t += delta; }
  1744. const RelativeTime operator- (const Time& time1, const Time& time2) { return RelativeTime::milliseconds (time1.toMilliseconds() - time2.toMilliseconds()); }
  1745. bool operator== (const Time& time1, const Time& time2) { return time1.toMilliseconds() == time2.toMilliseconds(); }
  1746. bool operator!= (const Time& time1, const Time& time2) { return time1.toMilliseconds() != time2.toMilliseconds(); }
  1747. bool operator< (const Time& time1, const Time& time2) { return time1.toMilliseconds() < time2.toMilliseconds(); }
  1748. bool operator> (const Time& time1, const Time& time2) { return time1.toMilliseconds() > time2.toMilliseconds(); }
  1749. bool operator<= (const Time& time1, const Time& time2) { return time1.toMilliseconds() <= time2.toMilliseconds(); }
  1750. bool operator>= (const Time& time1, const Time& time2) { return time1.toMilliseconds() >= time2.toMilliseconds(); }
  1751. END_JUCE_NAMESPACE
  1752. /*** End of inlined file: juce_Time.cpp ***/
  1753. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1754. BEGIN_JUCE_NAMESPACE
  1755. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1756. #endif
  1757. #if JUCE_WINDOWS
  1758. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1759. #endif
  1760. #if JUCE_DEBUG
  1761. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1762. #endif
  1763. static bool juceInitialisedNonGUI = false;
  1764. JUCE_API void JUCE_CALLTYPE initialiseJuce_NonGUI()
  1765. {
  1766. if (! juceInitialisedNonGUI)
  1767. {
  1768. juceInitialisedNonGUI = true;
  1769. JUCE_AUTORELEASEPOOL
  1770. DBG (SystemStats::getJUCEVersion());
  1771. SystemStats::initialiseStats();
  1772. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1773. }
  1774. // Some basic tests, to keep an eye on things and make sure these types work ok
  1775. // on all platforms. Let me know if any of these assertions fail on your system!
  1776. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1777. static_jassert (sizeof (int8) == 1);
  1778. static_jassert (sizeof (uint8) == 1);
  1779. static_jassert (sizeof (int16) == 2);
  1780. static_jassert (sizeof (uint16) == 2);
  1781. static_jassert (sizeof (int32) == 4);
  1782. static_jassert (sizeof (uint32) == 4);
  1783. static_jassert (sizeof (int64) == 8);
  1784. static_jassert (sizeof (uint64) == 8);
  1785. #if JUCE_NATIVE_WCHAR_IS_UTF8
  1786. static_jassert (sizeof (wchar_t) == 1);
  1787. #elif JUCE_NATIVE_WCHAR_IS_UTF16
  1788. static_jassert (sizeof (wchar_t) == 2);
  1789. #elif JUCE_NATIVE_WCHAR_IS_UTF32
  1790. static_jassert (sizeof (wchar_t) == 4);
  1791. #else
  1792. #error "native wchar_t size is unknown"
  1793. #endif
  1794. }
  1795. JUCE_API void JUCE_CALLTYPE shutdownJuce_NonGUI()
  1796. {
  1797. if (juceInitialisedNonGUI)
  1798. {
  1799. juceInitialisedNonGUI = false;
  1800. JUCE_AUTORELEASEPOOL
  1801. LocalisedStrings::setCurrentMappings (0);
  1802. Thread::stopAllThreads (3000);
  1803. #if JUCE_WINDOWS
  1804. juce_shutdownWin32Sockets();
  1805. #endif
  1806. #if JUCE_DEBUG
  1807. juce_CheckForDanglingStreams();
  1808. #endif
  1809. }
  1810. }
  1811. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1812. static bool juceInitialisedGUI = false;
  1813. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI()
  1814. {
  1815. if (! juceInitialisedGUI)
  1816. {
  1817. juceInitialisedGUI = true;
  1818. JUCE_AUTORELEASEPOOL
  1819. initialiseJuce_NonGUI();
  1820. MessageManager::getInstance();
  1821. LookAndFeel::setDefaultLookAndFeel (0);
  1822. #if JUCE_DEBUG
  1823. try // This section is just a safety-net for catching builds without RTTI enabled..
  1824. {
  1825. MemoryOutputStream mo;
  1826. OutputStream* o = &mo;
  1827. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1828. o = dynamic_cast <MemoryOutputStream*> (o);
  1829. jassert (o != 0);
  1830. }
  1831. catch (...)
  1832. {
  1833. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1834. jassertfalse;
  1835. }
  1836. #endif
  1837. }
  1838. }
  1839. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI()
  1840. {
  1841. if (juceInitialisedGUI)
  1842. {
  1843. juceInitialisedGUI = false;
  1844. JUCE_AUTORELEASEPOOL
  1845. DeletedAtShutdown::deleteAll();
  1846. LookAndFeel::clearDefaultLookAndFeel();
  1847. delete MessageManager::getInstance();
  1848. shutdownJuce_NonGUI();
  1849. }
  1850. }
  1851. #endif
  1852. #if JUCE_UNIT_TESTS
  1853. class AtomicTests : public UnitTest
  1854. {
  1855. public:
  1856. AtomicTests() : UnitTest ("Atomics") {}
  1857. void runTest()
  1858. {
  1859. beginTest ("Misc");
  1860. char a1[7];
  1861. expect (numElementsInArray(a1) == 7);
  1862. int a2[3];
  1863. expect (numElementsInArray(a2) == 3);
  1864. expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1865. expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1866. expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1867. beginTest ("Atomic types");
  1868. AtomicTester <int>::testInteger (*this);
  1869. AtomicTester <unsigned int>::testInteger (*this);
  1870. AtomicTester <int32>::testInteger (*this);
  1871. AtomicTester <uint32>::testInteger (*this);
  1872. AtomicTester <long>::testInteger (*this);
  1873. AtomicTester <void*>::testInteger (*this);
  1874. AtomicTester <int*>::testInteger (*this);
  1875. AtomicTester <float>::testFloat (*this);
  1876. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1877. AtomicTester <int64>::testInteger (*this);
  1878. AtomicTester <uint64>::testInteger (*this);
  1879. AtomicTester <double>::testFloat (*this);
  1880. #endif
  1881. }
  1882. template <typename Type>
  1883. class AtomicTester
  1884. {
  1885. public:
  1886. AtomicTester() {}
  1887. static void testInteger (UnitTest& test)
  1888. {
  1889. Atomic<Type> a, b;
  1890. a.set ((Type) 10);
  1891. a += (Type) 15;
  1892. a.memoryBarrier();
  1893. a -= (Type) 5;
  1894. ++a; ++a; --a;
  1895. a.memoryBarrier();
  1896. testFloat (test);
  1897. }
  1898. static void testFloat (UnitTest& test)
  1899. {
  1900. Atomic<Type> a, b;
  1901. a = (Type) 21;
  1902. a.memoryBarrier();
  1903. /* These are some simple test cases to check the atomics - let me know
  1904. if any of these assertions fail on your system!
  1905. */
  1906. test.expect (a.get() == (Type) 21);
  1907. test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1908. test.expect (a.get() == (Type) 21);
  1909. test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1910. test.expect (a.get() == (Type) 101);
  1911. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1912. test.expect (a.get() == (Type) 101);
  1913. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  1914. test.expect (a.get() == (Type) 200);
  1915. test.expect (a.exchange ((Type) 300) == (Type) 200);
  1916. test.expect (a.get() == (Type) 300);
  1917. b = a;
  1918. test.expect (b.get() == a.get());
  1919. }
  1920. };
  1921. };
  1922. static AtomicTests atomicUnitTests;
  1923. #endif
  1924. END_JUCE_NAMESPACE
  1925. /*** End of inlined file: juce_Initialisation.cpp ***/
  1926. /*** Start of inlined file: juce_AbstractFifo.cpp ***/
  1927. BEGIN_JUCE_NAMESPACE
  1928. AbstractFifo::AbstractFifo (const int capacity) throw()
  1929. : bufferSize (capacity)
  1930. {
  1931. jassert (bufferSize > 0);
  1932. }
  1933. AbstractFifo::~AbstractFifo() {}
  1934. int AbstractFifo::getTotalSize() const throw() { return bufferSize; }
  1935. int AbstractFifo::getFreeSpace() const throw() { return bufferSize - getNumReady(); }
  1936. int AbstractFifo::getNumReady() const throw()
  1937. {
  1938. const int vs = validStart.get();
  1939. const int ve = validEnd.get();
  1940. return ve >= vs ? (ve - vs) : (bufferSize - (vs - ve));
  1941. }
  1942. void AbstractFifo::reset() throw()
  1943. {
  1944. validEnd = 0;
  1945. validStart = 0;
  1946. }
  1947. void AbstractFifo::setTotalSize (int newSize) throw()
  1948. {
  1949. jassert (newSize > 0);
  1950. reset();
  1951. bufferSize = newSize;
  1952. }
  1953. void AbstractFifo::prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1954. {
  1955. const int vs = validStart.get();
  1956. const int ve = validEnd.value;
  1957. const int freeSpace = ve >= vs ? (bufferSize - (ve - vs)) : (vs - ve);
  1958. numToWrite = jmin (numToWrite, freeSpace - 1);
  1959. if (numToWrite <= 0)
  1960. {
  1961. startIndex1 = 0;
  1962. startIndex2 = 0;
  1963. blockSize1 = 0;
  1964. blockSize2 = 0;
  1965. }
  1966. else
  1967. {
  1968. startIndex1 = ve;
  1969. startIndex2 = 0;
  1970. blockSize1 = jmin (bufferSize - ve, numToWrite);
  1971. numToWrite -= blockSize1;
  1972. blockSize2 = numToWrite <= 0 ? 0 : jmin (numToWrite, vs);
  1973. }
  1974. }
  1975. void AbstractFifo::finishedWrite (int numWritten) throw()
  1976. {
  1977. jassert (numWritten >= 0 && numWritten < bufferSize);
  1978. int newEnd = validEnd.value + numWritten;
  1979. if (newEnd >= bufferSize)
  1980. newEnd -= bufferSize;
  1981. validEnd = newEnd;
  1982. }
  1983. void AbstractFifo::prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1984. {
  1985. const int vs = validStart.value;
  1986. const int ve = validEnd.get();
  1987. const int numReady = ve >= vs ? (ve - vs) : (bufferSize - (vs - ve));
  1988. numWanted = jmin (numWanted, numReady);
  1989. if (numWanted <= 0)
  1990. {
  1991. startIndex1 = 0;
  1992. startIndex2 = 0;
  1993. blockSize1 = 0;
  1994. blockSize2 = 0;
  1995. }
  1996. else
  1997. {
  1998. startIndex1 = vs;
  1999. startIndex2 = 0;
  2000. blockSize1 = jmin (bufferSize - vs, numWanted);
  2001. numWanted -= blockSize1;
  2002. blockSize2 = numWanted <= 0 ? 0 : jmin (numWanted, ve);
  2003. }
  2004. }
  2005. void AbstractFifo::finishedRead (int numRead) throw()
  2006. {
  2007. jassert (numRead >= 0 && numRead <= bufferSize);
  2008. int newStart = validStart.value + numRead;
  2009. if (newStart >= bufferSize)
  2010. newStart -= bufferSize;
  2011. validStart = newStart;
  2012. }
  2013. #if JUCE_UNIT_TESTS
  2014. class AbstractFifoTests : public UnitTest
  2015. {
  2016. public:
  2017. AbstractFifoTests() : UnitTest ("Abstract Fifo") {}
  2018. class WriteThread : public Thread
  2019. {
  2020. public:
  2021. WriteThread (AbstractFifo& fifo_, int* buffer_)
  2022. : Thread ("fifo writer"), fifo (fifo_), buffer (buffer_)
  2023. {
  2024. startThread();
  2025. }
  2026. ~WriteThread()
  2027. {
  2028. stopThread (5000);
  2029. }
  2030. void run()
  2031. {
  2032. int n = 0;
  2033. while (! threadShouldExit())
  2034. {
  2035. int num = Random::getSystemRandom().nextInt (2000) + 1;
  2036. int start1, size1, start2, size2;
  2037. fifo.prepareToWrite (num, start1, size1, start2, size2);
  2038. jassert (size1 >= 0 && size2 >= 0);
  2039. jassert (size1 == 0 || (start1 >= 0 && start1 < fifo.getTotalSize()));
  2040. jassert (size2 == 0 || (start2 >= 0 && start2 < fifo.getTotalSize()));
  2041. int i;
  2042. for (i = 0; i < size1; ++i)
  2043. buffer [start1 + i] = n++;
  2044. for (i = 0; i < size2; ++i)
  2045. buffer [start2 + i] = n++;
  2046. fifo.finishedWrite (size1 + size2);
  2047. }
  2048. }
  2049. private:
  2050. AbstractFifo& fifo;
  2051. int* buffer;
  2052. };
  2053. void runTest()
  2054. {
  2055. beginTest ("AbstractFifo");
  2056. int buffer [5000];
  2057. AbstractFifo fifo (numElementsInArray (buffer));
  2058. WriteThread writer (fifo, buffer);
  2059. int n = 0;
  2060. for (int count = 1000000; --count >= 0;)
  2061. {
  2062. int num = Random::getSystemRandom().nextInt (6000) + 1;
  2063. int start1, size1, start2, size2;
  2064. fifo.prepareToRead (num, start1, size1, start2, size2);
  2065. if (! (size1 >= 0 && size2 >= 0)
  2066. && (size1 == 0 || (start1 >= 0 && start1 < fifo.getTotalSize()))
  2067. && (size2 == 0 || (start2 >= 0 && start2 < fifo.getTotalSize())))
  2068. {
  2069. expect (false, "prepareToRead returned -ve values");
  2070. break;
  2071. }
  2072. bool failed = false;
  2073. int i;
  2074. for (i = 0; i < size1; ++i)
  2075. failed = (buffer [start1 + i] != n++) || failed;
  2076. for (i = 0; i < size2; ++i)
  2077. failed = (buffer [start2 + i] != n++) || failed;
  2078. if (failed)
  2079. {
  2080. expect (false, "read values were incorrect");
  2081. break;
  2082. }
  2083. fifo.finishedRead (size1 + size2);
  2084. }
  2085. }
  2086. };
  2087. static AbstractFifoTests fifoUnitTests;
  2088. #endif
  2089. END_JUCE_NAMESPACE
  2090. /*** End of inlined file: juce_AbstractFifo.cpp ***/
  2091. /*** Start of inlined file: juce_BigInteger.cpp ***/
  2092. BEGIN_JUCE_NAMESPACE
  2093. BigInteger::BigInteger()
  2094. : numValues (4),
  2095. highestBit (-1),
  2096. negative (false)
  2097. {
  2098. values.calloc (numValues + 1);
  2099. }
  2100. BigInteger::BigInteger (const int32 value)
  2101. : numValues (4),
  2102. highestBit (31),
  2103. negative (value < 0)
  2104. {
  2105. values.calloc (numValues + 1);
  2106. values[0] = abs (value);
  2107. highestBit = getHighestBit();
  2108. }
  2109. BigInteger::BigInteger (const uint32 value)
  2110. : numValues (4),
  2111. highestBit (31),
  2112. negative (false)
  2113. {
  2114. values.calloc (numValues + 1);
  2115. values[0] = value;
  2116. highestBit = getHighestBit();
  2117. }
  2118. BigInteger::BigInteger (int64 value)
  2119. : numValues (4),
  2120. highestBit (63),
  2121. negative (value < 0)
  2122. {
  2123. values.calloc (numValues + 1);
  2124. if (value < 0)
  2125. value = -value;
  2126. values[0] = (uint32) value;
  2127. values[1] = (uint32) (value >> 32);
  2128. highestBit = getHighestBit();
  2129. }
  2130. BigInteger::BigInteger (const BigInteger& other)
  2131. : numValues (jmax (4, bitToIndex (other.highestBit) + 1)),
  2132. highestBit (other.getHighestBit()),
  2133. negative (other.negative)
  2134. {
  2135. values.malloc (numValues + 1);
  2136. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2137. }
  2138. BigInteger::~BigInteger()
  2139. {
  2140. }
  2141. void BigInteger::swapWith (BigInteger& other) throw()
  2142. {
  2143. values.swapWith (other.values);
  2144. swapVariables (numValues, other.numValues);
  2145. swapVariables (highestBit, other.highestBit);
  2146. swapVariables (negative, other.negative);
  2147. }
  2148. BigInteger& BigInteger::operator= (const BigInteger& other)
  2149. {
  2150. if (this != &other)
  2151. {
  2152. highestBit = other.getHighestBit();
  2153. numValues = jmax (4, bitToIndex (highestBit) + 1);
  2154. negative = other.negative;
  2155. values.malloc (numValues + 1);
  2156. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2157. }
  2158. return *this;
  2159. }
  2160. void BigInteger::ensureSize (const int numVals)
  2161. {
  2162. if (numVals + 2 >= numValues)
  2163. {
  2164. int oldSize = numValues;
  2165. numValues = ((numVals + 2) * 3) / 2;
  2166. values.realloc (numValues + 1);
  2167. while (oldSize < numValues)
  2168. values [oldSize++] = 0;
  2169. }
  2170. }
  2171. bool BigInteger::operator[] (const int bit) const throw()
  2172. {
  2173. return bit <= highestBit && bit >= 0
  2174. && ((values [bitToIndex (bit)] & bitToMask (bit)) != 0);
  2175. }
  2176. int BigInteger::toInteger() const throw()
  2177. {
  2178. const int n = (int) (values[0] & 0x7fffffff);
  2179. return negative ? -n : n;
  2180. }
  2181. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2182. {
  2183. BigInteger r;
  2184. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2185. r.ensureSize (bitToIndex (numBits));
  2186. r.highestBit = numBits;
  2187. int i = 0;
  2188. while (numBits > 0)
  2189. {
  2190. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2191. numBits -= 32;
  2192. startBit += 32;
  2193. }
  2194. r.highestBit = r.getHighestBit();
  2195. return r;
  2196. }
  2197. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2198. {
  2199. if (numBits > 32)
  2200. {
  2201. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2202. numBits = 32;
  2203. }
  2204. numBits = jmin (numBits, highestBit + 1 - startBit);
  2205. if (numBits <= 0)
  2206. return 0;
  2207. const int pos = bitToIndex (startBit);
  2208. const int offset = startBit & 31;
  2209. const int endSpace = 32 - numBits;
  2210. uint32 n = ((uint32) values [pos]) >> offset;
  2211. if (offset > endSpace)
  2212. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2213. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2214. }
  2215. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, uint32 valueToSet)
  2216. {
  2217. if (numBits > 32)
  2218. {
  2219. jassertfalse;
  2220. numBits = 32;
  2221. }
  2222. for (int i = 0; i < numBits; ++i)
  2223. {
  2224. setBit (startBit + i, (valueToSet & 1) != 0);
  2225. valueToSet >>= 1;
  2226. }
  2227. }
  2228. void BigInteger::clear()
  2229. {
  2230. if (numValues > 16)
  2231. {
  2232. numValues = 4;
  2233. values.calloc (numValues + 1);
  2234. }
  2235. else
  2236. {
  2237. zeromem (values, sizeof (uint32) * (numValues + 1));
  2238. }
  2239. highestBit = -1;
  2240. negative = false;
  2241. }
  2242. void BigInteger::setBit (const int bit)
  2243. {
  2244. if (bit >= 0)
  2245. {
  2246. if (bit > highestBit)
  2247. {
  2248. ensureSize (bitToIndex (bit));
  2249. highestBit = bit;
  2250. }
  2251. values [bitToIndex (bit)] |= bitToMask (bit);
  2252. }
  2253. }
  2254. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2255. {
  2256. if (shouldBeSet)
  2257. setBit (bit);
  2258. else
  2259. clearBit (bit);
  2260. }
  2261. void BigInteger::clearBit (const int bit) throw()
  2262. {
  2263. if (bit >= 0 && bit <= highestBit)
  2264. values [bitToIndex (bit)] &= ~bitToMask (bit);
  2265. }
  2266. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2267. {
  2268. while (--numBits >= 0)
  2269. setBit (startBit++, shouldBeSet);
  2270. }
  2271. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2272. {
  2273. if (bit >= 0)
  2274. shiftBits (1, bit);
  2275. setBit (bit, shouldBeSet);
  2276. }
  2277. bool BigInteger::isZero() const throw()
  2278. {
  2279. return getHighestBit() < 0;
  2280. }
  2281. bool BigInteger::isOne() const throw()
  2282. {
  2283. return getHighestBit() == 0 && ! negative;
  2284. }
  2285. bool BigInteger::isNegative() const throw()
  2286. {
  2287. return negative && ! isZero();
  2288. }
  2289. void BigInteger::setNegative (const bool neg) throw()
  2290. {
  2291. negative = neg;
  2292. }
  2293. void BigInteger::negate() throw()
  2294. {
  2295. negative = (! negative) && ! isZero();
  2296. }
  2297. #if JUCE_USE_INTRINSICS
  2298. #pragma intrinsic (_BitScanReverse)
  2299. #endif
  2300. namespace BitFunctions
  2301. {
  2302. inline int countBitsInInt32 (uint32 n) throw()
  2303. {
  2304. n -= ((n >> 1) & 0x55555555);
  2305. n = (((n >> 2) & 0x33333333) + (n & 0x33333333));
  2306. n = (((n >> 4) + n) & 0x0f0f0f0f);
  2307. n += (n >> 8);
  2308. n += (n >> 16);
  2309. return n & 0x3f;
  2310. }
  2311. inline int highestBitInInt (uint32 n) throw()
  2312. {
  2313. jassert (n != 0); // (the built-in functions may not work for n = 0)
  2314. #if JUCE_GCC
  2315. return 31 - __builtin_clz (n);
  2316. #elif JUCE_USE_INTRINSICS
  2317. unsigned long highest;
  2318. _BitScanReverse (&highest, n);
  2319. return (int) highest;
  2320. #else
  2321. n |= (n >> 1);
  2322. n |= (n >> 2);
  2323. n |= (n >> 4);
  2324. n |= (n >> 8);
  2325. n |= (n >> 16);
  2326. return countBitsInInt32 (n >> 1);
  2327. #endif
  2328. }
  2329. }
  2330. int BigInteger::countNumberOfSetBits() const throw()
  2331. {
  2332. int total = 0;
  2333. for (int i = bitToIndex (highestBit) + 1; --i >= 0;)
  2334. total += BitFunctions::countBitsInInt32 (values[i]);
  2335. return total;
  2336. }
  2337. int BigInteger::getHighestBit() const throw()
  2338. {
  2339. for (int i = bitToIndex (highestBit + 1); i >= 0; --i)
  2340. {
  2341. const uint32 n = values[i];
  2342. if (n != 0)
  2343. return BitFunctions::highestBitInInt (n) + (i << 5);
  2344. }
  2345. return -1;
  2346. }
  2347. int BigInteger::findNextSetBit (int i) const throw()
  2348. {
  2349. for (; i <= highestBit; ++i)
  2350. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  2351. return i;
  2352. return -1;
  2353. }
  2354. int BigInteger::findNextClearBit (int i) const throw()
  2355. {
  2356. for (; i <= highestBit; ++i)
  2357. if ((values [bitToIndex (i)] & bitToMask (i)) == 0)
  2358. break;
  2359. return i;
  2360. }
  2361. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2362. {
  2363. if (other.isNegative())
  2364. return operator-= (-other);
  2365. if (isNegative())
  2366. {
  2367. if (compareAbsolute (other) < 0)
  2368. {
  2369. BigInteger temp (*this);
  2370. temp.negate();
  2371. *this = other;
  2372. operator-= (temp);
  2373. }
  2374. else
  2375. {
  2376. negate();
  2377. operator-= (other);
  2378. negate();
  2379. }
  2380. }
  2381. else
  2382. {
  2383. if (other.highestBit > highestBit)
  2384. highestBit = other.highestBit;
  2385. ++highestBit;
  2386. const int numInts = bitToIndex (highestBit) + 1;
  2387. ensureSize (numInts);
  2388. int64 remainder = 0;
  2389. for (int i = 0; i <= numInts; ++i)
  2390. {
  2391. if (i < numValues)
  2392. remainder += values[i];
  2393. if (i < other.numValues)
  2394. remainder += other.values[i];
  2395. values[i] = (uint32) remainder;
  2396. remainder >>= 32;
  2397. }
  2398. jassert (remainder == 0);
  2399. highestBit = getHighestBit();
  2400. }
  2401. return *this;
  2402. }
  2403. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2404. {
  2405. if (other.isNegative())
  2406. return operator+= (-other);
  2407. if (! isNegative())
  2408. {
  2409. if (compareAbsolute (other) < 0)
  2410. {
  2411. BigInteger temp (other);
  2412. swapWith (temp);
  2413. operator-= (temp);
  2414. negate();
  2415. return *this;
  2416. }
  2417. }
  2418. else
  2419. {
  2420. negate();
  2421. operator+= (other);
  2422. negate();
  2423. return *this;
  2424. }
  2425. const int numInts = bitToIndex (highestBit) + 1;
  2426. const int maxOtherInts = bitToIndex (other.highestBit) + 1;
  2427. int64 amountToSubtract = 0;
  2428. for (int i = 0; i <= numInts; ++i)
  2429. {
  2430. if (i <= maxOtherInts)
  2431. amountToSubtract += (int64) other.values[i];
  2432. if (values[i] >= amountToSubtract)
  2433. {
  2434. values[i] = (uint32) (values[i] - amountToSubtract);
  2435. amountToSubtract = 0;
  2436. }
  2437. else
  2438. {
  2439. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2440. values[i] = (uint32) n;
  2441. amountToSubtract = 1;
  2442. }
  2443. }
  2444. return *this;
  2445. }
  2446. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2447. {
  2448. BigInteger total;
  2449. highestBit = getHighestBit();
  2450. const bool wasNegative = isNegative();
  2451. setNegative (false);
  2452. for (int i = 0; i <= highestBit; ++i)
  2453. {
  2454. if (operator[](i))
  2455. {
  2456. BigInteger n (other);
  2457. n.setNegative (false);
  2458. n <<= i;
  2459. total += n;
  2460. }
  2461. }
  2462. total.setNegative (wasNegative ^ other.isNegative());
  2463. swapWith (total);
  2464. return *this;
  2465. }
  2466. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2467. {
  2468. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2469. const int divHB = divisor.getHighestBit();
  2470. const int ourHB = getHighestBit();
  2471. if (divHB < 0 || ourHB < 0)
  2472. {
  2473. // division by zero
  2474. remainder.clear();
  2475. clear();
  2476. }
  2477. else
  2478. {
  2479. const bool wasNegative = isNegative();
  2480. swapWith (remainder);
  2481. remainder.setNegative (false);
  2482. clear();
  2483. BigInteger temp (divisor);
  2484. temp.setNegative (false);
  2485. int leftShift = ourHB - divHB;
  2486. temp <<= leftShift;
  2487. while (leftShift >= 0)
  2488. {
  2489. if (remainder.compareAbsolute (temp) >= 0)
  2490. {
  2491. remainder -= temp;
  2492. setBit (leftShift);
  2493. }
  2494. if (--leftShift >= 0)
  2495. temp >>= 1;
  2496. }
  2497. negative = wasNegative ^ divisor.isNegative();
  2498. remainder.setNegative (wasNegative);
  2499. }
  2500. }
  2501. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2502. {
  2503. BigInteger remainder;
  2504. divideBy (other, remainder);
  2505. return *this;
  2506. }
  2507. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2508. {
  2509. // this operation doesn't take into account negative values..
  2510. jassert (isNegative() == other.isNegative());
  2511. if (other.highestBit >= 0)
  2512. {
  2513. ensureSize (bitToIndex (other.highestBit));
  2514. int n = bitToIndex (other.highestBit) + 1;
  2515. while (--n >= 0)
  2516. values[n] |= other.values[n];
  2517. if (other.highestBit > highestBit)
  2518. highestBit = other.highestBit;
  2519. highestBit = getHighestBit();
  2520. }
  2521. return *this;
  2522. }
  2523. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2524. {
  2525. // this operation doesn't take into account negative values..
  2526. jassert (isNegative() == other.isNegative());
  2527. int n = numValues;
  2528. while (n > other.numValues)
  2529. values[--n] = 0;
  2530. while (--n >= 0)
  2531. values[n] &= other.values[n];
  2532. if (other.highestBit < highestBit)
  2533. highestBit = other.highestBit;
  2534. highestBit = getHighestBit();
  2535. return *this;
  2536. }
  2537. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2538. {
  2539. // this operation will only work with the absolute values
  2540. jassert (isNegative() == other.isNegative());
  2541. if (other.highestBit >= 0)
  2542. {
  2543. ensureSize (bitToIndex (other.highestBit));
  2544. int n = bitToIndex (other.highestBit) + 1;
  2545. while (--n >= 0)
  2546. values[n] ^= other.values[n];
  2547. if (other.highestBit > highestBit)
  2548. highestBit = other.highestBit;
  2549. highestBit = getHighestBit();
  2550. }
  2551. return *this;
  2552. }
  2553. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2554. {
  2555. BigInteger remainder;
  2556. divideBy (divisor, remainder);
  2557. swapWith (remainder);
  2558. return *this;
  2559. }
  2560. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2561. {
  2562. shiftBits (numBitsToShift, 0);
  2563. return *this;
  2564. }
  2565. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2566. {
  2567. return operator<<= (-numBitsToShift);
  2568. }
  2569. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2570. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2571. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2572. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2573. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2574. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2575. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2576. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2577. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2578. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2579. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2580. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2581. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2582. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2583. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2584. int BigInteger::compare (const BigInteger& other) const throw()
  2585. {
  2586. if (isNegative() == other.isNegative())
  2587. {
  2588. const int absComp = compareAbsolute (other);
  2589. return isNegative() ? -absComp : absComp;
  2590. }
  2591. else
  2592. {
  2593. return isNegative() ? -1 : 1;
  2594. }
  2595. }
  2596. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2597. {
  2598. const int h1 = getHighestBit();
  2599. const int h2 = other.getHighestBit();
  2600. if (h1 > h2)
  2601. return 1;
  2602. else if (h1 < h2)
  2603. return -1;
  2604. for (int i = bitToIndex (h1) + 1; --i >= 0;)
  2605. if (values[i] != other.values[i])
  2606. return (values[i] > other.values[i]) ? 1 : -1;
  2607. return 0;
  2608. }
  2609. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2610. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2611. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2612. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2613. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2614. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2615. void BigInteger::shiftBits (int bits, const int startBit)
  2616. {
  2617. if (highestBit < 0)
  2618. return;
  2619. if (startBit > 0)
  2620. {
  2621. if (bits < 0)
  2622. {
  2623. // right shift
  2624. for (int i = startBit; i <= highestBit; ++i)
  2625. setBit (i, operator[] (i - bits));
  2626. highestBit = getHighestBit();
  2627. }
  2628. else if (bits > 0)
  2629. {
  2630. // left shift
  2631. for (int i = highestBit + 1; --i >= startBit;)
  2632. setBit (i + bits, operator[] (i));
  2633. while (--bits >= 0)
  2634. clearBit (bits + startBit);
  2635. }
  2636. }
  2637. else
  2638. {
  2639. if (bits < 0)
  2640. {
  2641. // right shift
  2642. bits = -bits;
  2643. if (bits > highestBit)
  2644. {
  2645. clear();
  2646. }
  2647. else
  2648. {
  2649. const int wordsToMove = bitToIndex (bits);
  2650. int top = 1 + bitToIndex (highestBit) - wordsToMove;
  2651. highestBit -= bits;
  2652. if (wordsToMove > 0)
  2653. {
  2654. int i;
  2655. for (i = 0; i < top; ++i)
  2656. values [i] = values [i + wordsToMove];
  2657. for (i = 0; i < wordsToMove; ++i)
  2658. values [top + i] = 0;
  2659. bits &= 31;
  2660. }
  2661. if (bits != 0)
  2662. {
  2663. const int invBits = 32 - bits;
  2664. --top;
  2665. for (int i = 0; i < top; ++i)
  2666. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2667. values[top] = (values[top] >> bits);
  2668. }
  2669. highestBit = getHighestBit();
  2670. }
  2671. }
  2672. else if (bits > 0)
  2673. {
  2674. // left shift
  2675. ensureSize (bitToIndex (highestBit + bits) + 1);
  2676. const int wordsToMove = bitToIndex (bits);
  2677. int top = 1 + bitToIndex (highestBit);
  2678. highestBit += bits;
  2679. if (wordsToMove > 0)
  2680. {
  2681. int i;
  2682. for (i = top; --i >= 0;)
  2683. values [i + wordsToMove] = values [i];
  2684. for (i = 0; i < wordsToMove; ++i)
  2685. values [i] = 0;
  2686. bits &= 31;
  2687. }
  2688. if (bits != 0)
  2689. {
  2690. const int invBits = 32 - bits;
  2691. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2692. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2693. values [wordsToMove] = values [wordsToMove] << bits;
  2694. }
  2695. highestBit = getHighestBit();
  2696. }
  2697. }
  2698. }
  2699. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2700. {
  2701. while (! m->isZero())
  2702. {
  2703. if (n->compareAbsolute (*m) > 0)
  2704. swapVariables (m, n);
  2705. *m -= *n;
  2706. }
  2707. return *n;
  2708. }
  2709. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2710. {
  2711. BigInteger m (*this);
  2712. while (! n.isZero())
  2713. {
  2714. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2715. return simpleGCD (&m, &n);
  2716. BigInteger temp1 (m), temp2;
  2717. temp1.divideBy (n, temp2);
  2718. m = n;
  2719. n = temp2;
  2720. }
  2721. return m;
  2722. }
  2723. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2724. {
  2725. BigInteger exp (exponent);
  2726. exp %= modulus;
  2727. BigInteger value (1);
  2728. swapWith (value);
  2729. value %= modulus;
  2730. while (! exp.isZero())
  2731. {
  2732. if (exp [0])
  2733. {
  2734. operator*= (value);
  2735. operator%= (modulus);
  2736. }
  2737. value *= value;
  2738. value %= modulus;
  2739. exp >>= 1;
  2740. }
  2741. }
  2742. void BigInteger::inverseModulo (const BigInteger& modulus)
  2743. {
  2744. if (modulus.isOne() || modulus.isNegative())
  2745. {
  2746. clear();
  2747. return;
  2748. }
  2749. if (isNegative() || compareAbsolute (modulus) >= 0)
  2750. operator%= (modulus);
  2751. if (isOne())
  2752. return;
  2753. if (! (*this)[0])
  2754. {
  2755. // not invertible
  2756. clear();
  2757. return;
  2758. }
  2759. BigInteger a1 (modulus);
  2760. BigInteger a2 (*this);
  2761. BigInteger b1 (modulus);
  2762. BigInteger b2 (1);
  2763. while (! a2.isOne())
  2764. {
  2765. BigInteger temp1, temp2, multiplier (a1);
  2766. multiplier.divideBy (a2, temp1);
  2767. temp1 = a2;
  2768. temp1 *= multiplier;
  2769. temp2 = a1;
  2770. temp2 -= temp1;
  2771. a1 = a2;
  2772. a2 = temp2;
  2773. temp1 = b2;
  2774. temp1 *= multiplier;
  2775. temp2 = b1;
  2776. temp2 -= temp1;
  2777. b1 = b2;
  2778. b2 = temp2;
  2779. }
  2780. while (b2.isNegative())
  2781. b2 += modulus;
  2782. b2 %= modulus;
  2783. swapWith (b2);
  2784. }
  2785. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2786. {
  2787. return stream << value.toString (10);
  2788. }
  2789. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2790. {
  2791. String s;
  2792. BigInteger v (*this);
  2793. if (base == 2 || base == 8 || base == 16)
  2794. {
  2795. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2796. static const char* const hexDigits = "0123456789abcdef";
  2797. for (;;)
  2798. {
  2799. const int remainder = v.getBitRangeAsInt (0, bits);
  2800. v >>= bits;
  2801. if (remainder == 0 && v.isZero())
  2802. break;
  2803. s = String::charToString (hexDigits [remainder]) + s;
  2804. }
  2805. }
  2806. else if (base == 10)
  2807. {
  2808. const BigInteger ten (10);
  2809. BigInteger remainder;
  2810. for (;;)
  2811. {
  2812. v.divideBy (ten, remainder);
  2813. if (remainder.isZero() && v.isZero())
  2814. break;
  2815. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2816. }
  2817. }
  2818. else
  2819. {
  2820. jassertfalse; // can't do the specified base!
  2821. return String::empty;
  2822. }
  2823. s = s.paddedLeft ('0', minimumNumCharacters);
  2824. return isNegative() ? "-" + s : s;
  2825. }
  2826. void BigInteger::parseString (const String& text, const int base)
  2827. {
  2828. clear();
  2829. String::CharPointerType t (text.getCharPointer());
  2830. if (base == 2 || base == 8 || base == 16)
  2831. {
  2832. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2833. for (;;)
  2834. {
  2835. const juce_wchar c = t.getAndAdvance();
  2836. const int digit = CharacterFunctions::getHexDigitValue (c);
  2837. if (((uint32) digit) < (uint32) base)
  2838. {
  2839. operator<<= (bits);
  2840. operator+= (digit);
  2841. }
  2842. else if (c == 0)
  2843. {
  2844. break;
  2845. }
  2846. }
  2847. }
  2848. else if (base == 10)
  2849. {
  2850. const BigInteger ten ((uint32) 10);
  2851. for (;;)
  2852. {
  2853. const juce_wchar c = t.getAndAdvance();
  2854. if (c >= '0' && c <= '9')
  2855. {
  2856. operator*= (ten);
  2857. operator+= ((int) (c - '0'));
  2858. }
  2859. else if (c == 0)
  2860. {
  2861. break;
  2862. }
  2863. }
  2864. }
  2865. setNegative (text.trimStart().startsWithChar ('-'));
  2866. }
  2867. const MemoryBlock BigInteger::toMemoryBlock() const
  2868. {
  2869. const int numBytes = (getHighestBit() + 8) >> 3;
  2870. MemoryBlock mb ((size_t) numBytes);
  2871. for (int i = 0; i < numBytes; ++i)
  2872. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2873. return mb;
  2874. }
  2875. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2876. {
  2877. clear();
  2878. for (int i = (int) data.getSize(); --i >= 0;)
  2879. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2880. }
  2881. END_JUCE_NAMESPACE
  2882. /*** End of inlined file: juce_BigInteger.cpp ***/
  2883. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2884. BEGIN_JUCE_NAMESPACE
  2885. MemoryBlock::MemoryBlock() throw()
  2886. : size (0)
  2887. {
  2888. }
  2889. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2890. {
  2891. if (initialSize > 0)
  2892. {
  2893. size = initialSize;
  2894. data.allocate (initialSize, initialiseToZero);
  2895. }
  2896. else
  2897. {
  2898. size = 0;
  2899. }
  2900. }
  2901. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2902. : size (other.size)
  2903. {
  2904. if (size > 0)
  2905. {
  2906. jassert (other.data != 0);
  2907. data.malloc (size);
  2908. memcpy (data, other.data, size);
  2909. }
  2910. }
  2911. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2912. : size (jmax ((size_t) 0, sizeInBytes))
  2913. {
  2914. jassert (sizeInBytes >= 0);
  2915. if (size > 0)
  2916. {
  2917. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2918. data.malloc (size);
  2919. if (dataToInitialiseFrom != 0)
  2920. memcpy (data, dataToInitialiseFrom, size);
  2921. }
  2922. }
  2923. MemoryBlock::~MemoryBlock() throw()
  2924. {
  2925. jassert (size >= 0); // should never happen
  2926. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2927. }
  2928. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2929. {
  2930. if (this != &other)
  2931. {
  2932. setSize (other.size, false);
  2933. memcpy (data, other.data, size);
  2934. }
  2935. return *this;
  2936. }
  2937. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2938. {
  2939. return matches (other.data, other.size);
  2940. }
  2941. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2942. {
  2943. return ! operator== (other);
  2944. }
  2945. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2946. {
  2947. return size == dataSize
  2948. && memcmp (data, dataToCompare, size) == 0;
  2949. }
  2950. // this will resize the block to this size
  2951. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2952. {
  2953. if (size != newSize)
  2954. {
  2955. if (newSize <= 0)
  2956. {
  2957. data.free();
  2958. size = 0;
  2959. }
  2960. else
  2961. {
  2962. if (data != 0)
  2963. {
  2964. data.realloc (newSize);
  2965. if (initialiseToZero && (newSize > size))
  2966. zeromem (data + size, newSize - size);
  2967. }
  2968. else
  2969. {
  2970. data.allocate (newSize, initialiseToZero);
  2971. }
  2972. size = newSize;
  2973. }
  2974. }
  2975. }
  2976. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2977. {
  2978. if (size < minimumSize)
  2979. setSize (minimumSize, initialiseToZero);
  2980. }
  2981. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2982. {
  2983. swapVariables (size, other.size);
  2984. data.swapWith (other.data);
  2985. }
  2986. void MemoryBlock::fillWith (const uint8 value) throw()
  2987. {
  2988. memset (data, (int) value, size);
  2989. }
  2990. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  2991. {
  2992. if (numBytes > 0)
  2993. {
  2994. const size_t oldSize = size;
  2995. setSize (size + numBytes);
  2996. memcpy (data + oldSize, srcData, numBytes);
  2997. }
  2998. }
  2999. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  3000. {
  3001. const char* d = static_cast<const char*> (src);
  3002. if (offset < 0)
  3003. {
  3004. d -= offset;
  3005. num -= offset;
  3006. offset = 0;
  3007. }
  3008. if (offset + num > size)
  3009. num = size - offset;
  3010. if (num > 0)
  3011. memcpy (data + offset, d, num);
  3012. }
  3013. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  3014. {
  3015. char* d = static_cast<char*> (dst);
  3016. if (offset < 0)
  3017. {
  3018. zeromem (d, -offset);
  3019. d -= offset;
  3020. num += offset;
  3021. offset = 0;
  3022. }
  3023. if (offset + num > size)
  3024. {
  3025. const size_t newNum = size - offset;
  3026. zeromem (d + newNum, num - newNum);
  3027. num = newNum;
  3028. }
  3029. if (num > 0)
  3030. memcpy (d, data + offset, num);
  3031. }
  3032. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  3033. {
  3034. if (startByte + numBytesToRemove >= size)
  3035. {
  3036. setSize (startByte);
  3037. }
  3038. else if (numBytesToRemove > 0)
  3039. {
  3040. memmove (data + startByte,
  3041. data + startByte + numBytesToRemove,
  3042. size - (startByte + numBytesToRemove));
  3043. setSize (size - numBytesToRemove);
  3044. }
  3045. }
  3046. const String MemoryBlock::toString() const
  3047. {
  3048. return String (static_cast <const char*> (getData()), size);
  3049. }
  3050. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  3051. {
  3052. int res = 0;
  3053. size_t byte = bitRangeStart >> 3;
  3054. int offsetInByte = (int) bitRangeStart & 7;
  3055. size_t bitsSoFar = 0;
  3056. while (numBits > 0 && (size_t) byte < size)
  3057. {
  3058. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  3059. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  3060. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  3061. bitsSoFar += bitsThisTime;
  3062. numBits -= bitsThisTime;
  3063. ++byte;
  3064. offsetInByte = 0;
  3065. }
  3066. return res;
  3067. }
  3068. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  3069. {
  3070. size_t byte = bitRangeStart >> 3;
  3071. int offsetInByte = (int) bitRangeStart & 7;
  3072. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  3073. while (numBits > 0 && (size_t) byte < size)
  3074. {
  3075. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  3076. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  3077. const unsigned int tempBits = bitsToSet << offsetInByte;
  3078. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  3079. ++byte;
  3080. numBits -= bitsThisTime;
  3081. bitsToSet >>= bitsThisTime;
  3082. mask >>= bitsThisTime;
  3083. offsetInByte = 0;
  3084. }
  3085. }
  3086. void MemoryBlock::loadFromHexString (const String& hex)
  3087. {
  3088. ensureSize (hex.length() >> 1);
  3089. char* dest = data;
  3090. int i = 0;
  3091. for (;;)
  3092. {
  3093. int byte = 0;
  3094. for (int loop = 2; --loop >= 0;)
  3095. {
  3096. byte <<= 4;
  3097. for (;;)
  3098. {
  3099. const juce_wchar c = hex [i++];
  3100. if (c >= '0' && c <= '9')
  3101. {
  3102. byte |= c - '0';
  3103. break;
  3104. }
  3105. else if (c >= 'a' && c <= 'z')
  3106. {
  3107. byte |= c - ('a' - 10);
  3108. break;
  3109. }
  3110. else if (c >= 'A' && c <= 'Z')
  3111. {
  3112. byte |= c - ('A' - 10);
  3113. break;
  3114. }
  3115. else if (c == 0)
  3116. {
  3117. setSize (static_cast <size_t> (dest - data));
  3118. return;
  3119. }
  3120. }
  3121. }
  3122. *dest++ = (char) byte;
  3123. }
  3124. }
  3125. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  3126. const String MemoryBlock::toBase64Encoding() const
  3127. {
  3128. const size_t numChars = ((size << 3) + 5) / 6;
  3129. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3130. const int initialLen = destString.length();
  3131. destString.preallocateStorage (initialLen + 2 + numChars);
  3132. String::CharPointerType d (destString.getCharPointer());
  3133. d += initialLen;
  3134. d.write ('.');
  3135. for (size_t i = 0; i < numChars; ++i)
  3136. d.write (encodingTable [getBitRange (i * 6, 6)]);
  3137. d.writeNull();
  3138. return destString;
  3139. }
  3140. bool MemoryBlock::fromBase64Encoding (const String& s)
  3141. {
  3142. const int startPos = s.indexOfChar ('.') + 1;
  3143. if (startPos <= 0)
  3144. return false;
  3145. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3146. setSize (numBytesNeeded, true);
  3147. const int numChars = s.length() - startPos;
  3148. String::CharPointerType srcChars (s.getCharPointer());
  3149. srcChars += startPos;
  3150. int pos = 0;
  3151. for (int i = 0; i < numChars; ++i)
  3152. {
  3153. const char c = (char) srcChars.getAndAdvance();
  3154. for (int j = 0; j < 64; ++j)
  3155. {
  3156. if (encodingTable[j] == c)
  3157. {
  3158. setBitRange (pos, 6, j);
  3159. pos += 6;
  3160. break;
  3161. }
  3162. }
  3163. }
  3164. return true;
  3165. }
  3166. END_JUCE_NAMESPACE
  3167. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3168. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3169. BEGIN_JUCE_NAMESPACE
  3170. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3171. : properties (ignoreCaseOfKeyNames),
  3172. fallbackProperties (0),
  3173. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3174. {
  3175. }
  3176. PropertySet::PropertySet (const PropertySet& other)
  3177. : properties (other.properties),
  3178. fallbackProperties (other.fallbackProperties),
  3179. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3180. {
  3181. }
  3182. PropertySet& PropertySet::operator= (const PropertySet& other)
  3183. {
  3184. properties = other.properties;
  3185. fallbackProperties = other.fallbackProperties;
  3186. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3187. propertyChanged();
  3188. return *this;
  3189. }
  3190. PropertySet::~PropertySet()
  3191. {
  3192. }
  3193. void PropertySet::clear()
  3194. {
  3195. const ScopedLock sl (lock);
  3196. if (properties.size() > 0)
  3197. {
  3198. properties.clear();
  3199. propertyChanged();
  3200. }
  3201. }
  3202. const String PropertySet::getValue (const String& keyName,
  3203. const String& defaultValue) const throw()
  3204. {
  3205. const ScopedLock sl (lock);
  3206. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3207. if (index >= 0)
  3208. return properties.getAllValues() [index];
  3209. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3210. : defaultValue;
  3211. }
  3212. int PropertySet::getIntValue (const String& keyName,
  3213. const int defaultValue) const throw()
  3214. {
  3215. const ScopedLock sl (lock);
  3216. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3217. if (index >= 0)
  3218. return properties.getAllValues() [index].getIntValue();
  3219. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3220. : defaultValue;
  3221. }
  3222. double PropertySet::getDoubleValue (const String& keyName,
  3223. const double defaultValue) const throw()
  3224. {
  3225. const ScopedLock sl (lock);
  3226. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3227. if (index >= 0)
  3228. return properties.getAllValues()[index].getDoubleValue();
  3229. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3230. : defaultValue;
  3231. }
  3232. bool PropertySet::getBoolValue (const String& keyName,
  3233. const bool defaultValue) const throw()
  3234. {
  3235. const ScopedLock sl (lock);
  3236. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3237. if (index >= 0)
  3238. return properties.getAllValues() [index].getIntValue() != 0;
  3239. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3240. : defaultValue;
  3241. }
  3242. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3243. {
  3244. return XmlDocument::parse (getValue (keyName));
  3245. }
  3246. void PropertySet::setValue (const String& keyName, const var& v)
  3247. {
  3248. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3249. if (keyName.isNotEmpty())
  3250. {
  3251. const String value (v.toString());
  3252. const ScopedLock sl (lock);
  3253. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3254. if (index < 0 || properties.getAllValues() [index] != value)
  3255. {
  3256. properties.set (keyName, value);
  3257. propertyChanged();
  3258. }
  3259. }
  3260. }
  3261. void PropertySet::removeValue (const String& keyName)
  3262. {
  3263. if (keyName.isNotEmpty())
  3264. {
  3265. const ScopedLock sl (lock);
  3266. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3267. if (index >= 0)
  3268. {
  3269. properties.remove (keyName);
  3270. propertyChanged();
  3271. }
  3272. }
  3273. }
  3274. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3275. {
  3276. setValue (keyName, xml == 0 ? var::null
  3277. : var (xml->createDocument (String::empty, true)));
  3278. }
  3279. bool PropertySet::containsKey (const String& keyName) const throw()
  3280. {
  3281. const ScopedLock sl (lock);
  3282. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3283. }
  3284. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3285. {
  3286. const ScopedLock sl (lock);
  3287. fallbackProperties = fallbackProperties_;
  3288. }
  3289. XmlElement* PropertySet::createXml (const String& nodeName) const
  3290. {
  3291. const ScopedLock sl (lock);
  3292. XmlElement* const xml = new XmlElement (nodeName);
  3293. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3294. {
  3295. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3296. e->setAttribute ("name", properties.getAllKeys()[i]);
  3297. e->setAttribute ("val", properties.getAllValues()[i]);
  3298. }
  3299. return xml;
  3300. }
  3301. void PropertySet::restoreFromXml (const XmlElement& xml)
  3302. {
  3303. const ScopedLock sl (lock);
  3304. clear();
  3305. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3306. {
  3307. if (e->hasAttribute ("name")
  3308. && e->hasAttribute ("val"))
  3309. {
  3310. properties.set (e->getStringAttribute ("name"),
  3311. e->getStringAttribute ("val"));
  3312. }
  3313. }
  3314. if (properties.size() > 0)
  3315. propertyChanged();
  3316. }
  3317. void PropertySet::propertyChanged()
  3318. {
  3319. }
  3320. END_JUCE_NAMESPACE
  3321. /*** End of inlined file: juce_PropertySet.cpp ***/
  3322. /*** Start of inlined file: juce_Identifier.cpp ***/
  3323. BEGIN_JUCE_NAMESPACE
  3324. StringPool& Identifier::getPool()
  3325. {
  3326. static StringPool pool;
  3327. return pool;
  3328. }
  3329. Identifier::Identifier() throw()
  3330. : name (0)
  3331. {
  3332. }
  3333. Identifier::Identifier (const Identifier& other) throw()
  3334. : name (other.name)
  3335. {
  3336. }
  3337. Identifier& Identifier::operator= (const Identifier& other) throw()
  3338. {
  3339. name = other.name;
  3340. return *this;
  3341. }
  3342. Identifier::Identifier (const String& name_)
  3343. : name (Identifier::getPool().getPooledString (name_))
  3344. {
  3345. /* An Identifier string must be suitable for use as a script variable or XML
  3346. attribute, so it can only contain this limited set of characters.. */
  3347. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3348. }
  3349. Identifier::Identifier (const char* const name_)
  3350. : name (Identifier::getPool().getPooledString (name_))
  3351. {
  3352. /* An Identifier string must be suitable for use as a script variable or XML
  3353. attribute, so it can only contain this limited set of characters.. */
  3354. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3355. }
  3356. Identifier::~Identifier()
  3357. {
  3358. }
  3359. END_JUCE_NAMESPACE
  3360. /*** End of inlined file: juce_Identifier.cpp ***/
  3361. /*** Start of inlined file: juce_Variant.cpp ***/
  3362. BEGIN_JUCE_NAMESPACE
  3363. class var::VariantType
  3364. {
  3365. public:
  3366. VariantType() {}
  3367. virtual ~VariantType() {}
  3368. virtual int toInt (const ValueUnion&) const { return 0; }
  3369. virtual double toDouble (const ValueUnion&) const { return 0; }
  3370. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3371. virtual bool toBool (const ValueUnion&) const { return false; }
  3372. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3373. virtual bool isVoid() const throw() { return false; }
  3374. virtual bool isInt() const throw() { return false; }
  3375. virtual bool isBool() const throw() { return false; }
  3376. virtual bool isDouble() const throw() { return false; }
  3377. virtual bool isString() const throw() { return false; }
  3378. virtual bool isObject() const throw() { return false; }
  3379. virtual bool isMethod() const throw() { return false; }
  3380. virtual void cleanUp (ValueUnion&) const throw() {}
  3381. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3382. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3383. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3384. };
  3385. class var::VariantType_Void : public var::VariantType
  3386. {
  3387. public:
  3388. VariantType_Void() {}
  3389. static const VariantType_Void instance;
  3390. bool isVoid() const throw() { return true; }
  3391. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3392. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3393. };
  3394. class var::VariantType_Int : public var::VariantType
  3395. {
  3396. public:
  3397. VariantType_Int() {}
  3398. static const VariantType_Int instance;
  3399. int toInt (const ValueUnion& data) const { return data.intValue; };
  3400. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3401. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3402. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3403. bool isInt() const throw() { return true; }
  3404. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3405. {
  3406. return otherType.toInt (otherData) == data.intValue;
  3407. }
  3408. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3409. {
  3410. output.writeCompressedInt (5);
  3411. output.writeByte (1);
  3412. output.writeInt (data.intValue);
  3413. }
  3414. };
  3415. class var::VariantType_Double : public var::VariantType
  3416. {
  3417. public:
  3418. VariantType_Double() {}
  3419. static const VariantType_Double instance;
  3420. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3421. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3422. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3423. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3424. bool isDouble() const throw() { return true; }
  3425. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3426. {
  3427. return otherType.toDouble (otherData) == data.doubleValue;
  3428. }
  3429. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3430. {
  3431. output.writeCompressedInt (9);
  3432. output.writeByte (4);
  3433. output.writeDouble (data.doubleValue);
  3434. }
  3435. };
  3436. class var::VariantType_Bool : public var::VariantType
  3437. {
  3438. public:
  3439. VariantType_Bool() {}
  3440. static const VariantType_Bool instance;
  3441. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3442. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3443. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3444. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3445. bool isBool() const throw() { return true; }
  3446. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3447. {
  3448. return otherType.toBool (otherData) == data.boolValue;
  3449. }
  3450. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3451. {
  3452. output.writeCompressedInt (1);
  3453. output.writeByte (data.boolValue ? 2 : 3);
  3454. }
  3455. };
  3456. class var::VariantType_String : public var::VariantType
  3457. {
  3458. public:
  3459. VariantType_String() {}
  3460. static const VariantType_String instance;
  3461. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3462. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3463. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3464. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3465. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3466. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3467. || data.stringValue->trim().equalsIgnoreCase ("true")
  3468. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3469. bool isString() const throw() { return true; }
  3470. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3471. {
  3472. return otherType.toString (otherData) == *data.stringValue;
  3473. }
  3474. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3475. {
  3476. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3477. output.writeCompressedInt (len + 1);
  3478. output.writeByte (5);
  3479. HeapBlock<char> temp (len);
  3480. data.stringValue->copyToUTF8 (temp, len);
  3481. output.write (temp, len);
  3482. }
  3483. };
  3484. class var::VariantType_Object : public var::VariantType
  3485. {
  3486. public:
  3487. VariantType_Object() {}
  3488. static const VariantType_Object instance;
  3489. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3490. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3491. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3492. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3493. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3494. bool isObject() const throw() { return true; }
  3495. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3496. {
  3497. return otherType.toObject (otherData) == data.objectValue;
  3498. }
  3499. void writeToStream (const ValueUnion&, OutputStream& output) const
  3500. {
  3501. jassertfalse; // Can't write an object to a stream!
  3502. output.writeCompressedInt (0);
  3503. }
  3504. };
  3505. class var::VariantType_Method : public var::VariantType
  3506. {
  3507. public:
  3508. VariantType_Method() {}
  3509. static const VariantType_Method instance;
  3510. const String toString (const ValueUnion&) const { return "Method"; }
  3511. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3512. bool isMethod() const throw() { return true; }
  3513. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3514. {
  3515. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3516. }
  3517. void writeToStream (const ValueUnion&, OutputStream& output) const
  3518. {
  3519. jassertfalse; // Can't write a method to a stream!
  3520. output.writeCompressedInt (0);
  3521. }
  3522. };
  3523. const var::VariantType_Void var::VariantType_Void::instance;
  3524. const var::VariantType_Int var::VariantType_Int::instance;
  3525. const var::VariantType_Bool var::VariantType_Bool::instance;
  3526. const var::VariantType_Double var::VariantType_Double::instance;
  3527. const var::VariantType_String var::VariantType_String::instance;
  3528. const var::VariantType_Object var::VariantType_Object::instance;
  3529. const var::VariantType_Method var::VariantType_Method::instance;
  3530. var::var() throw() : type (&VariantType_Void::instance)
  3531. {
  3532. }
  3533. var::~var() throw()
  3534. {
  3535. type->cleanUp (value);
  3536. }
  3537. const var var::null;
  3538. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3539. {
  3540. type->createCopy (value, valueToCopy.value);
  3541. }
  3542. var::var (const int value_) throw() : type (&VariantType_Int::instance)
  3543. {
  3544. value.intValue = value_;
  3545. }
  3546. var::var (const bool value_) throw() : type (&VariantType_Bool::instance)
  3547. {
  3548. value.boolValue = value_;
  3549. }
  3550. var::var (const double value_) throw() : type (&VariantType_Double::instance)
  3551. {
  3552. value.doubleValue = value_;
  3553. }
  3554. var::var (const String& value_) : type (&VariantType_String::instance)
  3555. {
  3556. value.stringValue = new String (value_);
  3557. }
  3558. var::var (const char* const value_) : type (&VariantType_String::instance)
  3559. {
  3560. value.stringValue = new String (value_);
  3561. }
  3562. var::var (const juce_wchar* const value_) : type (&VariantType_String::instance)
  3563. {
  3564. value.stringValue = new String (value_);
  3565. }
  3566. var::var (DynamicObject* const object) : type (&VariantType_Object::instance)
  3567. {
  3568. value.objectValue = object;
  3569. if (object != 0)
  3570. object->incReferenceCount();
  3571. }
  3572. var::var (MethodFunction method_) throw() : type (&VariantType_Method::instance)
  3573. {
  3574. value.methodValue = method_;
  3575. }
  3576. bool var::isVoid() const throw() { return type->isVoid(); }
  3577. bool var::isInt() const throw() { return type->isInt(); }
  3578. bool var::isBool() const throw() { return type->isBool(); }
  3579. bool var::isDouble() const throw() { return type->isDouble(); }
  3580. bool var::isString() const throw() { return type->isString(); }
  3581. bool var::isObject() const throw() { return type->isObject(); }
  3582. bool var::isMethod() const throw() { return type->isMethod(); }
  3583. var::operator int() const { return type->toInt (value); }
  3584. var::operator bool() const { return type->toBool (value); }
  3585. var::operator float() const { return (float) type->toDouble (value); }
  3586. var::operator double() const { return type->toDouble (value); }
  3587. const String var::toString() const { return type->toString (value); }
  3588. var::operator const String() const { return type->toString (value); }
  3589. DynamicObject* var::getObject() const { return type->toObject (value); }
  3590. void var::swapWith (var& other) throw()
  3591. {
  3592. swapVariables (type, other.type);
  3593. swapVariables (value, other.value);
  3594. }
  3595. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3596. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3597. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3598. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3599. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3600. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3601. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3602. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3603. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3604. bool var::equals (const var& other) const throw()
  3605. {
  3606. return type->equals (value, other.value, *other.type);
  3607. }
  3608. bool var::equalsWithSameType (const var& other) const throw()
  3609. {
  3610. return type == other.type && equals (other);
  3611. }
  3612. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3613. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3614. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3615. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3616. void var::writeToStream (OutputStream& output) const
  3617. {
  3618. type->writeToStream (value, output);
  3619. }
  3620. const var var::readFromStream (InputStream& input)
  3621. {
  3622. const int numBytes = input.readCompressedInt();
  3623. if (numBytes > 0)
  3624. {
  3625. switch (input.readByte())
  3626. {
  3627. case 1: return var (input.readInt());
  3628. case 2: return var (true);
  3629. case 3: return var (false);
  3630. case 4: return var (input.readDouble());
  3631. case 5:
  3632. {
  3633. MemoryOutputStream mo;
  3634. mo.writeFromInputStream (input, numBytes - 1);
  3635. return var (mo.toUTF8());
  3636. }
  3637. default: input.skipNextBytes (numBytes - 1); break;
  3638. }
  3639. }
  3640. return var::null;
  3641. }
  3642. const var var::operator[] (const Identifier& propertyName) const
  3643. {
  3644. DynamicObject* const o = getObject();
  3645. return o != 0 ? o->getProperty (propertyName) : var::null;
  3646. }
  3647. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3648. {
  3649. DynamicObject* const o = getObject();
  3650. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3651. }
  3652. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3653. {
  3654. if (isMethod())
  3655. {
  3656. DynamicObject* const target = targetObject.getObject();
  3657. if (target != 0)
  3658. return (target->*(value.methodValue)) (arguments, numArguments);
  3659. }
  3660. return var::null;
  3661. }
  3662. const var var::call (const Identifier& method) const
  3663. {
  3664. return invoke (method, 0, 0);
  3665. }
  3666. const var var::call (const Identifier& method, const var& arg1) const
  3667. {
  3668. return invoke (method, &arg1, 1);
  3669. }
  3670. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3671. {
  3672. var args[] = { arg1, arg2 };
  3673. return invoke (method, args, 2);
  3674. }
  3675. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3676. {
  3677. var args[] = { arg1, arg2, arg3 };
  3678. return invoke (method, args, 3);
  3679. }
  3680. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3681. {
  3682. var args[] = { arg1, arg2, arg3, arg4 };
  3683. return invoke (method, args, 4);
  3684. }
  3685. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3686. {
  3687. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3688. return invoke (method, args, 5);
  3689. }
  3690. END_JUCE_NAMESPACE
  3691. /*** End of inlined file: juce_Variant.cpp ***/
  3692. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3693. BEGIN_JUCE_NAMESPACE
  3694. NamedValueSet::NamedValue::NamedValue() throw()
  3695. {
  3696. }
  3697. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3698. : name (name_), value (value_)
  3699. {
  3700. }
  3701. NamedValueSet::NamedValue::NamedValue (const NamedValue& other)
  3702. : name (other.name), value (other.value)
  3703. {
  3704. }
  3705. NamedValueSet::NamedValue& NamedValueSet::NamedValue::operator= (const NamedValueSet::NamedValue& other)
  3706. {
  3707. name = other.name;
  3708. value = other.value;
  3709. return *this;
  3710. }
  3711. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3712. {
  3713. return name == other.name && value == other.value;
  3714. }
  3715. NamedValueSet::NamedValueSet() throw()
  3716. {
  3717. }
  3718. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3719. {
  3720. values.addCopyOfList (other.values);
  3721. }
  3722. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3723. {
  3724. clear();
  3725. values.addCopyOfList (other.values);
  3726. return *this;
  3727. }
  3728. NamedValueSet::~NamedValueSet()
  3729. {
  3730. clear();
  3731. }
  3732. void NamedValueSet::clear()
  3733. {
  3734. values.deleteAll();
  3735. }
  3736. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3737. {
  3738. const NamedValue* i1 = values;
  3739. const NamedValue* i2 = other.values;
  3740. while (i1 != 0 && i2 != 0)
  3741. {
  3742. if (! (*i1 == *i2))
  3743. return false;
  3744. i1 = i1->nextListItem;
  3745. i2 = i2->nextListItem;
  3746. }
  3747. return true;
  3748. }
  3749. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3750. {
  3751. return ! operator== (other);
  3752. }
  3753. int NamedValueSet::size() const throw()
  3754. {
  3755. return values.size();
  3756. }
  3757. const var& NamedValueSet::operator[] (const Identifier& name) const
  3758. {
  3759. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3760. if (i->name == name)
  3761. return i->value;
  3762. return var::null;
  3763. }
  3764. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3765. {
  3766. const var* v = getVarPointer (name);
  3767. return v != 0 ? *v : defaultReturnValue;
  3768. }
  3769. var* NamedValueSet::getVarPointer (const Identifier& name) const
  3770. {
  3771. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3772. if (i->name == name)
  3773. return &(i->value);
  3774. return 0;
  3775. }
  3776. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3777. {
  3778. LinkedListPointer<NamedValue>* i = &values;
  3779. while (i->get() != 0)
  3780. {
  3781. NamedValue* const v = i->get();
  3782. if (v->name == name)
  3783. {
  3784. if (v->value == newValue)
  3785. return false;
  3786. v->value = newValue;
  3787. return true;
  3788. }
  3789. i = &(v->nextListItem);
  3790. }
  3791. i->insertNext (new NamedValue (name, newValue));
  3792. return true;
  3793. }
  3794. bool NamedValueSet::contains (const Identifier& name) const
  3795. {
  3796. return getVarPointer (name) != 0;
  3797. }
  3798. bool NamedValueSet::remove (const Identifier& name)
  3799. {
  3800. LinkedListPointer<NamedValue>* i = &values;
  3801. for (;;)
  3802. {
  3803. NamedValue* const v = i->get();
  3804. if (v == 0)
  3805. break;
  3806. if (v->name == name)
  3807. {
  3808. delete i->removeNext();
  3809. return true;
  3810. }
  3811. i = &(v->nextListItem);
  3812. }
  3813. return false;
  3814. }
  3815. const Identifier NamedValueSet::getName (const int index) const
  3816. {
  3817. const NamedValue* const v = values[index];
  3818. jassert (v != 0);
  3819. return v->name;
  3820. }
  3821. const var NamedValueSet::getValueAt (const int index) const
  3822. {
  3823. const NamedValue* const v = values[index];
  3824. jassert (v != 0);
  3825. return v->value;
  3826. }
  3827. void NamedValueSet::setFromXmlAttributes (const XmlElement& xml)
  3828. {
  3829. clear();
  3830. LinkedListPointer<NamedValue>::Appender appender (values);
  3831. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  3832. for (int i = 0; i < numAtts; ++i)
  3833. appender.append (new NamedValue (xml.getAttributeName (i), var (xml.getAttributeValue (i))));
  3834. }
  3835. void NamedValueSet::copyToXmlAttributes (XmlElement& xml) const
  3836. {
  3837. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3838. {
  3839. jassert (! i->value.isObject()); // DynamicObjects can't be stored as XML!
  3840. xml.setAttribute (i->name.toString(),
  3841. i->value.toString());
  3842. }
  3843. }
  3844. END_JUCE_NAMESPACE
  3845. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3846. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3847. BEGIN_JUCE_NAMESPACE
  3848. DynamicObject::DynamicObject()
  3849. {
  3850. }
  3851. DynamicObject::~DynamicObject()
  3852. {
  3853. }
  3854. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3855. {
  3856. var* const v = properties.getVarPointer (propertyName);
  3857. return v != 0 && ! v->isMethod();
  3858. }
  3859. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3860. {
  3861. return properties [propertyName];
  3862. }
  3863. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3864. {
  3865. properties.set (propertyName, newValue);
  3866. }
  3867. void DynamicObject::removeProperty (const Identifier& propertyName)
  3868. {
  3869. properties.remove (propertyName);
  3870. }
  3871. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3872. {
  3873. return getProperty (methodName).isMethod();
  3874. }
  3875. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3876. const var* parameters,
  3877. int numParameters)
  3878. {
  3879. return properties [methodName].invoke (var (this), parameters, numParameters);
  3880. }
  3881. void DynamicObject::setMethod (const Identifier& name,
  3882. var::MethodFunction methodFunction)
  3883. {
  3884. properties.set (name, var (methodFunction));
  3885. }
  3886. void DynamicObject::clear()
  3887. {
  3888. properties.clear();
  3889. }
  3890. END_JUCE_NAMESPACE
  3891. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3892. /*** Start of inlined file: juce_Expression.cpp ***/
  3893. BEGIN_JUCE_NAMESPACE
  3894. class Expression::Term : public ReferenceCountedObject
  3895. {
  3896. public:
  3897. Term() {}
  3898. virtual ~Term() {}
  3899. virtual Type getType() const throw() = 0;
  3900. virtual Term* clone() const = 0;
  3901. virtual const ReferenceCountedObjectPtr<Term> resolve (const Scope&, int recursionDepth) = 0;
  3902. virtual const String toString() const = 0;
  3903. virtual double toDouble() const { return 0; }
  3904. virtual int getInputIndexFor (const Term*) const { return -1; }
  3905. virtual int getOperatorPrecedence() const { return 0; }
  3906. virtual int getNumInputs() const { return 0; }
  3907. virtual Term* getInput (int) const { return 0; }
  3908. virtual const ReferenceCountedObjectPtr<Term> negated();
  3909. virtual const ReferenceCountedObjectPtr<Term> createTermToEvaluateInput (const Scope&, const Term* /*inputTerm*/,
  3910. double /*overallTarget*/, Term* /*topLevelTerm*/) const
  3911. {
  3912. jassertfalse;
  3913. return 0;
  3914. }
  3915. virtual const String getName() const
  3916. {
  3917. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  3918. return String::empty;
  3919. }
  3920. virtual void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int recursionDepth)
  3921. {
  3922. for (int i = getNumInputs(); --i >= 0;)
  3923. getInput (i)->renameSymbol (oldSymbol, newName, scope, recursionDepth);
  3924. }
  3925. class SymbolVisitor
  3926. {
  3927. public:
  3928. virtual ~SymbolVisitor() {}
  3929. virtual void useSymbol (const Symbol&) = 0;
  3930. };
  3931. virtual void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth)
  3932. {
  3933. for (int i = getNumInputs(); --i >= 0;)
  3934. getInput(i)->visitAllSymbols (visitor, scope, recursionDepth);
  3935. }
  3936. private:
  3937. JUCE_DECLARE_NON_COPYABLE (Term);
  3938. };
  3939. class Expression::Helpers
  3940. {
  3941. public:
  3942. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  3943. // This helper function is needed to work around VC6 scoping bugs
  3944. static inline const TermPtr& getTermFor (const Expression& exp) throw() { return exp.term; }
  3945. static void checkRecursionDepth (const int depth)
  3946. {
  3947. if (depth > 256)
  3948. throw EvaluationError ("Recursive symbol references");
  3949. }
  3950. friend class Expression::Term; // (also only needed as a VC6 workaround)
  3951. /** An exception that can be thrown by Expression::evaluate(). */
  3952. class EvaluationError : public std::exception
  3953. {
  3954. public:
  3955. EvaluationError (const String& description_)
  3956. : description (description_)
  3957. {
  3958. DBG ("Expression::EvaluationError: " + description);
  3959. }
  3960. String description;
  3961. };
  3962. class Constant : public Term
  3963. {
  3964. public:
  3965. Constant (const double value_, const bool isResolutionTarget_)
  3966. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  3967. Type getType() const throw() { return constantType; }
  3968. Term* clone() const { return new Constant (value, isResolutionTarget); }
  3969. const TermPtr resolve (const Scope&, int) { return this; }
  3970. double toDouble() const { return value; }
  3971. const TermPtr negated() { return new Constant (-value, isResolutionTarget); }
  3972. const String toString() const
  3973. {
  3974. String s (value);
  3975. if (isResolutionTarget)
  3976. s = "@" + s;
  3977. return s;
  3978. }
  3979. double value;
  3980. bool isResolutionTarget;
  3981. };
  3982. class BinaryTerm : public Term
  3983. {
  3984. public:
  3985. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  3986. {
  3987. jassert (left_ != 0 && right_ != 0);
  3988. }
  3989. int getInputIndexFor (const Term* possibleInput) const
  3990. {
  3991. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  3992. }
  3993. Type getType() const throw() { return operatorType; }
  3994. int getNumInputs() const { return 2; }
  3995. Term* getInput (int index) const { return index == 0 ? left.getObject() : (index == 1 ? right.getObject() : 0); }
  3996. virtual double performFunction (double left, double right) const = 0;
  3997. virtual void writeOperator (String& dest) const = 0;
  3998. const TermPtr resolve (const Scope& scope, int recursionDepth)
  3999. {
  4000. return new Constant (performFunction (left->resolve (scope, recursionDepth)->toDouble(),
  4001. right->resolve (scope, recursionDepth)->toDouble()), false);
  4002. }
  4003. const String toString() const
  4004. {
  4005. String s;
  4006. const int ourPrecendence = getOperatorPrecedence();
  4007. if (left->getOperatorPrecedence() > ourPrecendence)
  4008. s << '(' << left->toString() << ')';
  4009. else
  4010. s = left->toString();
  4011. writeOperator (s);
  4012. if (right->getOperatorPrecedence() >= ourPrecendence)
  4013. s << '(' << right->toString() << ')';
  4014. else
  4015. s << right->toString();
  4016. return s;
  4017. }
  4018. protected:
  4019. const TermPtr left, right;
  4020. const TermPtr createDestinationTerm (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4021. {
  4022. jassert (input == left || input == right);
  4023. if (input != left && input != right)
  4024. return 0;
  4025. const Term* const dest = findDestinationFor (topLevelTerm, this);
  4026. if (dest == 0)
  4027. return new Constant (overallTarget, false);
  4028. return dest->createTermToEvaluateInput (scope, this, overallTarget, topLevelTerm);
  4029. }
  4030. };
  4031. class SymbolTerm : public Term
  4032. {
  4033. public:
  4034. explicit SymbolTerm (const String& symbol_) : symbol (symbol_) {}
  4035. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4036. {
  4037. checkRecursionDepth (recursionDepth);
  4038. return getTermFor (scope.getSymbolValue (symbol))->resolve (scope, recursionDepth + 1);
  4039. }
  4040. Type getType() const throw() { return symbolType; }
  4041. Term* clone() const { return new SymbolTerm (symbol); }
  4042. const String toString() const { return symbol; }
  4043. const String getName() const { return symbol; }
  4044. void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth)
  4045. {
  4046. checkRecursionDepth (recursionDepth);
  4047. visitor.useSymbol (Symbol (scope.getScopeUID(), symbol));
  4048. getTermFor (scope.getSymbolValue (symbol))->visitAllSymbols (visitor, scope, recursionDepth + 1);
  4049. }
  4050. void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int /*recursionDepth*/)
  4051. {
  4052. if (oldSymbol.symbolName == symbol && scope.getScopeUID() == oldSymbol.scopeUID)
  4053. symbol = newName;
  4054. }
  4055. String symbol;
  4056. };
  4057. class Function : public Term
  4058. {
  4059. public:
  4060. explicit Function (const String& functionName_) : functionName (functionName_) {}
  4061. Function (const String& functionName_, const Array<Expression>& parameters_)
  4062. : functionName (functionName_), parameters (parameters_)
  4063. {}
  4064. Type getType() const throw() { return functionType; }
  4065. Term* clone() const { return new Function (functionName, parameters); }
  4066. int getNumInputs() const { return parameters.size(); }
  4067. Term* getInput (int i) const { return getTermFor (parameters [i]); }
  4068. const String getName() const { return functionName; }
  4069. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4070. {
  4071. checkRecursionDepth (recursionDepth);
  4072. double result = 0;
  4073. const int numParams = parameters.size();
  4074. if (numParams > 0)
  4075. {
  4076. HeapBlock<double> params (numParams);
  4077. for (int i = 0; i < numParams; ++i)
  4078. params[i] = getTermFor (parameters.getReference(i))->resolve (scope, recursionDepth + 1)->toDouble();
  4079. result = scope.evaluateFunction (functionName, params, numParams);
  4080. }
  4081. else
  4082. {
  4083. result = scope.evaluateFunction (functionName, 0, 0);
  4084. }
  4085. return new Constant (result, false);
  4086. }
  4087. int getInputIndexFor (const Term* possibleInput) const
  4088. {
  4089. for (int i = 0; i < parameters.size(); ++i)
  4090. if (getTermFor (parameters.getReference(i)) == possibleInput)
  4091. return i;
  4092. return -1;
  4093. }
  4094. const String toString() const
  4095. {
  4096. if (parameters.size() == 0)
  4097. return functionName + "()";
  4098. String s (functionName + " (");
  4099. for (int i = 0; i < parameters.size(); ++i)
  4100. {
  4101. s << getTermFor (parameters.getReference(i))->toString();
  4102. if (i < parameters.size() - 1)
  4103. s << ", ";
  4104. }
  4105. s << ')';
  4106. return s;
  4107. }
  4108. const String functionName;
  4109. Array<Expression> parameters;
  4110. };
  4111. class DotOperator : public BinaryTerm
  4112. {
  4113. public:
  4114. DotOperator (SymbolTerm* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4115. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4116. {
  4117. checkRecursionDepth (recursionDepth);
  4118. EvaluationVisitor visitor (right, recursionDepth + 1);
  4119. scope.visitRelativeScope (getSymbol()->symbol, visitor);
  4120. return visitor.output;
  4121. }
  4122. Term* clone() const { return new DotOperator (getSymbol(), right); }
  4123. const String getName() const { return "."; }
  4124. int getOperatorPrecedence() const { return 1; }
  4125. void writeOperator (String& dest) const { dest << '.'; }
  4126. double performFunction (double, double) const { return 0.0; }
  4127. void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth)
  4128. {
  4129. checkRecursionDepth (recursionDepth);
  4130. visitor.useSymbol (Symbol (scope.getScopeUID(), getSymbol()->symbol));
  4131. SymbolVisitingVisitor v (right, visitor, recursionDepth + 1);
  4132. try
  4133. {
  4134. scope.visitRelativeScope (getSymbol()->symbol, v);
  4135. }
  4136. catch (...) {}
  4137. }
  4138. void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int recursionDepth)
  4139. {
  4140. checkRecursionDepth (recursionDepth);
  4141. getSymbol()->renameSymbol (oldSymbol, newName, scope, recursionDepth);
  4142. SymbolRenamingVisitor visitor (right, oldSymbol, newName, recursionDepth + 1);
  4143. try
  4144. {
  4145. scope.visitRelativeScope (getSymbol()->symbol, visitor);
  4146. }
  4147. catch (...) {}
  4148. }
  4149. private:
  4150. class EvaluationVisitor : public Scope::Visitor
  4151. {
  4152. public:
  4153. EvaluationVisitor (const TermPtr& input_, const int recursionCount_)
  4154. : input (input_), output (input_), recursionCount (recursionCount_) {}
  4155. void visit (const Scope& scope) { output = input->resolve (scope, recursionCount); }
  4156. const TermPtr input;
  4157. TermPtr output;
  4158. const int recursionCount;
  4159. private:
  4160. JUCE_DECLARE_NON_COPYABLE (EvaluationVisitor);
  4161. };
  4162. class SymbolVisitingVisitor : public Scope::Visitor
  4163. {
  4164. public:
  4165. SymbolVisitingVisitor (const TermPtr& input_, SymbolVisitor& visitor_, const int recursionCount_)
  4166. : input (input_), visitor (visitor_), recursionCount (recursionCount_) {}
  4167. void visit (const Scope& scope) { input->visitAllSymbols (visitor, scope, recursionCount); }
  4168. private:
  4169. const TermPtr input;
  4170. SymbolVisitor& visitor;
  4171. const int recursionCount;
  4172. JUCE_DECLARE_NON_COPYABLE (SymbolVisitingVisitor);
  4173. };
  4174. class SymbolRenamingVisitor : public Scope::Visitor
  4175. {
  4176. public:
  4177. SymbolRenamingVisitor (const TermPtr& input_, const Expression::Symbol& symbol_, const String& newName_, const int recursionCount_)
  4178. : input (input_), symbol (symbol_), newName (newName_), recursionCount (recursionCount_) {}
  4179. void visit (const Scope& scope) { input->renameSymbol (symbol, newName, scope, recursionCount); }
  4180. private:
  4181. const TermPtr input;
  4182. const Symbol& symbol;
  4183. const String newName;
  4184. const int recursionCount;
  4185. JUCE_DECLARE_NON_COPYABLE (SymbolRenamingVisitor);
  4186. };
  4187. SymbolTerm* getSymbol() const { return static_cast <SymbolTerm*> (left.getObject()); }
  4188. JUCE_DECLARE_NON_COPYABLE (DotOperator);
  4189. };
  4190. class Negate : public Term
  4191. {
  4192. public:
  4193. explicit Negate (const TermPtr& input_) : input (input_)
  4194. {
  4195. jassert (input_ != 0);
  4196. }
  4197. Type getType() const throw() { return operatorType; }
  4198. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  4199. int getNumInputs() const { return 1; }
  4200. Term* getInput (int index) const { return index == 0 ? input.getObject() : 0; }
  4201. Term* clone() const { return new Negate (input->clone()); }
  4202. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4203. {
  4204. return new Constant (-input->resolve (scope, recursionDepth)->toDouble(), false);
  4205. }
  4206. const String getName() const { return "-"; }
  4207. const TermPtr negated() { return input; }
  4208. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input_, double overallTarget, Term* topLevelTerm) const
  4209. {
  4210. (void) input_;
  4211. jassert (input_ == input);
  4212. const Term* const dest = findDestinationFor (topLevelTerm, this);
  4213. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  4214. : dest->createTermToEvaluateInput (scope, this, overallTarget, topLevelTerm));
  4215. }
  4216. const String toString() const
  4217. {
  4218. if (input->getOperatorPrecedence() > 0)
  4219. return "-(" + input->toString() + ")";
  4220. else
  4221. return "-" + input->toString();
  4222. }
  4223. private:
  4224. const TermPtr input;
  4225. };
  4226. class Add : public BinaryTerm
  4227. {
  4228. public:
  4229. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4230. Term* clone() const { return new Add (left->clone(), right->clone()); }
  4231. double performFunction (double lhs, double rhs) const { return lhs + rhs; }
  4232. int getOperatorPrecedence() const { return 3; }
  4233. const String getName() const { return "+"; }
  4234. void writeOperator (String& dest) const { dest << " + "; }
  4235. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4236. {
  4237. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4238. if (newDest == 0)
  4239. return 0;
  4240. return new Subtract (newDest, (input == left ? right : left)->clone());
  4241. }
  4242. private:
  4243. JUCE_DECLARE_NON_COPYABLE (Add);
  4244. };
  4245. class Subtract : public BinaryTerm
  4246. {
  4247. public:
  4248. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4249. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  4250. double performFunction (double lhs, double rhs) const { return lhs - rhs; }
  4251. int getOperatorPrecedence() const { return 3; }
  4252. const String getName() const { return "-"; }
  4253. void writeOperator (String& dest) const { dest << " - "; }
  4254. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4255. {
  4256. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4257. if (newDest == 0)
  4258. return 0;
  4259. if (input == left)
  4260. return new Add (newDest, right->clone());
  4261. else
  4262. return new Subtract (left->clone(), newDest);
  4263. }
  4264. private:
  4265. JUCE_DECLARE_NON_COPYABLE (Subtract);
  4266. };
  4267. class Multiply : public BinaryTerm
  4268. {
  4269. public:
  4270. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4271. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  4272. double performFunction (double lhs, double rhs) const { return lhs * rhs; }
  4273. const String getName() const { return "*"; }
  4274. void writeOperator (String& dest) const { dest << " * "; }
  4275. int getOperatorPrecedence() const { return 2; }
  4276. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4277. {
  4278. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4279. if (newDest == 0)
  4280. return 0;
  4281. return new Divide (newDest, (input == left ? right : left)->clone());
  4282. }
  4283. private:
  4284. JUCE_DECLARE_NON_COPYABLE (Multiply);
  4285. };
  4286. class Divide : public BinaryTerm
  4287. {
  4288. public:
  4289. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4290. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  4291. double performFunction (double lhs, double rhs) const { return lhs / rhs; }
  4292. const String getName() const { return "/"; }
  4293. void writeOperator (String& dest) const { dest << " / "; }
  4294. int getOperatorPrecedence() const { return 2; }
  4295. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4296. {
  4297. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4298. if (newDest == 0)
  4299. return 0;
  4300. if (input == left)
  4301. return new Multiply (newDest, right->clone());
  4302. else
  4303. return new Divide (left->clone(), newDest);
  4304. }
  4305. private:
  4306. JUCE_DECLARE_NON_COPYABLE (Divide);
  4307. };
  4308. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  4309. {
  4310. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  4311. if (inputIndex >= 0)
  4312. return topLevel;
  4313. for (int i = topLevel->getNumInputs(); --i >= 0;)
  4314. {
  4315. Term* const t = findDestinationFor (topLevel->getInput (i), inputTerm);
  4316. if (t != 0)
  4317. return t;
  4318. }
  4319. return 0;
  4320. }
  4321. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  4322. {
  4323. {
  4324. Constant* const c = dynamic_cast<Constant*> (term);
  4325. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4326. return c;
  4327. }
  4328. if (dynamic_cast<Function*> (term) != 0)
  4329. return 0;
  4330. int i;
  4331. const int numIns = term->getNumInputs();
  4332. for (i = 0; i < numIns; ++i)
  4333. {
  4334. Constant* const c = dynamic_cast<Constant*> (term->getInput (i));
  4335. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4336. return c;
  4337. }
  4338. for (i = 0; i < numIns; ++i)
  4339. {
  4340. Constant* const c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  4341. if (c != 0)
  4342. return c;
  4343. }
  4344. return 0;
  4345. }
  4346. static bool containsAnySymbols (const Term* const t)
  4347. {
  4348. if (t->getType() == Expression::symbolType)
  4349. return true;
  4350. for (int i = t->getNumInputs(); --i >= 0;)
  4351. if (containsAnySymbols (t->getInput (i)))
  4352. return true;
  4353. return false;
  4354. }
  4355. class SymbolCheckVisitor : public Term::SymbolVisitor
  4356. {
  4357. public:
  4358. SymbolCheckVisitor (const Symbol& symbol_) : wasFound (false), symbol (symbol_) {}
  4359. void useSymbol (const Symbol& s) { wasFound = wasFound || s == symbol; }
  4360. bool wasFound;
  4361. private:
  4362. const Symbol& symbol;
  4363. JUCE_DECLARE_NON_COPYABLE (SymbolCheckVisitor);
  4364. };
  4365. class SymbolListVisitor : public Term::SymbolVisitor
  4366. {
  4367. public:
  4368. SymbolListVisitor (Array<Symbol>& list_) : list (list_) {}
  4369. void useSymbol (const Symbol& s) { list.addIfNotAlreadyThere (s); }
  4370. private:
  4371. Array<Symbol>& list;
  4372. JUCE_DECLARE_NON_COPYABLE (SymbolListVisitor);
  4373. };
  4374. class Parser
  4375. {
  4376. public:
  4377. Parser (String::CharPointerType& stringToParse)
  4378. : text (stringToParse)
  4379. {
  4380. }
  4381. const TermPtr readUpToComma()
  4382. {
  4383. if (text.isEmpty())
  4384. return new Constant (0.0, false);
  4385. const TermPtr e (readExpression());
  4386. if (e == 0 || ((! readOperator (",")) && ! text.isEmpty()))
  4387. throw ParseError ("Syntax error: \"" + String (text) + "\"");
  4388. return e;
  4389. }
  4390. private:
  4391. String::CharPointerType& text;
  4392. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4393. {
  4394. return c >= '0' && c <= '9';
  4395. }
  4396. bool readChar (const juce_wchar required) throw()
  4397. {
  4398. if (*text == required)
  4399. {
  4400. ++text;
  4401. return true;
  4402. }
  4403. return false;
  4404. }
  4405. bool readOperator (const char* ops, char* const opType = 0) throw()
  4406. {
  4407. text = text.findEndOfWhitespace();
  4408. while (*ops != 0)
  4409. {
  4410. if (readChar (*ops))
  4411. {
  4412. if (opType != 0)
  4413. *opType = *ops;
  4414. return true;
  4415. }
  4416. ++ops;
  4417. }
  4418. return false;
  4419. }
  4420. bool readIdentifier (String& identifier) throw()
  4421. {
  4422. text = text.findEndOfWhitespace();
  4423. String::CharPointerType t (text);
  4424. int numChars = 0;
  4425. if (t.isLetter() || *t == '_')
  4426. {
  4427. ++t;
  4428. ++numChars;
  4429. while (t.isLetterOrDigit() || *t == '_')
  4430. {
  4431. ++t;
  4432. ++numChars;
  4433. }
  4434. }
  4435. if (numChars > 0)
  4436. {
  4437. identifier = String (text, numChars);
  4438. text = t;
  4439. return true;
  4440. }
  4441. return false;
  4442. }
  4443. Term* readNumber() throw()
  4444. {
  4445. text = text.findEndOfWhitespace();
  4446. String::CharPointerType t (text);
  4447. const bool isResolutionTarget = (*t == '@');
  4448. if (isResolutionTarget)
  4449. {
  4450. ++t;
  4451. t = t.findEndOfWhitespace();
  4452. text = t;
  4453. }
  4454. if (*t == '-')
  4455. {
  4456. ++t;
  4457. t = t.findEndOfWhitespace();
  4458. }
  4459. if (isDecimalDigit (*t) || (*t == '.' && isDecimalDigit (t[1])))
  4460. return new Constant (CharacterFunctions::readDoubleValue (text), isResolutionTarget);
  4461. return 0;
  4462. }
  4463. const TermPtr readExpression()
  4464. {
  4465. TermPtr lhs (readMultiplyOrDivideExpression());
  4466. char opType;
  4467. while (lhs != 0 && readOperator ("+-", &opType))
  4468. {
  4469. TermPtr rhs (readMultiplyOrDivideExpression());
  4470. if (rhs == 0)
  4471. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4472. if (opType == '+')
  4473. lhs = new Add (lhs, rhs);
  4474. else
  4475. lhs = new Subtract (lhs, rhs);
  4476. }
  4477. return lhs;
  4478. }
  4479. const TermPtr readMultiplyOrDivideExpression()
  4480. {
  4481. TermPtr lhs (readUnaryExpression());
  4482. char opType;
  4483. while (lhs != 0 && readOperator ("*/", &opType))
  4484. {
  4485. TermPtr rhs (readUnaryExpression());
  4486. if (rhs == 0)
  4487. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4488. if (opType == '*')
  4489. lhs = new Multiply (lhs, rhs);
  4490. else
  4491. lhs = new Divide (lhs, rhs);
  4492. }
  4493. return lhs;
  4494. }
  4495. const TermPtr readUnaryExpression()
  4496. {
  4497. char opType;
  4498. if (readOperator ("+-", &opType))
  4499. {
  4500. TermPtr term (readUnaryExpression());
  4501. if (term == 0)
  4502. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4503. if (opType == '-')
  4504. term = term->negated();
  4505. return term;
  4506. }
  4507. return readPrimaryExpression();
  4508. }
  4509. const TermPtr readPrimaryExpression()
  4510. {
  4511. TermPtr e (readParenthesisedExpression());
  4512. if (e != 0)
  4513. return e;
  4514. e = readNumber();
  4515. if (e != 0)
  4516. return e;
  4517. return readSymbolOrFunction();
  4518. }
  4519. const TermPtr readSymbolOrFunction()
  4520. {
  4521. String identifier;
  4522. if (readIdentifier (identifier))
  4523. {
  4524. if (readOperator ("(")) // method call...
  4525. {
  4526. Function* const f = new Function (identifier);
  4527. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4528. TermPtr param (readExpression());
  4529. if (param == 0)
  4530. {
  4531. if (readOperator (")"))
  4532. return func.release();
  4533. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4534. }
  4535. f->parameters.add (Expression (param));
  4536. while (readOperator (","))
  4537. {
  4538. param = readExpression();
  4539. if (param == 0)
  4540. throw ParseError ("Expected expression after \",\"");
  4541. f->parameters.add (Expression (param));
  4542. }
  4543. if (readOperator (")"))
  4544. return func.release();
  4545. throw ParseError ("Expected \")\"");
  4546. }
  4547. else if (readOperator ("."))
  4548. {
  4549. TermPtr rhs (readSymbolOrFunction());
  4550. if (rhs == 0)
  4551. throw ParseError ("Expected symbol or function after \".\"");
  4552. if (identifier == "this")
  4553. return rhs;
  4554. return new DotOperator (new SymbolTerm (identifier), rhs);
  4555. }
  4556. else // just a symbol..
  4557. {
  4558. jassert (identifier.trim() == identifier);
  4559. return new SymbolTerm (identifier);
  4560. }
  4561. }
  4562. return 0;
  4563. }
  4564. const TermPtr readParenthesisedExpression()
  4565. {
  4566. if (! readOperator ("("))
  4567. return 0;
  4568. const TermPtr e (readExpression());
  4569. if (e == 0 || ! readOperator (")"))
  4570. return 0;
  4571. return e;
  4572. }
  4573. JUCE_DECLARE_NON_COPYABLE (Parser);
  4574. };
  4575. };
  4576. Expression::Expression()
  4577. : term (new Expression::Helpers::Constant (0, false))
  4578. {
  4579. }
  4580. Expression::~Expression()
  4581. {
  4582. }
  4583. Expression::Expression (Term* const term_)
  4584. : term (term_)
  4585. {
  4586. jassert (term != 0);
  4587. }
  4588. Expression::Expression (const double constant)
  4589. : term (new Expression::Helpers::Constant (constant, false))
  4590. {
  4591. }
  4592. Expression::Expression (const Expression& other)
  4593. : term (other.term)
  4594. {
  4595. }
  4596. Expression& Expression::operator= (const Expression& other)
  4597. {
  4598. term = other.term;
  4599. return *this;
  4600. }
  4601. Expression::Expression (const String& stringToParse)
  4602. {
  4603. String::CharPointerType text (stringToParse.getCharPointer());
  4604. Helpers::Parser parser (text);
  4605. term = parser.readUpToComma();
  4606. }
  4607. const Expression Expression::parse (String::CharPointerType& stringToParse)
  4608. {
  4609. Helpers::Parser parser (stringToParse);
  4610. return Expression (parser.readUpToComma());
  4611. }
  4612. double Expression::evaluate() const
  4613. {
  4614. return evaluate (Expression::Scope());
  4615. }
  4616. double Expression::evaluate (const Expression::Scope& scope) const
  4617. {
  4618. try
  4619. {
  4620. return term->resolve (scope, 0)->toDouble();
  4621. }
  4622. catch (Helpers::EvaluationError&)
  4623. {}
  4624. return 0;
  4625. }
  4626. double Expression::evaluate (const Scope& scope, String& evaluationError) const
  4627. {
  4628. try
  4629. {
  4630. return term->resolve (scope, 0)->toDouble();
  4631. }
  4632. catch (Helpers::EvaluationError& e)
  4633. {
  4634. evaluationError = e.description;
  4635. }
  4636. return 0;
  4637. }
  4638. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4639. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4640. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4641. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4642. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4643. const Expression Expression::symbol (const String& symbol) { return Expression (new Helpers::SymbolTerm (symbol)); }
  4644. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4645. {
  4646. return Expression (new Helpers::Function (functionName, parameters));
  4647. }
  4648. const Expression Expression::adjustedToGiveNewResult (const double targetValue, const Expression::Scope& scope) const
  4649. {
  4650. ScopedPointer<Term> newTerm (term->clone());
  4651. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4652. if (termToAdjust == 0)
  4653. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4654. if (termToAdjust == 0)
  4655. {
  4656. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4657. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4658. }
  4659. jassert (termToAdjust != 0);
  4660. const Term* const parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4661. if (parent == 0)
  4662. {
  4663. termToAdjust->value = targetValue;
  4664. }
  4665. else
  4666. {
  4667. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (scope, termToAdjust, targetValue, newTerm));
  4668. if (reverseTerm == 0)
  4669. return Expression (targetValue);
  4670. termToAdjust->value = reverseTerm->resolve (scope, 0)->toDouble();
  4671. }
  4672. return Expression (newTerm.release());
  4673. }
  4674. const Expression Expression::withRenamedSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Scope& scope) const
  4675. {
  4676. jassert (newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4677. if (oldSymbol.symbolName == newName)
  4678. return *this;
  4679. Expression e (term->clone());
  4680. e.term->renameSymbol (oldSymbol, newName, scope, 0);
  4681. return e;
  4682. }
  4683. bool Expression::referencesSymbol (const Expression::Symbol& symbol, const Scope& scope) const
  4684. {
  4685. Helpers::SymbolCheckVisitor visitor (symbol);
  4686. try
  4687. {
  4688. term->visitAllSymbols (visitor, scope, 0);
  4689. }
  4690. catch (Helpers::EvaluationError&)
  4691. {}
  4692. return visitor.wasFound;
  4693. }
  4694. void Expression::findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const
  4695. {
  4696. try
  4697. {
  4698. Helpers::SymbolListVisitor visitor (results);
  4699. term->visitAllSymbols (visitor, scope, 0);
  4700. }
  4701. catch (Helpers::EvaluationError&)
  4702. {}
  4703. }
  4704. const String Expression::toString() const { return term->toString(); }
  4705. bool Expression::usesAnySymbols() const { return Helpers::containsAnySymbols (term); }
  4706. Expression::Type Expression::getType() const throw() { return term->getType(); }
  4707. const String Expression::getSymbolOrFunction() const { return term->getName(); }
  4708. int Expression::getNumInputs() const { return term->getNumInputs(); }
  4709. const Expression Expression::getInput (int index) const { return Expression (term->getInput (index)); }
  4710. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4711. {
  4712. return new Helpers::Negate (this);
  4713. }
  4714. Expression::ParseError::ParseError (const String& message)
  4715. : description (message)
  4716. {
  4717. DBG ("Expression::ParseError: " + message);
  4718. }
  4719. Expression::Symbol::Symbol (const String& scopeUID_, const String& symbolName_)
  4720. : scopeUID (scopeUID_), symbolName (symbolName_)
  4721. {
  4722. }
  4723. bool Expression::Symbol::operator== (const Symbol& other) const throw()
  4724. {
  4725. return symbolName == other.symbolName && scopeUID == other.scopeUID;
  4726. }
  4727. bool Expression::Symbol::operator!= (const Symbol& other) const throw()
  4728. {
  4729. return ! operator== (other);
  4730. }
  4731. Expression::Scope::Scope() {}
  4732. Expression::Scope::~Scope() {}
  4733. const Expression Expression::Scope::getSymbolValue (const String& symbol) const
  4734. {
  4735. throw Helpers::EvaluationError ("Unknown symbol: " + symbol);
  4736. }
  4737. double Expression::Scope::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4738. {
  4739. if (numParams > 0)
  4740. {
  4741. if (functionName == "min")
  4742. {
  4743. double v = parameters[0];
  4744. for (int i = 1; i < numParams; ++i)
  4745. v = jmin (v, parameters[i]);
  4746. return v;
  4747. }
  4748. else if (functionName == "max")
  4749. {
  4750. double v = parameters[0];
  4751. for (int i = 1; i < numParams; ++i)
  4752. v = jmax (v, parameters[i]);
  4753. return v;
  4754. }
  4755. else if (numParams == 1)
  4756. {
  4757. if (functionName == "sin") return sin (parameters[0]);
  4758. else if (functionName == "cos") return cos (parameters[0]);
  4759. else if (functionName == "tan") return tan (parameters[0]);
  4760. else if (functionName == "abs") return std::abs (parameters[0]);
  4761. }
  4762. }
  4763. throw Helpers::EvaluationError ("Unknown function: \"" + functionName + "\"");
  4764. }
  4765. void Expression::Scope::visitRelativeScope (const String& scopeName, Visitor&) const
  4766. {
  4767. throw Helpers::EvaluationError ("Unknown symbol: " + scopeName);
  4768. }
  4769. const String Expression::Scope::getScopeUID() const
  4770. {
  4771. return String::empty;
  4772. }
  4773. END_JUCE_NAMESPACE
  4774. /*** End of inlined file: juce_Expression.cpp ***/
  4775. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4776. BEGIN_JUCE_NAMESPACE
  4777. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4778. {
  4779. jassert (keyData != 0);
  4780. jassert (keyBytes > 0);
  4781. static const uint32 initialPValues [18] =
  4782. {
  4783. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4784. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4785. 0x9216d5d9, 0x8979fb1b
  4786. };
  4787. static const uint32 initialSValues [4 * 256] =
  4788. {
  4789. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4790. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4791. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4792. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4793. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4794. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4795. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4796. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4797. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4798. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4799. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4800. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4801. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4802. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4803. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4804. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4805. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4806. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4807. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4808. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4809. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4810. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4811. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4812. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4813. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4814. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4815. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4816. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4817. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4818. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4819. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4820. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4821. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4822. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4823. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4824. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4825. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4826. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4827. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4828. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4829. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4830. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4831. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4832. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4833. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4834. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4835. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4836. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4837. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4838. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4839. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4840. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4841. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4842. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4843. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4844. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4845. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4846. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4847. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4848. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4849. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4850. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4851. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4852. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4853. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4854. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4855. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4856. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4857. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4858. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4859. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4860. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4861. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4862. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4863. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4864. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4865. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4866. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4867. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4868. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4869. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4870. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4871. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4872. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4873. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4874. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4875. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4876. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4877. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4878. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4879. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4880. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4881. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4882. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4883. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4884. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4885. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4886. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4887. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4888. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4889. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4890. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4891. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4892. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4893. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4894. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4895. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4896. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4897. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4898. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4899. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4900. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4901. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4902. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4903. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4904. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4905. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4906. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4907. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4908. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4909. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4910. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4911. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4912. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4913. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4914. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4915. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4916. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4917. };
  4918. memcpy (p, initialPValues, sizeof (p));
  4919. int i, j = 0;
  4920. for (i = 4; --i >= 0;)
  4921. {
  4922. s[i].malloc (256);
  4923. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4924. }
  4925. for (i = 0; i < 18; ++i)
  4926. {
  4927. uint32 d = 0;
  4928. for (int k = 0; k < 4; ++k)
  4929. {
  4930. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4931. if (++j >= keyBytes)
  4932. j = 0;
  4933. }
  4934. p[i] = initialPValues[i] ^ d;
  4935. }
  4936. uint32 l = 0, r = 0;
  4937. for (i = 0; i < 18; i += 2)
  4938. {
  4939. encrypt (l, r);
  4940. p[i] = l;
  4941. p[i + 1] = r;
  4942. }
  4943. for (i = 0; i < 4; ++i)
  4944. {
  4945. for (j = 0; j < 256; j += 2)
  4946. {
  4947. encrypt (l, r);
  4948. s[i][j] = l;
  4949. s[i][j + 1] = r;
  4950. }
  4951. }
  4952. }
  4953. BlowFish::BlowFish (const BlowFish& other)
  4954. {
  4955. for (int i = 4; --i >= 0;)
  4956. s[i].malloc (256);
  4957. operator= (other);
  4958. }
  4959. BlowFish& BlowFish::operator= (const BlowFish& other)
  4960. {
  4961. memcpy (p, other.p, sizeof (p));
  4962. for (int i = 4; --i >= 0;)
  4963. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  4964. return *this;
  4965. }
  4966. BlowFish::~BlowFish()
  4967. {
  4968. }
  4969. uint32 BlowFish::F (const uint32 x) const throw()
  4970. {
  4971. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  4972. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  4973. }
  4974. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  4975. {
  4976. uint32 l = data1;
  4977. uint32 r = data2;
  4978. for (int i = 0; i < 16; ++i)
  4979. {
  4980. l ^= p[i];
  4981. r ^= F(l);
  4982. swapVariables (l, r);
  4983. }
  4984. data1 = r ^ p[17];
  4985. data2 = l ^ p[16];
  4986. }
  4987. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  4988. {
  4989. uint32 l = data1;
  4990. uint32 r = data2;
  4991. for (int i = 17; i > 1; --i)
  4992. {
  4993. l ^= p[i];
  4994. r ^= F(l);
  4995. swapVariables (l, r);
  4996. }
  4997. data1 = r ^ p[0];
  4998. data2 = l ^ p[1];
  4999. }
  5000. END_JUCE_NAMESPACE
  5001. /*** End of inlined file: juce_BlowFish.cpp ***/
  5002. /*** Start of inlined file: juce_MD5.cpp ***/
  5003. BEGIN_JUCE_NAMESPACE
  5004. MD5::MD5()
  5005. {
  5006. zerostruct (result);
  5007. }
  5008. MD5::MD5 (const MD5& other)
  5009. {
  5010. memcpy (result, other.result, sizeof (result));
  5011. }
  5012. MD5& MD5::operator= (const MD5& other)
  5013. {
  5014. memcpy (result, other.result, sizeof (result));
  5015. return *this;
  5016. }
  5017. MD5::MD5 (const MemoryBlock& data)
  5018. {
  5019. ProcessContext context;
  5020. context.processBlock (data.getData(), data.getSize());
  5021. context.finish (result);
  5022. }
  5023. MD5::MD5 (const void* data, const size_t numBytes)
  5024. {
  5025. ProcessContext context;
  5026. context.processBlock (data, numBytes);
  5027. context.finish (result);
  5028. }
  5029. MD5::MD5 (const String& text)
  5030. {
  5031. ProcessContext context;
  5032. String::CharPointerType t (text.getCharPointer());
  5033. while (! t.isEmpty())
  5034. {
  5035. // force the string into integer-sized unicode characters, to try to make it
  5036. // get the same results on all platforms + compilers.
  5037. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t.getAndAdvance());
  5038. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  5039. }
  5040. context.finish (result);
  5041. }
  5042. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  5043. {
  5044. ProcessContext context;
  5045. if (numBytesToRead < 0)
  5046. numBytesToRead = std::numeric_limits<int64>::max();
  5047. while (numBytesToRead > 0)
  5048. {
  5049. uint8 tempBuffer [512];
  5050. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  5051. if (bytesRead <= 0)
  5052. break;
  5053. numBytesToRead -= bytesRead;
  5054. context.processBlock (tempBuffer, bytesRead);
  5055. }
  5056. context.finish (result);
  5057. }
  5058. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  5059. {
  5060. processStream (input, numBytesToRead);
  5061. }
  5062. MD5::MD5 (const File& file)
  5063. {
  5064. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  5065. if (fin != 0)
  5066. processStream (*fin, -1);
  5067. else
  5068. zerostruct (result);
  5069. }
  5070. MD5::~MD5()
  5071. {
  5072. }
  5073. namespace MD5Functions
  5074. {
  5075. void encode (void* const output, const void* const input, const int numBytes) throw()
  5076. {
  5077. for (int i = 0; i < (numBytes >> 2); ++i)
  5078. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  5079. }
  5080. inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  5081. inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  5082. inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  5083. inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  5084. inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  5085. void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5086. {
  5087. a += F (b, c, d) + x + ac;
  5088. a = rotateLeft (a, s) + b;
  5089. }
  5090. void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5091. {
  5092. a += G (b, c, d) + x + ac;
  5093. a = rotateLeft (a, s) + b;
  5094. }
  5095. void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5096. {
  5097. a += H (b, c, d) + x + ac;
  5098. a = rotateLeft (a, s) + b;
  5099. }
  5100. void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5101. {
  5102. a += I (b, c, d) + x + ac;
  5103. a = rotateLeft (a, s) + b;
  5104. }
  5105. }
  5106. MD5::ProcessContext::ProcessContext()
  5107. {
  5108. state[0] = 0x67452301;
  5109. state[1] = 0xefcdab89;
  5110. state[2] = 0x98badcfe;
  5111. state[3] = 0x10325476;
  5112. count[0] = 0;
  5113. count[1] = 0;
  5114. }
  5115. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  5116. {
  5117. int bufferPos = ((count[0] >> 3) & 0x3F);
  5118. count[0] += (uint32) (dataSize << 3);
  5119. if (count[0] < ((uint32) dataSize << 3))
  5120. count[1]++;
  5121. count[1] += (uint32) (dataSize >> 29);
  5122. const size_t spaceLeft = 64 - bufferPos;
  5123. size_t i = 0;
  5124. if (dataSize >= spaceLeft)
  5125. {
  5126. memcpy (buffer + bufferPos, data, spaceLeft);
  5127. transform (buffer);
  5128. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  5129. transform (static_cast <const char*> (data) + i);
  5130. bufferPos = 0;
  5131. }
  5132. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  5133. }
  5134. void MD5::ProcessContext::finish (void* const result)
  5135. {
  5136. unsigned char encodedLength[8];
  5137. MD5Functions::encode (encodedLength, count, 8);
  5138. // Pad out to 56 mod 64.
  5139. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  5140. const int paddingLength = (index < 56) ? (56 - index)
  5141. : (120 - index);
  5142. uint8 paddingBuffer [64];
  5143. zeromem (paddingBuffer, paddingLength);
  5144. paddingBuffer [0] = 0x80;
  5145. processBlock (paddingBuffer, paddingLength);
  5146. processBlock (encodedLength, 8);
  5147. MD5Functions::encode (result, state, 16);
  5148. zerostruct (buffer);
  5149. }
  5150. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  5151. {
  5152. using namespace MD5Functions;
  5153. uint32 a = state[0];
  5154. uint32 b = state[1];
  5155. uint32 c = state[2];
  5156. uint32 d = state[3];
  5157. uint32 x[16];
  5158. encode (x, bufferToTransform, 64);
  5159. enum Constants
  5160. {
  5161. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  5162. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  5163. };
  5164. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  5165. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  5166. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  5167. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  5168. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  5169. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  5170. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  5171. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  5172. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  5173. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  5174. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  5175. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  5176. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  5177. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  5178. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  5179. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  5180. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  5181. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  5182. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  5183. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  5184. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  5185. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  5186. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  5187. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  5188. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  5189. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  5190. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  5191. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  5192. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  5193. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  5194. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  5195. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  5196. state[0] += a;
  5197. state[1] += b;
  5198. state[2] += c;
  5199. state[3] += d;
  5200. zerostruct (x);
  5201. }
  5202. const MemoryBlock MD5::getRawChecksumData() const
  5203. {
  5204. return MemoryBlock (result, sizeof (result));
  5205. }
  5206. const String MD5::toHexString() const
  5207. {
  5208. return String::toHexString (result, sizeof (result), 0);
  5209. }
  5210. bool MD5::operator== (const MD5& other) const
  5211. {
  5212. return memcmp (result, other.result, sizeof (result)) == 0;
  5213. }
  5214. bool MD5::operator!= (const MD5& other) const
  5215. {
  5216. return ! operator== (other);
  5217. }
  5218. END_JUCE_NAMESPACE
  5219. /*** End of inlined file: juce_MD5.cpp ***/
  5220. /*** Start of inlined file: juce_Primes.cpp ***/
  5221. BEGIN_JUCE_NAMESPACE
  5222. namespace PrimesHelpers
  5223. {
  5224. void createSmallSieve (const int numBits, BigInteger& result)
  5225. {
  5226. result.setBit (numBits);
  5227. result.clearBit (numBits); // to enlarge the array
  5228. result.setBit (0);
  5229. int n = 2;
  5230. do
  5231. {
  5232. for (int i = n + n; i < numBits; i += n)
  5233. result.setBit (i);
  5234. n = result.findNextClearBit (n + 1);
  5235. }
  5236. while (n <= (numBits >> 1));
  5237. }
  5238. void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  5239. const BigInteger& smallSieve, const int smallSieveSize)
  5240. {
  5241. jassert (! base[0]); // must be even!
  5242. result.setBit (numBits);
  5243. result.clearBit (numBits); // to enlarge the array
  5244. int index = smallSieve.findNextClearBit (0);
  5245. do
  5246. {
  5247. const int prime = (index << 1) + 1;
  5248. BigInteger r (base), remainder;
  5249. r.divideBy (prime, remainder);
  5250. int i = prime - remainder.getBitRangeAsInt (0, 32);
  5251. if (r.isZero())
  5252. i += prime;
  5253. if ((i & 1) == 0)
  5254. i += prime;
  5255. i = (i - 1) >> 1;
  5256. while (i < numBits)
  5257. {
  5258. result.setBit (i);
  5259. i += prime;
  5260. }
  5261. index = smallSieve.findNextClearBit (index + 1);
  5262. }
  5263. while (index < smallSieveSize);
  5264. }
  5265. bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  5266. const int numBits, BigInteger& result, const int certainty)
  5267. {
  5268. for (int i = 0; i < numBits; ++i)
  5269. {
  5270. if (! sieve[i])
  5271. {
  5272. result = base + (unsigned int) ((i << 1) + 1);
  5273. if (Primes::isProbablyPrime (result, certainty))
  5274. return true;
  5275. }
  5276. }
  5277. return false;
  5278. }
  5279. bool passesMillerRabin (const BigInteger& n, int iterations)
  5280. {
  5281. const BigInteger one (1), two (2);
  5282. const BigInteger nMinusOne (n - one);
  5283. BigInteger d (nMinusOne);
  5284. const int s = d.findNextSetBit (0);
  5285. d >>= s;
  5286. BigInteger smallPrimes;
  5287. int numBitsInSmallPrimes = 0;
  5288. for (;;)
  5289. {
  5290. numBitsInSmallPrimes += 256;
  5291. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  5292. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  5293. if (numPrimesFound > iterations + 1)
  5294. break;
  5295. }
  5296. int smallPrime = 2;
  5297. while (--iterations >= 0)
  5298. {
  5299. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  5300. BigInteger r (smallPrime);
  5301. r.exponentModulo (d, n);
  5302. if (r != one && r != nMinusOne)
  5303. {
  5304. for (int j = 0; j < s; ++j)
  5305. {
  5306. r.exponentModulo (two, n);
  5307. if (r == nMinusOne)
  5308. break;
  5309. }
  5310. if (r != nMinusOne)
  5311. return false;
  5312. }
  5313. }
  5314. return true;
  5315. }
  5316. }
  5317. const BigInteger Primes::createProbablePrime (const int bitLength,
  5318. const int certainty,
  5319. const int* randomSeeds,
  5320. int numRandomSeeds)
  5321. {
  5322. using namespace PrimesHelpers;
  5323. int defaultSeeds [16];
  5324. if (numRandomSeeds <= 0)
  5325. {
  5326. randomSeeds = defaultSeeds;
  5327. numRandomSeeds = numElementsInArray (defaultSeeds);
  5328. Random r (0);
  5329. for (int j = 10; --j >= 0;)
  5330. {
  5331. r.setSeedRandomly();
  5332. for (int i = numRandomSeeds; --i >= 0;)
  5333. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5334. }
  5335. }
  5336. BigInteger smallSieve;
  5337. const int smallSieveSize = 15000;
  5338. createSmallSieve (smallSieveSize, smallSieve);
  5339. BigInteger p;
  5340. for (int i = numRandomSeeds; --i >= 0;)
  5341. {
  5342. BigInteger p2;
  5343. Random r (randomSeeds[i]);
  5344. r.fillBitsRandomly (p2, 0, bitLength);
  5345. p ^= p2;
  5346. }
  5347. p.setBit (bitLength - 1);
  5348. p.clearBit (0);
  5349. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5350. while (p.getHighestBit() < bitLength)
  5351. {
  5352. p += 2 * searchLen;
  5353. BigInteger sieve;
  5354. bigSieve (p, searchLen, sieve,
  5355. smallSieve, smallSieveSize);
  5356. BigInteger candidate;
  5357. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5358. return candidate;
  5359. }
  5360. jassertfalse;
  5361. return BigInteger();
  5362. }
  5363. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5364. {
  5365. using namespace PrimesHelpers;
  5366. if (! number[0])
  5367. return false;
  5368. if (number.getHighestBit() <= 10)
  5369. {
  5370. const int num = number.getBitRangeAsInt (0, 10);
  5371. for (int i = num / 2; --i > 1;)
  5372. if (num % i == 0)
  5373. return false;
  5374. return true;
  5375. }
  5376. else
  5377. {
  5378. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5379. return false;
  5380. return passesMillerRabin (number, certainty);
  5381. }
  5382. }
  5383. END_JUCE_NAMESPACE
  5384. /*** End of inlined file: juce_Primes.cpp ***/
  5385. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5386. BEGIN_JUCE_NAMESPACE
  5387. RSAKey::RSAKey()
  5388. {
  5389. }
  5390. RSAKey::RSAKey (const String& s)
  5391. {
  5392. if (s.containsChar (','))
  5393. {
  5394. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5395. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5396. }
  5397. else
  5398. {
  5399. // the string needs to be two hex numbers, comma-separated..
  5400. jassertfalse;
  5401. }
  5402. }
  5403. RSAKey::~RSAKey()
  5404. {
  5405. }
  5406. bool RSAKey::operator== (const RSAKey& other) const throw()
  5407. {
  5408. return part1 == other.part1 && part2 == other.part2;
  5409. }
  5410. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5411. {
  5412. return ! operator== (other);
  5413. }
  5414. const String RSAKey::toString() const
  5415. {
  5416. return part1.toString (16) + "," + part2.toString (16);
  5417. }
  5418. bool RSAKey::applyToValue (BigInteger& value) const
  5419. {
  5420. if (part1.isZero() || part2.isZero() || value <= 0)
  5421. {
  5422. jassertfalse; // using an uninitialised key
  5423. value.clear();
  5424. return false;
  5425. }
  5426. BigInteger result;
  5427. while (! value.isZero())
  5428. {
  5429. result *= part2;
  5430. BigInteger remainder;
  5431. value.divideBy (part2, remainder);
  5432. remainder.exponentModulo (part1, part2);
  5433. result += remainder;
  5434. }
  5435. value.swapWith (result);
  5436. return true;
  5437. }
  5438. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5439. {
  5440. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5441. // are fast to divide + multiply
  5442. for (int i = 2; i <= 65536; i *= 2)
  5443. {
  5444. const BigInteger e (1 + i);
  5445. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5446. return e;
  5447. }
  5448. BigInteger e (4);
  5449. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5450. ++e;
  5451. return e;
  5452. }
  5453. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5454. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5455. {
  5456. jassert (numBits > 16); // not much point using less than this..
  5457. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5458. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5459. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5460. const BigInteger n (p * q);
  5461. const BigInteger m (--p * --q);
  5462. const BigInteger e (findBestCommonDivisor (p, q));
  5463. BigInteger d (e);
  5464. d.inverseModulo (m);
  5465. publicKey.part1 = e;
  5466. publicKey.part2 = n;
  5467. privateKey.part1 = d;
  5468. privateKey.part2 = n;
  5469. }
  5470. END_JUCE_NAMESPACE
  5471. /*** End of inlined file: juce_RSAKey.cpp ***/
  5472. /*** Start of inlined file: juce_InputStream.cpp ***/
  5473. BEGIN_JUCE_NAMESPACE
  5474. char InputStream::readByte()
  5475. {
  5476. char temp = 0;
  5477. read (&temp, 1);
  5478. return temp;
  5479. }
  5480. bool InputStream::readBool()
  5481. {
  5482. return readByte() != 0;
  5483. }
  5484. short InputStream::readShort()
  5485. {
  5486. char temp[2];
  5487. if (read (temp, 2) == 2)
  5488. return (short) ByteOrder::littleEndianShort (temp);
  5489. return 0;
  5490. }
  5491. short InputStream::readShortBigEndian()
  5492. {
  5493. char temp[2];
  5494. if (read (temp, 2) == 2)
  5495. return (short) ByteOrder::bigEndianShort (temp);
  5496. return 0;
  5497. }
  5498. int InputStream::readInt()
  5499. {
  5500. char temp[4];
  5501. if (read (temp, 4) == 4)
  5502. return (int) ByteOrder::littleEndianInt (temp);
  5503. return 0;
  5504. }
  5505. int InputStream::readIntBigEndian()
  5506. {
  5507. char temp[4];
  5508. if (read (temp, 4) == 4)
  5509. return (int) ByteOrder::bigEndianInt (temp);
  5510. return 0;
  5511. }
  5512. int InputStream::readCompressedInt()
  5513. {
  5514. const unsigned char sizeByte = readByte();
  5515. if (sizeByte == 0)
  5516. return 0;
  5517. const int numBytes = (sizeByte & 0x7f);
  5518. if (numBytes > 4)
  5519. {
  5520. jassertfalse; // trying to read corrupt data - this method must only be used
  5521. // to read data that was written by OutputStream::writeCompressedInt()
  5522. return 0;
  5523. }
  5524. char bytes[4] = { 0, 0, 0, 0 };
  5525. if (read (bytes, numBytes) != numBytes)
  5526. return 0;
  5527. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5528. return (sizeByte >> 7) ? -num : num;
  5529. }
  5530. int64 InputStream::readInt64()
  5531. {
  5532. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5533. if (read (n.asBytes, 8) == 8)
  5534. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5535. return 0;
  5536. }
  5537. int64 InputStream::readInt64BigEndian()
  5538. {
  5539. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5540. if (read (n.asBytes, 8) == 8)
  5541. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5542. return 0;
  5543. }
  5544. float InputStream::readFloat()
  5545. {
  5546. // the union below relies on these types being the same size...
  5547. static_jassert (sizeof (int32) == sizeof (float));
  5548. union { int32 asInt; float asFloat; } n;
  5549. n.asInt = (int32) readInt();
  5550. return n.asFloat;
  5551. }
  5552. float InputStream::readFloatBigEndian()
  5553. {
  5554. union { int32 asInt; float asFloat; } n;
  5555. n.asInt = (int32) readIntBigEndian();
  5556. return n.asFloat;
  5557. }
  5558. double InputStream::readDouble()
  5559. {
  5560. union { int64 asInt; double asDouble; } n;
  5561. n.asInt = readInt64();
  5562. return n.asDouble;
  5563. }
  5564. double InputStream::readDoubleBigEndian()
  5565. {
  5566. union { int64 asInt; double asDouble; } n;
  5567. n.asInt = readInt64BigEndian();
  5568. return n.asDouble;
  5569. }
  5570. const String InputStream::readString()
  5571. {
  5572. MemoryBlock buffer (256);
  5573. char* data = static_cast<char*> (buffer.getData());
  5574. size_t i = 0;
  5575. while ((data[i] = readByte()) != 0)
  5576. {
  5577. if (++i >= buffer.getSize())
  5578. {
  5579. buffer.setSize (buffer.getSize() + 512);
  5580. data = static_cast<char*> (buffer.getData());
  5581. }
  5582. }
  5583. return String::fromUTF8 (data, (int) i);
  5584. }
  5585. const String InputStream::readNextLine()
  5586. {
  5587. MemoryBlock buffer (256);
  5588. char* data = static_cast<char*> (buffer.getData());
  5589. size_t i = 0;
  5590. while ((data[i] = readByte()) != 0)
  5591. {
  5592. if (data[i] == '\n')
  5593. break;
  5594. if (data[i] == '\r')
  5595. {
  5596. const int64 lastPos = getPosition();
  5597. if (readByte() != '\n')
  5598. setPosition (lastPos);
  5599. break;
  5600. }
  5601. if (++i >= buffer.getSize())
  5602. {
  5603. buffer.setSize (buffer.getSize() + 512);
  5604. data = static_cast<char*> (buffer.getData());
  5605. }
  5606. }
  5607. return String::fromUTF8 (data, (int) i);
  5608. }
  5609. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5610. {
  5611. MemoryOutputStream mo (block, true);
  5612. return mo.writeFromInputStream (*this, numBytes);
  5613. }
  5614. const String InputStream::readEntireStreamAsString()
  5615. {
  5616. MemoryOutputStream mo;
  5617. mo.writeFromInputStream (*this, -1);
  5618. return mo.toString();
  5619. }
  5620. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5621. {
  5622. if (numBytesToSkip > 0)
  5623. {
  5624. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5625. HeapBlock<char> temp (skipBufferSize);
  5626. while (numBytesToSkip > 0 && ! isExhausted())
  5627. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5628. }
  5629. }
  5630. END_JUCE_NAMESPACE
  5631. /*** End of inlined file: juce_InputStream.cpp ***/
  5632. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5633. BEGIN_JUCE_NAMESPACE
  5634. #if JUCE_DEBUG
  5635. static Array<void*, CriticalSection> activeStreams;
  5636. void juce_CheckForDanglingStreams()
  5637. {
  5638. /*
  5639. It's always a bad idea to leak any object, but if you're leaking output
  5640. streams, then there's a good chance that you're failing to flush a file
  5641. to disk properly, which could result in corrupted data and other similar
  5642. nastiness..
  5643. */
  5644. jassert (activeStreams.size() == 0);
  5645. };
  5646. #endif
  5647. OutputStream::OutputStream()
  5648. : newLineString (NewLine::getDefault())
  5649. {
  5650. #if JUCE_DEBUG
  5651. activeStreams.add (this);
  5652. #endif
  5653. }
  5654. OutputStream::~OutputStream()
  5655. {
  5656. #if JUCE_DEBUG
  5657. activeStreams.removeValue (this);
  5658. #endif
  5659. }
  5660. void OutputStream::writeBool (const bool b)
  5661. {
  5662. writeByte (b ? (char) 1
  5663. : (char) 0);
  5664. }
  5665. void OutputStream::writeByte (char byte)
  5666. {
  5667. write (&byte, 1);
  5668. }
  5669. void OutputStream::writeRepeatedByte (uint8 byte, int numTimesToRepeat)
  5670. {
  5671. while (--numTimesToRepeat >= 0)
  5672. writeByte (byte);
  5673. }
  5674. void OutputStream::writeShort (short value)
  5675. {
  5676. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5677. write (&v, 2);
  5678. }
  5679. void OutputStream::writeShortBigEndian (short value)
  5680. {
  5681. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5682. write (&v, 2);
  5683. }
  5684. void OutputStream::writeInt (int value)
  5685. {
  5686. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5687. write (&v, 4);
  5688. }
  5689. void OutputStream::writeIntBigEndian (int value)
  5690. {
  5691. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5692. write (&v, 4);
  5693. }
  5694. void OutputStream::writeCompressedInt (int value)
  5695. {
  5696. unsigned int un = (value < 0) ? (unsigned int) -value
  5697. : (unsigned int) value;
  5698. uint8 data[5];
  5699. int num = 0;
  5700. while (un > 0)
  5701. {
  5702. data[++num] = (uint8) un;
  5703. un >>= 8;
  5704. }
  5705. data[0] = (uint8) num;
  5706. if (value < 0)
  5707. data[0] |= 0x80;
  5708. write (data, num + 1);
  5709. }
  5710. void OutputStream::writeInt64 (int64 value)
  5711. {
  5712. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5713. write (&v, 8);
  5714. }
  5715. void OutputStream::writeInt64BigEndian (int64 value)
  5716. {
  5717. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5718. write (&v, 8);
  5719. }
  5720. void OutputStream::writeFloat (float value)
  5721. {
  5722. union { int asInt; float asFloat; } n;
  5723. n.asFloat = value;
  5724. writeInt (n.asInt);
  5725. }
  5726. void OutputStream::writeFloatBigEndian (float value)
  5727. {
  5728. union { int asInt; float asFloat; } n;
  5729. n.asFloat = value;
  5730. writeIntBigEndian (n.asInt);
  5731. }
  5732. void OutputStream::writeDouble (double value)
  5733. {
  5734. union { int64 asInt; double asDouble; } n;
  5735. n.asDouble = value;
  5736. writeInt64 (n.asInt);
  5737. }
  5738. void OutputStream::writeDoubleBigEndian (double value)
  5739. {
  5740. union { int64 asInt; double asDouble; } n;
  5741. n.asDouble = value;
  5742. writeInt64BigEndian (n.asInt);
  5743. }
  5744. void OutputStream::writeString (const String& text)
  5745. {
  5746. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5747. // if lots of large, persistent strings were to be written to streams).
  5748. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5749. HeapBlock<char> temp (numBytes);
  5750. text.copyToUTF8 (temp, numBytes);
  5751. write (temp, numBytes);
  5752. }
  5753. void OutputStream::writeText (const String& text, const bool asUTF16,
  5754. const bool writeUTF16ByteOrderMark)
  5755. {
  5756. if (asUTF16)
  5757. {
  5758. if (writeUTF16ByteOrderMark)
  5759. write ("\x0ff\x0fe", 2);
  5760. String::CharPointerType src (text.getCharPointer());
  5761. bool lastCharWasReturn = false;
  5762. for (;;)
  5763. {
  5764. const juce_wchar c = src.getAndAdvance();
  5765. if (c == 0)
  5766. break;
  5767. if (c == '\n' && ! lastCharWasReturn)
  5768. writeShort ((short) '\r');
  5769. lastCharWasReturn = (c == L'\r');
  5770. writeShort ((short) c);
  5771. }
  5772. }
  5773. else
  5774. {
  5775. const char* src = text.toUTF8();
  5776. const char* t = src;
  5777. for (;;)
  5778. {
  5779. if (*t == '\n')
  5780. {
  5781. if (t > src)
  5782. write (src, (int) (t - src));
  5783. write ("\r\n", 2);
  5784. src = t + 1;
  5785. }
  5786. else if (*t == '\r')
  5787. {
  5788. if (t[1] == '\n')
  5789. ++t;
  5790. }
  5791. else if (*t == 0)
  5792. {
  5793. if (t > src)
  5794. write (src, (int) (t - src));
  5795. break;
  5796. }
  5797. ++t;
  5798. }
  5799. }
  5800. }
  5801. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5802. {
  5803. if (numBytesToWrite < 0)
  5804. numBytesToWrite = std::numeric_limits<int64>::max();
  5805. int numWritten = 0;
  5806. while (numBytesToWrite > 0 && ! source.isExhausted())
  5807. {
  5808. char buffer [8192];
  5809. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5810. if (num <= 0)
  5811. break;
  5812. write (buffer, num);
  5813. numBytesToWrite -= num;
  5814. numWritten += num;
  5815. }
  5816. return numWritten;
  5817. }
  5818. void OutputStream::setNewLineString (const String& newLineString_)
  5819. {
  5820. newLineString = newLineString_;
  5821. }
  5822. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5823. {
  5824. return stream << String (number);
  5825. }
  5826. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5827. {
  5828. return stream << String (number);
  5829. }
  5830. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5831. {
  5832. stream.writeByte (character);
  5833. return stream;
  5834. }
  5835. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5836. {
  5837. stream.write (text, (int) strlen (text));
  5838. return stream;
  5839. }
  5840. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5841. {
  5842. stream.write (data.getData(), (int) data.getSize());
  5843. return stream;
  5844. }
  5845. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5846. {
  5847. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5848. if (in != 0)
  5849. stream.writeFromInputStream (*in, -1);
  5850. return stream;
  5851. }
  5852. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const NewLine&)
  5853. {
  5854. return stream << stream.getNewLineString();
  5855. }
  5856. END_JUCE_NAMESPACE
  5857. /*** End of inlined file: juce_OutputStream.cpp ***/
  5858. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5859. BEGIN_JUCE_NAMESPACE
  5860. DirectoryIterator::DirectoryIterator (const File& directory,
  5861. bool isRecursive_,
  5862. const String& wildCard_,
  5863. const int whatToLookFor_)
  5864. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5865. wildCard (wildCard_),
  5866. path (File::addTrailingSeparator (directory.getFullPathName())),
  5867. index (-1),
  5868. totalNumFiles (-1),
  5869. whatToLookFor (whatToLookFor_),
  5870. isRecursive (isRecursive_),
  5871. hasBeenAdvanced (false)
  5872. {
  5873. // you have to specify the type of files you're looking for!
  5874. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5875. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5876. }
  5877. DirectoryIterator::~DirectoryIterator()
  5878. {
  5879. }
  5880. bool DirectoryIterator::next()
  5881. {
  5882. return next (0, 0, 0, 0, 0, 0);
  5883. }
  5884. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5885. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5886. {
  5887. hasBeenAdvanced = true;
  5888. if (subIterator != 0)
  5889. {
  5890. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5891. return true;
  5892. subIterator = 0;
  5893. }
  5894. String filename;
  5895. bool isDirectory, isHidden;
  5896. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5897. {
  5898. ++index;
  5899. if (! filename.containsOnly ("."))
  5900. {
  5901. const File fileFound (path + filename, 0);
  5902. bool matches = false;
  5903. if (isDirectory)
  5904. {
  5905. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5906. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5907. matches = (whatToLookFor & File::findDirectories) != 0;
  5908. }
  5909. else
  5910. {
  5911. matches = (whatToLookFor & File::findFiles) != 0;
  5912. }
  5913. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5914. if (matches && isRecursive)
  5915. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5916. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5917. matches = ! isHidden;
  5918. if (matches)
  5919. {
  5920. currentFile = fileFound;
  5921. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5922. if (isDirResult != 0) *isDirResult = isDirectory;
  5923. return true;
  5924. }
  5925. else if (subIterator != 0)
  5926. {
  5927. return next();
  5928. }
  5929. }
  5930. }
  5931. return false;
  5932. }
  5933. const File DirectoryIterator::getFile() const
  5934. {
  5935. if (subIterator != 0 && subIterator->hasBeenAdvanced)
  5936. return subIterator->getFile();
  5937. // You need to call DirectoryIterator::next() before asking it for the file that it found!
  5938. jassert (hasBeenAdvanced);
  5939. return currentFile;
  5940. }
  5941. float DirectoryIterator::getEstimatedProgress() const
  5942. {
  5943. if (totalNumFiles < 0)
  5944. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  5945. if (totalNumFiles <= 0)
  5946. return 0.0f;
  5947. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  5948. : (float) index;
  5949. return detailedIndex / totalNumFiles;
  5950. }
  5951. END_JUCE_NAMESPACE
  5952. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  5953. /*** Start of inlined file: juce_File.cpp ***/
  5954. #if ! JUCE_WINDOWS
  5955. #include <pwd.h>
  5956. #endif
  5957. BEGIN_JUCE_NAMESPACE
  5958. File::File (const String& fullPathName)
  5959. : fullPath (parseAbsolutePath (fullPathName))
  5960. {
  5961. }
  5962. File::File (const String& path, int)
  5963. : fullPath (path)
  5964. {
  5965. }
  5966. const File File::createFileWithoutCheckingPath (const String& path)
  5967. {
  5968. return File (path, 0);
  5969. }
  5970. File::File (const File& other)
  5971. : fullPath (other.fullPath)
  5972. {
  5973. }
  5974. File& File::operator= (const String& newPath)
  5975. {
  5976. fullPath = parseAbsolutePath (newPath);
  5977. return *this;
  5978. }
  5979. File& File::operator= (const File& other)
  5980. {
  5981. fullPath = other.fullPath;
  5982. return *this;
  5983. }
  5984. const File File::nonexistent;
  5985. const String File::parseAbsolutePath (const String& p)
  5986. {
  5987. if (p.isEmpty())
  5988. return String::empty;
  5989. #if JUCE_WINDOWS
  5990. // Windows..
  5991. String path (p.replaceCharacter ('/', '\\'));
  5992. if (path.startsWithChar (File::separator))
  5993. {
  5994. if (path[1] != File::separator)
  5995. {
  5996. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5997. If you're trying to parse a string that may be either a relative path or an absolute path,
  5998. you MUST provide a context against which the partial path can be evaluated - you can do
  5999. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  6000. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  6001. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  6002. */
  6003. jassertfalse;
  6004. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  6005. }
  6006. }
  6007. else if (! path.containsChar (':'))
  6008. {
  6009. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  6010. If you're trying to parse a string that may be either a relative path or an absolute path,
  6011. you MUST provide a context against which the partial path can be evaluated - you can do
  6012. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  6013. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  6014. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  6015. */
  6016. jassertfalse;
  6017. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  6018. }
  6019. #else
  6020. // Mac or Linux..
  6021. String path (p.replaceCharacter ('\\', '/'));
  6022. if (path.startsWithChar ('~'))
  6023. {
  6024. if (path[1] == File::separator || path[1] == 0)
  6025. {
  6026. // expand a name of the form "~/abc"
  6027. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  6028. + path.substring (1);
  6029. }
  6030. else
  6031. {
  6032. // expand a name of type "~dave/abc"
  6033. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  6034. struct passwd* const pw = getpwnam (userName.toUTF8());
  6035. if (pw != 0)
  6036. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  6037. }
  6038. }
  6039. else if (! path.startsWithChar (File::separator))
  6040. {
  6041. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  6042. If you're trying to parse a string that may be either a relative path or an absolute path,
  6043. you MUST provide a context against which the partial path can be evaluated - you can do
  6044. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  6045. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  6046. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  6047. */
  6048. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  6049. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  6050. }
  6051. #endif
  6052. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  6053. path = path.dropLastCharacters (1);
  6054. return path;
  6055. }
  6056. const String File::addTrailingSeparator (const String& path)
  6057. {
  6058. return path.endsWithChar (File::separator) ? path
  6059. : path + File::separator;
  6060. }
  6061. #if JUCE_LINUX
  6062. #define NAMES_ARE_CASE_SENSITIVE 1
  6063. #endif
  6064. bool File::areFileNamesCaseSensitive()
  6065. {
  6066. #if NAMES_ARE_CASE_SENSITIVE
  6067. return true;
  6068. #else
  6069. return false;
  6070. #endif
  6071. }
  6072. bool File::operator== (const File& other) const
  6073. {
  6074. #if NAMES_ARE_CASE_SENSITIVE
  6075. return fullPath == other.fullPath;
  6076. #else
  6077. return fullPath.equalsIgnoreCase (other.fullPath);
  6078. #endif
  6079. }
  6080. bool File::operator!= (const File& other) const
  6081. {
  6082. return ! operator== (other);
  6083. }
  6084. bool File::operator< (const File& other) const
  6085. {
  6086. #if NAMES_ARE_CASE_SENSITIVE
  6087. return fullPath < other.fullPath;
  6088. #else
  6089. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  6090. #endif
  6091. }
  6092. bool File::operator> (const File& other) const
  6093. {
  6094. #if NAMES_ARE_CASE_SENSITIVE
  6095. return fullPath > other.fullPath;
  6096. #else
  6097. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  6098. #endif
  6099. }
  6100. bool File::setReadOnly (const bool shouldBeReadOnly,
  6101. const bool applyRecursively) const
  6102. {
  6103. bool worked = true;
  6104. if (applyRecursively && isDirectory())
  6105. {
  6106. Array <File> subFiles;
  6107. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  6108. for (int i = subFiles.size(); --i >= 0;)
  6109. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  6110. }
  6111. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  6112. }
  6113. bool File::deleteRecursively() const
  6114. {
  6115. bool worked = true;
  6116. if (isDirectory())
  6117. {
  6118. Array<File> subFiles;
  6119. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  6120. for (int i = subFiles.size(); --i >= 0;)
  6121. worked = subFiles.getReference(i).deleteRecursively() && worked;
  6122. }
  6123. return deleteFile() && worked;
  6124. }
  6125. bool File::moveFileTo (const File& newFile) const
  6126. {
  6127. if (newFile.fullPath == fullPath)
  6128. return true;
  6129. #if ! NAMES_ARE_CASE_SENSITIVE
  6130. if (*this != newFile)
  6131. #endif
  6132. if (! newFile.deleteFile())
  6133. return false;
  6134. return moveInternal (newFile);
  6135. }
  6136. bool File::copyFileTo (const File& newFile) const
  6137. {
  6138. return (*this == newFile)
  6139. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  6140. }
  6141. bool File::copyDirectoryTo (const File& newDirectory) const
  6142. {
  6143. if (isDirectory() && newDirectory.createDirectory())
  6144. {
  6145. Array<File> subFiles;
  6146. findChildFiles (subFiles, File::findFiles, false);
  6147. int i;
  6148. for (i = 0; i < subFiles.size(); ++i)
  6149. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  6150. return false;
  6151. subFiles.clear();
  6152. findChildFiles (subFiles, File::findDirectories, false);
  6153. for (i = 0; i < subFiles.size(); ++i)
  6154. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  6155. return false;
  6156. return true;
  6157. }
  6158. return false;
  6159. }
  6160. const String File::getPathUpToLastSlash() const
  6161. {
  6162. const int lastSlash = fullPath.lastIndexOfChar (separator);
  6163. if (lastSlash > 0)
  6164. return fullPath.substring (0, lastSlash);
  6165. else if (lastSlash == 0)
  6166. return separatorString;
  6167. else
  6168. return fullPath;
  6169. }
  6170. const File File::getParentDirectory() const
  6171. {
  6172. return File (getPathUpToLastSlash(), (int) 0);
  6173. }
  6174. const String File::getFileName() const
  6175. {
  6176. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  6177. }
  6178. int File::hashCode() const
  6179. {
  6180. return fullPath.hashCode();
  6181. }
  6182. int64 File::hashCode64() const
  6183. {
  6184. return fullPath.hashCode64();
  6185. }
  6186. const String File::getFileNameWithoutExtension() const
  6187. {
  6188. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  6189. const int lastDot = fullPath.lastIndexOfChar ('.');
  6190. if (lastDot > lastSlash)
  6191. return fullPath.substring (lastSlash, lastDot);
  6192. else
  6193. return fullPath.substring (lastSlash);
  6194. }
  6195. bool File::isAChildOf (const File& potentialParent) const
  6196. {
  6197. if (potentialParent == File::nonexistent)
  6198. return false;
  6199. const String ourPath (getPathUpToLastSlash());
  6200. #if NAMES_ARE_CASE_SENSITIVE
  6201. if (potentialParent.fullPath == ourPath)
  6202. #else
  6203. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  6204. #endif
  6205. {
  6206. return true;
  6207. }
  6208. else if (potentialParent.fullPath.length() >= ourPath.length())
  6209. {
  6210. return false;
  6211. }
  6212. else
  6213. {
  6214. return getParentDirectory().isAChildOf (potentialParent);
  6215. }
  6216. }
  6217. bool File::isAbsolutePath (const String& path)
  6218. {
  6219. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  6220. #if JUCE_WINDOWS
  6221. || (path.isNotEmpty() && path[1] == ':');
  6222. #else
  6223. || path.startsWithChar ('~');
  6224. #endif
  6225. }
  6226. const File File::getChildFile (String relativePath) const
  6227. {
  6228. if (isAbsolutePath (relativePath))
  6229. {
  6230. // the path is really absolute..
  6231. return File (relativePath);
  6232. }
  6233. else
  6234. {
  6235. // it's relative, so remove any ../ or ./ bits at the start.
  6236. String path (fullPath);
  6237. if (relativePath[0] == '.')
  6238. {
  6239. #if JUCE_WINDOWS
  6240. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  6241. #else
  6242. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  6243. #endif
  6244. while (relativePath[0] == '.')
  6245. {
  6246. if (relativePath[1] == '.')
  6247. {
  6248. if (relativePath [2] == 0 || relativePath[2] == separator)
  6249. {
  6250. const int lastSlash = path.lastIndexOfChar (separator);
  6251. if (lastSlash >= 0)
  6252. path = path.substring (0, lastSlash);
  6253. relativePath = relativePath.substring (3);
  6254. }
  6255. else
  6256. {
  6257. break;
  6258. }
  6259. }
  6260. else if (relativePath[1] == separator)
  6261. {
  6262. relativePath = relativePath.substring (2);
  6263. }
  6264. else
  6265. {
  6266. break;
  6267. }
  6268. }
  6269. }
  6270. return File (addTrailingSeparator (path) + relativePath);
  6271. }
  6272. }
  6273. const File File::getSiblingFile (const String& fileName) const
  6274. {
  6275. return getParentDirectory().getChildFile (fileName);
  6276. }
  6277. const String File::descriptionOfSizeInBytes (const int64 bytes)
  6278. {
  6279. if (bytes == 1)
  6280. {
  6281. return "1 byte";
  6282. }
  6283. else if (bytes < 1024)
  6284. {
  6285. return String ((int) bytes) + " bytes";
  6286. }
  6287. else if (bytes < 1024 * 1024)
  6288. {
  6289. return String (bytes / 1024.0, 1) + " KB";
  6290. }
  6291. else if (bytes < 1024 * 1024 * 1024)
  6292. {
  6293. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  6294. }
  6295. else
  6296. {
  6297. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  6298. }
  6299. }
  6300. bool File::create() const
  6301. {
  6302. if (exists())
  6303. return true;
  6304. {
  6305. const File parentDir (getParentDirectory());
  6306. if (parentDir == *this || ! parentDir.createDirectory())
  6307. return false;
  6308. FileOutputStream fo (*this, 8);
  6309. }
  6310. return exists();
  6311. }
  6312. bool File::createDirectory() const
  6313. {
  6314. if (! isDirectory())
  6315. {
  6316. const File parentDir (getParentDirectory());
  6317. if (parentDir == *this || ! parentDir.createDirectory())
  6318. return false;
  6319. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  6320. return isDirectory();
  6321. }
  6322. return true;
  6323. }
  6324. const Time File::getCreationTime() const
  6325. {
  6326. int64 m, a, c;
  6327. getFileTimesInternal (m, a, c);
  6328. return Time (c);
  6329. }
  6330. const Time File::getLastModificationTime() const
  6331. {
  6332. int64 m, a, c;
  6333. getFileTimesInternal (m, a, c);
  6334. return Time (m);
  6335. }
  6336. const Time File::getLastAccessTime() const
  6337. {
  6338. int64 m, a, c;
  6339. getFileTimesInternal (m, a, c);
  6340. return Time (a);
  6341. }
  6342. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  6343. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  6344. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  6345. bool File::loadFileAsData (MemoryBlock& destBlock) const
  6346. {
  6347. if (! existsAsFile())
  6348. return false;
  6349. FileInputStream in (*this);
  6350. return getSize() == in.readIntoMemoryBlock (destBlock);
  6351. }
  6352. const String File::loadFileAsString() const
  6353. {
  6354. if (! existsAsFile())
  6355. return String::empty;
  6356. FileInputStream in (*this);
  6357. return in.readEntireStreamAsString();
  6358. }
  6359. int File::findChildFiles (Array<File>& results,
  6360. const int whatToLookFor,
  6361. const bool searchRecursively,
  6362. const String& wildCardPattern) const
  6363. {
  6364. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  6365. int total = 0;
  6366. while (di.next())
  6367. {
  6368. results.add (di.getFile());
  6369. ++total;
  6370. }
  6371. return total;
  6372. }
  6373. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  6374. {
  6375. DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
  6376. int total = 0;
  6377. while (di.next())
  6378. ++total;
  6379. return total;
  6380. }
  6381. bool File::containsSubDirectories() const
  6382. {
  6383. if (isDirectory())
  6384. {
  6385. DirectoryIterator di (*this, false, "*", findDirectories);
  6386. return di.next();
  6387. }
  6388. return false;
  6389. }
  6390. const File File::getNonexistentChildFile (const String& prefix_,
  6391. const String& suffix,
  6392. bool putNumbersInBrackets) const
  6393. {
  6394. File f (getChildFile (prefix_ + suffix));
  6395. if (f.exists())
  6396. {
  6397. int num = 2;
  6398. String prefix (prefix_);
  6399. // remove any bracketed numbers that may already be on the end..
  6400. if (prefix.trim().endsWithChar (')'))
  6401. {
  6402. putNumbersInBrackets = true;
  6403. const int openBracks = prefix.lastIndexOfChar ('(');
  6404. const int closeBracks = prefix.lastIndexOfChar (')');
  6405. if (openBracks > 0
  6406. && closeBracks > openBracks
  6407. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6408. {
  6409. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6410. prefix = prefix.substring (0, openBracks);
  6411. }
  6412. }
  6413. // also use brackets if it ends in a digit.
  6414. putNumbersInBrackets = putNumbersInBrackets
  6415. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6416. do
  6417. {
  6418. if (putNumbersInBrackets)
  6419. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6420. else
  6421. f = getChildFile (prefix + String (num++) + suffix);
  6422. } while (f.exists());
  6423. }
  6424. return f;
  6425. }
  6426. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6427. {
  6428. if (exists())
  6429. {
  6430. return getParentDirectory()
  6431. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6432. getFileExtension(),
  6433. putNumbersInBrackets);
  6434. }
  6435. else
  6436. {
  6437. return *this;
  6438. }
  6439. }
  6440. const String File::getFileExtension() const
  6441. {
  6442. String ext;
  6443. if (! isDirectory())
  6444. {
  6445. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6446. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6447. ext = fullPath.substring (indexOfDot);
  6448. }
  6449. return ext;
  6450. }
  6451. bool File::hasFileExtension (const String& possibleSuffix) const
  6452. {
  6453. if (possibleSuffix.isEmpty())
  6454. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6455. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6456. if (semicolon >= 0)
  6457. {
  6458. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6459. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6460. }
  6461. else
  6462. {
  6463. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6464. {
  6465. if (possibleSuffix.startsWithChar ('.'))
  6466. return true;
  6467. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6468. if (dotPos >= 0)
  6469. return fullPath [dotPos] == '.';
  6470. }
  6471. }
  6472. return false;
  6473. }
  6474. const File File::withFileExtension (const String& newExtension) const
  6475. {
  6476. if (fullPath.isEmpty())
  6477. return File::nonexistent;
  6478. String filePart (getFileName());
  6479. int i = filePart.lastIndexOfChar ('.');
  6480. if (i >= 0)
  6481. filePart = filePart.substring (0, i);
  6482. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6483. filePart << '.';
  6484. return getSiblingFile (filePart + newExtension);
  6485. }
  6486. bool File::startAsProcess (const String& parameters) const
  6487. {
  6488. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6489. }
  6490. FileInputStream* File::createInputStream() const
  6491. {
  6492. if (existsAsFile())
  6493. return new FileInputStream (*this);
  6494. return 0;
  6495. }
  6496. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6497. {
  6498. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6499. if (out->failedToOpen())
  6500. return 0;
  6501. return out.release();
  6502. }
  6503. bool File::appendData (const void* const dataToAppend,
  6504. const int numberOfBytes) const
  6505. {
  6506. if (numberOfBytes > 0)
  6507. {
  6508. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6509. if (out == 0)
  6510. return false;
  6511. out->write (dataToAppend, numberOfBytes);
  6512. }
  6513. return true;
  6514. }
  6515. bool File::replaceWithData (const void* const dataToWrite,
  6516. const int numberOfBytes) const
  6517. {
  6518. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6519. if (numberOfBytes <= 0)
  6520. return deleteFile();
  6521. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6522. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6523. return tempFile.overwriteTargetFileWithTemporary();
  6524. }
  6525. bool File::appendText (const String& text,
  6526. const bool asUnicode,
  6527. const bool writeUnicodeHeaderBytes) const
  6528. {
  6529. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6530. if (out != 0)
  6531. {
  6532. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6533. return true;
  6534. }
  6535. return false;
  6536. }
  6537. bool File::replaceWithText (const String& textToWrite,
  6538. const bool asUnicode,
  6539. const bool writeUnicodeHeaderBytes) const
  6540. {
  6541. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6542. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6543. return tempFile.overwriteTargetFileWithTemporary();
  6544. }
  6545. bool File::hasIdenticalContentTo (const File& other) const
  6546. {
  6547. if (other == *this)
  6548. return true;
  6549. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6550. {
  6551. FileInputStream in1 (*this), in2 (other);
  6552. const int bufferSize = 4096;
  6553. HeapBlock <char> buffer1, buffer2;
  6554. buffer1.malloc (bufferSize);
  6555. buffer2.malloc (bufferSize);
  6556. for (;;)
  6557. {
  6558. const int num1 = in1.read (buffer1, bufferSize);
  6559. const int num2 = in2.read (buffer2, bufferSize);
  6560. if (num1 != num2)
  6561. break;
  6562. if (num1 <= 0)
  6563. return true;
  6564. if (memcmp (buffer1, buffer2, num1) != 0)
  6565. break;
  6566. }
  6567. }
  6568. return false;
  6569. }
  6570. const String File::createLegalPathName (const String& original)
  6571. {
  6572. String s (original);
  6573. String start;
  6574. if (s[1] == ':')
  6575. {
  6576. start = s.substring (0, 2);
  6577. s = s.substring (2);
  6578. }
  6579. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6580. .substring (0, 1024);
  6581. }
  6582. const String File::createLegalFileName (const String& original)
  6583. {
  6584. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6585. const int maxLength = 128; // only the length of the filename, not the whole path
  6586. const int len = s.length();
  6587. if (len > maxLength)
  6588. {
  6589. const int lastDot = s.lastIndexOfChar ('.');
  6590. if (lastDot > jmax (0, len - 12))
  6591. {
  6592. s = s.substring (0, maxLength - (len - lastDot))
  6593. + s.substring (lastDot);
  6594. }
  6595. else
  6596. {
  6597. s = s.substring (0, maxLength);
  6598. }
  6599. }
  6600. return s;
  6601. }
  6602. const String File::getRelativePathFrom (const File& dir) const
  6603. {
  6604. String thisPath (fullPath);
  6605. while (thisPath.endsWithChar (separator))
  6606. thisPath = thisPath.dropLastCharacters (1);
  6607. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6608. : dir.fullPath));
  6609. const int len = jmin (thisPath.length(), dirPath.length());
  6610. int commonBitLength = 0;
  6611. for (int i = 0; i < len; ++i)
  6612. {
  6613. #if NAMES_ARE_CASE_SENSITIVE
  6614. if (thisPath[i] != dirPath[i])
  6615. #else
  6616. if (CharacterFunctions::toLowerCase (thisPath[i])
  6617. != CharacterFunctions::toLowerCase (dirPath[i]))
  6618. #endif
  6619. {
  6620. break;
  6621. }
  6622. ++commonBitLength;
  6623. }
  6624. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6625. --commonBitLength;
  6626. // if the only common bit is the root, then just return the full path..
  6627. if (commonBitLength <= 0
  6628. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6629. return fullPath;
  6630. thisPath = thisPath.substring (commonBitLength);
  6631. dirPath = dirPath.substring (commonBitLength);
  6632. while (dirPath.isNotEmpty())
  6633. {
  6634. #if JUCE_WINDOWS
  6635. thisPath = "..\\" + thisPath;
  6636. #else
  6637. thisPath = "../" + thisPath;
  6638. #endif
  6639. const int sep = dirPath.indexOfChar (separator);
  6640. if (sep >= 0)
  6641. dirPath = dirPath.substring (sep + 1);
  6642. else
  6643. dirPath = String::empty;
  6644. }
  6645. return thisPath;
  6646. }
  6647. const File File::createTempFile (const String& fileNameEnding)
  6648. {
  6649. const File tempFile (getSpecialLocation (tempDirectory)
  6650. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6651. .withFileExtension (fileNameEnding));
  6652. if (tempFile.exists())
  6653. return createTempFile (fileNameEnding);
  6654. else
  6655. return tempFile;
  6656. }
  6657. #if JUCE_UNIT_TESTS
  6658. class FileTests : public UnitTest
  6659. {
  6660. public:
  6661. FileTests() : UnitTest ("Files") {}
  6662. void runTest()
  6663. {
  6664. beginTest ("Reading");
  6665. const File home (File::getSpecialLocation (File::userHomeDirectory));
  6666. const File temp (File::getSpecialLocation (File::tempDirectory));
  6667. expect (! File::nonexistent.exists());
  6668. expect (home.isDirectory());
  6669. expect (home.exists());
  6670. expect (! home.existsAsFile());
  6671. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  6672. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  6673. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  6674. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  6675. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  6676. expect (home.getVolumeTotalSize() > 1024 * 1024);
  6677. expect (home.getBytesFreeOnVolume() > 0);
  6678. expect (! home.isHidden());
  6679. expect (home.isOnHardDisk());
  6680. expect (! home.isOnCDRomDrive());
  6681. expect (File::getCurrentWorkingDirectory().exists());
  6682. expect (home.setAsCurrentWorkingDirectory());
  6683. expect (File::getCurrentWorkingDirectory() == home);
  6684. {
  6685. Array<File> roots;
  6686. File::findFileSystemRoots (roots);
  6687. expect (roots.size() > 0);
  6688. int numRootsExisting = 0;
  6689. for (int i = 0; i < roots.size(); ++i)
  6690. if (roots[i].exists())
  6691. ++numRootsExisting;
  6692. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  6693. expect (numRootsExisting > 0);
  6694. }
  6695. beginTest ("Writing");
  6696. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  6697. expect (demoFolder.deleteRecursively());
  6698. expect (demoFolder.createDirectory());
  6699. expect (demoFolder.isDirectory());
  6700. expect (demoFolder.getParentDirectory() == temp);
  6701. expect (temp.isDirectory());
  6702. {
  6703. Array<File> files;
  6704. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  6705. expect (files.contains (demoFolder));
  6706. }
  6707. {
  6708. Array<File> files;
  6709. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  6710. expect (files.contains (demoFolder));
  6711. }
  6712. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  6713. expect (tempFile.getFileExtension() == ".txt");
  6714. expect (tempFile.hasFileExtension (".txt"));
  6715. expect (tempFile.hasFileExtension ("txt"));
  6716. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  6717. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  6718. expect (tempFile.hasWriteAccess());
  6719. {
  6720. FileOutputStream fo (tempFile);
  6721. fo.write ("0123456789", 10);
  6722. }
  6723. expect (tempFile.exists());
  6724. expect (tempFile.getSize() == 10);
  6725. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  6726. expect (tempFile.loadFileAsString() == "0123456789");
  6727. expect (! demoFolder.containsSubDirectories());
  6728. expectEquals (tempFile.getRelativePathFrom (demoFolder.getParentDirectory()), demoFolder.getFileName() + File::separatorString + tempFile.getFileName());
  6729. expectEquals (demoFolder.getParentDirectory().getRelativePathFrom (tempFile), ".." + File::separatorString + ".." + File::separatorString + demoFolder.getParentDirectory().getFileName());
  6730. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  6731. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  6732. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  6733. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  6734. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  6735. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  6736. expect (demoFolder.containsSubDirectories());
  6737. expect (tempFile.hasWriteAccess());
  6738. tempFile.setReadOnly (true);
  6739. expect (! tempFile.hasWriteAccess());
  6740. tempFile.setReadOnly (false);
  6741. expect (tempFile.hasWriteAccess());
  6742. Time t (Time::getCurrentTime());
  6743. tempFile.setLastModificationTime (t);
  6744. Time t2 = tempFile.getLastModificationTime();
  6745. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  6746. {
  6747. MemoryBlock mb;
  6748. tempFile.loadFileAsData (mb);
  6749. expect (mb.getSize() == 10);
  6750. expect (mb[0] == '0');
  6751. }
  6752. expect (tempFile.appendData ("abcdefghij", 10));
  6753. expect (tempFile.getSize() == 20);
  6754. expect (tempFile.replaceWithData ("abcdefghij", 10));
  6755. expect (tempFile.getSize() == 10);
  6756. File tempFile2 (tempFile.getNonexistentSibling (false));
  6757. expect (tempFile.copyFileTo (tempFile2));
  6758. expect (tempFile2.exists());
  6759. expect (tempFile2.hasIdenticalContentTo (tempFile));
  6760. expect (tempFile.deleteFile());
  6761. expect (! tempFile.exists());
  6762. expect (tempFile2.moveFileTo (tempFile));
  6763. expect (tempFile.exists());
  6764. expect (! tempFile2.exists());
  6765. expect (demoFolder.deleteRecursively());
  6766. expect (! demoFolder.exists());
  6767. }
  6768. };
  6769. static FileTests fileUnitTests;
  6770. #endif
  6771. END_JUCE_NAMESPACE
  6772. /*** End of inlined file: juce_File.cpp ***/
  6773. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6774. BEGIN_JUCE_NAMESPACE
  6775. int64 juce_fileSetPosition (void* handle, int64 pos);
  6776. FileInputStream::FileInputStream (const File& f)
  6777. : file (f),
  6778. fileHandle (0),
  6779. currentPosition (0),
  6780. totalSize (0),
  6781. needToSeek (true)
  6782. {
  6783. openHandle();
  6784. }
  6785. FileInputStream::~FileInputStream()
  6786. {
  6787. closeHandle();
  6788. }
  6789. int64 FileInputStream::getTotalLength()
  6790. {
  6791. return totalSize;
  6792. }
  6793. int FileInputStream::read (void* buffer, int bytesToRead)
  6794. {
  6795. if (needToSeek)
  6796. {
  6797. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6798. return 0;
  6799. needToSeek = false;
  6800. }
  6801. const size_t num = readInternal (buffer, bytesToRead);
  6802. currentPosition += num;
  6803. return (int) num;
  6804. }
  6805. bool FileInputStream::isExhausted()
  6806. {
  6807. return currentPosition >= totalSize;
  6808. }
  6809. int64 FileInputStream::getPosition()
  6810. {
  6811. return currentPosition;
  6812. }
  6813. bool FileInputStream::setPosition (int64 pos)
  6814. {
  6815. pos = jlimit ((int64) 0, totalSize, pos);
  6816. needToSeek |= (currentPosition != pos);
  6817. currentPosition = pos;
  6818. return true;
  6819. }
  6820. END_JUCE_NAMESPACE
  6821. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6822. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6823. BEGIN_JUCE_NAMESPACE
  6824. int64 juce_fileSetPosition (void* handle, int64 pos);
  6825. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6826. : file (f),
  6827. fileHandle (0),
  6828. currentPosition (0),
  6829. bufferSize (bufferSize_),
  6830. bytesInBuffer (0),
  6831. buffer (jmax (bufferSize_, 16))
  6832. {
  6833. openHandle();
  6834. }
  6835. FileOutputStream::~FileOutputStream()
  6836. {
  6837. flush();
  6838. closeHandle();
  6839. }
  6840. int64 FileOutputStream::getPosition()
  6841. {
  6842. return currentPosition;
  6843. }
  6844. bool FileOutputStream::setPosition (int64 newPosition)
  6845. {
  6846. if (newPosition != currentPosition)
  6847. {
  6848. flush();
  6849. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6850. }
  6851. return newPosition == currentPosition;
  6852. }
  6853. void FileOutputStream::flush()
  6854. {
  6855. if (bytesInBuffer > 0)
  6856. {
  6857. writeInternal (buffer, bytesInBuffer);
  6858. bytesInBuffer = 0;
  6859. }
  6860. flushInternal();
  6861. }
  6862. bool FileOutputStream::write (const void* const src, const int numBytes)
  6863. {
  6864. if (bytesInBuffer + numBytes < bufferSize)
  6865. {
  6866. memcpy (buffer + bytesInBuffer, src, numBytes);
  6867. bytesInBuffer += numBytes;
  6868. currentPosition += numBytes;
  6869. }
  6870. else
  6871. {
  6872. if (bytesInBuffer > 0)
  6873. {
  6874. // flush the reservoir
  6875. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6876. bytesInBuffer = 0;
  6877. if (! wroteOk)
  6878. return false;
  6879. }
  6880. if (numBytes < bufferSize)
  6881. {
  6882. memcpy (buffer + bytesInBuffer, src, numBytes);
  6883. bytesInBuffer += numBytes;
  6884. currentPosition += numBytes;
  6885. }
  6886. else
  6887. {
  6888. const int bytesWritten = writeInternal (src, numBytes);
  6889. if (bytesWritten < 0)
  6890. return false;
  6891. currentPosition += bytesWritten;
  6892. return bytesWritten == numBytes;
  6893. }
  6894. }
  6895. return true;
  6896. }
  6897. END_JUCE_NAMESPACE
  6898. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6899. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6900. BEGIN_JUCE_NAMESPACE
  6901. FileSearchPath::FileSearchPath()
  6902. {
  6903. }
  6904. FileSearchPath::FileSearchPath (const String& path)
  6905. {
  6906. init (path);
  6907. }
  6908. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6909. : directories (other.directories)
  6910. {
  6911. }
  6912. FileSearchPath::~FileSearchPath()
  6913. {
  6914. }
  6915. FileSearchPath& FileSearchPath::operator= (const String& path)
  6916. {
  6917. init (path);
  6918. return *this;
  6919. }
  6920. void FileSearchPath::init (const String& path)
  6921. {
  6922. directories.clear();
  6923. directories.addTokens (path, ";", "\"");
  6924. directories.trim();
  6925. directories.removeEmptyStrings();
  6926. for (int i = directories.size(); --i >= 0;)
  6927. directories.set (i, directories[i].unquoted());
  6928. }
  6929. int FileSearchPath::getNumPaths() const
  6930. {
  6931. return directories.size();
  6932. }
  6933. const File FileSearchPath::operator[] (const int index) const
  6934. {
  6935. return File (directories [index]);
  6936. }
  6937. const String FileSearchPath::toString() const
  6938. {
  6939. StringArray directories2 (directories);
  6940. for (int i = directories2.size(); --i >= 0;)
  6941. if (directories2[i].containsChar (';'))
  6942. directories2.set (i, directories2[i].quoted());
  6943. return directories2.joinIntoString (";");
  6944. }
  6945. void FileSearchPath::add (const File& dir, const int insertIndex)
  6946. {
  6947. directories.insert (insertIndex, dir.getFullPathName());
  6948. }
  6949. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  6950. {
  6951. for (int i = 0; i < directories.size(); ++i)
  6952. if (File (directories[i]) == dir)
  6953. return;
  6954. add (dir);
  6955. }
  6956. void FileSearchPath::remove (const int index)
  6957. {
  6958. directories.remove (index);
  6959. }
  6960. void FileSearchPath::addPath (const FileSearchPath& other)
  6961. {
  6962. for (int i = 0; i < other.getNumPaths(); ++i)
  6963. addIfNotAlreadyThere (other[i]);
  6964. }
  6965. void FileSearchPath::removeRedundantPaths()
  6966. {
  6967. for (int i = directories.size(); --i >= 0;)
  6968. {
  6969. const File d1 (directories[i]);
  6970. for (int j = directories.size(); --j >= 0;)
  6971. {
  6972. const File d2 (directories[j]);
  6973. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  6974. {
  6975. directories.remove (i);
  6976. break;
  6977. }
  6978. }
  6979. }
  6980. }
  6981. void FileSearchPath::removeNonExistentPaths()
  6982. {
  6983. for (int i = directories.size(); --i >= 0;)
  6984. if (! File (directories[i]).isDirectory())
  6985. directories.remove (i);
  6986. }
  6987. int FileSearchPath::findChildFiles (Array<File>& results,
  6988. const int whatToLookFor,
  6989. const bool searchRecursively,
  6990. const String& wildCardPattern) const
  6991. {
  6992. int total = 0;
  6993. for (int i = 0; i < directories.size(); ++i)
  6994. total += operator[] (i).findChildFiles (results,
  6995. whatToLookFor,
  6996. searchRecursively,
  6997. wildCardPattern);
  6998. return total;
  6999. }
  7000. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  7001. const bool checkRecursively) const
  7002. {
  7003. for (int i = directories.size(); --i >= 0;)
  7004. {
  7005. const File d (directories[i]);
  7006. if (checkRecursively)
  7007. {
  7008. if (fileToCheck.isAChildOf (d))
  7009. return true;
  7010. }
  7011. else
  7012. {
  7013. if (fileToCheck.getParentDirectory() == d)
  7014. return true;
  7015. }
  7016. }
  7017. return false;
  7018. }
  7019. END_JUCE_NAMESPACE
  7020. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  7021. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  7022. BEGIN_JUCE_NAMESPACE
  7023. NamedPipe::NamedPipe()
  7024. : internal (0)
  7025. {
  7026. }
  7027. NamedPipe::~NamedPipe()
  7028. {
  7029. close();
  7030. }
  7031. bool NamedPipe::openExisting (const String& pipeName)
  7032. {
  7033. currentPipeName = pipeName;
  7034. return openInternal (pipeName, false);
  7035. }
  7036. bool NamedPipe::createNewPipe (const String& pipeName)
  7037. {
  7038. currentPipeName = pipeName;
  7039. return openInternal (pipeName, true);
  7040. }
  7041. bool NamedPipe::isOpen() const
  7042. {
  7043. return internal != 0;
  7044. }
  7045. const String NamedPipe::getName() const
  7046. {
  7047. return currentPipeName;
  7048. }
  7049. // other methods for this class are implemented in the platform-specific files
  7050. END_JUCE_NAMESPACE
  7051. /*** End of inlined file: juce_NamedPipe.cpp ***/
  7052. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  7053. BEGIN_JUCE_NAMESPACE
  7054. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  7055. {
  7056. createTempFile (File::getSpecialLocation (File::tempDirectory),
  7057. "temp_" + String (Random::getSystemRandom().nextInt()),
  7058. suffix,
  7059. optionFlags);
  7060. }
  7061. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  7062. : targetFile (targetFile_)
  7063. {
  7064. // If you use this constructor, you need to give it a valid target file!
  7065. jassert (targetFile != File::nonexistent);
  7066. createTempFile (targetFile.getParentDirectory(),
  7067. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  7068. targetFile.getFileExtension(),
  7069. optionFlags);
  7070. }
  7071. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  7072. const String& suffix, const int optionFlags)
  7073. {
  7074. if ((optionFlags & useHiddenFile) != 0)
  7075. name = "." + name;
  7076. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  7077. }
  7078. TemporaryFile::~TemporaryFile()
  7079. {
  7080. if (! deleteTemporaryFile())
  7081. {
  7082. /* Failed to delete our temporary file! The most likely reason for this would be
  7083. that you've not closed an output stream that was being used to write to file.
  7084. If you find that something beyond your control is changing permissions on
  7085. your temporary files and preventing them from being deleted, you may want to
  7086. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  7087. handle them appropriately.
  7088. */
  7089. jassertfalse;
  7090. }
  7091. }
  7092. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  7093. {
  7094. // This method only works if you created this object with the constructor
  7095. // that takes a target file!
  7096. jassert (targetFile != File::nonexistent);
  7097. if (temporaryFile.exists())
  7098. {
  7099. // Have a few attempts at overwriting the file before giving up..
  7100. for (int i = 5; --i >= 0;)
  7101. {
  7102. if (temporaryFile.moveFileTo (targetFile))
  7103. return true;
  7104. Thread::sleep (100);
  7105. }
  7106. }
  7107. else
  7108. {
  7109. // There's no temporary file to use. If your write failed, you should
  7110. // probably check, and not bother calling this method.
  7111. jassertfalse;
  7112. }
  7113. return false;
  7114. }
  7115. bool TemporaryFile::deleteTemporaryFile() const
  7116. {
  7117. // Have a few attempts at deleting the file before giving up..
  7118. for (int i = 5; --i >= 0;)
  7119. {
  7120. if (temporaryFile.deleteFile())
  7121. return true;
  7122. Thread::sleep (50);
  7123. }
  7124. return false;
  7125. }
  7126. END_JUCE_NAMESPACE
  7127. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  7128. /*** Start of inlined file: juce_Socket.cpp ***/
  7129. #if JUCE_WINDOWS
  7130. #include <winsock2.h>
  7131. #if JUCE_MSVC
  7132. #pragma warning (push)
  7133. #pragma warning (disable : 4127 4389 4018)
  7134. #endif
  7135. #else
  7136. #if JUCE_LINUX || JUCE_ANDROID
  7137. #include <sys/types.h>
  7138. #include <sys/socket.h>
  7139. #include <sys/errno.h>
  7140. #include <unistd.h>
  7141. #include <netinet/in.h>
  7142. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  7143. #include <CoreServices/CoreServices.h>
  7144. #endif
  7145. #include <fcntl.h>
  7146. #include <netdb.h>
  7147. #include <arpa/inet.h>
  7148. #include <netinet/tcp.h>
  7149. #endif
  7150. BEGIN_JUCE_NAMESPACE
  7151. #if JUCE_LINUX || JUCE_MAC || JUCE_IOS || JUCE_ANDROID
  7152. typedef socklen_t juce_socklen_t;
  7153. #else
  7154. typedef int juce_socklen_t;
  7155. #endif
  7156. #if JUCE_WINDOWS
  7157. namespace SocketHelpers
  7158. {
  7159. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  7160. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  7161. void initWin32Sockets()
  7162. {
  7163. static CriticalSection lock;
  7164. const ScopedLock sl (lock);
  7165. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  7166. {
  7167. WSADATA wsaData;
  7168. const WORD wVersionRequested = MAKEWORD (1, 1);
  7169. WSAStartup (wVersionRequested, &wsaData);
  7170. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  7171. }
  7172. }
  7173. }
  7174. void juce_shutdownWin32Sockets()
  7175. {
  7176. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  7177. (*SocketHelpers::juce_CloseWin32SocketLib)();
  7178. }
  7179. #endif
  7180. namespace SocketHelpers
  7181. {
  7182. bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  7183. {
  7184. const int sndBufSize = 65536;
  7185. const int rcvBufSize = 65536;
  7186. const int one = 1;
  7187. return handle > 0
  7188. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  7189. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  7190. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  7191. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  7192. }
  7193. bool bindSocketToPort (const int handle, const int port) throw()
  7194. {
  7195. if (handle <= 0 || port <= 0)
  7196. return false;
  7197. struct sockaddr_in servTmpAddr;
  7198. zerostruct (servTmpAddr);
  7199. servTmpAddr.sin_family = PF_INET;
  7200. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7201. servTmpAddr.sin_port = htons ((uint16) port);
  7202. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  7203. }
  7204. int readSocket (const int handle,
  7205. void* const destBuffer, const int maxBytesToRead,
  7206. bool volatile& connected,
  7207. const bool blockUntilSpecifiedAmountHasArrived) throw()
  7208. {
  7209. int bytesRead = 0;
  7210. while (bytesRead < maxBytesToRead)
  7211. {
  7212. int bytesThisTime;
  7213. #if JUCE_WINDOWS
  7214. bytesThisTime = recv (handle, static_cast<char*> (destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  7215. #else
  7216. while ((bytesThisTime = (int) ::read (handle, addBytesToPointer (destBuffer, bytesRead), maxBytesToRead - bytesRead)) < 0
  7217. && errno == EINTR
  7218. && connected)
  7219. {
  7220. }
  7221. #endif
  7222. if (bytesThisTime <= 0 || ! connected)
  7223. {
  7224. if (bytesRead == 0)
  7225. bytesRead = -1;
  7226. break;
  7227. }
  7228. bytesRead += bytesThisTime;
  7229. if (! blockUntilSpecifiedAmountHasArrived)
  7230. break;
  7231. }
  7232. return bytesRead;
  7233. }
  7234. int waitForReadiness (const int handle, const bool forReading, const int timeoutMsecs) throw()
  7235. {
  7236. struct timeval timeout;
  7237. struct timeval* timeoutp;
  7238. if (timeoutMsecs >= 0)
  7239. {
  7240. timeout.tv_sec = timeoutMsecs / 1000;
  7241. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  7242. timeoutp = &timeout;
  7243. }
  7244. else
  7245. {
  7246. timeoutp = 0;
  7247. }
  7248. fd_set rset, wset;
  7249. FD_ZERO (&rset);
  7250. FD_SET (handle, &rset);
  7251. FD_ZERO (&wset);
  7252. FD_SET (handle, &wset);
  7253. fd_set* const prset = forReading ? &rset : 0;
  7254. fd_set* const pwset = forReading ? 0 : &wset;
  7255. #if JUCE_WINDOWS
  7256. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  7257. return -1;
  7258. #else
  7259. {
  7260. int result;
  7261. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  7262. && errno == EINTR)
  7263. {
  7264. }
  7265. if (result < 0)
  7266. return -1;
  7267. }
  7268. #endif
  7269. {
  7270. int opt;
  7271. juce_socklen_t len = sizeof (opt);
  7272. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  7273. || opt != 0)
  7274. return -1;
  7275. }
  7276. if ((forReading && FD_ISSET (handle, &rset))
  7277. || ((! forReading) && FD_ISSET (handle, &wset)))
  7278. return 1;
  7279. return 0;
  7280. }
  7281. bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  7282. {
  7283. #if JUCE_WINDOWS
  7284. u_long nonBlocking = shouldBlock ? 0 : 1;
  7285. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  7286. return false;
  7287. #else
  7288. int socketFlags = fcntl (handle, F_GETFL, 0);
  7289. if (socketFlags == -1)
  7290. return false;
  7291. if (shouldBlock)
  7292. socketFlags &= ~O_NONBLOCK;
  7293. else
  7294. socketFlags |= O_NONBLOCK;
  7295. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  7296. return false;
  7297. #endif
  7298. return true;
  7299. }
  7300. bool connectSocket (int volatile& handle,
  7301. const bool isDatagram,
  7302. void** serverAddress,
  7303. const String& hostName,
  7304. const int portNumber,
  7305. const int timeOutMillisecs) throw()
  7306. {
  7307. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  7308. if (hostEnt == 0)
  7309. return false;
  7310. struct in_addr targetAddress;
  7311. memcpy (&targetAddress.s_addr,
  7312. *(hostEnt->h_addr_list),
  7313. sizeof (targetAddress.s_addr));
  7314. struct sockaddr_in servTmpAddr;
  7315. zerostruct (servTmpAddr);
  7316. servTmpAddr.sin_family = PF_INET;
  7317. servTmpAddr.sin_addr = targetAddress;
  7318. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7319. if (handle < 0)
  7320. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  7321. if (handle < 0)
  7322. return false;
  7323. if (isDatagram)
  7324. {
  7325. *serverAddress = new struct sockaddr_in();
  7326. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  7327. return true;
  7328. }
  7329. setSocketBlockingState (handle, false);
  7330. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  7331. if (result < 0)
  7332. {
  7333. #if JUCE_WINDOWS
  7334. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  7335. #else
  7336. if (errno == EINPROGRESS)
  7337. #endif
  7338. {
  7339. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  7340. {
  7341. setSocketBlockingState (handle, true);
  7342. return false;
  7343. }
  7344. }
  7345. }
  7346. setSocketBlockingState (handle, true);
  7347. resetSocketOptions (handle, false, false);
  7348. return true;
  7349. }
  7350. }
  7351. StreamingSocket::StreamingSocket()
  7352. : portNumber (0),
  7353. handle (-1),
  7354. connected (false),
  7355. isListener (false)
  7356. {
  7357. #if JUCE_WINDOWS
  7358. SocketHelpers::initWin32Sockets();
  7359. #endif
  7360. }
  7361. StreamingSocket::StreamingSocket (const String& hostName_,
  7362. const int portNumber_,
  7363. const int handle_)
  7364. : hostName (hostName_),
  7365. portNumber (portNumber_),
  7366. handle (handle_),
  7367. connected (true),
  7368. isListener (false)
  7369. {
  7370. #if JUCE_WINDOWS
  7371. SocketHelpers::initWin32Sockets();
  7372. #endif
  7373. SocketHelpers::resetSocketOptions (handle_, false, false);
  7374. }
  7375. StreamingSocket::~StreamingSocket()
  7376. {
  7377. close();
  7378. }
  7379. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7380. {
  7381. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7382. : -1;
  7383. }
  7384. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7385. {
  7386. if (isListener || ! connected)
  7387. return -1;
  7388. #if JUCE_WINDOWS
  7389. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  7390. #else
  7391. int result;
  7392. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  7393. && errno == EINTR)
  7394. {
  7395. }
  7396. return result;
  7397. #endif
  7398. }
  7399. int StreamingSocket::waitUntilReady (const bool readyForReading,
  7400. const int timeoutMsecs) const
  7401. {
  7402. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7403. : -1;
  7404. }
  7405. bool StreamingSocket::bindToPort (const int port)
  7406. {
  7407. return SocketHelpers::bindSocketToPort (handle, port);
  7408. }
  7409. bool StreamingSocket::connect (const String& remoteHostName,
  7410. const int remotePortNumber,
  7411. const int timeOutMillisecs)
  7412. {
  7413. if (isListener)
  7414. {
  7415. jassertfalse; // a listener socket can't connect to another one!
  7416. return false;
  7417. }
  7418. if (connected)
  7419. close();
  7420. hostName = remoteHostName;
  7421. portNumber = remotePortNumber;
  7422. isListener = false;
  7423. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7424. remotePortNumber, timeOutMillisecs);
  7425. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7426. {
  7427. close();
  7428. return false;
  7429. }
  7430. return true;
  7431. }
  7432. void StreamingSocket::close()
  7433. {
  7434. #if JUCE_WINDOWS
  7435. if (handle != SOCKET_ERROR || connected)
  7436. closesocket (handle);
  7437. connected = false;
  7438. #else
  7439. if (connected)
  7440. {
  7441. connected = false;
  7442. if (isListener)
  7443. {
  7444. // need to do this to interrupt the accept() function..
  7445. StreamingSocket temp;
  7446. temp.connect ("localhost", portNumber, 1000);
  7447. }
  7448. }
  7449. if (handle != -1)
  7450. ::close (handle);
  7451. #endif
  7452. hostName = String::empty;
  7453. portNumber = 0;
  7454. handle = -1;
  7455. isListener = false;
  7456. }
  7457. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7458. {
  7459. if (connected)
  7460. close();
  7461. hostName = "listener";
  7462. portNumber = newPortNumber;
  7463. isListener = true;
  7464. struct sockaddr_in servTmpAddr;
  7465. zerostruct (servTmpAddr);
  7466. servTmpAddr.sin_family = PF_INET;
  7467. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7468. if (localHostName.isNotEmpty())
  7469. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7470. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7471. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7472. if (handle < 0)
  7473. return false;
  7474. const int reuse = 1;
  7475. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7476. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7477. || listen (handle, SOMAXCONN) < 0)
  7478. {
  7479. close();
  7480. return false;
  7481. }
  7482. connected = true;
  7483. return true;
  7484. }
  7485. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7486. {
  7487. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7488. // prepare this socket as a listener.
  7489. if (connected && isListener)
  7490. {
  7491. struct sockaddr address;
  7492. juce_socklen_t len = sizeof (sockaddr);
  7493. const int newSocket = (int) accept (handle, &address, &len);
  7494. if (newSocket >= 0 && connected)
  7495. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7496. portNumber, newSocket);
  7497. }
  7498. return 0;
  7499. }
  7500. bool StreamingSocket::isLocal() const throw()
  7501. {
  7502. return hostName == "127.0.0.1";
  7503. }
  7504. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7505. : portNumber (0),
  7506. handle (-1),
  7507. connected (true),
  7508. allowBroadcast (allowBroadcast_),
  7509. serverAddress (0)
  7510. {
  7511. #if JUCE_WINDOWS
  7512. SocketHelpers::initWin32Sockets();
  7513. #endif
  7514. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7515. bindToPort (localPortNumber);
  7516. }
  7517. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7518. const int handle_, const int localPortNumber)
  7519. : hostName (hostName_),
  7520. portNumber (portNumber_),
  7521. handle (handle_),
  7522. connected (true),
  7523. allowBroadcast (false),
  7524. serverAddress (0)
  7525. {
  7526. #if JUCE_WINDOWS
  7527. SocketHelpers::initWin32Sockets();
  7528. #endif
  7529. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7530. bindToPort (localPortNumber);
  7531. }
  7532. DatagramSocket::~DatagramSocket()
  7533. {
  7534. close();
  7535. delete static_cast <struct sockaddr_in*> (serverAddress);
  7536. serverAddress = 0;
  7537. }
  7538. void DatagramSocket::close()
  7539. {
  7540. #if JUCE_WINDOWS
  7541. closesocket (handle);
  7542. connected = false;
  7543. #else
  7544. connected = false;
  7545. ::close (handle);
  7546. #endif
  7547. hostName = String::empty;
  7548. portNumber = 0;
  7549. handle = -1;
  7550. }
  7551. bool DatagramSocket::bindToPort (const int port)
  7552. {
  7553. return SocketHelpers::bindSocketToPort (handle, port);
  7554. }
  7555. bool DatagramSocket::connect (const String& remoteHostName,
  7556. const int remotePortNumber,
  7557. const int timeOutMillisecs)
  7558. {
  7559. if (connected)
  7560. close();
  7561. hostName = remoteHostName;
  7562. portNumber = remotePortNumber;
  7563. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7564. remoteHostName, remotePortNumber,
  7565. timeOutMillisecs);
  7566. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7567. {
  7568. close();
  7569. return false;
  7570. }
  7571. return true;
  7572. }
  7573. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7574. {
  7575. struct sockaddr address;
  7576. juce_socklen_t len = sizeof (sockaddr);
  7577. while (waitUntilReady (true, -1) == 1)
  7578. {
  7579. char buf[1];
  7580. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7581. {
  7582. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7583. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7584. -1, -1);
  7585. }
  7586. }
  7587. return 0;
  7588. }
  7589. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7590. const int timeoutMsecs) const
  7591. {
  7592. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7593. : -1;
  7594. }
  7595. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7596. {
  7597. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7598. : -1;
  7599. }
  7600. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7601. {
  7602. // You need to call connect() first to set the server address..
  7603. jassert (serverAddress != 0 && connected);
  7604. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7605. numBytesToWrite, 0,
  7606. (const struct sockaddr*) serverAddress,
  7607. sizeof (struct sockaddr_in))
  7608. : -1;
  7609. }
  7610. bool DatagramSocket::isLocal() const throw()
  7611. {
  7612. return hostName == "127.0.0.1";
  7613. }
  7614. #if JUCE_MSVC
  7615. #pragma warning (pop)
  7616. #endif
  7617. END_JUCE_NAMESPACE
  7618. /*** End of inlined file: juce_Socket.cpp ***/
  7619. /*** Start of inlined file: juce_URL.cpp ***/
  7620. BEGIN_JUCE_NAMESPACE
  7621. URL::URL()
  7622. {
  7623. }
  7624. URL::URL (const String& url_)
  7625. : url (url_)
  7626. {
  7627. int i = url.indexOfChar ('?');
  7628. if (i >= 0)
  7629. {
  7630. do
  7631. {
  7632. const int nextAmp = url.indexOfChar (i + 1, '&');
  7633. const int equalsPos = url.indexOfChar (i + 1, '=');
  7634. if (equalsPos > i + 1)
  7635. {
  7636. if (nextAmp < 0)
  7637. {
  7638. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7639. removeEscapeChars (url.substring (equalsPos + 1)));
  7640. }
  7641. else if (nextAmp > 0 && equalsPos < nextAmp)
  7642. {
  7643. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7644. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7645. }
  7646. }
  7647. i = nextAmp;
  7648. }
  7649. while (i >= 0);
  7650. url = url.upToFirstOccurrenceOf ("?", false, false);
  7651. }
  7652. }
  7653. URL::URL (const URL& other)
  7654. : url (other.url),
  7655. postData (other.postData),
  7656. parameters (other.parameters),
  7657. filesToUpload (other.filesToUpload),
  7658. mimeTypes (other.mimeTypes)
  7659. {
  7660. }
  7661. URL& URL::operator= (const URL& other)
  7662. {
  7663. url = other.url;
  7664. postData = other.postData;
  7665. parameters = other.parameters;
  7666. filesToUpload = other.filesToUpload;
  7667. mimeTypes = other.mimeTypes;
  7668. return *this;
  7669. }
  7670. URL::~URL()
  7671. {
  7672. }
  7673. namespace URLHelpers
  7674. {
  7675. const String getMangledParameters (const StringPairArray& parameters)
  7676. {
  7677. String p;
  7678. for (int i = 0; i < parameters.size(); ++i)
  7679. {
  7680. if (i > 0)
  7681. p << '&';
  7682. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7683. << '='
  7684. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7685. }
  7686. return p;
  7687. }
  7688. int findStartOfDomain (const String& url)
  7689. {
  7690. int i = 0;
  7691. while (CharacterFunctions::isLetterOrDigit (url[i])
  7692. || url[i] == '+' || url[i] == '-' || url[i] == '.')
  7693. ++i;
  7694. return url[i] == ':' ? i + 1 : 0;
  7695. }
  7696. void createHeadersAndPostData (const URL& url, String& headers, MemoryBlock& postData)
  7697. {
  7698. MemoryOutputStream data (postData, false);
  7699. if (url.getFilesToUpload().size() > 0)
  7700. {
  7701. // need to upload some files, so do it as multi-part...
  7702. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7703. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7704. data << "--" << boundary;
  7705. int i;
  7706. for (i = 0; i < url.getParameters().size(); ++i)
  7707. {
  7708. data << "\r\nContent-Disposition: form-data; name=\""
  7709. << url.getParameters().getAllKeys() [i]
  7710. << "\"\r\n\r\n"
  7711. << url.getParameters().getAllValues() [i]
  7712. << "\r\n--"
  7713. << boundary;
  7714. }
  7715. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7716. {
  7717. const File file (url.getFilesToUpload().getAllValues() [i]);
  7718. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7719. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7720. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7721. const String mimeType (url.getMimeTypesOfUploadFiles()
  7722. .getValue (paramName, String::empty));
  7723. if (mimeType.isNotEmpty())
  7724. data << "Content-Type: " << mimeType << "\r\n";
  7725. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7726. << file << "\r\n--" << boundary;
  7727. }
  7728. data << "--\r\n";
  7729. data.flush();
  7730. }
  7731. else
  7732. {
  7733. data << getMangledParameters (url.getParameters()) << url.getPostData();
  7734. data.flush();
  7735. // just a short text attachment, so use simple url encoding..
  7736. headers << "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7737. << (int) postData.getSize() << "\r\n";
  7738. }
  7739. }
  7740. }
  7741. const String URL::toString (const bool includeGetParameters) const
  7742. {
  7743. if (includeGetParameters && parameters.size() > 0)
  7744. return url + "?" + URLHelpers::getMangledParameters (parameters);
  7745. else
  7746. return url;
  7747. }
  7748. bool URL::isWellFormed() const
  7749. {
  7750. //xxx TODO
  7751. return url.isNotEmpty();
  7752. }
  7753. const String URL::getDomain() const
  7754. {
  7755. int start = URLHelpers::findStartOfDomain (url);
  7756. while (url[start] == '/')
  7757. ++start;
  7758. const int end1 = url.indexOfChar (start, '/');
  7759. const int end2 = url.indexOfChar (start, ':');
  7760. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7761. : jmin (end1, end2);
  7762. return url.substring (start, end);
  7763. }
  7764. const String URL::getSubPath() const
  7765. {
  7766. int start = URLHelpers::findStartOfDomain (url);
  7767. while (url[start] == '/')
  7768. ++start;
  7769. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7770. return startOfPath <= 0 ? String::empty
  7771. : url.substring (startOfPath);
  7772. }
  7773. const String URL::getScheme() const
  7774. {
  7775. return url.substring (0, URLHelpers::findStartOfDomain (url) - 1);
  7776. }
  7777. const URL URL::withNewSubPath (const String& newPath) const
  7778. {
  7779. int start = URLHelpers::findStartOfDomain (url);
  7780. while (url[start] == '/')
  7781. ++start;
  7782. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7783. URL u (*this);
  7784. if (startOfPath > 0)
  7785. u.url = url.substring (0, startOfPath);
  7786. if (! u.url.endsWithChar ('/'))
  7787. u.url << '/';
  7788. if (newPath.startsWithChar ('/'))
  7789. u.url << newPath.substring (1);
  7790. else
  7791. u.url << newPath;
  7792. return u;
  7793. }
  7794. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7795. {
  7796. const char* validProtocols[] = { "http:", "ftp:", "https:" };
  7797. for (int i = 0; i < numElementsInArray (validProtocols); ++i)
  7798. if (possibleURL.startsWithIgnoreCase (validProtocols[i]))
  7799. return true;
  7800. if (possibleURL.containsChar ('@')
  7801. || possibleURL.containsChar (' '))
  7802. return false;
  7803. const String topLevelDomain (possibleURL.upToFirstOccurrenceOf ("/", false, false)
  7804. .fromLastOccurrenceOf (".", false, false));
  7805. return topLevelDomain.isNotEmpty() && topLevelDomain.length() <= 3;
  7806. }
  7807. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7808. {
  7809. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7810. return atSign > 0
  7811. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7812. && (! possibleEmailAddress.endsWithChar ('.'));
  7813. }
  7814. InputStream* URL::createInputStream (const bool usePostCommand,
  7815. OpenStreamProgressCallback* const progressCallback,
  7816. void* const progressCallbackContext,
  7817. const String& extraHeaders,
  7818. const int timeOutMs,
  7819. StringPairArray* const responseHeaders) const
  7820. {
  7821. String headers;
  7822. MemoryBlock headersAndPostData;
  7823. if (usePostCommand)
  7824. URLHelpers::createHeadersAndPostData (*this, headers, headersAndPostData);
  7825. headers += extraHeaders;
  7826. if (! headers.endsWithChar ('\n'))
  7827. headers << "\r\n";
  7828. return createNativeStream (toString (! usePostCommand), usePostCommand, headersAndPostData,
  7829. progressCallback, progressCallbackContext,
  7830. headers, timeOutMs, responseHeaders);
  7831. }
  7832. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7833. const bool usePostCommand) const
  7834. {
  7835. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7836. if (in != 0)
  7837. {
  7838. in->readIntoMemoryBlock (destData);
  7839. return true;
  7840. }
  7841. return false;
  7842. }
  7843. const String URL::readEntireTextStream (const bool usePostCommand) const
  7844. {
  7845. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7846. if (in != 0)
  7847. return in->readEntireStreamAsString();
  7848. return String::empty;
  7849. }
  7850. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7851. {
  7852. return XmlDocument::parse (readEntireTextStream (usePostCommand));
  7853. }
  7854. const URL URL::withParameter (const String& parameterName,
  7855. const String& parameterValue) const
  7856. {
  7857. URL u (*this);
  7858. u.parameters.set (parameterName, parameterValue);
  7859. return u;
  7860. }
  7861. const URL URL::withFileToUpload (const String& parameterName,
  7862. const File& fileToUpload,
  7863. const String& mimeType) const
  7864. {
  7865. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7866. URL u (*this);
  7867. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7868. u.mimeTypes.set (parameterName, mimeType);
  7869. return u;
  7870. }
  7871. const URL URL::withPOSTData (const String& postData_) const
  7872. {
  7873. URL u (*this);
  7874. u.postData = postData_;
  7875. return u;
  7876. }
  7877. const StringPairArray& URL::getParameters() const
  7878. {
  7879. return parameters;
  7880. }
  7881. const StringPairArray& URL::getFilesToUpload() const
  7882. {
  7883. return filesToUpload;
  7884. }
  7885. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7886. {
  7887. return mimeTypes;
  7888. }
  7889. const String URL::removeEscapeChars (const String& s)
  7890. {
  7891. String result (s.replaceCharacter ('+', ' '));
  7892. if (! result.containsChar ('%'))
  7893. return result;
  7894. // We need to operate on the string as raw UTF8 chars, and then recombine them into unicode
  7895. // after all the replacements have been made, so that multi-byte chars are handled.
  7896. Array<char> utf8 (result.toUTF8().getAddress(), result.getNumBytesAsUTF8());
  7897. for (int i = 0; i < utf8.size(); ++i)
  7898. {
  7899. if (utf8.getUnchecked(i) == '%')
  7900. {
  7901. const int hexDigit1 = CharacterFunctions::getHexDigitValue (utf8 [i + 1]);
  7902. const int hexDigit2 = CharacterFunctions::getHexDigitValue (utf8 [i + 2]);
  7903. if (hexDigit1 >= 0 && hexDigit2 >= 0)
  7904. {
  7905. utf8.set (i, (char) ((hexDigit1 << 4) + hexDigit2));
  7906. utf8.removeRange (i + 1, 2);
  7907. }
  7908. }
  7909. }
  7910. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7911. }
  7912. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7913. {
  7914. const CharPointer_UTF8 legalChars (isParameter ? "_-.*!'()"
  7915. : ",$_-.*!'()");
  7916. Array<char> utf8 (s.toUTF8().getAddress(), s.getNumBytesAsUTF8());
  7917. for (int i = 0; i < utf8.size(); ++i)
  7918. {
  7919. const char c = utf8.getUnchecked(i);
  7920. if (! (CharacterFunctions::isLetterOrDigit (c)
  7921. || legalChars.indexOf ((juce_wchar) c) >= 0))
  7922. {
  7923. if (c == ' ')
  7924. {
  7925. utf8.set (i, '+');
  7926. }
  7927. else
  7928. {
  7929. static const char* const hexDigits = "0123456789abcdef";
  7930. utf8.set (i, '%');
  7931. utf8.insert (++i, hexDigits [((uint8) c) >> 4]);
  7932. utf8.insert (++i, hexDigits [c & 15]);
  7933. }
  7934. }
  7935. }
  7936. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7937. }
  7938. bool URL::launchInDefaultBrowser() const
  7939. {
  7940. String u (toString (true));
  7941. if (u.containsChar ('@') && ! u.containsChar (':'))
  7942. u = "mailto:" + u;
  7943. return PlatformUtilities::openDocument (u, String::empty);
  7944. }
  7945. END_JUCE_NAMESPACE
  7946. /*** End of inlined file: juce_URL.cpp ***/
  7947. /*** Start of inlined file: juce_MACAddress.cpp ***/
  7948. BEGIN_JUCE_NAMESPACE
  7949. MACAddress::MACAddress()
  7950. : asInt64 (0)
  7951. {
  7952. }
  7953. MACAddress::MACAddress (const MACAddress& other)
  7954. : asInt64 (other.asInt64)
  7955. {
  7956. }
  7957. MACAddress& MACAddress::operator= (const MACAddress& other)
  7958. {
  7959. asInt64 = other.asInt64;
  7960. return *this;
  7961. }
  7962. MACAddress::MACAddress (const uint8 bytes[6])
  7963. : asInt64 (0)
  7964. {
  7965. memcpy (asBytes, bytes, sizeof (asBytes));
  7966. }
  7967. const String MACAddress::toString() const
  7968. {
  7969. String s;
  7970. s.preallocateStorage (18);
  7971. for (int i = 0; i < numElementsInArray (asBytes); ++i)
  7972. {
  7973. s << String::toHexString ((int) asBytes[i]).paddedLeft ('0', 2);
  7974. if (i < numElementsInArray (asBytes) - 1)
  7975. s << '-';
  7976. }
  7977. return s;
  7978. }
  7979. int64 MACAddress::toInt64() const throw()
  7980. {
  7981. int64 n = 0;
  7982. for (int i = numElementsInArray (asBytes); --i >= 0;)
  7983. n = (n << 8) | asBytes[i];
  7984. return n;
  7985. }
  7986. bool MACAddress::isNull() const throw() { return asInt64 == 0; }
  7987. bool MACAddress::operator== (const MACAddress& other) const throw() { return asInt64 == other.asInt64; }
  7988. bool MACAddress::operator!= (const MACAddress& other) const throw() { return asInt64 != other.asInt64; }
  7989. END_JUCE_NAMESPACE
  7990. /*** End of inlined file: juce_MACAddress.cpp ***/
  7991. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  7992. BEGIN_JUCE_NAMESPACE
  7993. namespace
  7994. {
  7995. int calcBufferStreamBufferSize (int requestedSize, InputStream* const source) throw()
  7996. {
  7997. // You need to supply a real stream when creating a BufferedInputStream
  7998. jassert (source != 0);
  7999. requestedSize = jmax (256, requestedSize);
  8000. const int64 sourceSize = source->getTotalLength();
  8001. if (sourceSize >= 0 && sourceSize < requestedSize)
  8002. requestedSize = jmax (32, (int) sourceSize);
  8003. return requestedSize;
  8004. }
  8005. }
  8006. BufferedInputStream::BufferedInputStream (InputStream* const sourceStream, const int bufferSize_,
  8007. const bool deleteSourceWhenDestroyed)
  8008. : source (sourceStream),
  8009. sourceToDelete (deleteSourceWhenDestroyed ? sourceStream : 0),
  8010. bufferSize (calcBufferStreamBufferSize (bufferSize_, sourceStream)),
  8011. position (sourceStream->getPosition()),
  8012. lastReadPos (0),
  8013. bufferStart (position),
  8014. bufferOverlap (128)
  8015. {
  8016. buffer.malloc (bufferSize);
  8017. }
  8018. BufferedInputStream::BufferedInputStream (InputStream& sourceStream, const int bufferSize_)
  8019. : source (&sourceStream),
  8020. bufferSize (calcBufferStreamBufferSize (bufferSize_, &sourceStream)),
  8021. position (sourceStream.getPosition()),
  8022. lastReadPos (0),
  8023. bufferStart (position),
  8024. bufferOverlap (128)
  8025. {
  8026. buffer.malloc (bufferSize);
  8027. }
  8028. BufferedInputStream::~BufferedInputStream()
  8029. {
  8030. }
  8031. int64 BufferedInputStream::getTotalLength()
  8032. {
  8033. return source->getTotalLength();
  8034. }
  8035. int64 BufferedInputStream::getPosition()
  8036. {
  8037. return position;
  8038. }
  8039. bool BufferedInputStream::setPosition (int64 newPosition)
  8040. {
  8041. position = jmax ((int64) 0, newPosition);
  8042. return true;
  8043. }
  8044. bool BufferedInputStream::isExhausted()
  8045. {
  8046. return (position >= lastReadPos)
  8047. && source->isExhausted();
  8048. }
  8049. void BufferedInputStream::ensureBuffered()
  8050. {
  8051. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  8052. if (position < bufferStart || position >= bufferEndOverlap)
  8053. {
  8054. int bytesRead;
  8055. if (position < lastReadPos
  8056. && position >= bufferEndOverlap
  8057. && position >= bufferStart)
  8058. {
  8059. const int bytesToKeep = (int) (lastReadPos - position);
  8060. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  8061. bufferStart = position;
  8062. bytesRead = source->read (buffer + bytesToKeep,
  8063. bufferSize - bytesToKeep);
  8064. lastReadPos += bytesRead;
  8065. bytesRead += bytesToKeep;
  8066. }
  8067. else
  8068. {
  8069. bufferStart = position;
  8070. source->setPosition (bufferStart);
  8071. bytesRead = source->read (buffer, bufferSize);
  8072. lastReadPos = bufferStart + bytesRead;
  8073. }
  8074. while (bytesRead < bufferSize)
  8075. buffer [bytesRead++] = 0;
  8076. }
  8077. }
  8078. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  8079. {
  8080. if (position >= bufferStart
  8081. && position + maxBytesToRead <= lastReadPos)
  8082. {
  8083. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  8084. position += maxBytesToRead;
  8085. return maxBytesToRead;
  8086. }
  8087. else
  8088. {
  8089. if (position < bufferStart || position >= lastReadPos)
  8090. ensureBuffered();
  8091. int bytesRead = 0;
  8092. while (maxBytesToRead > 0)
  8093. {
  8094. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  8095. if (bytesAvailable > 0)
  8096. {
  8097. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  8098. maxBytesToRead -= bytesAvailable;
  8099. bytesRead += bytesAvailable;
  8100. position += bytesAvailable;
  8101. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  8102. }
  8103. const int64 oldLastReadPos = lastReadPos;
  8104. ensureBuffered();
  8105. if (oldLastReadPos == lastReadPos)
  8106. break; // if ensureBuffered() failed to read any more data, bail out
  8107. if (isExhausted())
  8108. break;
  8109. }
  8110. return bytesRead;
  8111. }
  8112. }
  8113. const String BufferedInputStream::readString()
  8114. {
  8115. if (position >= bufferStart
  8116. && position < lastReadPos)
  8117. {
  8118. const int maxChars = (int) (lastReadPos - position);
  8119. const char* const src = buffer + (int) (position - bufferStart);
  8120. for (int i = 0; i < maxChars; ++i)
  8121. {
  8122. if (src[i] == 0)
  8123. {
  8124. position += i + 1;
  8125. return String::fromUTF8 (src, i);
  8126. }
  8127. }
  8128. }
  8129. return InputStream::readString();
  8130. }
  8131. END_JUCE_NAMESPACE
  8132. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  8133. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  8134. BEGIN_JUCE_NAMESPACE
  8135. FileInputSource::FileInputSource (const File& file_, bool useFileTimeInHashGeneration_)
  8136. : file (file_), useFileTimeInHashGeneration (useFileTimeInHashGeneration_)
  8137. {
  8138. }
  8139. FileInputSource::~FileInputSource()
  8140. {
  8141. }
  8142. InputStream* FileInputSource::createInputStream()
  8143. {
  8144. return file.createInputStream();
  8145. }
  8146. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  8147. {
  8148. return file.getSiblingFile (relatedItemPath).createInputStream();
  8149. }
  8150. int64 FileInputSource::hashCode() const
  8151. {
  8152. int64 h = file.hashCode();
  8153. if (useFileTimeInHashGeneration)
  8154. h ^= file.getLastModificationTime().toMilliseconds();
  8155. return h;
  8156. }
  8157. END_JUCE_NAMESPACE
  8158. /*** End of inlined file: juce_FileInputSource.cpp ***/
  8159. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  8160. BEGIN_JUCE_NAMESPACE
  8161. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  8162. const size_t sourceDataSize,
  8163. const bool keepInternalCopy)
  8164. : data (static_cast <const char*> (sourceData)),
  8165. dataSize (sourceDataSize),
  8166. position (0)
  8167. {
  8168. if (keepInternalCopy)
  8169. {
  8170. internalCopy.append (data, sourceDataSize);
  8171. data = static_cast <const char*> (internalCopy.getData());
  8172. }
  8173. }
  8174. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  8175. const bool keepInternalCopy)
  8176. : data (static_cast <const char*> (sourceData.getData())),
  8177. dataSize (sourceData.getSize()),
  8178. position (0)
  8179. {
  8180. if (keepInternalCopy)
  8181. {
  8182. internalCopy = sourceData;
  8183. data = static_cast <const char*> (internalCopy.getData());
  8184. }
  8185. }
  8186. MemoryInputStream::~MemoryInputStream()
  8187. {
  8188. }
  8189. int64 MemoryInputStream::getTotalLength()
  8190. {
  8191. return dataSize;
  8192. }
  8193. int MemoryInputStream::read (void* const buffer, const int howMany)
  8194. {
  8195. jassert (howMany >= 0);
  8196. const int num = jmin (howMany, (int) (dataSize - position));
  8197. memcpy (buffer, data + position, num);
  8198. position += num;
  8199. return (int) num;
  8200. }
  8201. bool MemoryInputStream::isExhausted()
  8202. {
  8203. return (position >= dataSize);
  8204. }
  8205. bool MemoryInputStream::setPosition (const int64 pos)
  8206. {
  8207. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  8208. return true;
  8209. }
  8210. int64 MemoryInputStream::getPosition()
  8211. {
  8212. return position;
  8213. }
  8214. #if JUCE_UNIT_TESTS
  8215. class MemoryStreamTests : public UnitTest
  8216. {
  8217. public:
  8218. MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream") {}
  8219. void runTest()
  8220. {
  8221. beginTest ("Basics");
  8222. int randomInt = Random::getSystemRandom().nextInt();
  8223. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  8224. double randomDouble = Random::getSystemRandom().nextDouble();
  8225. String randomString;
  8226. for (int i = 50; --i >= 0;)
  8227. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  8228. MemoryOutputStream mo;
  8229. mo.writeInt (randomInt);
  8230. mo.writeIntBigEndian (randomInt);
  8231. mo.writeCompressedInt (randomInt);
  8232. mo.writeString (randomString);
  8233. mo.writeInt64 (randomInt64);
  8234. mo.writeInt64BigEndian (randomInt64);
  8235. mo.writeDouble (randomDouble);
  8236. mo.writeDoubleBigEndian (randomDouble);
  8237. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  8238. expect (mi.readInt() == randomInt);
  8239. expect (mi.readIntBigEndian() == randomInt);
  8240. expect (mi.readCompressedInt() == randomInt);
  8241. expect (mi.readString() == randomString);
  8242. expect (mi.readInt64() == randomInt64);
  8243. expect (mi.readInt64BigEndian() == randomInt64);
  8244. expect (mi.readDouble() == randomDouble);
  8245. expect (mi.readDoubleBigEndian() == randomDouble);
  8246. }
  8247. };
  8248. static MemoryStreamTests memoryInputStreamUnitTests;
  8249. #endif
  8250. END_JUCE_NAMESPACE
  8251. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  8252. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  8253. BEGIN_JUCE_NAMESPACE
  8254. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  8255. : data (internalBlock),
  8256. position (0),
  8257. size (0)
  8258. {
  8259. internalBlock.setSize (initialSize, false);
  8260. }
  8261. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  8262. const bool appendToExistingBlockContent)
  8263. : data (memoryBlockToWriteTo),
  8264. position (0),
  8265. size (0)
  8266. {
  8267. if (appendToExistingBlockContent)
  8268. position = size = memoryBlockToWriteTo.getSize();
  8269. }
  8270. MemoryOutputStream::~MemoryOutputStream()
  8271. {
  8272. flush();
  8273. }
  8274. void MemoryOutputStream::flush()
  8275. {
  8276. if (&data != &internalBlock)
  8277. data.setSize (size, false);
  8278. }
  8279. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  8280. {
  8281. data.ensureSize (bytesToPreallocate + 1);
  8282. }
  8283. void MemoryOutputStream::reset() throw()
  8284. {
  8285. position = 0;
  8286. size = 0;
  8287. }
  8288. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  8289. {
  8290. if (howMany > 0)
  8291. {
  8292. const size_t storageNeeded = position + howMany;
  8293. if (storageNeeded >= data.getSize())
  8294. data.ensureSize ((storageNeeded + jmin ((int) (storageNeeded / 2), 1024 * 1024) + 32) & ~31);
  8295. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  8296. position += howMany;
  8297. size = jmax (size, position);
  8298. }
  8299. return true;
  8300. }
  8301. const void* MemoryOutputStream::getData() const throw()
  8302. {
  8303. void* const d = data.getData();
  8304. if (data.getSize() > size)
  8305. static_cast <char*> (d) [size] = 0;
  8306. return d;
  8307. }
  8308. bool MemoryOutputStream::setPosition (int64 newPosition)
  8309. {
  8310. if (newPosition <= (int64) size)
  8311. {
  8312. // ok to seek backwards
  8313. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  8314. return true;
  8315. }
  8316. else
  8317. {
  8318. // trying to make it bigger isn't a good thing to do..
  8319. return false;
  8320. }
  8321. }
  8322. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  8323. {
  8324. // before writing from an input, see if we can preallocate to make it more efficient..
  8325. int64 availableData = source.getTotalLength() - source.getPosition();
  8326. if (availableData > 0)
  8327. {
  8328. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  8329. availableData = maxNumBytesToWrite;
  8330. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  8331. }
  8332. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  8333. }
  8334. const String MemoryOutputStream::toUTF8() const
  8335. {
  8336. return String::fromUTF8 (static_cast <const char*> (getData()), getDataSize());
  8337. }
  8338. const String MemoryOutputStream::toString() const
  8339. {
  8340. return String::createStringFromData (getData(), (int) getDataSize());
  8341. }
  8342. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  8343. {
  8344. stream.write (streamToRead.getData(), (int) streamToRead.getDataSize());
  8345. return stream;
  8346. }
  8347. END_JUCE_NAMESPACE
  8348. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  8349. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  8350. BEGIN_JUCE_NAMESPACE
  8351. SubregionStream::SubregionStream (InputStream* const sourceStream,
  8352. const int64 startPositionInSourceStream_,
  8353. const int64 lengthOfSourceStream_,
  8354. const bool deleteSourceWhenDestroyed)
  8355. : source (sourceStream),
  8356. startPositionInSourceStream (startPositionInSourceStream_),
  8357. lengthOfSourceStream (lengthOfSourceStream_)
  8358. {
  8359. if (deleteSourceWhenDestroyed)
  8360. sourceToDelete = source;
  8361. setPosition (0);
  8362. }
  8363. SubregionStream::~SubregionStream()
  8364. {
  8365. }
  8366. int64 SubregionStream::getTotalLength()
  8367. {
  8368. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  8369. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  8370. : srcLen;
  8371. }
  8372. int64 SubregionStream::getPosition()
  8373. {
  8374. return source->getPosition() - startPositionInSourceStream;
  8375. }
  8376. bool SubregionStream::setPosition (int64 newPosition)
  8377. {
  8378. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  8379. }
  8380. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  8381. {
  8382. if (lengthOfSourceStream < 0)
  8383. {
  8384. return source->read (destBuffer, maxBytesToRead);
  8385. }
  8386. else
  8387. {
  8388. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  8389. if (maxBytesToRead <= 0)
  8390. return 0;
  8391. return source->read (destBuffer, maxBytesToRead);
  8392. }
  8393. }
  8394. bool SubregionStream::isExhausted()
  8395. {
  8396. if (lengthOfSourceStream >= 0)
  8397. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  8398. else
  8399. return source->isExhausted();
  8400. }
  8401. END_JUCE_NAMESPACE
  8402. /*** End of inlined file: juce_SubregionStream.cpp ***/
  8403. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  8404. BEGIN_JUCE_NAMESPACE
  8405. PerformanceCounter::PerformanceCounter (const String& name_,
  8406. int runsPerPrintout,
  8407. const File& loggingFile)
  8408. : name (name_),
  8409. numRuns (0),
  8410. runsPerPrint (runsPerPrintout),
  8411. totalTime (0),
  8412. outputFile (loggingFile)
  8413. {
  8414. if (outputFile != File::nonexistent)
  8415. {
  8416. String s ("**** Counter for \"");
  8417. s << name_ << "\" started at: "
  8418. << Time::getCurrentTime().toString (true, true)
  8419. << newLine;
  8420. outputFile.appendText (s, false, false);
  8421. }
  8422. }
  8423. PerformanceCounter::~PerformanceCounter()
  8424. {
  8425. printStatistics();
  8426. }
  8427. void PerformanceCounter::start()
  8428. {
  8429. started = Time::getHighResolutionTicks();
  8430. }
  8431. void PerformanceCounter::stop()
  8432. {
  8433. const int64 now = Time::getHighResolutionTicks();
  8434. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8435. if (++numRuns == runsPerPrint)
  8436. printStatistics();
  8437. }
  8438. void PerformanceCounter::printStatistics()
  8439. {
  8440. if (numRuns > 0)
  8441. {
  8442. String s ("Performance count for \"");
  8443. s << name << "\" - average over " << numRuns << " run(s) = ";
  8444. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8445. if (micros > 10000)
  8446. s << (micros/1000) << " millisecs";
  8447. else
  8448. s << micros << " microsecs";
  8449. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8450. Logger::outputDebugString (s);
  8451. s << newLine;
  8452. if (outputFile != File::nonexistent)
  8453. outputFile.appendText (s, false, false);
  8454. numRuns = 0;
  8455. totalTime = 0;
  8456. }
  8457. }
  8458. END_JUCE_NAMESPACE
  8459. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8460. /*** Start of inlined file: juce_Uuid.cpp ***/
  8461. BEGIN_JUCE_NAMESPACE
  8462. Uuid::Uuid()
  8463. {
  8464. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8465. // to make it very very unlikely that two UUIDs will ever be the same..
  8466. static int64 macAddresses[2];
  8467. static bool hasCheckedMacAddresses = false;
  8468. if (! hasCheckedMacAddresses)
  8469. {
  8470. hasCheckedMacAddresses = true;
  8471. Array<MACAddress> result;
  8472. MACAddress::findAllAddresses (result);
  8473. for (int i = 0; i < numElementsInArray (macAddresses); ++i)
  8474. macAddresses[i] = result[i].toInt64();
  8475. }
  8476. value.asInt64[0] = macAddresses[0];
  8477. value.asInt64[1] = macAddresses[1];
  8478. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8479. // whose seed will carry over between calls to this method.
  8480. Random r (macAddresses[0] ^ macAddresses[1]
  8481. ^ Random::getSystemRandom().nextInt64());
  8482. for (int i = 4; --i >= 0;)
  8483. {
  8484. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8485. value.asInt[i] ^= r.nextInt();
  8486. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8487. }
  8488. }
  8489. Uuid::~Uuid() throw()
  8490. {
  8491. }
  8492. Uuid::Uuid (const Uuid& other)
  8493. : value (other.value)
  8494. {
  8495. }
  8496. Uuid& Uuid::operator= (const Uuid& other)
  8497. {
  8498. value = other.value;
  8499. return *this;
  8500. }
  8501. bool Uuid::operator== (const Uuid& other) const
  8502. {
  8503. return value.asInt64[0] == other.value.asInt64[0]
  8504. && value.asInt64[1] == other.value.asInt64[1];
  8505. }
  8506. bool Uuid::operator!= (const Uuid& other) const
  8507. {
  8508. return ! operator== (other);
  8509. }
  8510. bool Uuid::isNull() const throw()
  8511. {
  8512. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8513. }
  8514. const String Uuid::toString() const
  8515. {
  8516. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8517. }
  8518. Uuid::Uuid (const String& uuidString)
  8519. {
  8520. operator= (uuidString);
  8521. }
  8522. Uuid& Uuid::operator= (const String& uuidString)
  8523. {
  8524. MemoryBlock mb;
  8525. mb.loadFromHexString (uuidString);
  8526. mb.ensureSize (sizeof (value.asBytes), true);
  8527. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8528. return *this;
  8529. }
  8530. Uuid::Uuid (const uint8* const rawData)
  8531. {
  8532. operator= (rawData);
  8533. }
  8534. Uuid& Uuid::operator= (const uint8* const rawData)
  8535. {
  8536. if (rawData != 0)
  8537. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8538. else
  8539. zeromem (value.asBytes, sizeof (value.asBytes));
  8540. return *this;
  8541. }
  8542. END_JUCE_NAMESPACE
  8543. /*** End of inlined file: juce_Uuid.cpp ***/
  8544. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8545. BEGIN_JUCE_NAMESPACE
  8546. class ZipFile::ZipEntryInfo
  8547. {
  8548. public:
  8549. ZipFile::ZipEntry entry;
  8550. int streamOffset;
  8551. int compressedSize;
  8552. bool compressed;
  8553. };
  8554. class ZipFile::ZipInputStream : public InputStream
  8555. {
  8556. public:
  8557. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8558. : file (file_),
  8559. zipEntryInfo (zei),
  8560. pos (0),
  8561. headerSize (0),
  8562. inputStream (0)
  8563. {
  8564. inputStream = file_.inputStream;
  8565. if (file_.inputSource != 0)
  8566. {
  8567. inputStream = streamToDelete = file.inputSource->createInputStream();
  8568. }
  8569. else
  8570. {
  8571. #if JUCE_DEBUG
  8572. file_.numOpenStreams++;
  8573. #endif
  8574. }
  8575. char buffer [30];
  8576. if (inputStream != 0
  8577. && inputStream->setPosition (zei.streamOffset)
  8578. && inputStream->read (buffer, 30) == 30
  8579. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8580. {
  8581. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8582. + ByteOrder::littleEndianShort (buffer + 28);
  8583. }
  8584. }
  8585. ~ZipInputStream()
  8586. {
  8587. #if JUCE_DEBUG
  8588. if (inputStream != 0 && inputStream == file.inputStream)
  8589. file.numOpenStreams--;
  8590. #endif
  8591. }
  8592. int64 getTotalLength()
  8593. {
  8594. return zipEntryInfo.compressedSize;
  8595. }
  8596. int read (void* buffer, int howMany)
  8597. {
  8598. if (headerSize <= 0)
  8599. return 0;
  8600. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8601. if (inputStream == 0)
  8602. return 0;
  8603. int num;
  8604. if (inputStream == file.inputStream)
  8605. {
  8606. const ScopedLock sl (file.lock);
  8607. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8608. num = inputStream->read (buffer, howMany);
  8609. }
  8610. else
  8611. {
  8612. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8613. num = inputStream->read (buffer, howMany);
  8614. }
  8615. pos += num;
  8616. return num;
  8617. }
  8618. bool isExhausted()
  8619. {
  8620. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8621. }
  8622. int64 getPosition()
  8623. {
  8624. return pos;
  8625. }
  8626. bool setPosition (int64 newPos)
  8627. {
  8628. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8629. return true;
  8630. }
  8631. private:
  8632. ZipFile& file;
  8633. ZipEntryInfo zipEntryInfo;
  8634. int64 pos;
  8635. int headerSize;
  8636. InputStream* inputStream;
  8637. ScopedPointer<InputStream> streamToDelete;
  8638. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipInputStream);
  8639. };
  8640. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8641. : inputStream (source_)
  8642. #if JUCE_DEBUG
  8643. , numOpenStreams (0)
  8644. #endif
  8645. {
  8646. if (deleteStreamWhenDestroyed)
  8647. streamToDelete = inputStream;
  8648. init();
  8649. }
  8650. ZipFile::ZipFile (const File& file)
  8651. : inputStream (0)
  8652. #if JUCE_DEBUG
  8653. , numOpenStreams (0)
  8654. #endif
  8655. {
  8656. inputSource = new FileInputSource (file);
  8657. init();
  8658. }
  8659. ZipFile::ZipFile (InputSource* const inputSource_)
  8660. : inputStream (0),
  8661. inputSource (inputSource_)
  8662. #if JUCE_DEBUG
  8663. , numOpenStreams (0)
  8664. #endif
  8665. {
  8666. init();
  8667. }
  8668. ZipFile::~ZipFile()
  8669. {
  8670. #if JUCE_DEBUG
  8671. entries.clear();
  8672. /* If you hit this assertion, it means you've created a stream to read one of the items in the
  8673. zipfile, but you've forgotten to delete that stream object before deleting the file..
  8674. Streams can't be kept open after the file is deleted because they need to share the input
  8675. stream that the file uses to read itself.
  8676. */
  8677. jassert (numOpenStreams == 0);
  8678. #endif
  8679. }
  8680. int ZipFile::getNumEntries() const throw()
  8681. {
  8682. return entries.size();
  8683. }
  8684. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8685. {
  8686. ZipEntryInfo* const zei = entries [index];
  8687. return zei != 0 ? &(zei->entry) : 0;
  8688. }
  8689. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8690. {
  8691. for (int i = 0; i < entries.size(); ++i)
  8692. if (entries.getUnchecked (i)->entry.filename == fileName)
  8693. return i;
  8694. return -1;
  8695. }
  8696. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8697. {
  8698. return getEntry (getIndexOfFileName (fileName));
  8699. }
  8700. InputStream* ZipFile::createStreamForEntry (const int index)
  8701. {
  8702. ZipEntryInfo* const zei = entries[index];
  8703. InputStream* stream = 0;
  8704. if (zei != 0)
  8705. {
  8706. stream = new ZipInputStream (*this, *zei);
  8707. if (zei->compressed)
  8708. {
  8709. stream = new GZIPDecompressorInputStream (stream, true, true,
  8710. zei->entry.uncompressedSize);
  8711. // (much faster to unzip in big blocks using a buffer..)
  8712. stream = new BufferedInputStream (stream, 32768, true);
  8713. }
  8714. }
  8715. return stream;
  8716. }
  8717. class ZipFile::ZipFilenameComparator
  8718. {
  8719. public:
  8720. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8721. {
  8722. return first->entry.filename.compare (second->entry.filename);
  8723. }
  8724. };
  8725. void ZipFile::sortEntriesByFilename()
  8726. {
  8727. ZipFilenameComparator sorter;
  8728. entries.sort (sorter);
  8729. }
  8730. void ZipFile::init()
  8731. {
  8732. ScopedPointer <InputStream> toDelete;
  8733. InputStream* in = inputStream;
  8734. if (inputSource != 0)
  8735. {
  8736. in = inputSource->createInputStream();
  8737. toDelete = in;
  8738. }
  8739. if (in != 0)
  8740. {
  8741. int numEntries = 0;
  8742. int pos = findEndOfZipEntryTable (*in, numEntries);
  8743. if (pos >= 0 && pos < in->getTotalLength())
  8744. {
  8745. const int size = (int) (in->getTotalLength() - pos);
  8746. in->setPosition (pos);
  8747. MemoryBlock headerData;
  8748. if (in->readIntoMemoryBlock (headerData, size) == size)
  8749. {
  8750. pos = 0;
  8751. for (int i = 0; i < numEntries; ++i)
  8752. {
  8753. if (pos + 46 > size)
  8754. break;
  8755. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8756. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8757. if (pos + 46 + fileNameLen > size)
  8758. break;
  8759. ZipEntryInfo* const zei = new ZipEntryInfo();
  8760. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8761. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8762. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8763. const int year = 1980 + (date >> 9);
  8764. const int month = ((date >> 5) & 15) - 1;
  8765. const int day = date & 31;
  8766. const int hours = time >> 11;
  8767. const int minutes = (time >> 5) & 63;
  8768. const int seconds = (time & 31) << 1;
  8769. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8770. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8771. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8772. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8773. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8774. entries.add (zei);
  8775. pos += 46 + fileNameLen
  8776. + ByteOrder::littleEndianShort (buffer + 30)
  8777. + ByteOrder::littleEndianShort (buffer + 32);
  8778. }
  8779. }
  8780. }
  8781. }
  8782. }
  8783. int ZipFile::findEndOfZipEntryTable (InputStream& input, int& numEntries)
  8784. {
  8785. BufferedInputStream in (input, 8192);
  8786. in.setPosition (in.getTotalLength());
  8787. int64 pos = in.getPosition();
  8788. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8789. char buffer [32];
  8790. zeromem (buffer, sizeof (buffer));
  8791. while (pos > lowestPos)
  8792. {
  8793. in.setPosition (pos - 22);
  8794. pos = in.getPosition();
  8795. memcpy (buffer + 22, buffer, 4);
  8796. if (in.read (buffer, 22) != 22)
  8797. return 0;
  8798. for (int i = 0; i < 22; ++i)
  8799. {
  8800. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8801. {
  8802. in.setPosition (pos + i);
  8803. in.read (buffer, 22);
  8804. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8805. return ByteOrder::littleEndianInt (buffer + 16);
  8806. }
  8807. }
  8808. }
  8809. return 0;
  8810. }
  8811. bool ZipFile::uncompressTo (const File& targetDirectory,
  8812. const bool shouldOverwriteFiles)
  8813. {
  8814. for (int i = 0; i < entries.size(); ++i)
  8815. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  8816. return false;
  8817. return true;
  8818. }
  8819. bool ZipFile::uncompressEntry (const int index,
  8820. const File& targetDirectory,
  8821. bool shouldOverwriteFiles)
  8822. {
  8823. const ZipEntryInfo* zei = entries [index];
  8824. if (zei != 0)
  8825. {
  8826. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  8827. if (zei->entry.filename.endsWithChar ('/'))
  8828. {
  8829. return targetFile.createDirectory(); // (entry is a directory, not a file)
  8830. }
  8831. else
  8832. {
  8833. ScopedPointer<InputStream> in (createStreamForEntry (index));
  8834. if (in != 0)
  8835. {
  8836. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  8837. return false;
  8838. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  8839. {
  8840. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  8841. if (out != 0)
  8842. {
  8843. out->writeFromInputStream (*in, -1);
  8844. out = 0;
  8845. targetFile.setCreationTime (zei->entry.fileTime);
  8846. targetFile.setLastModificationTime (zei->entry.fileTime);
  8847. targetFile.setLastAccessTime (zei->entry.fileTime);
  8848. return true;
  8849. }
  8850. }
  8851. }
  8852. }
  8853. }
  8854. return false;
  8855. }
  8856. END_JUCE_NAMESPACE
  8857. /*** End of inlined file: juce_ZipFile.cpp ***/
  8858. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8859. #if JUCE_MSVC
  8860. #pragma warning (push)
  8861. #pragma warning (disable: 4514 4996)
  8862. #endif
  8863. #if ! JUCE_ANDROID
  8864. #include <cwctype>
  8865. #endif
  8866. #include <cctype>
  8867. #include <ctime>
  8868. BEGIN_JUCE_NAMESPACE
  8869. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8870. {
  8871. return towupper ((wchar_t) character);
  8872. }
  8873. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8874. {
  8875. return towlower ((wchar_t) character);
  8876. }
  8877. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8878. {
  8879. #if JUCE_WINDOWS
  8880. return iswupper ((wchar_t) character) != 0;
  8881. #else
  8882. return toLowerCase (character) != character;
  8883. #endif
  8884. }
  8885. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8886. {
  8887. #if JUCE_WINDOWS
  8888. return iswlower ((wchar_t) character) != 0;
  8889. #else
  8890. return toUpperCase (character) != character;
  8891. #endif
  8892. }
  8893. bool CharacterFunctions::isWhitespace (const char character) throw()
  8894. {
  8895. return character == ' ' || (character <= 13 && character >= 9);
  8896. }
  8897. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  8898. {
  8899. return iswspace ((wchar_t) character) != 0;
  8900. }
  8901. bool CharacterFunctions::isDigit (const char character) throw()
  8902. {
  8903. return (character >= '0' && character <= '9');
  8904. }
  8905. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  8906. {
  8907. return iswdigit ((wchar_t) character) != 0;
  8908. }
  8909. bool CharacterFunctions::isLetter (const char character) throw()
  8910. {
  8911. return (character >= 'a' && character <= 'z')
  8912. || (character >= 'A' && character <= 'Z');
  8913. }
  8914. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  8915. {
  8916. return iswalpha ((wchar_t) character) != 0;
  8917. }
  8918. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  8919. {
  8920. return (character >= 'a' && character <= 'z')
  8921. || (character >= 'A' && character <= 'Z')
  8922. || (character >= '0' && character <= '9');
  8923. }
  8924. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  8925. {
  8926. return iswalnum ((wchar_t) character) != 0;
  8927. }
  8928. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  8929. {
  8930. unsigned int d = digit - '0';
  8931. if (d < (unsigned int) 10)
  8932. return (int) d;
  8933. d += (unsigned int) ('0' - 'a');
  8934. if (d < (unsigned int) 6)
  8935. return (int) d + 10;
  8936. d += (unsigned int) ('a' - 'A');
  8937. if (d < (unsigned int) 6)
  8938. return (int) d + 10;
  8939. return -1;
  8940. }
  8941. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  8942. {
  8943. return (int) strftime (dest, maxChars, format, tm);
  8944. }
  8945. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  8946. {
  8947. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  8948. return (int) wcsftime (dest, maxChars, format, tm);
  8949. #else
  8950. HeapBlock <char> tempDest;
  8951. tempDest.calloc (maxChars + 2);
  8952. int result = ftime (tempDest.getData(), maxChars, String (format).toUTF8(), tm);
  8953. CharPointer_UTF32 (dest).writeAll (CharPointer_UTF8 (tempDest.getData()));
  8954. return result;
  8955. #endif
  8956. }
  8957. #if JUCE_MSVC
  8958. #pragma warning (pop)
  8959. #endif
  8960. double CharacterFunctions::mulexp10 (const double value, int exponent) throw()
  8961. {
  8962. if (exponent == 0)
  8963. return value;
  8964. if (value == 0)
  8965. return 0;
  8966. const bool negative = (exponent < 0);
  8967. if (negative)
  8968. exponent = -exponent;
  8969. double result = 1.0, power = 10.0;
  8970. for (int bit = 1; exponent != 0; bit <<= 1)
  8971. {
  8972. if ((exponent & bit) != 0)
  8973. {
  8974. exponent ^= bit;
  8975. result *= power;
  8976. if (exponent == 0)
  8977. break;
  8978. }
  8979. power *= power;
  8980. }
  8981. return negative ? (value / result) : (value * result);
  8982. }
  8983. END_JUCE_NAMESPACE
  8984. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  8985. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  8986. BEGIN_JUCE_NAMESPACE
  8987. LocalisedStrings::LocalisedStrings (const String& fileContents)
  8988. {
  8989. loadFromText (fileContents);
  8990. }
  8991. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  8992. {
  8993. loadFromText (fileToLoad.loadFileAsString());
  8994. }
  8995. LocalisedStrings::~LocalisedStrings()
  8996. {
  8997. }
  8998. const String LocalisedStrings::translate (const String& text) const
  8999. {
  9000. return translations.getValue (text, text);
  9001. }
  9002. namespace
  9003. {
  9004. CriticalSection currentMappingsLock;
  9005. LocalisedStrings* currentMappings = 0;
  9006. int findCloseQuote (const String& text, int startPos)
  9007. {
  9008. juce_wchar lastChar = 0;
  9009. for (;;)
  9010. {
  9011. const juce_wchar c = text [startPos];
  9012. if (c == 0 || (c == '"' && lastChar != '\\'))
  9013. break;
  9014. lastChar = c;
  9015. ++startPos;
  9016. }
  9017. return startPos;
  9018. }
  9019. const String unescapeString (const String& s)
  9020. {
  9021. return s.replace ("\\\"", "\"")
  9022. .replace ("\\\'", "\'")
  9023. .replace ("\\t", "\t")
  9024. .replace ("\\r", "\r")
  9025. .replace ("\\n", "\n");
  9026. }
  9027. }
  9028. void LocalisedStrings::loadFromText (const String& fileContents)
  9029. {
  9030. StringArray lines;
  9031. lines.addLines (fileContents);
  9032. for (int i = 0; i < lines.size(); ++i)
  9033. {
  9034. String line (lines[i].trim());
  9035. if (line.startsWithChar ('"'))
  9036. {
  9037. int closeQuote = findCloseQuote (line, 1);
  9038. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9039. if (originalText.isNotEmpty())
  9040. {
  9041. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9042. closeQuote = findCloseQuote (line, openingQuote + 1);
  9043. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9044. if (newText.isNotEmpty())
  9045. translations.set (originalText, newText);
  9046. }
  9047. }
  9048. else if (line.startsWithIgnoreCase ("language:"))
  9049. {
  9050. languageName = line.substring (9).trim();
  9051. }
  9052. else if (line.startsWithIgnoreCase ("countries:"))
  9053. {
  9054. countryCodes.addTokens (line.substring (10).trim(), true);
  9055. countryCodes.trim();
  9056. countryCodes.removeEmptyStrings();
  9057. }
  9058. }
  9059. }
  9060. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9061. {
  9062. translations.setIgnoresCase (shouldIgnoreCase);
  9063. }
  9064. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9065. {
  9066. const ScopedLock sl (currentMappingsLock);
  9067. delete currentMappings;
  9068. currentMappings = newTranslations;
  9069. }
  9070. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9071. {
  9072. return currentMappings;
  9073. }
  9074. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9075. {
  9076. const ScopedLock sl (currentMappingsLock);
  9077. if (currentMappings != 0)
  9078. return currentMappings->translate (text);
  9079. return text;
  9080. }
  9081. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9082. {
  9083. return translateWithCurrentMappings (String (text));
  9084. }
  9085. END_JUCE_NAMESPACE
  9086. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9087. /*** Start of inlined file: juce_String.cpp ***/
  9088. #if JUCE_MSVC
  9089. #pragma warning (push)
  9090. #pragma warning (disable: 4514 4996)
  9091. #endif
  9092. #include <locale>
  9093. BEGIN_JUCE_NAMESPACE
  9094. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9095. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9096. #endif
  9097. #if JUCE_NATIVE_WCHAR_IS_UTF8
  9098. typedef CharPointer_UTF8 CharPointer_wchar_t;
  9099. #elif JUCE_NATIVE_WCHAR_IS_UTF16
  9100. typedef CharPointer_UTF16 CharPointer_wchar_t;
  9101. #else
  9102. typedef CharPointer_UTF32 CharPointer_wchar_t;
  9103. #endif
  9104. NewLine newLine;
  9105. class StringHolder
  9106. {
  9107. public:
  9108. StringHolder()
  9109. : refCount (0x3fffffff), allocatedNumChars (0)
  9110. {
  9111. text[0] = 0;
  9112. }
  9113. typedef String::CharPointerType CharPointerType;
  9114. static const CharPointerType createUninitialised (const size_t numChars)
  9115. {
  9116. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9117. s->refCount.value = 0;
  9118. s->allocatedNumChars = numChars;
  9119. return CharPointerType (&(s->text[0]));
  9120. }
  9121. template <class CharPointer>
  9122. static const CharPointerType createFromCharPointer (const CharPointer& text)
  9123. {
  9124. if (text.getAddress() == 0 || text.isEmpty())
  9125. return getEmpty();
  9126. const size_t numChars = text.length();
  9127. const CharPointerType dest (createUninitialised (numChars));
  9128. CharPointerType (dest).writeAll (text);
  9129. return dest;
  9130. }
  9131. template <class CharPointer>
  9132. static const CharPointerType createFromCharPointer (const CharPointer& text, size_t maxChars)
  9133. {
  9134. if (text.getAddress() == 0 || text.isEmpty())
  9135. return getEmpty();
  9136. size_t numChars = text.lengthUpTo (maxChars);
  9137. if (numChars == 0)
  9138. return getEmpty();
  9139. const CharPointerType dest (createUninitialised (numChars));
  9140. CharPointerType (dest).writeWithCharLimit (text, (int) (numChars + 1));
  9141. return dest;
  9142. }
  9143. static CharPointerType createFromFixedLength (const juce_wchar* const src, const size_t numChars)
  9144. {
  9145. CharPointerType dest (createUninitialised (numChars));
  9146. copyChars (dest, CharPointerType (src), (int) numChars);
  9147. return dest;
  9148. }
  9149. static const CharPointerType createFromFixedLength (const char* const src, const size_t numChars)
  9150. {
  9151. const CharPointerType dest (createUninitialised (numChars));
  9152. CharPointerType (dest).writeWithCharLimit (CharPointer_UTF8 (src), (int) (numChars + 1));
  9153. return dest;
  9154. }
  9155. static inline const CharPointerType getEmpty() throw()
  9156. {
  9157. return CharPointerType (&(empty.text[0]));
  9158. }
  9159. static void retain (const CharPointerType& text) throw()
  9160. {
  9161. ++(bufferFromText (text)->refCount);
  9162. }
  9163. static inline void release (StringHolder* const b) throw()
  9164. {
  9165. if (--(b->refCount) == -1 && b != &empty)
  9166. delete[] reinterpret_cast <char*> (b);
  9167. }
  9168. static void release (const CharPointerType& text) throw()
  9169. {
  9170. release (bufferFromText (text));
  9171. }
  9172. static CharPointerType makeUnique (const CharPointerType& text)
  9173. {
  9174. StringHolder* const b = bufferFromText (text);
  9175. if (b->refCount.get() <= 0)
  9176. return text;
  9177. CharPointerType newText (createFromFixedLength (text, b->allocatedNumChars));
  9178. release (b);
  9179. return newText;
  9180. }
  9181. static CharPointerType makeUniqueWithSize (const CharPointerType& text, size_t numChars)
  9182. {
  9183. StringHolder* const b = bufferFromText (text);
  9184. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9185. return text;
  9186. CharPointerType newText (createUninitialised (jmax (b->allocatedNumChars, numChars)));
  9187. copyChars (newText, text, b->allocatedNumChars);
  9188. release (b);
  9189. return newText;
  9190. }
  9191. static size_t getAllocatedNumChars (const CharPointerType& text) throw()
  9192. {
  9193. return bufferFromText (text)->allocatedNumChars;
  9194. }
  9195. static void copyChars (CharPointerType dest, const CharPointerType& src, const size_t numChars) throw()
  9196. {
  9197. jassert (src.getAddress() != 0 && dest.getAddress() != 0);
  9198. memcpy (dest.getAddress(), src.getAddress(), numChars * sizeof (juce_wchar));
  9199. CharPointerType (dest + (int) numChars).writeNull();
  9200. }
  9201. Atomic<int> refCount;
  9202. size_t allocatedNumChars;
  9203. juce_wchar text[1];
  9204. static StringHolder empty;
  9205. private:
  9206. static inline StringHolder* bufferFromText (const CharPointerType& text) throw()
  9207. {
  9208. // (Can't use offsetof() here because of warnings about this not being a POD)
  9209. return reinterpret_cast <StringHolder*> (reinterpret_cast <char*> (text.getAddress())
  9210. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9211. }
  9212. };
  9213. StringHolder StringHolder::empty;
  9214. const String String::empty;
  9215. void String::appendFixedLength (const juce_wchar* const newText, const int numExtraChars)
  9216. {
  9217. if (numExtraChars > 0)
  9218. {
  9219. const int oldLen = length();
  9220. const int newTotalLen = oldLen + numExtraChars;
  9221. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9222. StringHolder::copyChars (text + oldLen, CharPointer_UTF32 (newText), numExtraChars);
  9223. }
  9224. }
  9225. void String::preallocateStorage (const size_t numChars)
  9226. {
  9227. text = StringHolder::makeUniqueWithSize (text, numChars);
  9228. }
  9229. String::String() throw()
  9230. : text (StringHolder::getEmpty())
  9231. {
  9232. }
  9233. String::~String() throw()
  9234. {
  9235. StringHolder::release (text);
  9236. }
  9237. String::String (const String& other) throw()
  9238. : text (other.text)
  9239. {
  9240. StringHolder::retain (text);
  9241. }
  9242. void String::swapWith (String& other) throw()
  9243. {
  9244. swapVariables (text, other.text);
  9245. }
  9246. String& String::operator= (const String& other) throw()
  9247. {
  9248. StringHolder::retain (other.text);
  9249. StringHolder::release (text.atomicSwap (other.text));
  9250. return *this;
  9251. }
  9252. inline String::Preallocation::Preallocation (const size_t numChars_) : numChars (numChars_) {}
  9253. String::String (const Preallocation& preallocationSize)
  9254. : text (StringHolder::createUninitialised (preallocationSize.numChars))
  9255. {
  9256. }
  9257. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9258. : text (0)
  9259. {
  9260. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9261. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9262. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9263. }
  9264. String::String (const char* const t)
  9265. : text (StringHolder::createFromCharPointer (CharPointer_ASCII (t)))
  9266. {
  9267. /* If you get an assertion here, then you're trying to create a string from 8-bit data
  9268. that contains values greater than 127. These can NOT be correctly converted to unicode
  9269. because there's no way for the String class to know what encoding was used to
  9270. create them. The source data could be UTF-8, ASCII or one of many local code-pages.
  9271. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit
  9272. string to the String class - so for example if your source data is actually UTF-8,
  9273. you'd call String (CharPointer_UTF8 ("my utf8 string..")), and it would be able to
  9274. correctly convert the multi-byte characters to unicode. It's *highly* recommended that
  9275. you use UTF-8 with escape characters in your source code to represent extended characters,
  9276. because there's no other way to represent these strings in a way that isn't dependent on
  9277. the compiler, source code editor and platform.
  9278. */
  9279. jassert (t == 0 || CharPointer_ASCII::isValidString (t, std::numeric_limits<int>::max()));
  9280. }
  9281. String::String (const char* const t, const size_t maxChars)
  9282. : text (StringHolder::createFromCharPointer (CharPointer_ASCII (t), maxChars))
  9283. {
  9284. /* If you get an assertion here, then you're trying to create a string from 8-bit data
  9285. that contains values greater than 127. These can NOT be correctly converted to unicode
  9286. because there's no way for the String class to know what encoding was used to
  9287. create them. The source data could be UTF-8, ASCII or one of many local code-pages.
  9288. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit
  9289. string to the String class - so for example if your source data is actually UTF-8,
  9290. you'd call String (CharPointer_UTF8 ("my utf8 string..")), and it would be able to
  9291. correctly convert the multi-byte characters to unicode. It's *highly* recommended that
  9292. you use UTF-8 with escape characters in your source code to represent extended characters,
  9293. because there's no other way to represent these strings in a way that isn't dependent on
  9294. the compiler, source code editor and platform.
  9295. */
  9296. jassert (t == 0 || CharPointer_ASCII::isValidString (t, (int) maxChars));
  9297. }
  9298. String::String (const juce_wchar* const t)
  9299. : text (StringHolder::createFromCharPointer (CharPointer_UTF32 (t)))
  9300. {
  9301. }
  9302. String::String (const juce_wchar* const t, const size_t maxChars)
  9303. : text (StringHolder::createFromCharPointer (CharPointer_UTF32 (t), maxChars))
  9304. {
  9305. }
  9306. String::String (const CharPointer_UTF8& t)
  9307. : text (StringHolder::createFromCharPointer (t))
  9308. {
  9309. }
  9310. String::String (const CharPointer_UTF16& t)
  9311. : text (StringHolder::createFromCharPointer (t))
  9312. {
  9313. }
  9314. String::String (const CharPointer_UTF32& t)
  9315. : text (StringHolder::createFromCharPointer (t))
  9316. {
  9317. }
  9318. String::String (const CharPointer_UTF32& t, const size_t maxChars)
  9319. : text (StringHolder::createFromCharPointer (t, maxChars))
  9320. {
  9321. }
  9322. String::String (const CharPointer_ASCII& t)
  9323. : text (StringHolder::createFromCharPointer (t))
  9324. {
  9325. }
  9326. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  9327. String::String (const wchar_t* const t)
  9328. : text (StringHolder::createFromCharPointer
  9329. (CharPointer_wchar_t (reinterpret_cast <const CharPointer_wchar_t::CharType*> (t))))
  9330. {
  9331. }
  9332. String::String (const wchar_t* const t, size_t maxChars)
  9333. : text (StringHolder::createFromCharPointer
  9334. (CharPointer_wchar_t (reinterpret_cast <const CharPointer_wchar_t::CharType*> (t)), maxChars))
  9335. {
  9336. }
  9337. #endif
  9338. const String String::charToString (const juce_wchar character)
  9339. {
  9340. String result (Preallocation (1));
  9341. result.text[0] = character;
  9342. result.text[1] = 0;
  9343. return result;
  9344. }
  9345. namespace NumberToStringConverters
  9346. {
  9347. // pass in a pointer to the END of a buffer..
  9348. juce_wchar* numberToString (juce_wchar* t, const int64 n) throw()
  9349. {
  9350. *--t = 0;
  9351. int64 v = (n >= 0) ? n : -n;
  9352. do
  9353. {
  9354. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9355. v /= 10;
  9356. } while (v > 0);
  9357. if (n < 0)
  9358. *--t = '-';
  9359. return t;
  9360. }
  9361. juce_wchar* numberToString (juce_wchar* t, uint64 v) throw()
  9362. {
  9363. *--t = 0;
  9364. do
  9365. {
  9366. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9367. v /= 10;
  9368. } while (v > 0);
  9369. return t;
  9370. }
  9371. juce_wchar* numberToString (juce_wchar* t, const int n) throw()
  9372. {
  9373. if (n == (int) 0x80000000) // (would cause an overflow)
  9374. return numberToString (t, (int64) n);
  9375. *--t = 0;
  9376. int v = abs (n);
  9377. do
  9378. {
  9379. *--t = (juce_wchar) ('0' + (v % 10));
  9380. v /= 10;
  9381. } while (v > 0);
  9382. if (n < 0)
  9383. *--t = '-';
  9384. return t;
  9385. }
  9386. juce_wchar* numberToString (juce_wchar* t, unsigned int v) throw()
  9387. {
  9388. *--t = 0;
  9389. do
  9390. {
  9391. *--t = (juce_wchar) ('0' + (v % 10));
  9392. v /= 10;
  9393. } while (v > 0);
  9394. return t;
  9395. }
  9396. juce_wchar getDecimalPoint()
  9397. {
  9398. #if JUCE_VC7_OR_EARLIER
  9399. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9400. #else
  9401. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9402. #endif
  9403. return dp;
  9404. }
  9405. char* doubleToString (char* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9406. {
  9407. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9408. {
  9409. char* const end = buffer + numChars;
  9410. char* t = end;
  9411. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9412. *--t = (char) 0;
  9413. while (numDecPlaces >= 0 || v > 0)
  9414. {
  9415. if (numDecPlaces == 0)
  9416. *--t = (char) getDecimalPoint();
  9417. *--t = (char) ('0' + (v % 10));
  9418. v /= 10;
  9419. --numDecPlaces;
  9420. }
  9421. if (n < 0)
  9422. *--t = '-';
  9423. len = end - t - 1;
  9424. return t;
  9425. }
  9426. else
  9427. {
  9428. len = sprintf (buffer, "%.9g", n);
  9429. return buffer;
  9430. }
  9431. }
  9432. template <typename IntegerType>
  9433. const String::CharPointerType createFromInteger (const IntegerType number)
  9434. {
  9435. juce_wchar buffer [32];
  9436. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9437. juce_wchar* const start = numberToString (end, number);
  9438. return StringHolder::createFromFixedLength (start, end - start - 1);
  9439. }
  9440. const String::CharPointerType createFromDouble (const double number, const int numberOfDecimalPlaces)
  9441. {
  9442. char buffer [48];
  9443. size_t len;
  9444. char* const start = doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9445. return StringHolder::createFromFixedLength (start, len);
  9446. }
  9447. }
  9448. String::String (const int number)
  9449. : text (NumberToStringConverters::createFromInteger (number))
  9450. {
  9451. }
  9452. String::String (const unsigned int number)
  9453. : text (NumberToStringConverters::createFromInteger (number))
  9454. {
  9455. }
  9456. String::String (const short number)
  9457. : text (NumberToStringConverters::createFromInteger ((int) number))
  9458. {
  9459. }
  9460. String::String (const unsigned short number)
  9461. : text (NumberToStringConverters::createFromInteger ((unsigned int) number))
  9462. {
  9463. }
  9464. String::String (const int64 number)
  9465. : text (NumberToStringConverters::createFromInteger (number))
  9466. {
  9467. }
  9468. String::String (const uint64 number)
  9469. : text (NumberToStringConverters::createFromInteger (number))
  9470. {
  9471. }
  9472. String::String (const float number, const int numberOfDecimalPlaces)
  9473. : text (NumberToStringConverters::createFromDouble ((double) number, numberOfDecimalPlaces))
  9474. {
  9475. }
  9476. String::String (const double number, const int numberOfDecimalPlaces)
  9477. : text (NumberToStringConverters::createFromDouble (number, numberOfDecimalPlaces))
  9478. {
  9479. }
  9480. int String::length() const throw()
  9481. {
  9482. return (int) text.length();
  9483. }
  9484. const juce_wchar String::operator[] (int index) const throw()
  9485. {
  9486. jassert (index == 0 || isPositiveAndNotGreaterThan (index, length()));
  9487. return text [index];
  9488. }
  9489. int String::hashCode() const throw()
  9490. {
  9491. const juce_wchar* t = text;
  9492. int result = 0;
  9493. while (*t != (juce_wchar) 0)
  9494. result = 31 * result + *t++;
  9495. return result;
  9496. }
  9497. int64 String::hashCode64() const throw()
  9498. {
  9499. const juce_wchar* t = text;
  9500. int64 result = 0;
  9501. while (*t != (juce_wchar) 0)
  9502. result = 101 * result + *t++;
  9503. return result;
  9504. }
  9505. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw()
  9506. {
  9507. return string1.compare (string2) == 0;
  9508. }
  9509. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw()
  9510. {
  9511. return string1.compare (string2) == 0;
  9512. }
  9513. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  9514. {
  9515. return string1.compare (string2) == 0;
  9516. }
  9517. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF8& string2) throw()
  9518. {
  9519. return string1.getCharPointer().compare (string2) == 0;
  9520. }
  9521. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF16& string2) throw()
  9522. {
  9523. return string1.getCharPointer().compare (string2) == 0;
  9524. }
  9525. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF32& string2) throw()
  9526. {
  9527. return string1.getCharPointer().compare (string2) == 0;
  9528. }
  9529. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  9530. {
  9531. return string1.compare (string2) != 0;
  9532. }
  9533. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  9534. {
  9535. return string1.compare (string2) != 0;
  9536. }
  9537. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  9538. {
  9539. return string1.compare (string2) != 0;
  9540. }
  9541. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF8& string2) throw()
  9542. {
  9543. return string1.getCharPointer().compare (string2) != 0;
  9544. }
  9545. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF16& string2) throw()
  9546. {
  9547. return string1.getCharPointer().compare (string2) != 0;
  9548. }
  9549. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF32& string2) throw()
  9550. {
  9551. return string1.getCharPointer().compare (string2) != 0;
  9552. }
  9553. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  9554. {
  9555. return string1.compare (string2) > 0;
  9556. }
  9557. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  9558. {
  9559. return string1.compare (string2) < 0;
  9560. }
  9561. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  9562. {
  9563. return string1.compare (string2) >= 0;
  9564. }
  9565. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  9566. {
  9567. return string1.compare (string2) <= 0;
  9568. }
  9569. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9570. {
  9571. return t != 0 ? text.compareIgnoreCase (CharPointer_UTF32 (t)) == 0
  9572. : isEmpty();
  9573. }
  9574. bool String::equalsIgnoreCase (const char* t) const throw()
  9575. {
  9576. return t != 0 ? text.compareIgnoreCase (CharPointer_UTF8 (t)) == 0
  9577. : isEmpty();
  9578. }
  9579. bool String::equalsIgnoreCase (const String& other) const throw()
  9580. {
  9581. return text == other.text
  9582. || text.compareIgnoreCase (other.text) == 0;
  9583. }
  9584. int String::compare (const String& other) const throw()
  9585. {
  9586. return (text == other.text) ? 0 : text.compare (other.text);
  9587. }
  9588. int String::compare (const char* other) const throw()
  9589. {
  9590. return text.compare (CharPointer_UTF8 (other));
  9591. }
  9592. int String::compare (const juce_wchar* other) const throw()
  9593. {
  9594. return text.compare (CharPointer_UTF32 (other));
  9595. }
  9596. int String::compareIgnoreCase (const String& other) const throw()
  9597. {
  9598. return (text == other.text) ? 0 : text.compareIgnoreCase (other.text);
  9599. }
  9600. int String::compareLexicographically (const String& other) const throw()
  9601. {
  9602. CharPointerType s1 (text);
  9603. while (! (s1.isEmpty() || s1.isLetterOrDigit()))
  9604. ++s1;
  9605. CharPointerType s2 (other.text);
  9606. while (! (s2.isEmpty() || s2.isLetterOrDigit()))
  9607. ++s2;
  9608. return s1.compareIgnoreCase (s2);
  9609. }
  9610. void String::append (const String& textToAppend, size_t maxCharsToTake)
  9611. {
  9612. appendCharPointer (textToAppend.text, maxCharsToTake);
  9613. }
  9614. String& String::operator+= (const juce_wchar* const t)
  9615. {
  9616. appendCharPointer (CharPointer_UTF32 (t));
  9617. return *this;
  9618. }
  9619. String& String::operator+= (const String& other)
  9620. {
  9621. if (isEmpty())
  9622. return operator= (other);
  9623. appendCharPointer (other.text);
  9624. return *this;
  9625. }
  9626. String& String::operator+= (const char ch)
  9627. {
  9628. return operator+= ((juce_wchar) ch);
  9629. }
  9630. String& String::operator+= (const juce_wchar ch)
  9631. {
  9632. const juce_wchar asString[] = { ch, 0 };
  9633. return operator+= (static_cast <const juce_wchar*> (asString));
  9634. }
  9635. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  9636. String& String::operator+= (const wchar_t ch)
  9637. {
  9638. return operator+= ((juce_wchar) ch);
  9639. }
  9640. String& String::operator+= (const wchar_t* t)
  9641. {
  9642. return operator+= (String (t));
  9643. }
  9644. #endif
  9645. String& String::operator+= (const int number)
  9646. {
  9647. juce_wchar buffer [16];
  9648. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9649. juce_wchar* const start = NumberToStringConverters::numberToString (end, number);
  9650. appendFixedLength (start, (int) (end - start));
  9651. return *this;
  9652. }
  9653. JUCE_API const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  9654. {
  9655. String s (string1);
  9656. return s += string2;
  9657. }
  9658. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  9659. {
  9660. String s (string1);
  9661. return s += string2;
  9662. }
  9663. JUCE_API const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  9664. {
  9665. return String::charToString (string1) + string2;
  9666. }
  9667. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  9668. {
  9669. return String::charToString (string1) + string2;
  9670. }
  9671. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  9672. {
  9673. return string1 += string2;
  9674. }
  9675. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  9676. {
  9677. return string1 += string2;
  9678. }
  9679. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  9680. {
  9681. return string1 += string2;
  9682. }
  9683. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  9684. {
  9685. return string1 += string2;
  9686. }
  9687. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  9688. {
  9689. return string1 += string2;
  9690. }
  9691. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  9692. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, wchar_t string2)
  9693. {
  9694. return string1 += string2;
  9695. }
  9696. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const wchar_t* string2)
  9697. {
  9698. string1.appendCharPointer (CharPointer_wchar_t (reinterpret_cast <const CharPointer_wchar_t::CharType*> (string2)));
  9699. return string1;
  9700. }
  9701. JUCE_API const String JUCE_CALLTYPE operator+ (const wchar_t* string1, const String& string2)
  9702. {
  9703. String s (string1);
  9704. return s += string2;
  9705. }
  9706. #endif
  9707. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  9708. {
  9709. return string1 += characterToAppend;
  9710. }
  9711. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  9712. {
  9713. return string1 += characterToAppend;
  9714. }
  9715. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  9716. {
  9717. return string1 += string2;
  9718. }
  9719. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  9720. {
  9721. return string1 += string2;
  9722. }
  9723. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  9724. {
  9725. return string1 += string2;
  9726. }
  9727. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  9728. {
  9729. return string1 += (int) number;
  9730. }
  9731. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  9732. {
  9733. return string1 += number;
  9734. }
  9735. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  9736. {
  9737. return string1 += (int) number;
  9738. }
  9739. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  9740. {
  9741. return string1 += String (number);
  9742. }
  9743. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  9744. {
  9745. return string1 += String (number);
  9746. }
  9747. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  9748. {
  9749. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  9750. // if lots of large, persistent strings were to be written to streams).
  9751. const int numBytes = text.getNumBytesAsUTF8();
  9752. HeapBlock<char> temp (numBytes + 1);
  9753. text.copyToUTF8 (temp, numBytes + 1);
  9754. stream.write (temp, numBytes);
  9755. return stream;
  9756. }
  9757. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const NewLine&)
  9758. {
  9759. return string1 += NewLine::getDefault();
  9760. }
  9761. int String::indexOfChar (const juce_wchar character) const throw()
  9762. {
  9763. const juce_wchar* t = text;
  9764. for (;;)
  9765. {
  9766. if (*t == character)
  9767. return (int) (t - text);
  9768. if (*t++ == 0)
  9769. return -1;
  9770. }
  9771. }
  9772. int String::lastIndexOfChar (const juce_wchar character) const throw()
  9773. {
  9774. for (int i = length(); --i >= 0;)
  9775. if (text[i] == character)
  9776. return i;
  9777. return -1;
  9778. }
  9779. int String::indexOf (const String& t) const throw()
  9780. {
  9781. return t.isEmpty() ? 0 : text.indexOf (t.text);
  9782. }
  9783. int String::indexOfChar (const int startIndex,
  9784. const juce_wchar character) const throw()
  9785. {
  9786. if (startIndex > 0 && startIndex >= length())
  9787. return -1;
  9788. const juce_wchar* t = text + jmax (0, startIndex);
  9789. for (;;)
  9790. {
  9791. if (*t == character)
  9792. return (int) (t - text);
  9793. if (*t == 0)
  9794. return -1;
  9795. ++t;
  9796. }
  9797. }
  9798. int String::indexOfAnyOf (const String& charactersToLookFor,
  9799. const int startIndex,
  9800. const bool ignoreCase) const throw()
  9801. {
  9802. if (startIndex > 0 && startIndex >= length())
  9803. return -1;
  9804. CharPointerType t (text);
  9805. int i = jmax (0, startIndex);
  9806. t += i;
  9807. while (! t.isEmpty())
  9808. {
  9809. if (charactersToLookFor.text.indexOf (*t, ignoreCase) >= 0)
  9810. return i;
  9811. ++i;
  9812. ++t;
  9813. }
  9814. return -1;
  9815. }
  9816. int String::indexOf (const int startIndex, const String& other) const throw()
  9817. {
  9818. if (startIndex > 0 && startIndex >= length())
  9819. return -1;
  9820. int i = CharPointerType (text + jmax (0, startIndex)).indexOf (other.text);
  9821. return i >= 0 ? i + startIndex : -1;
  9822. }
  9823. int String::indexOfIgnoreCase (const String& other) const throw()
  9824. {
  9825. if (other.isEmpty())
  9826. return 0;
  9827. const int len = other.length();
  9828. const int end = length() - len;
  9829. for (int i = 0; i <= end; ++i)
  9830. if (CharPointerType (text + i).compareIgnoreCaseUpTo (other.text, len) == 0)
  9831. return i;
  9832. return -1;
  9833. }
  9834. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  9835. {
  9836. if (other.isNotEmpty())
  9837. {
  9838. const int len = other.length();
  9839. const int end = length() - len;
  9840. for (int i = jmax (0, startIndex); i <= end; ++i)
  9841. if (CharPointerType (text + i).compareIgnoreCaseUpTo (other.text, len) == 0)
  9842. return i;
  9843. }
  9844. return -1;
  9845. }
  9846. int String::lastIndexOf (const String& other) const throw()
  9847. {
  9848. if (other.isNotEmpty())
  9849. {
  9850. const int len = other.length();
  9851. int i = length() - len;
  9852. if (i >= 0)
  9853. {
  9854. CharPointerType n (text + i);
  9855. while (i >= 0)
  9856. {
  9857. if (n.compareUpTo (other.text, len) == 0)
  9858. return i;
  9859. --n;
  9860. --i;
  9861. }
  9862. }
  9863. }
  9864. return -1;
  9865. }
  9866. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  9867. {
  9868. if (other.isNotEmpty())
  9869. {
  9870. const int len = other.length();
  9871. int i = length() - len;
  9872. if (i >= 0)
  9873. {
  9874. CharPointerType n (text + i);
  9875. while (i >= 0)
  9876. {
  9877. if (n.compareIgnoreCaseUpTo (other.text, len) == 0)
  9878. return i;
  9879. --n;
  9880. --i;
  9881. }
  9882. }
  9883. }
  9884. return -1;
  9885. }
  9886. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  9887. {
  9888. for (int i = length(); --i >= 0;)
  9889. if (charactersToLookFor.text.indexOf (text[i], ignoreCase) >= 0)
  9890. return i;
  9891. return -1;
  9892. }
  9893. bool String::contains (const String& other) const throw()
  9894. {
  9895. return indexOf (other) >= 0;
  9896. }
  9897. bool String::containsChar (const juce_wchar character) const throw()
  9898. {
  9899. const juce_wchar* t = text;
  9900. for (;;)
  9901. {
  9902. if (*t == 0)
  9903. return false;
  9904. if (*t == character)
  9905. return true;
  9906. ++t;
  9907. }
  9908. }
  9909. bool String::containsIgnoreCase (const String& t) const throw()
  9910. {
  9911. return indexOfIgnoreCase (t) >= 0;
  9912. }
  9913. int String::indexOfWholeWord (const String& word) const throw()
  9914. {
  9915. if (word.isNotEmpty())
  9916. {
  9917. CharPointerType t (text);
  9918. const int wordLen = word.length();
  9919. const int end = (int) t.length() - wordLen;
  9920. for (int i = 0; i <= end; ++i)
  9921. {
  9922. if (t.compareUpTo (word.text, wordLen) == 0
  9923. && (i == 0 || ! (t - 1).isLetterOrDigit())
  9924. && ! (t + wordLen).isLetterOrDigit())
  9925. return i;
  9926. ++t;
  9927. }
  9928. }
  9929. return -1;
  9930. }
  9931. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  9932. {
  9933. if (word.isNotEmpty())
  9934. {
  9935. CharPointerType t (text);
  9936. const int wordLen = word.length();
  9937. const int end = (int) t.length() - wordLen;
  9938. for (int i = 0; i <= end; ++i)
  9939. {
  9940. if (t.compareIgnoreCaseUpTo (word.text, wordLen) == 0
  9941. && (i == 0 || ! (t + -1).isLetterOrDigit())
  9942. && ! (t + wordLen).isLetterOrDigit())
  9943. return i;
  9944. ++t;
  9945. }
  9946. }
  9947. return -1;
  9948. }
  9949. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  9950. {
  9951. return indexOfWholeWord (wordToLookFor) >= 0;
  9952. }
  9953. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  9954. {
  9955. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9956. }
  9957. namespace WildCardHelpers
  9958. {
  9959. int indexOfMatch (const String::CharPointerType& wildcard,
  9960. String::CharPointerType test,
  9961. const bool ignoreCase) throw()
  9962. {
  9963. int start = 0;
  9964. while (! test.isEmpty())
  9965. {
  9966. String::CharPointerType t (test);
  9967. String::CharPointerType w (wildcard);
  9968. for (;;)
  9969. {
  9970. const juce_wchar wc = *w;
  9971. const juce_wchar tc = *t;
  9972. if (wc == tc
  9973. || (ignoreCase && w.toLowerCase() == t.toLowerCase())
  9974. || (wc == '?' && tc != 0))
  9975. {
  9976. if (wc == 0)
  9977. return start;
  9978. ++t;
  9979. ++w;
  9980. }
  9981. else
  9982. {
  9983. if (wc == '*' && (w[1] == 0 || indexOfMatch (w + 1, t, ignoreCase) >= 0))
  9984. return start;
  9985. break;
  9986. }
  9987. }
  9988. ++start;
  9989. ++test;
  9990. }
  9991. return -1;
  9992. }
  9993. }
  9994. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  9995. {
  9996. CharPointerType w (wildcard.text);
  9997. CharPointerType t (text);
  9998. for (;;)
  9999. {
  10000. const juce_wchar wc = *w;
  10001. const juce_wchar tc = *t;
  10002. if (wc == tc
  10003. || (ignoreCase && w.toLowerCase() == t.toLowerCase())
  10004. || (wc == '?' && tc != 0))
  10005. {
  10006. if (wc == 0)
  10007. return true;
  10008. ++w;
  10009. ++t;
  10010. }
  10011. else
  10012. {
  10013. return wc == '*' && (w[1] == 0 || WildCardHelpers::indexOfMatch (w + 1, t, ignoreCase) >= 0);
  10014. }
  10015. }
  10016. }
  10017. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  10018. {
  10019. if (numberOfTimesToRepeat <= 0)
  10020. return String::empty;
  10021. const int len = stringToRepeat.length();
  10022. String result (Preallocation (len * numberOfTimesToRepeat + 1));
  10023. CharPointerType n (result.text);
  10024. while (--numberOfTimesToRepeat >= 0)
  10025. {
  10026. StringHolder::copyChars (n, stringToRepeat.text, len);
  10027. n += len;
  10028. }
  10029. return result;
  10030. }
  10031. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10032. {
  10033. jassert (padCharacter != 0);
  10034. const int len = length();
  10035. if (len >= minimumLength || padCharacter == 0)
  10036. return *this;
  10037. String result (Preallocation (minimumLength + 1));
  10038. CharPointerType n (result.text);
  10039. minimumLength -= len;
  10040. while (--minimumLength >= 0)
  10041. n.write (padCharacter);
  10042. StringHolder::copyChars (n, text, len);
  10043. return result;
  10044. }
  10045. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  10046. {
  10047. jassert (padCharacter != 0);
  10048. const int len = length();
  10049. if (len >= minimumLength || padCharacter == 0)
  10050. return *this;
  10051. String result (*this, (size_t) minimumLength);
  10052. CharPointerType n (result.text + len);
  10053. minimumLength -= len;
  10054. while (--minimumLength >= 0)
  10055. n.write (padCharacter);
  10056. n.writeNull();
  10057. return result;
  10058. }
  10059. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10060. {
  10061. if (index < 0)
  10062. {
  10063. // a negative index to replace from?
  10064. jassertfalse;
  10065. index = 0;
  10066. }
  10067. if (numCharsToReplace < 0)
  10068. {
  10069. // replacing a negative number of characters?
  10070. numCharsToReplace = 0;
  10071. jassertfalse;
  10072. }
  10073. const int len = length();
  10074. if (index + numCharsToReplace > len)
  10075. {
  10076. if (index > len)
  10077. {
  10078. // replacing beyond the end of the string?
  10079. index = len;
  10080. jassertfalse;
  10081. }
  10082. numCharsToReplace = len - index;
  10083. }
  10084. const int newStringLen = stringToInsert.length();
  10085. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10086. if (newTotalLen <= 0)
  10087. return String::empty;
  10088. String result (Preallocation ((size_t) newTotalLen));
  10089. StringHolder::copyChars (result.text, text, index);
  10090. if (newStringLen > 0)
  10091. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10092. const int endStringLen = newTotalLen - (index + newStringLen);
  10093. if (endStringLen > 0)
  10094. StringHolder::copyChars (result.text + (index + newStringLen),
  10095. text + (index + numCharsToReplace),
  10096. endStringLen);
  10097. return result;
  10098. }
  10099. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10100. {
  10101. const int stringToReplaceLen = stringToReplace.length();
  10102. const int stringToInsertLen = stringToInsert.length();
  10103. int i = 0;
  10104. String result (*this);
  10105. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10106. : result.indexOf (i, stringToReplace))) >= 0)
  10107. {
  10108. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10109. i += stringToInsertLen;
  10110. }
  10111. return result;
  10112. }
  10113. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10114. {
  10115. const int index = indexOfChar (charToReplace);
  10116. if (index < 0)
  10117. return *this;
  10118. String result (*this, size_t());
  10119. CharPointerType t (result.text + index);
  10120. while (! t.isEmpty())
  10121. {
  10122. if (*t == charToReplace)
  10123. t.replaceChar (charToInsert);
  10124. ++t;
  10125. }
  10126. return result;
  10127. }
  10128. const String String::replaceCharacters (const String& charactersToReplace,
  10129. const String& charactersToInsertInstead) const
  10130. {
  10131. String result (*this, size_t());
  10132. CharPointerType t (result.text);
  10133. const int len2 = charactersToInsertInstead.length();
  10134. // the two strings passed in are supposed to be the same length!
  10135. jassert (len2 == charactersToReplace.length());
  10136. while (! t.isEmpty())
  10137. {
  10138. const int index = charactersToReplace.indexOfChar (*t);
  10139. if (isPositiveAndBelow (index, len2))
  10140. t.replaceChar (charactersToInsertInstead [index]);
  10141. ++t;
  10142. }
  10143. return result;
  10144. }
  10145. bool String::startsWith (const String& other) const throw()
  10146. {
  10147. return text.compareUpTo (other.text, other.length()) == 0;
  10148. }
  10149. bool String::startsWithIgnoreCase (const String& other) const throw()
  10150. {
  10151. return text.compareIgnoreCaseUpTo (other.text, other.length()) == 0;
  10152. }
  10153. bool String::startsWithChar (const juce_wchar character) const throw()
  10154. {
  10155. jassert (character != 0); // strings can't contain a null character!
  10156. return text[0] == character;
  10157. }
  10158. bool String::endsWithChar (const juce_wchar character) const throw()
  10159. {
  10160. jassert (character != 0); // strings can't contain a null character!
  10161. return text[0] != 0
  10162. && text [length() - 1] == character;
  10163. }
  10164. bool String::endsWith (const String& other) const throw()
  10165. {
  10166. const int thisLen = length();
  10167. const int otherLen = other.length();
  10168. return thisLen >= otherLen
  10169. && CharPointerType (text + thisLen - otherLen).compare (other.text) == 0;
  10170. }
  10171. bool String::endsWithIgnoreCase (const String& other) const throw()
  10172. {
  10173. const int thisLen = length();
  10174. const int otherLen = other.length();
  10175. return thisLen >= otherLen
  10176. && CharPointerType (text + thisLen - otherLen).compareIgnoreCase (other.text) == 0;
  10177. }
  10178. const String String::toUpperCase() const
  10179. {
  10180. String result (Preallocation (this->length()));
  10181. CharPointerType dest (result.text);
  10182. CharPointerType src (text);
  10183. for (;;)
  10184. {
  10185. const juce_wchar c = src.toUpperCase();
  10186. dest.write (c);
  10187. if (c == 0)
  10188. break;
  10189. ++src;
  10190. }
  10191. return result;
  10192. }
  10193. const String String::toLowerCase() const
  10194. {
  10195. String result (Preallocation (this->length()));
  10196. CharPointerType dest (result.text);
  10197. CharPointerType src (text);
  10198. for (;;)
  10199. {
  10200. const juce_wchar c = src.toLowerCase();
  10201. dest.write (c);
  10202. if (c == 0)
  10203. break;
  10204. ++src;
  10205. }
  10206. return result;
  10207. }
  10208. juce_wchar String::getLastCharacter() const throw()
  10209. {
  10210. return isEmpty() ? juce_wchar() : text [length() - 1];
  10211. }
  10212. const String String::substring (int start, int end) const
  10213. {
  10214. if (start < 0)
  10215. start = 0;
  10216. else if (end <= start)
  10217. return empty;
  10218. int len = 0;
  10219. while (len <= end && text [len] != 0)
  10220. ++len;
  10221. if (end >= len)
  10222. {
  10223. if (start == 0)
  10224. return *this;
  10225. end = len;
  10226. }
  10227. return String (text + start, end - start);
  10228. }
  10229. const String String::substring (const int start) const
  10230. {
  10231. if (start <= 0)
  10232. return *this;
  10233. const int len = length();
  10234. if (start >= len)
  10235. return empty;
  10236. return String (text + start, len - start);
  10237. }
  10238. const String String::dropLastCharacters (const int numberToDrop) const
  10239. {
  10240. return String (text, jmax (0, length() - numberToDrop));
  10241. }
  10242. const String String::getLastCharacters (const int numCharacters) const
  10243. {
  10244. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10245. }
  10246. const String String::fromFirstOccurrenceOf (const String& sub,
  10247. const bool includeSubString,
  10248. const bool ignoreCase) const
  10249. {
  10250. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10251. : indexOf (sub);
  10252. if (i < 0)
  10253. return empty;
  10254. return substring (includeSubString ? i : i + sub.length());
  10255. }
  10256. const String String::fromLastOccurrenceOf (const String& sub,
  10257. const bool includeSubString,
  10258. const bool ignoreCase) const
  10259. {
  10260. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10261. : lastIndexOf (sub);
  10262. if (i < 0)
  10263. return *this;
  10264. return substring (includeSubString ? i : i + sub.length());
  10265. }
  10266. const String String::upToFirstOccurrenceOf (const String& sub,
  10267. const bool includeSubString,
  10268. const bool ignoreCase) const
  10269. {
  10270. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10271. : indexOf (sub);
  10272. if (i < 0)
  10273. return *this;
  10274. return substring (0, includeSubString ? i + sub.length() : i);
  10275. }
  10276. const String String::upToLastOccurrenceOf (const String& sub,
  10277. const bool includeSubString,
  10278. const bool ignoreCase) const
  10279. {
  10280. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10281. : lastIndexOf (sub);
  10282. if (i < 0)
  10283. return *this;
  10284. return substring (0, includeSubString ? i + sub.length() : i);
  10285. }
  10286. bool String::isQuotedString() const
  10287. {
  10288. const String trimmed (trimStart());
  10289. return trimmed[0] == '"'
  10290. || trimmed[0] == '\'';
  10291. }
  10292. const String String::unquoted() const
  10293. {
  10294. const int len = length();
  10295. if (len == 0)
  10296. return empty;
  10297. const juce_wchar lastChar = text [len - 1];
  10298. const int dropAtStart = (*text == '"' || *text == '\'') ? 1 : 0;
  10299. const int dropAtEnd = (lastChar == '"' || lastChar == '\'') ? 1 : 0;
  10300. return substring (dropAtStart, len - dropAtEnd);
  10301. }
  10302. const String String::quoted (const juce_wchar quoteCharacter) const
  10303. {
  10304. if (isEmpty())
  10305. return charToString (quoteCharacter) + quoteCharacter;
  10306. String t (*this);
  10307. if (! t.startsWithChar (quoteCharacter))
  10308. t = charToString (quoteCharacter) + t;
  10309. if (! t.endsWithChar (quoteCharacter))
  10310. t += quoteCharacter;
  10311. return t;
  10312. }
  10313. const String String::trim() const
  10314. {
  10315. if (isEmpty())
  10316. return empty;
  10317. int start = 0;
  10318. while ((text + start).isWhitespace())
  10319. ++start;
  10320. const int len = length();
  10321. int end = len - 1;
  10322. while ((end >= start) && (text + end).isWhitespace())
  10323. --end;
  10324. ++end;
  10325. if (end <= start)
  10326. return empty;
  10327. else if (start > 0 || end < len)
  10328. return String (text + start, end - start);
  10329. return *this;
  10330. }
  10331. const String String::trimStart() const
  10332. {
  10333. if (isEmpty())
  10334. return empty;
  10335. CharPointerType t (text.findEndOfWhitespace());
  10336. if (t == text)
  10337. return *this;
  10338. return String (t);
  10339. }
  10340. const String String::trimEnd() const
  10341. {
  10342. if (isEmpty())
  10343. return empty;
  10344. CharPointerType endT (text);
  10345. endT = endT.findTerminatingNull() - 1;
  10346. while ((endT.getAddress() >= text) && endT.isWhitespace())
  10347. --endT;
  10348. return String (text, 1 + (int) (endT.getAddress() - text));
  10349. }
  10350. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10351. {
  10352. CharPointerType t (text);
  10353. while (charactersToTrim.containsChar (*t))
  10354. ++t;
  10355. return t == text ? *this : String (t);
  10356. }
  10357. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10358. {
  10359. if (isEmpty())
  10360. return empty;
  10361. const int len = length();
  10362. const juce_wchar* endT = text + (len - 1);
  10363. int numToRemove = 0;
  10364. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  10365. {
  10366. ++numToRemove;
  10367. --endT;
  10368. }
  10369. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  10370. }
  10371. const String String::retainCharacters (const String& charactersToRetain) const
  10372. {
  10373. if (isEmpty())
  10374. return empty;
  10375. String result (Preallocation (StringHolder::getAllocatedNumChars (text)));
  10376. CharPointerType dst (result.text);
  10377. CharPointerType src (text);
  10378. for (;;)
  10379. {
  10380. const juce_wchar c = src.getAndAdvance();
  10381. if (c == 0)
  10382. break;
  10383. if (charactersToRetain.containsChar (c))
  10384. dst.write (c);
  10385. }
  10386. dst.writeNull();
  10387. return result;
  10388. }
  10389. const String String::removeCharacters (const String& charactersToRemove) const
  10390. {
  10391. if (isEmpty())
  10392. return empty;
  10393. String result (Preallocation (StringHolder::getAllocatedNumChars (text)));
  10394. CharPointerType dst (result.text);
  10395. CharPointerType src (text);
  10396. for (;;)
  10397. {
  10398. const juce_wchar c = src.getAndAdvance();
  10399. if (c == 0)
  10400. break;
  10401. if (! charactersToRemove.containsChar (c))
  10402. dst.write (c);
  10403. }
  10404. dst.writeNull();
  10405. return result;
  10406. }
  10407. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10408. {
  10409. int i = 0;
  10410. for (;;)
  10411. {
  10412. if (! permittedCharacters.containsChar (text[i]))
  10413. break;
  10414. ++i;
  10415. }
  10416. return substring (0, i);
  10417. }
  10418. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10419. {
  10420. const juce_wchar* const t = text;
  10421. int i = 0;
  10422. while (t[i] != 0)
  10423. {
  10424. if (charactersToStopAt.containsChar (t[i]))
  10425. return String (text, i);
  10426. ++i;
  10427. }
  10428. return empty;
  10429. }
  10430. bool String::containsOnly (const String& chars) const throw()
  10431. {
  10432. CharPointerType t (text);
  10433. while (! t.isEmpty())
  10434. if (! chars.containsChar (t.getAndAdvance()))
  10435. return false;
  10436. return true;
  10437. }
  10438. bool String::containsAnyOf (const String& chars) const throw()
  10439. {
  10440. const juce_wchar* t = text;
  10441. while (*t != 0)
  10442. if (chars.containsChar (*t++))
  10443. return true;
  10444. return false;
  10445. }
  10446. bool String::containsNonWhitespaceChars() const throw()
  10447. {
  10448. CharPointerType t (text);
  10449. while (! t.isEmpty())
  10450. {
  10451. if (! t.isWhitespace())
  10452. return true;
  10453. ++t;
  10454. }
  10455. return false;
  10456. }
  10457. const String String::formatted (const juce_wchar* const pf, ... )
  10458. {
  10459. jassert (pf != 0);
  10460. va_list args;
  10461. va_start (args, pf);
  10462. size_t bufferSize = 256;
  10463. String result (Preallocation ((size_t) bufferSize));
  10464. result.text[0] = 0;
  10465. for (;;)
  10466. {
  10467. #if JUCE_LINUX && JUCE_64BIT
  10468. va_list tempArgs;
  10469. va_copy (tempArgs, args);
  10470. const int num = (int) vswprintf (result.text.getAddress(), bufferSize - 1, pf, tempArgs);
  10471. va_end (tempArgs);
  10472. #elif JUCE_WINDOWS
  10473. HeapBlock <wchar_t> temp (bufferSize);
  10474. const int num = (int) _vsnwprintf (temp.getData(), bufferSize - 1, String (pf).toUTF16(), args);
  10475. if (num > 0)
  10476. CharPointerType (result.text).writeAll (CharPointer_UTF16 (temp.getData()));
  10477. #elif JUCE_ANDROID
  10478. HeapBlock <char> temp (bufferSize);
  10479. const int num = (int) vsnprintf (temp.getData(), bufferSize - 1, String (pf).toUTF8(), args);
  10480. if (num > 0)
  10481. CharPointerType (result.text).writeAll (CharPointer_UTF8 (temp.getData()));
  10482. #else
  10483. const int num = (int) vswprintf (result.text.getAddress(), bufferSize - 1, pf, args);
  10484. #endif
  10485. if (num > 0)
  10486. return result;
  10487. bufferSize += 256;
  10488. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10489. break; // returns -1 because of an error rather than because it needs more space.
  10490. result.preallocateStorage (bufferSize);
  10491. }
  10492. return empty;
  10493. }
  10494. int String::getIntValue() const throw()
  10495. {
  10496. return text.getIntValue32();
  10497. }
  10498. int String::getTrailingIntValue() const throw()
  10499. {
  10500. int n = 0;
  10501. int mult = 1;
  10502. CharPointerType t (text.findTerminatingNull());
  10503. while ((--t).getAddress() >= text)
  10504. {
  10505. if (! t.isDigit())
  10506. {
  10507. if (*t == '-')
  10508. n = -n;
  10509. break;
  10510. }
  10511. n += mult * (*t - '0');
  10512. mult *= 10;
  10513. }
  10514. return n;
  10515. }
  10516. int64 String::getLargeIntValue() const throw()
  10517. {
  10518. return text.getIntValue64();
  10519. }
  10520. float String::getFloatValue() const throw()
  10521. {
  10522. return (float) getDoubleValue();
  10523. }
  10524. double String::getDoubleValue() const throw()
  10525. {
  10526. return text.getDoubleValue();
  10527. }
  10528. static const char* const hexDigits = "0123456789abcdef";
  10529. const String String::toHexString (const int number)
  10530. {
  10531. juce_wchar buffer[32];
  10532. juce_wchar* const end = buffer + 32;
  10533. juce_wchar* t = end;
  10534. *--t = 0;
  10535. unsigned int v = (unsigned int) number;
  10536. do
  10537. {
  10538. *--t = (juce_wchar) hexDigits [v & 15];
  10539. v >>= 4;
  10540. } while (v != 0);
  10541. return String (t, (int) (((char*) end) - (char*) t) - 1);
  10542. }
  10543. const String String::toHexString (const int64 number)
  10544. {
  10545. juce_wchar buffer[32];
  10546. juce_wchar* const end = buffer + 32;
  10547. juce_wchar* t = end;
  10548. *--t = 0;
  10549. uint64 v = (uint64) number;
  10550. do
  10551. {
  10552. *--t = (juce_wchar) hexDigits [(int) (v & 15)];
  10553. v >>= 4;
  10554. } while (v != 0);
  10555. return String (t, (int) (((char*) end) - (char*) t));
  10556. }
  10557. const String String::toHexString (const short number)
  10558. {
  10559. return toHexString ((int) (unsigned short) number);
  10560. }
  10561. const String String::toHexString (const unsigned char* data, const int size, const int groupSize)
  10562. {
  10563. if (size <= 0)
  10564. return empty;
  10565. int numChars = (size * 2) + 2;
  10566. if (groupSize > 0)
  10567. numChars += size / groupSize;
  10568. String s (Preallocation ((size_t) numChars));
  10569. CharPointerType dest (s.text);
  10570. for (int i = 0; i < size; ++i)
  10571. {
  10572. dest.write ((juce_wchar) hexDigits [(*data) >> 4]);
  10573. dest.write ((juce_wchar) hexDigits [(*data) & 0xf]);
  10574. ++data;
  10575. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10576. dest.write ((juce_wchar) ' ');
  10577. }
  10578. dest.writeNull();
  10579. return s;
  10580. }
  10581. int String::getHexValue32() const throw()
  10582. {
  10583. int result = 0;
  10584. CharPointerType t (text);
  10585. while (! t.isEmpty())
  10586. {
  10587. const int hexValue = CharacterFunctions::getHexDigitValue (t.getAndAdvance());
  10588. if (hexValue >= 0)
  10589. result = (result << 4) | hexValue;
  10590. }
  10591. return result;
  10592. }
  10593. int64 String::getHexValue64() const throw()
  10594. {
  10595. int64 result = 0;
  10596. CharPointerType t (text);
  10597. while (! t.isEmpty())
  10598. {
  10599. const int hexValue = CharacterFunctions::getHexDigitValue (t.getAndAdvance());
  10600. if (hexValue >= 0)
  10601. result = (result << 4) | hexValue;
  10602. }
  10603. return result;
  10604. }
  10605. const String String::createStringFromData (const void* const data_, const int size)
  10606. {
  10607. const uint8* const data = static_cast <const uint8*> (data_);
  10608. if (size <= 0 || data == 0)
  10609. {
  10610. return empty;
  10611. }
  10612. else if (size == 1)
  10613. {
  10614. return charToString ((char) data[0]);
  10615. }
  10616. else if ((data[0] == (uint8) CharPointer_UTF16::byteOrderMarkBE1 && data[1] == (uint8) CharPointer_UTF16::byteOrderMarkBE2)
  10617. || (data[0] == (uint8) CharPointer_UTF16::byteOrderMarkLE1 && data[1] == (uint8) CharPointer_UTF16::byteOrderMarkLE1))
  10618. {
  10619. const bool bigEndian = (data[0] == (uint8) CharPointer_UTF16::byteOrderMarkBE1);
  10620. const int numChars = size / 2 - 1;
  10621. String result;
  10622. result.preallocateStorage (numChars + 2);
  10623. const uint16* const src = (const uint16*) (data + 2);
  10624. CharPointerType dst (result.getCharPointer());
  10625. if (bigEndian)
  10626. {
  10627. for (int i = 0; i < numChars; ++i)
  10628. dst.write ((juce_wchar) ByteOrder::swapIfLittleEndian (src[i]));
  10629. }
  10630. else
  10631. {
  10632. for (int i = 0; i < numChars; ++i)
  10633. dst.write ((juce_wchar) ByteOrder::swapIfBigEndian (src[i]));
  10634. }
  10635. dst.writeNull();
  10636. return result;
  10637. }
  10638. else
  10639. {
  10640. if (size >= 3
  10641. && data[0] == (uint8) CharPointer_UTF8::byteOrderMark1
  10642. && data[1] == (uint8) CharPointer_UTF8::byteOrderMark2
  10643. && data[2] == (uint8) CharPointer_UTF8::byteOrderMark3)
  10644. return String::fromUTF8 ((const char*) data + 3, size - 3);
  10645. return String::fromUTF8 ((const char*) data, size);
  10646. }
  10647. }
  10648. void* String::createSpaceAtEndOfBuffer (const size_t numExtraBytes) const
  10649. {
  10650. const int currentLen = length() + 1;
  10651. String& mutableThis = const_cast <String&> (*this);
  10652. mutableThis.preallocateStorage (currentLen + 1 + numExtraBytes / sizeof (juce_wchar));
  10653. return (mutableThis.text + currentLen).getAddress();
  10654. }
  10655. const CharPointer_UTF8 String::toUTF8() const
  10656. {
  10657. if (isEmpty())
  10658. return CharPointer_UTF8 (reinterpret_cast <const CharPointer_UTF8::CharType*> (text.getAddress()));
  10659. const size_t extraBytesNeeded = CharPointer_UTF8::getBytesRequiredFor (text);
  10660. CharPointer_UTF8 extraSpace (static_cast <CharPointer_UTF8::CharType*> (createSpaceAtEndOfBuffer (extraBytesNeeded)));
  10661. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10662. *(juce_wchar*) (addBytesToPointer (extraSpace.getAddress(), (extraBytesNeeded & ~(sizeof (juce_wchar) - 1)))) = 0;
  10663. #endif
  10664. CharPointer_UTF8 (extraSpace).writeAll (text);
  10665. return extraSpace;
  10666. }
  10667. CharPointer_UTF16 String::toUTF16() const
  10668. {
  10669. if (isEmpty())
  10670. return CharPointer_UTF16 (reinterpret_cast <const CharPointer_UTF16::CharType*> (text.getAddress()));
  10671. const size_t extraBytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text);
  10672. CharPointer_UTF16 extraSpace (static_cast <CharPointer_UTF16::CharType*> (createSpaceAtEndOfBuffer (extraBytesNeeded)));
  10673. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10674. *(juce_wchar*) (addBytesToPointer (extraSpace.getAddress(), (extraBytesNeeded & ~(sizeof (juce_wchar) - 1)))) = 0;
  10675. #endif
  10676. CharPointer_UTF16 (extraSpace).writeAll (text);
  10677. return extraSpace;
  10678. }
  10679. int String::copyToUTF8 (CharPointer_UTF8::CharType* const buffer, const int maxBufferSizeBytes) const throw()
  10680. {
  10681. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10682. if (buffer == 0)
  10683. return (int) CharPointer_UTF8::getBytesRequiredFor (text);
  10684. return CharPointer_UTF8 (buffer).writeWithDestByteLimit (text, maxBufferSizeBytes);
  10685. }
  10686. int String::copyToUTF16 (CharPointer_UTF16::CharType* const buffer, int maxBufferSizeBytes) const throw()
  10687. {
  10688. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10689. if (buffer == 0)
  10690. return (int) CharPointer_UTF16::getBytesRequiredFor (text);
  10691. return CharPointer_UTF16 (buffer).writeWithDestByteLimit (text, maxBufferSizeBytes);
  10692. }
  10693. int String::getNumBytesAsUTF8() const throw()
  10694. {
  10695. return (int) CharPointer_UTF8::getBytesRequiredFor (text);
  10696. }
  10697. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10698. {
  10699. if (buffer == 0)
  10700. return empty;
  10701. const int len = (int) (bufferSizeBytes >= 0 ? CharPointer_UTF8 (buffer).lengthUpTo (bufferSizeBytes)
  10702. : CharPointer_UTF8 (buffer).length());
  10703. String result (Preallocation (len + 1));
  10704. CharPointerType (result.text).writeWithCharLimit (CharPointer_UTF8 (buffer), len + 1);
  10705. return result;
  10706. }
  10707. const char* String::toCString() const
  10708. {
  10709. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  10710. if (isEmpty())
  10711. return reinterpret_cast <const char*> (text.getAddress());
  10712. const int len = getNumBytesAsCString();
  10713. char* const extraSpace = static_cast <char*> (createSpaceAtEndOfBuffer (len + 1));
  10714. wcstombs (extraSpace, text, len);
  10715. extraSpace [len] = 0;
  10716. return extraSpace;
  10717. #else
  10718. return toUTF8();
  10719. #endif
  10720. }
  10721. int String::getNumBytesAsCString() const throw()
  10722. {
  10723. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  10724. return (int) wcstombs (0, text, 0);
  10725. #else
  10726. return getNumBytesAsUTF8();
  10727. #endif
  10728. }
  10729. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  10730. {
  10731. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  10732. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  10733. if (destBuffer != 0 && numBytes >= 0)
  10734. destBuffer [numBytes] = 0;
  10735. return numBytes;
  10736. #else
  10737. return copyToUTF8 (destBuffer, maxBufferSizeBytes);
  10738. #endif
  10739. }
  10740. #if JUCE_MSVC
  10741. #pragma warning (pop)
  10742. #endif
  10743. String::Concatenator::Concatenator (String& stringToAppendTo)
  10744. : result (stringToAppendTo),
  10745. nextIndex (stringToAppendTo.length())
  10746. {
  10747. }
  10748. String::Concatenator::~Concatenator()
  10749. {
  10750. }
  10751. void String::Concatenator::append (const String& s)
  10752. {
  10753. const int len = s.length();
  10754. if (len > 0)
  10755. {
  10756. result.preallocateStorage (nextIndex + len);
  10757. CharPointerType (result.text + nextIndex).writeAll (s.text);
  10758. nextIndex += len;
  10759. }
  10760. }
  10761. #if JUCE_UNIT_TESTS
  10762. class StringTests : public UnitTest
  10763. {
  10764. public:
  10765. StringTests() : UnitTest ("String class") {}
  10766. template <class CharPointerType>
  10767. struct TestUTFConversion
  10768. {
  10769. static void test (UnitTest& test)
  10770. {
  10771. String s (createRandomWideCharString());
  10772. typename CharPointerType::CharType buffer [300];
  10773. memset (buffer, 0xff, sizeof (buffer));
  10774. CharPointerType (buffer).writeAll (s.toUTF32());
  10775. test.expectEquals (String (CharPointerType (buffer)), s);
  10776. memset (buffer, 0xff, sizeof (buffer));
  10777. CharPointerType (buffer).writeAll (s.toUTF16());
  10778. test.expectEquals (String (CharPointerType (buffer)), s);
  10779. memset (buffer, 0xff, sizeof (buffer));
  10780. CharPointerType (buffer).writeAll (s.toUTF8());
  10781. test.expectEquals (String (CharPointerType (buffer)), s);
  10782. }
  10783. };
  10784. static const String createRandomWideCharString()
  10785. {
  10786. juce_wchar buffer [50];
  10787. zerostruct (buffer);
  10788. for (int i = 0; i < numElementsInArray (buffer) - 1; ++i)
  10789. {
  10790. if (Random::getSystemRandom().nextBool())
  10791. {
  10792. do
  10793. {
  10794. buffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (0x10ffff - 1));
  10795. }
  10796. while (buffer[i] >= 0xd800 && buffer[i] <= 0xdfff); // (these code-points are illegal in UTF-16)
  10797. }
  10798. else
  10799. buffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (0xff));
  10800. }
  10801. return buffer;
  10802. }
  10803. void runTest()
  10804. {
  10805. {
  10806. beginTest ("Basics");
  10807. expect (String().length() == 0);
  10808. expect (String() == String::empty);
  10809. String s1, s2 ("abcd");
  10810. expect (s1.isEmpty() && ! s1.isNotEmpty());
  10811. expect (s2.isNotEmpty() && ! s2.isEmpty());
  10812. expect (s2.length() == 4);
  10813. s1 = "abcd";
  10814. expect (s2 == s1 && s1 == s2);
  10815. expect (s1 == "abcd" && s1 == L"abcd");
  10816. expect (String ("abcd") == String (L"abcd"));
  10817. expect (String ("abcdefg", 4) == L"abcd");
  10818. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  10819. expect (String::charToString ('x') == "x");
  10820. expect (String::charToString (0) == String::empty);
  10821. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  10822. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  10823. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  10824. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  10825. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  10826. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  10827. expect (s1.indexOf (String::empty) == 0);
  10828. expect (s1.indexOfIgnoreCase (String::empty) == 0);
  10829. expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty));
  10830. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  10831. expect (s1.containsChar ('a'));
  10832. expect (! s1.containsChar ('x'));
  10833. expect (! s1.containsChar (0));
  10834. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  10835. }
  10836. {
  10837. beginTest ("Operations");
  10838. String s ("012345678");
  10839. expect (s.hashCode() != 0);
  10840. expect (s.hashCode64() != 0);
  10841. expect (s.hashCode() != (s + s).hashCode());
  10842. expect (s.hashCode64() != (s + s).hashCode64());
  10843. expect (s.compare (String ("012345678")) == 0);
  10844. expect (s.compare (String ("012345679")) < 0);
  10845. expect (s.compare (String ("012345676")) > 0);
  10846. expect (s.substring (2, 3) == String::charToString (s[2]));
  10847. expect (s.substring (0, 1) == String::charToString (s[0]));
  10848. expect (s.getLastCharacter() == s [s.length() - 1]);
  10849. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  10850. expect (s.substring (0, 3) == L"012");
  10851. expect (s.substring (0, 100) == s);
  10852. expect (s.substring (-1, 100) == s);
  10853. expect (s.substring (3) == "345678");
  10854. expect (s.indexOf (L"45") == 4);
  10855. expect (String ("444445").indexOf ("45") == 4);
  10856. expect (String ("444445").lastIndexOfChar ('4') == 4);
  10857. expect (String ("45454545x").lastIndexOf (L"45") == 6);
  10858. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  10859. expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8);
  10860. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("aB") == 6);
  10861. expect (s.indexOfChar (L'4') == 4);
  10862. expect (s + s == "012345678012345678");
  10863. expect (s.startsWith (s));
  10864. expect (s.startsWith (s.substring (0, 4)));
  10865. expect (s.startsWith (s.dropLastCharacters (4)));
  10866. expect (s.endsWith (s.substring (5)));
  10867. expect (s.endsWith (s));
  10868. expect (s.contains (s.substring (3, 6)));
  10869. expect (s.contains (s.substring (3)));
  10870. expect (s.startsWithChar (s[0]));
  10871. expect (s.endsWithChar (s.getLastCharacter()));
  10872. expect (s [s.length()] == 0);
  10873. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  10874. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  10875. String s2 ("123");
  10876. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  10877. s2 += "xyz";
  10878. expect (s2 == "1234567890xyz");
  10879. beginTest ("Numeric conversions");
  10880. expect (String::empty.getIntValue() == 0);
  10881. expect (String::empty.getDoubleValue() == 0.0);
  10882. expect (String::empty.getFloatValue() == 0.0f);
  10883. expect (s.getIntValue() == 12345678);
  10884. expect (s.getLargeIntValue() == (int64) 12345678);
  10885. expect (s.getDoubleValue() == 12345678.0);
  10886. expect (s.getFloatValue() == 12345678.0f);
  10887. expect (String (-1234).getIntValue() == -1234);
  10888. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  10889. expect (String (-1234.56).getDoubleValue() == -1234.56);
  10890. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  10891. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  10892. expect (s.getHexValue32() == 0x12345678);
  10893. expect (s.getHexValue64() == (int64) 0x12345678);
  10894. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  10895. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  10896. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  10897. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  10898. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  10899. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  10900. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  10901. beginTest ("Subsections");
  10902. String s3;
  10903. s3 = "abcdeFGHIJ";
  10904. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  10905. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  10906. expect (s3.containsIgnoreCase (s3.substring (3)));
  10907. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  10908. expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1);
  10909. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  10910. expect (s3.containsAnyOf (L"zzzFs"));
  10911. expect (s3.startsWith ("abcd"));
  10912. expect (s3.startsWithIgnoreCase (L"abCD"));
  10913. expect (s3.startsWith (String::empty));
  10914. expect (s3.startsWithChar ('a'));
  10915. expect (s3.endsWith (String ("HIJ")));
  10916. expect (s3.endsWithIgnoreCase (L"Hij"));
  10917. expect (s3.endsWith (String::empty));
  10918. expect (s3.endsWithChar (L'J'));
  10919. expect (s3.indexOf ("HIJ") == 7);
  10920. expect (s3.indexOf (L"HIJK") == -1);
  10921. expect (s3.indexOfIgnoreCase ("hij") == 7);
  10922. expect (s3.indexOfIgnoreCase (L"hijk") == -1);
  10923. String s4 (s3);
  10924. s4.append (String ("xyz123"), 3);
  10925. expect (s4 == s3 + "xyz");
  10926. expect (String (1234) < String (1235));
  10927. expect (String (1235) > String (1234));
  10928. expect (String (1234) >= String (1234));
  10929. expect (String (1234) <= String (1234));
  10930. expect (String (1235) >= String (1234));
  10931. expect (String (1234) <= String (1235));
  10932. String s5 ("word word2 word3");
  10933. expect (s5.containsWholeWord (String ("word2")));
  10934. expect (s5.indexOfWholeWord ("word2") == 5);
  10935. expect (s5.containsWholeWord (L"word"));
  10936. expect (s5.containsWholeWord ("word3"));
  10937. expect (s5.containsWholeWord (s5));
  10938. expect (s5.containsWholeWordIgnoreCase (L"Word2"));
  10939. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  10940. expect (s5.containsWholeWordIgnoreCase (L"Word"));
  10941. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  10942. expect (! s5.containsWholeWordIgnoreCase (L"Wordx"));
  10943. expect (!s5.containsWholeWordIgnoreCase ("xWord2"));
  10944. expect (s5.containsNonWhitespaceChars());
  10945. expect (s5.containsOnly ("ordw23 "));
  10946. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  10947. expect (s5.matchesWildcard (L"wor*", false));
  10948. expect (s5.matchesWildcard ("wOr*", true));
  10949. expect (s5.matchesWildcard (L"*word3", true));
  10950. expect (s5.matchesWildcard ("*word?", true));
  10951. expect (s5.matchesWildcard (L"Word*3", true));
  10952. expectEquals (s5.fromFirstOccurrenceOf (String::empty, true, false), s5);
  10953. expectEquals (s5.fromFirstOccurrenceOf ("xword2", true, false), s5.substring (100));
  10954. expectEquals (s5.fromFirstOccurrenceOf (L"word2", true, false), s5.substring (5));
  10955. expectEquals (s5.fromFirstOccurrenceOf ("Word2", true, true), s5.substring (5));
  10956. expectEquals (s5.fromFirstOccurrenceOf ("word2", false, false), s5.getLastCharacters (6));
  10957. expectEquals (s5.fromFirstOccurrenceOf (L"Word2", false, true), s5.getLastCharacters (6));
  10958. expectEquals (s5.fromLastOccurrenceOf (String::empty, true, false), s5);
  10959. expectEquals (s5.fromLastOccurrenceOf (L"wordx", true, false), s5);
  10960. expectEquals (s5.fromLastOccurrenceOf ("word", true, false), s5.getLastCharacters (5));
  10961. expectEquals (s5.fromLastOccurrenceOf (L"worD", true, true), s5.getLastCharacters (5));
  10962. expectEquals (s5.fromLastOccurrenceOf ("word", false, false), s5.getLastCharacters (1));
  10963. expectEquals (s5.fromLastOccurrenceOf (L"worD", false, true), s5.getLastCharacters (1));
  10964. expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty());
  10965. expectEquals (s5.upToFirstOccurrenceOf ("word4", true, false), s5);
  10966. expectEquals (s5.upToFirstOccurrenceOf (L"word2", true, false), s5.substring (0, 10));
  10967. expectEquals (s5.upToFirstOccurrenceOf ("Word2", true, true), s5.substring (0, 10));
  10968. expectEquals (s5.upToFirstOccurrenceOf (L"word2", false, false), s5.substring (0, 5));
  10969. expectEquals (s5.upToFirstOccurrenceOf ("Word2", false, true), s5.substring (0, 5));
  10970. expectEquals (s5.upToLastOccurrenceOf (String::empty, true, false), s5);
  10971. expectEquals (s5.upToLastOccurrenceOf ("zword", true, false), s5);
  10972. expectEquals (s5.upToLastOccurrenceOf ("word", true, false), s5.dropLastCharacters (1));
  10973. expectEquals (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false), s5.dropLastCharacters (1));
  10974. expectEquals (s5.upToLastOccurrenceOf ("Word", true, true), s5.dropLastCharacters (1));
  10975. expectEquals (s5.upToLastOccurrenceOf ("word", false, false), s5.dropLastCharacters (5));
  10976. expectEquals (s5.upToLastOccurrenceOf ("Word", false, true), s5.dropLastCharacters (5));
  10977. expectEquals (s5.replace ("word", L"xyz", false), String ("xyz xyz2 xyz3"));
  10978. expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3");
  10979. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  10980. expect (s5.replace ("Word", "", true) == " 2 3");
  10981. expectEquals (s5.replace ("Word2", L"xyz", true), String ("word xyz word3"));
  10982. expect (s5.replaceCharacter (L'w', 'x') != s5);
  10983. expectEquals (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w'), s5);
  10984. expect (s5.replaceCharacters ("wo", "xy") != s5);
  10985. expectEquals (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo"), s5);
  10986. expectEquals (s5.retainCharacters ("1wordxya"), String ("wordwordword"));
  10987. expect (s5.retainCharacters (String::empty).isEmpty());
  10988. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  10989. expectEquals (s5.removeCharacters (String::empty), s5);
  10990. expect (s5.initialSectionContainingOnly ("word") == L"word");
  10991. expectEquals (s5.initialSectionNotContaining (String ("xyz ")), String ("word"));
  10992. expect (! s5.isQuotedString());
  10993. expect (s5.quoted().isQuotedString());
  10994. expect (! s5.quoted().unquoted().isQuotedString());
  10995. expect (! String ("x'").isQuotedString());
  10996. expect (String ("'x").isQuotedString());
  10997. String s6 (" \t xyz \t\r\n");
  10998. expectEquals (s6.trim(), String ("xyz"));
  10999. expect (s6.trim().trim() == "xyz");
  11000. expectEquals (s5.trim(), s5);
  11001. expectEquals (s6.trimStart().trimEnd(), s6.trim());
  11002. expectEquals (s6.trimStart().trimEnd(), s6.trimEnd().trimStart());
  11003. expectEquals (s6.trimStart().trimStart().trimEnd().trimEnd(), s6.trimEnd().trimStart());
  11004. expect (s6.trimStart() != s6.trimEnd());
  11005. expectEquals (("\t\r\n " + s6 + "\t\n \r").trim(), s6.trim());
  11006. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  11007. }
  11008. {
  11009. beginTest ("UTF conversions");
  11010. TestUTFConversion <CharPointer_UTF32>::test (*this);
  11011. TestUTFConversion <CharPointer_UTF8>::test (*this);
  11012. TestUTFConversion <CharPointer_UTF16>::test (*this);
  11013. }
  11014. {
  11015. beginTest ("StringArray");
  11016. StringArray s;
  11017. for (int i = 5; --i >= 0;)
  11018. s.add (String (i));
  11019. expectEquals (s.joinIntoString ("-"), String ("4-3-2-1-0"));
  11020. s.remove (2);
  11021. expectEquals (s.joinIntoString ("--"), String ("4--3--1--0"));
  11022. expectEquals (s.joinIntoString (String::empty), String ("4310"));
  11023. s.clear();
  11024. expectEquals (s.joinIntoString ("x"), String::empty);
  11025. }
  11026. }
  11027. };
  11028. static StringTests stringUnitTests;
  11029. #endif
  11030. END_JUCE_NAMESPACE
  11031. /*** End of inlined file: juce_String.cpp ***/
  11032. /*** Start of inlined file: juce_StringArray.cpp ***/
  11033. BEGIN_JUCE_NAMESPACE
  11034. StringArray::StringArray() throw()
  11035. {
  11036. }
  11037. StringArray::StringArray (const StringArray& other)
  11038. : strings (other.strings)
  11039. {
  11040. }
  11041. StringArray::StringArray (const String& firstValue)
  11042. {
  11043. strings.add (firstValue);
  11044. }
  11045. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  11046. const int numberOfStrings)
  11047. {
  11048. for (int i = 0; i < numberOfStrings; ++i)
  11049. strings.add (initialStrings [i]);
  11050. }
  11051. StringArray::StringArray (const char* const* const initialStrings,
  11052. const int numberOfStrings)
  11053. {
  11054. for (int i = 0; i < numberOfStrings; ++i)
  11055. strings.add (initialStrings [i]);
  11056. }
  11057. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  11058. {
  11059. int i = 0;
  11060. while (initialStrings[i] != 0)
  11061. strings.add (initialStrings [i++]);
  11062. }
  11063. StringArray::StringArray (const char* const* const initialStrings)
  11064. {
  11065. int i = 0;
  11066. while (initialStrings[i] != 0)
  11067. strings.add (initialStrings [i++]);
  11068. }
  11069. StringArray& StringArray::operator= (const StringArray& other)
  11070. {
  11071. strings = other.strings;
  11072. return *this;
  11073. }
  11074. StringArray::~StringArray()
  11075. {
  11076. }
  11077. bool StringArray::operator== (const StringArray& other) const throw()
  11078. {
  11079. if (other.size() != size())
  11080. return false;
  11081. for (int i = size(); --i >= 0;)
  11082. if (other.strings.getReference(i) != strings.getReference(i))
  11083. return false;
  11084. return true;
  11085. }
  11086. bool StringArray::operator!= (const StringArray& other) const throw()
  11087. {
  11088. return ! operator== (other);
  11089. }
  11090. void StringArray::clear()
  11091. {
  11092. strings.clear();
  11093. }
  11094. const String& StringArray::operator[] (const int index) const throw()
  11095. {
  11096. if (isPositiveAndBelow (index, strings.size()))
  11097. return strings.getReference (index);
  11098. return String::empty;
  11099. }
  11100. String& StringArray::getReference (const int index) throw()
  11101. {
  11102. jassert (isPositiveAndBelow (index, strings.size()));
  11103. return strings.getReference (index);
  11104. }
  11105. void StringArray::add (const String& newString)
  11106. {
  11107. strings.add (newString);
  11108. }
  11109. void StringArray::insert (const int index, const String& newString)
  11110. {
  11111. strings.insert (index, newString);
  11112. }
  11113. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  11114. {
  11115. if (! contains (newString, ignoreCase))
  11116. add (newString);
  11117. }
  11118. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  11119. {
  11120. if (startIndex < 0)
  11121. {
  11122. jassertfalse;
  11123. startIndex = 0;
  11124. }
  11125. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  11126. numElementsToAdd = otherArray.size() - startIndex;
  11127. while (--numElementsToAdd >= 0)
  11128. strings.add (otherArray.strings.getReference (startIndex++));
  11129. }
  11130. void StringArray::set (const int index, const String& newString)
  11131. {
  11132. strings.set (index, newString);
  11133. }
  11134. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  11135. {
  11136. if (ignoreCase)
  11137. {
  11138. for (int i = size(); --i >= 0;)
  11139. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11140. return true;
  11141. }
  11142. else
  11143. {
  11144. for (int i = size(); --i >= 0;)
  11145. if (stringToLookFor == strings.getReference(i))
  11146. return true;
  11147. }
  11148. return false;
  11149. }
  11150. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  11151. {
  11152. if (i < 0)
  11153. i = 0;
  11154. const int numElements = size();
  11155. if (ignoreCase)
  11156. {
  11157. while (i < numElements)
  11158. {
  11159. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11160. return i;
  11161. ++i;
  11162. }
  11163. }
  11164. else
  11165. {
  11166. while (i < numElements)
  11167. {
  11168. if (stringToLookFor == strings.getReference (i))
  11169. return i;
  11170. ++i;
  11171. }
  11172. }
  11173. return -1;
  11174. }
  11175. void StringArray::remove (const int index)
  11176. {
  11177. strings.remove (index);
  11178. }
  11179. void StringArray::removeString (const String& stringToRemove,
  11180. const bool ignoreCase)
  11181. {
  11182. if (ignoreCase)
  11183. {
  11184. for (int i = size(); --i >= 0;)
  11185. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  11186. strings.remove (i);
  11187. }
  11188. else
  11189. {
  11190. for (int i = size(); --i >= 0;)
  11191. if (stringToRemove == strings.getReference (i))
  11192. strings.remove (i);
  11193. }
  11194. }
  11195. void StringArray::removeRange (int startIndex, int numberToRemove)
  11196. {
  11197. strings.removeRange (startIndex, numberToRemove);
  11198. }
  11199. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11200. {
  11201. if (removeWhitespaceStrings)
  11202. {
  11203. for (int i = size(); --i >= 0;)
  11204. if (! strings.getReference(i).containsNonWhitespaceChars())
  11205. strings.remove (i);
  11206. }
  11207. else
  11208. {
  11209. for (int i = size(); --i >= 0;)
  11210. if (strings.getReference(i).isEmpty())
  11211. strings.remove (i);
  11212. }
  11213. }
  11214. void StringArray::trim()
  11215. {
  11216. for (int i = size(); --i >= 0;)
  11217. {
  11218. String& s = strings.getReference(i);
  11219. s = s.trim();
  11220. }
  11221. }
  11222. class InternalStringArrayComparator_CaseSensitive
  11223. {
  11224. public:
  11225. static int compareElements (String& first, String& second) { return first.compare (second); }
  11226. };
  11227. class InternalStringArrayComparator_CaseInsensitive
  11228. {
  11229. public:
  11230. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11231. };
  11232. void StringArray::sort (const bool ignoreCase)
  11233. {
  11234. if (ignoreCase)
  11235. {
  11236. InternalStringArrayComparator_CaseInsensitive comp;
  11237. strings.sort (comp);
  11238. }
  11239. else
  11240. {
  11241. InternalStringArrayComparator_CaseSensitive comp;
  11242. strings.sort (comp);
  11243. }
  11244. }
  11245. void StringArray::move (const int currentIndex, int newIndex) throw()
  11246. {
  11247. strings.move (currentIndex, newIndex);
  11248. }
  11249. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11250. {
  11251. const int last = (numberToJoin < 0) ? size()
  11252. : jmin (size(), start + numberToJoin);
  11253. if (start < 0)
  11254. start = 0;
  11255. if (start >= last)
  11256. return String::empty;
  11257. if (start == last - 1)
  11258. return strings.getReference (start);
  11259. const int separatorLen = separator.length();
  11260. int charsNeeded = separatorLen * (last - start - 1);
  11261. for (int i = start; i < last; ++i)
  11262. charsNeeded += strings.getReference(i).length();
  11263. String result;
  11264. result.preallocateStorage (charsNeeded);
  11265. String::CharPointerType dest (result.getCharPointer());
  11266. while (start < last)
  11267. {
  11268. const String& s = strings.getReference (start);
  11269. if (! s.isEmpty())
  11270. dest.writeAll (s.getCharPointer());
  11271. if (++start < last && separatorLen > 0)
  11272. dest.writeAll (separator.getCharPointer());
  11273. }
  11274. dest.writeNull();
  11275. return result;
  11276. }
  11277. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11278. {
  11279. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11280. }
  11281. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11282. {
  11283. int num = 0;
  11284. if (text.isNotEmpty())
  11285. {
  11286. bool insideQuotes = false;
  11287. juce_wchar currentQuoteChar = 0;
  11288. String::CharPointerType t (text.getCharPointer());
  11289. String::CharPointerType tokenStart (t);
  11290. int numChars = 0;
  11291. for (;;)
  11292. {
  11293. const juce_wchar c = t.getAndAdvance();
  11294. ++numChars;
  11295. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11296. if (! isBreak)
  11297. {
  11298. if (quoteCharacters.containsChar (c))
  11299. {
  11300. if (insideQuotes)
  11301. {
  11302. // only break out of quotes-mode if we find a matching quote to the
  11303. // one that we opened with..
  11304. if (currentQuoteChar == c)
  11305. insideQuotes = false;
  11306. }
  11307. else
  11308. {
  11309. insideQuotes = true;
  11310. currentQuoteChar = c;
  11311. }
  11312. }
  11313. }
  11314. else
  11315. {
  11316. add (String (tokenStart, numChars - 1));
  11317. ++num;
  11318. tokenStart = t;
  11319. numChars = 0;
  11320. }
  11321. if (c == 0)
  11322. break;
  11323. }
  11324. }
  11325. return num;
  11326. }
  11327. int StringArray::addLines (const String& sourceText)
  11328. {
  11329. int numLines = 0;
  11330. String::CharPointerType text (sourceText.getCharPointer());
  11331. bool finished = text.isEmpty();
  11332. while (! finished)
  11333. {
  11334. String::CharPointerType startOfLine (text);
  11335. int numChars = 0;
  11336. for (;;)
  11337. {
  11338. const juce_wchar c = text.getAndAdvance();
  11339. if (c == 0)
  11340. {
  11341. finished = true;
  11342. break;
  11343. }
  11344. if (c == '\n')
  11345. break;
  11346. if (c == '\r')
  11347. {
  11348. if (*text == '\n')
  11349. ++text;
  11350. break;
  11351. }
  11352. ++numChars;
  11353. }
  11354. add (String (startOfLine, numChars));
  11355. ++numLines;
  11356. }
  11357. return numLines;
  11358. }
  11359. void StringArray::removeDuplicates (const bool ignoreCase)
  11360. {
  11361. for (int i = 0; i < size() - 1; ++i)
  11362. {
  11363. const String s (strings.getReference(i));
  11364. int nextIndex = i + 1;
  11365. for (;;)
  11366. {
  11367. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11368. if (nextIndex < 0)
  11369. break;
  11370. strings.remove (nextIndex);
  11371. }
  11372. }
  11373. }
  11374. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11375. const bool appendNumberToFirstInstance,
  11376. CharPointer_UTF8 preNumberString,
  11377. CharPointer_UTF8 postNumberString)
  11378. {
  11379. CharPointer_UTF8 defaultPre (" ("), defaultPost (")");
  11380. if (preNumberString.getAddress() == 0)
  11381. preNumberString = defaultPre;
  11382. if (postNumberString.getAddress() == 0)
  11383. postNumberString = defaultPost;
  11384. for (int i = 0; i < size() - 1; ++i)
  11385. {
  11386. String& s = strings.getReference(i);
  11387. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11388. if (nextIndex >= 0)
  11389. {
  11390. const String original (s);
  11391. int number = 0;
  11392. if (appendNumberToFirstInstance)
  11393. s = original + String (preNumberString) + String (++number) + String (postNumberString);
  11394. else
  11395. ++number;
  11396. while (nextIndex >= 0)
  11397. {
  11398. set (nextIndex, (*this)[nextIndex] + String (preNumberString) + String (++number) + String (postNumberString));
  11399. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11400. }
  11401. }
  11402. }
  11403. }
  11404. void StringArray::minimiseStorageOverheads()
  11405. {
  11406. strings.minimiseStorageOverheads();
  11407. }
  11408. END_JUCE_NAMESPACE
  11409. /*** End of inlined file: juce_StringArray.cpp ***/
  11410. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11411. BEGIN_JUCE_NAMESPACE
  11412. StringPairArray::StringPairArray (const bool ignoreCase_)
  11413. : ignoreCase (ignoreCase_)
  11414. {
  11415. }
  11416. StringPairArray::StringPairArray (const StringPairArray& other)
  11417. : keys (other.keys),
  11418. values (other.values),
  11419. ignoreCase (other.ignoreCase)
  11420. {
  11421. }
  11422. StringPairArray::~StringPairArray()
  11423. {
  11424. }
  11425. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11426. {
  11427. keys = other.keys;
  11428. values = other.values;
  11429. return *this;
  11430. }
  11431. bool StringPairArray::operator== (const StringPairArray& other) const
  11432. {
  11433. for (int i = keys.size(); --i >= 0;)
  11434. if (other [keys[i]] != values[i])
  11435. return false;
  11436. return true;
  11437. }
  11438. bool StringPairArray::operator!= (const StringPairArray& other) const
  11439. {
  11440. return ! operator== (other);
  11441. }
  11442. const String& StringPairArray::operator[] (const String& key) const
  11443. {
  11444. return values [keys.indexOf (key, ignoreCase)];
  11445. }
  11446. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11447. {
  11448. const int i = keys.indexOf (key, ignoreCase);
  11449. if (i >= 0)
  11450. return values[i];
  11451. return defaultReturnValue;
  11452. }
  11453. void StringPairArray::set (const String& key, const String& value)
  11454. {
  11455. const int i = keys.indexOf (key, ignoreCase);
  11456. if (i >= 0)
  11457. {
  11458. values.set (i, value);
  11459. }
  11460. else
  11461. {
  11462. keys.add (key);
  11463. values.add (value);
  11464. }
  11465. }
  11466. void StringPairArray::addArray (const StringPairArray& other)
  11467. {
  11468. for (int i = 0; i < other.size(); ++i)
  11469. set (other.keys[i], other.values[i]);
  11470. }
  11471. void StringPairArray::clear()
  11472. {
  11473. keys.clear();
  11474. values.clear();
  11475. }
  11476. void StringPairArray::remove (const String& key)
  11477. {
  11478. remove (keys.indexOf (key, ignoreCase));
  11479. }
  11480. void StringPairArray::remove (const int index)
  11481. {
  11482. keys.remove (index);
  11483. values.remove (index);
  11484. }
  11485. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11486. {
  11487. ignoreCase = shouldIgnoreCase;
  11488. }
  11489. const String StringPairArray::getDescription() const
  11490. {
  11491. String s;
  11492. for (int i = 0; i < keys.size(); ++i)
  11493. {
  11494. s << keys[i] << " = " << values[i];
  11495. if (i < keys.size())
  11496. s << ", ";
  11497. }
  11498. return s;
  11499. }
  11500. void StringPairArray::minimiseStorageOverheads()
  11501. {
  11502. keys.minimiseStorageOverheads();
  11503. values.minimiseStorageOverheads();
  11504. }
  11505. END_JUCE_NAMESPACE
  11506. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11507. /*** Start of inlined file: juce_StringPool.cpp ***/
  11508. BEGIN_JUCE_NAMESPACE
  11509. StringPool::StringPool() throw() {}
  11510. StringPool::~StringPool() {}
  11511. namespace StringPoolHelpers
  11512. {
  11513. template <class StringType>
  11514. const String::CharPointerType getPooledStringFromArray (Array<String>& strings, StringType newString)
  11515. {
  11516. int start = 0;
  11517. int end = strings.size();
  11518. for (;;)
  11519. {
  11520. if (start >= end)
  11521. {
  11522. jassert (start <= end);
  11523. strings.insert (start, newString);
  11524. return strings.getReference (start).getCharPointer();
  11525. }
  11526. else
  11527. {
  11528. const String& startString = strings.getReference (start);
  11529. if (startString == newString)
  11530. return startString.getCharPointer();
  11531. const int halfway = (start + end) >> 1;
  11532. if (halfway == start)
  11533. {
  11534. if (startString.compare (newString) < 0)
  11535. ++start;
  11536. strings.insert (start, newString);
  11537. return strings.getReference (start).getCharPointer();
  11538. }
  11539. const int comp = strings.getReference (halfway).compare (newString);
  11540. if (comp == 0)
  11541. return strings.getReference (halfway).getCharPointer();
  11542. else if (comp < 0)
  11543. start = halfway;
  11544. else
  11545. end = halfway;
  11546. }
  11547. }
  11548. }
  11549. }
  11550. const String::CharPointerType StringPool::getPooledString (const String& s)
  11551. {
  11552. if (s.isEmpty())
  11553. return String::empty.getCharPointer();
  11554. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11555. }
  11556. const String::CharPointerType StringPool::getPooledString (const char* const s)
  11557. {
  11558. if (s == 0 || *s == 0)
  11559. return String::empty.getCharPointer();
  11560. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11561. }
  11562. const String::CharPointerType StringPool::getPooledString (const juce_wchar* const s)
  11563. {
  11564. if (s == 0 || *s == 0)
  11565. return String::empty.getCharPointer();
  11566. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11567. }
  11568. int StringPool::size() const throw()
  11569. {
  11570. return strings.size();
  11571. }
  11572. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11573. {
  11574. return strings [index].getCharPointer();
  11575. }
  11576. END_JUCE_NAMESPACE
  11577. /*** End of inlined file: juce_StringPool.cpp ***/
  11578. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11579. BEGIN_JUCE_NAMESPACE
  11580. XmlDocument::XmlDocument (const String& documentText)
  11581. : originalText (documentText),
  11582. input (0),
  11583. ignoreEmptyTextElements (true)
  11584. {
  11585. }
  11586. XmlDocument::XmlDocument (const File& file)
  11587. : input (0),
  11588. ignoreEmptyTextElements (true),
  11589. inputSource (new FileInputSource (file))
  11590. {
  11591. }
  11592. XmlDocument::~XmlDocument()
  11593. {
  11594. }
  11595. XmlElement* XmlDocument::parse (const File& file)
  11596. {
  11597. XmlDocument doc (file);
  11598. return doc.getDocumentElement();
  11599. }
  11600. XmlElement* XmlDocument::parse (const String& xmlData)
  11601. {
  11602. XmlDocument doc (xmlData);
  11603. return doc.getDocumentElement();
  11604. }
  11605. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11606. {
  11607. inputSource = newSource;
  11608. }
  11609. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11610. {
  11611. ignoreEmptyTextElements = shouldBeIgnored;
  11612. }
  11613. namespace XmlIdentifierChars
  11614. {
  11615. bool isIdentifierCharSlow (const juce_wchar c) throw()
  11616. {
  11617. return CharacterFunctions::isLetterOrDigit (c)
  11618. || c == '_' || c == '-' || c == ':' || c == '.';
  11619. }
  11620. bool isIdentifierChar (const juce_wchar c) throw()
  11621. {
  11622. static const uint32 legalChars[] = { 0, 0x7ff6000, 0x87fffffe, 0x7fffffe, 0 };
  11623. return ((int) c < (int) numElementsInArray (legalChars) * 32) ? ((legalChars [c >> 5] & (1 << (c & 31))) != 0)
  11624. : isIdentifierCharSlow (c);
  11625. }
  11626. /*static void generateIdentifierCharConstants()
  11627. {
  11628. uint32 n[8];
  11629. zerostruct (n);
  11630. for (int i = 0; i < 256; ++i)
  11631. if (isIdentifierCharSlow (i))
  11632. n[i >> 5] |= (1 << (i & 31));
  11633. String s;
  11634. for (int i = 0; i < 8; ++i)
  11635. s << "0x" << String::toHexString ((int) n[i]) << ", ";
  11636. DBG (s);
  11637. }*/
  11638. }
  11639. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  11640. {
  11641. String textToParse (originalText);
  11642. if (textToParse.isEmpty() && inputSource != 0)
  11643. {
  11644. ScopedPointer <InputStream> in (inputSource->createInputStream());
  11645. if (in != 0)
  11646. {
  11647. MemoryOutputStream data;
  11648. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  11649. textToParse = data.toString();
  11650. if (! onlyReadOuterDocumentElement)
  11651. originalText = textToParse;
  11652. }
  11653. }
  11654. input = textToParse.getCharPointer();
  11655. lastError = String::empty;
  11656. errorOccurred = false;
  11657. outOfData = false;
  11658. needToLoadDTD = true;
  11659. if (textToParse.isEmpty())
  11660. {
  11661. lastError = "not enough input";
  11662. }
  11663. else
  11664. {
  11665. skipHeader();
  11666. if (input.getAddress() != 0)
  11667. {
  11668. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  11669. if (! errorOccurred)
  11670. return result.release();
  11671. }
  11672. else
  11673. {
  11674. lastError = "incorrect xml header";
  11675. }
  11676. }
  11677. return 0;
  11678. }
  11679. const String& XmlDocument::getLastParseError() const throw()
  11680. {
  11681. return lastError;
  11682. }
  11683. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  11684. {
  11685. lastError = desc;
  11686. errorOccurred = ! carryOn;
  11687. }
  11688. const String XmlDocument::getFileContents (const String& filename) const
  11689. {
  11690. if (inputSource != 0)
  11691. {
  11692. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  11693. if (in != 0)
  11694. return in->readEntireStreamAsString();
  11695. }
  11696. return String::empty;
  11697. }
  11698. juce_wchar XmlDocument::readNextChar() throw()
  11699. {
  11700. if (*input != 0)
  11701. return *input++;
  11702. outOfData = true;
  11703. return 0;
  11704. }
  11705. int XmlDocument::findNextTokenLength() throw()
  11706. {
  11707. int len = 0;
  11708. juce_wchar c = *input;
  11709. while (XmlIdentifierChars::isIdentifierChar (c))
  11710. c = input [++len];
  11711. return len;
  11712. }
  11713. void XmlDocument::skipHeader()
  11714. {
  11715. const int headerStart = input.indexOf (CharPointer_UTF8 ("<?xml"));
  11716. if (headerStart >= 0)
  11717. {
  11718. const int headerEnd = (input + headerStart).indexOf (CharPointer_UTF8 ("?>"));
  11719. if (headerEnd < 0)
  11720. return;
  11721. #if JUCE_DEBUG
  11722. const String header ((input + headerStart).getAddress(), headerEnd - headerStart);
  11723. const String encoding (header.fromFirstOccurrenceOf ("encoding", false, true)
  11724. .fromFirstOccurrenceOf ("=", false, false)
  11725. .fromFirstOccurrenceOf ("\"", false, false)
  11726. .upToFirstOccurrenceOf ("\"", false, false).trim());
  11727. /* If you load an XML document with a non-UTF encoding type, it may have been
  11728. loaded wrongly.. Since all the files are read via the normal juce file streams,
  11729. they're treated as UTF-8, so by the time it gets to the parser, the encoding will
  11730. have been lost. Best plan is to stick to utf-8 or if you have specific files to
  11731. read, use your own code to convert them to a unicode String, and pass that to the
  11732. XML parser.
  11733. */
  11734. jassert (encoding.isEmpty() || encoding.startsWithIgnoreCase ("utf-"));
  11735. #endif
  11736. input += headerEnd + 2;
  11737. }
  11738. skipNextWhiteSpace();
  11739. const int docTypeIndex = input.indexOf (CharPointer_UTF8 ("<!DOCTYPE"));
  11740. if (docTypeIndex < 0)
  11741. return;
  11742. input += docTypeIndex + 9;
  11743. const String::CharPointerType docType (input);
  11744. int n = 1;
  11745. while (n > 0)
  11746. {
  11747. const juce_wchar c = readNextChar();
  11748. if (outOfData)
  11749. return;
  11750. if (c == '<')
  11751. ++n;
  11752. else if (c == '>')
  11753. --n;
  11754. }
  11755. dtdText = String (docType.getAddress(), (int) (input.getAddress() - (docType.getAddress() + 1))).trim();
  11756. }
  11757. void XmlDocument::skipNextWhiteSpace()
  11758. {
  11759. for (;;)
  11760. {
  11761. juce_wchar c = *input;
  11762. while (CharacterFunctions::isWhitespace (c))
  11763. c = *++input;
  11764. if (c == 0)
  11765. {
  11766. outOfData = true;
  11767. break;
  11768. }
  11769. else if (c == '<')
  11770. {
  11771. if (input[1] == '!'
  11772. && input[2] == '-'
  11773. && input[3] == '-')
  11774. {
  11775. const int closeComment = input.indexOf (CharPointer_UTF8 ("-->"));
  11776. if (closeComment < 0)
  11777. {
  11778. outOfData = true;
  11779. break;
  11780. }
  11781. input += closeComment + 3;
  11782. continue;
  11783. }
  11784. else if (input[1] == '?')
  11785. {
  11786. const int closeBracket = input.indexOf (CharPointer_UTF8 ("?>"));
  11787. if (closeBracket < 0)
  11788. {
  11789. outOfData = true;
  11790. break;
  11791. }
  11792. input += closeBracket + 2;
  11793. continue;
  11794. }
  11795. }
  11796. break;
  11797. }
  11798. }
  11799. void XmlDocument::readQuotedString (String& result)
  11800. {
  11801. const juce_wchar quote = readNextChar();
  11802. while (! outOfData)
  11803. {
  11804. const juce_wchar c = readNextChar();
  11805. if (c == quote)
  11806. break;
  11807. if (c == '&')
  11808. {
  11809. --input;
  11810. readEntity (result);
  11811. }
  11812. else
  11813. {
  11814. --input;
  11815. const String::CharPointerType start (input);
  11816. for (;;)
  11817. {
  11818. const juce_wchar character = *input;
  11819. if (character == quote)
  11820. {
  11821. result.appendCharPointer (start, (int) (input.getAddress() - start.getAddress()));
  11822. ++input;
  11823. return;
  11824. }
  11825. else if (character == '&')
  11826. {
  11827. result.appendCharPointer (start, (int) (input.getAddress() - start.getAddress()));
  11828. break;
  11829. }
  11830. else if (character == 0)
  11831. {
  11832. outOfData = true;
  11833. setLastError ("unmatched quotes", false);
  11834. break;
  11835. }
  11836. ++input;
  11837. }
  11838. }
  11839. }
  11840. }
  11841. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  11842. {
  11843. XmlElement* node = 0;
  11844. skipNextWhiteSpace();
  11845. if (outOfData)
  11846. return 0;
  11847. const int openBracket = input.indexOf ((juce_wchar) '<');
  11848. if (openBracket >= 0)
  11849. {
  11850. input += openBracket + 1;
  11851. int tagLen = findNextTokenLength();
  11852. if (tagLen == 0)
  11853. {
  11854. // no tag name - but allow for a gap after the '<' before giving an error
  11855. skipNextWhiteSpace();
  11856. tagLen = findNextTokenLength();
  11857. if (tagLen == 0)
  11858. {
  11859. setLastError ("tag name missing", false);
  11860. return node;
  11861. }
  11862. }
  11863. node = new XmlElement (String (input.getAddress(), tagLen));
  11864. input += tagLen;
  11865. LinkedListPointer<XmlElement::XmlAttributeNode>::Appender attributeAppender (node->attributes);
  11866. // look for attributes
  11867. for (;;)
  11868. {
  11869. skipNextWhiteSpace();
  11870. const juce_wchar c = *input;
  11871. // empty tag..
  11872. if (c == '/' && input[1] == '>')
  11873. {
  11874. input += 2;
  11875. break;
  11876. }
  11877. // parse the guts of the element..
  11878. if (c == '>')
  11879. {
  11880. ++input;
  11881. if (alsoParseSubElements)
  11882. readChildElements (node);
  11883. break;
  11884. }
  11885. // get an attribute..
  11886. if (XmlIdentifierChars::isIdentifierChar (c))
  11887. {
  11888. const int attNameLen = findNextTokenLength();
  11889. if (attNameLen > 0)
  11890. {
  11891. const String::CharPointerType attNameStart (input);
  11892. input += attNameLen;
  11893. skipNextWhiteSpace();
  11894. if (readNextChar() == '=')
  11895. {
  11896. skipNextWhiteSpace();
  11897. const juce_wchar nextChar = *input;
  11898. if (nextChar == '"' || nextChar == '\'')
  11899. {
  11900. XmlElement::XmlAttributeNode* const newAtt
  11901. = new XmlElement::XmlAttributeNode (String (attNameStart.getAddress(), attNameLen),
  11902. String::empty);
  11903. readQuotedString (newAtt->value);
  11904. attributeAppender.append (newAtt);
  11905. continue;
  11906. }
  11907. }
  11908. }
  11909. }
  11910. else
  11911. {
  11912. if (! outOfData)
  11913. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  11914. }
  11915. break;
  11916. }
  11917. }
  11918. return node;
  11919. }
  11920. void XmlDocument::readChildElements (XmlElement* parent)
  11921. {
  11922. LinkedListPointer<XmlElement>::Appender childAppender (parent->firstChildElement);
  11923. for (;;)
  11924. {
  11925. const String::CharPointerType preWhitespaceInput (input);
  11926. skipNextWhiteSpace();
  11927. if (outOfData)
  11928. {
  11929. setLastError ("unmatched tags", false);
  11930. break;
  11931. }
  11932. if (*input == '<')
  11933. {
  11934. if (input[1] == '/')
  11935. {
  11936. // our close tag..
  11937. const int closeTag = input.indexOf ((juce_wchar) '>');
  11938. if (closeTag >= 0)
  11939. input += closeTag + 1;
  11940. break;
  11941. }
  11942. else if (input[1] == '!'
  11943. && input[2] == '['
  11944. && input[3] == 'C'
  11945. && input[4] == 'D'
  11946. && input[5] == 'A'
  11947. && input[6] == 'T'
  11948. && input[7] == 'A'
  11949. && input[8] == '[')
  11950. {
  11951. input += 9;
  11952. const String::CharPointerType inputStart (input);
  11953. int len = 0;
  11954. for (;;)
  11955. {
  11956. if (*input == 0)
  11957. {
  11958. setLastError ("unterminated CDATA section", false);
  11959. outOfData = true;
  11960. break;
  11961. }
  11962. else if (input[0] == ']'
  11963. && input[1] == ']'
  11964. && input[2] == '>')
  11965. {
  11966. input += 3;
  11967. break;
  11968. }
  11969. ++input;
  11970. ++len;
  11971. }
  11972. childAppender.append (XmlElement::createTextElement (String (inputStart.getAddress(), len)));
  11973. }
  11974. else
  11975. {
  11976. // this is some other element, so parse and add it..
  11977. XmlElement* const n = readNextElement (true);
  11978. if (n != 0)
  11979. childAppender.append (n);
  11980. else
  11981. return;
  11982. }
  11983. }
  11984. else // must be a character block
  11985. {
  11986. input = preWhitespaceInput; // roll back to include the leading whitespace
  11987. String textElementContent;
  11988. for (;;)
  11989. {
  11990. const juce_wchar c = *input;
  11991. if (c == '<')
  11992. break;
  11993. if (c == 0)
  11994. {
  11995. setLastError ("unmatched tags", false);
  11996. outOfData = true;
  11997. return;
  11998. }
  11999. if (c == '&')
  12000. {
  12001. String entity;
  12002. readEntity (entity);
  12003. if (entity.startsWithChar ('<') && entity [1] != 0)
  12004. {
  12005. const String::CharPointerType oldInput (input);
  12006. const bool oldOutOfData = outOfData;
  12007. input = entity.getCharPointer();
  12008. outOfData = false;
  12009. for (;;)
  12010. {
  12011. XmlElement* const n = readNextElement (true);
  12012. if (n == 0)
  12013. break;
  12014. childAppender.append (n);
  12015. }
  12016. input = oldInput;
  12017. outOfData = oldOutOfData;
  12018. }
  12019. else
  12020. {
  12021. textElementContent += entity;
  12022. }
  12023. }
  12024. else
  12025. {
  12026. const String::CharPointerType start (input);
  12027. int len = 0;
  12028. for (;;)
  12029. {
  12030. const juce_wchar nextChar = *input;
  12031. if (nextChar == '<' || nextChar == '&')
  12032. {
  12033. break;
  12034. }
  12035. else if (nextChar == 0)
  12036. {
  12037. setLastError ("unmatched tags", false);
  12038. outOfData = true;
  12039. return;
  12040. }
  12041. ++input;
  12042. ++len;
  12043. }
  12044. textElementContent.append (start.getAddress(), len);
  12045. }
  12046. }
  12047. if ((! ignoreEmptyTextElements) || textElementContent.containsNonWhitespaceChars())
  12048. {
  12049. childAppender.append (XmlElement::createTextElement (textElementContent));
  12050. }
  12051. }
  12052. }
  12053. }
  12054. void XmlDocument::readEntity (String& result)
  12055. {
  12056. // skip over the ampersand
  12057. ++input;
  12058. if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("amp;"), 4) == 0)
  12059. {
  12060. input += 4;
  12061. result += '&';
  12062. }
  12063. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("quot;"), 5) == 0)
  12064. {
  12065. input += 5;
  12066. result += '"';
  12067. }
  12068. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("apos;"), 5) == 0)
  12069. {
  12070. input += 5;
  12071. result += '\'';
  12072. }
  12073. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("lt;"), 3) == 0)
  12074. {
  12075. input += 3;
  12076. result += '<';
  12077. }
  12078. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("gt;"), 3) == 0)
  12079. {
  12080. input += 3;
  12081. result += '>';
  12082. }
  12083. else if (*input == '#')
  12084. {
  12085. int charCode = 0;
  12086. ++input;
  12087. if (*input == 'x' || *input == 'X')
  12088. {
  12089. ++input;
  12090. int numChars = 0;
  12091. while (input[0] != ';')
  12092. {
  12093. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  12094. if (hexValue < 0 || ++numChars > 8)
  12095. {
  12096. setLastError ("illegal escape sequence", true);
  12097. break;
  12098. }
  12099. charCode = (charCode << 4) | hexValue;
  12100. ++input;
  12101. }
  12102. ++input;
  12103. }
  12104. else if (input[0] >= '0' && input[0] <= '9')
  12105. {
  12106. int numChars = 0;
  12107. while (input[0] != ';')
  12108. {
  12109. if (++numChars > 12)
  12110. {
  12111. setLastError ("illegal escape sequence", true);
  12112. break;
  12113. }
  12114. charCode = charCode * 10 + (input[0] - '0');
  12115. ++input;
  12116. }
  12117. ++input;
  12118. }
  12119. else
  12120. {
  12121. setLastError ("illegal escape sequence", true);
  12122. result += '&';
  12123. return;
  12124. }
  12125. result << (juce_wchar) charCode;
  12126. }
  12127. else
  12128. {
  12129. const String::CharPointerType entityNameStart (input);
  12130. const int closingSemiColon = input.indexOf ((juce_wchar) ';');
  12131. if (closingSemiColon < 0)
  12132. {
  12133. outOfData = true;
  12134. result += '&';
  12135. }
  12136. else
  12137. {
  12138. input += closingSemiColon + 1;
  12139. result += expandExternalEntity (String (entityNameStart.getAddress(), closingSemiColon));
  12140. }
  12141. }
  12142. }
  12143. const String XmlDocument::expandEntity (const String& ent)
  12144. {
  12145. if (ent.equalsIgnoreCase ("amp")) return String::charToString ('&');
  12146. if (ent.equalsIgnoreCase ("quot")) return String::charToString ('"');
  12147. if (ent.equalsIgnoreCase ("apos")) return String::charToString ('\'');
  12148. if (ent.equalsIgnoreCase ("lt")) return String::charToString ('<');
  12149. if (ent.equalsIgnoreCase ("gt")) return String::charToString ('>');
  12150. if (ent[0] == '#')
  12151. {
  12152. if (ent[1] == 'x' || ent[1] == 'X')
  12153. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  12154. if (ent[1] >= '0' && ent[1] <= '9')
  12155. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  12156. setLastError ("illegal escape sequence", false);
  12157. return String::charToString ('&');
  12158. }
  12159. return expandExternalEntity (ent);
  12160. }
  12161. const String XmlDocument::expandExternalEntity (const String& entity)
  12162. {
  12163. if (needToLoadDTD)
  12164. {
  12165. if (dtdText.isNotEmpty())
  12166. {
  12167. dtdText = dtdText.trimCharactersAtEnd (">");
  12168. tokenisedDTD.addTokens (dtdText, true);
  12169. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  12170. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  12171. {
  12172. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  12173. tokenisedDTD.clear();
  12174. tokenisedDTD.addTokens (getFileContents (fn), true);
  12175. }
  12176. else
  12177. {
  12178. tokenisedDTD.clear();
  12179. const int openBracket = dtdText.indexOfChar ('[');
  12180. if (openBracket > 0)
  12181. {
  12182. const int closeBracket = dtdText.lastIndexOfChar (']');
  12183. if (closeBracket > openBracket)
  12184. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  12185. closeBracket), true);
  12186. }
  12187. }
  12188. for (int i = tokenisedDTD.size(); --i >= 0;)
  12189. {
  12190. if (tokenisedDTD[i].startsWithChar ('%')
  12191. && tokenisedDTD[i].endsWithChar (';'))
  12192. {
  12193. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  12194. StringArray newToks;
  12195. newToks.addTokens (parsed, true);
  12196. tokenisedDTD.remove (i);
  12197. for (int j = newToks.size(); --j >= 0;)
  12198. tokenisedDTD.insert (i, newToks[j]);
  12199. }
  12200. }
  12201. }
  12202. needToLoadDTD = false;
  12203. }
  12204. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12205. {
  12206. if (tokenisedDTD[i] == entity)
  12207. {
  12208. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12209. {
  12210. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12211. // check for sub-entities..
  12212. int ampersand = ent.indexOfChar ('&');
  12213. while (ampersand >= 0)
  12214. {
  12215. const int semiColon = ent.indexOf (i + 1, ";");
  12216. if (semiColon < 0)
  12217. {
  12218. setLastError ("entity without terminating semi-colon", false);
  12219. break;
  12220. }
  12221. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12222. ent = ent.substring (0, ampersand)
  12223. + resolved
  12224. + ent.substring (semiColon + 1);
  12225. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12226. }
  12227. return ent;
  12228. }
  12229. }
  12230. }
  12231. setLastError ("unknown entity", true);
  12232. return entity;
  12233. }
  12234. const String XmlDocument::getParameterEntity (const String& entity)
  12235. {
  12236. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12237. {
  12238. if (tokenisedDTD[i] == entity
  12239. && tokenisedDTD [i - 1] == "%"
  12240. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12241. {
  12242. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12243. if (ent.equalsIgnoreCase ("system"))
  12244. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12245. else
  12246. return ent.trim().unquoted();
  12247. }
  12248. }
  12249. return entity;
  12250. }
  12251. END_JUCE_NAMESPACE
  12252. /*** End of inlined file: juce_XmlDocument.cpp ***/
  12253. /*** Start of inlined file: juce_XmlElement.cpp ***/
  12254. BEGIN_JUCE_NAMESPACE
  12255. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  12256. : name (other.name),
  12257. value (other.value)
  12258. {
  12259. }
  12260. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12261. : name (name_),
  12262. value (value_)
  12263. {
  12264. #if JUCE_DEBUG
  12265. // this checks whether the attribute name string contains any illegal characters..
  12266. for (String::CharPointerType t (name.getCharPointer()); ! t.isEmpty(); ++t)
  12267. jassert (t.isLetterOrDigit() || *t == '_' || *t == '-' || *t == ':');
  12268. #endif
  12269. }
  12270. inline bool XmlElement::XmlAttributeNode::hasName (const String& nameToMatch) const throw()
  12271. {
  12272. return name.equalsIgnoreCase (nameToMatch);
  12273. }
  12274. XmlElement::XmlElement (const String& tagName_) throw()
  12275. : tagName (tagName_)
  12276. {
  12277. // the tag name mustn't be empty, or it'll look like a text element!
  12278. jassert (tagName_.containsNonWhitespaceChars())
  12279. // The tag can't contain spaces or other characters that would create invalid XML!
  12280. jassert (! tagName_.containsAnyOf (" <>/&"));
  12281. }
  12282. XmlElement::XmlElement (int /*dummy*/) throw()
  12283. {
  12284. }
  12285. XmlElement::XmlElement (const XmlElement& other)
  12286. : tagName (other.tagName)
  12287. {
  12288. copyChildrenAndAttributesFrom (other);
  12289. }
  12290. XmlElement& XmlElement::operator= (const XmlElement& other)
  12291. {
  12292. if (this != &other)
  12293. {
  12294. removeAllAttributes();
  12295. deleteAllChildElements();
  12296. tagName = other.tagName;
  12297. copyChildrenAndAttributesFrom (other);
  12298. }
  12299. return *this;
  12300. }
  12301. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12302. {
  12303. jassert (firstChildElement.get() == 0);
  12304. firstChildElement.addCopyOfList (other.firstChildElement);
  12305. jassert (attributes.get() == 0);
  12306. attributes.addCopyOfList (other.attributes);
  12307. }
  12308. XmlElement::~XmlElement() throw()
  12309. {
  12310. firstChildElement.deleteAll();
  12311. attributes.deleteAll();
  12312. }
  12313. namespace XmlOutputFunctions
  12314. {
  12315. /*bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12316. {
  12317. if ((character >= 'a' && character <= 'z')
  12318. || (character >= 'A' && character <= 'Z')
  12319. || (character >= '0' && character <= '9'))
  12320. return true;
  12321. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12322. do
  12323. {
  12324. if (((juce_wchar) (uint8) *t) == character)
  12325. return true;
  12326. }
  12327. while (*++t != 0);
  12328. return false;
  12329. }
  12330. void generateLegalCharConstants()
  12331. {
  12332. uint8 n[32];
  12333. zerostruct (n);
  12334. for (int i = 0; i < 256; ++i)
  12335. if (isLegalXmlCharSlow (i))
  12336. n[i >> 3] |= (1 << (i & 7));
  12337. String s;
  12338. for (int i = 0; i < 32; ++i)
  12339. s << (int) n[i] << ", ";
  12340. DBG (s);
  12341. }*/
  12342. bool isLegalXmlChar (const uint32 c) throw()
  12343. {
  12344. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12345. return c < sizeof (legalChars) * 8
  12346. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12347. }
  12348. void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12349. {
  12350. String::CharPointerType t (text.getCharPointer());
  12351. for (;;)
  12352. {
  12353. const uint32 character = (uint32) t.getAndAdvance();
  12354. if (character == 0)
  12355. break;
  12356. if (isLegalXmlChar (character))
  12357. {
  12358. outputStream << (char) character;
  12359. }
  12360. else
  12361. {
  12362. switch (character)
  12363. {
  12364. case '&': outputStream << "&amp;"; break;
  12365. case '"': outputStream << "&quot;"; break;
  12366. case '>': outputStream << "&gt;"; break;
  12367. case '<': outputStream << "&lt;"; break;
  12368. case '\n':
  12369. case '\r':
  12370. if (! changeNewLines)
  12371. {
  12372. outputStream << (char) character;
  12373. break;
  12374. }
  12375. // Note: deliberate fall-through here!
  12376. default:
  12377. outputStream << "&#" << ((int) character) << ';';
  12378. break;
  12379. }
  12380. }
  12381. }
  12382. }
  12383. void writeSpaces (OutputStream& out, int numSpaces)
  12384. {
  12385. if (numSpaces > 0)
  12386. {
  12387. const char blanks[] = " ";
  12388. const int blankSize = (int) numElementsInArray (blanks) - 1;
  12389. while (numSpaces > blankSize)
  12390. {
  12391. out.write (blanks, blankSize);
  12392. numSpaces -= blankSize;
  12393. }
  12394. out.write (blanks, numSpaces);
  12395. }
  12396. }
  12397. }
  12398. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12399. const int indentationLevel,
  12400. const int lineWrapLength) const
  12401. {
  12402. using namespace XmlOutputFunctions;
  12403. writeSpaces (outputStream, indentationLevel);
  12404. if (! isTextElement())
  12405. {
  12406. outputStream.writeByte ('<');
  12407. outputStream << tagName;
  12408. {
  12409. const int attIndent = indentationLevel + tagName.length() + 1;
  12410. int lineLen = 0;
  12411. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12412. {
  12413. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12414. {
  12415. outputStream << newLine;
  12416. writeSpaces (outputStream, attIndent);
  12417. lineLen = 0;
  12418. }
  12419. const int64 startPos = outputStream.getPosition();
  12420. outputStream.writeByte (' ');
  12421. outputStream << att->name;
  12422. outputStream.write ("=\"", 2);
  12423. escapeIllegalXmlChars (outputStream, att->value, true);
  12424. outputStream.writeByte ('"');
  12425. lineLen += (int) (outputStream.getPosition() - startPos);
  12426. }
  12427. }
  12428. if (firstChildElement != 0)
  12429. {
  12430. outputStream.writeByte ('>');
  12431. XmlElement* child = firstChildElement;
  12432. bool lastWasTextNode = false;
  12433. while (child != 0)
  12434. {
  12435. if (child->isTextElement())
  12436. {
  12437. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12438. lastWasTextNode = true;
  12439. }
  12440. else
  12441. {
  12442. if (indentationLevel >= 0 && ! lastWasTextNode)
  12443. outputStream << newLine;
  12444. child->writeElementAsText (outputStream,
  12445. lastWasTextNode ? 0 : (indentationLevel + (indentationLevel >= 0 ? 2 : 0)), lineWrapLength);
  12446. lastWasTextNode = false;
  12447. }
  12448. child = child->getNextElement();
  12449. }
  12450. if (indentationLevel >= 0 && ! lastWasTextNode)
  12451. {
  12452. outputStream << newLine;
  12453. writeSpaces (outputStream, indentationLevel);
  12454. }
  12455. outputStream.write ("</", 2);
  12456. outputStream << tagName;
  12457. outputStream.writeByte ('>');
  12458. }
  12459. else
  12460. {
  12461. outputStream.write ("/>", 2);
  12462. }
  12463. }
  12464. else
  12465. {
  12466. escapeIllegalXmlChars (outputStream, getText(), false);
  12467. }
  12468. }
  12469. const String XmlElement::createDocument (const String& dtdToUse,
  12470. const bool allOnOneLine,
  12471. const bool includeXmlHeader,
  12472. const String& encodingType,
  12473. const int lineWrapLength) const
  12474. {
  12475. MemoryOutputStream mem (2048);
  12476. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12477. return mem.toUTF8();
  12478. }
  12479. void XmlElement::writeToStream (OutputStream& output,
  12480. const String& dtdToUse,
  12481. const bool allOnOneLine,
  12482. const bool includeXmlHeader,
  12483. const String& encodingType,
  12484. const int lineWrapLength) const
  12485. {
  12486. using namespace XmlOutputFunctions;
  12487. if (includeXmlHeader)
  12488. {
  12489. output << "<?xml version=\"1.0\" encoding=\"" << encodingType << "\"?>";
  12490. if (allOnOneLine)
  12491. output.writeByte (' ');
  12492. else
  12493. output << newLine << newLine;
  12494. }
  12495. if (dtdToUse.isNotEmpty())
  12496. {
  12497. output << dtdToUse;
  12498. if (allOnOneLine)
  12499. output.writeByte (' ');
  12500. else
  12501. output << newLine;
  12502. }
  12503. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12504. if (! allOnOneLine)
  12505. output << newLine;
  12506. }
  12507. bool XmlElement::writeToFile (const File& file,
  12508. const String& dtdToUse,
  12509. const String& encodingType,
  12510. const int lineWrapLength) const
  12511. {
  12512. if (file.hasWriteAccess())
  12513. {
  12514. TemporaryFile tempFile (file);
  12515. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12516. if (out != 0)
  12517. {
  12518. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12519. out = 0;
  12520. return tempFile.overwriteTargetFileWithTemporary();
  12521. }
  12522. }
  12523. return false;
  12524. }
  12525. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12526. {
  12527. #if JUCE_DEBUG
  12528. // if debugging, check that the case is actually the same, because
  12529. // valid xml is case-sensitive, and although this lets it pass, it's
  12530. // better not to..
  12531. if (tagName.equalsIgnoreCase (tagNameWanted))
  12532. {
  12533. jassert (tagName == tagNameWanted);
  12534. return true;
  12535. }
  12536. else
  12537. {
  12538. return false;
  12539. }
  12540. #else
  12541. return tagName.equalsIgnoreCase (tagNameWanted);
  12542. #endif
  12543. }
  12544. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12545. {
  12546. XmlElement* e = nextListItem;
  12547. while (e != 0 && ! e->hasTagName (requiredTagName))
  12548. e = e->nextListItem;
  12549. return e;
  12550. }
  12551. int XmlElement::getNumAttributes() const throw()
  12552. {
  12553. return attributes.size();
  12554. }
  12555. const String& XmlElement::getAttributeName (const int index) const throw()
  12556. {
  12557. const XmlAttributeNode* const att = attributes [index];
  12558. return att != 0 ? att->name : String::empty;
  12559. }
  12560. const String& XmlElement::getAttributeValue (const int index) const throw()
  12561. {
  12562. const XmlAttributeNode* const att = attributes [index];
  12563. return att != 0 ? att->value : String::empty;
  12564. }
  12565. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  12566. {
  12567. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12568. if (att->hasName (attributeName))
  12569. return true;
  12570. return false;
  12571. }
  12572. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  12573. {
  12574. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12575. if (att->hasName (attributeName))
  12576. return att->value;
  12577. return String::empty;
  12578. }
  12579. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  12580. {
  12581. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12582. if (att->hasName (attributeName))
  12583. return att->value;
  12584. return defaultReturnValue;
  12585. }
  12586. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  12587. {
  12588. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12589. if (att->hasName (attributeName))
  12590. return att->value.getIntValue();
  12591. return defaultReturnValue;
  12592. }
  12593. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  12594. {
  12595. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12596. if (att->hasName (attributeName))
  12597. return att->value.getDoubleValue();
  12598. return defaultReturnValue;
  12599. }
  12600. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  12601. {
  12602. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12603. {
  12604. if (att->hasName (attributeName))
  12605. {
  12606. juce_wchar firstChar = att->value[0];
  12607. if (CharacterFunctions::isWhitespace (firstChar))
  12608. firstChar = att->value.trimStart() [0];
  12609. return firstChar == '1'
  12610. || firstChar == 't'
  12611. || firstChar == 'y'
  12612. || firstChar == 'T'
  12613. || firstChar == 'Y';
  12614. }
  12615. }
  12616. return defaultReturnValue;
  12617. }
  12618. bool XmlElement::compareAttribute (const String& attributeName,
  12619. const String& stringToCompareAgainst,
  12620. const bool ignoreCase) const throw()
  12621. {
  12622. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12623. if (att->hasName (attributeName))
  12624. return ignoreCase ? att->value.equalsIgnoreCase (stringToCompareAgainst)
  12625. : att->value == stringToCompareAgainst;
  12626. return false;
  12627. }
  12628. void XmlElement::setAttribute (const String& attributeName, const String& value)
  12629. {
  12630. if (attributes == 0)
  12631. {
  12632. attributes = new XmlAttributeNode (attributeName, value);
  12633. }
  12634. else
  12635. {
  12636. XmlAttributeNode* att = attributes;
  12637. for (;;)
  12638. {
  12639. if (att->hasName (attributeName))
  12640. {
  12641. att->value = value;
  12642. break;
  12643. }
  12644. else if (att->nextListItem == 0)
  12645. {
  12646. att->nextListItem = new XmlAttributeNode (attributeName, value);
  12647. break;
  12648. }
  12649. att = att->nextListItem;
  12650. }
  12651. }
  12652. }
  12653. void XmlElement::setAttribute (const String& attributeName, const int number)
  12654. {
  12655. setAttribute (attributeName, String (number));
  12656. }
  12657. void XmlElement::setAttribute (const String& attributeName, const double number)
  12658. {
  12659. setAttribute (attributeName, String (number));
  12660. }
  12661. void XmlElement::removeAttribute (const String& attributeName) throw()
  12662. {
  12663. LinkedListPointer<XmlAttributeNode>* att = &attributes;
  12664. while (att->get() != 0)
  12665. {
  12666. if (att->get()->hasName (attributeName))
  12667. {
  12668. delete att->removeNext();
  12669. break;
  12670. }
  12671. att = &(att->get()->nextListItem);
  12672. }
  12673. }
  12674. void XmlElement::removeAllAttributes() throw()
  12675. {
  12676. attributes.deleteAll();
  12677. }
  12678. int XmlElement::getNumChildElements() const throw()
  12679. {
  12680. return firstChildElement.size();
  12681. }
  12682. XmlElement* XmlElement::getChildElement (const int index) const throw()
  12683. {
  12684. return firstChildElement [index].get();
  12685. }
  12686. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  12687. {
  12688. XmlElement* child = firstChildElement;
  12689. while (child != 0)
  12690. {
  12691. if (child->hasTagName (childName))
  12692. break;
  12693. child = child->nextListItem;
  12694. }
  12695. return child;
  12696. }
  12697. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  12698. {
  12699. if (newNode != 0)
  12700. firstChildElement.append (newNode);
  12701. }
  12702. void XmlElement::insertChildElement (XmlElement* const newNode,
  12703. int indexToInsertAt) throw()
  12704. {
  12705. if (newNode != 0)
  12706. {
  12707. removeChildElement (newNode, false);
  12708. firstChildElement.insertAtIndex (indexToInsertAt, newNode);
  12709. }
  12710. }
  12711. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  12712. {
  12713. XmlElement* const newElement = new XmlElement (childTagName);
  12714. addChildElement (newElement);
  12715. return newElement;
  12716. }
  12717. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  12718. XmlElement* const newNode) throw()
  12719. {
  12720. if (newNode != 0)
  12721. {
  12722. LinkedListPointer<XmlElement>* const p = firstChildElement.findPointerTo (currentChildElement);
  12723. if (p != 0)
  12724. {
  12725. if (currentChildElement != newNode)
  12726. delete p->replaceNext (newNode);
  12727. return true;
  12728. }
  12729. }
  12730. return false;
  12731. }
  12732. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  12733. const bool shouldDeleteTheChild) throw()
  12734. {
  12735. if (childToRemove != 0)
  12736. {
  12737. firstChildElement.remove (childToRemove);
  12738. if (shouldDeleteTheChild)
  12739. delete childToRemove;
  12740. }
  12741. }
  12742. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  12743. const bool ignoreOrderOfAttributes) const throw()
  12744. {
  12745. if (this != other)
  12746. {
  12747. if (other == 0 || tagName != other->tagName)
  12748. return false;
  12749. if (ignoreOrderOfAttributes)
  12750. {
  12751. int totalAtts = 0;
  12752. const XmlAttributeNode* att = attributes;
  12753. while (att != 0)
  12754. {
  12755. if (! other->compareAttribute (att->name, att->value))
  12756. return false;
  12757. att = att->nextListItem;
  12758. ++totalAtts;
  12759. }
  12760. if (totalAtts != other->getNumAttributes())
  12761. return false;
  12762. }
  12763. else
  12764. {
  12765. const XmlAttributeNode* thisAtt = attributes;
  12766. const XmlAttributeNode* otherAtt = other->attributes;
  12767. for (;;)
  12768. {
  12769. if (thisAtt == 0 || otherAtt == 0)
  12770. {
  12771. if (thisAtt == otherAtt) // both 0, so it's a match
  12772. break;
  12773. return false;
  12774. }
  12775. if (thisAtt->name != otherAtt->name
  12776. || thisAtt->value != otherAtt->value)
  12777. {
  12778. return false;
  12779. }
  12780. thisAtt = thisAtt->nextListItem;
  12781. otherAtt = otherAtt->nextListItem;
  12782. }
  12783. }
  12784. const XmlElement* thisChild = firstChildElement;
  12785. const XmlElement* otherChild = other->firstChildElement;
  12786. for (;;)
  12787. {
  12788. if (thisChild == 0 || otherChild == 0)
  12789. {
  12790. if (thisChild == otherChild) // both 0, so it's a match
  12791. break;
  12792. return false;
  12793. }
  12794. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  12795. return false;
  12796. thisChild = thisChild->nextListItem;
  12797. otherChild = otherChild->nextListItem;
  12798. }
  12799. }
  12800. return true;
  12801. }
  12802. void XmlElement::deleteAllChildElements() throw()
  12803. {
  12804. firstChildElement.deleteAll();
  12805. }
  12806. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  12807. {
  12808. XmlElement* child = firstChildElement;
  12809. while (child != 0)
  12810. {
  12811. XmlElement* const nextChild = child->nextListItem;
  12812. if (child->hasTagName (name))
  12813. removeChildElement (child, true);
  12814. child = nextChild;
  12815. }
  12816. }
  12817. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  12818. {
  12819. return firstChildElement.contains (possibleChild);
  12820. }
  12821. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  12822. {
  12823. if (this == elementToLookFor || elementToLookFor == 0)
  12824. return 0;
  12825. XmlElement* child = firstChildElement;
  12826. while (child != 0)
  12827. {
  12828. if (elementToLookFor == child)
  12829. return this;
  12830. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  12831. if (found != 0)
  12832. return found;
  12833. child = child->nextListItem;
  12834. }
  12835. return 0;
  12836. }
  12837. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  12838. {
  12839. firstChildElement.copyToArray (elems);
  12840. }
  12841. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  12842. {
  12843. XmlElement* e = firstChildElement = elems[0];
  12844. for (int i = 1; i < num; ++i)
  12845. {
  12846. e->nextListItem = elems[i];
  12847. e = e->nextListItem;
  12848. }
  12849. e->nextListItem = 0;
  12850. }
  12851. bool XmlElement::isTextElement() const throw()
  12852. {
  12853. return tagName.isEmpty();
  12854. }
  12855. static const String juce_xmltextContentAttributeName ("text");
  12856. const String& XmlElement::getText() const throw()
  12857. {
  12858. jassert (isTextElement()); // you're trying to get the text from an element that
  12859. // isn't actually a text element.. If this contains text sub-nodes, you
  12860. // probably want to use getAllSubText instead.
  12861. return getStringAttribute (juce_xmltextContentAttributeName);
  12862. }
  12863. void XmlElement::setText (const String& newText)
  12864. {
  12865. if (isTextElement())
  12866. setAttribute (juce_xmltextContentAttributeName, newText);
  12867. else
  12868. jassertfalse; // you can only change the text in a text element, not a normal one.
  12869. }
  12870. const String XmlElement::getAllSubText() const
  12871. {
  12872. if (isTextElement())
  12873. return getText();
  12874. String result;
  12875. String::Concatenator concatenator (result);
  12876. const XmlElement* child = firstChildElement;
  12877. while (child != 0)
  12878. {
  12879. concatenator.append (child->getAllSubText());
  12880. child = child->nextListItem;
  12881. }
  12882. return result;
  12883. }
  12884. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  12885. const String& defaultReturnValue) const
  12886. {
  12887. const XmlElement* const child = getChildByName (childTagName);
  12888. if (child != 0)
  12889. return child->getAllSubText();
  12890. return defaultReturnValue;
  12891. }
  12892. XmlElement* XmlElement::createTextElement (const String& text)
  12893. {
  12894. XmlElement* const e = new XmlElement ((int) 0);
  12895. e->setAttribute (juce_xmltextContentAttributeName, text);
  12896. return e;
  12897. }
  12898. void XmlElement::addTextElement (const String& text)
  12899. {
  12900. addChildElement (createTextElement (text));
  12901. }
  12902. void XmlElement::deleteAllTextElements() throw()
  12903. {
  12904. XmlElement* child = firstChildElement;
  12905. while (child != 0)
  12906. {
  12907. XmlElement* const next = child->nextListItem;
  12908. if (child->isTextElement())
  12909. removeChildElement (child, true);
  12910. child = next;
  12911. }
  12912. }
  12913. END_JUCE_NAMESPACE
  12914. /*** End of inlined file: juce_XmlElement.cpp ***/
  12915. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  12916. BEGIN_JUCE_NAMESPACE
  12917. ReadWriteLock::ReadWriteLock() throw()
  12918. : numWaitingWriters (0),
  12919. numWriters (0),
  12920. writerThreadId (0)
  12921. {
  12922. }
  12923. ReadWriteLock::~ReadWriteLock() throw()
  12924. {
  12925. jassert (readerThreads.size() == 0);
  12926. jassert (numWriters == 0);
  12927. }
  12928. void ReadWriteLock::enterRead() const throw()
  12929. {
  12930. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12931. const ScopedLock sl (accessLock);
  12932. for (;;)
  12933. {
  12934. jassert (readerThreads.size() % 2 == 0);
  12935. int i;
  12936. for (i = 0; i < readerThreads.size(); i += 2)
  12937. if (readerThreads.getUnchecked(i) == threadId)
  12938. break;
  12939. if (i < readerThreads.size()
  12940. || numWriters + numWaitingWriters == 0
  12941. || (threadId == writerThreadId && numWriters > 0))
  12942. {
  12943. if (i < readerThreads.size())
  12944. {
  12945. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  12946. }
  12947. else
  12948. {
  12949. readerThreads.add (threadId);
  12950. readerThreads.add ((Thread::ThreadID) 1);
  12951. }
  12952. return;
  12953. }
  12954. const ScopedUnlock ul (accessLock);
  12955. waitEvent.wait (100);
  12956. }
  12957. }
  12958. void ReadWriteLock::exitRead() const throw()
  12959. {
  12960. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12961. const ScopedLock sl (accessLock);
  12962. for (int i = 0; i < readerThreads.size(); i += 2)
  12963. {
  12964. if (readerThreads.getUnchecked(i) == threadId)
  12965. {
  12966. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  12967. if (newCount == 0)
  12968. {
  12969. readerThreads.removeRange (i, 2);
  12970. waitEvent.signal();
  12971. }
  12972. else
  12973. {
  12974. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  12975. }
  12976. return;
  12977. }
  12978. }
  12979. jassertfalse; // unlocking a lock that wasn't locked..
  12980. }
  12981. void ReadWriteLock::enterWrite() const throw()
  12982. {
  12983. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12984. const ScopedLock sl (accessLock);
  12985. for (;;)
  12986. {
  12987. if (readerThreads.size() + numWriters == 0
  12988. || threadId == writerThreadId
  12989. || (readerThreads.size() == 2
  12990. && readerThreads.getUnchecked(0) == threadId))
  12991. {
  12992. writerThreadId = threadId;
  12993. ++numWriters;
  12994. break;
  12995. }
  12996. ++numWaitingWriters;
  12997. accessLock.exit();
  12998. waitEvent.wait (100);
  12999. accessLock.enter();
  13000. --numWaitingWriters;
  13001. }
  13002. }
  13003. bool ReadWriteLock::tryEnterWrite() const throw()
  13004. {
  13005. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13006. const ScopedLock sl (accessLock);
  13007. if (readerThreads.size() + numWriters == 0
  13008. || threadId == writerThreadId
  13009. || (readerThreads.size() == 2
  13010. && readerThreads.getUnchecked(0) == threadId))
  13011. {
  13012. writerThreadId = threadId;
  13013. ++numWriters;
  13014. return true;
  13015. }
  13016. return false;
  13017. }
  13018. void ReadWriteLock::exitWrite() const throw()
  13019. {
  13020. const ScopedLock sl (accessLock);
  13021. // check this thread actually had the lock..
  13022. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13023. if (--numWriters == 0)
  13024. {
  13025. writerThreadId = 0;
  13026. waitEvent.signal();
  13027. }
  13028. }
  13029. END_JUCE_NAMESPACE
  13030. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13031. /*** Start of inlined file: juce_Thread.cpp ***/
  13032. BEGIN_JUCE_NAMESPACE
  13033. class RunningThreadsList
  13034. {
  13035. public:
  13036. RunningThreadsList()
  13037. {
  13038. }
  13039. void add (Thread* const thread)
  13040. {
  13041. const ScopedLock sl (lock);
  13042. jassert (! threads.contains (thread));
  13043. threads.add (thread);
  13044. }
  13045. void remove (Thread* const thread)
  13046. {
  13047. const ScopedLock sl (lock);
  13048. jassert (threads.contains (thread));
  13049. threads.removeValue (thread);
  13050. }
  13051. int size() const throw()
  13052. {
  13053. return threads.size();
  13054. }
  13055. Thread* getThreadWithID (const Thread::ThreadID targetID) const throw()
  13056. {
  13057. const ScopedLock sl (lock);
  13058. for (int i = threads.size(); --i >= 0;)
  13059. {
  13060. Thread* const t = threads.getUnchecked(i);
  13061. if (t->getThreadId() == targetID)
  13062. return t;
  13063. }
  13064. return 0;
  13065. }
  13066. void stopAll (const int timeOutMilliseconds)
  13067. {
  13068. signalAllThreadsToStop();
  13069. for (;;)
  13070. {
  13071. Thread* firstThread = getFirstThread();
  13072. if (firstThread != 0)
  13073. firstThread->stopThread (timeOutMilliseconds);
  13074. else
  13075. break;
  13076. }
  13077. }
  13078. static RunningThreadsList& getInstance()
  13079. {
  13080. static RunningThreadsList runningThreads;
  13081. return runningThreads;
  13082. }
  13083. private:
  13084. Array<Thread*> threads;
  13085. CriticalSection lock;
  13086. void signalAllThreadsToStop()
  13087. {
  13088. const ScopedLock sl (lock);
  13089. for (int i = threads.size(); --i >= 0;)
  13090. threads.getUnchecked(i)->signalThreadShouldExit();
  13091. }
  13092. Thread* getFirstThread() const
  13093. {
  13094. const ScopedLock sl (lock);
  13095. return threads.getFirst();
  13096. }
  13097. };
  13098. void Thread::threadEntryPoint()
  13099. {
  13100. RunningThreadsList::getInstance().add (this);
  13101. JUCE_TRY
  13102. {
  13103. if (threadName_.isNotEmpty())
  13104. setCurrentThreadName (threadName_);
  13105. if (startSuspensionEvent_.wait (10000))
  13106. {
  13107. jassert (getCurrentThreadId() == threadId_);
  13108. if (affinityMask_ != 0)
  13109. setCurrentThreadAffinityMask (affinityMask_);
  13110. run();
  13111. }
  13112. }
  13113. JUCE_CATCH_ALL_ASSERT
  13114. RunningThreadsList::getInstance().remove (this);
  13115. closeThreadHandle();
  13116. }
  13117. // used to wrap the incoming call from the platform-specific code
  13118. void JUCE_API juce_threadEntryPoint (void* userData)
  13119. {
  13120. static_cast <Thread*> (userData)->threadEntryPoint();
  13121. }
  13122. Thread::Thread (const String& threadName)
  13123. : threadName_ (threadName),
  13124. threadHandle_ (0),
  13125. threadId_ (0),
  13126. threadPriority_ (5),
  13127. affinityMask_ (0),
  13128. threadShouldExit_ (false)
  13129. {
  13130. }
  13131. Thread::~Thread()
  13132. {
  13133. /* If your thread class's destructor has been called without first stopping the thread, that
  13134. means that this partially destructed object is still performing some work - and that's
  13135. probably a Bad Thing!
  13136. To avoid this type of nastiness, always make sure you call stopThread() before or during
  13137. your subclass's destructor.
  13138. */
  13139. jassert (! isThreadRunning());
  13140. stopThread (100);
  13141. }
  13142. void Thread::startThread()
  13143. {
  13144. const ScopedLock sl (startStopLock);
  13145. threadShouldExit_ = false;
  13146. if (threadHandle_ == 0)
  13147. {
  13148. launchThread();
  13149. setThreadPriority (threadHandle_, threadPriority_);
  13150. startSuspensionEvent_.signal();
  13151. }
  13152. }
  13153. void Thread::startThread (const int priority)
  13154. {
  13155. const ScopedLock sl (startStopLock);
  13156. if (threadHandle_ == 0)
  13157. {
  13158. threadPriority_ = priority;
  13159. startThread();
  13160. }
  13161. else
  13162. {
  13163. setPriority (priority);
  13164. }
  13165. }
  13166. bool Thread::isThreadRunning() const
  13167. {
  13168. return threadHandle_ != 0;
  13169. }
  13170. void Thread::signalThreadShouldExit()
  13171. {
  13172. threadShouldExit_ = true;
  13173. }
  13174. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13175. {
  13176. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13177. jassert (getThreadId() != getCurrentThreadId());
  13178. const int sleepMsPerIteration = 5;
  13179. int count = timeOutMilliseconds / sleepMsPerIteration;
  13180. while (isThreadRunning())
  13181. {
  13182. if (timeOutMilliseconds > 0 && --count < 0)
  13183. return false;
  13184. sleep (sleepMsPerIteration);
  13185. }
  13186. return true;
  13187. }
  13188. void Thread::stopThread (const int timeOutMilliseconds)
  13189. {
  13190. // agh! You can't stop the thread that's calling this method! How on earth
  13191. // would that work??
  13192. jassert (getCurrentThreadId() != getThreadId());
  13193. const ScopedLock sl (startStopLock);
  13194. if (isThreadRunning())
  13195. {
  13196. signalThreadShouldExit();
  13197. notify();
  13198. if (timeOutMilliseconds != 0)
  13199. waitForThreadToExit (timeOutMilliseconds);
  13200. if (isThreadRunning())
  13201. {
  13202. // very bad karma if this point is reached, as there are bound to be
  13203. // locks and events left in silly states when a thread is killed by force..
  13204. jassertfalse;
  13205. Logger::writeToLog ("!! killing thread by force !!");
  13206. killThread();
  13207. RunningThreadsList::getInstance().remove (this);
  13208. threadHandle_ = 0;
  13209. threadId_ = 0;
  13210. }
  13211. }
  13212. }
  13213. bool Thread::setPriority (const int priority)
  13214. {
  13215. const ScopedLock sl (startStopLock);
  13216. if (setThreadPriority (threadHandle_, priority))
  13217. {
  13218. threadPriority_ = priority;
  13219. return true;
  13220. }
  13221. return false;
  13222. }
  13223. bool Thread::setCurrentThreadPriority (const int priority)
  13224. {
  13225. return setThreadPriority (0, priority);
  13226. }
  13227. void Thread::setAffinityMask (const uint32 affinityMask)
  13228. {
  13229. affinityMask_ = affinityMask;
  13230. }
  13231. bool Thread::wait (const int timeOutMilliseconds) const
  13232. {
  13233. return defaultEvent_.wait (timeOutMilliseconds);
  13234. }
  13235. void Thread::notify() const
  13236. {
  13237. defaultEvent_.signal();
  13238. }
  13239. int Thread::getNumRunningThreads()
  13240. {
  13241. return RunningThreadsList::getInstance().size();
  13242. }
  13243. Thread* Thread::getCurrentThread()
  13244. {
  13245. return RunningThreadsList::getInstance().getThreadWithID (getCurrentThreadId());
  13246. }
  13247. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13248. {
  13249. RunningThreadsList::getInstance().stopAll (timeOutMilliseconds);
  13250. }
  13251. END_JUCE_NAMESPACE
  13252. /*** End of inlined file: juce_Thread.cpp ***/
  13253. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13254. BEGIN_JUCE_NAMESPACE
  13255. ThreadPoolJob::ThreadPoolJob (const String& name)
  13256. : jobName (name),
  13257. pool (0),
  13258. shouldStop (false),
  13259. isActive (false),
  13260. shouldBeDeleted (false)
  13261. {
  13262. }
  13263. ThreadPoolJob::~ThreadPoolJob()
  13264. {
  13265. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13266. // to remove it first!
  13267. jassert (pool == 0 || ! pool->contains (this));
  13268. }
  13269. const String ThreadPoolJob::getJobName() const
  13270. {
  13271. return jobName;
  13272. }
  13273. void ThreadPoolJob::setJobName (const String& newName)
  13274. {
  13275. jobName = newName;
  13276. }
  13277. void ThreadPoolJob::signalJobShouldExit()
  13278. {
  13279. shouldStop = true;
  13280. }
  13281. class ThreadPool::ThreadPoolThread : public Thread
  13282. {
  13283. public:
  13284. ThreadPoolThread (ThreadPool& pool_)
  13285. : Thread ("Pool"),
  13286. pool (pool_),
  13287. busy (false)
  13288. {
  13289. }
  13290. void run()
  13291. {
  13292. while (! threadShouldExit())
  13293. {
  13294. if (! pool.runNextJob())
  13295. wait (500);
  13296. }
  13297. }
  13298. private:
  13299. ThreadPool& pool;
  13300. bool volatile busy;
  13301. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolThread);
  13302. };
  13303. ThreadPool::ThreadPool (const int numThreads,
  13304. const bool startThreadsOnlyWhenNeeded,
  13305. const int stopThreadsWhenNotUsedTimeoutMs)
  13306. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13307. priority (5)
  13308. {
  13309. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13310. for (int i = jmax (1, numThreads); --i >= 0;)
  13311. threads.add (new ThreadPoolThread (*this));
  13312. if (! startThreadsOnlyWhenNeeded)
  13313. for (int i = threads.size(); --i >= 0;)
  13314. threads.getUnchecked(i)->startThread (priority);
  13315. }
  13316. ThreadPool::~ThreadPool()
  13317. {
  13318. removeAllJobs (true, 4000);
  13319. int i;
  13320. for (i = threads.size(); --i >= 0;)
  13321. threads.getUnchecked(i)->signalThreadShouldExit();
  13322. for (i = threads.size(); --i >= 0;)
  13323. threads.getUnchecked(i)->stopThread (500);
  13324. }
  13325. void ThreadPool::addJob (ThreadPoolJob* const job)
  13326. {
  13327. jassert (job != 0);
  13328. jassert (job->pool == 0);
  13329. if (job->pool == 0)
  13330. {
  13331. job->pool = this;
  13332. job->shouldStop = false;
  13333. job->isActive = false;
  13334. {
  13335. const ScopedLock sl (lock);
  13336. jobs.add (job);
  13337. int numRunning = 0;
  13338. for (int i = threads.size(); --i >= 0;)
  13339. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13340. ++numRunning;
  13341. if (numRunning < threads.size())
  13342. {
  13343. bool startedOne = false;
  13344. int n = 1000;
  13345. while (--n >= 0 && ! startedOne)
  13346. {
  13347. for (int i = threads.size(); --i >= 0;)
  13348. {
  13349. if (! threads.getUnchecked(i)->isThreadRunning())
  13350. {
  13351. threads.getUnchecked(i)->startThread (priority);
  13352. startedOne = true;
  13353. break;
  13354. }
  13355. }
  13356. if (! startedOne)
  13357. Thread::sleep (2);
  13358. }
  13359. }
  13360. }
  13361. for (int i = threads.size(); --i >= 0;)
  13362. threads.getUnchecked(i)->notify();
  13363. }
  13364. }
  13365. int ThreadPool::getNumJobs() const
  13366. {
  13367. return jobs.size();
  13368. }
  13369. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13370. {
  13371. const ScopedLock sl (lock);
  13372. return jobs [index];
  13373. }
  13374. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13375. {
  13376. const ScopedLock sl (lock);
  13377. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13378. }
  13379. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13380. {
  13381. const ScopedLock sl (lock);
  13382. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13383. }
  13384. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13385. const int timeOutMs) const
  13386. {
  13387. if (job != 0)
  13388. {
  13389. const uint32 start = Time::getMillisecondCounter();
  13390. while (contains (job))
  13391. {
  13392. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13393. return false;
  13394. jobFinishedSignal.wait (2);
  13395. }
  13396. }
  13397. return true;
  13398. }
  13399. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13400. const bool interruptIfRunning,
  13401. const int timeOutMs)
  13402. {
  13403. bool dontWait = true;
  13404. if (job != 0)
  13405. {
  13406. const ScopedLock sl (lock);
  13407. if (jobs.contains (job))
  13408. {
  13409. if (job->isActive)
  13410. {
  13411. if (interruptIfRunning)
  13412. job->signalJobShouldExit();
  13413. dontWait = false;
  13414. }
  13415. else
  13416. {
  13417. jobs.removeValue (job);
  13418. job->pool = 0;
  13419. }
  13420. }
  13421. }
  13422. return dontWait || waitForJobToFinish (job, timeOutMs);
  13423. }
  13424. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13425. const int timeOutMs,
  13426. const bool deleteInactiveJobs,
  13427. ThreadPool::JobSelector* selectedJobsToRemove)
  13428. {
  13429. Array <ThreadPoolJob*> jobsToWaitFor;
  13430. {
  13431. const ScopedLock sl (lock);
  13432. for (int i = jobs.size(); --i >= 0;)
  13433. {
  13434. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13435. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13436. {
  13437. if (job->isActive)
  13438. {
  13439. jobsToWaitFor.add (job);
  13440. if (interruptRunningJobs)
  13441. job->signalJobShouldExit();
  13442. }
  13443. else
  13444. {
  13445. jobs.remove (i);
  13446. if (deleteInactiveJobs)
  13447. delete job;
  13448. else
  13449. job->pool = 0;
  13450. }
  13451. }
  13452. }
  13453. }
  13454. const uint32 start = Time::getMillisecondCounter();
  13455. for (;;)
  13456. {
  13457. for (int i = jobsToWaitFor.size(); --i >= 0;)
  13458. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  13459. jobsToWaitFor.remove (i);
  13460. if (jobsToWaitFor.size() == 0)
  13461. break;
  13462. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13463. return false;
  13464. jobFinishedSignal.wait (20);
  13465. }
  13466. return true;
  13467. }
  13468. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  13469. {
  13470. StringArray s;
  13471. const ScopedLock sl (lock);
  13472. for (int i = 0; i < jobs.size(); ++i)
  13473. {
  13474. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  13475. if (job->isActive || ! onlyReturnActiveJobs)
  13476. s.add (job->getJobName());
  13477. }
  13478. return s;
  13479. }
  13480. bool ThreadPool::setThreadPriorities (const int newPriority)
  13481. {
  13482. bool ok = true;
  13483. if (priority != newPriority)
  13484. {
  13485. priority = newPriority;
  13486. for (int i = threads.size(); --i >= 0;)
  13487. if (! threads.getUnchecked(i)->setPriority (newPriority))
  13488. ok = false;
  13489. }
  13490. return ok;
  13491. }
  13492. bool ThreadPool::runNextJob()
  13493. {
  13494. ThreadPoolJob* job = 0;
  13495. {
  13496. const ScopedLock sl (lock);
  13497. for (int i = 0; i < jobs.size(); ++i)
  13498. {
  13499. job = jobs[i];
  13500. if (job != 0 && ! (job->isActive || job->shouldStop))
  13501. break;
  13502. job = 0;
  13503. }
  13504. if (job != 0)
  13505. job->isActive = true;
  13506. }
  13507. if (job != 0)
  13508. {
  13509. JUCE_TRY
  13510. {
  13511. ThreadPoolJob::JobStatus result = job->runJob();
  13512. lastJobEndTime = Time::getApproximateMillisecondCounter();
  13513. const ScopedLock sl (lock);
  13514. if (jobs.contains (job))
  13515. {
  13516. job->isActive = false;
  13517. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  13518. {
  13519. job->pool = 0;
  13520. job->shouldStop = true;
  13521. jobs.removeValue (job);
  13522. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  13523. delete job;
  13524. jobFinishedSignal.signal();
  13525. }
  13526. else
  13527. {
  13528. // move the job to the end of the queue if it wants another go
  13529. jobs.move (jobs.indexOf (job), -1);
  13530. }
  13531. }
  13532. }
  13533. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13534. catch (...)
  13535. {
  13536. const ScopedLock sl (lock);
  13537. jobs.removeValue (job);
  13538. }
  13539. #endif
  13540. }
  13541. else
  13542. {
  13543. if (threadStopTimeout > 0
  13544. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  13545. {
  13546. const ScopedLock sl (lock);
  13547. if (jobs.size() == 0)
  13548. for (int i = threads.size(); --i >= 0;)
  13549. threads.getUnchecked(i)->signalThreadShouldExit();
  13550. }
  13551. else
  13552. {
  13553. return false;
  13554. }
  13555. }
  13556. return true;
  13557. }
  13558. END_JUCE_NAMESPACE
  13559. /*** End of inlined file: juce_ThreadPool.cpp ***/
  13560. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  13561. BEGIN_JUCE_NAMESPACE
  13562. TimeSliceThread::TimeSliceThread (const String& threadName)
  13563. : Thread (threadName),
  13564. clientBeingCalled (0)
  13565. {
  13566. }
  13567. TimeSliceThread::~TimeSliceThread()
  13568. {
  13569. stopThread (2000);
  13570. }
  13571. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client, int millisecondsBeforeStarting)
  13572. {
  13573. if (client != 0)
  13574. {
  13575. const ScopedLock sl (listLock);
  13576. client->nextCallTime = Time::getCurrentTime() + RelativeTime::milliseconds (millisecondsBeforeStarting);
  13577. clients.addIfNotAlreadyThere (client);
  13578. notify();
  13579. }
  13580. }
  13581. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  13582. {
  13583. const ScopedLock sl1 (listLock);
  13584. // if there's a chance we're in the middle of calling this client, we need to
  13585. // also lock the outer lock..
  13586. if (clientBeingCalled == client)
  13587. {
  13588. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  13589. const ScopedLock sl2 (callbackLock);
  13590. const ScopedLock sl3 (listLock);
  13591. clients.removeValue (client);
  13592. }
  13593. else
  13594. {
  13595. clients.removeValue (client);
  13596. }
  13597. }
  13598. int TimeSliceThread::getNumClients() const
  13599. {
  13600. return clients.size();
  13601. }
  13602. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  13603. {
  13604. const ScopedLock sl (listLock);
  13605. return clients [i];
  13606. }
  13607. TimeSliceClient* TimeSliceThread::getNextClient (int index) const
  13608. {
  13609. Time soonest;
  13610. TimeSliceClient* client = 0;
  13611. for (int i = clients.size(); --i >= 0;)
  13612. {
  13613. TimeSliceClient* const c = clients.getUnchecked ((i + index) % clients.size());
  13614. if (client == 0 || c->nextCallTime < soonest)
  13615. {
  13616. client = c;
  13617. soonest = c->nextCallTime;
  13618. }
  13619. }
  13620. return client;
  13621. }
  13622. void TimeSliceThread::run()
  13623. {
  13624. int index = 0;
  13625. while (! threadShouldExit())
  13626. {
  13627. int timeToWait = 500;
  13628. {
  13629. Time nextClientTime;
  13630. {
  13631. const ScopedLock sl2 (listLock);
  13632. index = clients.size() > 0 ? ((index + 1) % clients.size()) : 0;
  13633. TimeSliceClient* const firstClient = getNextClient (index);
  13634. if (firstClient != 0)
  13635. nextClientTime = firstClient->nextCallTime;
  13636. }
  13637. const Time now (Time::getCurrentTime());
  13638. if (nextClientTime > now)
  13639. {
  13640. timeToWait = (int) jmin ((int64) 500, (nextClientTime - now).inMilliseconds());
  13641. }
  13642. else
  13643. {
  13644. timeToWait = index == 0 ? 1 : 0;
  13645. const ScopedLock sl (callbackLock);
  13646. {
  13647. const ScopedLock sl2 (listLock);
  13648. clientBeingCalled = getNextClient (index);
  13649. }
  13650. if (clientBeingCalled != 0)
  13651. {
  13652. const int msUntilNextCall = clientBeingCalled->useTimeSlice();
  13653. const ScopedLock sl2 (listLock);
  13654. if (msUntilNextCall >= 0)
  13655. clientBeingCalled->nextCallTime += RelativeTime::milliseconds (msUntilNextCall);
  13656. else
  13657. clients.removeValue (clientBeingCalled);
  13658. clientBeingCalled = 0;
  13659. }
  13660. }
  13661. }
  13662. if (timeToWait > 0)
  13663. wait (timeToWait);
  13664. }
  13665. }
  13666. END_JUCE_NAMESPACE
  13667. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  13668. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  13669. BEGIN_JUCE_NAMESPACE
  13670. DeletedAtShutdown::DeletedAtShutdown()
  13671. {
  13672. const ScopedLock sl (getLock());
  13673. getObjects().add (this);
  13674. }
  13675. DeletedAtShutdown::~DeletedAtShutdown()
  13676. {
  13677. const ScopedLock sl (getLock());
  13678. getObjects().removeValue (this);
  13679. }
  13680. void DeletedAtShutdown::deleteAll()
  13681. {
  13682. // make a local copy of the array, so it can't get into a loop if something
  13683. // creates another DeletedAtShutdown object during its destructor.
  13684. Array <DeletedAtShutdown*> localCopy;
  13685. {
  13686. const ScopedLock sl (getLock());
  13687. localCopy = getObjects();
  13688. }
  13689. for (int i = localCopy.size(); --i >= 0;)
  13690. {
  13691. JUCE_TRY
  13692. {
  13693. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  13694. // double-check that it's not already been deleted during another object's destructor.
  13695. {
  13696. const ScopedLock sl (getLock());
  13697. if (! getObjects().contains (deletee))
  13698. deletee = 0;
  13699. }
  13700. delete deletee;
  13701. }
  13702. JUCE_CATCH_EXCEPTION
  13703. }
  13704. // if no objects got re-created during shutdown, this should have been emptied by their
  13705. // destructors
  13706. jassert (getObjects().size() == 0);
  13707. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  13708. }
  13709. CriticalSection& DeletedAtShutdown::getLock()
  13710. {
  13711. static CriticalSection lock;
  13712. return lock;
  13713. }
  13714. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  13715. {
  13716. static Array <DeletedAtShutdown*> objects;
  13717. return objects;
  13718. }
  13719. END_JUCE_NAMESPACE
  13720. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  13721. /*** Start of inlined file: juce_UnitTest.cpp ***/
  13722. BEGIN_JUCE_NAMESPACE
  13723. UnitTest::UnitTest (const String& name_)
  13724. : name (name_), runner (0)
  13725. {
  13726. getAllTests().add (this);
  13727. }
  13728. UnitTest::~UnitTest()
  13729. {
  13730. getAllTests().removeValue (this);
  13731. }
  13732. Array<UnitTest*>& UnitTest::getAllTests()
  13733. {
  13734. static Array<UnitTest*> tests;
  13735. return tests;
  13736. }
  13737. void UnitTest::initialise() {}
  13738. void UnitTest::shutdown() {}
  13739. void UnitTest::performTest (UnitTestRunner* const runner_)
  13740. {
  13741. jassert (runner_ != 0);
  13742. runner = runner_;
  13743. initialise();
  13744. runTest();
  13745. shutdown();
  13746. }
  13747. void UnitTest::logMessage (const String& message)
  13748. {
  13749. runner->logMessage (message);
  13750. }
  13751. void UnitTest::beginTest (const String& testName)
  13752. {
  13753. runner->beginNewTest (this, testName);
  13754. }
  13755. void UnitTest::expect (const bool result, const String& failureMessage)
  13756. {
  13757. if (result)
  13758. runner->addPass();
  13759. else
  13760. runner->addFail (failureMessage);
  13761. }
  13762. UnitTestRunner::UnitTestRunner()
  13763. : currentTest (0), assertOnFailure (false)
  13764. {
  13765. }
  13766. UnitTestRunner::~UnitTestRunner()
  13767. {
  13768. }
  13769. int UnitTestRunner::getNumResults() const throw()
  13770. {
  13771. return results.size();
  13772. }
  13773. const UnitTestRunner::TestResult* UnitTestRunner::getResult (int index) const throw()
  13774. {
  13775. return results [index];
  13776. }
  13777. void UnitTestRunner::resultsUpdated()
  13778. {
  13779. }
  13780. void UnitTestRunner::runTests (const Array<UnitTest*>& tests, const bool assertOnFailure_)
  13781. {
  13782. results.clear();
  13783. assertOnFailure = assertOnFailure_;
  13784. resultsUpdated();
  13785. for (int i = 0; i < tests.size(); ++i)
  13786. {
  13787. try
  13788. {
  13789. tests.getUnchecked(i)->performTest (this);
  13790. }
  13791. catch (...)
  13792. {
  13793. addFail ("An unhandled exception was thrown!");
  13794. }
  13795. }
  13796. endTest();
  13797. }
  13798. void UnitTestRunner::runAllTests (const bool assertOnFailure_)
  13799. {
  13800. runTests (UnitTest::getAllTests(), assertOnFailure_);
  13801. }
  13802. void UnitTestRunner::logMessage (const String& message)
  13803. {
  13804. Logger::writeToLog (message);
  13805. }
  13806. void UnitTestRunner::beginNewTest (UnitTest* const test, const String& subCategory)
  13807. {
  13808. endTest();
  13809. currentTest = test;
  13810. TestResult* const r = new TestResult();
  13811. r->unitTestName = test->getName();
  13812. r->subcategoryName = subCategory;
  13813. r->passes = 0;
  13814. r->failures = 0;
  13815. results.add (r);
  13816. logMessage ("-----------------------------------------------------------------");
  13817. logMessage ("Starting test: " + r->unitTestName + " / " + subCategory + "...");
  13818. resultsUpdated();
  13819. }
  13820. void UnitTestRunner::endTest()
  13821. {
  13822. if (results.size() > 0)
  13823. {
  13824. TestResult* const r = results.getLast();
  13825. if (r->failures > 0)
  13826. {
  13827. String m ("FAILED!!");
  13828. m << r->failures << (r->failures == 1 ? "test" : "tests")
  13829. << " failed, out of a total of " << (r->passes + r->failures);
  13830. logMessage (String::empty);
  13831. logMessage (m);
  13832. logMessage (String::empty);
  13833. }
  13834. else
  13835. {
  13836. logMessage ("All tests completed successfully");
  13837. }
  13838. }
  13839. }
  13840. void UnitTestRunner::addPass()
  13841. {
  13842. {
  13843. const ScopedLock sl (results.getLock());
  13844. TestResult* const r = results.getLast();
  13845. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  13846. r->passes++;
  13847. String message ("Test ");
  13848. message << (r->failures + r->passes) << " passed";
  13849. logMessage (message);
  13850. }
  13851. resultsUpdated();
  13852. }
  13853. void UnitTestRunner::addFail (const String& failureMessage)
  13854. {
  13855. {
  13856. const ScopedLock sl (results.getLock());
  13857. TestResult* const r = results.getLast();
  13858. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  13859. r->failures++;
  13860. String message ("!!! Test ");
  13861. message << (r->failures + r->passes) << " failed";
  13862. if (failureMessage.isNotEmpty())
  13863. message << ": " << failureMessage;
  13864. r->messages.add (message);
  13865. logMessage (message);
  13866. }
  13867. resultsUpdated();
  13868. if (assertOnFailure) { jassertfalse }
  13869. }
  13870. END_JUCE_NAMESPACE
  13871. /*** End of inlined file: juce_UnitTest.cpp ***/
  13872. #endif
  13873. #if JUCE_BUILD_MISC
  13874. /*** Start of inlined file: juce_ValueTree.cpp ***/
  13875. BEGIN_JUCE_NAMESPACE
  13876. class ValueTree::SetPropertyAction : public UndoableAction
  13877. {
  13878. public:
  13879. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  13880. const var& newValue_, const var& oldValue_,
  13881. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  13882. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  13883. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  13884. {
  13885. }
  13886. bool perform()
  13887. {
  13888. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  13889. if (isDeletingProperty)
  13890. target->removeProperty (name, 0);
  13891. else
  13892. target->setProperty (name, newValue, 0);
  13893. return true;
  13894. }
  13895. bool undo()
  13896. {
  13897. if (isAddingNewProperty)
  13898. target->removeProperty (name, 0);
  13899. else
  13900. target->setProperty (name, oldValue, 0);
  13901. return true;
  13902. }
  13903. int getSizeInUnits()
  13904. {
  13905. return (int) sizeof (*this); //xxx should be more accurate
  13906. }
  13907. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13908. {
  13909. if (! (isAddingNewProperty || isDeletingProperty))
  13910. {
  13911. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  13912. if (next != 0 && next->target == target && next->name == name
  13913. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  13914. {
  13915. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  13916. }
  13917. }
  13918. return 0;
  13919. }
  13920. private:
  13921. const SharedObjectPtr target;
  13922. const Identifier name;
  13923. const var newValue;
  13924. var oldValue;
  13925. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  13926. JUCE_DECLARE_NON_COPYABLE (SetPropertyAction);
  13927. };
  13928. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  13929. {
  13930. public:
  13931. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  13932. const SharedObjectPtr& newChild_)
  13933. : target (target_),
  13934. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  13935. childIndex (childIndex_),
  13936. isDeleting (newChild_ == 0)
  13937. {
  13938. jassert (child != 0);
  13939. }
  13940. bool perform()
  13941. {
  13942. if (isDeleting)
  13943. target->removeChild (childIndex, 0);
  13944. else
  13945. target->addChild (child, childIndex, 0);
  13946. return true;
  13947. }
  13948. bool undo()
  13949. {
  13950. if (isDeleting)
  13951. {
  13952. target->addChild (child, childIndex, 0);
  13953. }
  13954. else
  13955. {
  13956. // If you hit this, it seems that your object's state is getting confused - probably
  13957. // because you've interleaved some undoable and non-undoable operations?
  13958. jassert (childIndex < target->children.size());
  13959. target->removeChild (childIndex, 0);
  13960. }
  13961. return true;
  13962. }
  13963. int getSizeInUnits()
  13964. {
  13965. return (int) sizeof (*this); //xxx should be more accurate
  13966. }
  13967. private:
  13968. const SharedObjectPtr target, child;
  13969. const int childIndex;
  13970. const bool isDeleting;
  13971. JUCE_DECLARE_NON_COPYABLE (AddOrRemoveChildAction);
  13972. };
  13973. class ValueTree::MoveChildAction : public UndoableAction
  13974. {
  13975. public:
  13976. MoveChildAction (const SharedObjectPtr& parent_,
  13977. const int startIndex_, const int endIndex_)
  13978. : parent (parent_),
  13979. startIndex (startIndex_),
  13980. endIndex (endIndex_)
  13981. {
  13982. }
  13983. bool perform()
  13984. {
  13985. parent->moveChild (startIndex, endIndex, 0);
  13986. return true;
  13987. }
  13988. bool undo()
  13989. {
  13990. parent->moveChild (endIndex, startIndex, 0);
  13991. return true;
  13992. }
  13993. int getSizeInUnits()
  13994. {
  13995. return (int) sizeof (*this); //xxx should be more accurate
  13996. }
  13997. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13998. {
  13999. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  14000. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  14001. return new MoveChildAction (parent, startIndex, next->endIndex);
  14002. return 0;
  14003. }
  14004. private:
  14005. const SharedObjectPtr parent;
  14006. const int startIndex, endIndex;
  14007. JUCE_DECLARE_NON_COPYABLE (MoveChildAction);
  14008. };
  14009. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  14010. : type (type_), parent (0)
  14011. {
  14012. }
  14013. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  14014. : type (other.type), properties (other.properties), parent (0)
  14015. {
  14016. for (int i = 0; i < other.children.size(); ++i)
  14017. {
  14018. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  14019. child->parent = this;
  14020. children.add (child);
  14021. }
  14022. }
  14023. ValueTree::SharedObject::~SharedObject()
  14024. {
  14025. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  14026. for (int i = children.size(); --i >= 0;)
  14027. {
  14028. const SharedObjectPtr c (children.getUnchecked(i));
  14029. c->parent = 0;
  14030. children.remove (i);
  14031. c->sendParentChangeMessage();
  14032. }
  14033. }
  14034. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  14035. {
  14036. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14037. {
  14038. ValueTree* const v = valueTreesWithListeners[i];
  14039. if (v != 0)
  14040. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  14041. }
  14042. }
  14043. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  14044. {
  14045. ValueTree tree (this);
  14046. ValueTree::SharedObject* t = this;
  14047. while (t != 0)
  14048. {
  14049. t->sendPropertyChangeMessage (tree, property);
  14050. t = t->parent;
  14051. }
  14052. }
  14053. void ValueTree::SharedObject::sendChildAddedMessage (ValueTree& tree, ValueTree& child)
  14054. {
  14055. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14056. {
  14057. ValueTree* const v = valueTreesWithListeners[i];
  14058. if (v != 0)
  14059. v->listeners.call (&ValueTree::Listener::valueTreeChildAdded, tree, child);
  14060. }
  14061. }
  14062. void ValueTree::SharedObject::sendChildAddedMessage (ValueTree child)
  14063. {
  14064. ValueTree tree (this);
  14065. ValueTree::SharedObject* t = this;
  14066. while (t != 0)
  14067. {
  14068. t->sendChildAddedMessage (tree, child);
  14069. t = t->parent;
  14070. }
  14071. }
  14072. void ValueTree::SharedObject::sendChildRemovedMessage (ValueTree& tree, ValueTree& child)
  14073. {
  14074. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14075. {
  14076. ValueTree* const v = valueTreesWithListeners[i];
  14077. if (v != 0)
  14078. v->listeners.call (&ValueTree::Listener::valueTreeChildRemoved, tree, child);
  14079. }
  14080. }
  14081. void ValueTree::SharedObject::sendChildRemovedMessage (ValueTree child)
  14082. {
  14083. ValueTree tree (this);
  14084. ValueTree::SharedObject* t = this;
  14085. while (t != 0)
  14086. {
  14087. t->sendChildRemovedMessage (tree, child);
  14088. t = t->parent;
  14089. }
  14090. }
  14091. void ValueTree::SharedObject::sendChildOrderChangedMessage (ValueTree& tree)
  14092. {
  14093. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14094. {
  14095. ValueTree* const v = valueTreesWithListeners[i];
  14096. if (v != 0)
  14097. v->listeners.call (&ValueTree::Listener::valueTreeChildOrderChanged, tree);
  14098. }
  14099. }
  14100. void ValueTree::SharedObject::sendChildOrderChangedMessage()
  14101. {
  14102. ValueTree tree (this);
  14103. ValueTree::SharedObject* t = this;
  14104. while (t != 0)
  14105. {
  14106. t->sendChildOrderChangedMessage (tree);
  14107. t = t->parent;
  14108. }
  14109. }
  14110. void ValueTree::SharedObject::sendParentChangeMessage()
  14111. {
  14112. ValueTree tree (this);
  14113. int i;
  14114. for (i = children.size(); --i >= 0;)
  14115. {
  14116. SharedObject* const t = children[i];
  14117. if (t != 0)
  14118. t->sendParentChangeMessage();
  14119. }
  14120. for (i = valueTreesWithListeners.size(); --i >= 0;)
  14121. {
  14122. ValueTree* const v = valueTreesWithListeners[i];
  14123. if (v != 0)
  14124. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  14125. }
  14126. }
  14127. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  14128. {
  14129. return properties [name];
  14130. }
  14131. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14132. {
  14133. return properties.getWithDefault (name, defaultReturnValue);
  14134. }
  14135. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14136. {
  14137. if (undoManager == 0)
  14138. {
  14139. if (properties.set (name, newValue))
  14140. sendPropertyChangeMessage (name);
  14141. }
  14142. else
  14143. {
  14144. var* const existingValue = properties.getVarPointer (name);
  14145. if (existingValue != 0)
  14146. {
  14147. if (*existingValue != newValue)
  14148. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  14149. }
  14150. else
  14151. {
  14152. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  14153. }
  14154. }
  14155. }
  14156. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14157. {
  14158. return properties.contains (name);
  14159. }
  14160. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14161. {
  14162. if (undoManager == 0)
  14163. {
  14164. if (properties.remove (name))
  14165. sendPropertyChangeMessage (name);
  14166. }
  14167. else
  14168. {
  14169. if (properties.contains (name))
  14170. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14171. }
  14172. }
  14173. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14174. {
  14175. if (undoManager == 0)
  14176. {
  14177. while (properties.size() > 0)
  14178. {
  14179. const Identifier name (properties.getName (properties.size() - 1));
  14180. properties.remove (name);
  14181. sendPropertyChangeMessage (name);
  14182. }
  14183. }
  14184. else
  14185. {
  14186. for (int i = properties.size(); --i >= 0;)
  14187. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14188. }
  14189. }
  14190. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14191. {
  14192. for (int i = 0; i < children.size(); ++i)
  14193. if (children.getUnchecked(i)->type == typeToMatch)
  14194. return ValueTree (children.getUnchecked(i).getObject());
  14195. return ValueTree::invalid;
  14196. }
  14197. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14198. {
  14199. for (int i = 0; i < children.size(); ++i)
  14200. if (children.getUnchecked(i)->type == typeToMatch)
  14201. return ValueTree (children.getUnchecked(i).getObject());
  14202. SharedObject* const newObject = new SharedObject (typeToMatch);
  14203. addChild (newObject, -1, undoManager);
  14204. return ValueTree (newObject);
  14205. }
  14206. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14207. {
  14208. for (int i = 0; i < children.size(); ++i)
  14209. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14210. return ValueTree (children.getUnchecked(i).getObject());
  14211. return ValueTree::invalid;
  14212. }
  14213. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14214. {
  14215. const SharedObject* p = parent;
  14216. while (p != 0)
  14217. {
  14218. if (p == possibleParent)
  14219. return true;
  14220. p = p->parent;
  14221. }
  14222. return false;
  14223. }
  14224. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14225. {
  14226. return children.indexOf (child.object);
  14227. }
  14228. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14229. {
  14230. if (child != 0 && child->parent != this)
  14231. {
  14232. if (child != this && ! isAChildOf (child))
  14233. {
  14234. // You should always make sure that a child is removed from its previous parent before
  14235. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14236. // undomanager should be used when removing it from its current parent..
  14237. jassert (child->parent == 0);
  14238. if (child->parent != 0)
  14239. {
  14240. jassert (child->parent->children.indexOf (child) >= 0);
  14241. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14242. }
  14243. if (undoManager == 0)
  14244. {
  14245. children.insert (index, child);
  14246. child->parent = this;
  14247. sendChildAddedMessage (ValueTree (child));
  14248. child->sendParentChangeMessage();
  14249. }
  14250. else
  14251. {
  14252. if (index < 0)
  14253. index = children.size();
  14254. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14255. }
  14256. }
  14257. else
  14258. {
  14259. // You're attempting to create a recursive loop! A node
  14260. // can't be a child of one of its own children!
  14261. jassertfalse;
  14262. }
  14263. }
  14264. }
  14265. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14266. {
  14267. const SharedObjectPtr child (children [childIndex]);
  14268. if (child != 0)
  14269. {
  14270. if (undoManager == 0)
  14271. {
  14272. children.remove (childIndex);
  14273. child->parent = 0;
  14274. sendChildRemovedMessage (ValueTree (child));
  14275. child->sendParentChangeMessage();
  14276. }
  14277. else
  14278. {
  14279. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14280. }
  14281. }
  14282. }
  14283. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14284. {
  14285. while (children.size() > 0)
  14286. removeChild (children.size() - 1, undoManager);
  14287. }
  14288. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14289. {
  14290. // The source index must be a valid index!
  14291. jassert (isPositiveAndBelow (currentIndex, children.size()));
  14292. if (currentIndex != newIndex
  14293. && isPositiveAndBelow (currentIndex, children.size()))
  14294. {
  14295. if (undoManager == 0)
  14296. {
  14297. children.move (currentIndex, newIndex);
  14298. sendChildOrderChangedMessage();
  14299. }
  14300. else
  14301. {
  14302. if (! isPositiveAndBelow (newIndex, children.size()))
  14303. newIndex = children.size() - 1;
  14304. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14305. }
  14306. }
  14307. }
  14308. void ValueTree::SharedObject::reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager* undoManager)
  14309. {
  14310. jassert (newOrder.size() == children.size());
  14311. if (undoManager == 0)
  14312. {
  14313. children = newOrder;
  14314. sendChildOrderChangedMessage();
  14315. }
  14316. else
  14317. {
  14318. for (int i = 0; i < children.size(); ++i)
  14319. {
  14320. const SharedObjectPtr child (newOrder.getUnchecked(i));
  14321. if (children.getUnchecked(i) != child)
  14322. {
  14323. const int oldIndex = children.indexOf (child);
  14324. jassert (oldIndex >= 0);
  14325. moveChild (oldIndex, i, undoManager);
  14326. }
  14327. }
  14328. }
  14329. }
  14330. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14331. {
  14332. if (type != other.type
  14333. || properties.size() != other.properties.size()
  14334. || children.size() != other.children.size()
  14335. || properties != other.properties)
  14336. return false;
  14337. for (int i = 0; i < children.size(); ++i)
  14338. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14339. return false;
  14340. return true;
  14341. }
  14342. ValueTree::ValueTree() throw()
  14343. : object (0)
  14344. {
  14345. }
  14346. const ValueTree ValueTree::invalid;
  14347. ValueTree::ValueTree (const Identifier& type_)
  14348. : object (new ValueTree::SharedObject (type_))
  14349. {
  14350. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14351. }
  14352. ValueTree::ValueTree (SharedObject* const object_)
  14353. : object (object_)
  14354. {
  14355. }
  14356. ValueTree::ValueTree (const ValueTree& other)
  14357. : object (other.object)
  14358. {
  14359. }
  14360. ValueTree& ValueTree::operator= (const ValueTree& other)
  14361. {
  14362. if (listeners.size() > 0)
  14363. {
  14364. if (object != 0)
  14365. object->valueTreesWithListeners.removeValue (this);
  14366. if (other.object != 0)
  14367. other.object->valueTreesWithListeners.add (this);
  14368. }
  14369. object = other.object;
  14370. return *this;
  14371. }
  14372. ValueTree::~ValueTree()
  14373. {
  14374. if (listeners.size() > 0 && object != 0)
  14375. object->valueTreesWithListeners.removeValue (this);
  14376. }
  14377. bool ValueTree::operator== (const ValueTree& other) const throw()
  14378. {
  14379. return object == other.object;
  14380. }
  14381. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14382. {
  14383. return object != other.object;
  14384. }
  14385. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14386. {
  14387. return object == other.object
  14388. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14389. }
  14390. ValueTree ValueTree::createCopy() const
  14391. {
  14392. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14393. }
  14394. bool ValueTree::hasType (const Identifier& typeName) const
  14395. {
  14396. return object != 0 && object->type == typeName;
  14397. }
  14398. const Identifier ValueTree::getType() const
  14399. {
  14400. return object != 0 ? object->type : Identifier();
  14401. }
  14402. ValueTree ValueTree::getParent() const
  14403. {
  14404. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14405. }
  14406. ValueTree ValueTree::getSibling (const int delta) const
  14407. {
  14408. if (object == 0 || object->parent == 0)
  14409. return invalid;
  14410. const int index = object->parent->indexOf (*this) + delta;
  14411. return ValueTree (object->parent->children [index].getObject());
  14412. }
  14413. const var& ValueTree::operator[] (const Identifier& name) const
  14414. {
  14415. return object == 0 ? var::null : object->getProperty (name);
  14416. }
  14417. const var& ValueTree::getProperty (const Identifier& name) const
  14418. {
  14419. return object == 0 ? var::null : object->getProperty (name);
  14420. }
  14421. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14422. {
  14423. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14424. }
  14425. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14426. {
  14427. jassert (name.toString().isNotEmpty());
  14428. if (object != 0 && name.toString().isNotEmpty())
  14429. object->setProperty (name, newValue, undoManager);
  14430. }
  14431. bool ValueTree::hasProperty (const Identifier& name) const
  14432. {
  14433. return object != 0 && object->hasProperty (name);
  14434. }
  14435. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14436. {
  14437. if (object != 0)
  14438. object->removeProperty (name, undoManager);
  14439. }
  14440. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14441. {
  14442. if (object != 0)
  14443. object->removeAllProperties (undoManager);
  14444. }
  14445. int ValueTree::getNumProperties() const
  14446. {
  14447. return object == 0 ? 0 : object->properties.size();
  14448. }
  14449. const Identifier ValueTree::getPropertyName (const int index) const
  14450. {
  14451. return object == 0 ? Identifier()
  14452. : object->properties.getName (index);
  14453. }
  14454. class ValueTreePropertyValueSource : public Value::ValueSource,
  14455. public ValueTree::Listener
  14456. {
  14457. public:
  14458. ValueTreePropertyValueSource (const ValueTree& tree_,
  14459. const Identifier& property_,
  14460. UndoManager* const undoManager_)
  14461. : tree (tree_),
  14462. property (property_),
  14463. undoManager (undoManager_)
  14464. {
  14465. tree.addListener (this);
  14466. }
  14467. ~ValueTreePropertyValueSource()
  14468. {
  14469. tree.removeListener (this);
  14470. }
  14471. const var getValue() const
  14472. {
  14473. return tree [property];
  14474. }
  14475. void setValue (const var& newValue)
  14476. {
  14477. tree.setProperty (property, newValue, undoManager);
  14478. }
  14479. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14480. {
  14481. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14482. sendChangeMessage (false);
  14483. }
  14484. void valueTreeChildAdded (ValueTree&, ValueTree&) {}
  14485. void valueTreeChildRemoved (ValueTree&, ValueTree&) {}
  14486. void valueTreeChildOrderChanged (ValueTree&) {}
  14487. void valueTreeParentChanged (ValueTree&) {}
  14488. private:
  14489. ValueTree tree;
  14490. const Identifier property;
  14491. UndoManager* const undoManager;
  14492. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14493. };
  14494. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14495. {
  14496. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14497. }
  14498. int ValueTree::getNumChildren() const
  14499. {
  14500. return object == 0 ? 0 : object->children.size();
  14501. }
  14502. ValueTree ValueTree::getChild (int index) const
  14503. {
  14504. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  14505. }
  14506. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  14507. {
  14508. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  14509. }
  14510. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  14511. {
  14512. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  14513. }
  14514. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14515. {
  14516. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  14517. }
  14518. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  14519. {
  14520. return object != 0 && object->isAChildOf (possibleParent.object);
  14521. }
  14522. int ValueTree::indexOf (const ValueTree& child) const
  14523. {
  14524. return object != 0 ? object->indexOf (child) : -1;
  14525. }
  14526. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  14527. {
  14528. if (object != 0)
  14529. object->addChild (child.object, index, undoManager);
  14530. }
  14531. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  14532. {
  14533. if (object != 0)
  14534. object->removeChild (childIndex, undoManager);
  14535. }
  14536. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  14537. {
  14538. if (object != 0)
  14539. object->removeChild (object->children.indexOf (child.object), undoManager);
  14540. }
  14541. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  14542. {
  14543. if (object != 0)
  14544. object->removeAllChildren (undoManager);
  14545. }
  14546. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14547. {
  14548. if (object != 0)
  14549. object->moveChild (currentIndex, newIndex, undoManager);
  14550. }
  14551. void ValueTree::addListener (Listener* listener)
  14552. {
  14553. if (listener != 0)
  14554. {
  14555. if (listeners.size() == 0 && object != 0)
  14556. object->valueTreesWithListeners.add (this);
  14557. listeners.add (listener);
  14558. }
  14559. }
  14560. void ValueTree::removeListener (Listener* listener)
  14561. {
  14562. listeners.remove (listener);
  14563. if (listeners.size() == 0 && object != 0)
  14564. object->valueTreesWithListeners.removeValue (this);
  14565. }
  14566. XmlElement* ValueTree::SharedObject::createXml() const
  14567. {
  14568. XmlElement* const xml = new XmlElement (type.toString());
  14569. properties.copyToXmlAttributes (*xml);
  14570. for (int i = 0; i < children.size(); ++i)
  14571. xml->addChildElement (children.getUnchecked(i)->createXml());
  14572. return xml;
  14573. }
  14574. XmlElement* ValueTree::createXml() const
  14575. {
  14576. return object != 0 ? object->createXml() : 0;
  14577. }
  14578. ValueTree ValueTree::fromXml (const XmlElement& xml)
  14579. {
  14580. ValueTree v (xml.getTagName());
  14581. v.object->properties.setFromXmlAttributes (xml);
  14582. forEachXmlChildElement (xml, e)
  14583. v.addChild (fromXml (*e), -1, 0);
  14584. return v;
  14585. }
  14586. void ValueTree::writeToStream (OutputStream& output)
  14587. {
  14588. output.writeString (getType().toString());
  14589. const int numProps = getNumProperties();
  14590. output.writeCompressedInt (numProps);
  14591. int i;
  14592. for (i = 0; i < numProps; ++i)
  14593. {
  14594. const Identifier name (getPropertyName(i));
  14595. output.writeString (name.toString());
  14596. getProperty(name).writeToStream (output);
  14597. }
  14598. const int numChildren = getNumChildren();
  14599. output.writeCompressedInt (numChildren);
  14600. for (i = 0; i < numChildren; ++i)
  14601. getChild (i).writeToStream (output);
  14602. }
  14603. ValueTree ValueTree::readFromStream (InputStream& input)
  14604. {
  14605. const String type (input.readString());
  14606. if (type.isEmpty())
  14607. return ValueTree::invalid;
  14608. ValueTree v (type);
  14609. const int numProps = input.readCompressedInt();
  14610. if (numProps < 0)
  14611. {
  14612. jassertfalse; // trying to read corrupted data!
  14613. return v;
  14614. }
  14615. int i;
  14616. for (i = 0; i < numProps; ++i)
  14617. {
  14618. const String name (input.readString());
  14619. jassert (name.isNotEmpty());
  14620. const var value (var::readFromStream (input));
  14621. v.object->properties.set (name, value);
  14622. }
  14623. const int numChildren = input.readCompressedInt();
  14624. for (i = 0; i < numChildren; ++i)
  14625. {
  14626. ValueTree child (readFromStream (input));
  14627. v.object->children.add (child.object);
  14628. child.object->parent = v.object;
  14629. }
  14630. return v;
  14631. }
  14632. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  14633. {
  14634. MemoryInputStream in (data, numBytes, false);
  14635. return readFromStream (in);
  14636. }
  14637. END_JUCE_NAMESPACE
  14638. /*** End of inlined file: juce_ValueTree.cpp ***/
  14639. /*** Start of inlined file: juce_Value.cpp ***/
  14640. BEGIN_JUCE_NAMESPACE
  14641. Value::ValueSource::ValueSource()
  14642. {
  14643. }
  14644. Value::ValueSource::~ValueSource()
  14645. {
  14646. }
  14647. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  14648. {
  14649. if (synchronous)
  14650. {
  14651. for (int i = valuesWithListeners.size(); --i >= 0;)
  14652. {
  14653. Value* const v = valuesWithListeners[i];
  14654. if (v != 0)
  14655. v->callListeners();
  14656. }
  14657. }
  14658. else
  14659. {
  14660. triggerAsyncUpdate();
  14661. }
  14662. }
  14663. void Value::ValueSource::handleAsyncUpdate()
  14664. {
  14665. sendChangeMessage (true);
  14666. }
  14667. class SimpleValueSource : public Value::ValueSource
  14668. {
  14669. public:
  14670. SimpleValueSource()
  14671. {
  14672. }
  14673. SimpleValueSource (const var& initialValue)
  14674. : value (initialValue)
  14675. {
  14676. }
  14677. const var getValue() const
  14678. {
  14679. return value;
  14680. }
  14681. void setValue (const var& newValue)
  14682. {
  14683. if (! newValue.equalsWithSameType (value))
  14684. {
  14685. value = newValue;
  14686. sendChangeMessage (false);
  14687. }
  14688. }
  14689. private:
  14690. var value;
  14691. JUCE_DECLARE_NON_COPYABLE (SimpleValueSource);
  14692. };
  14693. Value::Value()
  14694. : value (new SimpleValueSource())
  14695. {
  14696. }
  14697. Value::Value (ValueSource* const value_)
  14698. : value (value_)
  14699. {
  14700. jassert (value_ != 0);
  14701. }
  14702. Value::Value (const var& initialValue)
  14703. : value (new SimpleValueSource (initialValue))
  14704. {
  14705. }
  14706. Value::Value (const Value& other)
  14707. : value (other.value)
  14708. {
  14709. }
  14710. Value& Value::operator= (const Value& other)
  14711. {
  14712. value = other.value;
  14713. return *this;
  14714. }
  14715. Value::~Value()
  14716. {
  14717. if (listeners.size() > 0)
  14718. value->valuesWithListeners.removeValue (this);
  14719. }
  14720. const var Value::getValue() const
  14721. {
  14722. return value->getValue();
  14723. }
  14724. Value::operator const var() const
  14725. {
  14726. return getValue();
  14727. }
  14728. void Value::setValue (const var& newValue)
  14729. {
  14730. value->setValue (newValue);
  14731. }
  14732. const String Value::toString() const
  14733. {
  14734. return value->getValue().toString();
  14735. }
  14736. Value& Value::operator= (const var& newValue)
  14737. {
  14738. value->setValue (newValue);
  14739. return *this;
  14740. }
  14741. void Value::referTo (const Value& valueToReferTo)
  14742. {
  14743. if (valueToReferTo.value != value)
  14744. {
  14745. if (listeners.size() > 0)
  14746. {
  14747. value->valuesWithListeners.removeValue (this);
  14748. valueToReferTo.value->valuesWithListeners.add (this);
  14749. }
  14750. value = valueToReferTo.value;
  14751. callListeners();
  14752. }
  14753. }
  14754. bool Value::refersToSameSourceAs (const Value& other) const
  14755. {
  14756. return value == other.value;
  14757. }
  14758. bool Value::operator== (const Value& other) const
  14759. {
  14760. return value == other.value || value->getValue() == other.getValue();
  14761. }
  14762. bool Value::operator!= (const Value& other) const
  14763. {
  14764. return value != other.value && value->getValue() != other.getValue();
  14765. }
  14766. void Value::addListener (ValueListener* const listener)
  14767. {
  14768. if (listener != 0)
  14769. {
  14770. if (listeners.size() == 0)
  14771. value->valuesWithListeners.add (this);
  14772. listeners.add (listener);
  14773. }
  14774. }
  14775. void Value::removeListener (ValueListener* const listener)
  14776. {
  14777. listeners.remove (listener);
  14778. if (listeners.size() == 0)
  14779. value->valuesWithListeners.removeValue (this);
  14780. }
  14781. void Value::callListeners()
  14782. {
  14783. Value v (*this); // (create a copy in case this gets deleted by a callback)
  14784. listeners.call (&ValueListener::valueChanged, v);
  14785. }
  14786. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  14787. {
  14788. return stream << value.toString();
  14789. }
  14790. END_JUCE_NAMESPACE
  14791. /*** End of inlined file: juce_Value.cpp ***/
  14792. /*** Start of inlined file: juce_Application.cpp ***/
  14793. BEGIN_JUCE_NAMESPACE
  14794. #if JUCE_MAC
  14795. extern void juce_initialiseMacMainMenu();
  14796. #endif
  14797. JUCEApplication::JUCEApplication()
  14798. : appReturnValue (0),
  14799. stillInitialising (true)
  14800. {
  14801. jassert (isStandaloneApp() && appInstance == 0);
  14802. appInstance = this;
  14803. }
  14804. JUCEApplication::~JUCEApplication()
  14805. {
  14806. if (appLock != 0)
  14807. {
  14808. appLock->exit();
  14809. appLock = 0;
  14810. }
  14811. jassert (appInstance == this);
  14812. appInstance = 0;
  14813. }
  14814. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  14815. JUCEApplication* JUCEApplication::appInstance = 0;
  14816. bool JUCEApplication::moreThanOneInstanceAllowed()
  14817. {
  14818. return true;
  14819. }
  14820. void JUCEApplication::anotherInstanceStarted (const String&)
  14821. {
  14822. }
  14823. void JUCEApplication::systemRequestedQuit()
  14824. {
  14825. quit();
  14826. }
  14827. void JUCEApplication::quit()
  14828. {
  14829. MessageManager::getInstance()->stopDispatchLoop();
  14830. }
  14831. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  14832. {
  14833. appReturnValue = newReturnValue;
  14834. }
  14835. void JUCEApplication::actionListenerCallback (const String& message)
  14836. {
  14837. if (message.startsWith (getApplicationName() + "/"))
  14838. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  14839. }
  14840. void JUCEApplication::unhandledException (const std::exception*,
  14841. const String&,
  14842. const int)
  14843. {
  14844. jassertfalse;
  14845. }
  14846. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  14847. const char* const sourceFile,
  14848. const int lineNumber)
  14849. {
  14850. if (appInstance != 0)
  14851. appInstance->unhandledException (e, sourceFile, lineNumber);
  14852. }
  14853. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  14854. {
  14855. return 0;
  14856. }
  14857. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  14858. {
  14859. commands.add (StandardApplicationCommandIDs::quit);
  14860. }
  14861. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  14862. {
  14863. if (commandID == StandardApplicationCommandIDs::quit)
  14864. {
  14865. result.setInfo (TRANS("Quit"),
  14866. TRANS("Quits the application"),
  14867. "Application",
  14868. 0);
  14869. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  14870. }
  14871. }
  14872. bool JUCEApplication::perform (const InvocationInfo& info)
  14873. {
  14874. if (info.commandID == StandardApplicationCommandIDs::quit)
  14875. {
  14876. systemRequestedQuit();
  14877. return true;
  14878. }
  14879. return false;
  14880. }
  14881. bool JUCEApplication::initialiseApp (const String& commandLine)
  14882. {
  14883. commandLineParameters = commandLine.trim();
  14884. #if ! JUCE_IOS
  14885. jassert (appLock == 0); // initialiseApp must only be called once!
  14886. if (! moreThanOneInstanceAllowed())
  14887. {
  14888. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  14889. if (! appLock->enter(0))
  14890. {
  14891. appLock = 0;
  14892. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  14893. DBG ("Another instance is running - quitting...");
  14894. return false;
  14895. }
  14896. }
  14897. #endif
  14898. // let the app do its setting-up..
  14899. initialise (commandLineParameters);
  14900. #if JUCE_MAC
  14901. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  14902. #endif
  14903. // register for broadcast new app messages
  14904. MessageManager::getInstance()->registerBroadcastListener (this);
  14905. stillInitialising = false;
  14906. return true;
  14907. }
  14908. int JUCEApplication::shutdownApp()
  14909. {
  14910. jassert (appInstance == this);
  14911. MessageManager::getInstance()->deregisterBroadcastListener (this);
  14912. JUCE_TRY
  14913. {
  14914. // give the app a chance to clean up..
  14915. shutdown();
  14916. }
  14917. JUCE_CATCH_EXCEPTION
  14918. return getApplicationReturnValue();
  14919. }
  14920. // This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown..
  14921. void JUCEApplication::appWillTerminateByForce()
  14922. {
  14923. {
  14924. const ScopedPointer<JUCEApplication> app (JUCEApplication::getInstance());
  14925. if (app != 0)
  14926. app->shutdownApp();
  14927. }
  14928. shutdownJuce_GUI();
  14929. }
  14930. int JUCEApplication::main (const String& commandLine)
  14931. {
  14932. ScopedJuceInitialiser_GUI libraryInitialiser;
  14933. jassert (createInstance != 0);
  14934. int returnCode = 0;
  14935. {
  14936. const ScopedPointer<JUCEApplication> app (createInstance());
  14937. if (! app->initialiseApp (commandLine))
  14938. return 0;
  14939. JUCE_TRY
  14940. {
  14941. // loop until a quit message is received..
  14942. MessageManager::getInstance()->runDispatchLoop();
  14943. }
  14944. JUCE_CATCH_EXCEPTION
  14945. returnCode = app->shutdownApp();
  14946. }
  14947. return returnCode;
  14948. }
  14949. #if JUCE_IOS
  14950. extern int juce_iOSMain (int argc, const char* argv[]);
  14951. #endif
  14952. #if ! JUCE_WINDOWS
  14953. extern const char* juce_Argv0;
  14954. #endif
  14955. int JUCEApplication::main (int argc, const char* argv[])
  14956. {
  14957. JUCE_AUTORELEASEPOOL
  14958. #if ! JUCE_WINDOWS
  14959. jassert (createInstance != 0);
  14960. juce_Argv0 = argv[0];
  14961. #endif
  14962. #if JUCE_IOS
  14963. return juce_iOSMain (argc, argv);
  14964. #else
  14965. String cmd;
  14966. for (int i = 1; i < argc; ++i)
  14967. cmd << argv[i] << ' ';
  14968. return JUCEApplication::main (cmd);
  14969. #endif
  14970. }
  14971. END_JUCE_NAMESPACE
  14972. /*** End of inlined file: juce_Application.cpp ***/
  14973. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14974. BEGIN_JUCE_NAMESPACE
  14975. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  14976. : commandID (commandID_),
  14977. flags (0)
  14978. {
  14979. }
  14980. void ApplicationCommandInfo::setInfo (const String& shortName_,
  14981. const String& description_,
  14982. const String& categoryName_,
  14983. const int flags_) throw()
  14984. {
  14985. shortName = shortName_;
  14986. description = description_;
  14987. categoryName = categoryName_;
  14988. flags = flags_;
  14989. }
  14990. void ApplicationCommandInfo::setActive (const bool b) throw()
  14991. {
  14992. if (b)
  14993. flags &= ~isDisabled;
  14994. else
  14995. flags |= isDisabled;
  14996. }
  14997. void ApplicationCommandInfo::setTicked (const bool b) throw()
  14998. {
  14999. if (b)
  15000. flags |= isTicked;
  15001. else
  15002. flags &= ~isTicked;
  15003. }
  15004. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  15005. {
  15006. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  15007. }
  15008. END_JUCE_NAMESPACE
  15009. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15010. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  15011. BEGIN_JUCE_NAMESPACE
  15012. ApplicationCommandManager::ApplicationCommandManager()
  15013. : firstTarget (0)
  15014. {
  15015. keyMappings = new KeyPressMappingSet (this);
  15016. Desktop::getInstance().addFocusChangeListener (this);
  15017. }
  15018. ApplicationCommandManager::~ApplicationCommandManager()
  15019. {
  15020. Desktop::getInstance().removeFocusChangeListener (this);
  15021. keyMappings = 0;
  15022. }
  15023. void ApplicationCommandManager::clearCommands()
  15024. {
  15025. commands.clear();
  15026. keyMappings->clearAllKeyPresses();
  15027. triggerAsyncUpdate();
  15028. }
  15029. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  15030. {
  15031. // zero isn't a valid command ID!
  15032. jassert (newCommand.commandID != 0);
  15033. // the name isn't optional!
  15034. jassert (newCommand.shortName.isNotEmpty());
  15035. if (getCommandForID (newCommand.commandID) == 0)
  15036. {
  15037. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  15038. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  15039. commands.add (newInfo);
  15040. keyMappings->resetToDefaultMapping (newCommand.commandID);
  15041. triggerAsyncUpdate();
  15042. }
  15043. else
  15044. {
  15045. // trying to re-register the same command with different parameters?
  15046. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  15047. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  15048. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  15049. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  15050. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  15051. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  15052. }
  15053. }
  15054. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  15055. {
  15056. if (target != 0)
  15057. {
  15058. Array <CommandID> commandIDs;
  15059. target->getAllCommands (commandIDs);
  15060. for (int i = 0; i < commandIDs.size(); ++i)
  15061. {
  15062. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  15063. target->getCommandInfo (info.commandID, info);
  15064. registerCommand (info);
  15065. }
  15066. }
  15067. }
  15068. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  15069. {
  15070. for (int i = commands.size(); --i >= 0;)
  15071. {
  15072. if (commands.getUnchecked (i)->commandID == commandID)
  15073. {
  15074. commands.remove (i);
  15075. triggerAsyncUpdate();
  15076. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  15077. for (int j = keys.size(); --j >= 0;)
  15078. keyMappings->removeKeyPress (keys.getReference (j));
  15079. }
  15080. }
  15081. }
  15082. void ApplicationCommandManager::commandStatusChanged()
  15083. {
  15084. triggerAsyncUpdate();
  15085. }
  15086. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  15087. {
  15088. for (int i = commands.size(); --i >= 0;)
  15089. if (commands.getUnchecked(i)->commandID == commandID)
  15090. return commands.getUnchecked(i);
  15091. return 0;
  15092. }
  15093. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  15094. {
  15095. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15096. return (ci != 0) ? ci->shortName : String::empty;
  15097. }
  15098. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  15099. {
  15100. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15101. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  15102. : String::empty;
  15103. }
  15104. const StringArray ApplicationCommandManager::getCommandCategories() const
  15105. {
  15106. StringArray s;
  15107. for (int i = 0; i < commands.size(); ++i)
  15108. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  15109. return s;
  15110. }
  15111. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const
  15112. {
  15113. Array <CommandID> results;
  15114. for (int i = 0; i < commands.size(); ++i)
  15115. if (commands.getUnchecked(i)->categoryName == categoryName)
  15116. results.add (commands.getUnchecked(i)->commandID);
  15117. return results;
  15118. }
  15119. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15120. {
  15121. ApplicationCommandTarget::InvocationInfo info (commandID);
  15122. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15123. return invoke (info, asynchronously);
  15124. }
  15125. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  15126. {
  15127. // This call isn't thread-safe for use from a non-UI thread without locking the message
  15128. // manager first..
  15129. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  15130. ApplicationCommandInfo commandInfo (0);
  15131. ApplicationCommandTarget* const target = getTargetForCommand (info_.commandID, commandInfo);
  15132. if (target == 0)
  15133. return false;
  15134. ApplicationCommandTarget::InvocationInfo info (info_);
  15135. info.commandFlags = commandInfo.flags;
  15136. sendListenerInvokeCallback (info);
  15137. const bool ok = target->invoke (info, asynchronously);
  15138. commandStatusChanged();
  15139. return ok;
  15140. }
  15141. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  15142. {
  15143. return firstTarget != 0 ? firstTarget
  15144. : findDefaultComponentTarget();
  15145. }
  15146. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  15147. {
  15148. firstTarget = newTarget;
  15149. }
  15150. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  15151. ApplicationCommandInfo& upToDateInfo)
  15152. {
  15153. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  15154. if (target == 0)
  15155. target = JUCEApplication::getInstance();
  15156. if (target != 0)
  15157. target = target->getTargetForCommand (commandID);
  15158. if (target != 0)
  15159. target->getCommandInfo (commandID, upToDateInfo);
  15160. return target;
  15161. }
  15162. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  15163. {
  15164. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  15165. if (target == 0 && c != 0)
  15166. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15167. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15168. return target;
  15169. }
  15170. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  15171. {
  15172. Component* c = Component::getCurrentlyFocusedComponent();
  15173. if (c == 0)
  15174. {
  15175. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  15176. if (activeWindow != 0)
  15177. {
  15178. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  15179. if (c == 0)
  15180. c = activeWindow;
  15181. }
  15182. }
  15183. if (c == 0 && Process::isForegroundProcess())
  15184. {
  15185. // getting a bit desperate now - try all desktop comps..
  15186. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15187. {
  15188. ApplicationCommandTarget* const target
  15189. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15190. ->getPeer()->getLastFocusedSubcomponent());
  15191. if (target != 0)
  15192. return target;
  15193. }
  15194. }
  15195. if (c != 0)
  15196. {
  15197. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15198. // if we're focused on a ResizableWindow, chances are that it's the content
  15199. // component that really should get the event. And if not, the event will
  15200. // still be passed up to the top level window anyway, so let's send it to the
  15201. // content comp.
  15202. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15203. c = resizableWindow->getContentComponent();
  15204. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15205. if (target != 0)
  15206. return target;
  15207. }
  15208. return JUCEApplication::getInstance();
  15209. }
  15210. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener)
  15211. {
  15212. listeners.add (listener);
  15213. }
  15214. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener)
  15215. {
  15216. listeners.remove (listener);
  15217. }
  15218. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15219. {
  15220. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15221. }
  15222. void ApplicationCommandManager::handleAsyncUpdate()
  15223. {
  15224. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15225. }
  15226. void ApplicationCommandManager::globalFocusChanged (Component*)
  15227. {
  15228. commandStatusChanged();
  15229. }
  15230. END_JUCE_NAMESPACE
  15231. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15232. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15233. BEGIN_JUCE_NAMESPACE
  15234. ApplicationCommandTarget::ApplicationCommandTarget()
  15235. {
  15236. }
  15237. ApplicationCommandTarget::~ApplicationCommandTarget()
  15238. {
  15239. messageInvoker = 0;
  15240. }
  15241. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15242. {
  15243. if (isCommandActive (info.commandID))
  15244. {
  15245. if (async)
  15246. {
  15247. if (messageInvoker == 0)
  15248. messageInvoker = new CommandTargetMessageInvoker (this);
  15249. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15250. return true;
  15251. }
  15252. else
  15253. {
  15254. const bool success = perform (info);
  15255. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15256. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15257. // returns the command's info.
  15258. return success;
  15259. }
  15260. }
  15261. return false;
  15262. }
  15263. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15264. {
  15265. Component* c = dynamic_cast <Component*> (this);
  15266. if (c != 0)
  15267. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15268. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15269. return 0;
  15270. }
  15271. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15272. {
  15273. ApplicationCommandTarget* target = this;
  15274. int depth = 0;
  15275. while (target != 0)
  15276. {
  15277. Array <CommandID> commandIDs;
  15278. target->getAllCommands (commandIDs);
  15279. if (commandIDs.contains (commandID))
  15280. return target;
  15281. target = target->getNextCommandTarget();
  15282. ++depth;
  15283. jassert (depth < 100); // could be a recursive command chain??
  15284. jassert (target != this); // definitely a recursive command chain!
  15285. if (depth > 100 || target == this)
  15286. break;
  15287. }
  15288. if (target == 0)
  15289. {
  15290. target = JUCEApplication::getInstance();
  15291. if (target != 0)
  15292. {
  15293. Array <CommandID> commandIDs;
  15294. target->getAllCommands (commandIDs);
  15295. if (commandIDs.contains (commandID))
  15296. return target;
  15297. }
  15298. }
  15299. return 0;
  15300. }
  15301. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15302. {
  15303. ApplicationCommandInfo info (commandID);
  15304. info.flags = ApplicationCommandInfo::isDisabled;
  15305. getCommandInfo (commandID, info);
  15306. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15307. }
  15308. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15309. {
  15310. ApplicationCommandTarget* target = this;
  15311. int depth = 0;
  15312. while (target != 0)
  15313. {
  15314. if (target->tryToInvoke (info, async))
  15315. return true;
  15316. target = target->getNextCommandTarget();
  15317. ++depth;
  15318. jassert (depth < 100); // could be a recursive command chain??
  15319. jassert (target != this); // definitely a recursive command chain!
  15320. if (depth > 100 || target == this)
  15321. break;
  15322. }
  15323. if (target == 0)
  15324. {
  15325. target = JUCEApplication::getInstance();
  15326. if (target != 0)
  15327. return target->tryToInvoke (info, async);
  15328. }
  15329. return false;
  15330. }
  15331. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15332. {
  15333. ApplicationCommandTarget::InvocationInfo info (commandID);
  15334. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15335. return invoke (info, asynchronously);
  15336. }
  15337. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_)
  15338. : commandID (commandID_),
  15339. commandFlags (0),
  15340. invocationMethod (direct),
  15341. originatingComponent (0),
  15342. isKeyDown (false),
  15343. millisecsSinceKeyPressed (0)
  15344. {
  15345. }
  15346. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15347. : owner (owner_)
  15348. {
  15349. }
  15350. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15351. {
  15352. }
  15353. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15354. {
  15355. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15356. owner->tryToInvoke (*info, false);
  15357. }
  15358. END_JUCE_NAMESPACE
  15359. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15360. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15361. BEGIN_JUCE_NAMESPACE
  15362. juce_ImplementSingleton (ApplicationProperties)
  15363. ApplicationProperties::ApplicationProperties()
  15364. : msBeforeSaving (3000),
  15365. options (PropertiesFile::storeAsBinary),
  15366. commonSettingsAreReadOnly (0),
  15367. processLock (0)
  15368. {
  15369. }
  15370. ApplicationProperties::~ApplicationProperties()
  15371. {
  15372. closeFiles();
  15373. clearSingletonInstance();
  15374. }
  15375. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15376. const String& fileNameSuffix,
  15377. const String& folderName_,
  15378. const int millisecondsBeforeSaving,
  15379. const int propertiesFileOptions,
  15380. InterProcessLock* processLock_)
  15381. {
  15382. appName = applicationName;
  15383. fileSuffix = fileNameSuffix;
  15384. folderName = folderName_;
  15385. msBeforeSaving = millisecondsBeforeSaving;
  15386. options = propertiesFileOptions;
  15387. processLock = processLock_;
  15388. }
  15389. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15390. const bool testCommonSettings,
  15391. const bool showWarningDialogOnFailure)
  15392. {
  15393. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15394. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15395. if (! (userOk && commonOk))
  15396. {
  15397. if (showWarningDialogOnFailure)
  15398. {
  15399. String filenames;
  15400. if (userProps != 0 && ! userOk)
  15401. filenames << '\n' << userProps->getFile().getFullPathName();
  15402. if (commonProps != 0 && ! commonOk)
  15403. filenames << '\n' << commonProps->getFile().getFullPathName();
  15404. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15405. appName + TRANS(" - Unable to save settings"),
  15406. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15407. + appName + TRANS(" needs to be able to write to the following files:\n")
  15408. + filenames
  15409. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15410. }
  15411. return false;
  15412. }
  15413. return true;
  15414. }
  15415. void ApplicationProperties::openFiles()
  15416. {
  15417. // You need to call setStorageParameters() before trying to get hold of the
  15418. // properties!
  15419. jassert (appName.isNotEmpty());
  15420. if (appName.isNotEmpty())
  15421. {
  15422. if (userProps == 0)
  15423. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15424. false, msBeforeSaving, options, processLock);
  15425. if (commonProps == 0)
  15426. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15427. true, msBeforeSaving, options, processLock);
  15428. userProps->setFallbackPropertySet (commonProps);
  15429. }
  15430. }
  15431. PropertiesFile* ApplicationProperties::getUserSettings()
  15432. {
  15433. if (userProps == 0)
  15434. openFiles();
  15435. return userProps;
  15436. }
  15437. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15438. {
  15439. if (commonProps == 0)
  15440. openFiles();
  15441. if (returnUserPropsIfReadOnly)
  15442. {
  15443. if (commonSettingsAreReadOnly == 0)
  15444. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15445. if (commonSettingsAreReadOnly > 0)
  15446. return userProps;
  15447. }
  15448. return commonProps;
  15449. }
  15450. bool ApplicationProperties::saveIfNeeded()
  15451. {
  15452. return (userProps == 0 || userProps->saveIfNeeded())
  15453. && (commonProps == 0 || commonProps->saveIfNeeded());
  15454. }
  15455. void ApplicationProperties::closeFiles()
  15456. {
  15457. userProps = 0;
  15458. commonProps = 0;
  15459. }
  15460. END_JUCE_NAMESPACE
  15461. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15462. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15463. BEGIN_JUCE_NAMESPACE
  15464. namespace PropertyFileConstants
  15465. {
  15466. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15467. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15468. static const char* const fileTag = "PROPERTIES";
  15469. static const char* const valueTag = "VALUE";
  15470. static const char* const nameAttribute = "name";
  15471. static const char* const valueAttribute = "val";
  15472. }
  15473. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15474. const int options_, InterProcessLock* const processLock_)
  15475. : PropertySet (ignoreCaseOfKeyNames),
  15476. file (f),
  15477. timerInterval (millisecondsBeforeSaving),
  15478. options (options_),
  15479. loadedOk (false),
  15480. needsWriting (false),
  15481. processLock (processLock_)
  15482. {
  15483. // You need to correctly specify just one storage format for the file
  15484. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15485. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15486. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15487. ProcessScopedLock pl (createProcessLock());
  15488. if (pl != 0 && ! pl->isLocked())
  15489. return; // locking failure..
  15490. ScopedPointer<InputStream> fileStream (f.createInputStream());
  15491. if (fileStream != 0)
  15492. {
  15493. int magicNumber = fileStream->readInt();
  15494. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  15495. {
  15496. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  15497. magicNumber = PropertyFileConstants::magicNumber;
  15498. }
  15499. if (magicNumber == PropertyFileConstants::magicNumber)
  15500. {
  15501. loadedOk = true;
  15502. BufferedInputStream in (fileStream.release(), 2048, true);
  15503. int numValues = in.readInt();
  15504. while (--numValues >= 0 && ! in.isExhausted())
  15505. {
  15506. const String key (in.readString());
  15507. const String value (in.readString());
  15508. jassert (key.isNotEmpty());
  15509. if (key.isNotEmpty())
  15510. getAllProperties().set (key, value);
  15511. }
  15512. }
  15513. else
  15514. {
  15515. // Not a binary props file - let's see if it's XML..
  15516. fileStream = 0;
  15517. XmlDocument parser (f);
  15518. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  15519. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  15520. {
  15521. doc = parser.getDocumentElement();
  15522. if (doc != 0)
  15523. {
  15524. loadedOk = true;
  15525. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  15526. {
  15527. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  15528. if (name.isNotEmpty())
  15529. {
  15530. getAllProperties().set (name,
  15531. e->getFirstChildElement() != 0
  15532. ? e->getFirstChildElement()->createDocument (String::empty, true)
  15533. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  15534. }
  15535. }
  15536. }
  15537. else
  15538. {
  15539. // must be a pretty broken XML file we're trying to parse here,
  15540. // or a sign that this object needs an InterProcessLock,
  15541. // or just a failure reading the file. This last reason is why
  15542. // we don't jassertfalse here.
  15543. }
  15544. }
  15545. }
  15546. }
  15547. else
  15548. {
  15549. loadedOk = ! f.exists();
  15550. }
  15551. }
  15552. PropertiesFile::~PropertiesFile()
  15553. {
  15554. if (! saveIfNeeded())
  15555. jassertfalse;
  15556. }
  15557. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  15558. {
  15559. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  15560. }
  15561. bool PropertiesFile::saveIfNeeded()
  15562. {
  15563. const ScopedLock sl (getLock());
  15564. return (! needsWriting) || save();
  15565. }
  15566. bool PropertiesFile::needsToBeSaved() const
  15567. {
  15568. const ScopedLock sl (getLock());
  15569. return needsWriting;
  15570. }
  15571. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  15572. {
  15573. const ScopedLock sl (getLock());
  15574. needsWriting = needsToBeSaved_;
  15575. }
  15576. bool PropertiesFile::save()
  15577. {
  15578. const ScopedLock sl (getLock());
  15579. stopTimer();
  15580. if (file == File::nonexistent
  15581. || file.isDirectory()
  15582. || ! file.getParentDirectory().createDirectory())
  15583. return false;
  15584. if ((options & storeAsXML) != 0)
  15585. {
  15586. XmlElement doc (PropertyFileConstants::fileTag);
  15587. for (int i = 0; i < getAllProperties().size(); ++i)
  15588. {
  15589. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  15590. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  15591. // if the value seems to contain xml, store it as such..
  15592. XmlElement* const childElement = XmlDocument::parse (getAllProperties().getAllValues() [i]);
  15593. if (childElement != 0)
  15594. e->addChildElement (childElement);
  15595. else
  15596. e->setAttribute (PropertyFileConstants::valueAttribute,
  15597. getAllProperties().getAllValues() [i]);
  15598. }
  15599. ProcessScopedLock pl (createProcessLock());
  15600. if (pl != 0 && ! pl->isLocked())
  15601. return false; // locking failure..
  15602. if (doc.writeToFile (file, String::empty))
  15603. {
  15604. needsWriting = false;
  15605. return true;
  15606. }
  15607. }
  15608. else
  15609. {
  15610. ProcessScopedLock pl (createProcessLock());
  15611. if (pl != 0 && ! pl->isLocked())
  15612. return false; // locking failure..
  15613. TemporaryFile tempFile (file);
  15614. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  15615. if (out != 0)
  15616. {
  15617. if ((options & storeAsCompressedBinary) != 0)
  15618. {
  15619. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  15620. out->flush();
  15621. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  15622. }
  15623. else
  15624. {
  15625. // have you set up the storage option flags correctly?
  15626. jassert ((options & storeAsBinary) != 0);
  15627. out->writeInt (PropertyFileConstants::magicNumber);
  15628. }
  15629. const int numProperties = getAllProperties().size();
  15630. out->writeInt (numProperties);
  15631. for (int i = 0; i < numProperties; ++i)
  15632. {
  15633. out->writeString (getAllProperties().getAllKeys() [i]);
  15634. out->writeString (getAllProperties().getAllValues() [i]);
  15635. }
  15636. out = 0;
  15637. if (tempFile.overwriteTargetFileWithTemporary())
  15638. {
  15639. needsWriting = false;
  15640. return true;
  15641. }
  15642. }
  15643. }
  15644. return false;
  15645. }
  15646. void PropertiesFile::timerCallback()
  15647. {
  15648. saveIfNeeded();
  15649. }
  15650. void PropertiesFile::propertyChanged()
  15651. {
  15652. sendChangeMessage();
  15653. needsWriting = true;
  15654. if (timerInterval > 0)
  15655. startTimer (timerInterval);
  15656. else if (timerInterval == 0)
  15657. saveIfNeeded();
  15658. }
  15659. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  15660. const String& fileNameSuffix,
  15661. const String& folderName,
  15662. const bool commonToAllUsers)
  15663. {
  15664. // mustn't have illegal characters in this name..
  15665. jassert (applicationName == File::createLegalFileName (applicationName));
  15666. #if JUCE_MAC || JUCE_IOS
  15667. File dir (commonToAllUsers ? "/Library/Preferences"
  15668. : "~/Library/Preferences");
  15669. if (folderName.isNotEmpty())
  15670. dir = dir.getChildFile (folderName);
  15671. #elif JUCE_LINUX || JUCE_ANDROID
  15672. const File dir ((commonToAllUsers ? "/var/" : "~/")
  15673. + (folderName.isNotEmpty() ? folderName
  15674. : ("." + applicationName)));
  15675. #elif JUCE_WINDOWS
  15676. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  15677. : File::userApplicationDataDirectory));
  15678. if (dir == File::nonexistent)
  15679. return File::nonexistent;
  15680. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  15681. : applicationName);
  15682. #endif
  15683. return dir.getChildFile (applicationName)
  15684. .withFileExtension (fileNameSuffix);
  15685. }
  15686. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  15687. const String& fileNameSuffix,
  15688. const String& folderName,
  15689. const bool commonToAllUsers,
  15690. const int millisecondsBeforeSaving,
  15691. const int propertiesFileOptions,
  15692. InterProcessLock* processLock_)
  15693. {
  15694. const File file (getDefaultAppSettingsFile (applicationName,
  15695. fileNameSuffix,
  15696. folderName,
  15697. commonToAllUsers));
  15698. jassert (file != File::nonexistent);
  15699. if (file == File::nonexistent)
  15700. return 0;
  15701. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  15702. }
  15703. END_JUCE_NAMESPACE
  15704. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  15705. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  15706. BEGIN_JUCE_NAMESPACE
  15707. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  15708. const String& fileWildcard_,
  15709. const String& openFileDialogTitle_,
  15710. const String& saveFileDialogTitle_)
  15711. : changedSinceSave (false),
  15712. fileExtension (fileExtension_),
  15713. fileWildcard (fileWildcard_),
  15714. openFileDialogTitle (openFileDialogTitle_),
  15715. saveFileDialogTitle (saveFileDialogTitle_)
  15716. {
  15717. }
  15718. FileBasedDocument::~FileBasedDocument()
  15719. {
  15720. }
  15721. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  15722. {
  15723. if (changedSinceSave != hasChanged)
  15724. {
  15725. changedSinceSave = hasChanged;
  15726. sendChangeMessage();
  15727. }
  15728. }
  15729. void FileBasedDocument::changed()
  15730. {
  15731. changedSinceSave = true;
  15732. sendChangeMessage();
  15733. }
  15734. void FileBasedDocument::setFile (const File& newFile)
  15735. {
  15736. if (documentFile != newFile)
  15737. {
  15738. documentFile = newFile;
  15739. changed();
  15740. }
  15741. }
  15742. bool FileBasedDocument::loadFrom (const File& newFile,
  15743. const bool showMessageOnFailure)
  15744. {
  15745. MouseCursor::showWaitCursor();
  15746. const File oldFile (documentFile);
  15747. documentFile = newFile;
  15748. String error;
  15749. if (newFile.existsAsFile())
  15750. {
  15751. error = loadDocument (newFile);
  15752. if (error.isEmpty())
  15753. {
  15754. setChangedFlag (false);
  15755. MouseCursor::hideWaitCursor();
  15756. setLastDocumentOpened (newFile);
  15757. return true;
  15758. }
  15759. }
  15760. else
  15761. {
  15762. error = "The file doesn't exist";
  15763. }
  15764. documentFile = oldFile;
  15765. MouseCursor::hideWaitCursor();
  15766. if (showMessageOnFailure)
  15767. {
  15768. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15769. TRANS("Failed to open file..."),
  15770. TRANS("There was an error while trying to load the file:\n\n")
  15771. + newFile.getFullPathName()
  15772. + "\n\n"
  15773. + error);
  15774. }
  15775. return false;
  15776. }
  15777. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  15778. {
  15779. FileChooser fc (openFileDialogTitle,
  15780. getLastDocumentOpened(),
  15781. fileWildcard);
  15782. if (fc.browseForFileToOpen())
  15783. return loadFrom (fc.getResult(), showMessageOnFailure);
  15784. return false;
  15785. }
  15786. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  15787. const bool showMessageOnFailure)
  15788. {
  15789. return saveAs (documentFile,
  15790. false,
  15791. askUserForFileIfNotSpecified,
  15792. showMessageOnFailure);
  15793. }
  15794. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  15795. const bool warnAboutOverwritingExistingFiles,
  15796. const bool askUserForFileIfNotSpecified,
  15797. const bool showMessageOnFailure)
  15798. {
  15799. if (newFile == File::nonexistent)
  15800. {
  15801. if (askUserForFileIfNotSpecified)
  15802. {
  15803. return saveAsInteractive (true);
  15804. }
  15805. else
  15806. {
  15807. // can't save to an unspecified file
  15808. jassertfalse;
  15809. return failedToWriteToFile;
  15810. }
  15811. }
  15812. if (warnAboutOverwritingExistingFiles && newFile.exists())
  15813. {
  15814. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  15815. TRANS("File already exists"),
  15816. TRANS("There's already a file called:\n\n")
  15817. + newFile.getFullPathName()
  15818. + TRANS("\n\nAre you sure you want to overwrite it?"),
  15819. TRANS("overwrite"),
  15820. TRANS("cancel")))
  15821. {
  15822. return userCancelledSave;
  15823. }
  15824. }
  15825. MouseCursor::showWaitCursor();
  15826. const File oldFile (documentFile);
  15827. documentFile = newFile;
  15828. String error (saveDocument (newFile));
  15829. if (error.isEmpty())
  15830. {
  15831. setChangedFlag (false);
  15832. MouseCursor::hideWaitCursor();
  15833. return savedOk;
  15834. }
  15835. documentFile = oldFile;
  15836. MouseCursor::hideWaitCursor();
  15837. if (showMessageOnFailure)
  15838. {
  15839. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15840. TRANS("Error writing to file..."),
  15841. TRANS("An error occurred while trying to save \"")
  15842. + getDocumentTitle()
  15843. + TRANS("\" to the file:\n\n")
  15844. + newFile.getFullPathName()
  15845. + "\n\n"
  15846. + error);
  15847. }
  15848. return failedToWriteToFile;
  15849. }
  15850. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  15851. {
  15852. if (! hasChangedSinceSaved())
  15853. return savedOk;
  15854. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  15855. TRANS("Closing document..."),
  15856. TRANS("Do you want to save the changes to \"")
  15857. + getDocumentTitle() + "\"?",
  15858. TRANS("save"),
  15859. TRANS("discard changes"),
  15860. TRANS("cancel"));
  15861. if (r == 1)
  15862. {
  15863. // save changes
  15864. return save (true, true);
  15865. }
  15866. else if (r == 2)
  15867. {
  15868. // discard changes
  15869. return savedOk;
  15870. }
  15871. return userCancelledSave;
  15872. }
  15873. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  15874. {
  15875. File f;
  15876. if (documentFile.existsAsFile())
  15877. f = documentFile;
  15878. else
  15879. f = getLastDocumentOpened();
  15880. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  15881. if (legalFilename.isEmpty())
  15882. legalFilename = "unnamed";
  15883. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  15884. f = f.getSiblingFile (legalFilename);
  15885. else
  15886. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  15887. f = f.withFileExtension (fileExtension)
  15888. .getNonexistentSibling (true);
  15889. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  15890. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  15891. {
  15892. File chosen (fc.getResult());
  15893. if (chosen.getFileExtension().isEmpty())
  15894. {
  15895. chosen = chosen.withFileExtension (fileExtension);
  15896. if (chosen.exists())
  15897. {
  15898. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  15899. TRANS("File already exists"),
  15900. TRANS("There's already a file called:")
  15901. + "\n\n" + chosen.getFullPathName()
  15902. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  15903. TRANS("overwrite"),
  15904. TRANS("cancel")))
  15905. {
  15906. return userCancelledSave;
  15907. }
  15908. }
  15909. }
  15910. setLastDocumentOpened (chosen);
  15911. return saveAs (chosen, false, false, true);
  15912. }
  15913. return userCancelledSave;
  15914. }
  15915. END_JUCE_NAMESPACE
  15916. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  15917. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15918. BEGIN_JUCE_NAMESPACE
  15919. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  15920. : maxNumberOfItems (10)
  15921. {
  15922. }
  15923. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  15924. {
  15925. }
  15926. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  15927. {
  15928. maxNumberOfItems = jmax (1, newMaxNumber);
  15929. while (getNumFiles() > maxNumberOfItems)
  15930. files.remove (getNumFiles() - 1);
  15931. }
  15932. int RecentlyOpenedFilesList::getNumFiles() const
  15933. {
  15934. return files.size();
  15935. }
  15936. const File RecentlyOpenedFilesList::getFile (const int index) const
  15937. {
  15938. return File (files [index]);
  15939. }
  15940. void RecentlyOpenedFilesList::clear()
  15941. {
  15942. files.clear();
  15943. }
  15944. void RecentlyOpenedFilesList::addFile (const File& file)
  15945. {
  15946. const String path (file.getFullPathName());
  15947. files.removeString (path, true);
  15948. files.insert (0, path);
  15949. setMaxNumberOfItems (maxNumberOfItems);
  15950. }
  15951. void RecentlyOpenedFilesList::removeNonExistentFiles()
  15952. {
  15953. for (int i = getNumFiles(); --i >= 0;)
  15954. if (! getFile(i).exists())
  15955. files.remove (i);
  15956. }
  15957. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  15958. const int baseItemId,
  15959. const bool showFullPaths,
  15960. const bool dontAddNonExistentFiles,
  15961. const File** filesToAvoid)
  15962. {
  15963. int num = 0;
  15964. for (int i = 0; i < getNumFiles(); ++i)
  15965. {
  15966. const File f (getFile(i));
  15967. if ((! dontAddNonExistentFiles) || f.exists())
  15968. {
  15969. bool needsAvoiding = false;
  15970. if (filesToAvoid != 0)
  15971. {
  15972. const File** avoid = filesToAvoid;
  15973. while (*avoid != 0)
  15974. {
  15975. if (f == **avoid)
  15976. {
  15977. needsAvoiding = true;
  15978. break;
  15979. }
  15980. ++avoid;
  15981. }
  15982. }
  15983. if (! needsAvoiding)
  15984. {
  15985. menuToAddTo.addItem (baseItemId + i,
  15986. showFullPaths ? f.getFullPathName()
  15987. : f.getFileName());
  15988. ++num;
  15989. }
  15990. }
  15991. }
  15992. return num;
  15993. }
  15994. const String RecentlyOpenedFilesList::toString() const
  15995. {
  15996. return files.joinIntoString ("\n");
  15997. }
  15998. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  15999. {
  16000. clear();
  16001. files.addLines (stringifiedVersion);
  16002. setMaxNumberOfItems (maxNumberOfItems);
  16003. }
  16004. END_JUCE_NAMESPACE
  16005. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16006. /*** Start of inlined file: juce_UndoManager.cpp ***/
  16007. BEGIN_JUCE_NAMESPACE
  16008. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  16009. const int minimumTransactions)
  16010. : totalUnitsStored (0),
  16011. nextIndex (0),
  16012. newTransaction (true),
  16013. reentrancyCheck (false)
  16014. {
  16015. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  16016. minimumTransactions);
  16017. }
  16018. UndoManager::~UndoManager()
  16019. {
  16020. clearUndoHistory();
  16021. }
  16022. void UndoManager::clearUndoHistory()
  16023. {
  16024. transactions.clear();
  16025. transactionNames.clear();
  16026. totalUnitsStored = 0;
  16027. nextIndex = 0;
  16028. sendChangeMessage();
  16029. }
  16030. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  16031. {
  16032. return totalUnitsStored;
  16033. }
  16034. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  16035. const int minimumTransactions)
  16036. {
  16037. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  16038. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  16039. }
  16040. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  16041. {
  16042. if (command_ != 0)
  16043. {
  16044. ScopedPointer<UndoableAction> command (command_);
  16045. if (actionName.isNotEmpty())
  16046. currentTransactionName = actionName;
  16047. if (reentrancyCheck)
  16048. {
  16049. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  16050. // undo() methods, or else these actions won't actually get done.
  16051. return false;
  16052. }
  16053. else if (command->perform())
  16054. {
  16055. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  16056. if (commandSet != 0 && ! newTransaction)
  16057. {
  16058. UndoableAction* lastAction = commandSet->getLast();
  16059. if (lastAction != 0)
  16060. {
  16061. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  16062. if (coalescedAction != 0)
  16063. {
  16064. command = coalescedAction;
  16065. totalUnitsStored -= lastAction->getSizeInUnits();
  16066. commandSet->removeLast();
  16067. }
  16068. }
  16069. }
  16070. else
  16071. {
  16072. commandSet = new OwnedArray<UndoableAction>();
  16073. transactions.insert (nextIndex, commandSet);
  16074. transactionNames.insert (nextIndex, currentTransactionName);
  16075. ++nextIndex;
  16076. }
  16077. totalUnitsStored += command->getSizeInUnits();
  16078. commandSet->add (command.release());
  16079. newTransaction = false;
  16080. while (nextIndex < transactions.size())
  16081. {
  16082. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  16083. for (int i = lastSet->size(); --i >= 0;)
  16084. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  16085. transactions.removeLast();
  16086. transactionNames.remove (transactionNames.size() - 1);
  16087. }
  16088. while (nextIndex > 0
  16089. && totalUnitsStored > maxNumUnitsToKeep
  16090. && transactions.size() > minimumTransactionsToKeep)
  16091. {
  16092. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  16093. for (int i = firstSet->size(); --i >= 0;)
  16094. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  16095. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  16096. transactions.remove (0);
  16097. transactionNames.remove (0);
  16098. --nextIndex;
  16099. }
  16100. sendChangeMessage();
  16101. return true;
  16102. }
  16103. }
  16104. return false;
  16105. }
  16106. void UndoManager::beginNewTransaction (const String& actionName)
  16107. {
  16108. newTransaction = true;
  16109. currentTransactionName = actionName;
  16110. }
  16111. void UndoManager::setCurrentTransactionName (const String& newName)
  16112. {
  16113. currentTransactionName = newName;
  16114. }
  16115. bool UndoManager::canUndo() const
  16116. {
  16117. return nextIndex > 0;
  16118. }
  16119. bool UndoManager::canRedo() const
  16120. {
  16121. return nextIndex < transactions.size();
  16122. }
  16123. const String UndoManager::getUndoDescription() const
  16124. {
  16125. return transactionNames [nextIndex - 1];
  16126. }
  16127. const String UndoManager::getRedoDescription() const
  16128. {
  16129. return transactionNames [nextIndex];
  16130. }
  16131. bool UndoManager::undo()
  16132. {
  16133. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16134. if (commandSet == 0)
  16135. return false;
  16136. bool failed = false;
  16137. {
  16138. const ScopedValueSetter<bool> setter (reentrancyCheck, true);
  16139. for (int i = commandSet->size(); --i >= 0;)
  16140. {
  16141. if (! commandSet->getUnchecked(i)->undo())
  16142. {
  16143. jassertfalse;
  16144. failed = true;
  16145. break;
  16146. }
  16147. }
  16148. }
  16149. if (failed)
  16150. clearUndoHistory();
  16151. else
  16152. --nextIndex;
  16153. beginNewTransaction();
  16154. sendChangeMessage();
  16155. return true;
  16156. }
  16157. bool UndoManager::redo()
  16158. {
  16159. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  16160. if (commandSet == 0)
  16161. return false;
  16162. bool failed = false;
  16163. {
  16164. const ScopedValueSetter<bool> setter (reentrancyCheck, true);
  16165. for (int i = 0; i < commandSet->size(); ++i)
  16166. {
  16167. if (! commandSet->getUnchecked(i)->perform())
  16168. {
  16169. jassertfalse;
  16170. failed = true;
  16171. break;
  16172. }
  16173. }
  16174. }
  16175. if (failed)
  16176. clearUndoHistory();
  16177. else
  16178. ++nextIndex;
  16179. beginNewTransaction();
  16180. sendChangeMessage();
  16181. return true;
  16182. }
  16183. bool UndoManager::undoCurrentTransactionOnly()
  16184. {
  16185. return newTransaction ? false : undo();
  16186. }
  16187. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16188. {
  16189. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16190. if (commandSet != 0 && ! newTransaction)
  16191. {
  16192. for (int i = 0; i < commandSet->size(); ++i)
  16193. actionsFound.add (commandSet->getUnchecked(i));
  16194. }
  16195. }
  16196. int UndoManager::getNumActionsInCurrentTransaction() const
  16197. {
  16198. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16199. if (commandSet != 0 && ! newTransaction)
  16200. return commandSet->size();
  16201. return 0;
  16202. }
  16203. END_JUCE_NAMESPACE
  16204. /*** End of inlined file: juce_UndoManager.cpp ***/
  16205. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16206. BEGIN_JUCE_NAMESPACE
  16207. static const char* const aiffFormatName = "AIFF file";
  16208. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16209. class AiffAudioFormatReader : public AudioFormatReader
  16210. {
  16211. public:
  16212. int bytesPerFrame;
  16213. int64 dataChunkStart;
  16214. bool littleEndian;
  16215. AiffAudioFormatReader (InputStream* in)
  16216. : AudioFormatReader (in, TRANS (aiffFormatName))
  16217. {
  16218. if (input->readInt() == chunkName ("FORM"))
  16219. {
  16220. const int len = input->readIntBigEndian();
  16221. const int64 end = input->getPosition() + len;
  16222. const int nextType = input->readInt();
  16223. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16224. {
  16225. bool hasGotVer = false;
  16226. bool hasGotData = false;
  16227. bool hasGotType = false;
  16228. while (input->getPosition() < end)
  16229. {
  16230. const int type = input->readInt();
  16231. const uint32 length = (uint32) input->readIntBigEndian();
  16232. const int64 chunkEnd = input->getPosition() + length;
  16233. if (type == chunkName ("FVER"))
  16234. {
  16235. hasGotVer = true;
  16236. const int ver = input->readIntBigEndian();
  16237. if (ver != 0 && ver != (int) 0xa2805140)
  16238. break;
  16239. }
  16240. else if (type == chunkName ("COMM"))
  16241. {
  16242. hasGotType = true;
  16243. numChannels = (unsigned int) input->readShortBigEndian();
  16244. lengthInSamples = input->readIntBigEndian();
  16245. bitsPerSample = input->readShortBigEndian();
  16246. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16247. unsigned char sampleRateBytes[10];
  16248. input->read (sampleRateBytes, 10);
  16249. const int byte0 = sampleRateBytes[0];
  16250. if ((byte0 & 0x80) != 0
  16251. || byte0 <= 0x3F || byte0 > 0x40
  16252. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16253. break;
  16254. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16255. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16256. sampleRate = (int) sampRate;
  16257. if (length <= 18)
  16258. {
  16259. // some types don't have a chunk large enough to include a compression
  16260. // type, so assume it's just big-endian pcm
  16261. littleEndian = false;
  16262. }
  16263. else
  16264. {
  16265. const int compType = input->readInt();
  16266. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16267. {
  16268. littleEndian = false;
  16269. }
  16270. else if (compType == chunkName ("sowt"))
  16271. {
  16272. littleEndian = true;
  16273. }
  16274. else
  16275. {
  16276. sampleRate = 0;
  16277. break;
  16278. }
  16279. }
  16280. }
  16281. else if (type == chunkName ("SSND"))
  16282. {
  16283. hasGotData = true;
  16284. const int offset = input->readIntBigEndian();
  16285. dataChunkStart = input->getPosition() + 4 + offset;
  16286. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16287. }
  16288. else if ((hasGotVer && hasGotData && hasGotType)
  16289. || chunkEnd < input->getPosition()
  16290. || input->isExhausted())
  16291. {
  16292. break;
  16293. }
  16294. input->setPosition (chunkEnd);
  16295. }
  16296. }
  16297. }
  16298. }
  16299. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16300. int64 startSampleInFile, int numSamples)
  16301. {
  16302. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16303. if (samplesAvailable < numSamples)
  16304. {
  16305. for (int i = numDestChannels; --i >= 0;)
  16306. if (destSamples[i] != 0)
  16307. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16308. numSamples = (int) samplesAvailable;
  16309. }
  16310. if (numSamples <= 0)
  16311. return true;
  16312. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16313. while (numSamples > 0)
  16314. {
  16315. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16316. char tempBuffer [tempBufSize];
  16317. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16318. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16319. if (bytesRead < numThisTime * bytesPerFrame)
  16320. {
  16321. jassert (bytesRead >= 0);
  16322. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16323. }
  16324. jassert (! usesFloatingPointData); // (would need to add support for this if it's possible)
  16325. if (littleEndian)
  16326. {
  16327. switch (bitsPerSample)
  16328. {
  16329. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16330. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16331. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16332. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16333. default: jassertfalse; break;
  16334. }
  16335. }
  16336. else
  16337. {
  16338. switch (bitsPerSample)
  16339. {
  16340. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16341. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16342. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16343. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16344. default: jassertfalse; break;
  16345. }
  16346. }
  16347. startOffsetInDestBuffer += numThisTime;
  16348. numSamples -= numThisTime;
  16349. }
  16350. return true;
  16351. }
  16352. private:
  16353. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16354. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatReader);
  16355. };
  16356. class AiffAudioFormatWriter : public AudioFormatWriter
  16357. {
  16358. public:
  16359. AiffAudioFormatWriter (OutputStream* out, double sampleRate_, unsigned int numChans, int bits)
  16360. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  16361. lengthInSamples (0),
  16362. bytesWritten (0),
  16363. writeFailed (false)
  16364. {
  16365. headerPosition = out->getPosition();
  16366. writeHeader();
  16367. }
  16368. ~AiffAudioFormatWriter()
  16369. {
  16370. if ((bytesWritten & 1) != 0)
  16371. output->writeByte (0);
  16372. writeHeader();
  16373. }
  16374. bool write (const int** data, int numSamples)
  16375. {
  16376. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  16377. if (writeFailed)
  16378. return false;
  16379. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16380. tempBlock.ensureSize (bytes, false);
  16381. switch (bitsPerSample)
  16382. {
  16383. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16384. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16385. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16386. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16387. default: jassertfalse; break;
  16388. }
  16389. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16390. || ! output->write (tempBlock.getData(), bytes))
  16391. {
  16392. // failed to write to disk, so let's try writing the header.
  16393. // If it's just run out of disk space, then if it does manage
  16394. // to write the header, we'll still have a useable file..
  16395. writeHeader();
  16396. writeFailed = true;
  16397. return false;
  16398. }
  16399. else
  16400. {
  16401. bytesWritten += bytes;
  16402. lengthInSamples += numSamples;
  16403. return true;
  16404. }
  16405. }
  16406. private:
  16407. MemoryBlock tempBlock;
  16408. uint32 lengthInSamples, bytesWritten;
  16409. int64 headerPosition;
  16410. bool writeFailed;
  16411. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16412. void writeHeader()
  16413. {
  16414. const bool couldSeekOk = output->setPosition (headerPosition);
  16415. (void) couldSeekOk;
  16416. // if this fails, you've given it an output stream that can't seek! It needs
  16417. // to be able to seek back to write the header
  16418. jassert (couldSeekOk);
  16419. const int headerLen = 54;
  16420. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16421. audioBytes += (audioBytes & 1);
  16422. output->writeInt (chunkName ("FORM"));
  16423. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16424. output->writeInt (chunkName ("AIFF"));
  16425. output->writeInt (chunkName ("COMM"));
  16426. output->writeIntBigEndian (18);
  16427. output->writeShortBigEndian ((short) numChannels);
  16428. output->writeIntBigEndian (lengthInSamples);
  16429. output->writeShortBigEndian ((short) bitsPerSample);
  16430. uint8 sampleRateBytes[10];
  16431. zeromem (sampleRateBytes, 10);
  16432. if (sampleRate <= 1)
  16433. {
  16434. sampleRateBytes[0] = 0x3f;
  16435. sampleRateBytes[1] = 0xff;
  16436. sampleRateBytes[2] = 0x80;
  16437. }
  16438. else
  16439. {
  16440. int mask = 0x40000000;
  16441. sampleRateBytes[0] = 0x40;
  16442. if (sampleRate >= mask)
  16443. {
  16444. jassertfalse;
  16445. sampleRateBytes[1] = 0x1d;
  16446. }
  16447. else
  16448. {
  16449. int n = (int) sampleRate;
  16450. int i;
  16451. for (i = 0; i <= 32 ; ++i)
  16452. {
  16453. if ((n & mask) != 0)
  16454. break;
  16455. mask >>= 1;
  16456. }
  16457. n = n << (i + 1);
  16458. sampleRateBytes[1] = (uint8) (29 - i);
  16459. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16460. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16461. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16462. sampleRateBytes[5] = (uint8) (n & 0xff);
  16463. }
  16464. }
  16465. output->write (sampleRateBytes, 10);
  16466. output->writeInt (chunkName ("SSND"));
  16467. output->writeIntBigEndian (audioBytes + 8);
  16468. output->writeInt (0);
  16469. output->writeInt (0);
  16470. jassert (output->getPosition() == headerLen);
  16471. }
  16472. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatWriter);
  16473. };
  16474. AiffAudioFormat::AiffAudioFormat()
  16475. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  16476. {
  16477. }
  16478. AiffAudioFormat::~AiffAudioFormat()
  16479. {
  16480. }
  16481. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  16482. {
  16483. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  16484. return Array <int> (rates);
  16485. }
  16486. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  16487. {
  16488. const int depths[] = { 8, 16, 24, 0 };
  16489. return Array <int> (depths);
  16490. }
  16491. bool AiffAudioFormat::canDoStereo() { return true; }
  16492. bool AiffAudioFormat::canDoMono() { return true; }
  16493. #if JUCE_MAC
  16494. bool AiffAudioFormat::canHandleFile (const File& f)
  16495. {
  16496. if (AudioFormat::canHandleFile (f))
  16497. return true;
  16498. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  16499. return type == 'AIFF' || type == 'AIFC'
  16500. || type == 'aiff' || type == 'aifc';
  16501. }
  16502. #endif
  16503. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  16504. {
  16505. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  16506. if (w->sampleRate != 0)
  16507. return w.release();
  16508. if (! deleteStreamIfOpeningFails)
  16509. w->input = 0;
  16510. return 0;
  16511. }
  16512. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  16513. double sampleRate,
  16514. unsigned int numberOfChannels,
  16515. int bitsPerSample,
  16516. const StringPairArray& /*metadataValues*/,
  16517. int /*qualityOptionIndex*/)
  16518. {
  16519. if (getPossibleBitDepths().contains (bitsPerSample))
  16520. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, bitsPerSample);
  16521. return 0;
  16522. }
  16523. END_JUCE_NAMESPACE
  16524. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  16525. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  16526. BEGIN_JUCE_NAMESPACE
  16527. AudioFormat::AudioFormat (const String& name, const StringArray& extensions)
  16528. : formatName (name),
  16529. fileExtensions (extensions)
  16530. {
  16531. }
  16532. AudioFormat::~AudioFormat()
  16533. {
  16534. }
  16535. bool AudioFormat::canHandleFile (const File& f)
  16536. {
  16537. for (int i = 0; i < fileExtensions.size(); ++i)
  16538. if (f.hasFileExtension (fileExtensions[i]))
  16539. return true;
  16540. return false;
  16541. }
  16542. const String& AudioFormat::getFormatName() const { return formatName; }
  16543. const StringArray& AudioFormat::getFileExtensions() const { return fileExtensions; }
  16544. bool AudioFormat::isCompressed() { return false; }
  16545. const StringArray AudioFormat::getQualityOptions() { return StringArray(); }
  16546. END_JUCE_NAMESPACE
  16547. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16548. /*** Start of inlined file: juce_AudioFormatReader.cpp ***/
  16549. BEGIN_JUCE_NAMESPACE
  16550. AudioFormatReader::AudioFormatReader (InputStream* const in,
  16551. const String& formatName_)
  16552. : sampleRate (0),
  16553. bitsPerSample (0),
  16554. lengthInSamples (0),
  16555. numChannels (0),
  16556. usesFloatingPointData (false),
  16557. input (in),
  16558. formatName (formatName_)
  16559. {
  16560. }
  16561. AudioFormatReader::~AudioFormatReader()
  16562. {
  16563. delete input;
  16564. }
  16565. bool AudioFormatReader::read (int* const* destSamples,
  16566. int numDestChannels,
  16567. int64 startSampleInSource,
  16568. int numSamplesToRead,
  16569. const bool fillLeftoverChannelsWithCopies)
  16570. {
  16571. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  16572. int startOffsetInDestBuffer = 0;
  16573. if (startSampleInSource < 0)
  16574. {
  16575. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  16576. for (int i = numDestChannels; --i >= 0;)
  16577. if (destSamples[i] != 0)
  16578. zeromem (destSamples[i], sizeof (int) * silence);
  16579. startOffsetInDestBuffer += silence;
  16580. numSamplesToRead -= silence;
  16581. startSampleInSource = 0;
  16582. }
  16583. if (numSamplesToRead <= 0)
  16584. return true;
  16585. if (! readSamples (const_cast<int**> (destSamples),
  16586. jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  16587. startSampleInSource, numSamplesToRead))
  16588. return false;
  16589. if (numDestChannels > (int) numChannels)
  16590. {
  16591. if (fillLeftoverChannelsWithCopies)
  16592. {
  16593. int* lastFullChannel = destSamples[0];
  16594. for (int i = (int) numChannels; --i > 0;)
  16595. {
  16596. if (destSamples[i] != 0)
  16597. {
  16598. lastFullChannel = destSamples[i];
  16599. break;
  16600. }
  16601. }
  16602. if (lastFullChannel != 0)
  16603. for (int i = numChannels; i < numDestChannels; ++i)
  16604. if (destSamples[i] != 0)
  16605. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  16606. }
  16607. else
  16608. {
  16609. for (int i = numChannels; i < numDestChannels; ++i)
  16610. if (destSamples[i] != 0)
  16611. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  16612. }
  16613. }
  16614. return true;
  16615. }
  16616. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  16617. int64 numSamples,
  16618. float& lowestLeft, float& highestLeft,
  16619. float& lowestRight, float& highestRight)
  16620. {
  16621. if (numSamples <= 0)
  16622. {
  16623. lowestLeft = 0;
  16624. lowestRight = 0;
  16625. highestLeft = 0;
  16626. highestRight = 0;
  16627. return;
  16628. }
  16629. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16630. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  16631. int* tempBuffer[3];
  16632. tempBuffer[0] = tempSpace.getData();
  16633. tempBuffer[1] = tempSpace.getData() + bufferSize;
  16634. tempBuffer[2] = 0;
  16635. if (usesFloatingPointData)
  16636. {
  16637. float lmin = 1.0e6f;
  16638. float lmax = -lmin;
  16639. float rmin = lmin;
  16640. float rmax = lmax;
  16641. while (numSamples > 0)
  16642. {
  16643. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16644. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  16645. numSamples -= numToDo;
  16646. startSampleInFile += numToDo;
  16647. float bufMin, bufMax;
  16648. findMinAndMax (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufMin, bufMax);
  16649. lmin = jmin (lmin, bufMin);
  16650. lmax = jmax (lmax, bufMax);
  16651. if (numChannels > 1)
  16652. {
  16653. findMinAndMax (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufMin, bufMax);
  16654. rmin = jmin (rmin, bufMin);
  16655. rmax = jmax (rmax, bufMax);
  16656. }
  16657. }
  16658. if (numChannels <= 1)
  16659. {
  16660. rmax = lmax;
  16661. rmin = lmin;
  16662. }
  16663. lowestLeft = lmin;
  16664. highestLeft = lmax;
  16665. lowestRight = rmin;
  16666. highestRight = rmax;
  16667. }
  16668. else
  16669. {
  16670. int lmax = std::numeric_limits<int>::min();
  16671. int lmin = std::numeric_limits<int>::max();
  16672. int rmax = std::numeric_limits<int>::min();
  16673. int rmin = std::numeric_limits<int>::max();
  16674. while (numSamples > 0)
  16675. {
  16676. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16677. if (! read (tempBuffer, 2, startSampleInFile, numToDo, false))
  16678. break;
  16679. numSamples -= numToDo;
  16680. startSampleInFile += numToDo;
  16681. for (int j = numChannels; --j >= 0;)
  16682. {
  16683. int bufMin, bufMax;
  16684. findMinAndMax (tempBuffer[j], numToDo, bufMin, bufMax);
  16685. if (j == 0)
  16686. {
  16687. lmax = jmax (lmax, bufMax);
  16688. lmin = jmin (lmin, bufMin);
  16689. }
  16690. else
  16691. {
  16692. rmax = jmax (rmax, bufMax);
  16693. rmin = jmin (rmin, bufMin);
  16694. }
  16695. }
  16696. }
  16697. if (numChannels <= 1)
  16698. {
  16699. rmax = lmax;
  16700. rmin = lmin;
  16701. }
  16702. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16703. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16704. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16705. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16706. }
  16707. }
  16708. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16709. int64 numSamplesToSearch,
  16710. const double magnitudeRangeMinimum,
  16711. const double magnitudeRangeMaximum,
  16712. const int minimumConsecutiveSamples)
  16713. {
  16714. if (numSamplesToSearch == 0)
  16715. return -1;
  16716. const int bufferSize = 4096;
  16717. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  16718. int* tempBuffer[3];
  16719. tempBuffer[0] = tempSpace.getData();
  16720. tempBuffer[1] = tempSpace.getData() + bufferSize;
  16721. tempBuffer[2] = 0;
  16722. int consecutive = 0;
  16723. int64 firstMatchPos = -1;
  16724. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16725. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16726. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16727. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16728. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16729. while (numSamplesToSearch != 0)
  16730. {
  16731. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16732. int64 bufferStart = startSample;
  16733. if (numSamplesToSearch < 0)
  16734. bufferStart -= numThisTime;
  16735. if (bufferStart >= (int) lengthInSamples)
  16736. break;
  16737. read (tempBuffer, 2, bufferStart, numThisTime, false);
  16738. int num = numThisTime;
  16739. while (--num >= 0)
  16740. {
  16741. if (numSamplesToSearch < 0)
  16742. --startSample;
  16743. bool matches = false;
  16744. const int index = (int) (startSample - bufferStart);
  16745. if (usesFloatingPointData)
  16746. {
  16747. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  16748. if (sample1 >= magnitudeRangeMinimum
  16749. && sample1 <= magnitudeRangeMaximum)
  16750. {
  16751. matches = true;
  16752. }
  16753. else if (numChannels > 1)
  16754. {
  16755. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  16756. matches = (sample2 >= magnitudeRangeMinimum
  16757. && sample2 <= magnitudeRangeMaximum);
  16758. }
  16759. }
  16760. else
  16761. {
  16762. const int sample1 = abs (tempBuffer[0] [index]);
  16763. if (sample1 >= intMagnitudeRangeMinimum
  16764. && sample1 <= intMagnitudeRangeMaximum)
  16765. {
  16766. matches = true;
  16767. }
  16768. else if (numChannels > 1)
  16769. {
  16770. const int sample2 = abs (tempBuffer[1][index]);
  16771. matches = (sample2 >= intMagnitudeRangeMinimum
  16772. && sample2 <= intMagnitudeRangeMaximum);
  16773. }
  16774. }
  16775. if (matches)
  16776. {
  16777. if (firstMatchPos < 0)
  16778. firstMatchPos = startSample;
  16779. if (++consecutive >= minimumConsecutiveSamples)
  16780. {
  16781. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  16782. return -1;
  16783. return firstMatchPos;
  16784. }
  16785. }
  16786. else
  16787. {
  16788. consecutive = 0;
  16789. firstMatchPos = -1;
  16790. }
  16791. if (numSamplesToSearch > 0)
  16792. ++startSample;
  16793. }
  16794. if (numSamplesToSearch > 0)
  16795. numSamplesToSearch -= numThisTime;
  16796. else
  16797. numSamplesToSearch += numThisTime;
  16798. }
  16799. return -1;
  16800. }
  16801. END_JUCE_NAMESPACE
  16802. /*** End of inlined file: juce_AudioFormatReader.cpp ***/
  16803. /*** Start of inlined file: juce_AudioFormatWriter.cpp ***/
  16804. BEGIN_JUCE_NAMESPACE
  16805. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  16806. const String& formatName_,
  16807. const double rate,
  16808. const unsigned int numChannels_,
  16809. const unsigned int bitsPerSample_)
  16810. : sampleRate (rate),
  16811. numChannels (numChannels_),
  16812. bitsPerSample (bitsPerSample_),
  16813. usesFloatingPointData (false),
  16814. output (out),
  16815. formatName (formatName_)
  16816. {
  16817. }
  16818. AudioFormatWriter::~AudioFormatWriter()
  16819. {
  16820. delete output;
  16821. }
  16822. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  16823. int64 startSample,
  16824. int64 numSamplesToRead)
  16825. {
  16826. const int bufferSize = 16384;
  16827. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  16828. int* buffers [128];
  16829. zerostruct (buffers);
  16830. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16831. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  16832. if (numSamplesToRead < 0)
  16833. numSamplesToRead = reader.lengthInSamples;
  16834. while (numSamplesToRead > 0)
  16835. {
  16836. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  16837. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  16838. return false;
  16839. if (reader.usesFloatingPointData != isFloatingPoint())
  16840. {
  16841. int** bufferChan = buffers;
  16842. while (*bufferChan != 0)
  16843. {
  16844. int* b = *bufferChan++;
  16845. if (isFloatingPoint())
  16846. {
  16847. // int -> float
  16848. const double factor = 1.0 / std::numeric_limits<int>::max();
  16849. for (int i = 0; i < numToDo; ++i)
  16850. ((float*) b)[i] = (float) (factor * b[i]);
  16851. }
  16852. else
  16853. {
  16854. // float -> int
  16855. for (int i = 0; i < numToDo; ++i)
  16856. {
  16857. const double samp = *(const float*) b;
  16858. if (samp <= -1.0)
  16859. *b++ = std::numeric_limits<int>::min();
  16860. else if (samp >= 1.0)
  16861. *b++ = std::numeric_limits<int>::max();
  16862. else
  16863. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16864. }
  16865. }
  16866. }
  16867. }
  16868. if (! write (const_cast<const int**> (buffers), numToDo))
  16869. return false;
  16870. numSamplesToRead -= numToDo;
  16871. startSample += numToDo;
  16872. }
  16873. return true;
  16874. }
  16875. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source, int numSamplesToRead, const int samplesPerBlock)
  16876. {
  16877. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  16878. while (numSamplesToRead > 0)
  16879. {
  16880. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  16881. AudioSourceChannelInfo info;
  16882. info.buffer = &tempBuffer;
  16883. info.startSample = 0;
  16884. info.numSamples = numToDo;
  16885. info.clearActiveBufferRegion();
  16886. source.getNextAudioBlock (info);
  16887. if (! writeFromAudioSampleBuffer (tempBuffer, 0, numToDo))
  16888. return false;
  16889. numSamplesToRead -= numToDo;
  16890. }
  16891. return true;
  16892. }
  16893. bool AudioFormatWriter::writeFromAudioSampleBuffer (const AudioSampleBuffer& source, int startSample, int numSamples)
  16894. {
  16895. jassert (startSample >= 0 && startSample + numSamples <= source.getNumSamples() && source.getNumChannels() > 0);
  16896. if (numSamples <= 0)
  16897. return true;
  16898. HeapBlock<int> tempBuffer;
  16899. HeapBlock<int*> chans (numChannels + 1);
  16900. chans [numChannels] = 0;
  16901. if (isFloatingPoint())
  16902. {
  16903. for (int i = numChannels; --i >= 0;)
  16904. chans[i] = reinterpret_cast<int*> (source.getSampleData (i, startSample));
  16905. }
  16906. else
  16907. {
  16908. tempBuffer.malloc (numSamples * numChannels);
  16909. for (unsigned int i = 0; i < numChannels; ++i)
  16910. {
  16911. typedef AudioData::Pointer <AudioData::Int32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestSampleType;
  16912. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleType;
  16913. DestSampleType destData (chans[i] = tempBuffer + i * numSamples);
  16914. SourceSampleType sourceData (source.getSampleData (i, startSample));
  16915. destData.convertSamples (sourceData, numSamples);
  16916. }
  16917. }
  16918. return write ((const int**) chans.getData(), numSamples);
  16919. }
  16920. class AudioFormatWriter::ThreadedWriter::Buffer : public TimeSliceClient,
  16921. public AbstractFifo
  16922. {
  16923. public:
  16924. Buffer (TimeSliceThread& timeSliceThread_, AudioFormatWriter* writer_, int numChannels, int bufferSize_)
  16925. : AbstractFifo (bufferSize_),
  16926. buffer (numChannels, bufferSize_),
  16927. timeSliceThread (timeSliceThread_),
  16928. writer (writer_),
  16929. thumbnailToUpdate (0),
  16930. samplesWritten (0),
  16931. isRunning (true)
  16932. {
  16933. timeSliceThread.addTimeSliceClient (this);
  16934. }
  16935. ~Buffer()
  16936. {
  16937. isRunning = false;
  16938. timeSliceThread.removeTimeSliceClient (this);
  16939. while (useTimeSlice() == 0)
  16940. {}
  16941. }
  16942. bool write (const float** data, int numSamples)
  16943. {
  16944. if (numSamples <= 0 || ! isRunning)
  16945. return true;
  16946. jassert (timeSliceThread.isThreadRunning()); // you need to get your thread running before pumping data into this!
  16947. int start1, size1, start2, size2;
  16948. prepareToWrite (numSamples, start1, size1, start2, size2);
  16949. if (size1 + size2 < numSamples)
  16950. return false;
  16951. for (int i = buffer.getNumChannels(); --i >= 0;)
  16952. {
  16953. buffer.copyFrom (i, start1, data[i], size1);
  16954. buffer.copyFrom (i, start2, data[i] + size1, size2);
  16955. }
  16956. finishedWrite (size1 + size2);
  16957. timeSliceThread.notify();
  16958. return true;
  16959. }
  16960. int useTimeSlice()
  16961. {
  16962. const int numToDo = getTotalSize() / 4;
  16963. int start1, size1, start2, size2;
  16964. prepareToRead (numToDo, start1, size1, start2, size2);
  16965. if (size1 <= 0)
  16966. return 10;
  16967. writer->writeFromAudioSampleBuffer (buffer, start1, size1);
  16968. const ScopedLock sl (thumbnailLock);
  16969. if (thumbnailToUpdate != 0)
  16970. thumbnailToUpdate->addBlock (samplesWritten, buffer, start1, size1);
  16971. samplesWritten += size1;
  16972. if (size2 > 0)
  16973. {
  16974. writer->writeFromAudioSampleBuffer (buffer, start2, size2);
  16975. if (thumbnailToUpdate != 0)
  16976. thumbnailToUpdate->addBlock (samplesWritten, buffer, start2, size2);
  16977. samplesWritten += size2;
  16978. }
  16979. finishedRead (size1 + size2);
  16980. return 0;
  16981. }
  16982. void setThumbnail (AudioThumbnail* thumb)
  16983. {
  16984. if (thumb != 0)
  16985. thumb->reset (buffer.getNumChannels(), writer->getSampleRate(), 0);
  16986. const ScopedLock sl (thumbnailLock);
  16987. thumbnailToUpdate = thumb;
  16988. samplesWritten = 0;
  16989. }
  16990. private:
  16991. AudioSampleBuffer buffer;
  16992. TimeSliceThread& timeSliceThread;
  16993. ScopedPointer<AudioFormatWriter> writer;
  16994. CriticalSection thumbnailLock;
  16995. AudioThumbnail* thumbnailToUpdate;
  16996. int64 samplesWritten;
  16997. volatile bool isRunning;
  16998. JUCE_DECLARE_NON_COPYABLE (Buffer);
  16999. };
  17000. AudioFormatWriter::ThreadedWriter::ThreadedWriter (AudioFormatWriter* writer, TimeSliceThread& backgroundThread, int numSamplesToBuffer)
  17001. : buffer (new AudioFormatWriter::ThreadedWriter::Buffer (backgroundThread, writer, writer->numChannels, numSamplesToBuffer))
  17002. {
  17003. }
  17004. AudioFormatWriter::ThreadedWriter::~ThreadedWriter()
  17005. {
  17006. }
  17007. bool AudioFormatWriter::ThreadedWriter::write (const float** data, int numSamples)
  17008. {
  17009. return buffer->write (data, numSamples);
  17010. }
  17011. void AudioFormatWriter::ThreadedWriter::setThumbnailToUpdate (AudioThumbnail* thumb)
  17012. {
  17013. buffer->setThumbnail (thumb);
  17014. }
  17015. END_JUCE_NAMESPACE
  17016. /*** End of inlined file: juce_AudioFormatWriter.cpp ***/
  17017. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  17018. BEGIN_JUCE_NAMESPACE
  17019. AudioFormatManager::AudioFormatManager()
  17020. : defaultFormatIndex (0)
  17021. {
  17022. }
  17023. AudioFormatManager::~AudioFormatManager()
  17024. {
  17025. }
  17026. void AudioFormatManager::registerFormat (AudioFormat* newFormat, const bool makeThisTheDefaultFormat)
  17027. {
  17028. jassert (newFormat != 0);
  17029. if (newFormat != 0)
  17030. {
  17031. #if JUCE_DEBUG
  17032. for (int i = getNumKnownFormats(); --i >= 0;)
  17033. {
  17034. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17035. {
  17036. jassertfalse; // trying to add the same format twice!
  17037. }
  17038. }
  17039. #endif
  17040. if (makeThisTheDefaultFormat)
  17041. defaultFormatIndex = getNumKnownFormats();
  17042. knownFormats.add (newFormat);
  17043. }
  17044. }
  17045. void AudioFormatManager::registerBasicFormats()
  17046. {
  17047. #if JUCE_MAC
  17048. registerFormat (new AiffAudioFormat(), true);
  17049. registerFormat (new WavAudioFormat(), false);
  17050. #else
  17051. registerFormat (new WavAudioFormat(), true);
  17052. registerFormat (new AiffAudioFormat(), false);
  17053. #endif
  17054. #if JUCE_USE_FLAC
  17055. registerFormat (new FlacAudioFormat(), false);
  17056. #endif
  17057. #if JUCE_USE_OGGVORBIS
  17058. registerFormat (new OggVorbisAudioFormat(), false);
  17059. #endif
  17060. }
  17061. void AudioFormatManager::clearFormats()
  17062. {
  17063. knownFormats.clear();
  17064. defaultFormatIndex = 0;
  17065. }
  17066. int AudioFormatManager::getNumKnownFormats() const
  17067. {
  17068. return knownFormats.size();
  17069. }
  17070. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17071. {
  17072. return knownFormats [index];
  17073. }
  17074. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17075. {
  17076. return getKnownFormat (defaultFormatIndex);
  17077. }
  17078. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17079. {
  17080. String e (fileExtension);
  17081. if (! e.startsWithChar ('.'))
  17082. e = "." + e;
  17083. for (int i = 0; i < getNumKnownFormats(); ++i)
  17084. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17085. return getKnownFormat(i);
  17086. return 0;
  17087. }
  17088. const String AudioFormatManager::getWildcardForAllFormats() const
  17089. {
  17090. StringArray allExtensions;
  17091. int i;
  17092. for (i = 0; i < getNumKnownFormats(); ++i)
  17093. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17094. allExtensions.trim();
  17095. allExtensions.removeEmptyStrings();
  17096. String s;
  17097. for (i = 0; i < allExtensions.size(); ++i)
  17098. {
  17099. s << '*';
  17100. if (! allExtensions[i].startsWithChar ('.'))
  17101. s << '.';
  17102. s << allExtensions[i];
  17103. if (i < allExtensions.size() - 1)
  17104. s << ';';
  17105. }
  17106. return s;
  17107. }
  17108. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17109. {
  17110. // you need to actually register some formats before the manager can
  17111. // use them to open a file!
  17112. jassert (getNumKnownFormats() > 0);
  17113. for (int i = 0; i < getNumKnownFormats(); ++i)
  17114. {
  17115. AudioFormat* const af = getKnownFormat(i);
  17116. if (af->canHandleFile (file))
  17117. {
  17118. InputStream* const in = file.createInputStream();
  17119. if (in != 0)
  17120. {
  17121. AudioFormatReader* const r = af->createReaderFor (in, true);
  17122. if (r != 0)
  17123. return r;
  17124. }
  17125. }
  17126. }
  17127. return 0;
  17128. }
  17129. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17130. {
  17131. // you need to actually register some formats before the manager can
  17132. // use them to open a file!
  17133. jassert (getNumKnownFormats() > 0);
  17134. ScopedPointer <InputStream> in (audioFileStream);
  17135. if (in != 0)
  17136. {
  17137. const int64 originalStreamPos = in->getPosition();
  17138. for (int i = 0; i < getNumKnownFormats(); ++i)
  17139. {
  17140. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17141. if (r != 0)
  17142. {
  17143. in.release();
  17144. return r;
  17145. }
  17146. in->setPosition (originalStreamPos);
  17147. // the stream that is passed-in must be capable of being repositioned so
  17148. // that all the formats can have a go at opening it.
  17149. jassert (in->getPosition() == originalStreamPos);
  17150. }
  17151. }
  17152. return 0;
  17153. }
  17154. END_JUCE_NAMESPACE
  17155. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17156. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17157. BEGIN_JUCE_NAMESPACE
  17158. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17159. const int64 startSample_,
  17160. const int64 length_,
  17161. const bool deleteSourceWhenDeleted_)
  17162. : AudioFormatReader (0, source_->getFormatName()),
  17163. source (source_),
  17164. startSample (startSample_),
  17165. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17166. {
  17167. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17168. sampleRate = source->sampleRate;
  17169. bitsPerSample = source->bitsPerSample;
  17170. lengthInSamples = length;
  17171. numChannels = source->numChannels;
  17172. usesFloatingPointData = source->usesFloatingPointData;
  17173. }
  17174. AudioSubsectionReader::~AudioSubsectionReader()
  17175. {
  17176. if (deleteSourceWhenDeleted)
  17177. delete source;
  17178. }
  17179. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17180. int64 startSampleInFile, int numSamples)
  17181. {
  17182. if (startSampleInFile + numSamples > length)
  17183. {
  17184. for (int i = numDestChannels; --i >= 0;)
  17185. if (destSamples[i] != 0)
  17186. zeromem (destSamples[i], sizeof (int) * numSamples);
  17187. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17188. if (numSamples <= 0)
  17189. return true;
  17190. }
  17191. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17192. startSampleInFile + startSample, numSamples);
  17193. }
  17194. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17195. int64 numSamples,
  17196. float& lowestLeft,
  17197. float& highestLeft,
  17198. float& lowestRight,
  17199. float& highestRight)
  17200. {
  17201. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17202. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17203. source->readMaxLevels (startSampleInFile + startSample,
  17204. numSamples,
  17205. lowestLeft,
  17206. highestLeft,
  17207. lowestRight,
  17208. highestRight);
  17209. }
  17210. END_JUCE_NAMESPACE
  17211. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17212. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17213. BEGIN_JUCE_NAMESPACE
  17214. struct AudioThumbnail::MinMaxValue
  17215. {
  17216. char minValue;
  17217. char maxValue;
  17218. MinMaxValue() : minValue (0), maxValue (0)
  17219. {
  17220. }
  17221. inline void set (const char newMin, const char newMax) throw()
  17222. {
  17223. minValue = newMin;
  17224. maxValue = newMax;
  17225. }
  17226. inline void setFloat (const float newMin, const float newMax) throw()
  17227. {
  17228. minValue = (char) jlimit (-128, 127, roundFloatToInt (newMin * 127.0f));
  17229. maxValue = (char) jlimit (-128, 127, roundFloatToInt (newMax * 127.0f));
  17230. if (maxValue == minValue)
  17231. maxValue = (char) jmin (127, maxValue + 1);
  17232. }
  17233. inline bool isNonZero() const throw()
  17234. {
  17235. return maxValue > minValue;
  17236. }
  17237. inline int getPeak() const throw()
  17238. {
  17239. return jmax (std::abs ((int) minValue),
  17240. std::abs ((int) maxValue));
  17241. }
  17242. inline void read (InputStream& input)
  17243. {
  17244. minValue = input.readByte();
  17245. maxValue = input.readByte();
  17246. }
  17247. inline void write (OutputStream& output)
  17248. {
  17249. output.writeByte (minValue);
  17250. output.writeByte (maxValue);
  17251. }
  17252. };
  17253. class AudioThumbnail::LevelDataSource : public TimeSliceClient
  17254. {
  17255. public:
  17256. LevelDataSource (AudioThumbnail& owner_, AudioFormatReader* newReader, int64 hash)
  17257. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  17258. hashCode (hash), owner (owner_), reader (newReader)
  17259. {
  17260. }
  17261. LevelDataSource (AudioThumbnail& owner_, InputSource* source_)
  17262. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  17263. hashCode (source_->hashCode()), owner (owner_), source (source_)
  17264. {
  17265. }
  17266. ~LevelDataSource()
  17267. {
  17268. owner.cache.removeTimeSliceClient (this);
  17269. }
  17270. enum { timeBeforeDeletingReader = 1000 };
  17271. void initialise (int64 numSamplesFinished_)
  17272. {
  17273. const ScopedLock sl (readerLock);
  17274. numSamplesFinished = numSamplesFinished_;
  17275. createReader();
  17276. if (reader != 0)
  17277. {
  17278. lengthInSamples = reader->lengthInSamples;
  17279. numChannels = reader->numChannels;
  17280. sampleRate = reader->sampleRate;
  17281. if (lengthInSamples <= 0 || isFullyLoaded())
  17282. reader = 0;
  17283. else
  17284. owner.cache.addTimeSliceClient (this);
  17285. }
  17286. }
  17287. void getLevels (int64 startSample, int numSamples, Array<float>& levels)
  17288. {
  17289. const ScopedLock sl (readerLock);
  17290. if (reader == 0)
  17291. {
  17292. createReader();
  17293. if (reader != 0)
  17294. owner.cache.addTimeSliceClient (this);
  17295. }
  17296. if (reader != 0)
  17297. {
  17298. float l[4] = { 0 };
  17299. reader->readMaxLevels (startSample, numSamples, l[0], l[1], l[2], l[3]);
  17300. levels.clearQuick();
  17301. levels.addArray ((const float*) l, 4);
  17302. }
  17303. }
  17304. void releaseResources()
  17305. {
  17306. const ScopedLock sl (readerLock);
  17307. reader = 0;
  17308. }
  17309. int useTimeSlice()
  17310. {
  17311. if (isFullyLoaded())
  17312. {
  17313. if (reader != 0 && source != 0)
  17314. releaseResources();
  17315. return -1;
  17316. }
  17317. bool justFinished = false;
  17318. {
  17319. const ScopedLock sl (readerLock);
  17320. createReader();
  17321. if (reader != 0)
  17322. {
  17323. if (! readNextBlock())
  17324. return 0;
  17325. justFinished = true;
  17326. }
  17327. }
  17328. if (justFinished)
  17329. owner.cache.storeThumb (owner, hashCode);
  17330. return timeBeforeDeletingReader;
  17331. }
  17332. bool isFullyLoaded() const throw()
  17333. {
  17334. return numSamplesFinished >= lengthInSamples;
  17335. }
  17336. inline int sampleToThumbSample (const int64 originalSample) const throw()
  17337. {
  17338. return (int) (originalSample / owner.samplesPerThumbSample);
  17339. }
  17340. int64 lengthInSamples, numSamplesFinished;
  17341. double sampleRate;
  17342. int numChannels;
  17343. int64 hashCode;
  17344. private:
  17345. AudioThumbnail& owner;
  17346. ScopedPointer <InputSource> source;
  17347. ScopedPointer <AudioFormatReader> reader;
  17348. CriticalSection readerLock;
  17349. void createReader()
  17350. {
  17351. if (reader == 0 && source != 0)
  17352. {
  17353. InputStream* audioFileStream = source->createInputStream();
  17354. if (audioFileStream != 0)
  17355. reader = owner.formatManagerToUse.createReaderFor (audioFileStream);
  17356. }
  17357. }
  17358. bool readNextBlock()
  17359. {
  17360. jassert (reader != 0);
  17361. if (! isFullyLoaded())
  17362. {
  17363. const int numToDo = (int) jmin (256 * (int64) owner.samplesPerThumbSample, lengthInSamples - numSamplesFinished);
  17364. if (numToDo > 0)
  17365. {
  17366. int64 startSample = numSamplesFinished;
  17367. const int firstThumbIndex = sampleToThumbSample (startSample);
  17368. const int lastThumbIndex = sampleToThumbSample (startSample + numToDo);
  17369. const int numThumbSamps = lastThumbIndex - firstThumbIndex;
  17370. HeapBlock<MinMaxValue> levelData (numThumbSamps * 2);
  17371. MinMaxValue* levels[2] = { levelData, levelData + numThumbSamps };
  17372. for (int i = 0; i < numThumbSamps; ++i)
  17373. {
  17374. float lowestLeft, highestLeft, lowestRight, highestRight;
  17375. reader->readMaxLevels ((firstThumbIndex + i) * owner.samplesPerThumbSample, owner.samplesPerThumbSample,
  17376. lowestLeft, highestLeft, lowestRight, highestRight);
  17377. levels[0][i].setFloat (lowestLeft, highestLeft);
  17378. levels[1][i].setFloat (lowestRight, highestRight);
  17379. }
  17380. {
  17381. const ScopedUnlock su (readerLock);
  17382. owner.setLevels (levels, firstThumbIndex, 2, numThumbSamps);
  17383. }
  17384. numSamplesFinished += numToDo;
  17385. }
  17386. }
  17387. return isFullyLoaded();
  17388. }
  17389. };
  17390. class AudioThumbnail::ThumbData
  17391. {
  17392. public:
  17393. ThumbData (const int numThumbSamples)
  17394. : peakLevel (-1)
  17395. {
  17396. ensureSize (numThumbSamples);
  17397. }
  17398. inline MinMaxValue* getData (const int thumbSampleIndex) throw()
  17399. {
  17400. jassert (thumbSampleIndex < data.size());
  17401. return data.getRawDataPointer() + thumbSampleIndex;
  17402. }
  17403. int getSize() const throw()
  17404. {
  17405. return data.size();
  17406. }
  17407. void getMinMax (int startSample, int endSample, MinMaxValue& result) throw()
  17408. {
  17409. if (startSample >= 0)
  17410. {
  17411. endSample = jmin (endSample, data.size() - 1);
  17412. char mx = -128;
  17413. char mn = 127;
  17414. while (startSample <= endSample)
  17415. {
  17416. const MinMaxValue& v = data.getReference (startSample);
  17417. if (v.minValue < mn) mn = v.minValue;
  17418. if (v.maxValue > mx) mx = v.maxValue;
  17419. ++startSample;
  17420. }
  17421. if (mn <= mx)
  17422. {
  17423. result.set (mn, mx);
  17424. return;
  17425. }
  17426. }
  17427. result.set (1, 0);
  17428. }
  17429. void write (const MinMaxValue* const source, const int startIndex, const int numValues)
  17430. {
  17431. resetPeak();
  17432. if (startIndex + numValues > data.size())
  17433. ensureSize (startIndex + numValues);
  17434. MinMaxValue* const dest = getData (startIndex);
  17435. for (int i = 0; i < numValues; ++i)
  17436. dest[i] = source[i];
  17437. }
  17438. void resetPeak()
  17439. {
  17440. peakLevel = -1;
  17441. }
  17442. int getPeak()
  17443. {
  17444. if (peakLevel < 0)
  17445. {
  17446. for (int i = 0; i < data.size(); ++i)
  17447. {
  17448. const int peak = data[i].getPeak();
  17449. if (peak > peakLevel)
  17450. peakLevel = peak;
  17451. }
  17452. }
  17453. return peakLevel;
  17454. }
  17455. private:
  17456. Array <MinMaxValue> data;
  17457. int peakLevel;
  17458. void ensureSize (const int thumbSamples)
  17459. {
  17460. const int extraNeeded = thumbSamples - data.size();
  17461. if (extraNeeded > 0)
  17462. data.insertMultiple (-1, MinMaxValue(), extraNeeded);
  17463. }
  17464. };
  17465. class AudioThumbnail::CachedWindow
  17466. {
  17467. public:
  17468. CachedWindow()
  17469. : cachedStart (0), cachedTimePerPixel (0),
  17470. numChannelsCached (0), numSamplesCached (0),
  17471. cacheNeedsRefilling (true)
  17472. {
  17473. }
  17474. void invalidate()
  17475. {
  17476. cacheNeedsRefilling = true;
  17477. }
  17478. void drawChannel (Graphics& g, const Rectangle<int>& area,
  17479. const double startTime, const double endTime,
  17480. const int channelNum, const float verticalZoomFactor,
  17481. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  17482. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  17483. {
  17484. refillCache (area.getWidth(), startTime, endTime, sampleRate,
  17485. numChannels, samplesPerThumbSample, levelData, channels);
  17486. if (isPositiveAndBelow (channelNum, numChannelsCached))
  17487. {
  17488. const Rectangle<int> clip (g.getClipBounds().getIntersection (area.withWidth (jmin (numSamplesCached, area.getWidth()))));
  17489. if (! clip.isEmpty())
  17490. {
  17491. const float topY = (float) area.getY();
  17492. const float bottomY = (float) area.getBottom();
  17493. const float midY = (topY + bottomY) * 0.5f;
  17494. const float vscale = verticalZoomFactor * (bottomY - topY) / 256.0f;
  17495. const MinMaxValue* cacheData = getData (channelNum, clip.getX() - area.getX());
  17496. int x = clip.getX();
  17497. for (int w = clip.getWidth(); --w >= 0;)
  17498. {
  17499. if (cacheData->isNonZero())
  17500. g.drawVerticalLine (x, jmax (midY - cacheData->maxValue * vscale - 0.3f, topY),
  17501. jmin (midY - cacheData->minValue * vscale + 0.3f, bottomY));
  17502. ++x;
  17503. ++cacheData;
  17504. }
  17505. }
  17506. }
  17507. }
  17508. private:
  17509. Array <MinMaxValue> data;
  17510. double cachedStart, cachedTimePerPixel;
  17511. int numChannelsCached, numSamplesCached;
  17512. bool cacheNeedsRefilling;
  17513. void refillCache (const int numSamples, double startTime, const double endTime,
  17514. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  17515. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  17516. {
  17517. const double timePerPixel = (endTime - startTime) / numSamples;
  17518. if (numSamples <= 0 || timePerPixel <= 0.0 || sampleRate <= 0)
  17519. {
  17520. invalidate();
  17521. return;
  17522. }
  17523. if (numSamples == numSamplesCached
  17524. && numChannelsCached == numChannels
  17525. && startTime == cachedStart
  17526. && timePerPixel == cachedTimePerPixel
  17527. && ! cacheNeedsRefilling)
  17528. {
  17529. return;
  17530. }
  17531. numSamplesCached = numSamples;
  17532. numChannelsCached = numChannels;
  17533. cachedStart = startTime;
  17534. cachedTimePerPixel = timePerPixel;
  17535. cacheNeedsRefilling = false;
  17536. ensureSize (numSamples);
  17537. if (timePerPixel * sampleRate <= samplesPerThumbSample && levelData != 0)
  17538. {
  17539. int sample = roundToInt (startTime * sampleRate);
  17540. Array<float> levels;
  17541. int i;
  17542. for (i = 0; i < numSamples; ++i)
  17543. {
  17544. const int nextSample = roundToInt ((startTime + timePerPixel) * sampleRate);
  17545. if (sample >= 0)
  17546. {
  17547. if (sample >= levelData->lengthInSamples)
  17548. break;
  17549. levelData->getLevels (sample, jmax (1, nextSample - sample), levels);
  17550. const int numChans = jmin (levels.size() / 2, numChannelsCached);
  17551. for (int chan = 0; chan < numChans; ++chan)
  17552. getData (chan, i)->setFloat (levels.getUnchecked (chan * 2),
  17553. levels.getUnchecked (chan * 2 + 1));
  17554. }
  17555. startTime += timePerPixel;
  17556. sample = nextSample;
  17557. }
  17558. numSamplesCached = i;
  17559. }
  17560. else
  17561. {
  17562. jassert (channels.size() == numChannelsCached);
  17563. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  17564. {
  17565. ThumbData* channelData = channels.getUnchecked (channelNum);
  17566. MinMaxValue* cacheData = getData (channelNum, 0);
  17567. const double timeToThumbSampleFactor = sampleRate / (double) samplesPerThumbSample;
  17568. startTime = cachedStart;
  17569. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  17570. for (int i = numSamples; --i >= 0;)
  17571. {
  17572. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  17573. channelData->getMinMax (sample, nextSample, *cacheData);
  17574. ++cacheData;
  17575. startTime += timePerPixel;
  17576. sample = nextSample;
  17577. }
  17578. }
  17579. }
  17580. }
  17581. MinMaxValue* getData (const int channelNum, const int cacheIndex) throw()
  17582. {
  17583. jassert (isPositiveAndBelow (channelNum, numChannelsCached) && isPositiveAndBelow (cacheIndex, data.size()));
  17584. return data.getRawDataPointer() + channelNum * numSamplesCached
  17585. + cacheIndex;
  17586. }
  17587. void ensureSize (const int numSamples)
  17588. {
  17589. const int itemsRequired = numSamples * numChannelsCached;
  17590. if (data.size() < itemsRequired)
  17591. data.insertMultiple (-1, MinMaxValue(), itemsRequired - data.size());
  17592. }
  17593. };
  17594. AudioThumbnail::AudioThumbnail (const int originalSamplesPerThumbnailSample,
  17595. AudioFormatManager& formatManagerToUse_,
  17596. AudioThumbnailCache& cacheToUse)
  17597. : formatManagerToUse (formatManagerToUse_),
  17598. cache (cacheToUse),
  17599. window (new CachedWindow()),
  17600. samplesPerThumbSample (originalSamplesPerThumbnailSample),
  17601. totalSamples (0),
  17602. numChannels (0),
  17603. sampleRate (0)
  17604. {
  17605. }
  17606. AudioThumbnail::~AudioThumbnail()
  17607. {
  17608. clear();
  17609. }
  17610. void AudioThumbnail::clear()
  17611. {
  17612. source = 0;
  17613. const ScopedLock sl (lock);
  17614. window->invalidate();
  17615. channels.clear();
  17616. totalSamples = numSamplesFinished = 0;
  17617. numChannels = 0;
  17618. sampleRate = 0;
  17619. sendChangeMessage();
  17620. }
  17621. void AudioThumbnail::reset (int newNumChannels, double newSampleRate, int64 totalSamplesInSource)
  17622. {
  17623. clear();
  17624. numChannels = newNumChannels;
  17625. sampleRate = newSampleRate;
  17626. totalSamples = totalSamplesInSource;
  17627. createChannels (1 + (int) (totalSamplesInSource / samplesPerThumbSample));
  17628. }
  17629. void AudioThumbnail::createChannels (const int length)
  17630. {
  17631. while (channels.size() < numChannels)
  17632. channels.add (new ThumbData (length));
  17633. }
  17634. void AudioThumbnail::loadFrom (InputStream& input)
  17635. {
  17636. clear();
  17637. if (input.readByte() != 'j' || input.readByte() != 'a' || input.readByte() != 't' || input.readByte() != 'm')
  17638. return;
  17639. samplesPerThumbSample = input.readInt();
  17640. totalSamples = input.readInt64(); // Total number of source samples.
  17641. numSamplesFinished = input.readInt64(); // Number of valid source samples that have been read into the thumbnail.
  17642. int32 numThumbnailSamples = input.readInt(); // Number of samples in the thumbnail data.
  17643. numChannels = input.readInt(); // Number of audio channels.
  17644. sampleRate = input.readInt(); // Source sample rate.
  17645. input.skipNextBytes (16); // reserved area
  17646. createChannels (numThumbnailSamples);
  17647. for (int i = 0; i < numThumbnailSamples; ++i)
  17648. for (int chan = 0; chan < numChannels; ++chan)
  17649. channels.getUnchecked(chan)->getData(i)->read (input);
  17650. }
  17651. void AudioThumbnail::saveTo (OutputStream& output) const
  17652. {
  17653. const ScopedLock sl (lock);
  17654. const int numThumbnailSamples = channels.size() == 0 ? 0 : channels.getUnchecked(0)->getSize();
  17655. output.write ("jatm", 4);
  17656. output.writeInt (samplesPerThumbSample);
  17657. output.writeInt64 (totalSamples);
  17658. output.writeInt64 (numSamplesFinished);
  17659. output.writeInt (numThumbnailSamples);
  17660. output.writeInt (numChannels);
  17661. output.writeInt ((int) sampleRate);
  17662. output.writeInt64 (0);
  17663. output.writeInt64 (0);
  17664. for (int i = 0; i < numThumbnailSamples; ++i)
  17665. for (int chan = 0; chan < numChannels; ++chan)
  17666. channels.getUnchecked(chan)->getData(i)->write (output);
  17667. }
  17668. bool AudioThumbnail::setDataSource (LevelDataSource* newSource)
  17669. {
  17670. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  17671. numSamplesFinished = 0;
  17672. if (cache.loadThumb (*this, newSource->hashCode) && isFullyLoaded())
  17673. {
  17674. source = newSource; // (make sure this isn't done before loadThumb is called)
  17675. source->lengthInSamples = totalSamples;
  17676. source->sampleRate = sampleRate;
  17677. source->numChannels = numChannels;
  17678. source->numSamplesFinished = numSamplesFinished;
  17679. }
  17680. else
  17681. {
  17682. source = newSource; // (make sure this isn't done before loadThumb is called)
  17683. const ScopedLock sl (lock);
  17684. source->initialise (numSamplesFinished);
  17685. totalSamples = source->lengthInSamples;
  17686. sampleRate = source->sampleRate;
  17687. numChannels = source->numChannels;
  17688. createChannels (1 + (int) (totalSamples / samplesPerThumbSample));
  17689. }
  17690. return sampleRate > 0 && totalSamples > 0;
  17691. }
  17692. bool AudioThumbnail::setSource (InputSource* const newSource)
  17693. {
  17694. clear();
  17695. return newSource != 0 && setDataSource (new LevelDataSource (*this, newSource));
  17696. }
  17697. void AudioThumbnail::setReader (AudioFormatReader* newReader, int64 hash)
  17698. {
  17699. clear();
  17700. if (newReader != 0)
  17701. setDataSource (new LevelDataSource (*this, newReader, hash));
  17702. }
  17703. int64 AudioThumbnail::getHashCode() const
  17704. {
  17705. return source == 0 ? 0 : source->hashCode;
  17706. }
  17707. void AudioThumbnail::addBlock (const int64 startSample, const AudioSampleBuffer& incoming,
  17708. int startOffsetInBuffer, int numSamples)
  17709. {
  17710. jassert (startSample >= 0);
  17711. const int firstThumbIndex = (int) (startSample / samplesPerThumbSample);
  17712. const int lastThumbIndex = (int) ((startSample + numSamples + (samplesPerThumbSample - 1)) / samplesPerThumbSample);
  17713. const int numToDo = lastThumbIndex - firstThumbIndex;
  17714. if (numToDo > 0)
  17715. {
  17716. const int numChans = jmin (channels.size(), incoming.getNumChannels());
  17717. const HeapBlock<MinMaxValue> thumbData (numToDo * numChans);
  17718. const HeapBlock<MinMaxValue*> thumbChannels (numChans);
  17719. for (int chan = 0; chan < numChans; ++chan)
  17720. {
  17721. const float* const sourceData = incoming.getSampleData (chan, startOffsetInBuffer);
  17722. MinMaxValue* const dest = thumbData + numToDo * chan;
  17723. thumbChannels [chan] = dest;
  17724. for (int i = 0; i < numToDo; ++i)
  17725. {
  17726. float low, high;
  17727. const int start = i * samplesPerThumbSample;
  17728. findMinAndMax (sourceData + start, jmin (samplesPerThumbSample, numSamples - start), low, high);
  17729. dest[i].setFloat (low, high);
  17730. }
  17731. }
  17732. setLevels (thumbChannels, firstThumbIndex, numChans, numToDo);
  17733. }
  17734. }
  17735. void AudioThumbnail::setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues)
  17736. {
  17737. const ScopedLock sl (lock);
  17738. for (int i = jmin (numChans, channels.size()); --i >= 0;)
  17739. channels.getUnchecked(i)->write (values[i], thumbIndex, numValues);
  17740. numSamplesFinished = jmax (numSamplesFinished, (thumbIndex + numValues) * (int64) samplesPerThumbSample);
  17741. totalSamples = jmax (numSamplesFinished, totalSamples);
  17742. window->invalidate();
  17743. sendChangeMessage();
  17744. }
  17745. int AudioThumbnail::getNumChannels() const throw()
  17746. {
  17747. return numChannels;
  17748. }
  17749. double AudioThumbnail::getTotalLength() const throw()
  17750. {
  17751. return totalSamples / sampleRate;
  17752. }
  17753. bool AudioThumbnail::isFullyLoaded() const throw()
  17754. {
  17755. return numSamplesFinished >= totalSamples - samplesPerThumbSample;
  17756. }
  17757. int64 AudioThumbnail::getNumSamplesFinished() const throw()
  17758. {
  17759. return numSamplesFinished;
  17760. }
  17761. float AudioThumbnail::getApproximatePeak() const
  17762. {
  17763. int peak = 0;
  17764. for (int i = channels.size(); --i >= 0;)
  17765. peak = jmax (peak, channels.getUnchecked(i)->getPeak());
  17766. return jlimit (0, 127, peak) / 127.0f;
  17767. }
  17768. void AudioThumbnail::drawChannel (Graphics& g, const Rectangle<int>& area, double startTime,
  17769. double endTime, int channelNum, float verticalZoomFactor)
  17770. {
  17771. const ScopedLock sl (lock);
  17772. window->drawChannel (g, area, startTime, endTime, channelNum, verticalZoomFactor,
  17773. sampleRate, numChannels, samplesPerThumbSample, source, channels);
  17774. }
  17775. void AudioThumbnail::drawChannels (Graphics& g, const Rectangle<int>& area, double startTimeSeconds,
  17776. double endTimeSeconds, float verticalZoomFactor)
  17777. {
  17778. for (int i = 0; i < numChannels; ++i)
  17779. {
  17780. const int y1 = roundToInt ((i * area.getHeight()) / numChannels);
  17781. const int y2 = roundToInt (((i + 1) * area.getHeight()) / numChannels);
  17782. drawChannel (g, Rectangle<int> (area.getX(), area.getY() + y1, area.getWidth(), y2 - y1),
  17783. startTimeSeconds, endTimeSeconds, i, verticalZoomFactor);
  17784. }
  17785. }
  17786. END_JUCE_NAMESPACE
  17787. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  17788. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  17789. BEGIN_JUCE_NAMESPACE
  17790. struct ThumbnailCacheEntry
  17791. {
  17792. int64 hash;
  17793. uint32 lastUsed;
  17794. MemoryBlock data;
  17795. JUCE_LEAK_DETECTOR (ThumbnailCacheEntry);
  17796. };
  17797. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  17798. : TimeSliceThread ("thumb cache"),
  17799. maxNumThumbsToStore (maxNumThumbsToStore_)
  17800. {
  17801. startThread (2);
  17802. }
  17803. AudioThumbnailCache::~AudioThumbnailCache()
  17804. {
  17805. }
  17806. ThumbnailCacheEntry* AudioThumbnailCache::findThumbFor (const int64 hash) const
  17807. {
  17808. for (int i = thumbs.size(); --i >= 0;)
  17809. if (thumbs.getUnchecked(i)->hash == hash)
  17810. return thumbs.getUnchecked(i);
  17811. return 0;
  17812. }
  17813. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  17814. {
  17815. ThumbnailCacheEntry* te = findThumbFor (hashCode);
  17816. if (te != 0)
  17817. {
  17818. te->lastUsed = Time::getMillisecondCounter();
  17819. MemoryInputStream in (te->data, false);
  17820. thumb.loadFrom (in);
  17821. return true;
  17822. }
  17823. return false;
  17824. }
  17825. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  17826. const int64 hashCode)
  17827. {
  17828. ThumbnailCacheEntry* te = findThumbFor (hashCode);
  17829. if (te == 0)
  17830. {
  17831. te = new ThumbnailCacheEntry();
  17832. te->hash = hashCode;
  17833. if (thumbs.size() < maxNumThumbsToStore)
  17834. {
  17835. thumbs.add (te);
  17836. }
  17837. else
  17838. {
  17839. int oldest = 0;
  17840. uint32 oldestTime = Time::getMillisecondCounter() + 1;
  17841. for (int i = thumbs.size(); --i >= 0;)
  17842. {
  17843. if (thumbs.getUnchecked(i)->lastUsed < oldestTime)
  17844. {
  17845. oldest = i;
  17846. oldestTime = thumbs.getUnchecked(i)->lastUsed;
  17847. }
  17848. }
  17849. thumbs.set (oldest, te);
  17850. }
  17851. }
  17852. te->lastUsed = Time::getMillisecondCounter();
  17853. MemoryOutputStream out (te->data, false);
  17854. thumb.saveTo (out);
  17855. }
  17856. void AudioThumbnailCache::clear()
  17857. {
  17858. thumbs.clear();
  17859. }
  17860. END_JUCE_NAMESPACE
  17861. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  17862. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17863. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  17864. #if ! JUCE_WINDOWS
  17865. #include <QuickTime/Movies.h>
  17866. #include <QuickTime/QTML.h>
  17867. #include <QuickTime/QuickTimeComponents.h>
  17868. #include <QuickTime/MediaHandlers.h>
  17869. #include <QuickTime/ImageCodec.h>
  17870. #else
  17871. #if JUCE_MSVC
  17872. #pragma warning (push)
  17873. #pragma warning (disable : 4100)
  17874. #endif
  17875. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  17876. add its header directory to your include path.
  17877. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  17878. flag in juce_Config.h
  17879. */
  17880. #include <Movies.h>
  17881. #include <QTML.h>
  17882. #include <QuickTimeComponents.h>
  17883. #include <MediaHandlers.h>
  17884. #include <ImageCodec.h>
  17885. #if JUCE_MSVC
  17886. #pragma warning (pop)
  17887. #endif
  17888. #endif
  17889. BEGIN_JUCE_NAMESPACE
  17890. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  17891. static const char* const quickTimeFormatName = "QuickTime file";
  17892. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", ".m4a", 0 };
  17893. class QTAudioReader : public AudioFormatReader
  17894. {
  17895. public:
  17896. QTAudioReader (InputStream* const input_, const int trackNum_)
  17897. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  17898. ok (false),
  17899. movie (0),
  17900. trackNum (trackNum_),
  17901. lastSampleRead (0),
  17902. lastThreadId (0),
  17903. extractor (0),
  17904. dataHandle (0)
  17905. {
  17906. JUCE_AUTORELEASEPOOL
  17907. bufferList.calloc (256, 1);
  17908. #if JUCE_WINDOWS
  17909. if (InitializeQTML (0) != noErr)
  17910. return;
  17911. #endif
  17912. if (EnterMovies() != noErr)
  17913. return;
  17914. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  17915. if (! opened)
  17916. return;
  17917. {
  17918. const int numTracks = GetMovieTrackCount (movie);
  17919. int trackCount = 0;
  17920. for (int i = 1; i <= numTracks; ++i)
  17921. {
  17922. track = GetMovieIndTrack (movie, i);
  17923. media = GetTrackMedia (track);
  17924. OSType mediaType;
  17925. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  17926. if (mediaType == SoundMediaType
  17927. && trackCount++ == trackNum_)
  17928. {
  17929. ok = true;
  17930. break;
  17931. }
  17932. }
  17933. }
  17934. if (! ok)
  17935. return;
  17936. ok = false;
  17937. lengthInSamples = GetMediaDecodeDuration (media);
  17938. usesFloatingPointData = false;
  17939. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  17940. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  17941. / GetMediaTimeScale (media);
  17942. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  17943. unsigned long output_layout_size;
  17944. err = MovieAudioExtractionGetPropertyInfo (extractor,
  17945. kQTPropertyClass_MovieAudioExtraction_Audio,
  17946. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17947. 0, &output_layout_size, 0);
  17948. if (err != noErr)
  17949. return;
  17950. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  17951. qt_audio_channel_layout.calloc (output_layout_size, 1);
  17952. err = MovieAudioExtractionGetProperty (extractor,
  17953. kQTPropertyClass_MovieAudioExtraction_Audio,
  17954. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17955. output_layout_size, qt_audio_channel_layout, 0);
  17956. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  17957. err = MovieAudioExtractionSetProperty (extractor,
  17958. kQTPropertyClass_MovieAudioExtraction_Audio,
  17959. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17960. output_layout_size,
  17961. qt_audio_channel_layout);
  17962. err = MovieAudioExtractionGetProperty (extractor,
  17963. kQTPropertyClass_MovieAudioExtraction_Audio,
  17964. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17965. sizeof (inputStreamDesc),
  17966. &inputStreamDesc, 0);
  17967. if (err != noErr)
  17968. return;
  17969. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  17970. | kAudioFormatFlagIsPacked
  17971. | kAudioFormatFlagsNativeEndian;
  17972. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  17973. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  17974. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  17975. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  17976. err = MovieAudioExtractionSetProperty (extractor,
  17977. kQTPropertyClass_MovieAudioExtraction_Audio,
  17978. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17979. sizeof (inputStreamDesc),
  17980. &inputStreamDesc);
  17981. if (err != noErr)
  17982. return;
  17983. Boolean allChannelsDiscrete = false;
  17984. err = MovieAudioExtractionSetProperty (extractor,
  17985. kQTPropertyClass_MovieAudioExtraction_Movie,
  17986. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  17987. sizeof (allChannelsDiscrete),
  17988. &allChannelsDiscrete);
  17989. if (err != noErr)
  17990. return;
  17991. bufferList->mNumberBuffers = 1;
  17992. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  17993. bufferList->mBuffers[0].mDataByteSize = jmax ((UInt32) 4096, (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16);
  17994. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  17995. bufferList->mBuffers[0].mData = dataBuffer;
  17996. sampleRate = inputStreamDesc.mSampleRate;
  17997. bitsPerSample = 16;
  17998. numChannels = inputStreamDesc.mChannelsPerFrame;
  17999. detachThread();
  18000. ok = true;
  18001. }
  18002. ~QTAudioReader()
  18003. {
  18004. JUCE_AUTORELEASEPOOL
  18005. checkThreadIsAttached();
  18006. if (dataHandle != 0)
  18007. DisposeHandle (dataHandle);
  18008. if (extractor != 0)
  18009. {
  18010. MovieAudioExtractionEnd (extractor);
  18011. extractor = 0;
  18012. }
  18013. DisposeMovie (movie);
  18014. #if JUCE_MAC
  18015. ExitMoviesOnThread ();
  18016. #endif
  18017. }
  18018. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18019. int64 startSampleInFile, int numSamples)
  18020. {
  18021. JUCE_AUTORELEASEPOOL
  18022. checkThreadIsAttached();
  18023. bool ok = true;
  18024. while (numSamples > 0)
  18025. {
  18026. if (lastSampleRead != startSampleInFile)
  18027. {
  18028. TimeRecord time;
  18029. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  18030. time.base = 0;
  18031. time.value.hi = 0;
  18032. time.value.lo = (UInt32) startSampleInFile;
  18033. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  18034. kQTPropertyClass_MovieAudioExtraction_Movie,
  18035. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  18036. sizeof (time), &time);
  18037. if (err != noErr)
  18038. {
  18039. ok = false;
  18040. break;
  18041. }
  18042. }
  18043. int framesToDo = jmin (numSamples, (int) (bufferList->mBuffers[0].mDataByteSize / inputStreamDesc.mBytesPerFrame));
  18044. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * framesToDo;
  18045. UInt32 outFlags = 0;
  18046. UInt32 actualNumFrames = framesToDo;
  18047. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumFrames, bufferList, &outFlags);
  18048. if (err != noErr)
  18049. {
  18050. ok = false;
  18051. break;
  18052. }
  18053. lastSampleRead = startSampleInFile + actualNumFrames;
  18054. const int samplesReceived = actualNumFrames;
  18055. for (int j = numDestChannels; --j >= 0;)
  18056. {
  18057. if (destSamples[j] != 0)
  18058. {
  18059. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  18060. for (int i = 0; i < samplesReceived; ++i)
  18061. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  18062. }
  18063. }
  18064. startOffsetInDestBuffer += samplesReceived;
  18065. startSampleInFile += samplesReceived;
  18066. numSamples -= samplesReceived;
  18067. if ((outFlags & kQTMovieAudioExtractionComplete) != 0 && numSamples > 0)
  18068. {
  18069. for (int j = numDestChannels; --j >= 0;)
  18070. if (destSamples[j] != 0)
  18071. zeromem (destSamples[j] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18072. break;
  18073. }
  18074. }
  18075. detachThread();
  18076. return ok;
  18077. }
  18078. bool ok;
  18079. private:
  18080. Movie movie;
  18081. Media media;
  18082. Track track;
  18083. const int trackNum;
  18084. double trackUnitsPerFrame;
  18085. int samplesPerFrame;
  18086. int64 lastSampleRead;
  18087. Thread::ThreadID lastThreadId;
  18088. MovieAudioExtractionRef extractor;
  18089. AudioStreamBasicDescription inputStreamDesc;
  18090. HeapBlock <AudioBufferList> bufferList;
  18091. HeapBlock <char> dataBuffer;
  18092. Handle dataHandle;
  18093. void checkThreadIsAttached()
  18094. {
  18095. #if JUCE_MAC
  18096. if (Thread::getCurrentThreadId() != lastThreadId)
  18097. EnterMoviesOnThread (0);
  18098. AttachMovieToCurrentThread (movie);
  18099. #endif
  18100. }
  18101. void detachThread()
  18102. {
  18103. #if JUCE_MAC
  18104. DetachMovieFromCurrentThread (movie);
  18105. #endif
  18106. }
  18107. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (QTAudioReader);
  18108. };
  18109. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18110. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18111. {
  18112. }
  18113. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18114. {
  18115. }
  18116. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates() { return Array<int>(); }
  18117. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths() { return Array<int>(); }
  18118. bool QuickTimeAudioFormat::canDoStereo() { return true; }
  18119. bool QuickTimeAudioFormat::canDoMono() { return true; }
  18120. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18121. const bool deleteStreamIfOpeningFails)
  18122. {
  18123. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18124. if (r->ok)
  18125. return r.release();
  18126. if (! deleteStreamIfOpeningFails)
  18127. r->input = 0;
  18128. return 0;
  18129. }
  18130. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18131. double /*sampleRateToUse*/,
  18132. unsigned int /*numberOfChannels*/,
  18133. int /*bitsPerSample*/,
  18134. const StringPairArray& /*metadataValues*/,
  18135. int /*qualityOptionIndex*/)
  18136. {
  18137. jassertfalse; // not yet implemented!
  18138. return 0;
  18139. }
  18140. END_JUCE_NAMESPACE
  18141. #endif
  18142. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18143. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18144. BEGIN_JUCE_NAMESPACE
  18145. static const char* const wavFormatName = "WAV file";
  18146. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18147. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18148. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18149. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18150. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18151. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18152. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18153. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18154. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18155. const String& originator,
  18156. const String& originatorRef,
  18157. const Time& date,
  18158. const int64 timeReferenceSamples,
  18159. const String& codingHistory)
  18160. {
  18161. StringPairArray m;
  18162. m.set (bwavDescription, description);
  18163. m.set (bwavOriginator, originator);
  18164. m.set (bwavOriginatorRef, originatorRef);
  18165. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18166. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18167. m.set (bwavTimeReference, String (timeReferenceSamples));
  18168. m.set (bwavCodingHistory, codingHistory);
  18169. return m;
  18170. }
  18171. namespace WavFileHelpers
  18172. {
  18173. #if JUCE_MSVC
  18174. #pragma pack (push, 1)
  18175. #define PACKED
  18176. #elif JUCE_GCC
  18177. #define PACKED __attribute__((packed))
  18178. #else
  18179. #define PACKED
  18180. #endif
  18181. struct BWAVChunk
  18182. {
  18183. char description [256];
  18184. char originator [32];
  18185. char originatorRef [32];
  18186. char originationDate [10];
  18187. char originationTime [8];
  18188. uint32 timeRefLow;
  18189. uint32 timeRefHigh;
  18190. uint16 version;
  18191. uint8 umid[64];
  18192. uint8 reserved[190];
  18193. char codingHistory[1];
  18194. void copyTo (StringPairArray& values) const
  18195. {
  18196. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18197. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18198. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18199. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18200. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18201. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18202. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18203. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18204. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18205. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18206. }
  18207. static MemoryBlock createFrom (const StringPairArray& values)
  18208. {
  18209. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18210. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18211. data.fillWith (0);
  18212. BWAVChunk* b = (BWAVChunk*) data.getData();
  18213. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18214. // as they get called in the right order..
  18215. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18216. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18217. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18218. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18219. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18220. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18221. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18222. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18223. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18224. if (b->description[0] != 0
  18225. || b->originator[0] != 0
  18226. || b->originationDate[0] != 0
  18227. || b->originationTime[0] != 0
  18228. || b->codingHistory[0] != 0
  18229. || time != 0)
  18230. {
  18231. return data;
  18232. }
  18233. return MemoryBlock();
  18234. }
  18235. } PACKED;
  18236. struct SMPLChunk
  18237. {
  18238. struct SampleLoop
  18239. {
  18240. uint32 identifier;
  18241. uint32 type;
  18242. uint32 start;
  18243. uint32 end;
  18244. uint32 fraction;
  18245. uint32 playCount;
  18246. } PACKED;
  18247. uint32 manufacturer;
  18248. uint32 product;
  18249. uint32 samplePeriod;
  18250. uint32 midiUnityNote;
  18251. uint32 midiPitchFraction;
  18252. uint32 smpteFormat;
  18253. uint32 smpteOffset;
  18254. uint32 numSampleLoops;
  18255. uint32 samplerData;
  18256. SampleLoop loops[1];
  18257. void copyTo (StringPairArray& values, const int totalSize) const
  18258. {
  18259. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18260. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18261. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18262. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18263. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18264. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18265. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18266. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18267. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18268. for (uint32 i = 0; i < numSampleLoops; ++i)
  18269. {
  18270. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18271. break;
  18272. const String prefix ("Loop" + String(i));
  18273. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18274. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18275. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18276. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18277. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18278. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18279. }
  18280. }
  18281. static MemoryBlock createFrom (const StringPairArray& values)
  18282. {
  18283. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18284. if (numLoops <= 0)
  18285. return MemoryBlock();
  18286. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18287. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18288. data.fillWith (0);
  18289. SMPLChunk* s = (SMPLChunk*) data.getData();
  18290. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18291. // as they get called in the right order..
  18292. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18293. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18294. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18295. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18296. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18297. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18298. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18299. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18300. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18301. for (int i = 0; i < numLoops; ++i)
  18302. {
  18303. const String prefix ("Loop" + String(i));
  18304. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18305. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18306. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18307. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18308. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18309. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18310. }
  18311. return data;
  18312. }
  18313. } PACKED;
  18314. struct ExtensibleWavSubFormat
  18315. {
  18316. uint32 data1;
  18317. uint16 data2;
  18318. uint16 data3;
  18319. uint8 data4[8];
  18320. } PACKED;
  18321. struct DataSize64Chunk // chunk ID = 'ds64' if data size > 0xffffffff, 'JUNK' otherwise
  18322. {
  18323. uint32 riffSizeLow; // low 4 byte size of RF64 block
  18324. uint32 riffSizeHigh; // high 4 byte size of RF64 block
  18325. uint32 dataSizeLow; // low 4 byte size of data chunk
  18326. uint32 dataSizeHigh; // high 4 byte size of data chunk
  18327. uint32 sampleCountLow; // low 4 byte sample count of fact chunk
  18328. uint32 sampleCountHigh; // high 4 byte sample count of fact chunk
  18329. uint32 tableLength; // number of valid entries in array 'table'
  18330. } PACKED;
  18331. #if JUCE_MSVC
  18332. #pragma pack (pop)
  18333. #endif
  18334. #undef PACKED
  18335. inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18336. }
  18337. class WavAudioFormatReader : public AudioFormatReader
  18338. {
  18339. public:
  18340. WavAudioFormatReader (InputStream* const in)
  18341. : AudioFormatReader (in, TRANS (wavFormatName)),
  18342. bwavChunkStart (0),
  18343. bwavSize (0),
  18344. dataLength (0),
  18345. isRF64 (false)
  18346. {
  18347. using namespace WavFileHelpers;
  18348. uint64 len = 0;
  18349. int64 end = 0;
  18350. bool hasGotType = false;
  18351. bool hasGotData = false;
  18352. const int firstChunkType = input->readInt();
  18353. if (firstChunkType == chunkName ("RF64"))
  18354. {
  18355. input->skipNextBytes (4); // size is -1 for RF64
  18356. isRF64 = true;
  18357. }
  18358. else if (firstChunkType == chunkName ("RIFF"))
  18359. {
  18360. len = (uint64) input->readInt();
  18361. end = input->getPosition() + len;
  18362. }
  18363. else
  18364. {
  18365. return;
  18366. }
  18367. const int64 startOfRIFFChunk = input->getPosition();
  18368. if (input->readInt() == chunkName ("WAVE"))
  18369. {
  18370. if (isRF64 && input->readInt() == chunkName ("ds64"))
  18371. {
  18372. uint32 length = (uint32) input->readInt();
  18373. if (length < 28)
  18374. {
  18375. return;
  18376. }
  18377. else
  18378. {
  18379. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18380. len = input->readInt64();
  18381. end = startOfRIFFChunk + len;
  18382. dataLength = input->readInt64();
  18383. input->setPosition (chunkEnd);
  18384. }
  18385. }
  18386. while (input->getPosition() < end && ! input->isExhausted())
  18387. {
  18388. const int chunkType = input->readInt();
  18389. uint32 length = (uint32) input->readInt();
  18390. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18391. if (chunkType == chunkName ("fmt "))
  18392. {
  18393. // read the format chunk
  18394. const unsigned short format = input->readShort();
  18395. const short numChans = input->readShort();
  18396. sampleRate = input->readInt();
  18397. const int bytesPerSec = input->readInt();
  18398. numChannels = numChans;
  18399. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18400. bitsPerSample = 8 * bytesPerFrame / numChans;
  18401. if (format == 3)
  18402. {
  18403. usesFloatingPointData = true;
  18404. }
  18405. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18406. {
  18407. if (length < 40) // too short
  18408. {
  18409. bytesPerFrame = 0;
  18410. }
  18411. else
  18412. {
  18413. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18414. ExtensibleWavSubFormat subFormat;
  18415. subFormat.data1 = input->readInt();
  18416. subFormat.data2 = input->readShort();
  18417. subFormat.data3 = input->readShort();
  18418. input->read (subFormat.data4, sizeof (subFormat.data4));
  18419. const ExtensibleWavSubFormat pcmFormat
  18420. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18421. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18422. {
  18423. const ExtensibleWavSubFormat ambisonicFormat
  18424. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18425. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18426. bytesPerFrame = 0;
  18427. }
  18428. }
  18429. }
  18430. else if (format != 1)
  18431. {
  18432. bytesPerFrame = 0;
  18433. }
  18434. hasGotType = true;
  18435. }
  18436. else if (chunkType == chunkName ("data"))
  18437. {
  18438. // get the data chunk's position
  18439. if (! isRF64) // data size is expected to be -1, actual data size is in ds64 chunk
  18440. dataLength = length;
  18441. dataChunkStart = input->getPosition();
  18442. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18443. hasGotData = true;
  18444. }
  18445. else if (chunkType == chunkName ("bext"))
  18446. {
  18447. bwavChunkStart = input->getPosition();
  18448. bwavSize = length;
  18449. // Broadcast-wav extension chunk..
  18450. HeapBlock <BWAVChunk> bwav;
  18451. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18452. input->read (bwav, length);
  18453. bwav->copyTo (metadataValues);
  18454. }
  18455. else if (chunkType == chunkName ("smpl"))
  18456. {
  18457. HeapBlock <SMPLChunk> smpl;
  18458. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18459. input->read (smpl, length);
  18460. smpl->copyTo (metadataValues, length);
  18461. }
  18462. else if (chunkEnd <= input->getPosition())
  18463. {
  18464. break;
  18465. }
  18466. input->setPosition (chunkEnd);
  18467. }
  18468. }
  18469. }
  18470. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18471. int64 startSampleInFile, int numSamples)
  18472. {
  18473. jassert (destSamples != 0);
  18474. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18475. if (samplesAvailable < numSamples)
  18476. {
  18477. for (int i = numDestChannels; --i >= 0;)
  18478. if (destSamples[i] != 0)
  18479. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18480. numSamples = (int) samplesAvailable;
  18481. }
  18482. if (numSamples <= 0)
  18483. return true;
  18484. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18485. while (numSamples > 0)
  18486. {
  18487. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18488. char tempBuffer [tempBufSize];
  18489. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18490. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18491. if (bytesRead < numThisTime * bytesPerFrame)
  18492. {
  18493. jassert (bytesRead >= 0);
  18494. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18495. }
  18496. switch (bitsPerSample)
  18497. {
  18498. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18499. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18500. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18501. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime);
  18502. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18503. default: jassertfalse; break;
  18504. }
  18505. startOffsetInDestBuffer += numThisTime;
  18506. numSamples -= numThisTime;
  18507. }
  18508. return true;
  18509. }
  18510. int64 bwavChunkStart, bwavSize;
  18511. private:
  18512. ScopedPointer<AudioData::Converter> converter;
  18513. int bytesPerFrame;
  18514. int64 dataChunkStart, dataLength;
  18515. bool isRF64;
  18516. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatReader);
  18517. };
  18518. class WavAudioFormatWriter : public AudioFormatWriter
  18519. {
  18520. public:
  18521. WavAudioFormatWriter (OutputStream* const out, const double sampleRate_,
  18522. const unsigned int numChannels_, const int bits,
  18523. const StringPairArray& metadataValues)
  18524. : AudioFormatWriter (out, TRANS (wavFormatName), sampleRate_, numChannels_, bits),
  18525. lengthInSamples (0),
  18526. bytesWritten (0),
  18527. writeFailed (false)
  18528. {
  18529. using namespace WavFileHelpers;
  18530. if (metadataValues.size() > 0)
  18531. {
  18532. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18533. smplChunk = SMPLChunk::createFrom (metadataValues);
  18534. }
  18535. headerPosition = out->getPosition();
  18536. writeHeader();
  18537. }
  18538. ~WavAudioFormatWriter()
  18539. {
  18540. if ((bytesWritten & 1) != 0) // pad to an even length
  18541. {
  18542. ++bytesWritten;
  18543. output->writeByte (0);
  18544. }
  18545. writeHeader();
  18546. }
  18547. bool write (const int** data, int numSamples)
  18548. {
  18549. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  18550. if (writeFailed)
  18551. return false;
  18552. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  18553. tempBlock.ensureSize (bytes, false);
  18554. switch (bitsPerSample)
  18555. {
  18556. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18557. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18558. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18559. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18560. default: jassertfalse; break;
  18561. }
  18562. if (! output->write (tempBlock.getData(), bytes))
  18563. {
  18564. // failed to write to disk, so let's try writing the header.
  18565. // If it's just run out of disk space, then if it does manage
  18566. // to write the header, we'll still have a useable file..
  18567. writeHeader();
  18568. writeFailed = true;
  18569. return false;
  18570. }
  18571. else
  18572. {
  18573. bytesWritten += bytes;
  18574. lengthInSamples += numSamples;
  18575. return true;
  18576. }
  18577. }
  18578. private:
  18579. ScopedPointer<AudioData::Converter> converter;
  18580. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18581. uint64 lengthInSamples, bytesWritten;
  18582. int64 headerPosition;
  18583. bool writeFailed;
  18584. static int getChannelMask (const int numChannels) throw()
  18585. {
  18586. switch (numChannels)
  18587. {
  18588. case 1: return 0;
  18589. case 2: return 1 + 2; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT
  18590. case 5: return 1 + 2 + 4 + 16 + 32; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT
  18591. case 6: return 1 + 2 + 4 + 8 + 16 + 32; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT
  18592. default: break;
  18593. }
  18594. return 0;
  18595. }
  18596. void writeHeader()
  18597. {
  18598. using namespace WavFileHelpers;
  18599. const bool seekedOk = output->setPosition (headerPosition);
  18600. (void) seekedOk;
  18601. // if this fails, you've given it an output stream that can't seek! It needs
  18602. // to be able to seek back to write the header
  18603. jassert (seekedOk);
  18604. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18605. int64 audioDataSize = bytesPerFrame * lengthInSamples;
  18606. const bool isRF64 = (bytesWritten >= literal64bit (0x100000000));
  18607. int64 riffChunkSize = 4 /* 'RIFF' */ + 8 + 40 /* WAVEFORMATEX */
  18608. + 8 + audioDataSize + (audioDataSize & 1)
  18609. + (bwavChunk.getSize() > 0 ? (8 + bwavChunk.getSize()) : 0)
  18610. + (smplChunk.getSize() > 0 ? (8 + smplChunk.getSize()) : 0)
  18611. + (8 + 28); // (ds64 chunk)
  18612. riffChunkSize += (riffChunkSize & 0x1);
  18613. output->writeInt (chunkName (isRF64 ? "RF64" : "RIFF"));
  18614. output->writeInt (isRF64 ? -1 : (int) riffChunkSize);
  18615. output->writeInt (chunkName ("WAVE"));
  18616. if (! isRF64)
  18617. {
  18618. output->writeInt (chunkName ("JUNK"));
  18619. output->writeInt (28 + 24);
  18620. output->writeRepeatedByte (0, 28 /* ds64 */ + 24 /* extra waveformatex */);
  18621. }
  18622. else
  18623. {
  18624. // write ds64 chunk
  18625. output->writeInt (chunkName ("ds64"));
  18626. output->writeInt (28); // chunk size for uncompressed data (no table)
  18627. output->writeInt64 (riffChunkSize);
  18628. output->writeInt64 (audioDataSize);
  18629. output->writeRepeatedByte (0, 12);
  18630. }
  18631. output->writeInt (chunkName ("fmt "));
  18632. if (isRF64)
  18633. {
  18634. output->writeInt (40); // chunk size
  18635. output->writeShort ((short) (uint16) 0xfffe); // WAVE_FORMAT_EXTENSIBLE
  18636. }
  18637. else
  18638. {
  18639. output->writeInt (16); // chunk size
  18640. output->writeShort (bitsPerSample < 32 ? (short) 1 /*WAVE_FORMAT_PCM*/
  18641. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  18642. }
  18643. output->writeShort ((short) numChannels);
  18644. output->writeInt ((int) sampleRate);
  18645. output->writeInt ((int) (bytesPerFrame * sampleRate)); // nAvgBytesPerSec
  18646. output->writeShort ((short) bytesPerFrame); // nBlockAlign
  18647. output->writeShort ((short) bitsPerSample); // wBitsPerSample
  18648. if (isRF64)
  18649. {
  18650. output->writeShort (22); // cbSize (size of the extension)
  18651. output->writeShort ((short) bitsPerSample); // wValidBitsPerSample
  18652. output->writeInt (getChannelMask (numChannels));
  18653. const ExtensibleWavSubFormat pcmFormat
  18654. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18655. const ExtensibleWavSubFormat IEEEFloatFormat
  18656. = { 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18657. const ExtensibleWavSubFormat& subFormat = bitsPerSample < 32 ? pcmFormat : IEEEFloatFormat;
  18658. output->writeInt ((int) subFormat.data1);
  18659. output->writeShort ((short) subFormat.data2);
  18660. output->writeShort ((short) subFormat.data3);
  18661. output->write (subFormat.data4, sizeof (subFormat.data4));
  18662. }
  18663. if (bwavChunk.getSize() > 0)
  18664. {
  18665. output->writeInt (chunkName ("bext"));
  18666. output->writeInt ((int) bwavChunk.getSize());
  18667. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18668. }
  18669. if (smplChunk.getSize() > 0)
  18670. {
  18671. output->writeInt (chunkName ("smpl"));
  18672. output->writeInt ((int) smplChunk.getSize());
  18673. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18674. }
  18675. output->writeInt (chunkName ("data"));
  18676. output->writeInt (isRF64 ? -1 : (int) (lengthInSamples * bytesPerFrame));
  18677. usesFloatingPointData = (bitsPerSample == 32);
  18678. }
  18679. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatWriter);
  18680. };
  18681. WavAudioFormat::WavAudioFormat()
  18682. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18683. {
  18684. }
  18685. WavAudioFormat::~WavAudioFormat()
  18686. {
  18687. }
  18688. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18689. {
  18690. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18691. return Array <int> (rates);
  18692. }
  18693. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18694. {
  18695. const int depths[] = { 8, 16, 24, 32, 0 };
  18696. return Array <int> (depths);
  18697. }
  18698. bool WavAudioFormat::canDoStereo() { return true; }
  18699. bool WavAudioFormat::canDoMono() { return true; }
  18700. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18701. const bool deleteStreamIfOpeningFails)
  18702. {
  18703. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18704. if (r->sampleRate != 0)
  18705. return r.release();
  18706. if (! deleteStreamIfOpeningFails)
  18707. r->input = 0;
  18708. return 0;
  18709. }
  18710. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out, double sampleRate,
  18711. unsigned int numChannels, int bitsPerSample,
  18712. const StringPairArray& metadataValues, int /*qualityOptionIndex*/)
  18713. {
  18714. if (getPossibleBitDepths().contains (bitsPerSample))
  18715. return new WavAudioFormatWriter (out, sampleRate, numChannels, bitsPerSample, metadataValues);
  18716. return 0;
  18717. }
  18718. namespace WavFileHelpers
  18719. {
  18720. bool slowCopyWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18721. {
  18722. TemporaryFile tempFile (file);
  18723. WavAudioFormat wav;
  18724. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18725. if (reader != 0)
  18726. {
  18727. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18728. if (outStream != 0)
  18729. {
  18730. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18731. reader->numChannels, reader->bitsPerSample,
  18732. metadata, 0));
  18733. if (writer != 0)
  18734. {
  18735. outStream.release();
  18736. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18737. writer = 0;
  18738. reader = 0;
  18739. return ok && tempFile.overwriteTargetFileWithTemporary();
  18740. }
  18741. }
  18742. }
  18743. return false;
  18744. }
  18745. }
  18746. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18747. {
  18748. using namespace WavFileHelpers;
  18749. ScopedPointer <WavAudioFormatReader> reader (static_cast <WavAudioFormatReader*> (createReaderFor (wavFile.createInputStream(), true)));
  18750. if (reader != 0)
  18751. {
  18752. const int64 bwavPos = reader->bwavChunkStart;
  18753. const int64 bwavSize = reader->bwavSize;
  18754. reader = 0;
  18755. if (bwavSize > 0)
  18756. {
  18757. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18758. if (chunk.getSize() <= (size_t) bwavSize)
  18759. {
  18760. // the new one will fit in the space available, so write it directly..
  18761. const int64 oldSize = wavFile.getSize();
  18762. {
  18763. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18764. out->setPosition (bwavPos);
  18765. out->write (chunk.getData(), (int) chunk.getSize());
  18766. out->setPosition (oldSize);
  18767. }
  18768. jassert (wavFile.getSize() == oldSize);
  18769. return true;
  18770. }
  18771. }
  18772. }
  18773. return slowCopyWavFileWithNewMetadata (wavFile, newMetadata);
  18774. }
  18775. END_JUCE_NAMESPACE
  18776. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18777. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  18778. #if JUCE_USE_CDREADER
  18779. BEGIN_JUCE_NAMESPACE
  18780. int AudioCDReader::getNumTracks() const
  18781. {
  18782. return trackStartSamples.size() - 1;
  18783. }
  18784. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  18785. {
  18786. return trackStartSamples [trackNum];
  18787. }
  18788. const Array<int>& AudioCDReader::getTrackOffsets() const
  18789. {
  18790. return trackStartSamples;
  18791. }
  18792. int AudioCDReader::getCDDBId()
  18793. {
  18794. int checksum = 0;
  18795. const int numTracks = getNumTracks();
  18796. for (int i = 0; i < numTracks; ++i)
  18797. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  18798. checksum += offset % 10;
  18799. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  18800. // CCLLLLTT: checksum, length, tracks
  18801. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  18802. }
  18803. END_JUCE_NAMESPACE
  18804. #endif
  18805. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  18806. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18807. BEGIN_JUCE_NAMESPACE
  18808. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18809. const bool deleteReaderWhenThisIsDeleted)
  18810. : reader (reader_),
  18811. deleteReader (deleteReaderWhenThisIsDeleted),
  18812. nextPlayPos (0),
  18813. looping (false)
  18814. {
  18815. jassert (reader != 0);
  18816. }
  18817. AudioFormatReaderSource::~AudioFormatReaderSource()
  18818. {
  18819. releaseResources();
  18820. if (deleteReader)
  18821. delete reader;
  18822. }
  18823. void AudioFormatReaderSource::setNextReadPosition (int64 newPosition)
  18824. {
  18825. nextPlayPos = newPosition;
  18826. }
  18827. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  18828. {
  18829. looping = shouldLoop;
  18830. }
  18831. int64 AudioFormatReaderSource::getNextReadPosition() const
  18832. {
  18833. return looping ? nextPlayPos % reader->lengthInSamples
  18834. : nextPlayPos;
  18835. }
  18836. int64 AudioFormatReaderSource::getTotalLength() const
  18837. {
  18838. return reader->lengthInSamples;
  18839. }
  18840. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18841. double /*sampleRate*/)
  18842. {
  18843. }
  18844. void AudioFormatReaderSource::releaseResources()
  18845. {
  18846. }
  18847. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18848. {
  18849. if (info.numSamples > 0)
  18850. {
  18851. const int64 start = nextPlayPos;
  18852. if (looping)
  18853. {
  18854. const int newStart = start % (int) reader->lengthInSamples;
  18855. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18856. if (newEnd > newStart)
  18857. {
  18858. info.buffer->readFromAudioReader (reader,
  18859. info.startSample,
  18860. newEnd - newStart,
  18861. newStart,
  18862. true, true);
  18863. }
  18864. else
  18865. {
  18866. const int endSamps = (int) reader->lengthInSamples - newStart;
  18867. info.buffer->readFromAudioReader (reader,
  18868. info.startSample,
  18869. endSamps,
  18870. newStart,
  18871. true, true);
  18872. info.buffer->readFromAudioReader (reader,
  18873. info.startSample + endSamps,
  18874. newEnd,
  18875. 0,
  18876. true, true);
  18877. }
  18878. nextPlayPos = newEnd;
  18879. }
  18880. else
  18881. {
  18882. info.buffer->readFromAudioReader (reader,
  18883. info.startSample,
  18884. info.numSamples,
  18885. start,
  18886. true, true);
  18887. nextPlayPos += info.numSamples;
  18888. }
  18889. }
  18890. }
  18891. END_JUCE_NAMESPACE
  18892. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18893. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  18894. BEGIN_JUCE_NAMESPACE
  18895. AudioSourcePlayer::AudioSourcePlayer()
  18896. : source (0),
  18897. sampleRate (0),
  18898. bufferSize (0),
  18899. tempBuffer (2, 8),
  18900. lastGain (1.0f),
  18901. gain (1.0f)
  18902. {
  18903. }
  18904. AudioSourcePlayer::~AudioSourcePlayer()
  18905. {
  18906. setSource (0);
  18907. }
  18908. void AudioSourcePlayer::setSource (AudioSource* newSource)
  18909. {
  18910. if (source != newSource)
  18911. {
  18912. AudioSource* const oldSource = source;
  18913. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  18914. newSource->prepareToPlay (bufferSize, sampleRate);
  18915. {
  18916. const ScopedLock sl (readLock);
  18917. source = newSource;
  18918. }
  18919. if (oldSource != 0)
  18920. oldSource->releaseResources();
  18921. }
  18922. }
  18923. void AudioSourcePlayer::setGain (const float newGain) throw()
  18924. {
  18925. gain = newGain;
  18926. }
  18927. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  18928. int totalNumInputChannels,
  18929. float** outputChannelData,
  18930. int totalNumOutputChannels,
  18931. int numSamples)
  18932. {
  18933. // these should have been prepared by audioDeviceAboutToStart()...
  18934. jassert (sampleRate > 0 && bufferSize > 0);
  18935. const ScopedLock sl (readLock);
  18936. if (source != 0)
  18937. {
  18938. AudioSourceChannelInfo info;
  18939. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  18940. // messy stuff needed to compact the channels down into an array
  18941. // of non-zero pointers..
  18942. for (i = 0; i < totalNumInputChannels; ++i)
  18943. {
  18944. if (inputChannelData[i] != 0)
  18945. {
  18946. inputChans [numInputs++] = inputChannelData[i];
  18947. if (numInputs >= numElementsInArray (inputChans))
  18948. break;
  18949. }
  18950. }
  18951. for (i = 0; i < totalNumOutputChannels; ++i)
  18952. {
  18953. if (outputChannelData[i] != 0)
  18954. {
  18955. outputChans [numOutputs++] = outputChannelData[i];
  18956. if (numOutputs >= numElementsInArray (outputChans))
  18957. break;
  18958. }
  18959. }
  18960. if (numInputs > numOutputs)
  18961. {
  18962. // if there aren't enough output channels for the number of
  18963. // inputs, we need to create some temporary extra ones (can't
  18964. // use the input data in case it gets written to)
  18965. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  18966. false, false, true);
  18967. for (i = 0; i < numOutputs; ++i)
  18968. {
  18969. channels[numActiveChans] = outputChans[i];
  18970. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18971. ++numActiveChans;
  18972. }
  18973. for (i = numOutputs; i < numInputs; ++i)
  18974. {
  18975. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  18976. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18977. ++numActiveChans;
  18978. }
  18979. }
  18980. else
  18981. {
  18982. for (i = 0; i < numInputs; ++i)
  18983. {
  18984. channels[numActiveChans] = outputChans[i];
  18985. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18986. ++numActiveChans;
  18987. }
  18988. for (i = numInputs; i < numOutputs; ++i)
  18989. {
  18990. channels[numActiveChans] = outputChans[i];
  18991. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  18992. ++numActiveChans;
  18993. }
  18994. }
  18995. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  18996. info.buffer = &buffer;
  18997. info.startSample = 0;
  18998. info.numSamples = numSamples;
  18999. source->getNextAudioBlock (info);
  19000. for (i = info.buffer->getNumChannels(); --i >= 0;)
  19001. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  19002. lastGain = gain;
  19003. }
  19004. else
  19005. {
  19006. for (int i = 0; i < totalNumOutputChannels; ++i)
  19007. if (outputChannelData[i] != 0)
  19008. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19009. }
  19010. }
  19011. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  19012. {
  19013. sampleRate = device->getCurrentSampleRate();
  19014. bufferSize = device->getCurrentBufferSizeSamples();
  19015. zeromem (channels, sizeof (channels));
  19016. if (source != 0)
  19017. source->prepareToPlay (bufferSize, sampleRate);
  19018. }
  19019. void AudioSourcePlayer::audioDeviceStopped()
  19020. {
  19021. if (source != 0)
  19022. source->releaseResources();
  19023. sampleRate = 0.0;
  19024. bufferSize = 0;
  19025. tempBuffer.setSize (2, 8);
  19026. }
  19027. END_JUCE_NAMESPACE
  19028. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19029. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19030. BEGIN_JUCE_NAMESPACE
  19031. AudioTransportSource::AudioTransportSource()
  19032. : source (0),
  19033. resamplerSource (0),
  19034. bufferingSource (0),
  19035. positionableSource (0),
  19036. masterSource (0),
  19037. gain (1.0f),
  19038. lastGain (1.0f),
  19039. playing (false),
  19040. stopped (true),
  19041. sampleRate (44100.0),
  19042. sourceSampleRate (0.0),
  19043. blockSize (128),
  19044. readAheadBufferSize (0),
  19045. isPrepared (false),
  19046. inputStreamEOF (false)
  19047. {
  19048. }
  19049. AudioTransportSource::~AudioTransportSource()
  19050. {
  19051. setSource (0);
  19052. releaseResources();
  19053. }
  19054. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19055. int readAheadBufferSize_,
  19056. double sourceSampleRateToCorrectFor,
  19057. int maxNumChannels)
  19058. {
  19059. if (source == newSource)
  19060. {
  19061. if (source == 0)
  19062. return;
  19063. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19064. }
  19065. readAheadBufferSize = readAheadBufferSize_;
  19066. sourceSampleRate = sourceSampleRateToCorrectFor;
  19067. ResamplingAudioSource* newResamplerSource = 0;
  19068. BufferingAudioSource* newBufferingSource = 0;
  19069. PositionableAudioSource* newPositionableSource = 0;
  19070. AudioSource* newMasterSource = 0;
  19071. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19072. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19073. AudioSource* oldMasterSource = masterSource;
  19074. if (newSource != 0)
  19075. {
  19076. newPositionableSource = newSource;
  19077. if (readAheadBufferSize_ > 0)
  19078. newPositionableSource = newBufferingSource
  19079. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19080. newPositionableSource->setNextReadPosition (0);
  19081. if (sourceSampleRateToCorrectFor != 0)
  19082. newMasterSource = newResamplerSource
  19083. = new ResamplingAudioSource (newPositionableSource, false, maxNumChannels);
  19084. else
  19085. newMasterSource = newPositionableSource;
  19086. if (isPrepared)
  19087. {
  19088. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19089. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19090. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19091. }
  19092. }
  19093. {
  19094. const ScopedLock sl (callbackLock);
  19095. source = newSource;
  19096. resamplerSource = newResamplerSource;
  19097. bufferingSource = newBufferingSource;
  19098. masterSource = newMasterSource;
  19099. positionableSource = newPositionableSource;
  19100. playing = false;
  19101. }
  19102. if (oldMasterSource != 0)
  19103. oldMasterSource->releaseResources();
  19104. }
  19105. void AudioTransportSource::start()
  19106. {
  19107. if ((! playing) && masterSource != 0)
  19108. {
  19109. {
  19110. const ScopedLock sl (callbackLock);
  19111. playing = true;
  19112. stopped = false;
  19113. inputStreamEOF = false;
  19114. }
  19115. sendChangeMessage();
  19116. }
  19117. }
  19118. void AudioTransportSource::stop()
  19119. {
  19120. if (playing)
  19121. {
  19122. {
  19123. const ScopedLock sl (callbackLock);
  19124. playing = false;
  19125. }
  19126. int n = 500;
  19127. while (--n >= 0 && ! stopped)
  19128. Thread::sleep (2);
  19129. sendChangeMessage();
  19130. }
  19131. }
  19132. void AudioTransportSource::setPosition (double newPosition)
  19133. {
  19134. if (sampleRate > 0.0)
  19135. setNextReadPosition ((int64) (newPosition * sampleRate));
  19136. }
  19137. double AudioTransportSource::getCurrentPosition() const
  19138. {
  19139. if (sampleRate > 0.0)
  19140. return getNextReadPosition() / sampleRate;
  19141. else
  19142. return 0.0;
  19143. }
  19144. double AudioTransportSource::getLengthInSeconds() const
  19145. {
  19146. return getTotalLength() / sampleRate;
  19147. }
  19148. void AudioTransportSource::setNextReadPosition (int64 newPosition)
  19149. {
  19150. if (positionableSource != 0)
  19151. {
  19152. if (sampleRate > 0 && sourceSampleRate > 0)
  19153. newPosition = (int64) (newPosition * sourceSampleRate / sampleRate);
  19154. positionableSource->setNextReadPosition (newPosition);
  19155. }
  19156. }
  19157. int64 AudioTransportSource::getNextReadPosition() const
  19158. {
  19159. if (positionableSource != 0)
  19160. {
  19161. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19162. return (int64) (positionableSource->getNextReadPosition() * ratio);
  19163. }
  19164. return 0;
  19165. }
  19166. int64 AudioTransportSource::getTotalLength() const
  19167. {
  19168. const ScopedLock sl (callbackLock);
  19169. if (positionableSource != 0)
  19170. {
  19171. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19172. return (int64) (positionableSource->getTotalLength() * ratio);
  19173. }
  19174. return 0;
  19175. }
  19176. bool AudioTransportSource::isLooping() const
  19177. {
  19178. const ScopedLock sl (callbackLock);
  19179. return positionableSource != 0
  19180. && positionableSource->isLooping();
  19181. }
  19182. void AudioTransportSource::setGain (const float newGain) throw()
  19183. {
  19184. gain = newGain;
  19185. }
  19186. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19187. double sampleRate_)
  19188. {
  19189. const ScopedLock sl (callbackLock);
  19190. sampleRate = sampleRate_;
  19191. blockSize = samplesPerBlockExpected;
  19192. if (masterSource != 0)
  19193. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19194. if (resamplerSource != 0 && sourceSampleRate != 0)
  19195. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19196. isPrepared = true;
  19197. }
  19198. void AudioTransportSource::releaseResources()
  19199. {
  19200. const ScopedLock sl (callbackLock);
  19201. if (masterSource != 0)
  19202. masterSource->releaseResources();
  19203. isPrepared = false;
  19204. }
  19205. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19206. {
  19207. const ScopedLock sl (callbackLock);
  19208. inputStreamEOF = false;
  19209. if (masterSource != 0 && ! stopped)
  19210. {
  19211. masterSource->getNextAudioBlock (info);
  19212. if (! playing)
  19213. {
  19214. // just stopped playing, so fade out the last block..
  19215. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19216. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19217. if (info.numSamples > 256)
  19218. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19219. }
  19220. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19221. && ! positionableSource->isLooping())
  19222. {
  19223. playing = false;
  19224. inputStreamEOF = true;
  19225. sendChangeMessage();
  19226. }
  19227. stopped = ! playing;
  19228. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19229. {
  19230. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19231. lastGain, gain);
  19232. }
  19233. }
  19234. else
  19235. {
  19236. info.clearActiveBufferRegion();
  19237. stopped = true;
  19238. }
  19239. lastGain = gain;
  19240. }
  19241. END_JUCE_NAMESPACE
  19242. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19243. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19244. BEGIN_JUCE_NAMESPACE
  19245. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19246. public Thread,
  19247. private Timer
  19248. {
  19249. public:
  19250. SharedBufferingAudioSourceThread()
  19251. : Thread ("Audio Buffer")
  19252. {
  19253. }
  19254. ~SharedBufferingAudioSourceThread()
  19255. {
  19256. stopThread (10000);
  19257. clearSingletonInstance();
  19258. }
  19259. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19260. void addSource (BufferingAudioSource* source)
  19261. {
  19262. const ScopedLock sl (lock);
  19263. if (! sources.contains (source))
  19264. {
  19265. sources.add (source);
  19266. startThread();
  19267. stopTimer();
  19268. }
  19269. notify();
  19270. }
  19271. void removeSource (BufferingAudioSource* source)
  19272. {
  19273. const ScopedLock sl (lock);
  19274. sources.removeValue (source);
  19275. if (sources.size() == 0)
  19276. startTimer (5000);
  19277. }
  19278. private:
  19279. Array <BufferingAudioSource*> sources;
  19280. CriticalSection lock;
  19281. void run()
  19282. {
  19283. while (! threadShouldExit())
  19284. {
  19285. bool busy = false;
  19286. for (int i = sources.size(); --i >= 0;)
  19287. {
  19288. if (threadShouldExit())
  19289. return;
  19290. const ScopedLock sl (lock);
  19291. BufferingAudioSource* const b = sources[i];
  19292. if (b != 0 && b->readNextBufferChunk())
  19293. busy = true;
  19294. }
  19295. if (! busy)
  19296. wait (500);
  19297. }
  19298. }
  19299. void timerCallback()
  19300. {
  19301. stopTimer();
  19302. if (sources.size() == 0)
  19303. deleteInstance();
  19304. }
  19305. JUCE_DECLARE_NON_COPYABLE (SharedBufferingAudioSourceThread);
  19306. };
  19307. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19308. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19309. const bool deleteSourceWhenDeleted_,
  19310. int numberOfSamplesToBuffer_)
  19311. : source (source_),
  19312. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19313. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19314. buffer (2, 0),
  19315. bufferValidStart (0),
  19316. bufferValidEnd (0),
  19317. nextPlayPos (0),
  19318. wasSourceLooping (false)
  19319. {
  19320. jassert (source_ != 0);
  19321. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19322. // not using a larger buffer..
  19323. }
  19324. BufferingAudioSource::~BufferingAudioSource()
  19325. {
  19326. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19327. if (thread != 0)
  19328. thread->removeSource (this);
  19329. if (deleteSourceWhenDeleted)
  19330. delete source;
  19331. }
  19332. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19333. {
  19334. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19335. sampleRate = sampleRate_;
  19336. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19337. buffer.clear();
  19338. bufferValidStart = 0;
  19339. bufferValidEnd = 0;
  19340. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19341. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19342. buffer.getNumSamples() / 2))
  19343. {
  19344. SharedBufferingAudioSourceThread::getInstance()->notify();
  19345. Thread::sleep (5);
  19346. }
  19347. }
  19348. void BufferingAudioSource::releaseResources()
  19349. {
  19350. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19351. if (thread != 0)
  19352. thread->removeSource (this);
  19353. buffer.setSize (2, 0);
  19354. source->releaseResources();
  19355. }
  19356. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19357. {
  19358. const ScopedLock sl (bufferStartPosLock);
  19359. const int validStart = (int) (jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos);
  19360. const int validEnd = (int) (jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos);
  19361. if (validStart == validEnd)
  19362. {
  19363. // total cache miss
  19364. info.clearActiveBufferRegion();
  19365. }
  19366. else
  19367. {
  19368. if (validStart > 0)
  19369. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19370. if (validEnd < info.numSamples)
  19371. info.buffer->clear (info.startSample + validEnd,
  19372. info.numSamples - validEnd); // partial cache miss at end
  19373. if (validStart < validEnd)
  19374. {
  19375. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19376. {
  19377. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19378. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19379. if (startBufferIndex < endBufferIndex)
  19380. {
  19381. info.buffer->copyFrom (chan, info.startSample + validStart,
  19382. buffer,
  19383. chan, startBufferIndex,
  19384. validEnd - validStart);
  19385. }
  19386. else
  19387. {
  19388. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19389. info.buffer->copyFrom (chan, info.startSample + validStart,
  19390. buffer,
  19391. chan, startBufferIndex,
  19392. initialSize);
  19393. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19394. buffer,
  19395. chan, 0,
  19396. (validEnd - validStart) - initialSize);
  19397. }
  19398. }
  19399. }
  19400. nextPlayPos += info.numSamples;
  19401. if (source->isLooping() && nextPlayPos > 0)
  19402. nextPlayPos %= source->getTotalLength();
  19403. }
  19404. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19405. if (thread != 0)
  19406. thread->notify();
  19407. }
  19408. int64 BufferingAudioSource::getNextReadPosition() const
  19409. {
  19410. return (source->isLooping() && nextPlayPos > 0)
  19411. ? nextPlayPos % source->getTotalLength()
  19412. : nextPlayPos;
  19413. }
  19414. void BufferingAudioSource::setNextReadPosition (int64 newPosition)
  19415. {
  19416. const ScopedLock sl (bufferStartPosLock);
  19417. nextPlayPos = newPosition;
  19418. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19419. if (thread != 0)
  19420. thread->notify();
  19421. }
  19422. bool BufferingAudioSource::readNextBufferChunk()
  19423. {
  19424. int64 newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19425. {
  19426. const ScopedLock sl (bufferStartPosLock);
  19427. if (wasSourceLooping != isLooping())
  19428. {
  19429. wasSourceLooping = isLooping();
  19430. bufferValidStart = 0;
  19431. bufferValidEnd = 0;
  19432. }
  19433. newBVS = jmax ((int64) 0, nextPlayPos);
  19434. newBVE = newBVS + buffer.getNumSamples() - 4;
  19435. sectionToReadStart = 0;
  19436. sectionToReadEnd = 0;
  19437. const int maxChunkSize = 2048;
  19438. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19439. {
  19440. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19441. sectionToReadStart = newBVS;
  19442. sectionToReadEnd = newBVE;
  19443. bufferValidStart = 0;
  19444. bufferValidEnd = 0;
  19445. }
  19446. else if (std::abs ((int) (newBVS - bufferValidStart)) > 512
  19447. || std::abs ((int) (newBVE - bufferValidEnd)) > 512)
  19448. {
  19449. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19450. sectionToReadStart = bufferValidEnd;
  19451. sectionToReadEnd = newBVE;
  19452. bufferValidStart = newBVS;
  19453. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19454. }
  19455. }
  19456. if (sectionToReadStart != sectionToReadEnd)
  19457. {
  19458. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19459. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19460. if (bufferIndexStart < bufferIndexEnd)
  19461. {
  19462. readBufferSection (sectionToReadStart,
  19463. (int) (sectionToReadEnd - sectionToReadStart),
  19464. bufferIndexStart);
  19465. }
  19466. else
  19467. {
  19468. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19469. readBufferSection (sectionToReadStart,
  19470. initialSize,
  19471. bufferIndexStart);
  19472. readBufferSection (sectionToReadStart + initialSize,
  19473. (int) (sectionToReadEnd - sectionToReadStart) - initialSize,
  19474. 0);
  19475. }
  19476. const ScopedLock sl2 (bufferStartPosLock);
  19477. bufferValidStart = newBVS;
  19478. bufferValidEnd = newBVE;
  19479. return true;
  19480. }
  19481. else
  19482. {
  19483. return false;
  19484. }
  19485. }
  19486. void BufferingAudioSource::readBufferSection (const int64 start, const int length, const int bufferOffset)
  19487. {
  19488. if (source->getNextReadPosition() != start)
  19489. source->setNextReadPosition (start);
  19490. AudioSourceChannelInfo info;
  19491. info.buffer = &buffer;
  19492. info.startSample = bufferOffset;
  19493. info.numSamples = length;
  19494. source->getNextAudioBlock (info);
  19495. }
  19496. END_JUCE_NAMESPACE
  19497. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19498. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19499. BEGIN_JUCE_NAMESPACE
  19500. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19501. const bool deleteSourceWhenDeleted_)
  19502. : requiredNumberOfChannels (2),
  19503. source (source_),
  19504. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19505. buffer (2, 16)
  19506. {
  19507. remappedInfo.buffer = &buffer;
  19508. remappedInfo.startSample = 0;
  19509. }
  19510. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19511. {
  19512. if (deleteSourceWhenDeleted)
  19513. delete source;
  19514. }
  19515. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19516. {
  19517. const ScopedLock sl (lock);
  19518. requiredNumberOfChannels = requiredNumberOfChannels_;
  19519. }
  19520. void ChannelRemappingAudioSource::clearAllMappings()
  19521. {
  19522. const ScopedLock sl (lock);
  19523. remappedInputs.clear();
  19524. remappedOutputs.clear();
  19525. }
  19526. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19527. {
  19528. const ScopedLock sl (lock);
  19529. while (remappedInputs.size() < destIndex)
  19530. remappedInputs.add (-1);
  19531. remappedInputs.set (destIndex, sourceIndex);
  19532. }
  19533. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19534. {
  19535. const ScopedLock sl (lock);
  19536. while (remappedOutputs.size() < sourceIndex)
  19537. remappedOutputs.add (-1);
  19538. remappedOutputs.set (sourceIndex, destIndex);
  19539. }
  19540. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19541. {
  19542. const ScopedLock sl (lock);
  19543. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19544. return remappedInputs.getUnchecked (inputChannelIndex);
  19545. return -1;
  19546. }
  19547. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19548. {
  19549. const ScopedLock sl (lock);
  19550. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19551. return remappedOutputs .getUnchecked (outputChannelIndex);
  19552. return -1;
  19553. }
  19554. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19555. {
  19556. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19557. }
  19558. void ChannelRemappingAudioSource::releaseResources()
  19559. {
  19560. source->releaseResources();
  19561. }
  19562. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19563. {
  19564. const ScopedLock sl (lock);
  19565. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  19566. const int numChans = bufferToFill.buffer->getNumChannels();
  19567. int i;
  19568. for (i = 0; i < buffer.getNumChannels(); ++i)
  19569. {
  19570. const int remappedChan = getRemappedInputChannel (i);
  19571. if (remappedChan >= 0 && remappedChan < numChans)
  19572. {
  19573. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  19574. remappedChan,
  19575. bufferToFill.startSample,
  19576. bufferToFill.numSamples);
  19577. }
  19578. else
  19579. {
  19580. buffer.clear (i, 0, bufferToFill.numSamples);
  19581. }
  19582. }
  19583. remappedInfo.numSamples = bufferToFill.numSamples;
  19584. source->getNextAudioBlock (remappedInfo);
  19585. bufferToFill.clearActiveBufferRegion();
  19586. for (i = 0; i < requiredNumberOfChannels; ++i)
  19587. {
  19588. const int remappedChan = getRemappedOutputChannel (i);
  19589. if (remappedChan >= 0 && remappedChan < numChans)
  19590. {
  19591. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  19592. buffer, i, 0, bufferToFill.numSamples);
  19593. }
  19594. }
  19595. }
  19596. XmlElement* ChannelRemappingAudioSource::createXml() const
  19597. {
  19598. XmlElement* e = new XmlElement ("MAPPINGS");
  19599. String ins, outs;
  19600. int i;
  19601. const ScopedLock sl (lock);
  19602. for (i = 0; i < remappedInputs.size(); ++i)
  19603. ins << remappedInputs.getUnchecked(i) << ' ';
  19604. for (i = 0; i < remappedOutputs.size(); ++i)
  19605. outs << remappedOutputs.getUnchecked(i) << ' ';
  19606. e->setAttribute ("inputs", ins.trimEnd());
  19607. e->setAttribute ("outputs", outs.trimEnd());
  19608. return e;
  19609. }
  19610. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  19611. {
  19612. if (e.hasTagName ("MAPPINGS"))
  19613. {
  19614. const ScopedLock sl (lock);
  19615. clearAllMappings();
  19616. StringArray ins, outs;
  19617. ins.addTokens (e.getStringAttribute ("inputs"), false);
  19618. outs.addTokens (e.getStringAttribute ("outputs"), false);
  19619. int i;
  19620. for (i = 0; i < ins.size(); ++i)
  19621. remappedInputs.add (ins[i].getIntValue());
  19622. for (i = 0; i < outs.size(); ++i)
  19623. remappedOutputs.add (outs[i].getIntValue());
  19624. }
  19625. }
  19626. END_JUCE_NAMESPACE
  19627. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19628. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19629. BEGIN_JUCE_NAMESPACE
  19630. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  19631. const bool deleteInputWhenDeleted_)
  19632. : input (inputSource),
  19633. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  19634. {
  19635. jassert (inputSource != 0);
  19636. for (int i = 2; --i >= 0;)
  19637. iirFilters.add (new IIRFilter());
  19638. }
  19639. IIRFilterAudioSource::~IIRFilterAudioSource()
  19640. {
  19641. if (deleteInputWhenDeleted)
  19642. delete input;
  19643. }
  19644. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  19645. {
  19646. for (int i = iirFilters.size(); --i >= 0;)
  19647. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  19648. }
  19649. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19650. {
  19651. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19652. for (int i = iirFilters.size(); --i >= 0;)
  19653. iirFilters.getUnchecked(i)->reset();
  19654. }
  19655. void IIRFilterAudioSource::releaseResources()
  19656. {
  19657. input->releaseResources();
  19658. }
  19659. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19660. {
  19661. input->getNextAudioBlock (bufferToFill);
  19662. const int numChannels = bufferToFill.buffer->getNumChannels();
  19663. while (numChannels > iirFilters.size())
  19664. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19665. for (int i = 0; i < numChannels; ++i)
  19666. iirFilters.getUnchecked(i)
  19667. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19668. bufferToFill.numSamples);
  19669. }
  19670. END_JUCE_NAMESPACE
  19671. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19672. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19673. BEGIN_JUCE_NAMESPACE
  19674. MixerAudioSource::MixerAudioSource()
  19675. : tempBuffer (2, 0),
  19676. currentSampleRate (0.0),
  19677. bufferSizeExpected (0)
  19678. {
  19679. }
  19680. MixerAudioSource::~MixerAudioSource()
  19681. {
  19682. removeAllInputs();
  19683. }
  19684. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19685. {
  19686. if (input != 0 && ! inputs.contains (input))
  19687. {
  19688. double localRate;
  19689. int localBufferSize;
  19690. {
  19691. const ScopedLock sl (lock);
  19692. localRate = currentSampleRate;
  19693. localBufferSize = bufferSizeExpected;
  19694. }
  19695. if (localRate != 0.0)
  19696. input->prepareToPlay (localBufferSize, localRate);
  19697. const ScopedLock sl (lock);
  19698. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19699. inputs.add (input);
  19700. }
  19701. }
  19702. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19703. {
  19704. if (input != 0)
  19705. {
  19706. int index;
  19707. {
  19708. const ScopedLock sl (lock);
  19709. index = inputs.indexOf (input);
  19710. if (index >= 0)
  19711. {
  19712. inputsToDelete.shiftBits (index, 1);
  19713. inputs.remove (index);
  19714. }
  19715. }
  19716. if (index >= 0)
  19717. {
  19718. input->releaseResources();
  19719. if (deleteInput)
  19720. delete input;
  19721. }
  19722. }
  19723. }
  19724. void MixerAudioSource::removeAllInputs()
  19725. {
  19726. OwnedArray<AudioSource> toDelete;
  19727. {
  19728. const ScopedLock sl (lock);
  19729. for (int i = inputs.size(); --i >= 0;)
  19730. if (inputsToDelete[i])
  19731. toDelete.add (inputs.getUnchecked(i));
  19732. }
  19733. }
  19734. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19735. {
  19736. tempBuffer.setSize (2, samplesPerBlockExpected);
  19737. const ScopedLock sl (lock);
  19738. currentSampleRate = sampleRate;
  19739. bufferSizeExpected = samplesPerBlockExpected;
  19740. for (int i = inputs.size(); --i >= 0;)
  19741. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19742. }
  19743. void MixerAudioSource::releaseResources()
  19744. {
  19745. const ScopedLock sl (lock);
  19746. for (int i = inputs.size(); --i >= 0;)
  19747. inputs.getUnchecked(i)->releaseResources();
  19748. tempBuffer.setSize (2, 0);
  19749. currentSampleRate = 0;
  19750. bufferSizeExpected = 0;
  19751. }
  19752. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19753. {
  19754. const ScopedLock sl (lock);
  19755. if (inputs.size() > 0)
  19756. {
  19757. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19758. if (inputs.size() > 1)
  19759. {
  19760. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19761. info.buffer->getNumSamples());
  19762. AudioSourceChannelInfo info2;
  19763. info2.buffer = &tempBuffer;
  19764. info2.numSamples = info.numSamples;
  19765. info2.startSample = 0;
  19766. for (int i = 1; i < inputs.size(); ++i)
  19767. {
  19768. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19769. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19770. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19771. }
  19772. }
  19773. }
  19774. else
  19775. {
  19776. info.clearActiveBufferRegion();
  19777. }
  19778. }
  19779. END_JUCE_NAMESPACE
  19780. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19781. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19782. BEGIN_JUCE_NAMESPACE
  19783. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19784. const bool deleteInputWhenDeleted_,
  19785. const int numChannels_)
  19786. : input (inputSource),
  19787. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19788. ratio (1.0),
  19789. lastRatio (1.0),
  19790. buffer (numChannels_, 0),
  19791. sampsInBuffer (0),
  19792. numChannels (numChannels_)
  19793. {
  19794. jassert (input != 0);
  19795. }
  19796. ResamplingAudioSource::~ResamplingAudioSource()
  19797. {
  19798. if (deleteInputWhenDeleted)
  19799. delete input;
  19800. }
  19801. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19802. {
  19803. jassert (samplesInPerOutputSample > 0);
  19804. const ScopedLock sl (ratioLock);
  19805. ratio = jmax (0.0, samplesInPerOutputSample);
  19806. }
  19807. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19808. double sampleRate)
  19809. {
  19810. const ScopedLock sl (ratioLock);
  19811. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19812. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19813. buffer.clear();
  19814. sampsInBuffer = 0;
  19815. bufferPos = 0;
  19816. subSampleOffset = 0.0;
  19817. filterStates.calloc (numChannels);
  19818. srcBuffers.calloc (numChannels);
  19819. destBuffers.calloc (numChannels);
  19820. createLowPass (ratio);
  19821. resetFilters();
  19822. }
  19823. void ResamplingAudioSource::releaseResources()
  19824. {
  19825. input->releaseResources();
  19826. buffer.setSize (numChannels, 0);
  19827. }
  19828. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19829. {
  19830. double localRatio;
  19831. {
  19832. const ScopedLock sl (ratioLock);
  19833. localRatio = ratio;
  19834. }
  19835. if (lastRatio != localRatio)
  19836. {
  19837. createLowPass (localRatio);
  19838. lastRatio = localRatio;
  19839. }
  19840. const int sampsNeeded = roundToInt (info.numSamples * localRatio) + 2;
  19841. int bufferSize = buffer.getNumSamples();
  19842. if (bufferSize < sampsNeeded + 8)
  19843. {
  19844. bufferPos %= bufferSize;
  19845. bufferSize = sampsNeeded + 32;
  19846. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19847. }
  19848. bufferPos %= bufferSize;
  19849. int endOfBufferPos = bufferPos + sampsInBuffer;
  19850. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  19851. while (sampsNeeded > sampsInBuffer)
  19852. {
  19853. endOfBufferPos %= bufferSize;
  19854. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19855. bufferSize - endOfBufferPos);
  19856. AudioSourceChannelInfo readInfo;
  19857. readInfo.buffer = &buffer;
  19858. readInfo.numSamples = numToDo;
  19859. readInfo.startSample = endOfBufferPos;
  19860. input->getNextAudioBlock (readInfo);
  19861. if (localRatio > 1.0001)
  19862. {
  19863. // for down-sampling, pre-apply the filter..
  19864. for (int i = channelsToProcess; --i >= 0;)
  19865. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19866. }
  19867. sampsInBuffer += numToDo;
  19868. endOfBufferPos += numToDo;
  19869. }
  19870. for (int channel = 0; channel < channelsToProcess; ++channel)
  19871. {
  19872. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  19873. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  19874. }
  19875. int nextPos = (bufferPos + 1) % bufferSize;
  19876. for (int m = info.numSamples; --m >= 0;)
  19877. {
  19878. const float alpha = (float) subSampleOffset;
  19879. const float invAlpha = 1.0f - alpha;
  19880. for (int channel = 0; channel < channelsToProcess; ++channel)
  19881. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  19882. subSampleOffset += localRatio;
  19883. jassert (sampsInBuffer > 0);
  19884. while (subSampleOffset >= 1.0)
  19885. {
  19886. if (++bufferPos >= bufferSize)
  19887. bufferPos = 0;
  19888. --sampsInBuffer;
  19889. nextPos = (bufferPos + 1) % bufferSize;
  19890. subSampleOffset -= 1.0;
  19891. }
  19892. }
  19893. if (localRatio < 0.9999)
  19894. {
  19895. // for up-sampling, apply the filter after transposing..
  19896. for (int i = channelsToProcess; --i >= 0;)
  19897. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  19898. }
  19899. else if (localRatio <= 1.0001)
  19900. {
  19901. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  19902. for (int i = channelsToProcess; --i >= 0;)
  19903. {
  19904. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  19905. FilterState& fs = filterStates[i];
  19906. if (info.numSamples > 1)
  19907. {
  19908. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  19909. }
  19910. else
  19911. {
  19912. fs.y2 = fs.y1;
  19913. fs.x2 = fs.x1;
  19914. }
  19915. fs.y1 = fs.x1 = *endOfBuffer;
  19916. }
  19917. }
  19918. jassert (sampsInBuffer >= 0);
  19919. }
  19920. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  19921. {
  19922. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  19923. : 0.5 * frequencyRatio;
  19924. const double n = 1.0 / std::tan (double_Pi * jmax (0.001, proportionalRate));
  19925. const double nSquared = n * n;
  19926. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  19927. setFilterCoefficients (c1,
  19928. c1 * 2.0f,
  19929. c1,
  19930. 1.0,
  19931. c1 * 2.0 * (1.0 - nSquared),
  19932. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  19933. }
  19934. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  19935. {
  19936. const double a = 1.0 / c4;
  19937. c1 *= a;
  19938. c2 *= a;
  19939. c3 *= a;
  19940. c5 *= a;
  19941. c6 *= a;
  19942. coefficients[0] = c1;
  19943. coefficients[1] = c2;
  19944. coefficients[2] = c3;
  19945. coefficients[3] = c4;
  19946. coefficients[4] = c5;
  19947. coefficients[5] = c6;
  19948. }
  19949. void ResamplingAudioSource::resetFilters()
  19950. {
  19951. zeromem (filterStates, sizeof (FilterState) * numChannels);
  19952. }
  19953. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  19954. {
  19955. while (--num >= 0)
  19956. {
  19957. const double in = *samples;
  19958. double out = coefficients[0] * in
  19959. + coefficients[1] * fs.x1
  19960. + coefficients[2] * fs.x2
  19961. - coefficients[4] * fs.y1
  19962. - coefficients[5] * fs.y2;
  19963. #if JUCE_INTEL
  19964. if (! (out < -1.0e-8 || out > 1.0e-8))
  19965. out = 0;
  19966. #endif
  19967. fs.x2 = fs.x1;
  19968. fs.x1 = in;
  19969. fs.y2 = fs.y1;
  19970. fs.y1 = out;
  19971. *samples++ = (float) out;
  19972. }
  19973. }
  19974. END_JUCE_NAMESPACE
  19975. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  19976. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19977. BEGIN_JUCE_NAMESPACE
  19978. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  19979. : frequency (1000.0),
  19980. sampleRate (44100.0),
  19981. currentPhase (0.0),
  19982. phasePerSample (0.0),
  19983. amplitude (0.5f)
  19984. {
  19985. }
  19986. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  19987. {
  19988. }
  19989. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  19990. {
  19991. amplitude = newAmplitude;
  19992. }
  19993. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  19994. {
  19995. frequency = newFrequencyHz;
  19996. phasePerSample = 0.0;
  19997. }
  19998. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19999. double sampleRate_)
  20000. {
  20001. currentPhase = 0.0;
  20002. phasePerSample = 0.0;
  20003. sampleRate = sampleRate_;
  20004. }
  20005. void ToneGeneratorAudioSource::releaseResources()
  20006. {
  20007. }
  20008. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20009. {
  20010. if (phasePerSample == 0.0)
  20011. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20012. for (int i = 0; i < info.numSamples; ++i)
  20013. {
  20014. const float sample = amplitude * (float) std::sin (currentPhase);
  20015. currentPhase += phasePerSample;
  20016. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  20017. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  20018. }
  20019. }
  20020. END_JUCE_NAMESPACE
  20021. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20022. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20023. BEGIN_JUCE_NAMESPACE
  20024. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20025. : sampleRate (0),
  20026. bufferSize (0),
  20027. useDefaultInputChannels (true),
  20028. useDefaultOutputChannels (true)
  20029. {
  20030. }
  20031. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20032. {
  20033. return outputDeviceName == other.outputDeviceName
  20034. && inputDeviceName == other.inputDeviceName
  20035. && sampleRate == other.sampleRate
  20036. && bufferSize == other.bufferSize
  20037. && inputChannels == other.inputChannels
  20038. && useDefaultInputChannels == other.useDefaultInputChannels
  20039. && outputChannels == other.outputChannels
  20040. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20041. }
  20042. AudioDeviceManager::AudioDeviceManager()
  20043. : currentAudioDevice (0),
  20044. numInputChansNeeded (0),
  20045. numOutputChansNeeded (2),
  20046. listNeedsScanning (true),
  20047. useInputNames (false),
  20048. inputLevelMeasurementEnabledCount (0),
  20049. inputLevel (0),
  20050. tempBuffer (2, 2),
  20051. defaultMidiOutput (0),
  20052. cpuUsageMs (0),
  20053. timeToCpuScale (0)
  20054. {
  20055. callbackHandler.owner = this;
  20056. }
  20057. AudioDeviceManager::~AudioDeviceManager()
  20058. {
  20059. currentAudioDevice = 0;
  20060. defaultMidiOutput = 0;
  20061. }
  20062. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20063. {
  20064. if (availableDeviceTypes.size() == 0)
  20065. {
  20066. createAudioDeviceTypes (availableDeviceTypes);
  20067. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20068. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20069. if (availableDeviceTypes.size() > 0)
  20070. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20071. }
  20072. }
  20073. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20074. {
  20075. scanDevicesIfNeeded();
  20076. return availableDeviceTypes;
  20077. }
  20078. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  20079. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  20080. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  20081. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  20082. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  20083. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  20084. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20085. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20086. {
  20087. (void) list; // (to avoid 'unused param' warnings)
  20088. #if JUCE_WINDOWS
  20089. #if JUCE_WASAPI
  20090. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  20091. list.add (juce_createAudioIODeviceType_WASAPI());
  20092. #endif
  20093. #if JUCE_DIRECTSOUND
  20094. list.add (juce_createAudioIODeviceType_DirectSound());
  20095. #endif
  20096. #if JUCE_ASIO
  20097. list.add (juce_createAudioIODeviceType_ASIO());
  20098. #endif
  20099. #endif
  20100. #if JUCE_MAC
  20101. list.add (juce_createAudioIODeviceType_CoreAudio());
  20102. #endif
  20103. #if JUCE_IOS
  20104. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  20105. #endif
  20106. #if JUCE_LINUX && JUCE_ALSA
  20107. list.add (juce_createAudioIODeviceType_ALSA());
  20108. #endif
  20109. #if JUCE_LINUX && JUCE_JACK
  20110. list.add (juce_createAudioIODeviceType_JACK());
  20111. #endif
  20112. }
  20113. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20114. const int numOutputChannelsNeeded,
  20115. const XmlElement* const e,
  20116. const bool selectDefaultDeviceOnFailure,
  20117. const String& preferredDefaultDeviceName,
  20118. const AudioDeviceSetup* preferredSetupOptions)
  20119. {
  20120. scanDevicesIfNeeded();
  20121. numInputChansNeeded = numInputChannelsNeeded;
  20122. numOutputChansNeeded = numOutputChannelsNeeded;
  20123. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20124. {
  20125. lastExplicitSettings = new XmlElement (*e);
  20126. String error;
  20127. AudioDeviceSetup setup;
  20128. if (preferredSetupOptions != 0)
  20129. setup = *preferredSetupOptions;
  20130. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20131. {
  20132. setup.inputDeviceName = setup.outputDeviceName
  20133. = e->getStringAttribute ("audioDeviceName");
  20134. }
  20135. else
  20136. {
  20137. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20138. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20139. }
  20140. currentDeviceType = e->getStringAttribute ("deviceType");
  20141. if (currentDeviceType.isEmpty())
  20142. {
  20143. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20144. if (type != 0)
  20145. currentDeviceType = type->getTypeName();
  20146. else if (availableDeviceTypes.size() > 0)
  20147. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20148. }
  20149. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20150. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20151. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20152. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20153. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20154. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20155. error = setAudioDeviceSetup (setup, true);
  20156. midiInsFromXml.clear();
  20157. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20158. midiInsFromXml.add (c->getStringAttribute ("name"));
  20159. const StringArray allMidiIns (MidiInput::getDevices());
  20160. for (int i = allMidiIns.size(); --i >= 0;)
  20161. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20162. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20163. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20164. false, preferredDefaultDeviceName);
  20165. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20166. return error;
  20167. }
  20168. else
  20169. {
  20170. AudioDeviceSetup setup;
  20171. if (preferredSetupOptions != 0)
  20172. {
  20173. setup = *preferredSetupOptions;
  20174. }
  20175. else if (preferredDefaultDeviceName.isNotEmpty())
  20176. {
  20177. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20178. {
  20179. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20180. StringArray outs (type->getDeviceNames (false));
  20181. int i;
  20182. for (i = 0; i < outs.size(); ++i)
  20183. {
  20184. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20185. {
  20186. setup.outputDeviceName = outs[i];
  20187. break;
  20188. }
  20189. }
  20190. StringArray ins (type->getDeviceNames (true));
  20191. for (i = 0; i < ins.size(); ++i)
  20192. {
  20193. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20194. {
  20195. setup.inputDeviceName = ins[i];
  20196. break;
  20197. }
  20198. }
  20199. }
  20200. }
  20201. insertDefaultDeviceNames (setup);
  20202. return setAudioDeviceSetup (setup, false);
  20203. }
  20204. }
  20205. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20206. {
  20207. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20208. if (type != 0)
  20209. {
  20210. if (setup.outputDeviceName.isEmpty())
  20211. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20212. if (setup.inputDeviceName.isEmpty())
  20213. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20214. }
  20215. }
  20216. XmlElement* AudioDeviceManager::createStateXml() const
  20217. {
  20218. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20219. }
  20220. void AudioDeviceManager::scanDevicesIfNeeded()
  20221. {
  20222. if (listNeedsScanning)
  20223. {
  20224. listNeedsScanning = false;
  20225. createDeviceTypesIfNeeded();
  20226. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20227. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20228. }
  20229. }
  20230. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20231. {
  20232. scanDevicesIfNeeded();
  20233. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20234. {
  20235. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20236. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20237. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20238. {
  20239. return type;
  20240. }
  20241. }
  20242. return 0;
  20243. }
  20244. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20245. {
  20246. setup = currentSetup;
  20247. }
  20248. void AudioDeviceManager::deleteCurrentDevice()
  20249. {
  20250. currentAudioDevice = 0;
  20251. currentSetup.inputDeviceName = String::empty;
  20252. currentSetup.outputDeviceName = String::empty;
  20253. }
  20254. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20255. const bool treatAsChosenDevice)
  20256. {
  20257. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20258. {
  20259. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20260. && currentDeviceType != type)
  20261. {
  20262. currentDeviceType = type;
  20263. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20264. insertDefaultDeviceNames (s);
  20265. setAudioDeviceSetup (s, treatAsChosenDevice);
  20266. sendChangeMessage();
  20267. break;
  20268. }
  20269. }
  20270. }
  20271. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20272. {
  20273. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20274. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20275. return availableDeviceTypes[i];
  20276. return availableDeviceTypes[0];
  20277. }
  20278. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20279. const bool treatAsChosenDevice)
  20280. {
  20281. jassert (&newSetup != &currentSetup); // this will have no effect
  20282. if (newSetup == currentSetup && currentAudioDevice != 0)
  20283. return String::empty;
  20284. if (! (newSetup == currentSetup))
  20285. sendChangeMessage();
  20286. stopDevice();
  20287. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20288. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20289. String error;
  20290. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20291. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20292. {
  20293. deleteCurrentDevice();
  20294. if (treatAsChosenDevice)
  20295. updateXml();
  20296. return String::empty;
  20297. }
  20298. if (currentSetup.inputDeviceName != newInputDeviceName
  20299. || currentSetup.outputDeviceName != newOutputDeviceName
  20300. || currentAudioDevice == 0)
  20301. {
  20302. deleteCurrentDevice();
  20303. scanDevicesIfNeeded();
  20304. if (newOutputDeviceName.isNotEmpty()
  20305. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20306. {
  20307. return "No such device: " + newOutputDeviceName;
  20308. }
  20309. if (newInputDeviceName.isNotEmpty()
  20310. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20311. {
  20312. return "No such device: " + newInputDeviceName;
  20313. }
  20314. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20315. if (currentAudioDevice == 0)
  20316. 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!";
  20317. else
  20318. error = currentAudioDevice->getLastError();
  20319. if (error.isNotEmpty())
  20320. {
  20321. deleteCurrentDevice();
  20322. return error;
  20323. }
  20324. if (newSetup.useDefaultInputChannels)
  20325. {
  20326. inputChannels.clear();
  20327. inputChannels.setRange (0, numInputChansNeeded, true);
  20328. }
  20329. if (newSetup.useDefaultOutputChannels)
  20330. {
  20331. outputChannels.clear();
  20332. outputChannels.setRange (0, numOutputChansNeeded, true);
  20333. }
  20334. if (newInputDeviceName.isEmpty())
  20335. inputChannels.clear();
  20336. if (newOutputDeviceName.isEmpty())
  20337. outputChannels.clear();
  20338. }
  20339. if (! newSetup.useDefaultInputChannels)
  20340. inputChannels = newSetup.inputChannels;
  20341. if (! newSetup.useDefaultOutputChannels)
  20342. outputChannels = newSetup.outputChannels;
  20343. currentSetup = newSetup;
  20344. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20345. currentSetup.bufferSize = chooseBestBufferSize (newSetup.bufferSize);
  20346. error = currentAudioDevice->open (inputChannels,
  20347. outputChannels,
  20348. currentSetup.sampleRate,
  20349. currentSetup.bufferSize);
  20350. if (error.isEmpty())
  20351. {
  20352. currentDeviceType = currentAudioDevice->getTypeName();
  20353. currentAudioDevice->start (&callbackHandler);
  20354. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20355. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20356. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20357. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20358. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20359. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20360. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20361. if (treatAsChosenDevice)
  20362. updateXml();
  20363. }
  20364. else
  20365. {
  20366. deleteCurrentDevice();
  20367. }
  20368. return error;
  20369. }
  20370. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20371. {
  20372. jassert (currentAudioDevice != 0);
  20373. if (rate > 0)
  20374. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20375. if (currentAudioDevice->getSampleRate (i) == rate)
  20376. return rate;
  20377. double lowestAbove44 = 0.0;
  20378. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20379. {
  20380. const double sr = currentAudioDevice->getSampleRate (i);
  20381. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  20382. lowestAbove44 = sr;
  20383. }
  20384. if (lowestAbove44 > 0.0)
  20385. return lowestAbove44;
  20386. return currentAudioDevice->getSampleRate (0);
  20387. }
  20388. int AudioDeviceManager::chooseBestBufferSize (int bufferSize) const
  20389. {
  20390. jassert (currentAudioDevice != 0);
  20391. if (bufferSize > 0)
  20392. for (int i = currentAudioDevice->getNumBufferSizesAvailable(); --i >= 0;)
  20393. if (currentAudioDevice->getBufferSizeSamples(i) == bufferSize)
  20394. return bufferSize;
  20395. return currentAudioDevice->getDefaultBufferSize();
  20396. }
  20397. void AudioDeviceManager::stopDevice()
  20398. {
  20399. if (currentAudioDevice != 0)
  20400. currentAudioDevice->stop();
  20401. testSound = 0;
  20402. }
  20403. void AudioDeviceManager::closeAudioDevice()
  20404. {
  20405. stopDevice();
  20406. currentAudioDevice = 0;
  20407. }
  20408. void AudioDeviceManager::restartLastAudioDevice()
  20409. {
  20410. if (currentAudioDevice == 0)
  20411. {
  20412. if (currentSetup.inputDeviceName.isEmpty()
  20413. && currentSetup.outputDeviceName.isEmpty())
  20414. {
  20415. // This method will only reload the last device that was running
  20416. // before closeAudioDevice() was called - you need to actually open
  20417. // one first, with setAudioDevice().
  20418. jassertfalse;
  20419. return;
  20420. }
  20421. AudioDeviceSetup s (currentSetup);
  20422. setAudioDeviceSetup (s, false);
  20423. }
  20424. }
  20425. void AudioDeviceManager::updateXml()
  20426. {
  20427. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20428. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20429. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20430. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20431. if (currentAudioDevice != 0)
  20432. {
  20433. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20434. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20435. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20436. if (! currentSetup.useDefaultInputChannels)
  20437. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20438. if (! currentSetup.useDefaultOutputChannels)
  20439. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20440. }
  20441. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20442. {
  20443. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20444. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20445. }
  20446. if (midiInsFromXml.size() > 0)
  20447. {
  20448. // Add any midi devices that have been enabled before, but which aren't currently
  20449. // open because the device has been disconnected.
  20450. const StringArray availableMidiDevices (MidiInput::getDevices());
  20451. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20452. {
  20453. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20454. {
  20455. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20456. m->setAttribute ("name", midiInsFromXml[i]);
  20457. }
  20458. }
  20459. }
  20460. if (defaultMidiOutputName.isNotEmpty())
  20461. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20462. }
  20463. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20464. {
  20465. {
  20466. const ScopedLock sl (audioCallbackLock);
  20467. if (callbacks.contains (newCallback))
  20468. return;
  20469. }
  20470. if (currentAudioDevice != 0 && newCallback != 0)
  20471. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20472. const ScopedLock sl (audioCallbackLock);
  20473. callbacks.add (newCallback);
  20474. }
  20475. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callbackToRemove)
  20476. {
  20477. if (callbackToRemove != 0)
  20478. {
  20479. bool needsDeinitialising = currentAudioDevice != 0;
  20480. {
  20481. const ScopedLock sl (audioCallbackLock);
  20482. needsDeinitialising = needsDeinitialising && callbacks.contains (callbackToRemove);
  20483. callbacks.removeValue (callbackToRemove);
  20484. }
  20485. if (needsDeinitialising)
  20486. callbackToRemove->audioDeviceStopped();
  20487. }
  20488. }
  20489. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20490. int numInputChannels,
  20491. float** outputChannelData,
  20492. int numOutputChannels,
  20493. int numSamples)
  20494. {
  20495. const ScopedLock sl (audioCallbackLock);
  20496. if (inputLevelMeasurementEnabledCount > 0)
  20497. {
  20498. for (int j = 0; j < numSamples; ++j)
  20499. {
  20500. float s = 0;
  20501. for (int i = 0; i < numInputChannels; ++i)
  20502. s += std::abs (inputChannelData[i][j]);
  20503. s /= numInputChannels;
  20504. const double decayFactor = 0.99992;
  20505. if (s > inputLevel)
  20506. inputLevel = s;
  20507. else if (inputLevel > 0.001f)
  20508. inputLevel *= decayFactor;
  20509. else
  20510. inputLevel = 0;
  20511. }
  20512. }
  20513. if (callbacks.size() > 0)
  20514. {
  20515. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20516. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20517. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20518. outputChannelData, numOutputChannels, numSamples);
  20519. float** const tempChans = tempBuffer.getArrayOfChannels();
  20520. for (int i = callbacks.size(); --i > 0;)
  20521. {
  20522. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20523. tempChans, numOutputChannels, numSamples);
  20524. for (int chan = 0; chan < numOutputChannels; ++chan)
  20525. {
  20526. const float* const src = tempChans [chan];
  20527. float* const dst = outputChannelData [chan];
  20528. if (src != 0 && dst != 0)
  20529. for (int j = 0; j < numSamples; ++j)
  20530. dst[j] += src[j];
  20531. }
  20532. }
  20533. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20534. const double filterAmount = 0.2;
  20535. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20536. }
  20537. else
  20538. {
  20539. for (int i = 0; i < numOutputChannels; ++i)
  20540. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20541. }
  20542. if (testSound != 0)
  20543. {
  20544. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20545. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20546. for (int i = 0; i < numOutputChannels; ++i)
  20547. for (int j = 0; j < numSamps; ++j)
  20548. outputChannelData [i][j] += src[j];
  20549. testSoundPosition += numSamps;
  20550. if (testSoundPosition >= testSound->getNumSamples())
  20551. testSound = 0;
  20552. }
  20553. }
  20554. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20555. {
  20556. cpuUsageMs = 0;
  20557. const double sampleRate = device->getCurrentSampleRate();
  20558. const int blockSize = device->getCurrentBufferSizeSamples();
  20559. if (sampleRate > 0.0 && blockSize > 0)
  20560. {
  20561. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20562. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20563. }
  20564. {
  20565. const ScopedLock sl (audioCallbackLock);
  20566. for (int i = callbacks.size(); --i >= 0;)
  20567. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  20568. }
  20569. sendChangeMessage();
  20570. }
  20571. void AudioDeviceManager::audioDeviceStoppedInt()
  20572. {
  20573. cpuUsageMs = 0;
  20574. timeToCpuScale = 0;
  20575. sendChangeMessage();
  20576. const ScopedLock sl (audioCallbackLock);
  20577. for (int i = callbacks.size(); --i >= 0;)
  20578. callbacks.getUnchecked(i)->audioDeviceStopped();
  20579. }
  20580. double AudioDeviceManager::getCpuUsage() const
  20581. {
  20582. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  20583. }
  20584. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  20585. const bool enabled)
  20586. {
  20587. if (enabled != isMidiInputEnabled (name))
  20588. {
  20589. if (enabled)
  20590. {
  20591. const int index = MidiInput::getDevices().indexOf (name);
  20592. if (index >= 0)
  20593. {
  20594. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  20595. if (min != 0)
  20596. {
  20597. enabledMidiInputs.add (min);
  20598. min->start();
  20599. }
  20600. }
  20601. }
  20602. else
  20603. {
  20604. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20605. if (enabledMidiInputs[i]->getName() == name)
  20606. enabledMidiInputs.remove (i);
  20607. }
  20608. updateXml();
  20609. sendChangeMessage();
  20610. }
  20611. }
  20612. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  20613. {
  20614. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20615. if (enabledMidiInputs[i]->getName() == name)
  20616. return true;
  20617. return false;
  20618. }
  20619. void AudioDeviceManager::addMidiInputCallback (const String& name,
  20620. MidiInputCallback* callbackToAdd)
  20621. {
  20622. removeMidiInputCallback (name, callbackToAdd);
  20623. if (name.isEmpty() || isMidiInputEnabled (name))
  20624. {
  20625. const ScopedLock sl (midiCallbackLock);
  20626. midiCallbacks.add (callbackToAdd);
  20627. midiCallbackDevices.add (name);
  20628. }
  20629. }
  20630. void AudioDeviceManager::removeMidiInputCallback (const String& name, MidiInputCallback* callback)
  20631. {
  20632. for (int i = midiCallbacks.size(); --i >= 0;)
  20633. {
  20634. if (midiCallbackDevices[i] == name && midiCallbacks.getUnchecked(i) == callback)
  20635. {
  20636. const ScopedLock sl (midiCallbackLock);
  20637. midiCallbacks.remove (i);
  20638. midiCallbackDevices.remove (i);
  20639. }
  20640. }
  20641. }
  20642. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20643. const MidiMessage& message)
  20644. {
  20645. if (! message.isActiveSense())
  20646. {
  20647. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20648. const ScopedLock sl (midiCallbackLock);
  20649. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20650. {
  20651. const String name (midiCallbackDevices[i]);
  20652. if ((isDefaultSource && name.isEmpty()) || (name.isNotEmpty() && name == source->getName()))
  20653. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20654. }
  20655. }
  20656. }
  20657. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20658. {
  20659. if (defaultMidiOutputName != deviceName)
  20660. {
  20661. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20662. {
  20663. const ScopedLock sl (audioCallbackLock);
  20664. oldCallbacks = callbacks;
  20665. callbacks.clear();
  20666. }
  20667. if (currentAudioDevice != 0)
  20668. for (int i = oldCallbacks.size(); --i >= 0;)
  20669. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20670. defaultMidiOutput = 0;
  20671. defaultMidiOutputName = deviceName;
  20672. if (deviceName.isNotEmpty())
  20673. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20674. if (currentAudioDevice != 0)
  20675. for (int i = oldCallbacks.size(); --i >= 0;)
  20676. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20677. {
  20678. const ScopedLock sl (audioCallbackLock);
  20679. callbacks = oldCallbacks;
  20680. }
  20681. updateXml();
  20682. sendChangeMessage();
  20683. }
  20684. }
  20685. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20686. int numInputChannels,
  20687. float** outputChannelData,
  20688. int numOutputChannels,
  20689. int numSamples)
  20690. {
  20691. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20692. }
  20693. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20694. {
  20695. owner->audioDeviceAboutToStartInt (device);
  20696. }
  20697. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20698. {
  20699. owner->audioDeviceStoppedInt();
  20700. }
  20701. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20702. {
  20703. owner->handleIncomingMidiMessageInt (source, message);
  20704. }
  20705. void AudioDeviceManager::playTestSound()
  20706. {
  20707. { // cunningly nested to swap, unlock and delete in that order.
  20708. ScopedPointer <AudioSampleBuffer> oldSound;
  20709. {
  20710. const ScopedLock sl (audioCallbackLock);
  20711. oldSound = testSound;
  20712. }
  20713. }
  20714. testSoundPosition = 0;
  20715. if (currentAudioDevice != 0)
  20716. {
  20717. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20718. const int soundLength = (int) sampleRate;
  20719. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20720. float* samples = newSound->getSampleData (0);
  20721. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20722. const float amplitude = 0.5f;
  20723. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20724. for (int i = 0; i < soundLength; ++i)
  20725. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20726. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20727. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20728. const ScopedLock sl (audioCallbackLock);
  20729. testSound = newSound;
  20730. }
  20731. }
  20732. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20733. {
  20734. const ScopedLock sl (audioCallbackLock);
  20735. if (enableMeasurement)
  20736. ++inputLevelMeasurementEnabledCount;
  20737. else
  20738. --inputLevelMeasurementEnabledCount;
  20739. inputLevel = 0;
  20740. }
  20741. double AudioDeviceManager::getCurrentInputLevel() const
  20742. {
  20743. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20744. return inputLevel;
  20745. }
  20746. END_JUCE_NAMESPACE
  20747. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20748. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20749. BEGIN_JUCE_NAMESPACE
  20750. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20751. : name (deviceName),
  20752. typeName (typeName_)
  20753. {
  20754. }
  20755. AudioIODevice::~AudioIODevice()
  20756. {
  20757. }
  20758. bool AudioIODevice::hasControlPanel() const
  20759. {
  20760. return false;
  20761. }
  20762. bool AudioIODevice::showControlPanel()
  20763. {
  20764. jassertfalse; // this should only be called for devices which return true from
  20765. // their hasControlPanel() method.
  20766. return false;
  20767. }
  20768. END_JUCE_NAMESPACE
  20769. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20770. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20771. BEGIN_JUCE_NAMESPACE
  20772. AudioIODeviceType::AudioIODeviceType (const String& name)
  20773. : typeName (name)
  20774. {
  20775. }
  20776. AudioIODeviceType::~AudioIODeviceType()
  20777. {
  20778. }
  20779. END_JUCE_NAMESPACE
  20780. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20781. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20782. BEGIN_JUCE_NAMESPACE
  20783. MidiOutput::MidiOutput()
  20784. : Thread ("midi out"),
  20785. internal (0),
  20786. firstMessage (0)
  20787. {
  20788. }
  20789. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20790. const double sampleNumber)
  20791. : message (data, len, sampleNumber)
  20792. {
  20793. }
  20794. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20795. const double millisecondCounterToStartAt,
  20796. double samplesPerSecondForBuffer)
  20797. {
  20798. // You've got to call startBackgroundThread() for this to actually work..
  20799. jassert (isThreadRunning());
  20800. // this needs to be a value in the future - RTFM for this method!
  20801. jassert (millisecondCounterToStartAt > 0);
  20802. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20803. MidiBuffer::Iterator i (buffer);
  20804. const uint8* data;
  20805. int len, time;
  20806. while (i.getNextEvent (data, len, time))
  20807. {
  20808. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20809. PendingMessage* const m
  20810. = new PendingMessage (data, len, eventTime);
  20811. const ScopedLock sl (lock);
  20812. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20813. {
  20814. m->next = firstMessage;
  20815. firstMessage = m;
  20816. }
  20817. else
  20818. {
  20819. PendingMessage* mm = firstMessage;
  20820. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20821. mm = mm->next;
  20822. m->next = mm->next;
  20823. mm->next = m;
  20824. }
  20825. }
  20826. notify();
  20827. }
  20828. void MidiOutput::clearAllPendingMessages()
  20829. {
  20830. const ScopedLock sl (lock);
  20831. while (firstMessage != 0)
  20832. {
  20833. PendingMessage* const m = firstMessage;
  20834. firstMessage = firstMessage->next;
  20835. delete m;
  20836. }
  20837. }
  20838. void MidiOutput::startBackgroundThread()
  20839. {
  20840. startThread (9);
  20841. }
  20842. void MidiOutput::stopBackgroundThread()
  20843. {
  20844. stopThread (5000);
  20845. }
  20846. void MidiOutput::run()
  20847. {
  20848. while (! threadShouldExit())
  20849. {
  20850. uint32 now = Time::getMillisecondCounter();
  20851. uint32 eventTime = 0;
  20852. uint32 timeToWait = 500;
  20853. PendingMessage* message;
  20854. {
  20855. const ScopedLock sl (lock);
  20856. message = firstMessage;
  20857. if (message != 0)
  20858. {
  20859. eventTime = roundToInt (message->message.getTimeStamp());
  20860. if (eventTime > now + 20)
  20861. {
  20862. timeToWait = eventTime - (now + 20);
  20863. message = 0;
  20864. }
  20865. else
  20866. {
  20867. firstMessage = message->next;
  20868. }
  20869. }
  20870. }
  20871. if (message != 0)
  20872. {
  20873. if (eventTime > now)
  20874. {
  20875. Time::waitForMillisecondCounter (eventTime);
  20876. if (threadShouldExit())
  20877. break;
  20878. }
  20879. if (eventTime > now - 200)
  20880. sendMessageNow (message->message);
  20881. delete message;
  20882. }
  20883. else
  20884. {
  20885. jassert (timeToWait < 1000 * 30);
  20886. wait (timeToWait);
  20887. }
  20888. }
  20889. clearAllPendingMessages();
  20890. }
  20891. END_JUCE_NAMESPACE
  20892. /*** End of inlined file: juce_MidiOutput.cpp ***/
  20893. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  20894. BEGIN_JUCE_NAMESPACE
  20895. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20896. {
  20897. const double maxVal = (double) 0x7fff;
  20898. char* intData = static_cast <char*> (dest);
  20899. if (dest != (void*) source || destBytesPerSample <= 4)
  20900. {
  20901. for (int i = 0; i < numSamples; ++i)
  20902. {
  20903. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20904. intData += destBytesPerSample;
  20905. }
  20906. }
  20907. else
  20908. {
  20909. intData += destBytesPerSample * numSamples;
  20910. for (int i = numSamples; --i >= 0;)
  20911. {
  20912. intData -= destBytesPerSample;
  20913. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20914. }
  20915. }
  20916. }
  20917. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20918. {
  20919. const double maxVal = (double) 0x7fff;
  20920. char* intData = static_cast <char*> (dest);
  20921. if (dest != (void*) source || destBytesPerSample <= 4)
  20922. {
  20923. for (int i = 0; i < numSamples; ++i)
  20924. {
  20925. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20926. intData += destBytesPerSample;
  20927. }
  20928. }
  20929. else
  20930. {
  20931. intData += destBytesPerSample * numSamples;
  20932. for (int i = numSamples; --i >= 0;)
  20933. {
  20934. intData -= destBytesPerSample;
  20935. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20936. }
  20937. }
  20938. }
  20939. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20940. {
  20941. const double maxVal = (double) 0x7fffff;
  20942. char* intData = static_cast <char*> (dest);
  20943. if (dest != (void*) source || destBytesPerSample <= 4)
  20944. {
  20945. for (int i = 0; i < numSamples; ++i)
  20946. {
  20947. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20948. intData += destBytesPerSample;
  20949. }
  20950. }
  20951. else
  20952. {
  20953. intData += destBytesPerSample * numSamples;
  20954. for (int i = numSamples; --i >= 0;)
  20955. {
  20956. intData -= destBytesPerSample;
  20957. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20958. }
  20959. }
  20960. }
  20961. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20962. {
  20963. const double maxVal = (double) 0x7fffff;
  20964. char* intData = static_cast <char*> (dest);
  20965. if (dest != (void*) source || destBytesPerSample <= 4)
  20966. {
  20967. for (int i = 0; i < numSamples; ++i)
  20968. {
  20969. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20970. intData += destBytesPerSample;
  20971. }
  20972. }
  20973. else
  20974. {
  20975. intData += destBytesPerSample * numSamples;
  20976. for (int i = numSamples; --i >= 0;)
  20977. {
  20978. intData -= destBytesPerSample;
  20979. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20980. }
  20981. }
  20982. }
  20983. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20984. {
  20985. const double maxVal = (double) 0x7fffffff;
  20986. char* intData = static_cast <char*> (dest);
  20987. if (dest != (void*) source || destBytesPerSample <= 4)
  20988. {
  20989. for (int i = 0; i < numSamples; ++i)
  20990. {
  20991. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20992. intData += destBytesPerSample;
  20993. }
  20994. }
  20995. else
  20996. {
  20997. intData += destBytesPerSample * numSamples;
  20998. for (int i = numSamples; --i >= 0;)
  20999. {
  21000. intData -= destBytesPerSample;
  21001. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21002. }
  21003. }
  21004. }
  21005. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21006. {
  21007. const double maxVal = (double) 0x7fffffff;
  21008. char* intData = static_cast <char*> (dest);
  21009. if (dest != (void*) source || destBytesPerSample <= 4)
  21010. {
  21011. for (int i = 0; i < numSamples; ++i)
  21012. {
  21013. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21014. intData += destBytesPerSample;
  21015. }
  21016. }
  21017. else
  21018. {
  21019. intData += destBytesPerSample * numSamples;
  21020. for (int i = numSamples; --i >= 0;)
  21021. {
  21022. intData -= destBytesPerSample;
  21023. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21024. }
  21025. }
  21026. }
  21027. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21028. {
  21029. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21030. char* d = static_cast <char*> (dest);
  21031. for (int i = 0; i < numSamples; ++i)
  21032. {
  21033. *(float*) d = source[i];
  21034. #if JUCE_BIG_ENDIAN
  21035. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21036. #endif
  21037. d += destBytesPerSample;
  21038. }
  21039. }
  21040. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21041. {
  21042. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21043. char* d = static_cast <char*> (dest);
  21044. for (int i = 0; i < numSamples; ++i)
  21045. {
  21046. *(float*) d = source[i];
  21047. #if JUCE_LITTLE_ENDIAN
  21048. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21049. #endif
  21050. d += destBytesPerSample;
  21051. }
  21052. }
  21053. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21054. {
  21055. const float scale = 1.0f / 0x7fff;
  21056. const char* intData = static_cast <const char*> (source);
  21057. if (source != (void*) dest || srcBytesPerSample >= 4)
  21058. {
  21059. for (int i = 0; i < numSamples; ++i)
  21060. {
  21061. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21062. intData += srcBytesPerSample;
  21063. }
  21064. }
  21065. else
  21066. {
  21067. intData += srcBytesPerSample * numSamples;
  21068. for (int i = numSamples; --i >= 0;)
  21069. {
  21070. intData -= srcBytesPerSample;
  21071. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21072. }
  21073. }
  21074. }
  21075. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21076. {
  21077. const float scale = 1.0f / 0x7fff;
  21078. const char* intData = static_cast <const char*> (source);
  21079. if (source != (void*) dest || srcBytesPerSample >= 4)
  21080. {
  21081. for (int i = 0; i < numSamples; ++i)
  21082. {
  21083. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21084. intData += srcBytesPerSample;
  21085. }
  21086. }
  21087. else
  21088. {
  21089. intData += srcBytesPerSample * numSamples;
  21090. for (int i = numSamples; --i >= 0;)
  21091. {
  21092. intData -= srcBytesPerSample;
  21093. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21094. }
  21095. }
  21096. }
  21097. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21098. {
  21099. const float scale = 1.0f / 0x7fffff;
  21100. const char* intData = static_cast <const char*> (source);
  21101. if (source != (void*) dest || srcBytesPerSample >= 4)
  21102. {
  21103. for (int i = 0; i < numSamples; ++i)
  21104. {
  21105. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21106. intData += srcBytesPerSample;
  21107. }
  21108. }
  21109. else
  21110. {
  21111. intData += srcBytesPerSample * numSamples;
  21112. for (int i = numSamples; --i >= 0;)
  21113. {
  21114. intData -= srcBytesPerSample;
  21115. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21116. }
  21117. }
  21118. }
  21119. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21120. {
  21121. const float scale = 1.0f / 0x7fffff;
  21122. const char* intData = static_cast <const char*> (source);
  21123. if (source != (void*) dest || srcBytesPerSample >= 4)
  21124. {
  21125. for (int i = 0; i < numSamples; ++i)
  21126. {
  21127. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21128. intData += srcBytesPerSample;
  21129. }
  21130. }
  21131. else
  21132. {
  21133. intData += srcBytesPerSample * numSamples;
  21134. for (int i = numSamples; --i >= 0;)
  21135. {
  21136. intData -= srcBytesPerSample;
  21137. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21138. }
  21139. }
  21140. }
  21141. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21142. {
  21143. const float scale = 1.0f / 0x7fffffff;
  21144. const char* intData = static_cast <const char*> (source);
  21145. if (source != (void*) dest || srcBytesPerSample >= 4)
  21146. {
  21147. for (int i = 0; i < numSamples; ++i)
  21148. {
  21149. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21150. intData += srcBytesPerSample;
  21151. }
  21152. }
  21153. else
  21154. {
  21155. intData += srcBytesPerSample * numSamples;
  21156. for (int i = numSamples; --i >= 0;)
  21157. {
  21158. intData -= srcBytesPerSample;
  21159. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21160. }
  21161. }
  21162. }
  21163. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21164. {
  21165. const float scale = 1.0f / 0x7fffffff;
  21166. const char* intData = static_cast <const char*> (source);
  21167. if (source != (void*) dest || srcBytesPerSample >= 4)
  21168. {
  21169. for (int i = 0; i < numSamples; ++i)
  21170. {
  21171. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21172. intData += srcBytesPerSample;
  21173. }
  21174. }
  21175. else
  21176. {
  21177. intData += srcBytesPerSample * numSamples;
  21178. for (int i = numSamples; --i >= 0;)
  21179. {
  21180. intData -= srcBytesPerSample;
  21181. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21182. }
  21183. }
  21184. }
  21185. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21186. {
  21187. const char* s = static_cast <const char*> (source);
  21188. for (int i = 0; i < numSamples; ++i)
  21189. {
  21190. dest[i] = *(float*)s;
  21191. #if JUCE_BIG_ENDIAN
  21192. uint32* const d = (uint32*) (dest + i);
  21193. *d = ByteOrder::swap (*d);
  21194. #endif
  21195. s += srcBytesPerSample;
  21196. }
  21197. }
  21198. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21199. {
  21200. const char* s = static_cast <const char*> (source);
  21201. for (int i = 0; i < numSamples; ++i)
  21202. {
  21203. dest[i] = *(float*)s;
  21204. #if JUCE_LITTLE_ENDIAN
  21205. uint32* const d = (uint32*) (dest + i);
  21206. *d = ByteOrder::swap (*d);
  21207. #endif
  21208. s += srcBytesPerSample;
  21209. }
  21210. }
  21211. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21212. const float* const source,
  21213. void* const dest,
  21214. const int numSamples)
  21215. {
  21216. switch (destFormat)
  21217. {
  21218. case int16LE:
  21219. convertFloatToInt16LE (source, dest, numSamples);
  21220. break;
  21221. case int16BE:
  21222. convertFloatToInt16BE (source, dest, numSamples);
  21223. break;
  21224. case int24LE:
  21225. convertFloatToInt24LE (source, dest, numSamples);
  21226. break;
  21227. case int24BE:
  21228. convertFloatToInt24BE (source, dest, numSamples);
  21229. break;
  21230. case int32LE:
  21231. convertFloatToInt32LE (source, dest, numSamples);
  21232. break;
  21233. case int32BE:
  21234. convertFloatToInt32BE (source, dest, numSamples);
  21235. break;
  21236. case float32LE:
  21237. convertFloatToFloat32LE (source, dest, numSamples);
  21238. break;
  21239. case float32BE:
  21240. convertFloatToFloat32BE (source, dest, numSamples);
  21241. break;
  21242. default:
  21243. jassertfalse;
  21244. break;
  21245. }
  21246. }
  21247. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21248. const void* const source,
  21249. float* const dest,
  21250. const int numSamples)
  21251. {
  21252. switch (sourceFormat)
  21253. {
  21254. case int16LE:
  21255. convertInt16LEToFloat (source, dest, numSamples);
  21256. break;
  21257. case int16BE:
  21258. convertInt16BEToFloat (source, dest, numSamples);
  21259. break;
  21260. case int24LE:
  21261. convertInt24LEToFloat (source, dest, numSamples);
  21262. break;
  21263. case int24BE:
  21264. convertInt24BEToFloat (source, dest, numSamples);
  21265. break;
  21266. case int32LE:
  21267. convertInt32LEToFloat (source, dest, numSamples);
  21268. break;
  21269. case int32BE:
  21270. convertInt32BEToFloat (source, dest, numSamples);
  21271. break;
  21272. case float32LE:
  21273. convertFloat32LEToFloat (source, dest, numSamples);
  21274. break;
  21275. case float32BE:
  21276. convertFloat32BEToFloat (source, dest, numSamples);
  21277. break;
  21278. default:
  21279. jassertfalse;
  21280. break;
  21281. }
  21282. }
  21283. void AudioDataConverters::interleaveSamples (const float** const source,
  21284. float* const dest,
  21285. const int numSamples,
  21286. const int numChannels)
  21287. {
  21288. for (int chan = 0; chan < numChannels; ++chan)
  21289. {
  21290. int i = chan;
  21291. const float* src = source [chan];
  21292. for (int j = 0; j < numSamples; ++j)
  21293. {
  21294. dest [i] = src [j];
  21295. i += numChannels;
  21296. }
  21297. }
  21298. }
  21299. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21300. float** const dest,
  21301. const int numSamples,
  21302. const int numChannels)
  21303. {
  21304. for (int chan = 0; chan < numChannels; ++chan)
  21305. {
  21306. int i = chan;
  21307. float* dst = dest [chan];
  21308. for (int j = 0; j < numSamples; ++j)
  21309. {
  21310. dst [j] = source [i];
  21311. i += numChannels;
  21312. }
  21313. }
  21314. }
  21315. #if JUCE_UNIT_TESTS
  21316. class AudioConversionTests : public UnitTest
  21317. {
  21318. public:
  21319. AudioConversionTests() : UnitTest ("Audio data conversion") {}
  21320. template <class F1, class E1, class F2, class E2>
  21321. struct Test5
  21322. {
  21323. static void test (UnitTest& unitTest)
  21324. {
  21325. test (unitTest, false);
  21326. test (unitTest, true);
  21327. }
  21328. static void test (UnitTest& unitTest, bool inPlace)
  21329. {
  21330. const int numSamples = 2048;
  21331. int32 original [numSamples], converted [numSamples], reversed [numSamples];
  21332. {
  21333. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> d (original);
  21334. bool clippingFailed = false;
  21335. for (int i = 0; i < numSamples / 2; ++i)
  21336. {
  21337. d.setAsFloat (Random::getSystemRandom().nextFloat() * 2.2f - 1.1f);
  21338. if (! d.isFloatingPoint())
  21339. clippingFailed = d.getAsFloat() > 1.0f || d.getAsFloat() < -1.0f || clippingFailed;
  21340. ++d;
  21341. d.setAsInt32 (Random::getSystemRandom().nextInt());
  21342. ++d;
  21343. }
  21344. unitTest.expect (! clippingFailed);
  21345. }
  21346. // convert data from the source to dest format..
  21347. ScopedPointer<AudioData::Converter> conv (new AudioData::ConverterInstance <AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>,
  21348. AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::NonConst> >());
  21349. conv->convertSamples (inPlace ? reversed : converted, original, numSamples);
  21350. // ..and back again..
  21351. conv = new AudioData::ConverterInstance <AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>,
  21352. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> >();
  21353. if (! inPlace)
  21354. zerostruct (reversed);
  21355. conv->convertSamples (reversed, inPlace ? reversed : converted, numSamples);
  21356. {
  21357. int biggestDiff = 0;
  21358. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d1 (original);
  21359. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d2 (reversed);
  21360. const int errorMargin = 2 * AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution()
  21361. + AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution();
  21362. for (int i = 0; i < numSamples; ++i)
  21363. {
  21364. biggestDiff = jmax (biggestDiff, std::abs (d1.getAsInt32() - d2.getAsInt32()));
  21365. ++d1;
  21366. ++d2;
  21367. }
  21368. unitTest.expect (biggestDiff <= errorMargin);
  21369. }
  21370. }
  21371. };
  21372. template <class F1, class E1, class FormatType>
  21373. struct Test3
  21374. {
  21375. static void test (UnitTest& unitTest)
  21376. {
  21377. Test5 <F1, E1, FormatType, AudioData::BigEndian>::test (unitTest);
  21378. Test5 <F1, E1, FormatType, AudioData::LittleEndian>::test (unitTest);
  21379. }
  21380. };
  21381. template <class FormatType, class Endianness>
  21382. struct Test2
  21383. {
  21384. static void test (UnitTest& unitTest)
  21385. {
  21386. Test3 <FormatType, Endianness, AudioData::Int8>::test (unitTest);
  21387. Test3 <FormatType, Endianness, AudioData::UInt8>::test (unitTest);
  21388. Test3 <FormatType, Endianness, AudioData::Int16>::test (unitTest);
  21389. Test3 <FormatType, Endianness, AudioData::Int24>::test (unitTest);
  21390. Test3 <FormatType, Endianness, AudioData::Int32>::test (unitTest);
  21391. Test3 <FormatType, Endianness, AudioData::Float32>::test (unitTest);
  21392. }
  21393. };
  21394. template <class FormatType>
  21395. struct Test1
  21396. {
  21397. static void test (UnitTest& unitTest)
  21398. {
  21399. Test2 <FormatType, AudioData::BigEndian>::test (unitTest);
  21400. Test2 <FormatType, AudioData::LittleEndian>::test (unitTest);
  21401. }
  21402. };
  21403. void runTest()
  21404. {
  21405. beginTest ("Round-trip conversion");
  21406. Test1 <AudioData::Int8>::test (*this);
  21407. Test1 <AudioData::Int16>::test (*this);
  21408. Test1 <AudioData::Int24>::test (*this);
  21409. Test1 <AudioData::Int32>::test (*this);
  21410. Test1 <AudioData::Float32>::test (*this);
  21411. }
  21412. };
  21413. static AudioConversionTests audioConversionUnitTests;
  21414. #endif
  21415. END_JUCE_NAMESPACE
  21416. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21417. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21418. BEGIN_JUCE_NAMESPACE
  21419. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21420. const int numSamples) throw()
  21421. : numChannels (numChannels_),
  21422. size (numSamples)
  21423. {
  21424. jassert (numSamples >= 0);
  21425. jassert (numChannels_ > 0);
  21426. allocateData();
  21427. }
  21428. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21429. : numChannels (other.numChannels),
  21430. size (other.size)
  21431. {
  21432. allocateData();
  21433. const size_t numBytes = size * sizeof (float);
  21434. for (int i = 0; i < numChannels; ++i)
  21435. memcpy (channels[i], other.channels[i], numBytes);
  21436. }
  21437. void AudioSampleBuffer::allocateData()
  21438. {
  21439. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21440. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21441. allocatedData.malloc (allocatedBytes);
  21442. channels = reinterpret_cast <float**> (allocatedData.getData());
  21443. float* chan = (float*) (allocatedData + channelListSize);
  21444. for (int i = 0; i < numChannels; ++i)
  21445. {
  21446. channels[i] = chan;
  21447. chan += size;
  21448. }
  21449. channels [numChannels] = 0;
  21450. }
  21451. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21452. const int numChannels_,
  21453. const int numSamples) throw()
  21454. : numChannels (numChannels_),
  21455. size (numSamples),
  21456. allocatedBytes (0)
  21457. {
  21458. jassert (numChannels_ > 0);
  21459. allocateChannels (dataToReferTo, 0);
  21460. }
  21461. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21462. const int numChannels_,
  21463. const int startSample,
  21464. const int numSamples) throw()
  21465. : numChannels (numChannels_),
  21466. size (numSamples),
  21467. allocatedBytes (0)
  21468. {
  21469. jassert (numChannels_ > 0);
  21470. allocateChannels (dataToReferTo, startSample);
  21471. }
  21472. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21473. const int newNumChannels,
  21474. const int newNumSamples) throw()
  21475. {
  21476. jassert (newNumChannels > 0);
  21477. allocatedBytes = 0;
  21478. allocatedData.free();
  21479. numChannels = newNumChannels;
  21480. size = newNumSamples;
  21481. allocateChannels (dataToReferTo, 0);
  21482. }
  21483. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo, int offset)
  21484. {
  21485. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21486. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21487. {
  21488. channels = static_cast <float**> (preallocatedChannelSpace);
  21489. }
  21490. else
  21491. {
  21492. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21493. channels = reinterpret_cast <float**> (allocatedData.getData());
  21494. }
  21495. for (int i = 0; i < numChannels; ++i)
  21496. {
  21497. // you have to pass in the same number of valid pointers as numChannels
  21498. jassert (dataToReferTo[i] != 0);
  21499. channels[i] = dataToReferTo[i] + offset;
  21500. }
  21501. channels [numChannels] = 0;
  21502. }
  21503. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21504. {
  21505. if (this != &other)
  21506. {
  21507. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21508. const size_t numBytes = size * sizeof (float);
  21509. for (int i = 0; i < numChannels; ++i)
  21510. memcpy (channels[i], other.channels[i], numBytes);
  21511. }
  21512. return *this;
  21513. }
  21514. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21515. {
  21516. }
  21517. void AudioSampleBuffer::setSize (const int newNumChannels,
  21518. const int newNumSamples,
  21519. const bool keepExistingContent,
  21520. const bool clearExtraSpace,
  21521. const bool avoidReallocating) throw()
  21522. {
  21523. jassert (newNumChannels > 0);
  21524. if (newNumSamples != size || newNumChannels != numChannels)
  21525. {
  21526. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21527. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21528. if (keepExistingContent)
  21529. {
  21530. HeapBlock <char> newData;
  21531. newData.allocate (newTotalBytes, clearExtraSpace);
  21532. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21533. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21534. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21535. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21536. for (int i = 0; i < numChansToCopy; ++i)
  21537. {
  21538. memcpy (newChan, channels[i], numBytesToCopy);
  21539. newChannels[i] = newChan;
  21540. newChan += newNumSamples;
  21541. }
  21542. allocatedData.swapWith (newData);
  21543. allocatedBytes = (int) newTotalBytes;
  21544. channels = newChannels;
  21545. }
  21546. else
  21547. {
  21548. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21549. {
  21550. if (clearExtraSpace)
  21551. zeromem (allocatedData, newTotalBytes);
  21552. }
  21553. else
  21554. {
  21555. allocatedBytes = newTotalBytes;
  21556. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21557. channels = reinterpret_cast <float**> (allocatedData.getData());
  21558. }
  21559. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21560. for (int i = 0; i < newNumChannels; ++i)
  21561. {
  21562. channels[i] = chan;
  21563. chan += newNumSamples;
  21564. }
  21565. }
  21566. channels [newNumChannels] = 0;
  21567. size = newNumSamples;
  21568. numChannels = newNumChannels;
  21569. }
  21570. }
  21571. void AudioSampleBuffer::clear() throw()
  21572. {
  21573. for (int i = 0; i < numChannels; ++i)
  21574. zeromem (channels[i], size * sizeof (float));
  21575. }
  21576. void AudioSampleBuffer::clear (const int startSample,
  21577. const int numSamples) throw()
  21578. {
  21579. jassert (startSample >= 0 && startSample + numSamples <= size);
  21580. for (int i = 0; i < numChannels; ++i)
  21581. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21582. }
  21583. void AudioSampleBuffer::clear (const int channel,
  21584. const int startSample,
  21585. const int numSamples) throw()
  21586. {
  21587. jassert (isPositiveAndBelow (channel, numChannels));
  21588. jassert (startSample >= 0 && startSample + numSamples <= size);
  21589. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21590. }
  21591. void AudioSampleBuffer::applyGain (const int channel,
  21592. const int startSample,
  21593. int numSamples,
  21594. const float gain) throw()
  21595. {
  21596. jassert (isPositiveAndBelow (channel, numChannels));
  21597. jassert (startSample >= 0 && startSample + numSamples <= size);
  21598. if (gain != 1.0f)
  21599. {
  21600. float* d = channels [channel] + startSample;
  21601. if (gain == 0.0f)
  21602. {
  21603. zeromem (d, sizeof (float) * numSamples);
  21604. }
  21605. else
  21606. {
  21607. while (--numSamples >= 0)
  21608. *d++ *= gain;
  21609. }
  21610. }
  21611. }
  21612. void AudioSampleBuffer::applyGainRamp (const int channel,
  21613. const int startSample,
  21614. int numSamples,
  21615. float startGain,
  21616. float endGain) throw()
  21617. {
  21618. if (startGain == endGain)
  21619. {
  21620. applyGain (channel, startSample, numSamples, startGain);
  21621. }
  21622. else
  21623. {
  21624. jassert (isPositiveAndBelow (channel, numChannels));
  21625. jassert (startSample >= 0 && startSample + numSamples <= size);
  21626. const float increment = (endGain - startGain) / numSamples;
  21627. float* d = channels [channel] + startSample;
  21628. while (--numSamples >= 0)
  21629. {
  21630. *d++ *= startGain;
  21631. startGain += increment;
  21632. }
  21633. }
  21634. }
  21635. void AudioSampleBuffer::applyGain (const int startSample,
  21636. const int numSamples,
  21637. const float gain) throw()
  21638. {
  21639. for (int i = 0; i < numChannels; ++i)
  21640. applyGain (i, startSample, numSamples, gain);
  21641. }
  21642. void AudioSampleBuffer::addFrom (const int destChannel,
  21643. const int destStartSample,
  21644. const AudioSampleBuffer& source,
  21645. const int sourceChannel,
  21646. const int sourceStartSample,
  21647. int numSamples,
  21648. const float gain) throw()
  21649. {
  21650. jassert (&source != this || sourceChannel != destChannel);
  21651. jassert (isPositiveAndBelow (destChannel, numChannels));
  21652. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21653. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  21654. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21655. if (gain != 0.0f && numSamples > 0)
  21656. {
  21657. float* d = channels [destChannel] + destStartSample;
  21658. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21659. if (gain != 1.0f)
  21660. {
  21661. while (--numSamples >= 0)
  21662. *d++ += gain * *s++;
  21663. }
  21664. else
  21665. {
  21666. while (--numSamples >= 0)
  21667. *d++ += *s++;
  21668. }
  21669. }
  21670. }
  21671. void AudioSampleBuffer::addFrom (const int destChannel,
  21672. const int destStartSample,
  21673. const float* source,
  21674. int numSamples,
  21675. const float gain) throw()
  21676. {
  21677. jassert (isPositiveAndBelow (destChannel, numChannels));
  21678. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21679. jassert (source != 0);
  21680. if (gain != 0.0f && numSamples > 0)
  21681. {
  21682. float* d = channels [destChannel] + destStartSample;
  21683. if (gain != 1.0f)
  21684. {
  21685. while (--numSamples >= 0)
  21686. *d++ += gain * *source++;
  21687. }
  21688. else
  21689. {
  21690. while (--numSamples >= 0)
  21691. *d++ += *source++;
  21692. }
  21693. }
  21694. }
  21695. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  21696. const int destStartSample,
  21697. const float* source,
  21698. int numSamples,
  21699. float startGain,
  21700. const float endGain) throw()
  21701. {
  21702. jassert (isPositiveAndBelow (destChannel, numChannels));
  21703. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21704. jassert (source != 0);
  21705. if (startGain == endGain)
  21706. {
  21707. addFrom (destChannel,
  21708. destStartSample,
  21709. source,
  21710. numSamples,
  21711. startGain);
  21712. }
  21713. else
  21714. {
  21715. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21716. {
  21717. const float increment = (endGain - startGain) / numSamples;
  21718. float* d = channels [destChannel] + destStartSample;
  21719. while (--numSamples >= 0)
  21720. {
  21721. *d++ += startGain * *source++;
  21722. startGain += increment;
  21723. }
  21724. }
  21725. }
  21726. }
  21727. void AudioSampleBuffer::copyFrom (const int destChannel,
  21728. const int destStartSample,
  21729. const AudioSampleBuffer& source,
  21730. const int sourceChannel,
  21731. const int sourceStartSample,
  21732. int numSamples) throw()
  21733. {
  21734. jassert (&source != this || sourceChannel != destChannel);
  21735. jassert (isPositiveAndBelow (destChannel, numChannels));
  21736. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21737. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  21738. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21739. if (numSamples > 0)
  21740. {
  21741. memcpy (channels [destChannel] + destStartSample,
  21742. source.channels [sourceChannel] + sourceStartSample,
  21743. sizeof (float) * numSamples);
  21744. }
  21745. }
  21746. void AudioSampleBuffer::copyFrom (const int destChannel,
  21747. const int destStartSample,
  21748. const float* source,
  21749. int numSamples) throw()
  21750. {
  21751. jassert (isPositiveAndBelow (destChannel, numChannels));
  21752. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21753. jassert (source != 0);
  21754. if (numSamples > 0)
  21755. {
  21756. memcpy (channels [destChannel] + destStartSample,
  21757. source,
  21758. sizeof (float) * numSamples);
  21759. }
  21760. }
  21761. void AudioSampleBuffer::copyFrom (const int destChannel,
  21762. const int destStartSample,
  21763. const float* source,
  21764. int numSamples,
  21765. const float gain) throw()
  21766. {
  21767. jassert (isPositiveAndBelow (destChannel, numChannels));
  21768. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21769. jassert (source != 0);
  21770. if (numSamples > 0)
  21771. {
  21772. float* d = channels [destChannel] + destStartSample;
  21773. if (gain != 1.0f)
  21774. {
  21775. if (gain == 0)
  21776. {
  21777. zeromem (d, sizeof (float) * numSamples);
  21778. }
  21779. else
  21780. {
  21781. while (--numSamples >= 0)
  21782. *d++ = gain * *source++;
  21783. }
  21784. }
  21785. else
  21786. {
  21787. memcpy (d, source, sizeof (float) * numSamples);
  21788. }
  21789. }
  21790. }
  21791. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  21792. const int destStartSample,
  21793. const float* source,
  21794. int numSamples,
  21795. float startGain,
  21796. float endGain) throw()
  21797. {
  21798. jassert (isPositiveAndBelow (destChannel, numChannels));
  21799. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21800. jassert (source != 0);
  21801. if (startGain == endGain)
  21802. {
  21803. copyFrom (destChannel,
  21804. destStartSample,
  21805. source,
  21806. numSamples,
  21807. startGain);
  21808. }
  21809. else
  21810. {
  21811. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21812. {
  21813. const float increment = (endGain - startGain) / numSamples;
  21814. float* d = channels [destChannel] + destStartSample;
  21815. while (--numSamples >= 0)
  21816. {
  21817. *d++ = startGain * *source++;
  21818. startGain += increment;
  21819. }
  21820. }
  21821. }
  21822. }
  21823. void AudioSampleBuffer::findMinMax (const int channel,
  21824. const int startSample,
  21825. int numSamples,
  21826. float& minVal,
  21827. float& maxVal) const throw()
  21828. {
  21829. jassert (isPositiveAndBelow (channel, numChannels));
  21830. jassert (startSample >= 0 && startSample + numSamples <= size);
  21831. findMinAndMax (channels [channel] + startSample, numSamples, minVal, maxVal);
  21832. }
  21833. float AudioSampleBuffer::getMagnitude (const int channel,
  21834. const int startSample,
  21835. const int numSamples) const throw()
  21836. {
  21837. jassert (isPositiveAndBelow (channel, numChannels));
  21838. jassert (startSample >= 0 && startSample + numSamples <= size);
  21839. float mn, mx;
  21840. findMinMax (channel, startSample, numSamples, mn, mx);
  21841. return jmax (mn, -mn, mx, -mx);
  21842. }
  21843. float AudioSampleBuffer::getMagnitude (const int startSample,
  21844. const int numSamples) const throw()
  21845. {
  21846. float mag = 0.0f;
  21847. for (int i = 0; i < numChannels; ++i)
  21848. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21849. return mag;
  21850. }
  21851. float AudioSampleBuffer::getRMSLevel (const int channel,
  21852. const int startSample,
  21853. const int numSamples) const throw()
  21854. {
  21855. jassert (isPositiveAndBelow (channel, numChannels));
  21856. jassert (startSample >= 0 && startSample + numSamples <= size);
  21857. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21858. return 0.0f;
  21859. const float* const data = channels [channel] + startSample;
  21860. double sum = 0.0;
  21861. for (int i = 0; i < numSamples; ++i)
  21862. {
  21863. const float sample = data [i];
  21864. sum += sample * sample;
  21865. }
  21866. return (float) std::sqrt (sum / numSamples);
  21867. }
  21868. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  21869. const int startSample,
  21870. const int numSamples,
  21871. const int64 readerStartSample,
  21872. const bool useLeftChan,
  21873. const bool useRightChan)
  21874. {
  21875. jassert (reader != 0);
  21876. jassert (startSample >= 0 && startSample + numSamples <= size);
  21877. if (numSamples > 0)
  21878. {
  21879. int* chans[3];
  21880. if (useLeftChan == useRightChan)
  21881. {
  21882. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  21883. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? reinterpret_cast<int*> (getSampleData (1, startSample)) : 0;
  21884. }
  21885. else if (useLeftChan || (reader->numChannels == 1))
  21886. {
  21887. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  21888. chans[1] = 0;
  21889. }
  21890. else if (useRightChan)
  21891. {
  21892. chans[0] = 0;
  21893. chans[1] = reinterpret_cast<int*> (getSampleData (0, startSample));
  21894. }
  21895. chans[2] = 0;
  21896. reader->read (chans, 2, readerStartSample, numSamples, true);
  21897. if (! reader->usesFloatingPointData)
  21898. {
  21899. for (int j = 0; j < 2; ++j)
  21900. {
  21901. float* const d = reinterpret_cast <float*> (chans[j]);
  21902. if (d != 0)
  21903. {
  21904. const float multiplier = 1.0f / 0x7fffffff;
  21905. for (int i = 0; i < numSamples; ++i)
  21906. d[i] = *reinterpret_cast<int*> (d + i) * multiplier;
  21907. }
  21908. }
  21909. }
  21910. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  21911. {
  21912. // if this is a stereo buffer and the source was mono, dupe the first channel..
  21913. memcpy (getSampleData (1, startSample),
  21914. getSampleData (0, startSample),
  21915. sizeof (float) * numSamples);
  21916. }
  21917. }
  21918. }
  21919. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  21920. const int startSample,
  21921. const int numSamples) const
  21922. {
  21923. jassert (writer != 0);
  21924. writer->writeFromAudioSampleBuffer (*this, startSample, numSamples);
  21925. }
  21926. END_JUCE_NAMESPACE
  21927. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  21928. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  21929. BEGIN_JUCE_NAMESPACE
  21930. IIRFilter::IIRFilter()
  21931. : active (false)
  21932. {
  21933. reset();
  21934. }
  21935. IIRFilter::IIRFilter (const IIRFilter& other)
  21936. : active (other.active)
  21937. {
  21938. const ScopedLock sl (other.processLock);
  21939. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21940. reset();
  21941. }
  21942. IIRFilter::~IIRFilter()
  21943. {
  21944. }
  21945. void IIRFilter::reset() throw()
  21946. {
  21947. const ScopedLock sl (processLock);
  21948. x1 = 0;
  21949. x2 = 0;
  21950. y1 = 0;
  21951. y2 = 0;
  21952. }
  21953. float IIRFilter::processSingleSampleRaw (const float in) throw()
  21954. {
  21955. float out = coefficients[0] * in
  21956. + coefficients[1] * x1
  21957. + coefficients[2] * x2
  21958. - coefficients[4] * y1
  21959. - coefficients[5] * y2;
  21960. #if JUCE_INTEL
  21961. if (! (out < -1.0e-8 || out > 1.0e-8))
  21962. out = 0;
  21963. #endif
  21964. x2 = x1;
  21965. x1 = in;
  21966. y2 = y1;
  21967. y1 = out;
  21968. return out;
  21969. }
  21970. void IIRFilter::processSamples (float* const samples,
  21971. const int numSamples) throw()
  21972. {
  21973. const ScopedLock sl (processLock);
  21974. if (active)
  21975. {
  21976. for (int i = 0; i < numSamples; ++i)
  21977. {
  21978. const float in = samples[i];
  21979. float out = coefficients[0] * in
  21980. + coefficients[1] * x1
  21981. + coefficients[2] * x2
  21982. - coefficients[4] * y1
  21983. - coefficients[5] * y2;
  21984. #if JUCE_INTEL
  21985. if (! (out < -1.0e-8 || out > 1.0e-8))
  21986. out = 0;
  21987. #endif
  21988. x2 = x1;
  21989. x1 = in;
  21990. y2 = y1;
  21991. y1 = out;
  21992. samples[i] = out;
  21993. }
  21994. }
  21995. }
  21996. void IIRFilter::makeLowPass (const double sampleRate,
  21997. const double frequency) throw()
  21998. {
  21999. jassert (sampleRate > 0);
  22000. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  22001. const double nSquared = n * n;
  22002. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22003. setCoefficients (c1,
  22004. c1 * 2.0f,
  22005. c1,
  22006. 1.0,
  22007. c1 * 2.0 * (1.0 - nSquared),
  22008. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22009. }
  22010. void IIRFilter::makeHighPass (const double sampleRate,
  22011. const double frequency) throw()
  22012. {
  22013. const double n = tan (double_Pi * frequency / sampleRate);
  22014. const double nSquared = n * n;
  22015. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22016. setCoefficients (c1,
  22017. c1 * -2.0f,
  22018. c1,
  22019. 1.0,
  22020. c1 * 2.0 * (nSquared - 1.0),
  22021. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22022. }
  22023. void IIRFilter::makeLowShelf (const double sampleRate,
  22024. const double cutOffFrequency,
  22025. const double Q,
  22026. const float gainFactor) throw()
  22027. {
  22028. jassert (sampleRate > 0);
  22029. jassert (Q > 0);
  22030. const double A = jmax (0.0f, gainFactor);
  22031. const double aminus1 = A - 1.0;
  22032. const double aplus1 = A + 1.0;
  22033. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22034. const double coso = std::cos (omega);
  22035. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22036. const double aminus1TimesCoso = aminus1 * coso;
  22037. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22038. A * 2.0 * (aminus1 - aplus1 * coso),
  22039. A * (aplus1 - aminus1TimesCoso - beta),
  22040. aplus1 + aminus1TimesCoso + beta,
  22041. -2.0 * (aminus1 + aplus1 * coso),
  22042. aplus1 + aminus1TimesCoso - beta);
  22043. }
  22044. void IIRFilter::makeHighShelf (const double sampleRate,
  22045. const double cutOffFrequency,
  22046. const double Q,
  22047. const float gainFactor) throw()
  22048. {
  22049. jassert (sampleRate > 0);
  22050. jassert (Q > 0);
  22051. const double A = jmax (0.0f, gainFactor);
  22052. const double aminus1 = A - 1.0;
  22053. const double aplus1 = A + 1.0;
  22054. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22055. const double coso = std::cos (omega);
  22056. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22057. const double aminus1TimesCoso = aminus1 * coso;
  22058. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22059. A * -2.0 * (aminus1 + aplus1 * coso),
  22060. A * (aplus1 + aminus1TimesCoso - beta),
  22061. aplus1 - aminus1TimesCoso + beta,
  22062. 2.0 * (aminus1 - aplus1 * coso),
  22063. aplus1 - aminus1TimesCoso - beta);
  22064. }
  22065. void IIRFilter::makeBandPass (const double sampleRate,
  22066. const double centreFrequency,
  22067. const double Q,
  22068. const float gainFactor) throw()
  22069. {
  22070. jassert (sampleRate > 0);
  22071. jassert (Q > 0);
  22072. const double A = jmax (0.0f, gainFactor);
  22073. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22074. const double alpha = 0.5 * std::sin (omega) / Q;
  22075. const double c2 = -2.0 * std::cos (omega);
  22076. const double alphaTimesA = alpha * A;
  22077. const double alphaOverA = alpha / A;
  22078. setCoefficients (1.0 + alphaTimesA,
  22079. c2,
  22080. 1.0 - alphaTimesA,
  22081. 1.0 + alphaOverA,
  22082. c2,
  22083. 1.0 - alphaOverA);
  22084. }
  22085. void IIRFilter::makeInactive() throw()
  22086. {
  22087. const ScopedLock sl (processLock);
  22088. active = false;
  22089. }
  22090. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22091. {
  22092. const ScopedLock sl (processLock);
  22093. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22094. active = other.active;
  22095. }
  22096. void IIRFilter::setCoefficients (double c1,
  22097. double c2,
  22098. double c3,
  22099. double c4,
  22100. double c5,
  22101. double c6) throw()
  22102. {
  22103. const double a = 1.0 / c4;
  22104. c1 *= a;
  22105. c2 *= a;
  22106. c3 *= a;
  22107. c5 *= a;
  22108. c6 *= a;
  22109. const ScopedLock sl (processLock);
  22110. coefficients[0] = (float) c1;
  22111. coefficients[1] = (float) c2;
  22112. coefficients[2] = (float) c3;
  22113. coefficients[3] = (float) c4;
  22114. coefficients[4] = (float) c5;
  22115. coefficients[5] = (float) c6;
  22116. active = true;
  22117. }
  22118. END_JUCE_NAMESPACE
  22119. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22120. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22121. BEGIN_JUCE_NAMESPACE
  22122. MidiBuffer::MidiBuffer() throw()
  22123. : bytesUsed (0)
  22124. {
  22125. }
  22126. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22127. : bytesUsed (0)
  22128. {
  22129. addEvent (message, 0);
  22130. }
  22131. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22132. : data (other.data),
  22133. bytesUsed (other.bytesUsed)
  22134. {
  22135. }
  22136. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22137. {
  22138. bytesUsed = other.bytesUsed;
  22139. data = other.data;
  22140. return *this;
  22141. }
  22142. void MidiBuffer::swapWith (MidiBuffer& other) throw()
  22143. {
  22144. data.swapWith (other.data);
  22145. swapVariables <int> (bytesUsed, other.bytesUsed);
  22146. }
  22147. MidiBuffer::~MidiBuffer()
  22148. {
  22149. }
  22150. inline uint8* MidiBuffer::getData() const throw()
  22151. {
  22152. return static_cast <uint8*> (data.getData());
  22153. }
  22154. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22155. {
  22156. return *static_cast <const int*> (d);
  22157. }
  22158. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22159. {
  22160. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22161. }
  22162. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22163. {
  22164. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22165. }
  22166. void MidiBuffer::clear() throw()
  22167. {
  22168. bytesUsed = 0;
  22169. }
  22170. void MidiBuffer::clear (const int startSample, const int numSamples)
  22171. {
  22172. uint8* const start = findEventAfter (getData(), startSample - 1);
  22173. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22174. if (end > start)
  22175. {
  22176. const int bytesToMove = bytesUsed - (int) (end - getData());
  22177. if (bytesToMove > 0)
  22178. memmove (start, end, bytesToMove);
  22179. bytesUsed -= (int) (end - start);
  22180. }
  22181. }
  22182. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22183. {
  22184. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22185. }
  22186. namespace MidiBufferHelpers
  22187. {
  22188. int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22189. {
  22190. unsigned int byte = (unsigned int) *data;
  22191. int size = 0;
  22192. if (byte == 0xf0 || byte == 0xf7)
  22193. {
  22194. const uint8* d = data + 1;
  22195. while (d < data + maxBytes)
  22196. if (*d++ == 0xf7)
  22197. break;
  22198. size = (int) (d - data);
  22199. }
  22200. else if (byte == 0xff)
  22201. {
  22202. int n;
  22203. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22204. size = jmin (maxBytes, n + 2 + bytesLeft);
  22205. }
  22206. else if (byte >= 0x80)
  22207. {
  22208. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22209. }
  22210. return size;
  22211. }
  22212. }
  22213. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22214. {
  22215. const int numBytes = MidiBufferHelpers::findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22216. if (numBytes > 0)
  22217. {
  22218. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22219. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22220. uint8* d = findEventAfter (getData(), sampleNumber);
  22221. const int bytesToMove = bytesUsed - (int) (d - getData());
  22222. if (bytesToMove > 0)
  22223. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22224. *reinterpret_cast <int*> (d) = sampleNumber;
  22225. d += sizeof (int);
  22226. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22227. d += sizeof (uint16);
  22228. memcpy (d, newData, numBytes);
  22229. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22230. }
  22231. }
  22232. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22233. const int startSample,
  22234. const int numSamples,
  22235. const int sampleDeltaToAdd)
  22236. {
  22237. Iterator i (otherBuffer);
  22238. i.setNextSamplePosition (startSample);
  22239. const uint8* eventData;
  22240. int eventSize, position;
  22241. while (i.getNextEvent (eventData, eventSize, position)
  22242. && (position < startSample + numSamples || numSamples < 0))
  22243. {
  22244. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22245. }
  22246. }
  22247. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22248. {
  22249. data.ensureSize (minimumNumBytes);
  22250. }
  22251. bool MidiBuffer::isEmpty() const throw()
  22252. {
  22253. return bytesUsed == 0;
  22254. }
  22255. int MidiBuffer::getNumEvents() const throw()
  22256. {
  22257. int n = 0;
  22258. const uint8* d = getData();
  22259. const uint8* const end = d + bytesUsed;
  22260. while (d < end)
  22261. {
  22262. d += getEventTotalSize (d);
  22263. ++n;
  22264. }
  22265. return n;
  22266. }
  22267. int MidiBuffer::getFirstEventTime() const throw()
  22268. {
  22269. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22270. }
  22271. int MidiBuffer::getLastEventTime() const throw()
  22272. {
  22273. if (bytesUsed == 0)
  22274. return 0;
  22275. const uint8* d = getData();
  22276. const uint8* const endData = d + bytesUsed;
  22277. for (;;)
  22278. {
  22279. const uint8* const nextOne = d + getEventTotalSize (d);
  22280. if (nextOne >= endData)
  22281. return getEventTime (d);
  22282. d = nextOne;
  22283. }
  22284. }
  22285. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22286. {
  22287. const uint8* const endData = getData() + bytesUsed;
  22288. while (d < endData && getEventTime (d) <= samplePosition)
  22289. d += getEventTotalSize (d);
  22290. return d;
  22291. }
  22292. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22293. : buffer (buffer_),
  22294. data (buffer_.getData())
  22295. {
  22296. }
  22297. MidiBuffer::Iterator::~Iterator() throw()
  22298. {
  22299. }
  22300. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22301. {
  22302. data = buffer.getData();
  22303. const uint8* dataEnd = data + buffer.bytesUsed;
  22304. while (data < dataEnd && getEventTime (data) < samplePosition)
  22305. data += getEventTotalSize (data);
  22306. }
  22307. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22308. {
  22309. if (data >= buffer.getData() + buffer.bytesUsed)
  22310. return false;
  22311. samplePosition = getEventTime (data);
  22312. numBytes = getEventDataSize (data);
  22313. data += sizeof (int) + sizeof (uint16);
  22314. midiData = data;
  22315. data += numBytes;
  22316. return true;
  22317. }
  22318. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22319. {
  22320. if (data >= buffer.getData() + buffer.bytesUsed)
  22321. return false;
  22322. samplePosition = getEventTime (data);
  22323. const int numBytes = getEventDataSize (data);
  22324. data += sizeof (int) + sizeof (uint16);
  22325. result = MidiMessage (data, numBytes, samplePosition);
  22326. data += numBytes;
  22327. return true;
  22328. }
  22329. END_JUCE_NAMESPACE
  22330. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22331. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22332. BEGIN_JUCE_NAMESPACE
  22333. namespace MidiFileHelpers
  22334. {
  22335. void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22336. {
  22337. unsigned int buffer = v & 0x7F;
  22338. while ((v >>= 7) != 0)
  22339. {
  22340. buffer <<= 8;
  22341. buffer |= ((v & 0x7F) | 0x80);
  22342. }
  22343. for (;;)
  22344. {
  22345. out.writeByte ((char) buffer);
  22346. if (buffer & 0x80)
  22347. buffer >>= 8;
  22348. else
  22349. break;
  22350. }
  22351. }
  22352. bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22353. {
  22354. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22355. data += 4;
  22356. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22357. {
  22358. bool ok = false;
  22359. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22360. {
  22361. for (int i = 0; i < 8; ++i)
  22362. {
  22363. ch = ByteOrder::bigEndianInt (data);
  22364. data += 4;
  22365. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22366. {
  22367. ok = true;
  22368. break;
  22369. }
  22370. }
  22371. }
  22372. if (! ok)
  22373. return false;
  22374. }
  22375. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22376. data += 4;
  22377. fileType = (short) ByteOrder::bigEndianShort (data);
  22378. data += 2;
  22379. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22380. data += 2;
  22381. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22382. data += 2;
  22383. bytesRemaining -= 6;
  22384. data += bytesRemaining;
  22385. return true;
  22386. }
  22387. double convertTicksToSeconds (const double time,
  22388. const MidiMessageSequence& tempoEvents,
  22389. const int timeFormat)
  22390. {
  22391. if (timeFormat > 0)
  22392. {
  22393. int numer = 4, denom = 4;
  22394. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22395. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22396. double secsPerTick = 0.5 * tickLen;
  22397. const int numEvents = tempoEvents.getNumEvents();
  22398. for (int i = 0; i < numEvents; ++i)
  22399. {
  22400. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22401. if (time <= m.getTimeStamp())
  22402. break;
  22403. if (timeFormat > 0)
  22404. {
  22405. correctedTempoTime = correctedTempoTime
  22406. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22407. }
  22408. else
  22409. {
  22410. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22411. }
  22412. tempoTime = m.getTimeStamp();
  22413. if (m.isTempoMetaEvent())
  22414. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22415. else if (m.isTimeSignatureMetaEvent())
  22416. m.getTimeSignatureInfo (numer, denom);
  22417. while (i + 1 < numEvents)
  22418. {
  22419. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22420. if (m2.getTimeStamp() == tempoTime)
  22421. {
  22422. ++i;
  22423. if (m2.isTempoMetaEvent())
  22424. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22425. else if (m2.isTimeSignatureMetaEvent())
  22426. m2.getTimeSignatureInfo (numer, denom);
  22427. }
  22428. else
  22429. {
  22430. break;
  22431. }
  22432. }
  22433. }
  22434. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22435. }
  22436. else
  22437. {
  22438. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22439. }
  22440. }
  22441. // a comparator that puts all the note-offs before note-ons that have the same time
  22442. struct Sorter
  22443. {
  22444. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22445. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22446. {
  22447. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22448. if (diff == 0)
  22449. {
  22450. if (first->message.isNoteOff() && second->message.isNoteOn())
  22451. return -1;
  22452. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22453. return 1;
  22454. else
  22455. return 0;
  22456. }
  22457. else
  22458. {
  22459. return (diff > 0) ? 1 : -1;
  22460. }
  22461. }
  22462. };
  22463. }
  22464. MidiFile::MidiFile()
  22465. : timeFormat ((short) (unsigned short) 0xe728)
  22466. {
  22467. }
  22468. MidiFile::~MidiFile()
  22469. {
  22470. clear();
  22471. }
  22472. void MidiFile::clear()
  22473. {
  22474. tracks.clear();
  22475. }
  22476. int MidiFile::getNumTracks() const throw()
  22477. {
  22478. return tracks.size();
  22479. }
  22480. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22481. {
  22482. return tracks [index];
  22483. }
  22484. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22485. {
  22486. tracks.add (new MidiMessageSequence (trackSequence));
  22487. }
  22488. short MidiFile::getTimeFormat() const throw()
  22489. {
  22490. return timeFormat;
  22491. }
  22492. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22493. {
  22494. timeFormat = (short) ticks;
  22495. }
  22496. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22497. const int subframeResolution) throw()
  22498. {
  22499. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22500. }
  22501. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22502. {
  22503. for (int i = tracks.size(); --i >= 0;)
  22504. {
  22505. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22506. for (int j = 0; j < numEvents; ++j)
  22507. {
  22508. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22509. if (m.isTempoMetaEvent())
  22510. tempoChangeEvents.addEvent (m);
  22511. }
  22512. }
  22513. }
  22514. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22515. {
  22516. for (int i = tracks.size(); --i >= 0;)
  22517. {
  22518. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22519. for (int j = 0; j < numEvents; ++j)
  22520. {
  22521. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22522. if (m.isTimeSignatureMetaEvent())
  22523. timeSigEvents.addEvent (m);
  22524. }
  22525. }
  22526. }
  22527. double MidiFile::getLastTimestamp() const
  22528. {
  22529. double t = 0.0;
  22530. for (int i = tracks.size(); --i >= 0;)
  22531. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22532. return t;
  22533. }
  22534. bool MidiFile::readFrom (InputStream& sourceStream)
  22535. {
  22536. clear();
  22537. MemoryBlock data;
  22538. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22539. // (put a sanity-check on the file size, as midi files are generally small)
  22540. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22541. {
  22542. size_t size = data.getSize();
  22543. const uint8* d = static_cast <const uint8*> (data.getData());
  22544. short fileType, expectedTracks;
  22545. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22546. {
  22547. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22548. int track = 0;
  22549. while (size > 0 && track < expectedTracks)
  22550. {
  22551. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22552. d += 4;
  22553. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22554. d += 4;
  22555. if (chunkSize <= 0)
  22556. break;
  22557. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22558. {
  22559. readNextTrack (d, chunkSize);
  22560. }
  22561. size -= chunkSize + 8;
  22562. d += chunkSize;
  22563. ++track;
  22564. }
  22565. return true;
  22566. }
  22567. }
  22568. return false;
  22569. }
  22570. void MidiFile::readNextTrack (const uint8* data, int size)
  22571. {
  22572. double time = 0;
  22573. char lastStatusByte = 0;
  22574. MidiMessageSequence result;
  22575. while (size > 0)
  22576. {
  22577. int bytesUsed;
  22578. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22579. data += bytesUsed;
  22580. size -= bytesUsed;
  22581. time += delay;
  22582. int messSize = 0;
  22583. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22584. if (messSize <= 0)
  22585. break;
  22586. size -= messSize;
  22587. data += messSize;
  22588. result.addEvent (mm);
  22589. const char firstByte = *(mm.getRawData());
  22590. if ((firstByte & 0xf0) != 0xf0)
  22591. lastStatusByte = firstByte;
  22592. }
  22593. // use a sort that puts all the note-offs before note-ons that have the same time
  22594. MidiFileHelpers::Sorter sorter;
  22595. result.list.sort (sorter, true);
  22596. result.updateMatchedPairs();
  22597. addTrack (result);
  22598. }
  22599. void MidiFile::convertTimestampTicksToSeconds()
  22600. {
  22601. MidiMessageSequence tempoEvents;
  22602. findAllTempoEvents (tempoEvents);
  22603. findAllTimeSigEvents (tempoEvents);
  22604. for (int i = 0; i < tracks.size(); ++i)
  22605. {
  22606. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22607. for (int j = ms.getNumEvents(); --j >= 0;)
  22608. {
  22609. MidiMessage& m = ms.getEventPointer(j)->message;
  22610. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22611. tempoEvents,
  22612. timeFormat));
  22613. }
  22614. }
  22615. }
  22616. bool MidiFile::writeTo (OutputStream& out)
  22617. {
  22618. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  22619. out.writeIntBigEndian (6);
  22620. out.writeShortBigEndian (1); // type
  22621. out.writeShortBigEndian ((short) tracks.size());
  22622. out.writeShortBigEndian (timeFormat);
  22623. for (int i = 0; i < tracks.size(); ++i)
  22624. writeTrack (out, i);
  22625. out.flush();
  22626. return true;
  22627. }
  22628. void MidiFile::writeTrack (OutputStream& mainOut, const int trackNum)
  22629. {
  22630. MemoryOutputStream out;
  22631. const MidiMessageSequence& ms = *tracks[trackNum];
  22632. int lastTick = 0;
  22633. char lastStatusByte = 0;
  22634. for (int i = 0; i < ms.getNumEvents(); ++i)
  22635. {
  22636. const MidiMessage& mm = ms.getEventPointer(i)->message;
  22637. const int tick = roundToInt (mm.getTimeStamp());
  22638. const int delta = jmax (0, tick - lastTick);
  22639. MidiFileHelpers::writeVariableLengthInt (out, delta);
  22640. lastTick = tick;
  22641. const char statusByte = *(mm.getRawData());
  22642. if ((statusByte == lastStatusByte)
  22643. && ((statusByte & 0xf0) != 0xf0)
  22644. && i > 0
  22645. && mm.getRawDataSize() > 1)
  22646. {
  22647. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  22648. }
  22649. else
  22650. {
  22651. out.write (mm.getRawData(), mm.getRawDataSize());
  22652. }
  22653. lastStatusByte = statusByte;
  22654. }
  22655. out.writeByte (0);
  22656. const MidiMessage m (MidiMessage::endOfTrack());
  22657. out.write (m.getRawData(),
  22658. m.getRawDataSize());
  22659. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  22660. mainOut.writeIntBigEndian ((int) out.getDataSize());
  22661. mainOut.write (out.getData(), (int) out.getDataSize());
  22662. }
  22663. END_JUCE_NAMESPACE
  22664. /*** End of inlined file: juce_MidiFile.cpp ***/
  22665. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  22666. BEGIN_JUCE_NAMESPACE
  22667. MidiKeyboardState::MidiKeyboardState()
  22668. {
  22669. zerostruct (noteStates);
  22670. }
  22671. MidiKeyboardState::~MidiKeyboardState()
  22672. {
  22673. }
  22674. void MidiKeyboardState::reset()
  22675. {
  22676. const ScopedLock sl (lock);
  22677. zerostruct (noteStates);
  22678. eventsToAdd.clear();
  22679. }
  22680. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  22681. {
  22682. jassert (midiChannel >= 0 && midiChannel <= 16);
  22683. return isPositiveAndBelow (n, (int) 128)
  22684. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  22685. }
  22686. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  22687. {
  22688. return isPositiveAndBelow (n, (int) 128)
  22689. && (noteStates[n] & midiChannelMask) != 0;
  22690. }
  22691. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  22692. {
  22693. jassert (midiChannel >= 0 && midiChannel <= 16);
  22694. jassert (isPositiveAndBelow (midiNoteNumber, (int) 128));
  22695. const ScopedLock sl (lock);
  22696. if (isPositiveAndBelow (midiNoteNumber, (int) 128))
  22697. {
  22698. const int timeNow = (int) Time::getMillisecondCounter();
  22699. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  22700. eventsToAdd.clear (0, timeNow - 500);
  22701. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  22702. }
  22703. }
  22704. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  22705. {
  22706. if (isPositiveAndBelow (midiNoteNumber, (int) 128))
  22707. {
  22708. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  22709. for (int i = listeners.size(); --i >= 0;)
  22710. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  22711. }
  22712. }
  22713. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  22714. {
  22715. const ScopedLock sl (lock);
  22716. if (isNoteOn (midiChannel, midiNoteNumber))
  22717. {
  22718. const int timeNow = (int) Time::getMillisecondCounter();
  22719. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  22720. eventsToAdd.clear (0, timeNow - 500);
  22721. noteOffInternal (midiChannel, midiNoteNumber);
  22722. }
  22723. }
  22724. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22725. {
  22726. if (isNoteOn (midiChannel, midiNoteNumber))
  22727. {
  22728. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22729. for (int i = listeners.size(); --i >= 0;)
  22730. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22731. }
  22732. }
  22733. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22734. {
  22735. const ScopedLock sl (lock);
  22736. if (midiChannel <= 0)
  22737. {
  22738. for (int i = 1; i <= 16; ++i)
  22739. allNotesOff (i);
  22740. }
  22741. else
  22742. {
  22743. for (int i = 0; i < 128; ++i)
  22744. noteOff (midiChannel, i);
  22745. }
  22746. }
  22747. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22748. {
  22749. if (message.isNoteOn())
  22750. {
  22751. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22752. }
  22753. else if (message.isNoteOff())
  22754. {
  22755. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22756. }
  22757. else if (message.isAllNotesOff())
  22758. {
  22759. for (int i = 0; i < 128; ++i)
  22760. noteOffInternal (message.getChannel(), i);
  22761. }
  22762. }
  22763. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22764. const int startSample,
  22765. const int numSamples,
  22766. const bool injectIndirectEvents)
  22767. {
  22768. MidiBuffer::Iterator i (buffer);
  22769. MidiMessage message (0xf4, 0.0);
  22770. int time;
  22771. const ScopedLock sl (lock);
  22772. while (i.getNextEvent (message, time))
  22773. processNextMidiEvent (message);
  22774. if (injectIndirectEvents)
  22775. {
  22776. MidiBuffer::Iterator i2 (eventsToAdd);
  22777. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22778. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22779. while (i2.getNextEvent (message, time))
  22780. {
  22781. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22782. buffer.addEvent (message, startSample + pos);
  22783. }
  22784. }
  22785. eventsToAdd.clear();
  22786. }
  22787. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  22788. {
  22789. const ScopedLock sl (lock);
  22790. listeners.addIfNotAlreadyThere (listener);
  22791. }
  22792. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  22793. {
  22794. const ScopedLock sl (lock);
  22795. listeners.removeValue (listener);
  22796. }
  22797. END_JUCE_NAMESPACE
  22798. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22799. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22800. BEGIN_JUCE_NAMESPACE
  22801. namespace MidiHelpers
  22802. {
  22803. inline uint8 initialByte (const int type, const int channel) throw()
  22804. {
  22805. return (uint8) (type | jlimit (0, 15, channel - 1));
  22806. }
  22807. inline uint8 validVelocity (const int v) throw()
  22808. {
  22809. return (uint8) jlimit (0, 127, v);
  22810. }
  22811. }
  22812. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  22813. {
  22814. numBytesUsed = 0;
  22815. int v = 0;
  22816. int i;
  22817. do
  22818. {
  22819. i = (int) *data++;
  22820. if (++numBytesUsed > 6)
  22821. break;
  22822. v = (v << 7) + (i & 0x7f);
  22823. } while (i & 0x80);
  22824. return v;
  22825. }
  22826. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22827. {
  22828. // this method only works for valid starting bytes of a short midi message
  22829. jassert (firstByte >= 0x80 && firstByte != 0xf0 && firstByte != 0xf7);
  22830. static const char messageLengths[] =
  22831. {
  22832. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22833. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22834. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22835. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22836. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22837. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22838. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22839. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22840. };
  22841. return messageLengths [firstByte & 0x7f];
  22842. }
  22843. MidiMessage::MidiMessage() throw()
  22844. : timeStamp (0),
  22845. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22846. size (2)
  22847. {
  22848. data[0] = 0xf0;
  22849. data[1] = 0xf7;
  22850. }
  22851. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22852. : timeStamp (t),
  22853. size (dataSize)
  22854. {
  22855. jassert (dataSize > 0);
  22856. if (dataSize <= 4)
  22857. data = static_cast<uint8*> (preallocatedData.asBytes);
  22858. else
  22859. data = new uint8 [dataSize];
  22860. memcpy (data, d, dataSize);
  22861. // check that the length matches the data..
  22862. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22863. }
  22864. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22865. : timeStamp (t),
  22866. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22867. size (1)
  22868. {
  22869. data[0] = (uint8) byte1;
  22870. // check that the length matches the data..
  22871. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22872. }
  22873. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22874. : timeStamp (t),
  22875. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22876. size (2)
  22877. {
  22878. data[0] = (uint8) byte1;
  22879. data[1] = (uint8) byte2;
  22880. // check that the length matches the data..
  22881. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  22882. }
  22883. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  22884. : timeStamp (t),
  22885. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22886. size (3)
  22887. {
  22888. data[0] = (uint8) byte1;
  22889. data[1] = (uint8) byte2;
  22890. data[2] = (uint8) byte3;
  22891. // check that the length matches the data..
  22892. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  22893. }
  22894. MidiMessage::MidiMessage (const MidiMessage& other)
  22895. : timeStamp (other.timeStamp),
  22896. size (other.size)
  22897. {
  22898. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22899. {
  22900. data = new uint8 [size];
  22901. memcpy (data, other.data, size);
  22902. }
  22903. else
  22904. {
  22905. data = static_cast<uint8*> (preallocatedData.asBytes);
  22906. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22907. }
  22908. }
  22909. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  22910. : timeStamp (newTimeStamp),
  22911. size (other.size)
  22912. {
  22913. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22914. {
  22915. data = new uint8 [size];
  22916. memcpy (data, other.data, size);
  22917. }
  22918. else
  22919. {
  22920. data = static_cast<uint8*> (preallocatedData.asBytes);
  22921. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22922. }
  22923. }
  22924. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  22925. : timeStamp (t),
  22926. data (static_cast<uint8*> (preallocatedData.asBytes))
  22927. {
  22928. const uint8* src = static_cast <const uint8*> (src_);
  22929. unsigned int byte = (unsigned int) *src;
  22930. if (byte < 0x80)
  22931. {
  22932. byte = (unsigned int) (uint8) lastStatusByte;
  22933. numBytesUsed = -1;
  22934. }
  22935. else
  22936. {
  22937. numBytesUsed = 0;
  22938. --sz;
  22939. ++src;
  22940. }
  22941. if (byte >= 0x80)
  22942. {
  22943. if (byte == 0xf0)
  22944. {
  22945. const uint8* d = src;
  22946. bool haveReadAllLengthBytes = false;
  22947. while (d < src + sz)
  22948. {
  22949. if (*d >= 0x80)
  22950. {
  22951. if (*d == 0xf7)
  22952. {
  22953. ++d; // include the trailing 0xf7 when we hit it
  22954. break;
  22955. }
  22956. if (haveReadAllLengthBytes) // if we see a 0x80 bit set after the initial data length
  22957. break; // bytes, assume it's the end of the sysex
  22958. ++d;
  22959. continue;
  22960. }
  22961. haveReadAllLengthBytes = true;
  22962. ++d;
  22963. }
  22964. size = 1 + (int) (d - src);
  22965. data = new uint8 [size];
  22966. *data = (uint8) byte;
  22967. memcpy (data + 1, src, size - 1);
  22968. }
  22969. else if (byte == 0xff)
  22970. {
  22971. int n;
  22972. const int bytesLeft = readVariableLengthVal (src + 1, n);
  22973. size = jmin (sz + 1, n + 2 + bytesLeft);
  22974. data = new uint8 [size];
  22975. *data = (uint8) byte;
  22976. memcpy (data + 1, src, size - 1);
  22977. }
  22978. else
  22979. {
  22980. preallocatedData.asInt32 = 0;
  22981. size = getMessageLengthFromFirstByte ((uint8) byte);
  22982. data[0] = (uint8) byte;
  22983. if (size > 1)
  22984. {
  22985. data[1] = src[0];
  22986. if (size > 2)
  22987. data[2] = src[1];
  22988. }
  22989. }
  22990. numBytesUsed += size;
  22991. }
  22992. else
  22993. {
  22994. preallocatedData.asInt32 = 0;
  22995. size = 0;
  22996. }
  22997. }
  22998. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  22999. {
  23000. if (this != &other)
  23001. {
  23002. timeStamp = other.timeStamp;
  23003. size = other.size;
  23004. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23005. delete[] data;
  23006. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23007. {
  23008. data = new uint8 [size];
  23009. memcpy (data, other.data, size);
  23010. }
  23011. else
  23012. {
  23013. data = static_cast<uint8*> (preallocatedData.asBytes);
  23014. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23015. }
  23016. }
  23017. return *this;
  23018. }
  23019. MidiMessage::~MidiMessage()
  23020. {
  23021. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23022. delete[] data;
  23023. }
  23024. int MidiMessage::getChannel() const throw()
  23025. {
  23026. if ((data[0] & 0xf0) != 0xf0)
  23027. return (data[0] & 0xf) + 1;
  23028. else
  23029. return 0;
  23030. }
  23031. bool MidiMessage::isForChannel (const int channel) const throw()
  23032. {
  23033. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23034. return ((data[0] & 0xf) == channel - 1)
  23035. && ((data[0] & 0xf0) != 0xf0);
  23036. }
  23037. void MidiMessage::setChannel (const int channel) throw()
  23038. {
  23039. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23040. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23041. data[0] = (uint8) ((data[0] & (uint8) 0xf0)
  23042. | (uint8)(channel - 1));
  23043. }
  23044. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23045. {
  23046. return ((data[0] & 0xf0) == 0x90)
  23047. && (returnTrueForVelocity0 || data[2] != 0);
  23048. }
  23049. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23050. {
  23051. return ((data[0] & 0xf0) == 0x80)
  23052. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23053. }
  23054. bool MidiMessage::isNoteOnOrOff() const throw()
  23055. {
  23056. const int d = data[0] & 0xf0;
  23057. return (d == 0x90) || (d == 0x80);
  23058. }
  23059. int MidiMessage::getNoteNumber() const throw()
  23060. {
  23061. return data[1];
  23062. }
  23063. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23064. {
  23065. if (isNoteOnOrOff())
  23066. data[1] = newNoteNumber & 127;
  23067. }
  23068. uint8 MidiMessage::getVelocity() const throw()
  23069. {
  23070. if (isNoteOnOrOff())
  23071. return data[2];
  23072. else
  23073. return 0;
  23074. }
  23075. float MidiMessage::getFloatVelocity() const throw()
  23076. {
  23077. return getVelocity() * (1.0f / 127.0f);
  23078. }
  23079. void MidiMessage::setVelocity (const float newVelocity) throw()
  23080. {
  23081. if (isNoteOnOrOff())
  23082. data[2] = MidiHelpers::validVelocity (roundToInt (newVelocity * 127.0f));
  23083. }
  23084. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23085. {
  23086. if (isNoteOnOrOff())
  23087. data[2] = MidiHelpers::validVelocity (roundToInt (scaleFactor * data[2]));
  23088. }
  23089. bool MidiMessage::isAftertouch() const throw()
  23090. {
  23091. return (data[0] & 0xf0) == 0xa0;
  23092. }
  23093. int MidiMessage::getAfterTouchValue() const throw()
  23094. {
  23095. return data[2];
  23096. }
  23097. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23098. const int noteNum,
  23099. const int aftertouchValue) throw()
  23100. {
  23101. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23102. jassert (isPositiveAndBelow (noteNum, (int) 128));
  23103. jassert (isPositiveAndBelow (aftertouchValue, (int) 128));
  23104. return MidiMessage (MidiHelpers::initialByte (0xa0, channel),
  23105. noteNum & 0x7f,
  23106. aftertouchValue & 0x7f);
  23107. }
  23108. bool MidiMessage::isChannelPressure() const throw()
  23109. {
  23110. return (data[0] & 0xf0) == 0xd0;
  23111. }
  23112. int MidiMessage::getChannelPressureValue() const throw()
  23113. {
  23114. jassert (isChannelPressure());
  23115. return data[1];
  23116. }
  23117. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23118. const int pressure) throw()
  23119. {
  23120. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23121. jassert (isPositiveAndBelow (pressure, (int) 128));
  23122. return MidiMessage (MidiHelpers::initialByte (0xd0, channel), pressure & 0x7f);
  23123. }
  23124. bool MidiMessage::isProgramChange() const throw()
  23125. {
  23126. return (data[0] & 0xf0) == 0xc0;
  23127. }
  23128. int MidiMessage::getProgramChangeNumber() const throw()
  23129. {
  23130. return data[1];
  23131. }
  23132. const MidiMessage MidiMessage::programChange (const int channel,
  23133. const int programNumber) throw()
  23134. {
  23135. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23136. return MidiMessage (MidiHelpers::initialByte (0xc0, channel), programNumber & 0x7f);
  23137. }
  23138. bool MidiMessage::isPitchWheel() const throw()
  23139. {
  23140. return (data[0] & 0xf0) == 0xe0;
  23141. }
  23142. int MidiMessage::getPitchWheelValue() const throw()
  23143. {
  23144. return data[1] | (data[2] << 7);
  23145. }
  23146. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23147. const int position) throw()
  23148. {
  23149. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23150. jassert (isPositiveAndBelow (position, (int) 0x4000));
  23151. return MidiMessage (MidiHelpers::initialByte (0xe0, channel), position & 127, (position >> 7) & 127);
  23152. }
  23153. bool MidiMessage::isController() const throw()
  23154. {
  23155. return (data[0] & 0xf0) == 0xb0;
  23156. }
  23157. int MidiMessage::getControllerNumber() const throw()
  23158. {
  23159. jassert (isController());
  23160. return data[1];
  23161. }
  23162. int MidiMessage::getControllerValue() const throw()
  23163. {
  23164. jassert (isController());
  23165. return data[2];
  23166. }
  23167. const MidiMessage MidiMessage::controllerEvent (const int channel, const int controllerType, const int value) throw()
  23168. {
  23169. // the channel must be between 1 and 16 inclusive
  23170. jassert (channel > 0 && channel <= 16);
  23171. return MidiMessage (MidiHelpers::initialByte (0xb0, channel), controllerType & 127, value & 127);
  23172. }
  23173. const MidiMessage MidiMessage::noteOn (const int channel, const int noteNumber, const float velocity) throw()
  23174. {
  23175. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23176. }
  23177. const MidiMessage MidiMessage::noteOn (const int channel, const int noteNumber, const uint8 velocity) throw()
  23178. {
  23179. jassert (channel > 0 && channel <= 16);
  23180. jassert (isPositiveAndBelow (noteNumber, (int) 128));
  23181. return MidiMessage (MidiHelpers::initialByte (0x90, channel), noteNumber & 127, MidiHelpers::validVelocity (velocity));
  23182. }
  23183. const MidiMessage MidiMessage::noteOff (const int channel, const int noteNumber, uint8 velocity) throw()
  23184. {
  23185. jassert (channel > 0 && channel <= 16);
  23186. jassert (isPositiveAndBelow (noteNumber, (int) 128));
  23187. return MidiMessage (MidiHelpers::initialByte (0x80, channel), noteNumber & 127, MidiHelpers::validVelocity (velocity));
  23188. }
  23189. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23190. {
  23191. return controllerEvent (channel, 123, 0);
  23192. }
  23193. bool MidiMessage::isAllNotesOff() const throw()
  23194. {
  23195. return (data[0] & 0xf0) == 0xb0 && data[1] == 123;
  23196. }
  23197. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23198. {
  23199. return controllerEvent (channel, 120, 0);
  23200. }
  23201. bool MidiMessage::isAllSoundOff() const throw()
  23202. {
  23203. return (data[0] & 0xf0) == 0xb0 && data[1] == 120;
  23204. }
  23205. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23206. {
  23207. return controllerEvent (channel, 121, 0);
  23208. }
  23209. const MidiMessage MidiMessage::masterVolume (const float volume)
  23210. {
  23211. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23212. uint8 buf[8];
  23213. buf[0] = 0xf0;
  23214. buf[1] = 0x7f;
  23215. buf[2] = 0x7f;
  23216. buf[3] = 0x04;
  23217. buf[4] = 0x01;
  23218. buf[5] = (uint8) (vol & 0x7f);
  23219. buf[6] = (uint8) (vol >> 7);
  23220. buf[7] = 0xf7;
  23221. return MidiMessage (buf, 8);
  23222. }
  23223. bool MidiMessage::isSysEx() const throw()
  23224. {
  23225. return *data == 0xf0;
  23226. }
  23227. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23228. {
  23229. HeapBlock<uint8> m (dataSize + 2);
  23230. m[0] = 0xf0;
  23231. memcpy (m + 1, sysexData, dataSize);
  23232. m[dataSize + 1] = 0xf7;
  23233. return MidiMessage (m, dataSize + 2);
  23234. }
  23235. const uint8* MidiMessage::getSysExData() const throw()
  23236. {
  23237. return isSysEx() ? getRawData() + 1 : 0;
  23238. }
  23239. int MidiMessage::getSysExDataSize() const throw()
  23240. {
  23241. return isSysEx() ? size - 2 : 0;
  23242. }
  23243. bool MidiMessage::isMetaEvent() const throw()
  23244. {
  23245. return *data == 0xff;
  23246. }
  23247. bool MidiMessage::isActiveSense() const throw()
  23248. {
  23249. return *data == 0xfe;
  23250. }
  23251. int MidiMessage::getMetaEventType() const throw()
  23252. {
  23253. return *data != 0xff ? -1 : data[1];
  23254. }
  23255. int MidiMessage::getMetaEventLength() const throw()
  23256. {
  23257. if (*data == 0xff)
  23258. {
  23259. int n;
  23260. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23261. }
  23262. return 0;
  23263. }
  23264. const uint8* MidiMessage::getMetaEventData() const throw()
  23265. {
  23266. int n;
  23267. const uint8* d = data + 2;
  23268. readVariableLengthVal (d, n);
  23269. return d + n;
  23270. }
  23271. bool MidiMessage::isTrackMetaEvent() const throw()
  23272. {
  23273. return getMetaEventType() == 0;
  23274. }
  23275. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23276. {
  23277. return getMetaEventType() == 47;
  23278. }
  23279. bool MidiMessage::isTextMetaEvent() const throw()
  23280. {
  23281. const int t = getMetaEventType();
  23282. return t > 0 && t < 16;
  23283. }
  23284. const String MidiMessage::getTextFromTextMetaEvent() const
  23285. {
  23286. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23287. }
  23288. bool MidiMessage::isTrackNameEvent() const throw()
  23289. {
  23290. return (data[1] == 3) && (*data == 0xff);
  23291. }
  23292. bool MidiMessage::isTempoMetaEvent() const throw()
  23293. {
  23294. return (data[1] == 81) && (*data == 0xff);
  23295. }
  23296. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23297. {
  23298. return (data[1] == 0x20) && (*data == 0xff) && (data[2] == 1);
  23299. }
  23300. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23301. {
  23302. return data[3] + 1;
  23303. }
  23304. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23305. {
  23306. if (! isTempoMetaEvent())
  23307. return 0.0;
  23308. const uint8* const d = getMetaEventData();
  23309. return (((unsigned int) d[0] << 16)
  23310. | ((unsigned int) d[1] << 8)
  23311. | d[2])
  23312. / 1000000.0;
  23313. }
  23314. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23315. {
  23316. if (timeFormat > 0)
  23317. {
  23318. if (! isTempoMetaEvent())
  23319. return 0.5 / timeFormat;
  23320. return getTempoSecondsPerQuarterNote() / timeFormat;
  23321. }
  23322. else
  23323. {
  23324. const int frameCode = (-timeFormat) >> 8;
  23325. double framesPerSecond;
  23326. switch (frameCode)
  23327. {
  23328. case 24: framesPerSecond = 24.0; break;
  23329. case 25: framesPerSecond = 25.0; break;
  23330. case 29: framesPerSecond = 29.97; break;
  23331. case 30: framesPerSecond = 30.0; break;
  23332. default: framesPerSecond = 30.0; break;
  23333. }
  23334. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23335. }
  23336. }
  23337. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23338. {
  23339. uint8 d[8];
  23340. d[0] = 0xff;
  23341. d[1] = 81;
  23342. d[2] = 3;
  23343. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23344. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23345. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23346. return MidiMessage (d, 6, 0.0);
  23347. }
  23348. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23349. {
  23350. return (data[1] == 0x58) && (*data == (uint8) 0xff);
  23351. }
  23352. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23353. {
  23354. if (isTimeSignatureMetaEvent())
  23355. {
  23356. const uint8* const d = getMetaEventData();
  23357. numerator = d[0];
  23358. denominator = 1 << d[1];
  23359. }
  23360. else
  23361. {
  23362. numerator = 4;
  23363. denominator = 4;
  23364. }
  23365. }
  23366. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23367. {
  23368. uint8 d[8];
  23369. d[0] = 0xff;
  23370. d[1] = 0x58;
  23371. d[2] = 0x04;
  23372. d[3] = (uint8) numerator;
  23373. int n = 1;
  23374. int powerOfTwo = 0;
  23375. while (n < denominator)
  23376. {
  23377. n <<= 1;
  23378. ++powerOfTwo;
  23379. }
  23380. d[4] = (uint8) powerOfTwo;
  23381. d[5] = 0x01;
  23382. d[6] = 96;
  23383. return MidiMessage (d, 7, 0.0);
  23384. }
  23385. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23386. {
  23387. uint8 d[8];
  23388. d[0] = 0xff;
  23389. d[1] = 0x20;
  23390. d[2] = 0x01;
  23391. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23392. return MidiMessage (d, 4, 0.0);
  23393. }
  23394. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23395. {
  23396. return getMetaEventType() == 89;
  23397. }
  23398. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23399. {
  23400. return (int) *getMetaEventData();
  23401. }
  23402. const MidiMessage MidiMessage::endOfTrack() throw()
  23403. {
  23404. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23405. }
  23406. bool MidiMessage::isSongPositionPointer() const throw()
  23407. {
  23408. return *data == 0xf2;
  23409. }
  23410. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23411. {
  23412. return data[1] | (data[2] << 7);
  23413. }
  23414. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23415. {
  23416. return MidiMessage (0xf2,
  23417. positionInMidiBeats & 127,
  23418. (positionInMidiBeats >> 7) & 127);
  23419. }
  23420. bool MidiMessage::isMidiStart() const throw()
  23421. {
  23422. return *data == 0xfa;
  23423. }
  23424. const MidiMessage MidiMessage::midiStart() throw()
  23425. {
  23426. return MidiMessage (0xfa);
  23427. }
  23428. bool MidiMessage::isMidiContinue() const throw()
  23429. {
  23430. return *data == 0xfb;
  23431. }
  23432. const MidiMessage MidiMessage::midiContinue() throw()
  23433. {
  23434. return MidiMessage (0xfb);
  23435. }
  23436. bool MidiMessage::isMidiStop() const throw()
  23437. {
  23438. return *data == 0xfc;
  23439. }
  23440. const MidiMessage MidiMessage::midiStop() throw()
  23441. {
  23442. return MidiMessage (0xfc);
  23443. }
  23444. bool MidiMessage::isMidiClock() const throw()
  23445. {
  23446. return *data == 0xf8;
  23447. }
  23448. const MidiMessage MidiMessage::midiClock() throw()
  23449. {
  23450. return MidiMessage (0xf8);
  23451. }
  23452. bool MidiMessage::isQuarterFrame() const throw()
  23453. {
  23454. return *data == 0xf1;
  23455. }
  23456. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23457. {
  23458. return ((int) data[1]) >> 4;
  23459. }
  23460. int MidiMessage::getQuarterFrameValue() const throw()
  23461. {
  23462. return ((int) data[1]) & 0x0f;
  23463. }
  23464. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23465. const int value) throw()
  23466. {
  23467. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23468. }
  23469. bool MidiMessage::isFullFrame() const throw()
  23470. {
  23471. return data[0] == 0xf0
  23472. && data[1] == 0x7f
  23473. && size >= 10
  23474. && data[3] == 0x01
  23475. && data[4] == 0x01;
  23476. }
  23477. void MidiMessage::getFullFrameParameters (int& hours,
  23478. int& minutes,
  23479. int& seconds,
  23480. int& frames,
  23481. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23482. {
  23483. jassert (isFullFrame());
  23484. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23485. hours = data[5] & 0x1f;
  23486. minutes = data[6];
  23487. seconds = data[7];
  23488. frames = data[8];
  23489. }
  23490. const MidiMessage MidiMessage::fullFrame (const int hours,
  23491. const int minutes,
  23492. const int seconds,
  23493. const int frames,
  23494. MidiMessage::SmpteTimecodeType timecodeType)
  23495. {
  23496. uint8 d[10];
  23497. d[0] = 0xf0;
  23498. d[1] = 0x7f;
  23499. d[2] = 0x7f;
  23500. d[3] = 0x01;
  23501. d[4] = 0x01;
  23502. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23503. d[6] = (uint8) minutes;
  23504. d[7] = (uint8) seconds;
  23505. d[8] = (uint8) frames;
  23506. d[9] = 0xf7;
  23507. return MidiMessage (d, 10, 0.0);
  23508. }
  23509. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23510. {
  23511. return data[0] == 0xf0
  23512. && data[1] == 0x7f
  23513. && data[3] == 0x06
  23514. && size > 5;
  23515. }
  23516. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23517. {
  23518. jassert (isMidiMachineControlMessage());
  23519. return (MidiMachineControlCommand) data[4];
  23520. }
  23521. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23522. {
  23523. uint8 d[6];
  23524. d[0] = 0xf0;
  23525. d[1] = 0x7f;
  23526. d[2] = 0x00;
  23527. d[3] = 0x06;
  23528. d[4] = (uint8) command;
  23529. d[5] = 0xf7;
  23530. return MidiMessage (d, 6, 0.0);
  23531. }
  23532. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23533. int& minutes,
  23534. int& seconds,
  23535. int& frames) const throw()
  23536. {
  23537. if (size >= 12
  23538. && data[0] == 0xf0
  23539. && data[1] == 0x7f
  23540. && data[3] == 0x06
  23541. && data[4] == 0x44
  23542. && data[5] == 0x06
  23543. && data[6] == 0x01)
  23544. {
  23545. hours = data[7] % 24; // (that some machines send out hours > 24)
  23546. minutes = data[8];
  23547. seconds = data[9];
  23548. frames = data[10];
  23549. return true;
  23550. }
  23551. return false;
  23552. }
  23553. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23554. int minutes,
  23555. int seconds,
  23556. int frames)
  23557. {
  23558. uint8 d[12];
  23559. d[0] = 0xf0;
  23560. d[1] = 0x7f;
  23561. d[2] = 0x00;
  23562. d[3] = 0x06;
  23563. d[4] = 0x44;
  23564. d[5] = 0x06;
  23565. d[6] = 0x01;
  23566. d[7] = (uint8) hours;
  23567. d[8] = (uint8) minutes;
  23568. d[9] = (uint8) seconds;
  23569. d[10] = (uint8) frames;
  23570. d[11] = 0xf7;
  23571. return MidiMessage (d, 12, 0.0);
  23572. }
  23573. const String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  23574. {
  23575. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  23576. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  23577. if (isPositiveAndBelow (note, (int) 128))
  23578. {
  23579. String s (useSharps ? sharpNoteNames [note % 12]
  23580. : flatNoteNames [note % 12]);
  23581. if (includeOctaveNumber)
  23582. s << (note / 12 + (octaveNumForMiddleC - 5));
  23583. return s;
  23584. }
  23585. return String::empty;
  23586. }
  23587. const double MidiMessage::getMidiNoteInHertz (int noteNumber, const double frequencyOfA) throw()
  23588. {
  23589. noteNumber -= 12 * 6 + 9; // now 0 = A
  23590. return frequencyOfA * pow (2.0, noteNumber / 12.0);
  23591. }
  23592. const String MidiMessage::getGMInstrumentName (const int n)
  23593. {
  23594. const char* names[] =
  23595. {
  23596. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23597. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23598. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23599. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23600. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23601. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23602. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23603. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23604. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23605. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23606. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23607. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23608. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23609. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  23610. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  23611. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  23612. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  23613. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  23614. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  23615. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  23616. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  23617. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  23618. "Applause", "Gunshot"
  23619. };
  23620. return isPositiveAndBelow (n, (int) 128) ? names[n] : (const char*) 0;
  23621. }
  23622. const String MidiMessage::getGMInstrumentBankName (const int n)
  23623. {
  23624. const char* names[] =
  23625. {
  23626. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  23627. "Bass", "Strings", "Ensemble", "Brass",
  23628. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  23629. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  23630. };
  23631. return isPositiveAndBelow (n, (int) 16) ? names[n] : (const char*) 0;
  23632. }
  23633. const String MidiMessage::getRhythmInstrumentName (const int n)
  23634. {
  23635. const char* names[] =
  23636. {
  23637. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  23638. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  23639. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  23640. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  23641. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  23642. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  23643. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  23644. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  23645. "Mute Triangle", "Open Triangle"
  23646. };
  23647. return (n >= 35 && n <= 81) ? names [n - 35] : (const char*) 0;
  23648. }
  23649. const String MidiMessage::getControllerName (const int n)
  23650. {
  23651. const char* names[] =
  23652. {
  23653. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  23654. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  23655. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  23656. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  23657. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  23658. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  23659. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  23660. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  23661. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  23662. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23663. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  23664. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  23665. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  23666. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  23667. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  23668. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  23669. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  23670. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  23671. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  23672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  23673. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  23674. "Poly Operation"
  23675. };
  23676. return isPositiveAndBelow (n, (int) 128) ? names[n] : (const char*) 0;
  23677. }
  23678. END_JUCE_NAMESPACE
  23679. /*** End of inlined file: juce_MidiMessage.cpp ***/
  23680. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  23681. BEGIN_JUCE_NAMESPACE
  23682. MidiMessageCollector::MidiMessageCollector()
  23683. : lastCallbackTime (0),
  23684. sampleRate (44100.0001)
  23685. {
  23686. }
  23687. MidiMessageCollector::~MidiMessageCollector()
  23688. {
  23689. }
  23690. void MidiMessageCollector::reset (const double sampleRate_)
  23691. {
  23692. jassert (sampleRate_ > 0);
  23693. const ScopedLock sl (midiCallbackLock);
  23694. sampleRate = sampleRate_;
  23695. incomingMessages.clear();
  23696. lastCallbackTime = Time::getMillisecondCounterHiRes();
  23697. }
  23698. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  23699. {
  23700. // you need to call reset() to set the correct sample rate before using this object
  23701. jassert (sampleRate != 44100.0001);
  23702. // the messages that come in here need to be time-stamped correctly - see MidiInput
  23703. // for details of what the number should be.
  23704. jassert (message.getTimeStamp() != 0);
  23705. const ScopedLock sl (midiCallbackLock);
  23706. const int sampleNumber
  23707. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23708. incomingMessages.addEvent (message, sampleNumber);
  23709. // if the messages don't get used for over a second, we'd better
  23710. // get rid of any old ones to avoid the queue getting too big
  23711. if (sampleNumber > sampleRate)
  23712. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23713. }
  23714. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23715. const int numSamples)
  23716. {
  23717. // you need to call reset() to set the correct sample rate before using this object
  23718. jassert (sampleRate != 44100.0001);
  23719. const double timeNow = Time::getMillisecondCounterHiRes();
  23720. const double msElapsed = timeNow - lastCallbackTime;
  23721. const ScopedLock sl (midiCallbackLock);
  23722. lastCallbackTime = timeNow;
  23723. if (! incomingMessages.isEmpty())
  23724. {
  23725. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23726. int startSample = 0;
  23727. int scale = 1 << 16;
  23728. const uint8* midiData;
  23729. int numBytes, samplePosition;
  23730. MidiBuffer::Iterator iter (incomingMessages);
  23731. if (numSourceSamples > numSamples)
  23732. {
  23733. // if our list of events is longer than the buffer we're being
  23734. // asked for, scale them down to squeeze them all in..
  23735. const int maxBlockLengthToUse = numSamples << 5;
  23736. if (numSourceSamples > maxBlockLengthToUse)
  23737. {
  23738. startSample = numSourceSamples - maxBlockLengthToUse;
  23739. numSourceSamples = maxBlockLengthToUse;
  23740. iter.setNextSamplePosition (startSample);
  23741. }
  23742. scale = (numSamples << 10) / numSourceSamples;
  23743. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23744. {
  23745. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23746. destBuffer.addEvent (midiData, numBytes,
  23747. jlimit (0, numSamples - 1, samplePosition));
  23748. }
  23749. }
  23750. else
  23751. {
  23752. // if our event list is shorter than the number we need, put them
  23753. // towards the end of the buffer
  23754. startSample = numSamples - numSourceSamples;
  23755. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23756. {
  23757. destBuffer.addEvent (midiData, numBytes,
  23758. jlimit (0, numSamples - 1, samplePosition + startSample));
  23759. }
  23760. }
  23761. incomingMessages.clear();
  23762. }
  23763. }
  23764. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23765. {
  23766. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23767. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23768. addMessageToQueue (m);
  23769. }
  23770. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23771. {
  23772. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23773. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23774. addMessageToQueue (m);
  23775. }
  23776. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23777. {
  23778. addMessageToQueue (message);
  23779. }
  23780. END_JUCE_NAMESPACE
  23781. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23782. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23783. BEGIN_JUCE_NAMESPACE
  23784. MidiMessageSequence::MidiMessageSequence()
  23785. {
  23786. }
  23787. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23788. {
  23789. list.ensureStorageAllocated (other.list.size());
  23790. for (int i = 0; i < other.list.size(); ++i)
  23791. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23792. }
  23793. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23794. {
  23795. MidiMessageSequence otherCopy (other);
  23796. swapWith (otherCopy);
  23797. return *this;
  23798. }
  23799. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23800. {
  23801. list.swapWithArray (other.list);
  23802. }
  23803. MidiMessageSequence::~MidiMessageSequence()
  23804. {
  23805. }
  23806. void MidiMessageSequence::clear()
  23807. {
  23808. list.clear();
  23809. }
  23810. int MidiMessageSequence::getNumEvents() const
  23811. {
  23812. return list.size();
  23813. }
  23814. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23815. {
  23816. return list [index];
  23817. }
  23818. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23819. {
  23820. const MidiEventHolder* const meh = list [index];
  23821. if (meh != 0 && meh->noteOffObject != 0)
  23822. return meh->noteOffObject->message.getTimeStamp();
  23823. else
  23824. return 0.0;
  23825. }
  23826. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23827. {
  23828. const MidiEventHolder* const meh = list [index];
  23829. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23830. }
  23831. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23832. {
  23833. return list.indexOf (event);
  23834. }
  23835. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23836. {
  23837. const int numEvents = list.size();
  23838. int i;
  23839. for (i = 0; i < numEvents; ++i)
  23840. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23841. break;
  23842. return i;
  23843. }
  23844. double MidiMessageSequence::getStartTime() const
  23845. {
  23846. if (list.size() > 0)
  23847. return list.getUnchecked(0)->message.getTimeStamp();
  23848. else
  23849. return 0;
  23850. }
  23851. double MidiMessageSequence::getEndTime() const
  23852. {
  23853. if (list.size() > 0)
  23854. return list.getLast()->message.getTimeStamp();
  23855. else
  23856. return 0;
  23857. }
  23858. double MidiMessageSequence::getEventTime (const int index) const
  23859. {
  23860. if (isPositiveAndBelow (index, list.size()))
  23861. return list.getUnchecked (index)->message.getTimeStamp();
  23862. return 0.0;
  23863. }
  23864. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  23865. double timeAdjustment)
  23866. {
  23867. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  23868. timeAdjustment += newMessage.getTimeStamp();
  23869. newOne->message.setTimeStamp (timeAdjustment);
  23870. int i;
  23871. for (i = list.size(); --i >= 0;)
  23872. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  23873. break;
  23874. list.insert (i + 1, newOne);
  23875. }
  23876. void MidiMessageSequence::deleteEvent (const int index,
  23877. const bool deleteMatchingNoteUp)
  23878. {
  23879. if (isPositiveAndBelow (index, list.size()))
  23880. {
  23881. if (deleteMatchingNoteUp)
  23882. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  23883. list.remove (index);
  23884. }
  23885. }
  23886. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  23887. double timeAdjustment,
  23888. double firstAllowableTime,
  23889. double endOfAllowableDestTimes)
  23890. {
  23891. firstAllowableTime -= timeAdjustment;
  23892. endOfAllowableDestTimes -= timeAdjustment;
  23893. for (int i = 0; i < other.list.size(); ++i)
  23894. {
  23895. const MidiMessage& m = other.list.getUnchecked(i)->message;
  23896. const double t = m.getTimeStamp();
  23897. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  23898. {
  23899. MidiEventHolder* const newOne = new MidiEventHolder (m);
  23900. newOne->message.setTimeStamp (timeAdjustment + t);
  23901. list.add (newOne);
  23902. }
  23903. }
  23904. sort();
  23905. }
  23906. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  23907. const MidiMessageSequence::MidiEventHolder* const second) throw()
  23908. {
  23909. const double diff = first->message.getTimeStamp()
  23910. - second->message.getTimeStamp();
  23911. return (diff > 0) - (diff < 0);
  23912. }
  23913. void MidiMessageSequence::sort()
  23914. {
  23915. list.sort (*this, true);
  23916. }
  23917. void MidiMessageSequence::updateMatchedPairs()
  23918. {
  23919. for (int i = 0; i < list.size(); ++i)
  23920. {
  23921. const MidiMessage& m1 = list.getUnchecked(i)->message;
  23922. if (m1.isNoteOn())
  23923. {
  23924. list.getUnchecked(i)->noteOffObject = 0;
  23925. const int note = m1.getNoteNumber();
  23926. const int chan = m1.getChannel();
  23927. const int len = list.size();
  23928. for (int j = i + 1; j < len; ++j)
  23929. {
  23930. const MidiMessage& m = list.getUnchecked(j)->message;
  23931. if (m.getNoteNumber() == note && m.getChannel() == chan)
  23932. {
  23933. if (m.isNoteOff())
  23934. {
  23935. list.getUnchecked(i)->noteOffObject = list[j];
  23936. break;
  23937. }
  23938. else if (m.isNoteOn())
  23939. {
  23940. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  23941. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  23942. list.getUnchecked(i)->noteOffObject = list[j];
  23943. break;
  23944. }
  23945. }
  23946. }
  23947. }
  23948. }
  23949. }
  23950. void MidiMessageSequence::addTimeToMessages (const double delta)
  23951. {
  23952. for (int i = list.size(); --i >= 0;)
  23953. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  23954. + delta);
  23955. }
  23956. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  23957. MidiMessageSequence& destSequence,
  23958. const bool alsoIncludeMetaEvents) const
  23959. {
  23960. for (int i = 0; i < list.size(); ++i)
  23961. {
  23962. const MidiMessage& mm = list.getUnchecked(i)->message;
  23963. if (mm.isForChannel (channelNumberToExtract)
  23964. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  23965. {
  23966. destSequence.addEvent (mm);
  23967. }
  23968. }
  23969. }
  23970. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  23971. {
  23972. for (int i = 0; i < list.size(); ++i)
  23973. {
  23974. const MidiMessage& mm = list.getUnchecked(i)->message;
  23975. if (mm.isSysEx())
  23976. destSequence.addEvent (mm);
  23977. }
  23978. }
  23979. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  23980. {
  23981. for (int i = list.size(); --i >= 0;)
  23982. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  23983. list.remove(i);
  23984. }
  23985. void MidiMessageSequence::deleteSysExMessages()
  23986. {
  23987. for (int i = list.size(); --i >= 0;)
  23988. if (list.getUnchecked(i)->message.isSysEx())
  23989. list.remove(i);
  23990. }
  23991. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  23992. const double time,
  23993. OwnedArray<MidiMessage>& dest)
  23994. {
  23995. bool doneProg = false;
  23996. bool donePitchWheel = false;
  23997. Array <int> doneControllers;
  23998. doneControllers.ensureStorageAllocated (32);
  23999. for (int i = list.size(); --i >= 0;)
  24000. {
  24001. const MidiMessage& mm = list.getUnchecked(i)->message;
  24002. if (mm.isForChannel (channelNumber)
  24003. && mm.getTimeStamp() <= time)
  24004. {
  24005. if (mm.isProgramChange())
  24006. {
  24007. if (! doneProg)
  24008. {
  24009. dest.add (new MidiMessage (mm, 0.0));
  24010. doneProg = true;
  24011. }
  24012. }
  24013. else if (mm.isController())
  24014. {
  24015. if (! doneControllers.contains (mm.getControllerNumber()))
  24016. {
  24017. dest.add (new MidiMessage (mm, 0.0));
  24018. doneControllers.add (mm.getControllerNumber());
  24019. }
  24020. }
  24021. else if (mm.isPitchWheel())
  24022. {
  24023. if (! donePitchWheel)
  24024. {
  24025. dest.add (new MidiMessage (mm, 0.0));
  24026. donePitchWheel = true;
  24027. }
  24028. }
  24029. }
  24030. }
  24031. }
  24032. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24033. : message (message_),
  24034. noteOffObject (0)
  24035. {
  24036. }
  24037. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24038. {
  24039. }
  24040. END_JUCE_NAMESPACE
  24041. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24042. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24043. BEGIN_JUCE_NAMESPACE
  24044. AudioPluginFormat::AudioPluginFormat() throw()
  24045. {
  24046. }
  24047. AudioPluginFormat::~AudioPluginFormat()
  24048. {
  24049. }
  24050. END_JUCE_NAMESPACE
  24051. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24052. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24053. BEGIN_JUCE_NAMESPACE
  24054. AudioPluginFormatManager::AudioPluginFormatManager()
  24055. {
  24056. }
  24057. AudioPluginFormatManager::~AudioPluginFormatManager()
  24058. {
  24059. clearSingletonInstance();
  24060. }
  24061. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24062. void AudioPluginFormatManager::addDefaultFormats()
  24063. {
  24064. #if JUCE_DEBUG
  24065. // you should only call this method once!
  24066. for (int i = formats.size(); --i >= 0;)
  24067. {
  24068. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24069. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24070. #endif
  24071. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24072. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24073. #endif
  24074. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24075. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24076. #endif
  24077. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24078. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24079. #endif
  24080. }
  24081. #endif
  24082. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24083. formats.add (new AudioUnitPluginFormat());
  24084. #endif
  24085. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24086. formats.add (new VSTPluginFormat());
  24087. #endif
  24088. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24089. formats.add (new DirectXPluginFormat());
  24090. #endif
  24091. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24092. formats.add (new LADSPAPluginFormat());
  24093. #endif
  24094. }
  24095. int AudioPluginFormatManager::getNumFormats()
  24096. {
  24097. return formats.size();
  24098. }
  24099. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24100. {
  24101. return formats [index];
  24102. }
  24103. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24104. {
  24105. formats.add (format);
  24106. }
  24107. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24108. String& errorMessage) const
  24109. {
  24110. AudioPluginInstance* result = 0;
  24111. for (int i = 0; i < formats.size(); ++i)
  24112. {
  24113. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24114. if (result != 0)
  24115. break;
  24116. }
  24117. if (result == 0)
  24118. {
  24119. if (! doesPluginStillExist (description))
  24120. errorMessage = TRANS ("This plug-in file no longer exists");
  24121. else
  24122. errorMessage = TRANS ("This plug-in failed to load correctly");
  24123. }
  24124. return result;
  24125. }
  24126. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24127. {
  24128. for (int i = 0; i < formats.size(); ++i)
  24129. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24130. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24131. return false;
  24132. }
  24133. END_JUCE_NAMESPACE
  24134. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24135. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24136. #define JUCE_PLUGIN_HOST 1
  24137. BEGIN_JUCE_NAMESPACE
  24138. AudioPluginInstance::AudioPluginInstance()
  24139. {
  24140. }
  24141. AudioPluginInstance::~AudioPluginInstance()
  24142. {
  24143. }
  24144. void* AudioPluginInstance::getPlatformSpecificData()
  24145. {
  24146. return 0;
  24147. }
  24148. END_JUCE_NAMESPACE
  24149. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24150. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24151. BEGIN_JUCE_NAMESPACE
  24152. KnownPluginList::KnownPluginList()
  24153. {
  24154. }
  24155. KnownPluginList::~KnownPluginList()
  24156. {
  24157. }
  24158. void KnownPluginList::clear()
  24159. {
  24160. if (types.size() > 0)
  24161. {
  24162. types.clear();
  24163. sendChangeMessage();
  24164. }
  24165. }
  24166. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24167. {
  24168. for (int i = 0; i < types.size(); ++i)
  24169. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24170. return types.getUnchecked(i);
  24171. return 0;
  24172. }
  24173. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24174. {
  24175. for (int i = 0; i < types.size(); ++i)
  24176. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24177. return types.getUnchecked(i);
  24178. return 0;
  24179. }
  24180. bool KnownPluginList::addType (const PluginDescription& type)
  24181. {
  24182. for (int i = types.size(); --i >= 0;)
  24183. {
  24184. if (types.getUnchecked(i)->isDuplicateOf (type))
  24185. {
  24186. // strange - found a duplicate plugin with different info..
  24187. jassert (types.getUnchecked(i)->name == type.name);
  24188. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24189. *types.getUnchecked(i) = type;
  24190. return false;
  24191. }
  24192. }
  24193. types.add (new PluginDescription (type));
  24194. sendChangeMessage();
  24195. return true;
  24196. }
  24197. void KnownPluginList::removeType (const int index)
  24198. {
  24199. types.remove (index);
  24200. sendChangeMessage();
  24201. }
  24202. namespace
  24203. {
  24204. const Time getPluginFileModTime (const String& fileOrIdentifier)
  24205. {
  24206. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24207. return File (fileOrIdentifier).getLastModificationTime();
  24208. return Time();
  24209. }
  24210. bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24211. {
  24212. return t1 != t2 || t1 == Time();
  24213. }
  24214. }
  24215. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24216. {
  24217. if (getTypeForFile (fileOrIdentifier) == 0)
  24218. return false;
  24219. for (int i = types.size(); --i >= 0;)
  24220. {
  24221. const PluginDescription* const d = types.getUnchecked(i);
  24222. if (d->fileOrIdentifier == fileOrIdentifier
  24223. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24224. {
  24225. return false;
  24226. }
  24227. }
  24228. return true;
  24229. }
  24230. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24231. const bool dontRescanIfAlreadyInList,
  24232. OwnedArray <PluginDescription>& typesFound,
  24233. AudioPluginFormat& format)
  24234. {
  24235. bool addedOne = false;
  24236. if (dontRescanIfAlreadyInList
  24237. && getTypeForFile (fileOrIdentifier) != 0)
  24238. {
  24239. bool needsRescanning = false;
  24240. for (int i = types.size(); --i >= 0;)
  24241. {
  24242. const PluginDescription* const d = types.getUnchecked(i);
  24243. if (d->fileOrIdentifier == fileOrIdentifier)
  24244. {
  24245. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24246. needsRescanning = true;
  24247. else
  24248. typesFound.add (new PluginDescription (*d));
  24249. }
  24250. }
  24251. if (! needsRescanning)
  24252. return false;
  24253. }
  24254. OwnedArray <PluginDescription> found;
  24255. format.findAllTypesForFile (found, fileOrIdentifier);
  24256. for (int i = 0; i < found.size(); ++i)
  24257. {
  24258. PluginDescription* const desc = found.getUnchecked(i);
  24259. jassert (desc != 0);
  24260. if (addType (*desc))
  24261. addedOne = true;
  24262. typesFound.add (new PluginDescription (*desc));
  24263. }
  24264. return addedOne;
  24265. }
  24266. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24267. OwnedArray <PluginDescription>& typesFound)
  24268. {
  24269. for (int i = 0; i < files.size(); ++i)
  24270. {
  24271. bool loaded = false;
  24272. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24273. {
  24274. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24275. if (scanAndAddFile (files[i], true, typesFound, *format))
  24276. loaded = true;
  24277. }
  24278. if (! loaded)
  24279. {
  24280. const File f (files[i]);
  24281. if (f.isDirectory())
  24282. {
  24283. StringArray s;
  24284. {
  24285. Array<File> subFiles;
  24286. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24287. for (int j = 0; j < subFiles.size(); ++j)
  24288. s.add (subFiles.getReference(j).getFullPathName());
  24289. }
  24290. scanAndAddDragAndDroppedFiles (s, typesFound);
  24291. }
  24292. }
  24293. }
  24294. }
  24295. class PluginSorter
  24296. {
  24297. public:
  24298. KnownPluginList::SortMethod method;
  24299. PluginSorter() throw() {}
  24300. int compareElements (const PluginDescription* const first,
  24301. const PluginDescription* const second) const
  24302. {
  24303. int diff = 0;
  24304. if (method == KnownPluginList::sortByCategory)
  24305. diff = first->category.compareLexicographically (second->category);
  24306. else if (method == KnownPluginList::sortByManufacturer)
  24307. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24308. else if (method == KnownPluginList::sortByFileSystemLocation)
  24309. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24310. .upToLastOccurrenceOf ("/", false, false)
  24311. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24312. .upToLastOccurrenceOf ("/", false, false));
  24313. if (diff == 0)
  24314. diff = first->name.compareLexicographically (second->name);
  24315. return diff;
  24316. }
  24317. };
  24318. void KnownPluginList::sort (const SortMethod method)
  24319. {
  24320. if (method != defaultOrder)
  24321. {
  24322. PluginSorter sorter;
  24323. sorter.method = method;
  24324. types.sort (sorter, true);
  24325. sendChangeMessage();
  24326. }
  24327. }
  24328. XmlElement* KnownPluginList::createXml() const
  24329. {
  24330. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24331. for (int i = 0; i < types.size(); ++i)
  24332. e->addChildElement (types.getUnchecked(i)->createXml());
  24333. return e;
  24334. }
  24335. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24336. {
  24337. clear();
  24338. if (xml.hasTagName ("KNOWNPLUGINS"))
  24339. {
  24340. forEachXmlChildElement (xml, e)
  24341. {
  24342. PluginDescription info;
  24343. if (info.loadFromXml (*e))
  24344. addType (info);
  24345. }
  24346. }
  24347. }
  24348. const int menuIdBase = 0x324503f4;
  24349. // This is used to turn a bunch of paths into a nested menu structure.
  24350. struct PluginFilesystemTree
  24351. {
  24352. private:
  24353. String folder;
  24354. OwnedArray <PluginFilesystemTree> subFolders;
  24355. Array <PluginDescription*> plugins;
  24356. void addPlugin (PluginDescription* const pd, const String& path)
  24357. {
  24358. if (path.isEmpty())
  24359. {
  24360. plugins.add (pd);
  24361. }
  24362. else
  24363. {
  24364. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24365. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24366. for (int i = subFolders.size(); --i >= 0;)
  24367. {
  24368. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24369. {
  24370. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24371. return;
  24372. }
  24373. }
  24374. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24375. newFolder->folder = firstSubFolder;
  24376. subFolders.add (newFolder);
  24377. newFolder->addPlugin (pd, remainingPath);
  24378. }
  24379. }
  24380. // removes any deeply nested folders that don't contain any actual plugins
  24381. void optimise()
  24382. {
  24383. for (int i = subFolders.size(); --i >= 0;)
  24384. {
  24385. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24386. sub->optimise();
  24387. if (sub->plugins.size() == 0)
  24388. {
  24389. for (int j = 0; j < sub->subFolders.size(); ++j)
  24390. subFolders.add (sub->subFolders.getUnchecked(j));
  24391. sub->subFolders.clear (false);
  24392. subFolders.remove (i);
  24393. }
  24394. }
  24395. }
  24396. public:
  24397. void buildTree (const Array <PluginDescription*>& allPlugins)
  24398. {
  24399. for (int i = 0; i < allPlugins.size(); ++i)
  24400. {
  24401. String path (allPlugins.getUnchecked(i)
  24402. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24403. .upToLastOccurrenceOf ("/", false, false));
  24404. if (path.substring (1, 2) == ":")
  24405. path = path.substring (2);
  24406. addPlugin (allPlugins.getUnchecked(i), path);
  24407. }
  24408. optimise();
  24409. }
  24410. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24411. {
  24412. int i;
  24413. for (i = 0; i < subFolders.size(); ++i)
  24414. {
  24415. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24416. PopupMenu subMenu;
  24417. sub->addToMenu (subMenu, allPlugins);
  24418. #if JUCE_MAC
  24419. // avoid the special AU formatting nonsense on Mac..
  24420. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24421. #else
  24422. m.addSubMenu (sub->folder, subMenu);
  24423. #endif
  24424. }
  24425. for (i = 0; i < plugins.size(); ++i)
  24426. {
  24427. PluginDescription* const plugin = plugins.getUnchecked(i);
  24428. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24429. plugin->name, true, false);
  24430. }
  24431. }
  24432. };
  24433. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24434. {
  24435. Array <PluginDescription*> sorted;
  24436. {
  24437. PluginSorter sorter;
  24438. sorter.method = sortMethod;
  24439. for (int i = 0; i < types.size(); ++i)
  24440. sorted.addSorted (sorter, types.getUnchecked(i));
  24441. }
  24442. if (sortMethod == sortByCategory
  24443. || sortMethod == sortByManufacturer)
  24444. {
  24445. String lastSubMenuName;
  24446. PopupMenu sub;
  24447. for (int i = 0; i < sorted.size(); ++i)
  24448. {
  24449. const PluginDescription* const pd = sorted.getUnchecked(i);
  24450. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24451. : pd->manufacturerName);
  24452. if (! thisSubMenuName.containsNonWhitespaceChars())
  24453. thisSubMenuName = "Other";
  24454. if (thisSubMenuName != lastSubMenuName)
  24455. {
  24456. if (sub.getNumItems() > 0)
  24457. {
  24458. menu.addSubMenu (lastSubMenuName, sub);
  24459. sub.clear();
  24460. }
  24461. lastSubMenuName = thisSubMenuName;
  24462. }
  24463. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24464. }
  24465. if (sub.getNumItems() > 0)
  24466. menu.addSubMenu (lastSubMenuName, sub);
  24467. }
  24468. else if (sortMethod == sortByFileSystemLocation)
  24469. {
  24470. PluginFilesystemTree root;
  24471. root.buildTree (sorted);
  24472. root.addToMenu (menu, types);
  24473. }
  24474. else
  24475. {
  24476. for (int i = 0; i < sorted.size(); ++i)
  24477. {
  24478. const PluginDescription* const pd = sorted.getUnchecked(i);
  24479. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24480. }
  24481. }
  24482. }
  24483. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24484. {
  24485. const int i = menuResultCode - menuIdBase;
  24486. return isPositiveAndBelow (i, types.size()) ? i : -1;
  24487. }
  24488. END_JUCE_NAMESPACE
  24489. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24490. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24491. BEGIN_JUCE_NAMESPACE
  24492. PluginDescription::PluginDescription()
  24493. : uid (0),
  24494. isInstrument (false),
  24495. numInputChannels (0),
  24496. numOutputChannels (0)
  24497. {
  24498. }
  24499. PluginDescription::~PluginDescription()
  24500. {
  24501. }
  24502. PluginDescription::PluginDescription (const PluginDescription& other)
  24503. : name (other.name),
  24504. descriptiveName (other.descriptiveName),
  24505. pluginFormatName (other.pluginFormatName),
  24506. category (other.category),
  24507. manufacturerName (other.manufacturerName),
  24508. version (other.version),
  24509. fileOrIdentifier (other.fileOrIdentifier),
  24510. lastFileModTime (other.lastFileModTime),
  24511. uid (other.uid),
  24512. isInstrument (other.isInstrument),
  24513. numInputChannels (other.numInputChannels),
  24514. numOutputChannels (other.numOutputChannels)
  24515. {
  24516. }
  24517. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24518. {
  24519. name = other.name;
  24520. descriptiveName = other.descriptiveName;
  24521. pluginFormatName = other.pluginFormatName;
  24522. category = other.category;
  24523. manufacturerName = other.manufacturerName;
  24524. version = other.version;
  24525. fileOrIdentifier = other.fileOrIdentifier;
  24526. uid = other.uid;
  24527. isInstrument = other.isInstrument;
  24528. lastFileModTime = other.lastFileModTime;
  24529. numInputChannels = other.numInputChannels;
  24530. numOutputChannels = other.numOutputChannels;
  24531. return *this;
  24532. }
  24533. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24534. {
  24535. return fileOrIdentifier == other.fileOrIdentifier
  24536. && uid == other.uid;
  24537. }
  24538. const String PluginDescription::createIdentifierString() const
  24539. {
  24540. return pluginFormatName
  24541. + "-" + name
  24542. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24543. + "-" + String::toHexString (uid);
  24544. }
  24545. XmlElement* PluginDescription::createXml() const
  24546. {
  24547. XmlElement* const e = new XmlElement ("PLUGIN");
  24548. e->setAttribute ("name", name);
  24549. if (descriptiveName != name)
  24550. e->setAttribute ("descriptiveName", descriptiveName);
  24551. e->setAttribute ("format", pluginFormatName);
  24552. e->setAttribute ("category", category);
  24553. e->setAttribute ("manufacturer", manufacturerName);
  24554. e->setAttribute ("version", version);
  24555. e->setAttribute ("file", fileOrIdentifier);
  24556. e->setAttribute ("uid", String::toHexString (uid));
  24557. e->setAttribute ("isInstrument", isInstrument);
  24558. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24559. e->setAttribute ("numInputs", numInputChannels);
  24560. e->setAttribute ("numOutputs", numOutputChannels);
  24561. return e;
  24562. }
  24563. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24564. {
  24565. if (xml.hasTagName ("PLUGIN"))
  24566. {
  24567. name = xml.getStringAttribute ("name");
  24568. descriptiveName = xml.getStringAttribute ("name", name);
  24569. pluginFormatName = xml.getStringAttribute ("format");
  24570. category = xml.getStringAttribute ("category");
  24571. manufacturerName = xml.getStringAttribute ("manufacturer");
  24572. version = xml.getStringAttribute ("version");
  24573. fileOrIdentifier = xml.getStringAttribute ("file");
  24574. uid = xml.getStringAttribute ("uid").getHexValue32();
  24575. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24576. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24577. numInputChannels = xml.getIntAttribute ("numInputs");
  24578. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24579. return true;
  24580. }
  24581. return false;
  24582. }
  24583. END_JUCE_NAMESPACE
  24584. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24585. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24586. BEGIN_JUCE_NAMESPACE
  24587. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24588. AudioPluginFormat& formatToLookFor,
  24589. FileSearchPath directoriesToSearch,
  24590. const bool recursive,
  24591. const File& deadMansPedalFile_)
  24592. : list (listToAddTo),
  24593. format (formatToLookFor),
  24594. deadMansPedalFile (deadMansPedalFile_),
  24595. nextIndex (0),
  24596. progress (0)
  24597. {
  24598. directoriesToSearch.removeRedundantPaths();
  24599. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24600. // If any plugins have crashed recently when being loaded, move them to the
  24601. // end of the list to give the others a chance to load correctly..
  24602. const StringArray crashedPlugins (getDeadMansPedalFile());
  24603. for (int i = 0; i < crashedPlugins.size(); ++i)
  24604. {
  24605. const String f = crashedPlugins[i];
  24606. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24607. if (f == filesOrIdentifiersToScan[j])
  24608. filesOrIdentifiersToScan.move (j, -1);
  24609. }
  24610. }
  24611. PluginDirectoryScanner::~PluginDirectoryScanner()
  24612. {
  24613. }
  24614. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24615. {
  24616. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24617. }
  24618. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24619. {
  24620. String file (filesOrIdentifiersToScan [nextIndex]);
  24621. if (file.isNotEmpty() && ! list.isListingUpToDate (file))
  24622. {
  24623. OwnedArray <PluginDescription> typesFound;
  24624. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  24625. StringArray crashedPlugins (getDeadMansPedalFile());
  24626. crashedPlugins.removeString (file);
  24627. crashedPlugins.add (file);
  24628. setDeadMansPedalFile (crashedPlugins);
  24629. list.scanAndAddFile (file,
  24630. dontRescanIfAlreadyInList,
  24631. typesFound,
  24632. format);
  24633. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  24634. crashedPlugins.removeString (file);
  24635. setDeadMansPedalFile (crashedPlugins);
  24636. if (typesFound.size() == 0)
  24637. failedFiles.add (file);
  24638. }
  24639. return skipNextFile();
  24640. }
  24641. bool PluginDirectoryScanner::skipNextFile()
  24642. {
  24643. if (nextIndex >= filesOrIdentifiersToScan.size())
  24644. return false;
  24645. progress = ++nextIndex / (float) filesOrIdentifiersToScan.size();
  24646. return nextIndex < filesOrIdentifiersToScan.size();
  24647. }
  24648. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  24649. {
  24650. StringArray lines;
  24651. if (deadMansPedalFile != File::nonexistent)
  24652. {
  24653. lines.addLines (deadMansPedalFile.loadFileAsString());
  24654. lines.removeEmptyStrings();
  24655. }
  24656. return lines;
  24657. }
  24658. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  24659. {
  24660. if (deadMansPedalFile != File::nonexistent)
  24661. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  24662. }
  24663. END_JUCE_NAMESPACE
  24664. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24665. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  24666. BEGIN_JUCE_NAMESPACE
  24667. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  24668. const File& deadMansPedalFile_,
  24669. PropertiesFile* const propertiesToUse_)
  24670. : list (listToEdit),
  24671. deadMansPedalFile (deadMansPedalFile_),
  24672. optionsButton ("Options..."),
  24673. propertiesToUse (propertiesToUse_)
  24674. {
  24675. listBox.setModel (this);
  24676. addAndMakeVisible (&listBox);
  24677. addAndMakeVisible (&optionsButton);
  24678. optionsButton.addListener (this);
  24679. optionsButton.setTriggeredOnMouseDown (true);
  24680. setSize (400, 600);
  24681. list.addChangeListener (this);
  24682. changeListenerCallback (0);
  24683. }
  24684. PluginListComponent::~PluginListComponent()
  24685. {
  24686. list.removeChangeListener (this);
  24687. }
  24688. void PluginListComponent::resized()
  24689. {
  24690. listBox.setBounds (0, 0, getWidth(), getHeight() - 30);
  24691. optionsButton.changeWidthToFitText (24);
  24692. optionsButton.setTopLeftPosition (8, getHeight() - 28);
  24693. }
  24694. void PluginListComponent::changeListenerCallback (ChangeBroadcaster*)
  24695. {
  24696. listBox.updateContent();
  24697. listBox.repaint();
  24698. }
  24699. int PluginListComponent::getNumRows()
  24700. {
  24701. return list.getNumTypes();
  24702. }
  24703. void PluginListComponent::paintListBoxItem (int row,
  24704. Graphics& g,
  24705. int width, int height,
  24706. bool rowIsSelected)
  24707. {
  24708. if (rowIsSelected)
  24709. g.fillAll (findColour (TextEditor::highlightColourId));
  24710. const PluginDescription* const pd = list.getType (row);
  24711. if (pd != 0)
  24712. {
  24713. GlyphArrangement ga;
  24714. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  24715. g.setColour (Colours::black);
  24716. ga.draw (g);
  24717. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  24718. String desc;
  24719. desc << pd->pluginFormatName
  24720. << (pd->isInstrument ? " instrument" : " effect")
  24721. << " - "
  24722. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24723. << " / "
  24724. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24725. if (pd->manufacturerName.isNotEmpty())
  24726. desc << " - " << pd->manufacturerName;
  24727. if (pd->version.isNotEmpty())
  24728. desc << " - " << pd->version;
  24729. if (pd->category.isNotEmpty())
  24730. desc << " - category: '" << pd->category << '\'';
  24731. g.setColour (Colours::grey);
  24732. ga.clear();
  24733. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24734. ga.draw (g);
  24735. }
  24736. }
  24737. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24738. {
  24739. list.removeType (lastRowSelected);
  24740. }
  24741. void PluginListComponent::buttonClicked (Button* button)
  24742. {
  24743. if (button == &optionsButton)
  24744. {
  24745. PopupMenu menu;
  24746. menu.addItem (1, TRANS("Clear list"));
  24747. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox.getNumSelectedRows() > 0);
  24748. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox.getNumSelectedRows() > 0);
  24749. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24750. menu.addSeparator();
  24751. menu.addItem (2, TRANS("Sort alphabetically"));
  24752. menu.addItem (3, TRANS("Sort by category"));
  24753. menu.addItem (4, TRANS("Sort by manufacturer"));
  24754. menu.addSeparator();
  24755. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24756. {
  24757. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24758. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24759. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24760. }
  24761. const int r = menu.showAt (&optionsButton);
  24762. if (r == 1)
  24763. {
  24764. list.clear();
  24765. }
  24766. else if (r == 2)
  24767. {
  24768. list.sort (KnownPluginList::sortAlphabetically);
  24769. }
  24770. else if (r == 3)
  24771. {
  24772. list.sort (KnownPluginList::sortByCategory);
  24773. }
  24774. else if (r == 4)
  24775. {
  24776. list.sort (KnownPluginList::sortByManufacturer);
  24777. }
  24778. else if (r == 5)
  24779. {
  24780. const SparseSet <int> selected (listBox.getSelectedRows());
  24781. for (int i = list.getNumTypes(); --i >= 0;)
  24782. if (selected.contains (i))
  24783. list.removeType (i);
  24784. }
  24785. else if (r == 6)
  24786. {
  24787. const PluginDescription* const desc = list.getType (listBox.getSelectedRow());
  24788. if (desc != 0)
  24789. {
  24790. if (File (desc->fileOrIdentifier).existsAsFile())
  24791. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24792. }
  24793. }
  24794. else if (r == 7)
  24795. {
  24796. for (int i = list.getNumTypes(); --i >= 0;)
  24797. {
  24798. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24799. {
  24800. list.removeType (i);
  24801. }
  24802. }
  24803. }
  24804. else if (r != 0)
  24805. {
  24806. typeToScan = r - 10;
  24807. startTimer (1);
  24808. }
  24809. }
  24810. }
  24811. void PluginListComponent::timerCallback()
  24812. {
  24813. stopTimer();
  24814. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24815. }
  24816. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24817. {
  24818. return true;
  24819. }
  24820. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24821. {
  24822. OwnedArray <PluginDescription> typesFound;
  24823. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24824. }
  24825. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24826. {
  24827. if (format == 0)
  24828. return;
  24829. FileSearchPath path (format->getDefaultLocationsToSearch());
  24830. if (propertiesToUse != 0)
  24831. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24832. {
  24833. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24834. FileSearchPathListComponent pathList;
  24835. pathList.setSize (500, 300);
  24836. pathList.setPath (path);
  24837. aw.addCustomComponent (&pathList);
  24838. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24839. aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
  24840. if (aw.runModalLoop() == 0)
  24841. return;
  24842. path = pathList.getPath();
  24843. }
  24844. if (propertiesToUse != 0)
  24845. {
  24846. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24847. propertiesToUse->saveIfNeeded();
  24848. }
  24849. double progress = 0.0;
  24850. AlertWindow aw (TRANS("Scanning for plugins..."),
  24851. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24852. aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
  24853. aw.addProgressBarComponent (progress);
  24854. aw.enterModalState();
  24855. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24856. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24857. for (;;)
  24858. {
  24859. aw.setMessage (TRANS("Testing:\n\n")
  24860. + scanner.getNextPluginFileThatWillBeScanned());
  24861. MessageManager::getInstance()->runDispatchLoopUntil (20);
  24862. if (! scanner.scanNextFile (true))
  24863. break;
  24864. if (! aw.isCurrentlyModal())
  24865. break;
  24866. progress = scanner.getProgress();
  24867. }
  24868. if (scanner.getFailedFiles().size() > 0)
  24869. {
  24870. StringArray shortNames;
  24871. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  24872. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  24873. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  24874. TRANS("Scan complete"),
  24875. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  24876. + shortNames.joinIntoString (", "));
  24877. }
  24878. }
  24879. END_JUCE_NAMESPACE
  24880. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  24881. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  24882. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  24883. #include <AudioUnit/AudioUnit.h>
  24884. #include <AudioUnit/AUCocoaUIView.h>
  24885. #include <CoreAudioKit/AUGenericView.h>
  24886. #if JUCE_SUPPORT_CARBON
  24887. #include <AudioToolbox/AudioUnitUtilities.h>
  24888. #include <AudioUnit/AudioUnitCarbonView.h>
  24889. #endif
  24890. BEGIN_JUCE_NAMESPACE
  24891. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24892. #endif
  24893. #if JUCE_MAC
  24894. // Change this to disable logging of various activities
  24895. #ifndef AU_LOGGING
  24896. #define AU_LOGGING 1
  24897. #endif
  24898. #if AU_LOGGING
  24899. #define log(a) Logger::writeToLog(a);
  24900. #else
  24901. #define log(a)
  24902. #endif
  24903. namespace AudioUnitFormatHelpers
  24904. {
  24905. static int insideCallback = 0;
  24906. const String osTypeToString (OSType type)
  24907. {
  24908. char s[4];
  24909. s[0] = (char) (((uint32) type) >> 24);
  24910. s[1] = (char) (((uint32) type) >> 16);
  24911. s[2] = (char) (((uint32) type) >> 8);
  24912. s[3] = (char) ((uint32) type);
  24913. return String (s, 4);
  24914. }
  24915. OSType stringToOSType (const String& s1)
  24916. {
  24917. const String s (s1 + " ");
  24918. return (((OSType) (unsigned char) s[0]) << 24)
  24919. | (((OSType) (unsigned char) s[1]) << 16)
  24920. | (((OSType) (unsigned char) s[2]) << 8)
  24921. | ((OSType) (unsigned char) s[3]);
  24922. }
  24923. static const char* auIdentifierPrefix = "AudioUnit:";
  24924. const String createAUPluginIdentifier (const ComponentDescription& desc)
  24925. {
  24926. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  24927. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  24928. String s (auIdentifierPrefix);
  24929. if (desc.componentType == kAudioUnitType_MusicDevice)
  24930. s << "Synths/";
  24931. else if (desc.componentType == kAudioUnitType_MusicEffect
  24932. || desc.componentType == kAudioUnitType_Effect)
  24933. s << "Effects/";
  24934. else if (desc.componentType == kAudioUnitType_Generator)
  24935. s << "Generators/";
  24936. else if (desc.componentType == kAudioUnitType_Panner)
  24937. s << "Panners/";
  24938. s << osTypeToString (desc.componentType) << ","
  24939. << osTypeToString (desc.componentSubType) << ","
  24940. << osTypeToString (desc.componentManufacturer);
  24941. return s;
  24942. }
  24943. void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  24944. {
  24945. Handle componentNameHandle = NewHandle (sizeof (void*));
  24946. Handle componentInfoHandle = NewHandle (sizeof (void*));
  24947. if (componentNameHandle != 0 && componentInfoHandle != 0)
  24948. {
  24949. ComponentDescription desc;
  24950. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  24951. {
  24952. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  24953. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  24954. if (nameString != 0 && nameString[0] != 0)
  24955. {
  24956. const String all ((const char*) nameString + 1, nameString[0]);
  24957. DBG ("name: "+ all);
  24958. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  24959. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  24960. }
  24961. if (infoString != 0 && infoString[0] != 0)
  24962. {
  24963. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  24964. }
  24965. if (name.isEmpty())
  24966. name = "<Unknown>";
  24967. }
  24968. DisposeHandle (componentNameHandle);
  24969. DisposeHandle (componentInfoHandle);
  24970. }
  24971. }
  24972. bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  24973. String& name, String& version, String& manufacturer)
  24974. {
  24975. zerostruct (desc);
  24976. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  24977. {
  24978. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  24979. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  24980. StringArray tokens;
  24981. tokens.addTokens (s, ",", String::empty);
  24982. tokens.trim();
  24983. tokens.removeEmptyStrings();
  24984. if (tokens.size() == 3)
  24985. {
  24986. desc.componentType = stringToOSType (tokens[0]);
  24987. desc.componentSubType = stringToOSType (tokens[1]);
  24988. desc.componentManufacturer = stringToOSType (tokens[2]);
  24989. ComponentRecord* comp = FindNextComponent (0, &desc);
  24990. if (comp != 0)
  24991. {
  24992. getAUDetails (comp, name, manufacturer);
  24993. return true;
  24994. }
  24995. }
  24996. }
  24997. return false;
  24998. }
  24999. }
  25000. class AudioUnitPluginWindowCarbon;
  25001. class AudioUnitPluginWindowCocoa;
  25002. class AudioUnitPluginInstance : public AudioPluginInstance
  25003. {
  25004. public:
  25005. ~AudioUnitPluginInstance();
  25006. void initialise();
  25007. // AudioPluginInstance methods:
  25008. void fillInPluginDescription (PluginDescription& desc) const
  25009. {
  25010. desc.name = pluginName;
  25011. desc.descriptiveName = pluginName;
  25012. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  25013. desc.uid = ((int) componentDesc.componentType)
  25014. ^ ((int) componentDesc.componentSubType)
  25015. ^ ((int) componentDesc.componentManufacturer);
  25016. desc.lastFileModTime = Time();
  25017. desc.pluginFormatName = "AudioUnit";
  25018. desc.category = getCategory();
  25019. desc.manufacturerName = manufacturer;
  25020. desc.version = version;
  25021. desc.numInputChannels = getNumInputChannels();
  25022. desc.numOutputChannels = getNumOutputChannels();
  25023. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25024. }
  25025. void* getPlatformSpecificData() { return audioUnit; }
  25026. const String getName() const { return pluginName; }
  25027. bool acceptsMidi() const { return wantsMidiMessages; }
  25028. bool producesMidi() const { return false; }
  25029. // AudioProcessor methods:
  25030. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25031. void releaseResources();
  25032. void processBlock (AudioSampleBuffer& buffer,
  25033. MidiBuffer& midiMessages);
  25034. bool hasEditor() const;
  25035. AudioProcessorEditor* createEditor();
  25036. const String getInputChannelName (int index) const;
  25037. bool isInputChannelStereoPair (int index) const;
  25038. const String getOutputChannelName (int index) const;
  25039. bool isOutputChannelStereoPair (int index) const;
  25040. int getNumParameters();
  25041. float getParameter (int index);
  25042. void setParameter (int index, float newValue);
  25043. const String getParameterName (int index);
  25044. const String getParameterText (int index);
  25045. bool isParameterAutomatable (int index) const;
  25046. int getNumPrograms();
  25047. int getCurrentProgram();
  25048. void setCurrentProgram (int index);
  25049. const String getProgramName (int index);
  25050. void changeProgramName (int index, const String& newName);
  25051. void getStateInformation (MemoryBlock& destData);
  25052. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25053. void setStateInformation (const void* data, int sizeInBytes);
  25054. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25055. private:
  25056. friend class AudioUnitPluginWindowCarbon;
  25057. friend class AudioUnitPluginWindowCocoa;
  25058. friend class AudioUnitPluginFormat;
  25059. ComponentDescription componentDesc;
  25060. String pluginName, manufacturer, version;
  25061. String fileOrIdentifier;
  25062. CriticalSection lock;
  25063. bool wantsMidiMessages, wasPlaying, prepared;
  25064. HeapBlock <AudioBufferList> outputBufferList;
  25065. AudioTimeStamp timeStamp;
  25066. AudioSampleBuffer* currentBuffer;
  25067. AudioUnit audioUnit;
  25068. Array <int> parameterIds;
  25069. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25070. void setPluginCallbacks();
  25071. void getParameterListFromPlugin();
  25072. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25073. const AudioTimeStamp* inTimeStamp,
  25074. UInt32 inBusNumber,
  25075. UInt32 inNumberFrames,
  25076. AudioBufferList* ioData) const;
  25077. static OSStatus renderGetInputCallback (void* inRefCon,
  25078. AudioUnitRenderActionFlags* ioActionFlags,
  25079. const AudioTimeStamp* inTimeStamp,
  25080. UInt32 inBusNumber,
  25081. UInt32 inNumberFrames,
  25082. AudioBufferList* ioData)
  25083. {
  25084. return ((AudioUnitPluginInstance*) inRefCon)
  25085. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25086. }
  25087. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25088. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25089. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25090. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25091. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25092. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25093. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25094. {
  25095. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25096. }
  25097. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25098. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25099. Float64* outCurrentMeasureDownBeat)
  25100. {
  25101. return ((AudioUnitPluginInstance*) inHostUserData)
  25102. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25103. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25104. }
  25105. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25106. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25107. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25108. {
  25109. return ((AudioUnitPluginInstance*) inHostUserData)
  25110. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25111. outCurrentSampleInTimeLine, outIsCycling,
  25112. outCycleStartBeat, outCycleEndBeat);
  25113. }
  25114. void getNumChannels (int& numIns, int& numOuts)
  25115. {
  25116. numIns = 0;
  25117. numOuts = 0;
  25118. AUChannelInfo supportedChannels [128];
  25119. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25120. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25121. 0, supportedChannels, &supportedChannelsSize) == noErr
  25122. && supportedChannelsSize > 0)
  25123. {
  25124. int explicitNumIns = 0;
  25125. int explicitNumOuts = 0;
  25126. int maximumNumIns = 0;
  25127. int maximumNumOuts = 0;
  25128. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25129. {
  25130. const int inChannels = (int) supportedChannels[i].inChannels;
  25131. const int outChannels = (int) supportedChannels[i].outChannels;
  25132. if (inChannels < 0)
  25133. maximumNumIns = jmin (maximumNumIns, inChannels);
  25134. else
  25135. explicitNumIns = jmax (explicitNumIns, inChannels);
  25136. if (outChannels < 0)
  25137. maximumNumOuts = jmin (maximumNumOuts, outChannels);
  25138. else
  25139. explicitNumOuts = jmax (explicitNumOuts, outChannels);
  25140. }
  25141. if ((maximumNumIns == -1 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, as long as they match)
  25142. || (maximumNumIns == -2 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, even if they don't match)
  25143. || (maximumNumIns == -1 && maximumNumOuts == -2))
  25144. {
  25145. numIns = numOuts = 2;
  25146. }
  25147. else
  25148. {
  25149. numIns = explicitNumIns;
  25150. numOuts = explicitNumOuts;
  25151. if (maximumNumIns == -1 || (maximumNumIns < 0 && explicitNumIns <= -maximumNumIns))
  25152. numIns = 2;
  25153. if (maximumNumOuts == -1 || (maximumNumOuts < 0 && explicitNumOuts <= -maximumNumOuts))
  25154. numOuts = 2;
  25155. }
  25156. }
  25157. else
  25158. {
  25159. // (this really means the plugin will take any number of ins/outs as long
  25160. // as they are the same)
  25161. numIns = numOuts = 2;
  25162. }
  25163. }
  25164. const String getCategory() const;
  25165. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25166. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginInstance);
  25167. };
  25168. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25169. : fileOrIdentifier (fileOrIdentifier),
  25170. wantsMidiMessages (false), wasPlaying (false), prepared (false),
  25171. currentBuffer (0),
  25172. audioUnit (0)
  25173. {
  25174. using namespace AudioUnitFormatHelpers;
  25175. try
  25176. {
  25177. ++insideCallback;
  25178. log ("Opening AU: " + fileOrIdentifier);
  25179. if (getComponentDescFromFile (fileOrIdentifier))
  25180. {
  25181. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25182. if (comp != 0)
  25183. {
  25184. audioUnit = (AudioUnit) OpenComponent (comp);
  25185. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25186. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25187. }
  25188. }
  25189. --insideCallback;
  25190. }
  25191. catch (...)
  25192. {
  25193. --insideCallback;
  25194. }
  25195. }
  25196. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25197. {
  25198. const ScopedLock sl (lock);
  25199. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25200. if (audioUnit != 0)
  25201. {
  25202. AudioUnitUninitialize (audioUnit);
  25203. CloseComponent (audioUnit);
  25204. audioUnit = 0;
  25205. }
  25206. }
  25207. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25208. {
  25209. zerostruct (componentDesc);
  25210. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25211. return true;
  25212. const File file (fileOrIdentifier);
  25213. if (! file.hasFileExtension (".component"))
  25214. return false;
  25215. const char* const utf8 = fileOrIdentifier.toUTF8();
  25216. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25217. strlen (utf8), file.isDirectory());
  25218. if (url != 0)
  25219. {
  25220. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25221. CFRelease (url);
  25222. if (bundleRef != 0)
  25223. {
  25224. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25225. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25226. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25227. if (pluginName.isEmpty())
  25228. pluginName = file.getFileNameWithoutExtension();
  25229. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25230. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25231. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25232. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25233. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25234. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25235. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25236. UseResFile (resFileId);
  25237. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25238. {
  25239. Handle h = Get1IndResource ('thng', i);
  25240. if (h != 0)
  25241. {
  25242. HLock (h);
  25243. const uint32* const types = (const uint32*) *h;
  25244. if (types[0] == kAudioUnitType_MusicDevice
  25245. || types[0] == kAudioUnitType_MusicEffect
  25246. || types[0] == kAudioUnitType_Effect
  25247. || types[0] == kAudioUnitType_Generator
  25248. || types[0] == kAudioUnitType_Panner)
  25249. {
  25250. componentDesc.componentType = types[0];
  25251. componentDesc.componentSubType = types[1];
  25252. componentDesc.componentManufacturer = types[2];
  25253. break;
  25254. }
  25255. HUnlock (h);
  25256. ReleaseResource (h);
  25257. }
  25258. }
  25259. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25260. CFRelease (bundleRef);
  25261. }
  25262. }
  25263. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25264. }
  25265. void AudioUnitPluginInstance::initialise()
  25266. {
  25267. getParameterListFromPlugin();
  25268. setPluginCallbacks();
  25269. int numIns, numOuts;
  25270. getNumChannels (numIns, numOuts);
  25271. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25272. setLatencySamples (0);
  25273. }
  25274. void AudioUnitPluginInstance::getParameterListFromPlugin()
  25275. {
  25276. parameterIds.clear();
  25277. if (audioUnit != 0)
  25278. {
  25279. UInt32 paramListSize = 0;
  25280. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25281. 0, 0, &paramListSize);
  25282. if (paramListSize > 0)
  25283. {
  25284. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25285. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25286. 0, &parameterIds.getReference(0), &paramListSize);
  25287. }
  25288. }
  25289. }
  25290. void AudioUnitPluginInstance::setPluginCallbacks()
  25291. {
  25292. if (audioUnit != 0)
  25293. {
  25294. {
  25295. AURenderCallbackStruct info;
  25296. zerostruct (info);
  25297. info.inputProcRefCon = this;
  25298. info.inputProc = renderGetInputCallback;
  25299. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25300. 0, &info, sizeof (info));
  25301. }
  25302. {
  25303. HostCallbackInfo info;
  25304. zerostruct (info);
  25305. info.hostUserData = this;
  25306. info.beatAndTempoProc = getBeatAndTempoCallback;
  25307. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25308. info.transportStateProc = getTransportStateCallback;
  25309. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25310. 0, &info, sizeof (info));
  25311. }
  25312. }
  25313. }
  25314. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25315. int samplesPerBlockExpected)
  25316. {
  25317. if (audioUnit != 0)
  25318. {
  25319. releaseResources();
  25320. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25321. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25322. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25323. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25324. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25325. {
  25326. Float64 sr = sampleRate_;
  25327. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25328. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25329. }
  25330. int numIns, numOuts;
  25331. getNumChannels (numIns, numOuts);
  25332. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25333. Float64 latencySecs = 0.0;
  25334. UInt32 latencySize = sizeof (latencySecs);
  25335. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25336. 0, &latencySecs, &latencySize);
  25337. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25338. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25339. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25340. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25341. {
  25342. AudioStreamBasicDescription stream;
  25343. zerostruct (stream);
  25344. stream.mSampleRate = sampleRate_;
  25345. stream.mFormatID = kAudioFormatLinearPCM;
  25346. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25347. stream.mFramesPerPacket = 1;
  25348. stream.mBytesPerPacket = 4;
  25349. stream.mBytesPerFrame = 4;
  25350. stream.mBitsPerChannel = 32;
  25351. stream.mChannelsPerFrame = numIns;
  25352. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25353. 0, &stream, sizeof (stream));
  25354. stream.mChannelsPerFrame = numOuts;
  25355. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25356. 0, &stream, sizeof (stream));
  25357. }
  25358. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25359. outputBufferList->mNumberBuffers = numOuts;
  25360. for (int i = numOuts; --i >= 0;)
  25361. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25362. zerostruct (timeStamp);
  25363. timeStamp.mSampleTime = 0;
  25364. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25365. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25366. currentBuffer = 0;
  25367. wasPlaying = false;
  25368. prepared = (AudioUnitInitialize (audioUnit) == noErr);
  25369. }
  25370. }
  25371. void AudioUnitPluginInstance::releaseResources()
  25372. {
  25373. if (prepared)
  25374. {
  25375. AudioUnitUninitialize (audioUnit);
  25376. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25377. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25378. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25379. outputBufferList.free();
  25380. currentBuffer = 0;
  25381. prepared = false;
  25382. }
  25383. }
  25384. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25385. const AudioTimeStamp* inTimeStamp,
  25386. UInt32 inBusNumber,
  25387. UInt32 inNumberFrames,
  25388. AudioBufferList* ioData) const
  25389. {
  25390. if (inBusNumber == 0
  25391. && currentBuffer != 0)
  25392. {
  25393. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25394. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25395. {
  25396. if (i < currentBuffer->getNumChannels())
  25397. {
  25398. memcpy (ioData->mBuffers[i].mData,
  25399. currentBuffer->getSampleData (i, 0),
  25400. sizeof (float) * inNumberFrames);
  25401. }
  25402. else
  25403. {
  25404. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25405. }
  25406. }
  25407. }
  25408. return noErr;
  25409. }
  25410. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25411. MidiBuffer& midiMessages)
  25412. {
  25413. const int numSamples = buffer.getNumSamples();
  25414. if (prepared)
  25415. {
  25416. AudioUnitRenderActionFlags flags = 0;
  25417. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25418. for (int i = getNumOutputChannels(); --i >= 0;)
  25419. {
  25420. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25421. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25422. }
  25423. currentBuffer = &buffer;
  25424. if (wantsMidiMessages)
  25425. {
  25426. const uint8* midiEventData;
  25427. int midiEventSize, midiEventPosition;
  25428. MidiBuffer::Iterator i (midiMessages);
  25429. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25430. {
  25431. if (midiEventSize <= 3)
  25432. MusicDeviceMIDIEvent (audioUnit,
  25433. midiEventData[0], midiEventData[1], midiEventData[2],
  25434. midiEventPosition);
  25435. else
  25436. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25437. }
  25438. midiMessages.clear();
  25439. }
  25440. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25441. 0, numSamples, outputBufferList);
  25442. timeStamp.mSampleTime += numSamples;
  25443. }
  25444. else
  25445. {
  25446. // Plugin not working correctly, so just bypass..
  25447. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25448. buffer.clear (i, 0, buffer.getNumSamples());
  25449. }
  25450. }
  25451. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25452. {
  25453. AudioPlayHead* const ph = getPlayHead();
  25454. AudioPlayHead::CurrentPositionInfo result;
  25455. if (ph != 0 && ph->getCurrentPosition (result))
  25456. {
  25457. if (outCurrentBeat != 0)
  25458. *outCurrentBeat = result.ppqPosition;
  25459. if (outCurrentTempo != 0)
  25460. *outCurrentTempo = result.bpm;
  25461. }
  25462. else
  25463. {
  25464. if (outCurrentBeat != 0)
  25465. *outCurrentBeat = 0;
  25466. if (outCurrentTempo != 0)
  25467. *outCurrentTempo = 120.0;
  25468. }
  25469. return noErr;
  25470. }
  25471. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25472. Float32* outTimeSig_Numerator,
  25473. UInt32* outTimeSig_Denominator,
  25474. Float64* outCurrentMeasureDownBeat) const
  25475. {
  25476. AudioPlayHead* const ph = getPlayHead();
  25477. AudioPlayHead::CurrentPositionInfo result;
  25478. if (ph != 0 && ph->getCurrentPosition (result))
  25479. {
  25480. if (outTimeSig_Numerator != 0)
  25481. *outTimeSig_Numerator = result.timeSigNumerator;
  25482. if (outTimeSig_Denominator != 0)
  25483. *outTimeSig_Denominator = result.timeSigDenominator;
  25484. if (outDeltaSampleOffsetToNextBeat != 0)
  25485. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25486. if (outCurrentMeasureDownBeat != 0)
  25487. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25488. }
  25489. else
  25490. {
  25491. if (outDeltaSampleOffsetToNextBeat != 0)
  25492. *outDeltaSampleOffsetToNextBeat = 0;
  25493. if (outTimeSig_Numerator != 0)
  25494. *outTimeSig_Numerator = 4;
  25495. if (outTimeSig_Denominator != 0)
  25496. *outTimeSig_Denominator = 4;
  25497. if (outCurrentMeasureDownBeat != 0)
  25498. *outCurrentMeasureDownBeat = 0;
  25499. }
  25500. return noErr;
  25501. }
  25502. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25503. Boolean* outTransportStateChanged,
  25504. Float64* outCurrentSampleInTimeLine,
  25505. Boolean* outIsCycling,
  25506. Float64* outCycleStartBeat,
  25507. Float64* outCycleEndBeat)
  25508. {
  25509. AudioPlayHead* const ph = getPlayHead();
  25510. AudioPlayHead::CurrentPositionInfo result;
  25511. if (ph != 0 && ph->getCurrentPosition (result))
  25512. {
  25513. if (outIsPlaying != 0)
  25514. *outIsPlaying = result.isPlaying;
  25515. if (outTransportStateChanged != 0)
  25516. {
  25517. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25518. wasPlaying = result.isPlaying;
  25519. }
  25520. if (outCurrentSampleInTimeLine != 0)
  25521. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25522. if (outIsCycling != 0)
  25523. *outIsCycling = false;
  25524. if (outCycleStartBeat != 0)
  25525. *outCycleStartBeat = 0;
  25526. if (outCycleEndBeat != 0)
  25527. *outCycleEndBeat = 0;
  25528. }
  25529. else
  25530. {
  25531. if (outIsPlaying != 0)
  25532. *outIsPlaying = false;
  25533. if (outTransportStateChanged != 0)
  25534. *outTransportStateChanged = false;
  25535. if (outCurrentSampleInTimeLine != 0)
  25536. *outCurrentSampleInTimeLine = 0;
  25537. if (outIsCycling != 0)
  25538. *outIsCycling = false;
  25539. if (outCycleStartBeat != 0)
  25540. *outCycleStartBeat = 0;
  25541. if (outCycleEndBeat != 0)
  25542. *outCycleEndBeat = 0;
  25543. }
  25544. return noErr;
  25545. }
  25546. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor,
  25547. public Timer
  25548. {
  25549. public:
  25550. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25551. : AudioProcessorEditor (&plugin_),
  25552. plugin (plugin_)
  25553. {
  25554. addAndMakeVisible (&wrapper);
  25555. setOpaque (true);
  25556. setVisible (true);
  25557. setSize (100, 100);
  25558. createView (createGenericViewIfNeeded);
  25559. }
  25560. ~AudioUnitPluginWindowCocoa()
  25561. {
  25562. const bool wasValid = isValid();
  25563. wrapper.setView (0);
  25564. if (wasValid)
  25565. plugin.editorBeingDeleted (this);
  25566. }
  25567. bool isValid() const { return wrapper.getView() != 0; }
  25568. void paint (Graphics& g)
  25569. {
  25570. g.fillAll (Colours::white);
  25571. }
  25572. void resized()
  25573. {
  25574. wrapper.setSize (getWidth(), getHeight());
  25575. }
  25576. void timerCallback()
  25577. {
  25578. wrapper.resizeToFitView();
  25579. startTimer (jmin (713, getTimerInterval() + 51));
  25580. }
  25581. void childBoundsChanged (Component* child)
  25582. {
  25583. setSize (wrapper.getWidth(), wrapper.getHeight());
  25584. startTimer (70);
  25585. }
  25586. private:
  25587. AudioUnitPluginInstance& plugin;
  25588. NSViewComponent wrapper;
  25589. bool createView (const bool createGenericViewIfNeeded)
  25590. {
  25591. NSView* pluginView = 0;
  25592. UInt32 dataSize = 0;
  25593. Boolean isWritable = false;
  25594. AudioUnitInitialize (plugin.audioUnit);
  25595. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25596. 0, &dataSize, &isWritable) == noErr
  25597. && dataSize != 0
  25598. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25599. 0, &dataSize, &isWritable) == noErr)
  25600. {
  25601. HeapBlock <AudioUnitCocoaViewInfo> info;
  25602. info.calloc (dataSize, 1);
  25603. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25604. 0, info, &dataSize) == noErr)
  25605. {
  25606. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25607. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25608. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25609. Class viewClass = [viewBundle classNamed: viewClassName];
  25610. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25611. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25612. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25613. {
  25614. id factory = [[[viewClass alloc] init] autorelease];
  25615. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25616. withSize: NSMakeSize (getWidth(), getHeight())];
  25617. }
  25618. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25619. CFRelease (info->mCocoaAUViewClass[i]);
  25620. CFRelease (info->mCocoaAUViewBundleLocation);
  25621. }
  25622. }
  25623. if (createGenericViewIfNeeded && (pluginView == 0))
  25624. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25625. wrapper.setView (pluginView);
  25626. if (pluginView != 0)
  25627. {
  25628. timerCallback();
  25629. startTimer (70);
  25630. }
  25631. return pluginView != 0;
  25632. }
  25633. };
  25634. #if JUCE_SUPPORT_CARBON
  25635. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25636. {
  25637. public:
  25638. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25639. : AudioProcessorEditor (&plugin_),
  25640. plugin (plugin_),
  25641. viewComponent (0)
  25642. {
  25643. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25644. setOpaque (true);
  25645. setVisible (true);
  25646. setSize (400, 300);
  25647. ComponentDescription viewList [16];
  25648. UInt32 viewListSize = sizeof (viewList);
  25649. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25650. 0, &viewList, &viewListSize);
  25651. componentRecord = FindNextComponent (0, &viewList[0]);
  25652. }
  25653. ~AudioUnitPluginWindowCarbon()
  25654. {
  25655. innerWrapper = 0;
  25656. if (isValid())
  25657. plugin.editorBeingDeleted (this);
  25658. }
  25659. bool isValid() const throw() { return componentRecord != 0; }
  25660. void paint (Graphics& g)
  25661. {
  25662. g.fillAll (Colours::black);
  25663. }
  25664. void resized()
  25665. {
  25666. innerWrapper->setSize (getWidth(), getHeight());
  25667. }
  25668. bool keyStateChanged (bool)
  25669. {
  25670. return false;
  25671. }
  25672. bool keyPressed (const KeyPress&)
  25673. {
  25674. return false;
  25675. }
  25676. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  25677. AudioUnitCarbonView getViewComponent()
  25678. {
  25679. if (viewComponent == 0 && componentRecord != 0)
  25680. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  25681. return viewComponent;
  25682. }
  25683. void closeViewComponent()
  25684. {
  25685. if (viewComponent != 0)
  25686. {
  25687. log ("Closing AU GUI: " + plugin.getName());
  25688. CloseComponent (viewComponent);
  25689. viewComponent = 0;
  25690. }
  25691. }
  25692. private:
  25693. AudioUnitPluginInstance& plugin;
  25694. ComponentRecord* componentRecord;
  25695. AudioUnitCarbonView viewComponent;
  25696. class InnerWrapperComponent : public CarbonViewWrapperComponent
  25697. {
  25698. public:
  25699. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  25700. : owner (owner_)
  25701. {
  25702. }
  25703. ~InnerWrapperComponent()
  25704. {
  25705. deleteWindow();
  25706. }
  25707. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  25708. {
  25709. log ("Opening AU GUI: " + owner->plugin.getName());
  25710. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  25711. if (viewComponent == 0)
  25712. return 0;
  25713. Float32Point pos = { 0, 0 };
  25714. Float32Point size = { 250, 200 };
  25715. HIViewRef pluginView = 0;
  25716. AudioUnitCarbonViewCreate (viewComponent,
  25717. owner->getAudioUnit(),
  25718. windowRef,
  25719. rootView,
  25720. &pos,
  25721. &size,
  25722. (ControlRef*) &pluginView);
  25723. return pluginView;
  25724. }
  25725. void removeView (HIViewRef)
  25726. {
  25727. owner->closeViewComponent();
  25728. }
  25729. private:
  25730. AudioUnitPluginWindowCarbon* const owner;
  25731. };
  25732. friend class InnerWrapperComponent;
  25733. ScopedPointer<InnerWrapperComponent> innerWrapper;
  25734. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginWindowCarbon);
  25735. };
  25736. #endif
  25737. bool AudioUnitPluginInstance::hasEditor() const
  25738. {
  25739. return true;
  25740. }
  25741. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  25742. {
  25743. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  25744. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25745. w = 0;
  25746. #if JUCE_SUPPORT_CARBON
  25747. if (w == 0)
  25748. {
  25749. w = new AudioUnitPluginWindowCarbon (*this);
  25750. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25751. w = 0;
  25752. }
  25753. #endif
  25754. if (w == 0)
  25755. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  25756. return w.release();
  25757. }
  25758. const String AudioUnitPluginInstance::getCategory() const
  25759. {
  25760. const char* result = 0;
  25761. switch (componentDesc.componentType)
  25762. {
  25763. case kAudioUnitType_Effect:
  25764. case kAudioUnitType_MusicEffect: result = "Effect"; break;
  25765. case kAudioUnitType_MusicDevice: result = "Synth"; break;
  25766. case kAudioUnitType_Generator: result = "Generator"; break;
  25767. case kAudioUnitType_Panner: result = "Panner"; break;
  25768. default: break;
  25769. }
  25770. return result;
  25771. }
  25772. int AudioUnitPluginInstance::getNumParameters()
  25773. {
  25774. return parameterIds.size();
  25775. }
  25776. float AudioUnitPluginInstance::getParameter (int index)
  25777. {
  25778. const ScopedLock sl (lock);
  25779. Float32 value = 0.0f;
  25780. if (audioUnit != 0 && isPositiveAndBelow (index, parameterIds.size()))
  25781. {
  25782. AudioUnitGetParameter (audioUnit,
  25783. (UInt32) parameterIds.getUnchecked (index),
  25784. kAudioUnitScope_Global, 0,
  25785. &value);
  25786. }
  25787. return value;
  25788. }
  25789. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25790. {
  25791. const ScopedLock sl (lock);
  25792. if (audioUnit != 0 && isPositiveAndBelow (index, parameterIds.size()))
  25793. {
  25794. AudioUnitSetParameter (audioUnit,
  25795. (UInt32) parameterIds.getUnchecked (index),
  25796. kAudioUnitScope_Global, 0,
  25797. newValue, 0);
  25798. }
  25799. }
  25800. const String AudioUnitPluginInstance::getParameterName (int index)
  25801. {
  25802. AudioUnitParameterInfo info;
  25803. zerostruct (info);
  25804. UInt32 sz = sizeof (info);
  25805. String name;
  25806. if (AudioUnitGetProperty (audioUnit,
  25807. kAudioUnitProperty_ParameterInfo,
  25808. kAudioUnitScope_Global,
  25809. parameterIds [index], &info, &sz) == noErr)
  25810. {
  25811. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25812. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25813. else
  25814. name = String (info.name, sizeof (info.name));
  25815. }
  25816. return name;
  25817. }
  25818. const String AudioUnitPluginInstance::getParameterText (int index)
  25819. {
  25820. return String (getParameter (index));
  25821. }
  25822. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25823. {
  25824. AudioUnitParameterInfo info;
  25825. UInt32 sz = sizeof (info);
  25826. if (AudioUnitGetProperty (audioUnit,
  25827. kAudioUnitProperty_ParameterInfo,
  25828. kAudioUnitScope_Global,
  25829. parameterIds [index], &info, &sz) == noErr)
  25830. {
  25831. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25832. }
  25833. return true;
  25834. }
  25835. int AudioUnitPluginInstance::getNumPrograms()
  25836. {
  25837. CFArrayRef presets;
  25838. UInt32 sz = sizeof (CFArrayRef);
  25839. int num = 0;
  25840. if (AudioUnitGetProperty (audioUnit,
  25841. kAudioUnitProperty_FactoryPresets,
  25842. kAudioUnitScope_Global,
  25843. 0, &presets, &sz) == noErr)
  25844. {
  25845. num = (int) CFArrayGetCount (presets);
  25846. CFRelease (presets);
  25847. }
  25848. return num;
  25849. }
  25850. int AudioUnitPluginInstance::getCurrentProgram()
  25851. {
  25852. AUPreset current;
  25853. current.presetNumber = 0;
  25854. UInt32 sz = sizeof (AUPreset);
  25855. AudioUnitGetProperty (audioUnit,
  25856. kAudioUnitProperty_FactoryPresets,
  25857. kAudioUnitScope_Global,
  25858. 0, &current, &sz);
  25859. return current.presetNumber;
  25860. }
  25861. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  25862. {
  25863. AUPreset current;
  25864. current.presetNumber = newIndex;
  25865. current.presetName = 0;
  25866. AudioUnitSetProperty (audioUnit,
  25867. kAudioUnitProperty_FactoryPresets,
  25868. kAudioUnitScope_Global,
  25869. 0, &current, sizeof (AUPreset));
  25870. }
  25871. const String AudioUnitPluginInstance::getProgramName (int index)
  25872. {
  25873. String s;
  25874. CFArrayRef presets;
  25875. UInt32 sz = sizeof (CFArrayRef);
  25876. if (AudioUnitGetProperty (audioUnit,
  25877. kAudioUnitProperty_FactoryPresets,
  25878. kAudioUnitScope_Global,
  25879. 0, &presets, &sz) == noErr)
  25880. {
  25881. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  25882. {
  25883. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  25884. if (p != 0 && p->presetNumber == index)
  25885. {
  25886. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  25887. break;
  25888. }
  25889. }
  25890. CFRelease (presets);
  25891. }
  25892. return s;
  25893. }
  25894. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  25895. {
  25896. jassertfalse; // xxx not implemented!
  25897. }
  25898. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  25899. {
  25900. if (isPositiveAndBelow (index, getNumInputChannels()))
  25901. return "Input " + String (index + 1);
  25902. return String::empty;
  25903. }
  25904. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  25905. {
  25906. if (! isPositiveAndBelow (index, getNumInputChannels()))
  25907. return false;
  25908. return true;
  25909. }
  25910. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  25911. {
  25912. if (isPositiveAndBelow (index, getNumOutputChannels()))
  25913. return "Output " + String (index + 1);
  25914. return String::empty;
  25915. }
  25916. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  25917. {
  25918. if (! isPositiveAndBelow (index, getNumOutputChannels()))
  25919. return false;
  25920. return true;
  25921. }
  25922. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  25923. {
  25924. getCurrentProgramStateInformation (destData);
  25925. }
  25926. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  25927. {
  25928. CFPropertyListRef propertyList = 0;
  25929. UInt32 sz = sizeof (CFPropertyListRef);
  25930. if (AudioUnitGetProperty (audioUnit,
  25931. kAudioUnitProperty_ClassInfo,
  25932. kAudioUnitScope_Global,
  25933. 0, &propertyList, &sz) == noErr)
  25934. {
  25935. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  25936. CFWriteStreamOpen (stream);
  25937. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  25938. CFWriteStreamClose (stream);
  25939. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  25940. destData.setSize (bytesWritten);
  25941. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  25942. CFRelease (data);
  25943. CFRelease (stream);
  25944. CFRelease (propertyList);
  25945. }
  25946. }
  25947. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  25948. {
  25949. setCurrentProgramStateInformation (data, sizeInBytes);
  25950. }
  25951. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  25952. {
  25953. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  25954. (const UInt8*) data,
  25955. sizeInBytes,
  25956. kCFAllocatorNull);
  25957. CFReadStreamOpen (stream);
  25958. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  25959. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  25960. stream,
  25961. 0,
  25962. kCFPropertyListImmutable,
  25963. &format,
  25964. 0);
  25965. CFRelease (stream);
  25966. if (propertyList != 0)
  25967. AudioUnitSetProperty (audioUnit,
  25968. kAudioUnitProperty_ClassInfo,
  25969. kAudioUnitScope_Global,
  25970. 0, &propertyList, sizeof (propertyList));
  25971. }
  25972. AudioUnitPluginFormat::AudioUnitPluginFormat()
  25973. {
  25974. }
  25975. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  25976. {
  25977. }
  25978. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  25979. const String& fileOrIdentifier)
  25980. {
  25981. if (! fileMightContainThisPluginType (fileOrIdentifier))
  25982. return;
  25983. PluginDescription desc;
  25984. desc.fileOrIdentifier = fileOrIdentifier;
  25985. desc.uid = 0;
  25986. try
  25987. {
  25988. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  25989. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  25990. if (auInstance != 0)
  25991. {
  25992. auInstance->fillInPluginDescription (desc);
  25993. results.add (new PluginDescription (desc));
  25994. }
  25995. }
  25996. catch (...)
  25997. {
  25998. // crashed while loading...
  25999. }
  26000. }
  26001. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  26002. {
  26003. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  26004. {
  26005. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  26006. if (result->audioUnit != 0)
  26007. {
  26008. result->initialise();
  26009. return result.release();
  26010. }
  26011. }
  26012. return 0;
  26013. }
  26014. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  26015. const bool /*recursive*/)
  26016. {
  26017. StringArray result;
  26018. ComponentRecord* comp = 0;
  26019. ComponentDescription desc;
  26020. zerostruct (desc);
  26021. for (;;)
  26022. {
  26023. zerostruct (desc);
  26024. comp = FindNextComponent (comp, &desc);
  26025. if (comp == 0)
  26026. break;
  26027. GetComponentInfo (comp, &desc, 0, 0, 0);
  26028. if (desc.componentType == kAudioUnitType_MusicDevice
  26029. || desc.componentType == kAudioUnitType_MusicEffect
  26030. || desc.componentType == kAudioUnitType_Effect
  26031. || desc.componentType == kAudioUnitType_Generator
  26032. || desc.componentType == kAudioUnitType_Panner)
  26033. {
  26034. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26035. DBG (s);
  26036. result.add (s);
  26037. }
  26038. }
  26039. return result;
  26040. }
  26041. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26042. {
  26043. ComponentDescription desc;
  26044. String name, version, manufacturer;
  26045. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26046. return FindNextComponent (0, &desc) != 0;
  26047. const File f (fileOrIdentifier);
  26048. return f.hasFileExtension (".component")
  26049. && f.isDirectory();
  26050. }
  26051. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26052. {
  26053. ComponentDescription desc;
  26054. String name, version, manufacturer;
  26055. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26056. if (name.isEmpty())
  26057. name = fileOrIdentifier;
  26058. return name;
  26059. }
  26060. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26061. {
  26062. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26063. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26064. else
  26065. return File (desc.fileOrIdentifier).exists();
  26066. }
  26067. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26068. {
  26069. return FileSearchPath ("/(Default AudioUnit locations)");
  26070. }
  26071. #endif
  26072. END_JUCE_NAMESPACE
  26073. #undef log
  26074. #endif
  26075. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26076. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26077. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26078. #define JUCE_MAC_VST_INCLUDED 1
  26079. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26080. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26081. #if JUCE_WINDOWS
  26082. #undef _WIN32_WINNT
  26083. #define _WIN32_WINNT 0x500
  26084. #undef STRICT
  26085. #define STRICT
  26086. #include <windows.h>
  26087. #include <float.h>
  26088. #pragma warning (disable : 4312 4355)
  26089. #ifdef __INTEL_COMPILER
  26090. #pragma warning (disable : 1899)
  26091. #endif
  26092. #elif JUCE_LINUX
  26093. #include <float.h>
  26094. #include <sys/time.h>
  26095. #include <X11/Xlib.h>
  26096. #include <X11/Xutil.h>
  26097. #include <X11/Xatom.h>
  26098. #undef Font
  26099. #undef KeyPress
  26100. #undef Drawable
  26101. #undef Time
  26102. #else
  26103. #include <Cocoa/Cocoa.h>
  26104. #include <Carbon/Carbon.h>
  26105. #endif
  26106. #if ! (JUCE_MAC && JUCE_64BIT)
  26107. BEGIN_JUCE_NAMESPACE
  26108. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26109. #endif
  26110. #undef PRAGMA_ALIGN_SUPPORTED
  26111. #define VST_FORCE_DEPRECATED 0
  26112. #if JUCE_MSVC
  26113. #pragma warning (push)
  26114. #pragma warning (disable: 4996)
  26115. #endif
  26116. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26117. your include path if you want to add VST support.
  26118. If you're not interested in VSTs, you can disable them by changing the
  26119. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26120. */
  26121. #include <pluginterfaces/vst2.x/aeffectx.h>
  26122. #if JUCE_MSVC
  26123. #pragma warning (pop)
  26124. #endif
  26125. #if JUCE_LINUX
  26126. #define Font JUCE_NAMESPACE::Font
  26127. #define KeyPress JUCE_NAMESPACE::KeyPress
  26128. #define Drawable JUCE_NAMESPACE::Drawable
  26129. #define Time JUCE_NAMESPACE::Time
  26130. #endif
  26131. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26132. #ifdef __aeffect__
  26133. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26134. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26135. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26136. events to the list.
  26137. This is used by both the VST hosting code and the plugin wrapper.
  26138. */
  26139. class VSTMidiEventList
  26140. {
  26141. public:
  26142. VSTMidiEventList()
  26143. : numEventsUsed (0), numEventsAllocated (0)
  26144. {
  26145. }
  26146. ~VSTMidiEventList()
  26147. {
  26148. freeEvents();
  26149. }
  26150. void clear()
  26151. {
  26152. numEventsUsed = 0;
  26153. if (events != 0)
  26154. events->numEvents = 0;
  26155. }
  26156. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26157. {
  26158. ensureSize (numEventsUsed + 1);
  26159. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26160. events->numEvents = ++numEventsUsed;
  26161. if (numBytes <= 4)
  26162. {
  26163. if (e->type == kVstSysExType)
  26164. {
  26165. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26166. e->type = kVstMidiType;
  26167. e->byteSize = sizeof (VstMidiEvent);
  26168. e->noteLength = 0;
  26169. e->noteOffset = 0;
  26170. e->detune = 0;
  26171. e->noteOffVelocity = 0;
  26172. }
  26173. e->deltaFrames = frameOffset;
  26174. memcpy (e->midiData, midiData, numBytes);
  26175. }
  26176. else
  26177. {
  26178. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26179. if (se->type == kVstSysExType)
  26180. delete[] se->sysexDump;
  26181. se->sysexDump = new char [numBytes];
  26182. memcpy (se->sysexDump, midiData, numBytes);
  26183. se->type = kVstSysExType;
  26184. se->byteSize = sizeof (VstMidiSysexEvent);
  26185. se->deltaFrames = frameOffset;
  26186. se->flags = 0;
  26187. se->dumpBytes = numBytes;
  26188. se->resvd1 = 0;
  26189. se->resvd2 = 0;
  26190. }
  26191. }
  26192. // Handy method to pull the events out of an event buffer supplied by the host
  26193. // or plugin.
  26194. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26195. {
  26196. for (int i = 0; i < events->numEvents; ++i)
  26197. {
  26198. const VstEvent* const e = events->events[i];
  26199. if (e != 0)
  26200. {
  26201. if (e->type == kVstMidiType)
  26202. {
  26203. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26204. 4, e->deltaFrames);
  26205. }
  26206. else if (e->type == kVstSysExType)
  26207. {
  26208. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26209. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26210. e->deltaFrames);
  26211. }
  26212. }
  26213. }
  26214. }
  26215. void ensureSize (int numEventsNeeded)
  26216. {
  26217. if (numEventsNeeded > numEventsAllocated)
  26218. {
  26219. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26220. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26221. if (events == 0)
  26222. events.calloc (size, 1);
  26223. else
  26224. events.realloc (size, 1);
  26225. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26226. {
  26227. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26228. (int) sizeof (VstMidiSysexEvent)));
  26229. e->type = kVstMidiType;
  26230. e->byteSize = sizeof (VstMidiEvent);
  26231. events->events[i] = (VstEvent*) e;
  26232. }
  26233. numEventsAllocated = numEventsNeeded;
  26234. }
  26235. }
  26236. void freeEvents()
  26237. {
  26238. if (events != 0)
  26239. {
  26240. for (int i = numEventsAllocated; --i >= 0;)
  26241. {
  26242. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26243. if (e->type == kVstSysExType)
  26244. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26245. juce_free (e);
  26246. }
  26247. events.free();
  26248. numEventsUsed = 0;
  26249. numEventsAllocated = 0;
  26250. }
  26251. }
  26252. HeapBlock <VstEvents> events;
  26253. private:
  26254. int numEventsUsed, numEventsAllocated;
  26255. };
  26256. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26257. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26258. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26259. #if ! JUCE_WINDOWS
  26260. static void _fpreset() {}
  26261. static void _clearfp() {}
  26262. #endif
  26263. extern void juce_callAnyTimersSynchronously();
  26264. const int fxbVersionNum = 1;
  26265. struct fxProgram
  26266. {
  26267. long chunkMagic; // 'CcnK'
  26268. long byteSize; // of this chunk, excl. magic + byteSize
  26269. long fxMagic; // 'FxCk'
  26270. long version;
  26271. long fxID; // fx unique id
  26272. long fxVersion;
  26273. long numParams;
  26274. char prgName[28];
  26275. float params[1]; // variable no. of parameters
  26276. };
  26277. struct fxSet
  26278. {
  26279. long chunkMagic; // 'CcnK'
  26280. long byteSize; // of this chunk, excl. magic + byteSize
  26281. long fxMagic; // 'FxBk'
  26282. long version;
  26283. long fxID; // fx unique id
  26284. long fxVersion;
  26285. long numPrograms;
  26286. char future[128];
  26287. fxProgram programs[1]; // variable no. of programs
  26288. };
  26289. struct fxChunkSet
  26290. {
  26291. long chunkMagic; // 'CcnK'
  26292. long byteSize; // of this chunk, excl. magic + byteSize
  26293. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26294. long version;
  26295. long fxID; // fx unique id
  26296. long fxVersion;
  26297. long numPrograms;
  26298. char future[128];
  26299. long chunkSize;
  26300. char chunk[8]; // variable
  26301. };
  26302. struct fxProgramSet
  26303. {
  26304. long chunkMagic; // 'CcnK'
  26305. long byteSize; // of this chunk, excl. magic + byteSize
  26306. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26307. long version;
  26308. long fxID; // fx unique id
  26309. long fxVersion;
  26310. long numPrograms;
  26311. char name[28];
  26312. long chunkSize;
  26313. char chunk[8]; // variable
  26314. };
  26315. namespace
  26316. {
  26317. long vst_swap (const long x) throw()
  26318. {
  26319. #ifdef JUCE_LITTLE_ENDIAN
  26320. return (long) ByteOrder::swap ((uint32) x);
  26321. #else
  26322. return x;
  26323. #endif
  26324. }
  26325. float vst_swapFloat (const float x) throw()
  26326. {
  26327. #ifdef JUCE_LITTLE_ENDIAN
  26328. union { uint32 asInt; float asFloat; } n;
  26329. n.asFloat = x;
  26330. n.asInt = ByteOrder::swap (n.asInt);
  26331. return n.asFloat;
  26332. #else
  26333. return x;
  26334. #endif
  26335. }
  26336. double getVSTHostTimeNanoseconds()
  26337. {
  26338. #if JUCE_WINDOWS
  26339. return timeGetTime() * 1000000.0;
  26340. #elif JUCE_LINUX
  26341. timeval micro;
  26342. gettimeofday (&micro, 0);
  26343. return micro.tv_usec * 1000.0;
  26344. #elif JUCE_MAC
  26345. UnsignedWide micro;
  26346. Microseconds (&micro);
  26347. return micro.lo * 1000.0;
  26348. #endif
  26349. }
  26350. }
  26351. typedef AEffect* (VSTCALLBACK *MainCall) (audioMasterCallback);
  26352. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26353. static int shellUIDToCreate = 0;
  26354. static int insideVSTCallback = 0;
  26355. class VSTPluginWindow;
  26356. // Change this to disable logging of various VST activities
  26357. #ifndef VST_LOGGING
  26358. #define VST_LOGGING 1
  26359. #endif
  26360. #if VST_LOGGING
  26361. #define log(a) Logger::writeToLog(a);
  26362. #else
  26363. #define log(a)
  26364. #endif
  26365. #if JUCE_MAC && JUCE_PPC
  26366. static void* NewCFMFromMachO (void* const machofp) throw()
  26367. {
  26368. void* result = (void*) new char[8];
  26369. ((void**) result)[0] = machofp;
  26370. ((void**) result)[1] = result;
  26371. return result;
  26372. }
  26373. #endif
  26374. #if JUCE_LINUX
  26375. extern Display* display;
  26376. extern XContext windowHandleXContext;
  26377. typedef void (*EventProcPtr) (XEvent* ev);
  26378. static bool xErrorTriggered;
  26379. namespace
  26380. {
  26381. int temporaryErrorHandler (Display*, XErrorEvent*)
  26382. {
  26383. xErrorTriggered = true;
  26384. return 0;
  26385. }
  26386. int getPropertyFromXWindow (Window handle, Atom atom)
  26387. {
  26388. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26389. xErrorTriggered = false;
  26390. int userSize;
  26391. unsigned long bytes, userCount;
  26392. unsigned char* data;
  26393. Atom userType;
  26394. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26395. &userType, &userSize, &userCount, &bytes, &data);
  26396. XSetErrorHandler (oldErrorHandler);
  26397. return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast<int*> (data)
  26398. : 0;
  26399. }
  26400. Window getChildWindow (Window windowToCheck)
  26401. {
  26402. Window rootWindow, parentWindow;
  26403. Window* childWindows;
  26404. unsigned int numChildren;
  26405. XQueryTree (display,
  26406. windowToCheck,
  26407. &rootWindow,
  26408. &parentWindow,
  26409. &childWindows,
  26410. &numChildren);
  26411. if (numChildren > 0)
  26412. return childWindows [0];
  26413. return 0;
  26414. }
  26415. void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26416. {
  26417. if (e.mods.isLeftButtonDown())
  26418. {
  26419. ev.xbutton.button = Button1;
  26420. ev.xbutton.state |= Button1Mask;
  26421. }
  26422. else if (e.mods.isRightButtonDown())
  26423. {
  26424. ev.xbutton.button = Button3;
  26425. ev.xbutton.state |= Button3Mask;
  26426. }
  26427. else if (e.mods.isMiddleButtonDown())
  26428. {
  26429. ev.xbutton.button = Button2;
  26430. ev.xbutton.state |= Button2Mask;
  26431. }
  26432. }
  26433. void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26434. {
  26435. if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask;
  26436. else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask;
  26437. else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask;
  26438. }
  26439. void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26440. {
  26441. if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask;
  26442. else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask;
  26443. else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask;
  26444. }
  26445. void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26446. {
  26447. if (increment < 0)
  26448. {
  26449. ev.xbutton.button = Button5;
  26450. ev.xbutton.state |= Button5Mask;
  26451. }
  26452. else if (increment > 0)
  26453. {
  26454. ev.xbutton.button = Button4;
  26455. ev.xbutton.state |= Button4Mask;
  26456. }
  26457. }
  26458. }
  26459. #endif
  26460. class ModuleHandle : public ReferenceCountedObject
  26461. {
  26462. public:
  26463. File file;
  26464. MainCall moduleMain;
  26465. String pluginName;
  26466. static Array <ModuleHandle*>& getActiveModules()
  26467. {
  26468. static Array <ModuleHandle*> activeModules;
  26469. return activeModules;
  26470. }
  26471. static ModuleHandle* findOrCreateModule (const File& file)
  26472. {
  26473. for (int i = getActiveModules().size(); --i >= 0;)
  26474. {
  26475. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26476. if (module->file == file)
  26477. return module;
  26478. }
  26479. _fpreset(); // (doesn't do any harm)
  26480. ++insideVSTCallback;
  26481. shellUIDToCreate = 0;
  26482. log ("Attempting to load VST: " + file.getFullPathName());
  26483. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26484. if (! m->open())
  26485. m = 0;
  26486. --insideVSTCallback;
  26487. _fpreset(); // (doesn't do any harm)
  26488. return m.release();
  26489. }
  26490. ModuleHandle (const File& file_)
  26491. : file (file_),
  26492. moduleMain (0),
  26493. #if JUCE_WINDOWS || JUCE_LINUX
  26494. hModule (0)
  26495. #elif JUCE_MAC
  26496. fragId (0),
  26497. resHandle (0),
  26498. bundleRef (0),
  26499. resFileId (0)
  26500. #endif
  26501. {
  26502. getActiveModules().add (this);
  26503. #if JUCE_WINDOWS || JUCE_LINUX
  26504. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26505. #elif JUCE_MAC
  26506. FSRef ref;
  26507. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26508. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26509. #endif
  26510. }
  26511. ~ModuleHandle()
  26512. {
  26513. getActiveModules().removeValue (this);
  26514. close();
  26515. }
  26516. #if JUCE_WINDOWS || JUCE_LINUX
  26517. void* hModule;
  26518. String fullParentDirectoryPathName;
  26519. bool open()
  26520. {
  26521. #if JUCE_WINDOWS
  26522. static bool timePeriodSet = false;
  26523. if (! timePeriodSet)
  26524. {
  26525. timePeriodSet = true;
  26526. timeBeginPeriod (2);
  26527. }
  26528. #endif
  26529. pluginName = file.getFileNameWithoutExtension();
  26530. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26531. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26532. if (moduleMain == 0)
  26533. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26534. return moduleMain != 0;
  26535. }
  26536. void close()
  26537. {
  26538. _fpreset(); // (doesn't do any harm)
  26539. PlatformUtilities::freeDynamicLibrary (hModule);
  26540. }
  26541. void closeEffect (AEffect* eff)
  26542. {
  26543. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26544. }
  26545. #else
  26546. CFragConnectionID fragId;
  26547. Handle resHandle;
  26548. CFBundleRef bundleRef;
  26549. FSSpec parentDirFSSpec;
  26550. short resFileId;
  26551. bool open()
  26552. {
  26553. bool ok = false;
  26554. const String filename (file.getFullPathName());
  26555. if (file.hasFileExtension (".vst"))
  26556. {
  26557. const char* const utf8 = filename.toUTF8();
  26558. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26559. strlen (utf8), file.isDirectory());
  26560. if (url != 0)
  26561. {
  26562. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26563. CFRelease (url);
  26564. if (bundleRef != 0)
  26565. {
  26566. if (CFBundleLoadExecutable (bundleRef))
  26567. {
  26568. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26569. if (moduleMain == 0)
  26570. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26571. if (moduleMain != 0)
  26572. {
  26573. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26574. if (name != 0)
  26575. {
  26576. if (CFGetTypeID (name) == CFStringGetTypeID())
  26577. {
  26578. char buffer[1024];
  26579. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26580. pluginName = buffer;
  26581. }
  26582. }
  26583. if (pluginName.isEmpty())
  26584. pluginName = file.getFileNameWithoutExtension();
  26585. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26586. ok = true;
  26587. }
  26588. }
  26589. if (! ok)
  26590. {
  26591. CFBundleUnloadExecutable (bundleRef);
  26592. CFRelease (bundleRef);
  26593. bundleRef = 0;
  26594. }
  26595. }
  26596. }
  26597. }
  26598. #if JUCE_PPC
  26599. else
  26600. {
  26601. FSRef fn;
  26602. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  26603. {
  26604. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26605. if (resFileId != -1)
  26606. {
  26607. const int numEffs = Count1Resources ('aEff');
  26608. for (int i = 0; i < numEffs; ++i)
  26609. {
  26610. resHandle = Get1IndResource ('aEff', i + 1);
  26611. if (resHandle != 0)
  26612. {
  26613. OSType type;
  26614. Str255 name;
  26615. SInt16 id;
  26616. GetResInfo (resHandle, &id, &type, name);
  26617. pluginName = String ((const char*) name + 1, name[0]);
  26618. DetachResource (resHandle);
  26619. HLock (resHandle);
  26620. Ptr ptr;
  26621. Str255 errorText;
  26622. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26623. name, kPrivateCFragCopy,
  26624. &fragId, &ptr, errorText);
  26625. if (err == noErr)
  26626. {
  26627. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26628. ok = true;
  26629. }
  26630. else
  26631. {
  26632. HUnlock (resHandle);
  26633. }
  26634. break;
  26635. }
  26636. }
  26637. if (! ok)
  26638. CloseResFile (resFileId);
  26639. }
  26640. }
  26641. }
  26642. #endif
  26643. return ok;
  26644. }
  26645. void close()
  26646. {
  26647. #if JUCE_PPC
  26648. if (fragId != 0)
  26649. {
  26650. if (moduleMain != 0)
  26651. disposeMachOFromCFM ((void*) moduleMain);
  26652. CloseConnection (&fragId);
  26653. HUnlock (resHandle);
  26654. if (resFileId != 0)
  26655. CloseResFile (resFileId);
  26656. }
  26657. else
  26658. #endif
  26659. if (bundleRef != 0)
  26660. {
  26661. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26662. if (CFGetRetainCount (bundleRef) == 1)
  26663. CFBundleUnloadExecutable (bundleRef);
  26664. if (CFGetRetainCount (bundleRef) > 0)
  26665. CFRelease (bundleRef);
  26666. }
  26667. }
  26668. void closeEffect (AEffect* eff)
  26669. {
  26670. #if JUCE_PPC
  26671. if (fragId != 0)
  26672. {
  26673. Array<void*> thingsToDelete;
  26674. thingsToDelete.add ((void*) eff->dispatcher);
  26675. thingsToDelete.add ((void*) eff->process);
  26676. thingsToDelete.add ((void*) eff->setParameter);
  26677. thingsToDelete.add ((void*) eff->getParameter);
  26678. thingsToDelete.add ((void*) eff->processReplacing);
  26679. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26680. for (int i = thingsToDelete.size(); --i >= 0;)
  26681. disposeMachOFromCFM (thingsToDelete[i]);
  26682. }
  26683. else
  26684. #endif
  26685. {
  26686. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26687. }
  26688. }
  26689. #if JUCE_PPC
  26690. static void* newMachOFromCFM (void* cfmfp)
  26691. {
  26692. if (cfmfp == 0)
  26693. return 0;
  26694. UInt32* const mfp = new UInt32[6];
  26695. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  26696. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  26697. mfp[2] = 0x800c0000;
  26698. mfp[3] = 0x804c0004;
  26699. mfp[4] = 0x7c0903a6;
  26700. mfp[5] = 0x4e800420;
  26701. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  26702. return mfp;
  26703. }
  26704. static void disposeMachOFromCFM (void* ptr)
  26705. {
  26706. delete[] static_cast <UInt32*> (ptr);
  26707. }
  26708. void coerceAEffectFunctionCalls (AEffect* eff)
  26709. {
  26710. if (fragId != 0)
  26711. {
  26712. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  26713. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  26714. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  26715. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  26716. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  26717. }
  26718. }
  26719. #endif
  26720. #endif
  26721. private:
  26722. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ModuleHandle);
  26723. };
  26724. /**
  26725. An instance of a plugin, created by a VSTPluginFormat.
  26726. */
  26727. class VSTPluginInstance : public AudioPluginInstance,
  26728. private Timer,
  26729. private AsyncUpdater
  26730. {
  26731. public:
  26732. ~VSTPluginInstance();
  26733. // AudioPluginInstance methods:
  26734. void fillInPluginDescription (PluginDescription& desc) const
  26735. {
  26736. desc.name = name;
  26737. {
  26738. char buffer [512];
  26739. zerostruct (buffer);
  26740. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26741. desc.descriptiveName = String (buffer).trim();
  26742. if (desc.descriptiveName.isEmpty())
  26743. desc.descriptiveName = name;
  26744. }
  26745. desc.fileOrIdentifier = module->file.getFullPathName();
  26746. desc.uid = getUID();
  26747. desc.lastFileModTime = module->file.getLastModificationTime();
  26748. desc.pluginFormatName = "VST";
  26749. desc.category = getCategory();
  26750. {
  26751. char buffer [kVstMaxVendorStrLen + 8];
  26752. zerostruct (buffer);
  26753. dispatch (effGetVendorString, 0, 0, buffer, 0);
  26754. desc.manufacturerName = buffer;
  26755. }
  26756. desc.version = getVersion();
  26757. desc.numInputChannels = getNumInputChannels();
  26758. desc.numOutputChannels = getNumOutputChannels();
  26759. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  26760. }
  26761. void* getPlatformSpecificData() { return effect; }
  26762. const String getName() const { return name; }
  26763. int getUID() const;
  26764. bool acceptsMidi() const { return wantsMidiMessages; }
  26765. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  26766. // AudioProcessor methods:
  26767. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  26768. void releaseResources();
  26769. void processBlock (AudioSampleBuffer& buffer,
  26770. MidiBuffer& midiMessages);
  26771. bool hasEditor() const { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26772. AudioProcessorEditor* createEditor();
  26773. const String getInputChannelName (int index) const;
  26774. bool isInputChannelStereoPair (int index) const;
  26775. const String getOutputChannelName (int index) const;
  26776. bool isOutputChannelStereoPair (int index) const;
  26777. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  26778. float getParameter (int index);
  26779. void setParameter (int index, float newValue);
  26780. const String getParameterName (int index);
  26781. const String getParameterText (int index);
  26782. bool isParameterAutomatable (int index) const;
  26783. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  26784. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  26785. void setCurrentProgram (int index);
  26786. const String getProgramName (int index);
  26787. void changeProgramName (int index, const String& newName);
  26788. void getStateInformation (MemoryBlock& destData);
  26789. void getCurrentProgramStateInformation (MemoryBlock& destData);
  26790. void setStateInformation (const void* data, int sizeInBytes);
  26791. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  26792. void timerCallback();
  26793. void handleAsyncUpdate();
  26794. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  26795. private:
  26796. friend class VSTPluginWindow;
  26797. friend class VSTPluginFormat;
  26798. AEffect* effect;
  26799. String name;
  26800. CriticalSection lock;
  26801. bool wantsMidiMessages, initialised, isPowerOn;
  26802. mutable StringArray programNames;
  26803. AudioSampleBuffer tempBuffer;
  26804. CriticalSection midiInLock;
  26805. MidiBuffer incomingMidi;
  26806. VSTMidiEventList midiEventsToSend;
  26807. VstTimeInfo vstHostTime;
  26808. ReferenceCountedObjectPtr <ModuleHandle> module;
  26809. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26810. bool restoreProgramSettings (const fxProgram* const prog);
  26811. const String getCurrentProgramName();
  26812. void setParamsInProgramBlock (fxProgram* const prog);
  26813. void updateStoredProgramNames();
  26814. void initialise();
  26815. void handleMidiFromPlugin (const VstEvents* const events);
  26816. void createTempParameterStore (MemoryBlock& dest);
  26817. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26818. const String getParameterLabel (int index) const;
  26819. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26820. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26821. void setChunkData (const char* data, int size, bool isPreset);
  26822. bool loadFromFXBFile (const void* data, int numBytes);
  26823. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26824. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26825. const String getVersion() const;
  26826. const String getCategory() const;
  26827. void setPower (const bool on);
  26828. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26829. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginInstance);
  26830. };
  26831. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26832. : effect (0),
  26833. wantsMidiMessages (false),
  26834. initialised (false),
  26835. isPowerOn (false),
  26836. tempBuffer (1, 1),
  26837. module (module_)
  26838. {
  26839. try
  26840. {
  26841. _fpreset();
  26842. ++insideVSTCallback;
  26843. name = module->pluginName;
  26844. log ("Creating VST instance: " + name);
  26845. #if JUCE_MAC
  26846. if (module->resFileId != 0)
  26847. UseResFile (module->resFileId);
  26848. #if JUCE_PPC
  26849. if (module->fragId != 0)
  26850. {
  26851. static void* audioMasterCoerced = 0;
  26852. if (audioMasterCoerced == 0)
  26853. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26854. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26855. }
  26856. else
  26857. #endif
  26858. #endif
  26859. {
  26860. effect = module->moduleMain (&audioMaster);
  26861. }
  26862. --insideVSTCallback;
  26863. if (effect != 0 && effect->magic == kEffectMagic)
  26864. {
  26865. #if JUCE_PPC
  26866. module->coerceAEffectFunctionCalls (effect);
  26867. #endif
  26868. jassert (effect->resvd2 == 0);
  26869. jassert (effect->object != 0);
  26870. _fpreset(); // some dodgy plugs fuck around with this
  26871. }
  26872. else
  26873. {
  26874. effect = 0;
  26875. }
  26876. }
  26877. catch (...)
  26878. {
  26879. --insideVSTCallback;
  26880. }
  26881. }
  26882. VSTPluginInstance::~VSTPluginInstance()
  26883. {
  26884. const ScopedLock sl (lock);
  26885. jassert (insideVSTCallback == 0);
  26886. if (effect != 0 && effect->magic == kEffectMagic)
  26887. {
  26888. try
  26889. {
  26890. #if JUCE_MAC
  26891. if (module->resFileId != 0)
  26892. UseResFile (module->resFileId);
  26893. #endif
  26894. // Must delete any editors before deleting the plugin instance!
  26895. jassert (getActiveEditor() == 0);
  26896. _fpreset(); // some dodgy plugs fuck around with this
  26897. module->closeEffect (effect);
  26898. }
  26899. catch (...)
  26900. {}
  26901. }
  26902. module = 0;
  26903. effect = 0;
  26904. }
  26905. void VSTPluginInstance::initialise()
  26906. {
  26907. if (initialised || effect == 0)
  26908. return;
  26909. log ("Initialising VST: " + module->pluginName);
  26910. initialised = true;
  26911. dispatch (effIdentify, 0, 0, 0, 0);
  26912. if (getSampleRate() > 0)
  26913. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  26914. if (getBlockSize() > 0)
  26915. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  26916. dispatch (effOpen, 0, 0, 0, 0);
  26917. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26918. getSampleRate(), getBlockSize());
  26919. if (getNumPrograms() > 1)
  26920. setCurrentProgram (0);
  26921. else
  26922. dispatch (effSetProgram, 0, 0, 0, 0);
  26923. int i;
  26924. for (i = effect->numInputs; --i >= 0;)
  26925. dispatch (effConnectInput, i, 1, 0, 0);
  26926. for (i = effect->numOutputs; --i >= 0;)
  26927. dispatch (effConnectOutput, i, 1, 0, 0);
  26928. updateStoredProgramNames();
  26929. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  26930. setLatencySamples (effect->initialDelay);
  26931. }
  26932. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  26933. int samplesPerBlockExpected)
  26934. {
  26935. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26936. sampleRate_, samplesPerBlockExpected);
  26937. setLatencySamples (effect->initialDelay);
  26938. vstHostTime.tempo = 120.0;
  26939. vstHostTime.timeSigNumerator = 4;
  26940. vstHostTime.timeSigDenominator = 4;
  26941. vstHostTime.sampleRate = sampleRate_;
  26942. vstHostTime.samplePos = 0;
  26943. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  26944. initialise();
  26945. if (initialised)
  26946. {
  26947. wantsMidiMessages = wantsMidiMessages
  26948. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  26949. if (wantsMidiMessages)
  26950. midiEventsToSend.ensureSize (256);
  26951. else
  26952. midiEventsToSend.freeEvents();
  26953. incomingMidi.clear();
  26954. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  26955. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  26956. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  26957. if (! isPowerOn)
  26958. setPower (true);
  26959. // dodgy hack to force some plugins to initialise the sample rate..
  26960. if ((! hasEditor()) && getNumParameters() > 0)
  26961. {
  26962. const float old = getParameter (0);
  26963. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  26964. setParameter (0, old);
  26965. }
  26966. dispatch (effStartProcess, 0, 0, 0, 0);
  26967. }
  26968. }
  26969. void VSTPluginInstance::releaseResources()
  26970. {
  26971. if (initialised)
  26972. {
  26973. dispatch (effStopProcess, 0, 0, 0, 0);
  26974. setPower (false);
  26975. }
  26976. tempBuffer.setSize (1, 1);
  26977. incomingMidi.clear();
  26978. midiEventsToSend.freeEvents();
  26979. }
  26980. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  26981. MidiBuffer& midiMessages)
  26982. {
  26983. const int numSamples = buffer.getNumSamples();
  26984. if (initialised)
  26985. {
  26986. AudioPlayHead* playHead = getPlayHead();
  26987. if (playHead != 0)
  26988. {
  26989. AudioPlayHead::CurrentPositionInfo position;
  26990. playHead->getCurrentPosition (position);
  26991. vstHostTime.tempo = position.bpm;
  26992. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  26993. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  26994. vstHostTime.ppqPos = position.ppqPosition;
  26995. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  26996. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  26997. if (position.isPlaying)
  26998. vstHostTime.flags |= kVstTransportPlaying;
  26999. else
  27000. vstHostTime.flags &= ~kVstTransportPlaying;
  27001. }
  27002. vstHostTime.nanoSeconds = getVSTHostTimeNanoseconds();
  27003. if (wantsMidiMessages)
  27004. {
  27005. midiEventsToSend.clear();
  27006. midiEventsToSend.ensureSize (1);
  27007. MidiBuffer::Iterator iter (midiMessages);
  27008. const uint8* midiData;
  27009. int numBytesOfMidiData, samplePosition;
  27010. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  27011. {
  27012. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  27013. jlimit (0, numSamples - 1, samplePosition));
  27014. }
  27015. try
  27016. {
  27017. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  27018. }
  27019. catch (...)
  27020. {}
  27021. }
  27022. _clearfp();
  27023. if ((effect->flags & effFlagsCanReplacing) != 0)
  27024. {
  27025. try
  27026. {
  27027. effect->processReplacing (effect, buffer.getArrayOfChannels(), buffer.getArrayOfChannels(), numSamples);
  27028. }
  27029. catch (...)
  27030. {}
  27031. }
  27032. else
  27033. {
  27034. tempBuffer.setSize (effect->numOutputs, numSamples);
  27035. tempBuffer.clear();
  27036. try
  27037. {
  27038. effect->process (effect, buffer.getArrayOfChannels(), tempBuffer.getArrayOfChannels(), numSamples);
  27039. }
  27040. catch (...)
  27041. {}
  27042. for (int i = effect->numOutputs; --i >= 0;)
  27043. buffer.copyFrom (i, 0, tempBuffer.getSampleData (i), numSamples);
  27044. }
  27045. }
  27046. else
  27047. {
  27048. // Not initialised, so just bypass..
  27049. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27050. buffer.clear (i, 0, buffer.getNumSamples());
  27051. }
  27052. {
  27053. // copy any incoming midi..
  27054. const ScopedLock sl (midiInLock);
  27055. midiMessages.swapWith (incomingMidi);
  27056. incomingMidi.clear();
  27057. }
  27058. }
  27059. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27060. {
  27061. if (events != 0)
  27062. {
  27063. const ScopedLock sl (midiInLock);
  27064. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27065. }
  27066. }
  27067. static Array <VSTPluginWindow*> activeVSTWindows;
  27068. class VSTPluginWindow : public AudioProcessorEditor,
  27069. #if ! JUCE_MAC
  27070. public ComponentMovementWatcher,
  27071. #endif
  27072. public Timer
  27073. {
  27074. public:
  27075. VSTPluginWindow (VSTPluginInstance& plugin_)
  27076. : AudioProcessorEditor (&plugin_),
  27077. #if ! JUCE_MAC
  27078. ComponentMovementWatcher (this),
  27079. #endif
  27080. plugin (plugin_),
  27081. isOpen (false),
  27082. recursiveResize (false),
  27083. pluginWantsKeys (false),
  27084. pluginRefusesToResize (false),
  27085. alreadyInside (false)
  27086. {
  27087. #if JUCE_WINDOWS
  27088. sizeCheckCount = 0;
  27089. pluginHWND = 0;
  27090. #elif JUCE_LINUX
  27091. pluginWindow = None;
  27092. pluginProc = None;
  27093. #else
  27094. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27095. #endif
  27096. activeVSTWindows.add (this);
  27097. setSize (1, 1);
  27098. setOpaque (true);
  27099. setVisible (true);
  27100. }
  27101. ~VSTPluginWindow()
  27102. {
  27103. #if JUCE_MAC
  27104. innerWrapper = 0;
  27105. #else
  27106. closePluginWindow();
  27107. #endif
  27108. activeVSTWindows.removeValue (this);
  27109. plugin.editorBeingDeleted (this);
  27110. }
  27111. #if ! JUCE_MAC
  27112. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27113. {
  27114. if (recursiveResize)
  27115. return;
  27116. Component* const topComp = getTopLevelComponent();
  27117. if (topComp->getPeer() != 0)
  27118. {
  27119. const Point<int> pos (topComp->getLocalPoint (this, Point<int>()));
  27120. recursiveResize = true;
  27121. #if JUCE_WINDOWS
  27122. if (pluginHWND != 0)
  27123. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27124. #elif JUCE_LINUX
  27125. if (pluginWindow != 0)
  27126. {
  27127. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27128. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27129. XMapRaised (display, pluginWindow);
  27130. }
  27131. #endif
  27132. recursiveResize = false;
  27133. }
  27134. }
  27135. void componentVisibilityChanged()
  27136. {
  27137. if (isShowing())
  27138. openPluginWindow();
  27139. else
  27140. closePluginWindow();
  27141. componentMovedOrResized (true, true);
  27142. }
  27143. void componentPeerChanged()
  27144. {
  27145. closePluginWindow();
  27146. openPluginWindow();
  27147. }
  27148. #endif
  27149. bool keyStateChanged (bool)
  27150. {
  27151. return pluginWantsKeys;
  27152. }
  27153. bool keyPressed (const KeyPress&)
  27154. {
  27155. return pluginWantsKeys;
  27156. }
  27157. #if JUCE_MAC
  27158. void paint (Graphics& g)
  27159. {
  27160. g.fillAll (Colours::black);
  27161. }
  27162. #else
  27163. void paint (Graphics& g)
  27164. {
  27165. if (isOpen)
  27166. {
  27167. ComponentPeer* const peer = getPeer();
  27168. if (peer != 0)
  27169. {
  27170. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27171. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27172. #if JUCE_LINUX
  27173. if (pluginWindow != 0)
  27174. {
  27175. const Rectangle<int> clip (g.getClipBounds());
  27176. XEvent ev;
  27177. zerostruct (ev);
  27178. ev.xexpose.type = Expose;
  27179. ev.xexpose.display = display;
  27180. ev.xexpose.window = pluginWindow;
  27181. ev.xexpose.x = clip.getX();
  27182. ev.xexpose.y = clip.getY();
  27183. ev.xexpose.width = clip.getWidth();
  27184. ev.xexpose.height = clip.getHeight();
  27185. sendEventToChild (&ev);
  27186. }
  27187. #endif
  27188. }
  27189. }
  27190. else
  27191. {
  27192. g.fillAll (Colours::black);
  27193. }
  27194. }
  27195. #endif
  27196. void timerCallback()
  27197. {
  27198. #if JUCE_WINDOWS
  27199. if (--sizeCheckCount <= 0)
  27200. {
  27201. sizeCheckCount = 10;
  27202. checkPluginWindowSize();
  27203. }
  27204. #endif
  27205. try
  27206. {
  27207. static bool reentrant = false;
  27208. if (! reentrant)
  27209. {
  27210. reentrant = true;
  27211. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27212. reentrant = false;
  27213. }
  27214. }
  27215. catch (...)
  27216. {}
  27217. }
  27218. void mouseDown (const MouseEvent& e)
  27219. {
  27220. #if JUCE_LINUX
  27221. if (pluginWindow == 0)
  27222. return;
  27223. toFront (true);
  27224. XEvent ev;
  27225. zerostruct (ev);
  27226. ev.xbutton.display = display;
  27227. ev.xbutton.type = ButtonPress;
  27228. ev.xbutton.window = pluginWindow;
  27229. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27230. ev.xbutton.time = CurrentTime;
  27231. ev.xbutton.x = e.x;
  27232. ev.xbutton.y = e.y;
  27233. ev.xbutton.x_root = e.getScreenX();
  27234. ev.xbutton.y_root = e.getScreenY();
  27235. translateJuceToXButtonModifiers (e, ev);
  27236. sendEventToChild (&ev);
  27237. #elif JUCE_WINDOWS
  27238. (void) e;
  27239. toFront (true);
  27240. #endif
  27241. }
  27242. void broughtToFront()
  27243. {
  27244. activeVSTWindows.removeValue (this);
  27245. activeVSTWindows.add (this);
  27246. #if JUCE_MAC
  27247. dispatch (effEditTop, 0, 0, 0, 0);
  27248. #endif
  27249. }
  27250. private:
  27251. VSTPluginInstance& plugin;
  27252. bool isOpen, recursiveResize;
  27253. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27254. #if JUCE_WINDOWS
  27255. HWND pluginHWND;
  27256. void* originalWndProc;
  27257. int sizeCheckCount;
  27258. #elif JUCE_LINUX
  27259. Window pluginWindow;
  27260. EventProcPtr pluginProc;
  27261. #endif
  27262. #if JUCE_MAC
  27263. void openPluginWindow (WindowRef parentWindow)
  27264. {
  27265. if (isOpen || parentWindow == 0)
  27266. return;
  27267. isOpen = true;
  27268. ERect* rect = 0;
  27269. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27270. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27271. // do this before and after like in the steinberg example
  27272. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27273. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27274. // Install keyboard hooks
  27275. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27276. // double-check it's not too tiny
  27277. int w = 250, h = 150;
  27278. if (rect != 0)
  27279. {
  27280. w = rect->right - rect->left;
  27281. h = rect->bottom - rect->top;
  27282. if (w == 0 || h == 0)
  27283. {
  27284. w = 250;
  27285. h = 150;
  27286. }
  27287. }
  27288. w = jmax (w, 32);
  27289. h = jmax (h, 32);
  27290. setSize (w, h);
  27291. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27292. repaint();
  27293. }
  27294. #else
  27295. void openPluginWindow()
  27296. {
  27297. if (isOpen || getWindowHandle() == 0)
  27298. return;
  27299. log ("Opening VST UI: " + plugin.name);
  27300. isOpen = true;
  27301. ERect* rect = 0;
  27302. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27303. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27304. // do this before and after like in the steinberg example
  27305. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27306. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27307. // Install keyboard hooks
  27308. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27309. #if JUCE_WINDOWS
  27310. originalWndProc = 0;
  27311. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27312. if (pluginHWND == 0)
  27313. {
  27314. isOpen = false;
  27315. setSize (300, 150);
  27316. return;
  27317. }
  27318. #pragma warning (push)
  27319. #pragma warning (disable: 4244)
  27320. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWLP_WNDPROC);
  27321. if (! pluginWantsKeys)
  27322. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27323. #pragma warning (pop)
  27324. int w, h;
  27325. RECT r;
  27326. GetWindowRect (pluginHWND, &r);
  27327. w = r.right - r.left;
  27328. h = r.bottom - r.top;
  27329. if (rect != 0)
  27330. {
  27331. const int rw = rect->right - rect->left;
  27332. const int rh = rect->bottom - rect->top;
  27333. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27334. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27335. {
  27336. // very dodgy logic to decide which size is right.
  27337. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27338. {
  27339. SetWindowPos (pluginHWND, 0,
  27340. 0, 0, rw, rh,
  27341. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27342. GetWindowRect (pluginHWND, &r);
  27343. w = r.right - r.left;
  27344. h = r.bottom - r.top;
  27345. pluginRefusesToResize = (w != rw) || (h != rh);
  27346. w = rw;
  27347. h = rh;
  27348. }
  27349. }
  27350. }
  27351. #elif JUCE_LINUX
  27352. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27353. if (pluginWindow != 0)
  27354. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27355. XInternAtom (display, "_XEventProc", False));
  27356. int w = 250, h = 150;
  27357. if (rect != 0)
  27358. {
  27359. w = rect->right - rect->left;
  27360. h = rect->bottom - rect->top;
  27361. if (w == 0 || h == 0)
  27362. {
  27363. w = 250;
  27364. h = 150;
  27365. }
  27366. }
  27367. if (pluginWindow != 0)
  27368. XMapRaised (display, pluginWindow);
  27369. #endif
  27370. // double-check it's not too tiny
  27371. w = jmax (w, 32);
  27372. h = jmax (h, 32);
  27373. setSize (w, h);
  27374. #if JUCE_WINDOWS
  27375. checkPluginWindowSize();
  27376. #endif
  27377. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27378. repaint();
  27379. }
  27380. #endif
  27381. #if ! JUCE_MAC
  27382. void closePluginWindow()
  27383. {
  27384. if (isOpen)
  27385. {
  27386. log ("Closing VST UI: " + plugin.getName());
  27387. isOpen = false;
  27388. dispatch (effEditClose, 0, 0, 0, 0);
  27389. #if JUCE_WINDOWS
  27390. #pragma warning (push)
  27391. #pragma warning (disable: 4244)
  27392. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27393. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27394. #pragma warning (pop)
  27395. stopTimer();
  27396. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27397. DestroyWindow (pluginHWND);
  27398. pluginHWND = 0;
  27399. #elif JUCE_LINUX
  27400. stopTimer();
  27401. pluginWindow = 0;
  27402. pluginProc = 0;
  27403. #endif
  27404. }
  27405. }
  27406. #endif
  27407. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27408. {
  27409. return plugin.dispatch (opcode, index, value, ptr, opt);
  27410. }
  27411. #if JUCE_WINDOWS
  27412. void checkPluginWindowSize()
  27413. {
  27414. RECT r;
  27415. GetWindowRect (pluginHWND, &r);
  27416. const int w = r.right - r.left;
  27417. const int h = r.bottom - r.top;
  27418. if (isShowing() && w > 0 && h > 0
  27419. && (w != getWidth() || h != getHeight())
  27420. && ! pluginRefusesToResize)
  27421. {
  27422. setSize (w, h);
  27423. sizeCheckCount = 0;
  27424. }
  27425. }
  27426. // hooks to get keyboard events from VST windows..
  27427. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27428. {
  27429. for (int i = activeVSTWindows.size(); --i >= 0;)
  27430. {
  27431. const VSTPluginWindow* const w = activeVSTWindows.getUnchecked (i);
  27432. if (w->pluginHWND == hW)
  27433. {
  27434. if (message == WM_CHAR
  27435. || message == WM_KEYDOWN
  27436. || message == WM_SYSKEYDOWN
  27437. || message == WM_KEYUP
  27438. || message == WM_SYSKEYUP
  27439. || message == WM_APPCOMMAND)
  27440. {
  27441. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27442. message, wParam, lParam);
  27443. }
  27444. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27445. (HWND) w->pluginHWND,
  27446. message,
  27447. wParam,
  27448. lParam);
  27449. }
  27450. }
  27451. return DefWindowProc (hW, message, wParam, lParam);
  27452. }
  27453. #endif
  27454. #if JUCE_LINUX
  27455. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27456. void sendEventToChild (XEvent* event)
  27457. {
  27458. if (pluginProc != 0)
  27459. {
  27460. // if the plugin publishes an event procedure, pass the event directly..
  27461. pluginProc (event);
  27462. }
  27463. else if (pluginWindow != 0)
  27464. {
  27465. // if the plugin has a window, then send the event to the window so that
  27466. // its message thread will pick it up..
  27467. XSendEvent (display, pluginWindow, False, 0L, event);
  27468. XFlush (display);
  27469. }
  27470. }
  27471. void mouseEnter (const MouseEvent& e)
  27472. {
  27473. if (pluginWindow != 0)
  27474. {
  27475. XEvent ev;
  27476. zerostruct (ev);
  27477. ev.xcrossing.display = display;
  27478. ev.xcrossing.type = EnterNotify;
  27479. ev.xcrossing.window = pluginWindow;
  27480. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27481. ev.xcrossing.time = CurrentTime;
  27482. ev.xcrossing.x = e.x;
  27483. ev.xcrossing.y = e.y;
  27484. ev.xcrossing.x_root = e.getScreenX();
  27485. ev.xcrossing.y_root = e.getScreenY();
  27486. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27487. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27488. translateJuceToXCrossingModifiers (e, ev);
  27489. sendEventToChild (&ev);
  27490. }
  27491. }
  27492. void mouseExit (const MouseEvent& e)
  27493. {
  27494. if (pluginWindow != 0)
  27495. {
  27496. XEvent ev;
  27497. zerostruct (ev);
  27498. ev.xcrossing.display = display;
  27499. ev.xcrossing.type = LeaveNotify;
  27500. ev.xcrossing.window = pluginWindow;
  27501. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27502. ev.xcrossing.time = CurrentTime;
  27503. ev.xcrossing.x = e.x;
  27504. ev.xcrossing.y = e.y;
  27505. ev.xcrossing.x_root = e.getScreenX();
  27506. ev.xcrossing.y_root = e.getScreenY();
  27507. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27508. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27509. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27510. translateJuceToXCrossingModifiers (e, ev);
  27511. sendEventToChild (&ev);
  27512. }
  27513. }
  27514. void mouseMove (const MouseEvent& e)
  27515. {
  27516. if (pluginWindow != 0)
  27517. {
  27518. XEvent ev;
  27519. zerostruct (ev);
  27520. ev.xmotion.display = display;
  27521. ev.xmotion.type = MotionNotify;
  27522. ev.xmotion.window = pluginWindow;
  27523. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27524. ev.xmotion.time = CurrentTime;
  27525. ev.xmotion.is_hint = NotifyNormal;
  27526. ev.xmotion.x = e.x;
  27527. ev.xmotion.y = e.y;
  27528. ev.xmotion.x_root = e.getScreenX();
  27529. ev.xmotion.y_root = e.getScreenY();
  27530. sendEventToChild (&ev);
  27531. }
  27532. }
  27533. void mouseDrag (const MouseEvent& e)
  27534. {
  27535. if (pluginWindow != 0)
  27536. {
  27537. XEvent ev;
  27538. zerostruct (ev);
  27539. ev.xmotion.display = display;
  27540. ev.xmotion.type = MotionNotify;
  27541. ev.xmotion.window = pluginWindow;
  27542. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27543. ev.xmotion.time = CurrentTime;
  27544. ev.xmotion.x = e.x ;
  27545. ev.xmotion.y = e.y;
  27546. ev.xmotion.x_root = e.getScreenX();
  27547. ev.xmotion.y_root = e.getScreenY();
  27548. ev.xmotion.is_hint = NotifyNormal;
  27549. translateJuceToXMotionModifiers (e, ev);
  27550. sendEventToChild (&ev);
  27551. }
  27552. }
  27553. void mouseUp (const MouseEvent& e)
  27554. {
  27555. if (pluginWindow != 0)
  27556. {
  27557. XEvent ev;
  27558. zerostruct (ev);
  27559. ev.xbutton.display = display;
  27560. ev.xbutton.type = ButtonRelease;
  27561. ev.xbutton.window = pluginWindow;
  27562. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27563. ev.xbutton.time = CurrentTime;
  27564. ev.xbutton.x = e.x;
  27565. ev.xbutton.y = e.y;
  27566. ev.xbutton.x_root = e.getScreenX();
  27567. ev.xbutton.y_root = e.getScreenY();
  27568. translateJuceToXButtonModifiers (e, ev);
  27569. sendEventToChild (&ev);
  27570. }
  27571. }
  27572. void mouseWheelMove (const MouseEvent& e,
  27573. float incrementX,
  27574. float incrementY)
  27575. {
  27576. if (pluginWindow != 0)
  27577. {
  27578. XEvent ev;
  27579. zerostruct (ev);
  27580. ev.xbutton.display = display;
  27581. ev.xbutton.type = ButtonPress;
  27582. ev.xbutton.window = pluginWindow;
  27583. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27584. ev.xbutton.time = CurrentTime;
  27585. ev.xbutton.x = e.x;
  27586. ev.xbutton.y = e.y;
  27587. ev.xbutton.x_root = e.getScreenX();
  27588. ev.xbutton.y_root = e.getScreenY();
  27589. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27590. sendEventToChild (&ev);
  27591. // TODO - put a usleep here ?
  27592. ev.xbutton.type = ButtonRelease;
  27593. sendEventToChild (&ev);
  27594. }
  27595. }
  27596. #endif
  27597. #if JUCE_MAC
  27598. #if ! JUCE_SUPPORT_CARBON
  27599. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27600. #endif
  27601. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27602. {
  27603. public:
  27604. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27605. : owner (owner_),
  27606. alreadyInside (false)
  27607. {
  27608. }
  27609. ~InnerWrapperComponent()
  27610. {
  27611. deleteWindow();
  27612. }
  27613. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27614. {
  27615. owner->openPluginWindow (windowRef);
  27616. return 0;
  27617. }
  27618. void removeView (HIViewRef)
  27619. {
  27620. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27621. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27622. }
  27623. bool getEmbeddedViewSize (int& w, int& h)
  27624. {
  27625. ERect* rect = 0;
  27626. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27627. w = rect->right - rect->left;
  27628. h = rect->bottom - rect->top;
  27629. return true;
  27630. }
  27631. void mouseDown (int x, int y)
  27632. {
  27633. if (! alreadyInside)
  27634. {
  27635. alreadyInside = true;
  27636. getTopLevelComponent()->toFront (true);
  27637. owner->dispatch (effEditMouse, x, y, 0, 0);
  27638. alreadyInside = false;
  27639. }
  27640. else
  27641. {
  27642. PostEvent (::mouseDown, 0);
  27643. }
  27644. }
  27645. void paint()
  27646. {
  27647. ComponentPeer* const peer = getPeer();
  27648. if (peer != 0)
  27649. {
  27650. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27651. ERect r;
  27652. r.left = pos.getX();
  27653. r.right = r.left + getWidth();
  27654. r.top = pos.getY();
  27655. r.bottom = r.top + getHeight();
  27656. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27657. }
  27658. }
  27659. private:
  27660. VSTPluginWindow* const owner;
  27661. bool alreadyInside;
  27662. };
  27663. friend class InnerWrapperComponent;
  27664. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27665. void resized()
  27666. {
  27667. innerWrapper->setSize (getWidth(), getHeight());
  27668. }
  27669. #endif
  27670. private:
  27671. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginWindow);
  27672. };
  27673. AudioProcessorEditor* VSTPluginInstance::createEditor()
  27674. {
  27675. if (hasEditor())
  27676. return new VSTPluginWindow (*this);
  27677. return 0;
  27678. }
  27679. void VSTPluginInstance::handleAsyncUpdate()
  27680. {
  27681. // indicates that something about the plugin has changed..
  27682. updateHostDisplay();
  27683. }
  27684. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  27685. {
  27686. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  27687. {
  27688. changeProgramName (getCurrentProgram(), prog->prgName);
  27689. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27690. setParameter (i, vst_swapFloat (prog->params[i]));
  27691. return true;
  27692. }
  27693. return false;
  27694. }
  27695. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  27696. const int dataSize)
  27697. {
  27698. if (dataSize < 28)
  27699. return false;
  27700. const fxSet* const set = (const fxSet*) data;
  27701. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  27702. || vst_swap (set->version) > fxbVersionNum)
  27703. return false;
  27704. if (vst_swap (set->fxMagic) == 'FxBk')
  27705. {
  27706. // bank of programs
  27707. if (vst_swap (set->numPrograms) >= 0)
  27708. {
  27709. const int oldProg = getCurrentProgram();
  27710. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  27711. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27712. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  27713. {
  27714. if (i != oldProg)
  27715. {
  27716. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  27717. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27718. return false;
  27719. if (vst_swap (set->numPrograms) > 0)
  27720. setCurrentProgram (i);
  27721. if (! restoreProgramSettings (prog))
  27722. return false;
  27723. }
  27724. }
  27725. if (vst_swap (set->numPrograms) > 0)
  27726. setCurrentProgram (oldProg);
  27727. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  27728. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27729. return false;
  27730. if (! restoreProgramSettings (prog))
  27731. return false;
  27732. }
  27733. }
  27734. else if (vst_swap (set->fxMagic) == 'FxCk')
  27735. {
  27736. // single program
  27737. const fxProgram* const prog = (const fxProgram*) data;
  27738. if (vst_swap (prog->chunkMagic) != 'CcnK')
  27739. return false;
  27740. changeProgramName (getCurrentProgram(), prog->prgName);
  27741. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27742. setParameter (i, vst_swapFloat (prog->params[i]));
  27743. }
  27744. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  27745. {
  27746. // non-preset chunk
  27747. const fxChunkSet* const cset = (const fxChunkSet*) data;
  27748. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  27749. return false;
  27750. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27751. }
  27752. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27753. {
  27754. // preset chunk
  27755. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27756. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27757. return false;
  27758. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  27759. changeProgramName (getCurrentProgram(), cset->name);
  27760. }
  27761. else
  27762. {
  27763. return false;
  27764. }
  27765. return true;
  27766. }
  27767. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog)
  27768. {
  27769. const int numParams = getNumParameters();
  27770. prog->chunkMagic = vst_swap ('CcnK');
  27771. prog->byteSize = 0;
  27772. prog->fxMagic = vst_swap ('FxCk');
  27773. prog->version = vst_swap (fxbVersionNum);
  27774. prog->fxID = vst_swap (getUID());
  27775. prog->fxVersion = vst_swap (getVersionNumber());
  27776. prog->numParams = vst_swap (numParams);
  27777. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27778. for (int i = 0; i < numParams; ++i)
  27779. prog->params[i] = vst_swapFloat (getParameter (i));
  27780. }
  27781. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27782. {
  27783. const int numPrograms = getNumPrograms();
  27784. const int numParams = getNumParameters();
  27785. if (usesChunks())
  27786. {
  27787. if (isFXB)
  27788. {
  27789. MemoryBlock chunk;
  27790. getChunkData (chunk, false, maxSizeMB);
  27791. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27792. dest.setSize (totalLen, true);
  27793. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27794. set->chunkMagic = vst_swap ('CcnK');
  27795. set->byteSize = 0;
  27796. set->fxMagic = vst_swap ('FBCh');
  27797. set->version = vst_swap (fxbVersionNum);
  27798. set->fxID = vst_swap (getUID());
  27799. set->fxVersion = vst_swap (getVersionNumber());
  27800. set->numPrograms = vst_swap (numPrograms);
  27801. set->chunkSize = vst_swap ((long) chunk.getSize());
  27802. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27803. }
  27804. else
  27805. {
  27806. MemoryBlock chunk;
  27807. getChunkData (chunk, true, maxSizeMB);
  27808. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27809. dest.setSize (totalLen, true);
  27810. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27811. set->chunkMagic = vst_swap ('CcnK');
  27812. set->byteSize = 0;
  27813. set->fxMagic = vst_swap ('FPCh');
  27814. set->version = vst_swap (fxbVersionNum);
  27815. set->fxID = vst_swap (getUID());
  27816. set->fxVersion = vst_swap (getVersionNumber());
  27817. set->numPrograms = vst_swap (numPrograms);
  27818. set->chunkSize = vst_swap ((long) chunk.getSize());
  27819. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27820. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27821. }
  27822. }
  27823. else
  27824. {
  27825. if (isFXB)
  27826. {
  27827. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27828. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27829. dest.setSize (len, true);
  27830. fxSet* const set = (fxSet*) dest.getData();
  27831. set->chunkMagic = vst_swap ('CcnK');
  27832. set->byteSize = 0;
  27833. set->fxMagic = vst_swap ('FxBk');
  27834. set->version = vst_swap (fxbVersionNum);
  27835. set->fxID = vst_swap (getUID());
  27836. set->fxVersion = vst_swap (getVersionNumber());
  27837. set->numPrograms = vst_swap (numPrograms);
  27838. const int oldProgram = getCurrentProgram();
  27839. MemoryBlock oldSettings;
  27840. createTempParameterStore (oldSettings);
  27841. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27842. for (int i = 0; i < numPrograms; ++i)
  27843. {
  27844. if (i != oldProgram)
  27845. {
  27846. setCurrentProgram (i);
  27847. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27848. }
  27849. }
  27850. setCurrentProgram (oldProgram);
  27851. restoreFromTempParameterStore (oldSettings);
  27852. }
  27853. else
  27854. {
  27855. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27856. dest.setSize (totalLen, true);
  27857. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27858. }
  27859. }
  27860. return true;
  27861. }
  27862. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  27863. {
  27864. if (usesChunks())
  27865. {
  27866. void* data = 0;
  27867. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  27868. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  27869. {
  27870. mb.setSize (bytes);
  27871. mb.copyFrom (data, 0, bytes);
  27872. }
  27873. }
  27874. }
  27875. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  27876. {
  27877. if (size > 0 && usesChunks())
  27878. {
  27879. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  27880. if (! isPreset)
  27881. updateStoredProgramNames();
  27882. }
  27883. }
  27884. void VSTPluginInstance::timerCallback()
  27885. {
  27886. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  27887. stopTimer();
  27888. }
  27889. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  27890. {
  27891. const ScopedLock sl (lock);
  27892. ++insideVSTCallback;
  27893. int result = 0;
  27894. try
  27895. {
  27896. if (effect != 0)
  27897. {
  27898. #if JUCE_MAC
  27899. if (module->resFileId != 0)
  27900. UseResFile (module->resFileId);
  27901. #endif
  27902. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  27903. #if JUCE_MAC
  27904. module->resFileId = CurResFile();
  27905. #endif
  27906. --insideVSTCallback;
  27907. return result;
  27908. }
  27909. }
  27910. catch (...)
  27911. {
  27912. }
  27913. --insideVSTCallback;
  27914. return result;
  27915. }
  27916. namespace
  27917. {
  27918. static const int defaultVSTSampleRateValue = 16384;
  27919. static const int defaultVSTBlockSizeValue = 512;
  27920. // handles non plugin-specific callbacks..
  27921. VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27922. {
  27923. (void) index;
  27924. (void) value;
  27925. (void) opt;
  27926. switch (opcode)
  27927. {
  27928. case audioMasterCanDo:
  27929. {
  27930. static const char* canDos[] = { "supplyIdle",
  27931. "sendVstEvents",
  27932. "sendVstMidiEvent",
  27933. "sendVstTimeInfo",
  27934. "receiveVstEvents",
  27935. "receiveVstMidiEvent",
  27936. "supportShell",
  27937. "shellCategory" };
  27938. for (int i = 0; i < numElementsInArray (canDos); ++i)
  27939. if (strcmp (canDos[i], (const char*) ptr) == 0)
  27940. return 1;
  27941. return 0;
  27942. }
  27943. case audioMasterVersion: return 0x2400;
  27944. case audioMasterCurrentId: return shellUIDToCreate;
  27945. case audioMasterGetNumAutomatableParameters: return 0;
  27946. case audioMasterGetAutomationState: return 1;
  27947. case audioMasterGetVendorVersion: return 0x0101;
  27948. case audioMasterGetVendorString:
  27949. case audioMasterGetProductString:
  27950. {
  27951. String hostName ("Juce VST Host");
  27952. if (JUCEApplication::getInstance() != 0)
  27953. hostName = JUCEApplication::getInstance()->getApplicationName();
  27954. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  27955. break;
  27956. }
  27957. case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue;
  27958. case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue;
  27959. case audioMasterSetOutputSampleRate: return 0;
  27960. default:
  27961. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  27962. break;
  27963. }
  27964. return 0;
  27965. }
  27966. }
  27967. // handles callbacks for a specific plugin
  27968. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27969. {
  27970. switch (opcode)
  27971. {
  27972. case audioMasterAutomate:
  27973. sendParamChangeMessageToListeners (index, opt);
  27974. break;
  27975. case audioMasterProcessEvents:
  27976. handleMidiFromPlugin ((const VstEvents*) ptr);
  27977. break;
  27978. case audioMasterGetTime:
  27979. #if JUCE_MSVC
  27980. #pragma warning (push)
  27981. #pragma warning (disable: 4311)
  27982. #endif
  27983. return (VstIntPtr) &vstHostTime;
  27984. #if JUCE_MSVC
  27985. #pragma warning (pop)
  27986. #endif
  27987. break;
  27988. case audioMasterIdle:
  27989. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  27990. {
  27991. ++insideVSTCallback;
  27992. #if JUCE_MAC
  27993. if (getActiveEditor() != 0)
  27994. dispatch (effEditIdle, 0, 0, 0, 0);
  27995. #endif
  27996. juce_callAnyTimersSynchronously();
  27997. handleUpdateNowIfNeeded();
  27998. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  27999. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  28000. --insideVSTCallback;
  28001. }
  28002. break;
  28003. case audioMasterUpdateDisplay:
  28004. triggerAsyncUpdate();
  28005. break;
  28006. case audioMasterTempoAt:
  28007. // returns (10000 * bpm)
  28008. break;
  28009. case audioMasterNeedIdle:
  28010. startTimer (50);
  28011. break;
  28012. case audioMasterSizeWindow:
  28013. if (getActiveEditor() != 0)
  28014. getActiveEditor()->setSize (index, value);
  28015. return 1;
  28016. case audioMasterGetSampleRate:
  28017. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  28018. case audioMasterGetBlockSize:
  28019. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28020. case audioMasterWantMidi:
  28021. wantsMidiMessages = true;
  28022. break;
  28023. case audioMasterGetDirectory:
  28024. #if JUCE_MAC
  28025. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28026. #else
  28027. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8().getAddress();
  28028. #endif
  28029. case audioMasterGetAutomationState:
  28030. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28031. break;
  28032. // none of these are handled (yet)..
  28033. case audioMasterBeginEdit:
  28034. case audioMasterEndEdit:
  28035. case audioMasterSetTime:
  28036. case audioMasterPinConnected:
  28037. case audioMasterGetParameterQuantization:
  28038. case audioMasterIOChanged:
  28039. case audioMasterGetInputLatency:
  28040. case audioMasterGetOutputLatency:
  28041. case audioMasterGetPreviousPlug:
  28042. case audioMasterGetNextPlug:
  28043. case audioMasterWillReplaceOrAccumulate:
  28044. case audioMasterGetCurrentProcessLevel:
  28045. case audioMasterOfflineStart:
  28046. case audioMasterOfflineRead:
  28047. case audioMasterOfflineWrite:
  28048. case audioMasterOfflineGetCurrentPass:
  28049. case audioMasterOfflineGetCurrentMetaPass:
  28050. case audioMasterVendorSpecific:
  28051. case audioMasterSetIcon:
  28052. case audioMasterGetLanguage:
  28053. case audioMasterOpenWindow:
  28054. case audioMasterCloseWindow:
  28055. break;
  28056. default:
  28057. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28058. }
  28059. return 0;
  28060. }
  28061. // entry point for all callbacks from the plugin
  28062. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28063. {
  28064. try
  28065. {
  28066. if (effect != 0 && effect->resvd2 != 0)
  28067. {
  28068. return ((VSTPluginInstance*)(effect->resvd2))
  28069. ->handleCallback (opcode, index, value, ptr, opt);
  28070. }
  28071. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28072. }
  28073. catch (...)
  28074. {
  28075. return 0;
  28076. }
  28077. }
  28078. const String VSTPluginInstance::getVersion() const
  28079. {
  28080. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28081. String s;
  28082. if (v == 0 || v == -1)
  28083. v = getVersionNumber();
  28084. if (v != 0)
  28085. {
  28086. int versionBits[4];
  28087. int n = 0;
  28088. while (v != 0)
  28089. {
  28090. versionBits [n++] = (v & 0xff);
  28091. v >>= 8;
  28092. }
  28093. s << 'V';
  28094. while (n > 0)
  28095. {
  28096. s << versionBits [--n];
  28097. if (n > 0)
  28098. s << '.';
  28099. }
  28100. }
  28101. return s;
  28102. }
  28103. int VSTPluginInstance::getUID() const
  28104. {
  28105. int uid = effect != 0 ? effect->uniqueID : 0;
  28106. if (uid == 0)
  28107. uid = module->file.hashCode();
  28108. return uid;
  28109. }
  28110. const String VSTPluginInstance::getCategory() const
  28111. {
  28112. const char* result = 0;
  28113. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28114. {
  28115. case kPlugCategEffect: result = "Effect"; break;
  28116. case kPlugCategSynth: result = "Synth"; break;
  28117. case kPlugCategAnalysis: result = "Anaylsis"; break;
  28118. case kPlugCategMastering: result = "Mastering"; break;
  28119. case kPlugCategSpacializer: result = "Spacial"; break;
  28120. case kPlugCategRoomFx: result = "Reverb"; break;
  28121. case kPlugSurroundFx: result = "Surround"; break;
  28122. case kPlugCategRestoration: result = "Restoration"; break;
  28123. case kPlugCategGenerator: result = "Tone generation"; break;
  28124. default: break;
  28125. }
  28126. return result;
  28127. }
  28128. float VSTPluginInstance::getParameter (int index)
  28129. {
  28130. if (effect != 0 && isPositiveAndBelow (index, (int) effect->numParams))
  28131. {
  28132. try
  28133. {
  28134. const ScopedLock sl (lock);
  28135. return effect->getParameter (effect, index);
  28136. }
  28137. catch (...)
  28138. {
  28139. }
  28140. }
  28141. return 0.0f;
  28142. }
  28143. void VSTPluginInstance::setParameter (int index, float newValue)
  28144. {
  28145. if (effect != 0 && isPositiveAndBelow (index, (int) effect->numParams))
  28146. {
  28147. try
  28148. {
  28149. const ScopedLock sl (lock);
  28150. if (effect->getParameter (effect, index) != newValue)
  28151. effect->setParameter (effect, index, newValue);
  28152. }
  28153. catch (...)
  28154. {
  28155. }
  28156. }
  28157. }
  28158. const String VSTPluginInstance::getParameterName (int index)
  28159. {
  28160. if (effect != 0)
  28161. {
  28162. jassert (index >= 0 && index < effect->numParams);
  28163. char nm [256];
  28164. zerostruct (nm);
  28165. dispatch (effGetParamName, index, 0, nm, 0);
  28166. return String (nm).trim();
  28167. }
  28168. return String::empty;
  28169. }
  28170. const String VSTPluginInstance::getParameterLabel (int index) const
  28171. {
  28172. if (effect != 0)
  28173. {
  28174. jassert (index >= 0 && index < effect->numParams);
  28175. char nm [256];
  28176. zerostruct (nm);
  28177. dispatch (effGetParamLabel, index, 0, nm, 0);
  28178. return String (nm).trim();
  28179. }
  28180. return String::empty;
  28181. }
  28182. const String VSTPluginInstance::getParameterText (int index)
  28183. {
  28184. if (effect != 0)
  28185. {
  28186. jassert (index >= 0 && index < effect->numParams);
  28187. char nm [256];
  28188. zerostruct (nm);
  28189. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28190. return String (nm).trim();
  28191. }
  28192. return String::empty;
  28193. }
  28194. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28195. {
  28196. if (effect != 0)
  28197. {
  28198. jassert (index >= 0 && index < effect->numParams);
  28199. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28200. }
  28201. return false;
  28202. }
  28203. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28204. {
  28205. dest.setSize (64 + 4 * getNumParameters());
  28206. dest.fillWith (0);
  28207. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28208. float* const p = (float*) (((char*) dest.getData()) + 64);
  28209. for (int i = 0; i < getNumParameters(); ++i)
  28210. p[i] = getParameter(i);
  28211. }
  28212. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28213. {
  28214. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28215. float* p = (float*) (((char*) m.getData()) + 64);
  28216. for (int i = 0; i < getNumParameters(); ++i)
  28217. setParameter (i, p[i]);
  28218. }
  28219. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28220. {
  28221. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28222. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28223. }
  28224. const String VSTPluginInstance::getProgramName (int index)
  28225. {
  28226. if (index == getCurrentProgram())
  28227. {
  28228. return getCurrentProgramName();
  28229. }
  28230. else if (effect != 0)
  28231. {
  28232. char nm [256];
  28233. zerostruct (nm);
  28234. if (dispatch (effGetProgramNameIndexed,
  28235. jlimit (0, getNumPrograms(), index),
  28236. -1, nm, 0) != 0)
  28237. {
  28238. return String (nm).trim();
  28239. }
  28240. }
  28241. return programNames [index];
  28242. }
  28243. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28244. {
  28245. if (index == getCurrentProgram())
  28246. {
  28247. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28248. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28249. }
  28250. else
  28251. {
  28252. jassertfalse; // xxx not implemented!
  28253. }
  28254. }
  28255. void VSTPluginInstance::updateStoredProgramNames()
  28256. {
  28257. if (effect != 0 && getNumPrograms() > 0)
  28258. {
  28259. char nm [256];
  28260. zerostruct (nm);
  28261. // only do this if the plugin can't use indexed names..
  28262. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28263. {
  28264. const int oldProgram = getCurrentProgram();
  28265. MemoryBlock oldSettings;
  28266. createTempParameterStore (oldSettings);
  28267. for (int i = 0; i < getNumPrograms(); ++i)
  28268. {
  28269. setCurrentProgram (i);
  28270. getCurrentProgramName(); // (this updates the list)
  28271. }
  28272. setCurrentProgram (oldProgram);
  28273. restoreFromTempParameterStore (oldSettings);
  28274. }
  28275. }
  28276. }
  28277. const String VSTPluginInstance::getCurrentProgramName()
  28278. {
  28279. if (effect != 0)
  28280. {
  28281. char nm [256];
  28282. zerostruct (nm);
  28283. dispatch (effGetProgramName, 0, 0, nm, 0);
  28284. const int index = getCurrentProgram();
  28285. if (programNames[index].isEmpty())
  28286. {
  28287. while (programNames.size() < index)
  28288. programNames.add (String::empty);
  28289. programNames.set (index, String (nm).trim());
  28290. }
  28291. return String (nm).trim();
  28292. }
  28293. return String::empty;
  28294. }
  28295. const String VSTPluginInstance::getInputChannelName (int index) const
  28296. {
  28297. if (index >= 0 && index < getNumInputChannels())
  28298. {
  28299. VstPinProperties pinProps;
  28300. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28301. return String (pinProps.label, sizeof (pinProps.label));
  28302. }
  28303. return String::empty;
  28304. }
  28305. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28306. {
  28307. if (index < 0 || index >= getNumInputChannels())
  28308. return false;
  28309. VstPinProperties pinProps;
  28310. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28311. return (pinProps.flags & kVstPinIsStereo) != 0;
  28312. return true;
  28313. }
  28314. const String VSTPluginInstance::getOutputChannelName (int index) const
  28315. {
  28316. if (index >= 0 && index < getNumOutputChannels())
  28317. {
  28318. VstPinProperties pinProps;
  28319. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28320. return String (pinProps.label, sizeof (pinProps.label));
  28321. }
  28322. return String::empty;
  28323. }
  28324. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28325. {
  28326. if (index < 0 || index >= getNumOutputChannels())
  28327. return false;
  28328. VstPinProperties pinProps;
  28329. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28330. return (pinProps.flags & kVstPinIsStereo) != 0;
  28331. return true;
  28332. }
  28333. void VSTPluginInstance::setPower (const bool on)
  28334. {
  28335. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28336. isPowerOn = on;
  28337. }
  28338. const int defaultMaxSizeMB = 64;
  28339. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28340. {
  28341. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28342. }
  28343. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28344. {
  28345. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28346. }
  28347. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28348. {
  28349. loadFromFXBFile (data, sizeInBytes);
  28350. }
  28351. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28352. {
  28353. loadFromFXBFile (data, sizeInBytes);
  28354. }
  28355. VSTPluginFormat::VSTPluginFormat()
  28356. {
  28357. }
  28358. VSTPluginFormat::~VSTPluginFormat()
  28359. {
  28360. }
  28361. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28362. const String& fileOrIdentifier)
  28363. {
  28364. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28365. return;
  28366. PluginDescription desc;
  28367. desc.fileOrIdentifier = fileOrIdentifier;
  28368. desc.uid = 0;
  28369. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28370. if (instance == 0)
  28371. return;
  28372. try
  28373. {
  28374. #if JUCE_MAC
  28375. if (instance->module->resFileId != 0)
  28376. UseResFile (instance->module->resFileId);
  28377. #endif
  28378. instance->fillInPluginDescription (desc);
  28379. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28380. if (category != kPlugCategShell)
  28381. {
  28382. // Normal plugin...
  28383. results.add (new PluginDescription (desc));
  28384. ++insideVSTCallback;
  28385. instance->dispatch (effOpen, 0, 0, 0, 0);
  28386. --insideVSTCallback;
  28387. }
  28388. else
  28389. {
  28390. // It's a shell plugin, so iterate all the subtypes...
  28391. char shellEffectName [64];
  28392. for (;;)
  28393. {
  28394. zerostruct (shellEffectName);
  28395. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28396. if (uid == 0)
  28397. {
  28398. break;
  28399. }
  28400. else
  28401. {
  28402. desc.uid = uid;
  28403. desc.name = shellEffectName;
  28404. desc.descriptiveName = shellEffectName;
  28405. bool alreadyThere = false;
  28406. for (int i = results.size(); --i >= 0;)
  28407. {
  28408. PluginDescription* const d = results.getUnchecked(i);
  28409. if (d->isDuplicateOf (desc))
  28410. {
  28411. alreadyThere = true;
  28412. break;
  28413. }
  28414. }
  28415. if (! alreadyThere)
  28416. results.add (new PluginDescription (desc));
  28417. }
  28418. }
  28419. }
  28420. }
  28421. catch (...)
  28422. {
  28423. // crashed while loading...
  28424. }
  28425. }
  28426. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28427. {
  28428. ScopedPointer <VSTPluginInstance> result;
  28429. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28430. {
  28431. File file (desc.fileOrIdentifier);
  28432. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28433. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28434. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28435. if (module != 0)
  28436. {
  28437. shellUIDToCreate = desc.uid;
  28438. result = new VSTPluginInstance (module);
  28439. if (result->effect != 0)
  28440. {
  28441. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28442. result->initialise();
  28443. }
  28444. else
  28445. {
  28446. result = 0;
  28447. }
  28448. }
  28449. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28450. }
  28451. return result.release();
  28452. }
  28453. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28454. {
  28455. const File f (fileOrIdentifier);
  28456. #if JUCE_MAC
  28457. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28458. return true;
  28459. #if JUCE_PPC
  28460. FSRef fileRef;
  28461. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28462. {
  28463. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28464. if (resFileId != -1)
  28465. {
  28466. const int numEffects = Count1Resources ('aEff');
  28467. CloseResFile (resFileId);
  28468. if (numEffects > 0)
  28469. return true;
  28470. }
  28471. }
  28472. #endif
  28473. return false;
  28474. #elif JUCE_WINDOWS
  28475. return f.existsAsFile() && f.hasFileExtension (".dll");
  28476. #elif JUCE_LINUX
  28477. return f.existsAsFile() && f.hasFileExtension (".so");
  28478. #endif
  28479. }
  28480. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28481. {
  28482. return fileOrIdentifier;
  28483. }
  28484. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28485. {
  28486. return File (desc.fileOrIdentifier).exists();
  28487. }
  28488. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28489. {
  28490. StringArray results;
  28491. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28492. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28493. return results;
  28494. }
  28495. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28496. {
  28497. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28498. // .component or .vst directories.
  28499. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28500. while (iter.next())
  28501. {
  28502. const File f (iter.getFile());
  28503. bool isPlugin = false;
  28504. if (fileMightContainThisPluginType (f.getFullPathName()))
  28505. {
  28506. isPlugin = true;
  28507. results.add (f.getFullPathName());
  28508. }
  28509. if (recursive && (! isPlugin) && f.isDirectory())
  28510. recursiveFileSearch (results, f, true);
  28511. }
  28512. }
  28513. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28514. {
  28515. #if JUCE_MAC
  28516. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28517. #elif JUCE_WINDOWS
  28518. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28519. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28520. #elif JUCE_LINUX
  28521. return FileSearchPath ("/usr/lib/vst");
  28522. #endif
  28523. }
  28524. END_JUCE_NAMESPACE
  28525. #endif
  28526. #undef log
  28527. #endif
  28528. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28529. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28530. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28531. BEGIN_JUCE_NAMESPACE
  28532. AudioProcessor::AudioProcessor()
  28533. : playHead (0),
  28534. sampleRate (0),
  28535. blockSize (0),
  28536. numInputChannels (0),
  28537. numOutputChannels (0),
  28538. latencySamples (0),
  28539. suspended (false),
  28540. nonRealtime (false)
  28541. {
  28542. }
  28543. AudioProcessor::~AudioProcessor()
  28544. {
  28545. // ooh, nasty - the editor should have been deleted before the filter
  28546. // that it refers to is deleted..
  28547. jassert (activeEditor == 0);
  28548. #if JUCE_DEBUG
  28549. // This will fail if you've called beginParameterChangeGesture() for one
  28550. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28551. jassert (changingParams.countNumberOfSetBits() == 0);
  28552. #endif
  28553. }
  28554. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28555. {
  28556. playHead = newPlayHead;
  28557. }
  28558. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28559. {
  28560. const ScopedLock sl (listenerLock);
  28561. listeners.addIfNotAlreadyThere (newListener);
  28562. }
  28563. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28564. {
  28565. const ScopedLock sl (listenerLock);
  28566. listeners.removeValue (listenerToRemove);
  28567. }
  28568. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28569. const int numOuts,
  28570. const double sampleRate_,
  28571. const int blockSize_) throw()
  28572. {
  28573. numInputChannels = numIns;
  28574. numOutputChannels = numOuts;
  28575. sampleRate = sampleRate_;
  28576. blockSize = blockSize_;
  28577. }
  28578. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28579. {
  28580. nonRealtime = nonRealtime_;
  28581. }
  28582. void AudioProcessor::setLatencySamples (const int newLatency)
  28583. {
  28584. if (latencySamples != newLatency)
  28585. {
  28586. latencySamples = newLatency;
  28587. updateHostDisplay();
  28588. }
  28589. }
  28590. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28591. const float newValue)
  28592. {
  28593. setParameter (parameterIndex, newValue);
  28594. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28595. }
  28596. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28597. {
  28598. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28599. for (int i = listeners.size(); --i >= 0;)
  28600. {
  28601. AudioProcessorListener* l;
  28602. {
  28603. const ScopedLock sl (listenerLock);
  28604. l = listeners [i];
  28605. }
  28606. if (l != 0)
  28607. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28608. }
  28609. }
  28610. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28611. {
  28612. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28613. #if JUCE_DEBUG
  28614. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28615. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28616. jassert (! changingParams [parameterIndex]);
  28617. changingParams.setBit (parameterIndex);
  28618. #endif
  28619. for (int i = listeners.size(); --i >= 0;)
  28620. {
  28621. AudioProcessorListener* l;
  28622. {
  28623. const ScopedLock sl (listenerLock);
  28624. l = listeners [i];
  28625. }
  28626. if (l != 0)
  28627. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28628. }
  28629. }
  28630. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28631. {
  28632. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28633. #if JUCE_DEBUG
  28634. // This means you've called endParameterChangeGesture without having previously called
  28635. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28636. // calls matched correctly.
  28637. jassert (changingParams [parameterIndex]);
  28638. changingParams.clearBit (parameterIndex);
  28639. #endif
  28640. for (int i = listeners.size(); --i >= 0;)
  28641. {
  28642. AudioProcessorListener* l;
  28643. {
  28644. const ScopedLock sl (listenerLock);
  28645. l = listeners [i];
  28646. }
  28647. if (l != 0)
  28648. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28649. }
  28650. }
  28651. void AudioProcessor::updateHostDisplay()
  28652. {
  28653. for (int i = listeners.size(); --i >= 0;)
  28654. {
  28655. AudioProcessorListener* l;
  28656. {
  28657. const ScopedLock sl (listenerLock);
  28658. l = listeners [i];
  28659. }
  28660. if (l != 0)
  28661. l->audioProcessorChanged (this);
  28662. }
  28663. }
  28664. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28665. {
  28666. return true;
  28667. }
  28668. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  28669. {
  28670. return false;
  28671. }
  28672. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  28673. {
  28674. const ScopedLock sl (callbackLock);
  28675. suspended = shouldBeSuspended;
  28676. }
  28677. void AudioProcessor::reset()
  28678. {
  28679. }
  28680. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  28681. {
  28682. const ScopedLock sl (callbackLock);
  28683. if (activeEditor == editor)
  28684. activeEditor = 0;
  28685. }
  28686. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  28687. {
  28688. if (activeEditor != 0)
  28689. return activeEditor;
  28690. AudioProcessorEditor* const ed = createEditor();
  28691. // You must make your hasEditor() method return a consistent result!
  28692. jassert (hasEditor() == (ed != 0));
  28693. if (ed != 0)
  28694. {
  28695. // you must give your editor comp a size before returning it..
  28696. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  28697. const ScopedLock sl (callbackLock);
  28698. activeEditor = ed;
  28699. }
  28700. return ed;
  28701. }
  28702. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  28703. {
  28704. getStateInformation (destData);
  28705. }
  28706. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28707. {
  28708. setStateInformation (data, sizeInBytes);
  28709. }
  28710. // magic number to identify memory blocks that we've stored as XML
  28711. const uint32 magicXmlNumber = 0x21324356;
  28712. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28713. JUCE_NAMESPACE::MemoryBlock& destData)
  28714. {
  28715. const String xmlString (xml.createDocument (String::empty, true, false));
  28716. const int stringLength = xmlString.getNumBytesAsUTF8();
  28717. destData.setSize (stringLength + 10);
  28718. char* const d = static_cast<char*> (destData.getData());
  28719. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28720. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28721. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28722. }
  28723. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28724. const int sizeInBytes)
  28725. {
  28726. if (sizeInBytes > 8
  28727. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28728. {
  28729. const int stringLength = (int) ByteOrder::littleEndianInt (addBytesToPointer (data, 4));
  28730. if (stringLength > 0)
  28731. return XmlDocument::parse (String::fromUTF8 (static_cast<const char*> (data) + 8,
  28732. jmin ((sizeInBytes - 8), stringLength)));
  28733. }
  28734. return 0;
  28735. }
  28736. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int) {}
  28737. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int) {}
  28738. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28739. {
  28740. return timeInSeconds == other.timeInSeconds
  28741. && ppqPosition == other.ppqPosition
  28742. && editOriginTime == other.editOriginTime
  28743. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28744. && frameRate == other.frameRate
  28745. && isPlaying == other.isPlaying
  28746. && isRecording == other.isRecording
  28747. && bpm == other.bpm
  28748. && timeSigNumerator == other.timeSigNumerator
  28749. && timeSigDenominator == other.timeSigDenominator;
  28750. }
  28751. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28752. {
  28753. return ! operator== (other);
  28754. }
  28755. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28756. {
  28757. zerostruct (*this);
  28758. timeSigNumerator = 4;
  28759. timeSigDenominator = 4;
  28760. bpm = 120;
  28761. }
  28762. END_JUCE_NAMESPACE
  28763. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28764. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28765. BEGIN_JUCE_NAMESPACE
  28766. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28767. : owner (owner_)
  28768. {
  28769. // the filter must be valid..
  28770. jassert (owner != 0);
  28771. }
  28772. AudioProcessorEditor::~AudioProcessorEditor()
  28773. {
  28774. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28775. // filter for some reason..
  28776. jassert (owner->getActiveEditor() != this);
  28777. }
  28778. END_JUCE_NAMESPACE
  28779. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28780. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28781. BEGIN_JUCE_NAMESPACE
  28782. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28783. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28784. : id (id_),
  28785. processor (processor_),
  28786. isPrepared (false)
  28787. {
  28788. jassert (processor_ != 0);
  28789. }
  28790. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28791. AudioProcessorGraph* const graph)
  28792. {
  28793. if (! isPrepared)
  28794. {
  28795. isPrepared = true;
  28796. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28797. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  28798. if (ioProc != 0)
  28799. ioProc->setParentGraph (graph);
  28800. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28801. processor->getNumOutputChannels(),
  28802. sampleRate, blockSize);
  28803. processor->prepareToPlay (sampleRate, blockSize);
  28804. }
  28805. }
  28806. void AudioProcessorGraph::Node::unprepare()
  28807. {
  28808. if (isPrepared)
  28809. {
  28810. isPrepared = false;
  28811. processor->releaseResources();
  28812. }
  28813. }
  28814. AudioProcessorGraph::AudioProcessorGraph()
  28815. : lastNodeId (0),
  28816. renderingBuffers (1, 1),
  28817. currentAudioOutputBuffer (1, 1)
  28818. {
  28819. }
  28820. AudioProcessorGraph::~AudioProcessorGraph()
  28821. {
  28822. clearRenderingSequence();
  28823. clear();
  28824. }
  28825. const String AudioProcessorGraph::getName() const
  28826. {
  28827. return "Audio Graph";
  28828. }
  28829. void AudioProcessorGraph::clear()
  28830. {
  28831. nodes.clear();
  28832. connections.clear();
  28833. triggerAsyncUpdate();
  28834. }
  28835. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28836. {
  28837. for (int i = nodes.size(); --i >= 0;)
  28838. if (nodes.getUnchecked(i)->id == nodeId)
  28839. return nodes.getUnchecked(i);
  28840. return 0;
  28841. }
  28842. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28843. uint32 nodeId)
  28844. {
  28845. if (newProcessor == 0)
  28846. {
  28847. jassertfalse;
  28848. return 0;
  28849. }
  28850. if (nodeId == 0)
  28851. {
  28852. nodeId = ++lastNodeId;
  28853. }
  28854. else
  28855. {
  28856. // you can't add a node with an id that already exists in the graph..
  28857. jassert (getNodeForId (nodeId) == 0);
  28858. removeNode (nodeId);
  28859. }
  28860. lastNodeId = nodeId;
  28861. Node* const n = new Node (nodeId, newProcessor);
  28862. nodes.add (n);
  28863. triggerAsyncUpdate();
  28864. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28865. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  28866. if (ioProc != 0)
  28867. ioProc->setParentGraph (this);
  28868. return n;
  28869. }
  28870. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  28871. {
  28872. disconnectNode (nodeId);
  28873. for (int i = nodes.size(); --i >= 0;)
  28874. {
  28875. if (nodes.getUnchecked(i)->id == nodeId)
  28876. {
  28877. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28878. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  28879. if (ioProc != 0)
  28880. ioProc->setParentGraph (0);
  28881. nodes.remove (i);
  28882. triggerAsyncUpdate();
  28883. return true;
  28884. }
  28885. }
  28886. return false;
  28887. }
  28888. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  28889. const int sourceChannelIndex,
  28890. const uint32 destNodeId,
  28891. const int destChannelIndex) const
  28892. {
  28893. for (int i = connections.size(); --i >= 0;)
  28894. {
  28895. const Connection* const c = connections.getUnchecked(i);
  28896. if (c->sourceNodeId == sourceNodeId
  28897. && c->destNodeId == destNodeId
  28898. && c->sourceChannelIndex == sourceChannelIndex
  28899. && c->destChannelIndex == destChannelIndex)
  28900. {
  28901. return c;
  28902. }
  28903. }
  28904. return 0;
  28905. }
  28906. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  28907. const uint32 possibleDestNodeId) const
  28908. {
  28909. for (int i = connections.size(); --i >= 0;)
  28910. {
  28911. const Connection* const c = connections.getUnchecked(i);
  28912. if (c->sourceNodeId == possibleSourceNodeId
  28913. && c->destNodeId == possibleDestNodeId)
  28914. {
  28915. return true;
  28916. }
  28917. }
  28918. return false;
  28919. }
  28920. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  28921. const int sourceChannelIndex,
  28922. const uint32 destNodeId,
  28923. const int destChannelIndex) const
  28924. {
  28925. if (sourceChannelIndex < 0
  28926. || destChannelIndex < 0
  28927. || sourceNodeId == destNodeId
  28928. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  28929. return false;
  28930. const Node* const source = getNodeForId (sourceNodeId);
  28931. if (source == 0
  28932. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  28933. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  28934. return false;
  28935. const Node* const dest = getNodeForId (destNodeId);
  28936. if (dest == 0
  28937. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  28938. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  28939. return false;
  28940. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  28941. destNodeId, destChannelIndex) == 0;
  28942. }
  28943. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  28944. const int sourceChannelIndex,
  28945. const uint32 destNodeId,
  28946. const int destChannelIndex)
  28947. {
  28948. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  28949. return false;
  28950. Connection* const c = new Connection();
  28951. c->sourceNodeId = sourceNodeId;
  28952. c->sourceChannelIndex = sourceChannelIndex;
  28953. c->destNodeId = destNodeId;
  28954. c->destChannelIndex = destChannelIndex;
  28955. connections.add (c);
  28956. triggerAsyncUpdate();
  28957. return true;
  28958. }
  28959. void AudioProcessorGraph::removeConnection (const int index)
  28960. {
  28961. connections.remove (index);
  28962. triggerAsyncUpdate();
  28963. }
  28964. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  28965. const uint32 destNodeId, const int destChannelIndex)
  28966. {
  28967. bool doneAnything = false;
  28968. for (int i = connections.size(); --i >= 0;)
  28969. {
  28970. const Connection* const c = connections.getUnchecked(i);
  28971. if (c->sourceNodeId == sourceNodeId
  28972. && c->destNodeId == destNodeId
  28973. && c->sourceChannelIndex == sourceChannelIndex
  28974. && c->destChannelIndex == destChannelIndex)
  28975. {
  28976. removeConnection (i);
  28977. doneAnything = true;
  28978. triggerAsyncUpdate();
  28979. }
  28980. }
  28981. return doneAnything;
  28982. }
  28983. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  28984. {
  28985. bool doneAnything = false;
  28986. for (int i = connections.size(); --i >= 0;)
  28987. {
  28988. const Connection* const c = connections.getUnchecked(i);
  28989. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  28990. {
  28991. removeConnection (i);
  28992. doneAnything = true;
  28993. triggerAsyncUpdate();
  28994. }
  28995. }
  28996. return doneAnything;
  28997. }
  28998. bool AudioProcessorGraph::removeIllegalConnections()
  28999. {
  29000. bool doneAnything = false;
  29001. for (int i = connections.size(); --i >= 0;)
  29002. {
  29003. const Connection* const c = connections.getUnchecked(i);
  29004. const Node* const source = getNodeForId (c->sourceNodeId);
  29005. const Node* const dest = getNodeForId (c->destNodeId);
  29006. if (source == 0 || dest == 0
  29007. || (c->sourceChannelIndex != midiChannelIndex
  29008. && ! isPositiveAndBelow (c->sourceChannelIndex, source->processor->getNumOutputChannels()))
  29009. || (c->sourceChannelIndex == midiChannelIndex
  29010. && ! source->processor->producesMidi())
  29011. || (c->destChannelIndex != midiChannelIndex
  29012. && ! isPositiveAndBelow (c->destChannelIndex, dest->processor->getNumInputChannels()))
  29013. || (c->destChannelIndex == midiChannelIndex
  29014. && ! dest->processor->acceptsMidi()))
  29015. {
  29016. removeConnection (i);
  29017. doneAnything = true;
  29018. triggerAsyncUpdate();
  29019. }
  29020. }
  29021. return doneAnything;
  29022. }
  29023. namespace GraphRenderingOps
  29024. {
  29025. class AudioGraphRenderingOp
  29026. {
  29027. public:
  29028. AudioGraphRenderingOp() {}
  29029. virtual ~AudioGraphRenderingOp() {}
  29030. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29031. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29032. const int numSamples) = 0;
  29033. JUCE_LEAK_DETECTOR (AudioGraphRenderingOp);
  29034. };
  29035. class ClearChannelOp : public AudioGraphRenderingOp
  29036. {
  29037. public:
  29038. ClearChannelOp (const int channelNum_)
  29039. : channelNum (channelNum_)
  29040. {}
  29041. ~ClearChannelOp() {}
  29042. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29043. {
  29044. sharedBufferChans.clear (channelNum, 0, numSamples);
  29045. }
  29046. private:
  29047. const int channelNum;
  29048. JUCE_DECLARE_NON_COPYABLE (ClearChannelOp);
  29049. };
  29050. class CopyChannelOp : public AudioGraphRenderingOp
  29051. {
  29052. public:
  29053. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29054. : srcChannelNum (srcChannelNum_),
  29055. dstChannelNum (dstChannelNum_)
  29056. {}
  29057. ~CopyChannelOp() {}
  29058. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29059. {
  29060. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29061. }
  29062. private:
  29063. const int srcChannelNum, dstChannelNum;
  29064. JUCE_DECLARE_NON_COPYABLE (CopyChannelOp);
  29065. };
  29066. class AddChannelOp : public AudioGraphRenderingOp
  29067. {
  29068. public:
  29069. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29070. : srcChannelNum (srcChannelNum_),
  29071. dstChannelNum (dstChannelNum_)
  29072. {}
  29073. ~AddChannelOp() {}
  29074. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29075. {
  29076. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29077. }
  29078. private:
  29079. const int srcChannelNum, dstChannelNum;
  29080. JUCE_DECLARE_NON_COPYABLE (AddChannelOp);
  29081. };
  29082. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29083. {
  29084. public:
  29085. ClearMidiBufferOp (const int bufferNum_)
  29086. : bufferNum (bufferNum_)
  29087. {}
  29088. ~ClearMidiBufferOp() {}
  29089. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29090. {
  29091. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29092. }
  29093. private:
  29094. const int bufferNum;
  29095. JUCE_DECLARE_NON_COPYABLE (ClearMidiBufferOp);
  29096. };
  29097. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29098. {
  29099. public:
  29100. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29101. : srcBufferNum (srcBufferNum_),
  29102. dstBufferNum (dstBufferNum_)
  29103. {}
  29104. ~CopyMidiBufferOp() {}
  29105. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29106. {
  29107. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29108. }
  29109. private:
  29110. const int srcBufferNum, dstBufferNum;
  29111. JUCE_DECLARE_NON_COPYABLE (CopyMidiBufferOp);
  29112. };
  29113. class AddMidiBufferOp : public AudioGraphRenderingOp
  29114. {
  29115. public:
  29116. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29117. : srcBufferNum (srcBufferNum_),
  29118. dstBufferNum (dstBufferNum_)
  29119. {}
  29120. ~AddMidiBufferOp() {}
  29121. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29122. {
  29123. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29124. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29125. }
  29126. private:
  29127. const int srcBufferNum, dstBufferNum;
  29128. JUCE_DECLARE_NON_COPYABLE (AddMidiBufferOp);
  29129. };
  29130. class ProcessBufferOp : public AudioGraphRenderingOp
  29131. {
  29132. public:
  29133. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29134. const Array <int>& audioChannelsToUse_,
  29135. const int totalChans_,
  29136. const int midiBufferToUse_)
  29137. : node (node_),
  29138. processor (node_->getProcessor()),
  29139. audioChannelsToUse (audioChannelsToUse_),
  29140. totalChans (jmax (1, totalChans_)),
  29141. midiBufferToUse (midiBufferToUse_)
  29142. {
  29143. channels.calloc (totalChans);
  29144. while (audioChannelsToUse.size() < totalChans)
  29145. audioChannelsToUse.add (0);
  29146. }
  29147. ~ProcessBufferOp()
  29148. {
  29149. }
  29150. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29151. {
  29152. for (int i = totalChans; --i >= 0;)
  29153. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29154. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29155. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29156. }
  29157. const AudioProcessorGraph::Node::Ptr node;
  29158. AudioProcessor* const processor;
  29159. private:
  29160. Array <int> audioChannelsToUse;
  29161. HeapBlock <float*> channels;
  29162. int totalChans;
  29163. int midiBufferToUse;
  29164. JUCE_DECLARE_NON_COPYABLE (ProcessBufferOp);
  29165. };
  29166. /** Used to calculate the correct sequence of rendering ops needed, based on
  29167. the best re-use of shared buffers at each stage.
  29168. */
  29169. class RenderingOpSequenceCalculator
  29170. {
  29171. public:
  29172. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29173. const Array<void*>& orderedNodes_,
  29174. Array<void*>& renderingOps)
  29175. : graph (graph_),
  29176. orderedNodes (orderedNodes_)
  29177. {
  29178. nodeIds.add ((uint32) zeroNodeID); // first buffer is read-only zeros
  29179. channels.add (0);
  29180. midiNodeIds.add ((uint32) zeroNodeID);
  29181. for (int i = 0; i < orderedNodes.size(); ++i)
  29182. {
  29183. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29184. renderingOps, i);
  29185. markAnyUnusedBuffersAsFree (i);
  29186. }
  29187. }
  29188. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29189. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29190. private:
  29191. AudioProcessorGraph& graph;
  29192. const Array<void*>& orderedNodes;
  29193. Array <int> channels;
  29194. Array <uint32> nodeIds, midiNodeIds;
  29195. enum { freeNodeID = 0xffffffff, zeroNodeID = 0xfffffffe };
  29196. static bool isNodeBusy (uint32 nodeID) throw() { return nodeID != freeNodeID && nodeID != zeroNodeID; }
  29197. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29198. Array<void*>& renderingOps,
  29199. const int ourRenderingIndex)
  29200. {
  29201. const int numIns = node->getProcessor()->getNumInputChannels();
  29202. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29203. const int totalChans = jmax (numIns, numOuts);
  29204. Array <int> audioChannelsToUse;
  29205. int midiBufferToUse = -1;
  29206. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29207. {
  29208. // get a list of all the inputs to this node
  29209. Array <int> sourceNodes, sourceOutputChans;
  29210. for (int i = graph.getNumConnections(); --i >= 0;)
  29211. {
  29212. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29213. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29214. {
  29215. sourceNodes.add (c->sourceNodeId);
  29216. sourceOutputChans.add (c->sourceChannelIndex);
  29217. }
  29218. }
  29219. int bufIndex = -1;
  29220. if (sourceNodes.size() == 0)
  29221. {
  29222. // unconnected input channel
  29223. if (inputChan >= numOuts)
  29224. {
  29225. bufIndex = getReadOnlyEmptyBuffer();
  29226. jassert (bufIndex >= 0);
  29227. }
  29228. else
  29229. {
  29230. bufIndex = getFreeBuffer (false);
  29231. renderingOps.add (new ClearChannelOp (bufIndex));
  29232. }
  29233. }
  29234. else if (sourceNodes.size() == 1)
  29235. {
  29236. // channel with a straightforward single input..
  29237. const int srcNode = sourceNodes.getUnchecked(0);
  29238. const int srcChan = sourceOutputChans.getUnchecked(0);
  29239. bufIndex = getBufferContaining (srcNode, srcChan);
  29240. if (bufIndex < 0)
  29241. {
  29242. // if not found, this is probably a feedback loop
  29243. bufIndex = getReadOnlyEmptyBuffer();
  29244. jassert (bufIndex >= 0);
  29245. }
  29246. if (inputChan < numOuts
  29247. && isBufferNeededLater (ourRenderingIndex,
  29248. inputChan,
  29249. srcNode, srcChan))
  29250. {
  29251. // can't mess up this channel because it's needed later by another node, so we
  29252. // need to use a copy of it..
  29253. const int newFreeBuffer = getFreeBuffer (false);
  29254. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29255. bufIndex = newFreeBuffer;
  29256. }
  29257. }
  29258. else
  29259. {
  29260. // channel with a mix of several inputs..
  29261. // try to find a re-usable channel from our inputs..
  29262. int reusableInputIndex = -1;
  29263. for (int i = 0; i < sourceNodes.size(); ++i)
  29264. {
  29265. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29266. sourceOutputChans.getUnchecked(i));
  29267. if (sourceBufIndex >= 0
  29268. && ! isBufferNeededLater (ourRenderingIndex,
  29269. inputChan,
  29270. sourceNodes.getUnchecked(i),
  29271. sourceOutputChans.getUnchecked(i)))
  29272. {
  29273. // we've found one of our input chans that can be re-used..
  29274. reusableInputIndex = i;
  29275. bufIndex = sourceBufIndex;
  29276. break;
  29277. }
  29278. }
  29279. if (reusableInputIndex < 0)
  29280. {
  29281. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29282. bufIndex = getFreeBuffer (false);
  29283. jassert (bufIndex != 0);
  29284. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29285. sourceOutputChans.getUnchecked (0));
  29286. if (srcIndex < 0)
  29287. {
  29288. // if not found, this is probably a feedback loop
  29289. renderingOps.add (new ClearChannelOp (bufIndex));
  29290. }
  29291. else
  29292. {
  29293. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29294. }
  29295. reusableInputIndex = 0;
  29296. }
  29297. for (int j = 0; j < sourceNodes.size(); ++j)
  29298. {
  29299. if (j != reusableInputIndex)
  29300. {
  29301. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29302. sourceOutputChans.getUnchecked(j));
  29303. if (srcIndex >= 0)
  29304. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29305. }
  29306. }
  29307. }
  29308. jassert (bufIndex >= 0);
  29309. audioChannelsToUse.add (bufIndex);
  29310. if (inputChan < numOuts)
  29311. markBufferAsContaining (bufIndex, node->id, inputChan);
  29312. }
  29313. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29314. {
  29315. const int bufIndex = getFreeBuffer (false);
  29316. jassert (bufIndex != 0);
  29317. audioChannelsToUse.add (bufIndex);
  29318. markBufferAsContaining (bufIndex, node->id, outputChan);
  29319. }
  29320. // Now the same thing for midi..
  29321. Array <int> midiSourceNodes;
  29322. for (int i = graph.getNumConnections(); --i >= 0;)
  29323. {
  29324. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29325. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29326. midiSourceNodes.add (c->sourceNodeId);
  29327. }
  29328. if (midiSourceNodes.size() == 0)
  29329. {
  29330. // No midi inputs..
  29331. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29332. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29333. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29334. }
  29335. else if (midiSourceNodes.size() == 1)
  29336. {
  29337. // One midi input..
  29338. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29339. AudioProcessorGraph::midiChannelIndex);
  29340. if (midiBufferToUse >= 0)
  29341. {
  29342. if (isBufferNeededLater (ourRenderingIndex,
  29343. AudioProcessorGraph::midiChannelIndex,
  29344. midiSourceNodes.getUnchecked(0),
  29345. AudioProcessorGraph::midiChannelIndex))
  29346. {
  29347. // can't mess up this channel because it's needed later by another node, so we
  29348. // need to use a copy of it..
  29349. const int newFreeBuffer = getFreeBuffer (true);
  29350. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29351. midiBufferToUse = newFreeBuffer;
  29352. }
  29353. }
  29354. else
  29355. {
  29356. // probably a feedback loop, so just use an empty one..
  29357. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29358. }
  29359. }
  29360. else
  29361. {
  29362. // More than one midi input being mixed..
  29363. int reusableInputIndex = -1;
  29364. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29365. {
  29366. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29367. AudioProcessorGraph::midiChannelIndex);
  29368. if (sourceBufIndex >= 0
  29369. && ! isBufferNeededLater (ourRenderingIndex,
  29370. AudioProcessorGraph::midiChannelIndex,
  29371. midiSourceNodes.getUnchecked(i),
  29372. AudioProcessorGraph::midiChannelIndex))
  29373. {
  29374. // we've found one of our input buffers that can be re-used..
  29375. reusableInputIndex = i;
  29376. midiBufferToUse = sourceBufIndex;
  29377. break;
  29378. }
  29379. }
  29380. if (reusableInputIndex < 0)
  29381. {
  29382. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29383. midiBufferToUse = getFreeBuffer (true);
  29384. jassert (midiBufferToUse >= 0);
  29385. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29386. AudioProcessorGraph::midiChannelIndex);
  29387. if (srcIndex >= 0)
  29388. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29389. else
  29390. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29391. reusableInputIndex = 0;
  29392. }
  29393. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29394. {
  29395. if (j != reusableInputIndex)
  29396. {
  29397. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29398. AudioProcessorGraph::midiChannelIndex);
  29399. if (srcIndex >= 0)
  29400. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29401. }
  29402. }
  29403. }
  29404. if (node->getProcessor()->producesMidi())
  29405. markBufferAsContaining (midiBufferToUse, node->id,
  29406. AudioProcessorGraph::midiChannelIndex);
  29407. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29408. totalChans, midiBufferToUse));
  29409. }
  29410. int getFreeBuffer (const bool forMidi)
  29411. {
  29412. if (forMidi)
  29413. {
  29414. for (int i = 1; i < midiNodeIds.size(); ++i)
  29415. if (midiNodeIds.getUnchecked(i) == freeNodeID)
  29416. return i;
  29417. midiNodeIds.add ((uint32) freeNodeID);
  29418. return midiNodeIds.size() - 1;
  29419. }
  29420. else
  29421. {
  29422. for (int i = 1; i < nodeIds.size(); ++i)
  29423. if (nodeIds.getUnchecked(i) == freeNodeID)
  29424. return i;
  29425. nodeIds.add ((uint32) freeNodeID);
  29426. channels.add (0);
  29427. return nodeIds.size() - 1;
  29428. }
  29429. }
  29430. int getReadOnlyEmptyBuffer() const
  29431. {
  29432. return 0;
  29433. }
  29434. int getBufferContaining (const uint32 nodeId, const int outputChannel) const
  29435. {
  29436. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29437. {
  29438. for (int i = midiNodeIds.size(); --i >= 0;)
  29439. if (midiNodeIds.getUnchecked(i) == nodeId)
  29440. return i;
  29441. }
  29442. else
  29443. {
  29444. for (int i = nodeIds.size(); --i >= 0;)
  29445. if (nodeIds.getUnchecked(i) == nodeId
  29446. && channels.getUnchecked(i) == outputChannel)
  29447. return i;
  29448. }
  29449. return -1;
  29450. }
  29451. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29452. {
  29453. int i;
  29454. for (i = 0; i < nodeIds.size(); ++i)
  29455. {
  29456. if (isNodeBusy (nodeIds.getUnchecked(i))
  29457. && ! isBufferNeededLater (stepIndex, -1,
  29458. nodeIds.getUnchecked(i),
  29459. channels.getUnchecked(i)))
  29460. {
  29461. nodeIds.set (i, (uint32) freeNodeID);
  29462. }
  29463. }
  29464. for (i = 0; i < midiNodeIds.size(); ++i)
  29465. {
  29466. if (isNodeBusy (midiNodeIds.getUnchecked(i))
  29467. && ! isBufferNeededLater (stepIndex, -1,
  29468. midiNodeIds.getUnchecked(i),
  29469. AudioProcessorGraph::midiChannelIndex))
  29470. {
  29471. midiNodeIds.set (i, (uint32) freeNodeID);
  29472. }
  29473. }
  29474. }
  29475. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29476. int inputChannelOfIndexToIgnore,
  29477. const uint32 nodeId,
  29478. const int outputChanIndex) const
  29479. {
  29480. while (stepIndexToSearchFrom < orderedNodes.size())
  29481. {
  29482. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29483. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29484. {
  29485. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29486. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29487. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29488. return true;
  29489. }
  29490. else
  29491. {
  29492. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29493. if (i != inputChannelOfIndexToIgnore
  29494. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29495. node->id, i) != 0)
  29496. return true;
  29497. }
  29498. inputChannelOfIndexToIgnore = -1;
  29499. ++stepIndexToSearchFrom;
  29500. }
  29501. return false;
  29502. }
  29503. void markBufferAsContaining (int bufferNum, uint32 nodeId, int outputIndex)
  29504. {
  29505. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29506. {
  29507. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29508. midiNodeIds.set (bufferNum, nodeId);
  29509. }
  29510. else
  29511. {
  29512. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29513. nodeIds.set (bufferNum, nodeId);
  29514. channels.set (bufferNum, outputIndex);
  29515. }
  29516. }
  29517. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RenderingOpSequenceCalculator);
  29518. };
  29519. }
  29520. void AudioProcessorGraph::clearRenderingSequence()
  29521. {
  29522. const ScopedLock sl (renderLock);
  29523. for (int i = renderingOps.size(); --i >= 0;)
  29524. {
  29525. GraphRenderingOps::AudioGraphRenderingOp* const r
  29526. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29527. renderingOps.remove (i);
  29528. delete r;
  29529. }
  29530. }
  29531. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29532. const uint32 possibleDestinationId,
  29533. const int recursionCheck) const
  29534. {
  29535. if (recursionCheck > 0)
  29536. {
  29537. for (int i = connections.size(); --i >= 0;)
  29538. {
  29539. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29540. if (c->destNodeId == possibleDestinationId
  29541. && (c->sourceNodeId == possibleInputId
  29542. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29543. return true;
  29544. }
  29545. }
  29546. return false;
  29547. }
  29548. void AudioProcessorGraph::buildRenderingSequence()
  29549. {
  29550. Array<void*> newRenderingOps;
  29551. int numRenderingBuffersNeeded = 2;
  29552. int numMidiBuffersNeeded = 1;
  29553. {
  29554. MessageManagerLock mml;
  29555. Array<void*> orderedNodes;
  29556. int i;
  29557. for (i = 0; i < nodes.size(); ++i)
  29558. {
  29559. Node* const node = nodes.getUnchecked(i);
  29560. node->prepare (getSampleRate(), getBlockSize(), this);
  29561. int j = 0;
  29562. for (; j < orderedNodes.size(); ++j)
  29563. if (isAnInputTo (node->id,
  29564. ((Node*) orderedNodes.getUnchecked (j))->id,
  29565. nodes.size() + 1))
  29566. break;
  29567. orderedNodes.insert (j, node);
  29568. }
  29569. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29570. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29571. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29572. }
  29573. Array<void*> oldRenderingOps (renderingOps);
  29574. {
  29575. // swap over to the new rendering sequence..
  29576. const ScopedLock sl (renderLock);
  29577. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29578. renderingBuffers.clear();
  29579. for (int i = midiBuffers.size(); --i >= 0;)
  29580. midiBuffers.getUnchecked(i)->clear();
  29581. while (midiBuffers.size() < numMidiBuffersNeeded)
  29582. midiBuffers.add (new MidiBuffer());
  29583. renderingOps = newRenderingOps;
  29584. }
  29585. for (int i = oldRenderingOps.size(); --i >= 0;)
  29586. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29587. }
  29588. void AudioProcessorGraph::handleAsyncUpdate()
  29589. {
  29590. buildRenderingSequence();
  29591. }
  29592. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29593. {
  29594. currentAudioInputBuffer = 0;
  29595. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29596. currentMidiInputBuffer = 0;
  29597. currentMidiOutputBuffer.clear();
  29598. clearRenderingSequence();
  29599. buildRenderingSequence();
  29600. }
  29601. void AudioProcessorGraph::releaseResources()
  29602. {
  29603. for (int i = 0; i < nodes.size(); ++i)
  29604. nodes.getUnchecked(i)->unprepare();
  29605. renderingBuffers.setSize (1, 1);
  29606. midiBuffers.clear();
  29607. currentAudioInputBuffer = 0;
  29608. currentAudioOutputBuffer.setSize (1, 1);
  29609. currentMidiInputBuffer = 0;
  29610. currentMidiOutputBuffer.clear();
  29611. }
  29612. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29613. {
  29614. const int numSamples = buffer.getNumSamples();
  29615. const ScopedLock sl (renderLock);
  29616. currentAudioInputBuffer = &buffer;
  29617. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29618. currentAudioOutputBuffer.clear();
  29619. currentMidiInputBuffer = &midiMessages;
  29620. currentMidiOutputBuffer.clear();
  29621. int i;
  29622. for (i = 0; i < renderingOps.size(); ++i)
  29623. {
  29624. GraphRenderingOps::AudioGraphRenderingOp* const op
  29625. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29626. op->perform (renderingBuffers, midiBuffers, numSamples);
  29627. }
  29628. for (i = 0; i < buffer.getNumChannels(); ++i)
  29629. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29630. midiMessages.clear();
  29631. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29632. }
  29633. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29634. {
  29635. return "Input " + String (channelIndex + 1);
  29636. }
  29637. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29638. {
  29639. return "Output " + String (channelIndex + 1);
  29640. }
  29641. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29642. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29643. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29644. bool AudioProcessorGraph::producesMidi() const { return true; }
  29645. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29646. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29647. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29648. : type (type_),
  29649. graph (0)
  29650. {
  29651. }
  29652. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29653. {
  29654. }
  29655. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29656. {
  29657. switch (type)
  29658. {
  29659. case audioOutputNode: return "Audio Output";
  29660. case audioInputNode: return "Audio Input";
  29661. case midiOutputNode: return "Midi Output";
  29662. case midiInputNode: return "Midi Input";
  29663. default: break;
  29664. }
  29665. return String::empty;
  29666. }
  29667. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29668. {
  29669. d.name = getName();
  29670. d.uid = d.name.hashCode();
  29671. d.category = "I/O devices";
  29672. d.pluginFormatName = "Internal";
  29673. d.manufacturerName = "Raw Material Software";
  29674. d.version = "1.0";
  29675. d.isInstrument = false;
  29676. d.numInputChannels = getNumInputChannels();
  29677. if (type == audioOutputNode && graph != 0)
  29678. d.numInputChannels = graph->getNumInputChannels();
  29679. d.numOutputChannels = getNumOutputChannels();
  29680. if (type == audioInputNode && graph != 0)
  29681. d.numOutputChannels = graph->getNumOutputChannels();
  29682. }
  29683. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29684. {
  29685. jassert (graph != 0);
  29686. }
  29687. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29688. {
  29689. }
  29690. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29691. MidiBuffer& midiMessages)
  29692. {
  29693. jassert (graph != 0);
  29694. switch (type)
  29695. {
  29696. case audioOutputNode:
  29697. {
  29698. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29699. buffer.getNumChannels()); --i >= 0;)
  29700. {
  29701. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29702. }
  29703. break;
  29704. }
  29705. case audioInputNode:
  29706. {
  29707. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29708. buffer.getNumChannels()); --i >= 0;)
  29709. {
  29710. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29711. }
  29712. break;
  29713. }
  29714. case midiOutputNode:
  29715. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29716. break;
  29717. case midiInputNode:
  29718. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29719. break;
  29720. default:
  29721. break;
  29722. }
  29723. }
  29724. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29725. {
  29726. return type == midiOutputNode;
  29727. }
  29728. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29729. {
  29730. return type == midiInputNode;
  29731. }
  29732. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  29733. {
  29734. switch (type)
  29735. {
  29736. case audioOutputNode: return "Output " + String (channelIndex + 1);
  29737. case midiOutputNode: return "Midi Output";
  29738. default: break;
  29739. }
  29740. return String::empty;
  29741. }
  29742. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  29743. {
  29744. switch (type)
  29745. {
  29746. case audioInputNode: return "Input " + String (channelIndex + 1);
  29747. case midiInputNode: return "Midi Input";
  29748. default: break;
  29749. }
  29750. return String::empty;
  29751. }
  29752. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29753. {
  29754. return type == audioInputNode || type == audioOutputNode;
  29755. }
  29756. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29757. {
  29758. return isInputChannelStereoPair (index);
  29759. }
  29760. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29761. {
  29762. return type == audioInputNode || type == midiInputNode;
  29763. }
  29764. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29765. {
  29766. return type == audioOutputNode || type == midiOutputNode;
  29767. }
  29768. bool AudioProcessorGraph::AudioGraphIOProcessor::hasEditor() const { return false; }
  29769. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor() { return 0; }
  29770. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29771. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29772. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29773. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29774. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29775. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29776. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29777. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29778. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29779. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29780. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29781. {
  29782. }
  29783. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29784. {
  29785. }
  29786. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29787. {
  29788. graph = newGraph;
  29789. if (graph != 0)
  29790. {
  29791. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29792. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29793. getSampleRate(),
  29794. getBlockSize());
  29795. updateHostDisplay();
  29796. }
  29797. }
  29798. END_JUCE_NAMESPACE
  29799. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29800. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29801. BEGIN_JUCE_NAMESPACE
  29802. AudioProcessorPlayer::AudioProcessorPlayer()
  29803. : processor (0),
  29804. sampleRate (0),
  29805. blockSize (0),
  29806. isPrepared (false),
  29807. numInputChans (0),
  29808. numOutputChans (0),
  29809. tempBuffer (1, 1)
  29810. {
  29811. }
  29812. AudioProcessorPlayer::~AudioProcessorPlayer()
  29813. {
  29814. setProcessor (0);
  29815. }
  29816. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29817. {
  29818. if (processor != processorToPlay)
  29819. {
  29820. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29821. {
  29822. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29823. sampleRate, blockSize);
  29824. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29825. }
  29826. AudioProcessor* oldOne;
  29827. {
  29828. const ScopedLock sl (lock);
  29829. oldOne = isPrepared ? processor : 0;
  29830. processor = processorToPlay;
  29831. isPrepared = true;
  29832. }
  29833. if (oldOne != 0)
  29834. oldOne->releaseResources();
  29835. }
  29836. }
  29837. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  29838. const int numInputChannels,
  29839. float** const outputChannelData,
  29840. const int numOutputChannels,
  29841. const int numSamples)
  29842. {
  29843. // these should have been prepared by audioDeviceAboutToStart()...
  29844. jassert (sampleRate > 0 && blockSize > 0);
  29845. incomingMidi.clear();
  29846. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29847. int i, totalNumChans = 0;
  29848. if (numInputChannels > numOutputChannels)
  29849. {
  29850. // if there aren't enough output channels for the number of
  29851. // inputs, we need to create some temporary extra ones (can't
  29852. // use the input data in case it gets written to)
  29853. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29854. false, false, true);
  29855. for (i = 0; i < numOutputChannels; ++i)
  29856. {
  29857. channels[totalNumChans] = outputChannelData[i];
  29858. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29859. ++totalNumChans;
  29860. }
  29861. for (i = numOutputChannels; i < numInputChannels; ++i)
  29862. {
  29863. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  29864. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29865. ++totalNumChans;
  29866. }
  29867. }
  29868. else
  29869. {
  29870. for (i = 0; i < numInputChannels; ++i)
  29871. {
  29872. channels[totalNumChans] = outputChannelData[i];
  29873. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29874. ++totalNumChans;
  29875. }
  29876. for (i = numInputChannels; i < numOutputChannels; ++i)
  29877. {
  29878. channels[totalNumChans] = outputChannelData[i];
  29879. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  29880. ++totalNumChans;
  29881. }
  29882. }
  29883. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  29884. const ScopedLock sl (lock);
  29885. if (processor != 0)
  29886. {
  29887. const ScopedLock sl2 (processor->getCallbackLock());
  29888. if (processor->isSuspended())
  29889. {
  29890. for (i = 0; i < numOutputChannels; ++i)
  29891. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  29892. }
  29893. else
  29894. {
  29895. processor->processBlock (buffer, incomingMidi);
  29896. }
  29897. }
  29898. }
  29899. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  29900. {
  29901. const ScopedLock sl (lock);
  29902. sampleRate = device->getCurrentSampleRate();
  29903. blockSize = device->getCurrentBufferSizeSamples();
  29904. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  29905. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  29906. messageCollector.reset (sampleRate);
  29907. zeromem (channels, sizeof (channels));
  29908. if (processor != 0)
  29909. {
  29910. if (isPrepared)
  29911. processor->releaseResources();
  29912. AudioProcessor* const oldProcessor = processor;
  29913. setProcessor (0);
  29914. setProcessor (oldProcessor);
  29915. }
  29916. }
  29917. void AudioProcessorPlayer::audioDeviceStopped()
  29918. {
  29919. const ScopedLock sl (lock);
  29920. if (processor != 0 && isPrepared)
  29921. processor->releaseResources();
  29922. sampleRate = 0.0;
  29923. blockSize = 0;
  29924. isPrepared = false;
  29925. tempBuffer.setSize (1, 1);
  29926. }
  29927. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  29928. {
  29929. messageCollector.addMessageToQueue (message);
  29930. }
  29931. END_JUCE_NAMESPACE
  29932. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29933. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29934. BEGIN_JUCE_NAMESPACE
  29935. class ProcessorParameterPropertyComp : public PropertyComponent,
  29936. public AudioProcessorListener,
  29937. public Timer
  29938. {
  29939. public:
  29940. ProcessorParameterPropertyComp (const String& name, AudioProcessor& owner_, const int index_)
  29941. : PropertyComponent (name),
  29942. owner (owner_),
  29943. index (index_),
  29944. paramHasChanged (false),
  29945. slider (owner_, index_)
  29946. {
  29947. startTimer (100);
  29948. addAndMakeVisible (&slider);
  29949. owner_.addListener (this);
  29950. }
  29951. ~ProcessorParameterPropertyComp()
  29952. {
  29953. owner.removeListener (this);
  29954. }
  29955. void refresh()
  29956. {
  29957. paramHasChanged = false;
  29958. slider.setValue (owner.getParameter (index), false);
  29959. }
  29960. void audioProcessorChanged (AudioProcessor*) {}
  29961. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  29962. {
  29963. if (parameterIndex == index)
  29964. paramHasChanged = true;
  29965. }
  29966. void timerCallback()
  29967. {
  29968. if (paramHasChanged)
  29969. {
  29970. refresh();
  29971. startTimer (1000 / 50);
  29972. }
  29973. else
  29974. {
  29975. startTimer (jmin (1000 / 4, getTimerInterval() + 10));
  29976. }
  29977. }
  29978. private:
  29979. class ParamSlider : public Slider
  29980. {
  29981. public:
  29982. ParamSlider (AudioProcessor& owner_, const int index_)
  29983. : owner (owner_),
  29984. index (index_)
  29985. {
  29986. setRange (0.0, 1.0, 0.0);
  29987. setSliderStyle (Slider::LinearBar);
  29988. setTextBoxIsEditable (false);
  29989. setScrollWheelEnabled (false);
  29990. }
  29991. void valueChanged()
  29992. {
  29993. const float newVal = (float) getValue();
  29994. if (owner.getParameter (index) != newVal)
  29995. owner.setParameter (index, newVal);
  29996. }
  29997. const String getTextFromValue (double /*value*/)
  29998. {
  29999. return owner.getParameterText (index);
  30000. }
  30001. private:
  30002. AudioProcessor& owner;
  30003. const int index;
  30004. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ParamSlider);
  30005. };
  30006. AudioProcessor& owner;
  30007. const int index;
  30008. bool volatile paramHasChanged;
  30009. ParamSlider slider;
  30010. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProcessorParameterPropertyComp);
  30011. };
  30012. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  30013. : AudioProcessorEditor (owner_)
  30014. {
  30015. jassert (owner_ != 0);
  30016. setOpaque (true);
  30017. addAndMakeVisible (&panel);
  30018. Array <PropertyComponent*> params;
  30019. const int numParams = owner_->getNumParameters();
  30020. int totalHeight = 0;
  30021. for (int i = 0; i < numParams; ++i)
  30022. {
  30023. String name (owner_->getParameterName (i));
  30024. if (name.trim().isEmpty())
  30025. name = "Unnamed";
  30026. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, *owner_, i);
  30027. params.add (pc);
  30028. totalHeight += pc->getPreferredHeight();
  30029. }
  30030. panel.addProperties (params);
  30031. setSize (400, jlimit (25, 400, totalHeight));
  30032. }
  30033. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30034. {
  30035. }
  30036. void GenericAudioProcessorEditor::paint (Graphics& g)
  30037. {
  30038. g.fillAll (Colours::white);
  30039. }
  30040. void GenericAudioProcessorEditor::resized()
  30041. {
  30042. panel.setBounds (getLocalBounds());
  30043. }
  30044. END_JUCE_NAMESPACE
  30045. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30046. /*** Start of inlined file: juce_Sampler.cpp ***/
  30047. BEGIN_JUCE_NAMESPACE
  30048. SamplerSound::SamplerSound (const String& name_,
  30049. AudioFormatReader& source,
  30050. const BigInteger& midiNotes_,
  30051. const int midiNoteForNormalPitch,
  30052. const double attackTimeSecs,
  30053. const double releaseTimeSecs,
  30054. const double maxSampleLengthSeconds)
  30055. : name (name_),
  30056. midiNotes (midiNotes_),
  30057. midiRootNote (midiNoteForNormalPitch)
  30058. {
  30059. sourceSampleRate = source.sampleRate;
  30060. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30061. {
  30062. length = 0;
  30063. attackSamples = 0;
  30064. releaseSamples = 0;
  30065. }
  30066. else
  30067. {
  30068. length = jmin ((int) source.lengthInSamples,
  30069. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30070. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30071. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30072. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30073. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30074. }
  30075. }
  30076. SamplerSound::~SamplerSound()
  30077. {
  30078. }
  30079. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30080. {
  30081. return midiNotes [midiNoteNumber];
  30082. }
  30083. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30084. {
  30085. return true;
  30086. }
  30087. SamplerVoice::SamplerVoice()
  30088. : pitchRatio (0.0),
  30089. sourceSamplePosition (0.0),
  30090. lgain (0.0f),
  30091. rgain (0.0f),
  30092. isInAttack (false),
  30093. isInRelease (false)
  30094. {
  30095. }
  30096. SamplerVoice::~SamplerVoice()
  30097. {
  30098. }
  30099. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30100. {
  30101. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30102. }
  30103. void SamplerVoice::startNote (const int midiNoteNumber,
  30104. const float velocity,
  30105. SynthesiserSound* s,
  30106. const int /*currentPitchWheelPosition*/)
  30107. {
  30108. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30109. jassert (sound != 0); // this object can only play SamplerSounds!
  30110. if (sound != 0)
  30111. {
  30112. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30113. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30114. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30115. sourceSamplePosition = 0.0;
  30116. lgain = velocity;
  30117. rgain = velocity;
  30118. isInAttack = (sound->attackSamples > 0);
  30119. isInRelease = false;
  30120. if (isInAttack)
  30121. {
  30122. attackReleaseLevel = 0.0f;
  30123. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30124. }
  30125. else
  30126. {
  30127. attackReleaseLevel = 1.0f;
  30128. attackDelta = 0.0f;
  30129. }
  30130. if (sound->releaseSamples > 0)
  30131. {
  30132. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30133. }
  30134. else
  30135. {
  30136. releaseDelta = 0.0f;
  30137. }
  30138. }
  30139. }
  30140. void SamplerVoice::stopNote (const bool allowTailOff)
  30141. {
  30142. if (allowTailOff)
  30143. {
  30144. isInAttack = false;
  30145. isInRelease = true;
  30146. }
  30147. else
  30148. {
  30149. clearCurrentNote();
  30150. }
  30151. }
  30152. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30153. {
  30154. }
  30155. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30156. const int /*newValue*/)
  30157. {
  30158. }
  30159. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30160. {
  30161. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30162. if (playingSound != 0)
  30163. {
  30164. const float* const inL = playingSound->data->getSampleData (0, 0);
  30165. const float* const inR = playingSound->data->getNumChannels() > 1
  30166. ? playingSound->data->getSampleData (1, 0) : 0;
  30167. float* outL = outputBuffer.getSampleData (0, startSample);
  30168. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30169. while (--numSamples >= 0)
  30170. {
  30171. const int pos = (int) sourceSamplePosition;
  30172. const float alpha = (float) (sourceSamplePosition - pos);
  30173. const float invAlpha = 1.0f - alpha;
  30174. // just using a very simple linear interpolation here..
  30175. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30176. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30177. : l;
  30178. l *= lgain;
  30179. r *= rgain;
  30180. if (isInAttack)
  30181. {
  30182. l *= attackReleaseLevel;
  30183. r *= attackReleaseLevel;
  30184. attackReleaseLevel += attackDelta;
  30185. if (attackReleaseLevel >= 1.0f)
  30186. {
  30187. attackReleaseLevel = 1.0f;
  30188. isInAttack = false;
  30189. }
  30190. }
  30191. else if (isInRelease)
  30192. {
  30193. l *= attackReleaseLevel;
  30194. r *= attackReleaseLevel;
  30195. attackReleaseLevel += releaseDelta;
  30196. if (attackReleaseLevel <= 0.0f)
  30197. {
  30198. stopNote (false);
  30199. break;
  30200. }
  30201. }
  30202. if (outR != 0)
  30203. {
  30204. *outL++ += l;
  30205. *outR++ += r;
  30206. }
  30207. else
  30208. {
  30209. *outL++ += (l + r) * 0.5f;
  30210. }
  30211. sourceSamplePosition += pitchRatio;
  30212. if (sourceSamplePosition > playingSound->length)
  30213. {
  30214. stopNote (false);
  30215. break;
  30216. }
  30217. }
  30218. }
  30219. }
  30220. END_JUCE_NAMESPACE
  30221. /*** End of inlined file: juce_Sampler.cpp ***/
  30222. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30223. BEGIN_JUCE_NAMESPACE
  30224. SynthesiserSound::SynthesiserSound()
  30225. {
  30226. }
  30227. SynthesiserSound::~SynthesiserSound()
  30228. {
  30229. }
  30230. SynthesiserVoice::SynthesiserVoice()
  30231. : currentSampleRate (44100.0),
  30232. currentlyPlayingNote (-1),
  30233. noteOnTime (0),
  30234. currentlyPlayingSound (0)
  30235. {
  30236. }
  30237. SynthesiserVoice::~SynthesiserVoice()
  30238. {
  30239. }
  30240. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30241. {
  30242. return currentlyPlayingSound != 0
  30243. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30244. }
  30245. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30246. {
  30247. currentSampleRate = newRate;
  30248. }
  30249. void SynthesiserVoice::clearCurrentNote()
  30250. {
  30251. currentlyPlayingNote = -1;
  30252. currentlyPlayingSound = 0;
  30253. }
  30254. Synthesiser::Synthesiser()
  30255. : sampleRate (0),
  30256. lastNoteOnCounter (0),
  30257. shouldStealNotes (true)
  30258. {
  30259. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30260. lastPitchWheelValues[i] = 0x2000;
  30261. }
  30262. Synthesiser::~Synthesiser()
  30263. {
  30264. }
  30265. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30266. {
  30267. const ScopedLock sl (lock);
  30268. return voices [index];
  30269. }
  30270. void Synthesiser::clearVoices()
  30271. {
  30272. const ScopedLock sl (lock);
  30273. voices.clear();
  30274. }
  30275. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30276. {
  30277. const ScopedLock sl (lock);
  30278. voices.add (newVoice);
  30279. }
  30280. void Synthesiser::removeVoice (const int index)
  30281. {
  30282. const ScopedLock sl (lock);
  30283. voices.remove (index);
  30284. }
  30285. void Synthesiser::clearSounds()
  30286. {
  30287. const ScopedLock sl (lock);
  30288. sounds.clear();
  30289. }
  30290. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30291. {
  30292. const ScopedLock sl (lock);
  30293. sounds.add (newSound);
  30294. }
  30295. void Synthesiser::removeSound (const int index)
  30296. {
  30297. const ScopedLock sl (lock);
  30298. sounds.remove (index);
  30299. }
  30300. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30301. {
  30302. shouldStealNotes = shouldStealNotes_;
  30303. }
  30304. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30305. {
  30306. if (sampleRate != newRate)
  30307. {
  30308. const ScopedLock sl (lock);
  30309. allNotesOff (0, false);
  30310. sampleRate = newRate;
  30311. for (int i = voices.size(); --i >= 0;)
  30312. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30313. }
  30314. }
  30315. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30316. const MidiBuffer& midiData,
  30317. int startSample,
  30318. int numSamples)
  30319. {
  30320. // must set the sample rate before using this!
  30321. jassert (sampleRate != 0);
  30322. const ScopedLock sl (lock);
  30323. MidiBuffer::Iterator midiIterator (midiData);
  30324. midiIterator.setNextSamplePosition (startSample);
  30325. MidiMessage m (0xf4, 0.0);
  30326. while (numSamples > 0)
  30327. {
  30328. int midiEventPos;
  30329. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30330. && midiEventPos < startSample + numSamples;
  30331. const int numThisTime = useEvent ? midiEventPos - startSample
  30332. : numSamples;
  30333. if (numThisTime > 0)
  30334. {
  30335. for (int i = voices.size(); --i >= 0;)
  30336. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30337. }
  30338. if (useEvent)
  30339. {
  30340. if (m.isNoteOn())
  30341. {
  30342. const int channel = m.getChannel();
  30343. noteOn (channel,
  30344. m.getNoteNumber(),
  30345. m.getFloatVelocity());
  30346. }
  30347. else if (m.isNoteOff())
  30348. {
  30349. noteOff (m.getChannel(),
  30350. m.getNoteNumber(),
  30351. true);
  30352. }
  30353. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30354. {
  30355. allNotesOff (m.getChannel(), true);
  30356. }
  30357. else if (m.isPitchWheel())
  30358. {
  30359. const int channel = m.getChannel();
  30360. const int wheelPos = m.getPitchWheelValue();
  30361. lastPitchWheelValues [channel - 1] = wheelPos;
  30362. handlePitchWheel (channel, wheelPos);
  30363. }
  30364. else if (m.isController())
  30365. {
  30366. handleController (m.getChannel(),
  30367. m.getControllerNumber(),
  30368. m.getControllerValue());
  30369. }
  30370. }
  30371. startSample += numThisTime;
  30372. numSamples -= numThisTime;
  30373. }
  30374. }
  30375. void Synthesiser::noteOn (const int midiChannel,
  30376. const int midiNoteNumber,
  30377. const float velocity)
  30378. {
  30379. const ScopedLock sl (lock);
  30380. for (int i = sounds.size(); --i >= 0;)
  30381. {
  30382. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30383. if (sound->appliesToNote (midiNoteNumber)
  30384. && sound->appliesToChannel (midiChannel))
  30385. {
  30386. startVoice (findFreeVoice (sound, shouldStealNotes),
  30387. sound, midiChannel, midiNoteNumber, velocity);
  30388. }
  30389. }
  30390. }
  30391. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30392. SynthesiserSound* const sound,
  30393. const int midiChannel,
  30394. const int midiNoteNumber,
  30395. const float velocity)
  30396. {
  30397. if (voice != 0 && sound != 0)
  30398. {
  30399. if (voice->currentlyPlayingSound != 0)
  30400. voice->stopNote (false);
  30401. voice->startNote (midiNoteNumber,
  30402. velocity,
  30403. sound,
  30404. lastPitchWheelValues [midiChannel - 1]);
  30405. voice->currentlyPlayingNote = midiNoteNumber;
  30406. voice->noteOnTime = ++lastNoteOnCounter;
  30407. voice->currentlyPlayingSound = sound;
  30408. }
  30409. }
  30410. void Synthesiser::noteOff (const int midiChannel,
  30411. const int midiNoteNumber,
  30412. const bool allowTailOff)
  30413. {
  30414. const ScopedLock sl (lock);
  30415. for (int i = voices.size(); --i >= 0;)
  30416. {
  30417. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30418. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30419. {
  30420. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30421. if (sound != 0
  30422. && sound->appliesToNote (midiNoteNumber)
  30423. && sound->appliesToChannel (midiChannel))
  30424. {
  30425. voice->stopNote (allowTailOff);
  30426. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30427. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30428. }
  30429. }
  30430. }
  30431. }
  30432. void Synthesiser::allNotesOff (const int midiChannel,
  30433. const bool allowTailOff)
  30434. {
  30435. const ScopedLock sl (lock);
  30436. for (int i = voices.size(); --i >= 0;)
  30437. {
  30438. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30439. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30440. voice->stopNote (allowTailOff);
  30441. }
  30442. }
  30443. void Synthesiser::handlePitchWheel (const int midiChannel,
  30444. const int wheelValue)
  30445. {
  30446. const ScopedLock sl (lock);
  30447. for (int i = voices.size(); --i >= 0;)
  30448. {
  30449. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30450. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30451. {
  30452. voice->pitchWheelMoved (wheelValue);
  30453. }
  30454. }
  30455. }
  30456. void Synthesiser::handleController (const int midiChannel,
  30457. const int controllerNumber,
  30458. const int controllerValue)
  30459. {
  30460. const ScopedLock sl (lock);
  30461. for (int i = voices.size(); --i >= 0;)
  30462. {
  30463. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30464. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30465. voice->controllerMoved (controllerNumber, controllerValue);
  30466. }
  30467. }
  30468. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30469. const bool stealIfNoneAvailable) const
  30470. {
  30471. const ScopedLock sl (lock);
  30472. for (int i = voices.size(); --i >= 0;)
  30473. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30474. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30475. return voices.getUnchecked (i);
  30476. if (stealIfNoneAvailable)
  30477. {
  30478. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30479. SynthesiserVoice* oldest = 0;
  30480. for (int i = voices.size(); --i >= 0;)
  30481. {
  30482. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30483. if (voice->canPlaySound (soundToPlay)
  30484. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30485. oldest = voice;
  30486. }
  30487. jassert (oldest != 0);
  30488. return oldest;
  30489. }
  30490. return 0;
  30491. }
  30492. END_JUCE_NAMESPACE
  30493. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30494. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30495. BEGIN_JUCE_NAMESPACE
  30496. // special message of our own with a string in it
  30497. class ActionMessage : public Message
  30498. {
  30499. public:
  30500. ActionMessage (const String& messageText, ActionListener* const listener_) throw()
  30501. : message (messageText)
  30502. {
  30503. pointerParameter = listener_;
  30504. }
  30505. const String message;
  30506. private:
  30507. JUCE_DECLARE_NON_COPYABLE (ActionMessage);
  30508. };
  30509. ActionBroadcaster::CallbackReceiver::CallbackReceiver() {}
  30510. void ActionBroadcaster::CallbackReceiver::handleMessage (const Message& message)
  30511. {
  30512. const ActionMessage& am = static_cast <const ActionMessage&> (message);
  30513. ActionListener* const target = static_cast <ActionListener*> (am.pointerParameter);
  30514. if (owner->actionListeners.contains (target))
  30515. target->actionListenerCallback (am.message);
  30516. }
  30517. ActionBroadcaster::ActionBroadcaster()
  30518. {
  30519. // are you trying to create this object before or after juce has been intialised??
  30520. jassert (MessageManager::instance != 0);
  30521. callback.owner = this;
  30522. }
  30523. ActionBroadcaster::~ActionBroadcaster()
  30524. {
  30525. // all event-based objects must be deleted BEFORE juce is shut down!
  30526. jassert (MessageManager::instance != 0);
  30527. }
  30528. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30529. {
  30530. const ScopedLock sl (actionListenerLock);
  30531. if (listener != 0)
  30532. actionListeners.add (listener);
  30533. }
  30534. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30535. {
  30536. const ScopedLock sl (actionListenerLock);
  30537. actionListeners.removeValue (listener);
  30538. }
  30539. void ActionBroadcaster::removeAllActionListeners()
  30540. {
  30541. const ScopedLock sl (actionListenerLock);
  30542. actionListeners.clear();
  30543. }
  30544. void ActionBroadcaster::sendActionMessage (const String& message) const
  30545. {
  30546. const ScopedLock sl (actionListenerLock);
  30547. for (int i = actionListeners.size(); --i >= 0;)
  30548. callback.postMessage (new ActionMessage (message, actionListeners.getUnchecked(i)));
  30549. }
  30550. END_JUCE_NAMESPACE
  30551. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30552. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30553. BEGIN_JUCE_NAMESPACE
  30554. class AsyncUpdaterMessage : public CallbackMessage
  30555. {
  30556. public:
  30557. AsyncUpdaterMessage (AsyncUpdater& owner_)
  30558. : owner (owner_)
  30559. {
  30560. }
  30561. void messageCallback()
  30562. {
  30563. if (shouldDeliver.compareAndSetBool (0, 1))
  30564. owner.handleAsyncUpdate();
  30565. }
  30566. Atomic<int> shouldDeliver;
  30567. private:
  30568. AsyncUpdater& owner;
  30569. };
  30570. AsyncUpdater::AsyncUpdater()
  30571. {
  30572. message = new AsyncUpdaterMessage (*this);
  30573. }
  30574. inline Atomic<int>& AsyncUpdater::getDeliveryFlag() const throw()
  30575. {
  30576. return static_cast <AsyncUpdaterMessage*> (message.getObject())->shouldDeliver;
  30577. }
  30578. AsyncUpdater::~AsyncUpdater()
  30579. {
  30580. // You're deleting this object with a background thread while there's an update
  30581. // pending on the main event thread - that's pretty dodgy threading, as the callback could
  30582. // happen after this destructor has finished. You should either use a MessageManagerLock while
  30583. // deleting this object, or find some other way to avoid such a race condition.
  30584. jassert ((! isUpdatePending()) || MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30585. getDeliveryFlag().set (0);
  30586. }
  30587. void AsyncUpdater::triggerAsyncUpdate()
  30588. {
  30589. if (getDeliveryFlag().compareAndSetBool (1, 0))
  30590. message->post();
  30591. }
  30592. void AsyncUpdater::cancelPendingUpdate() throw()
  30593. {
  30594. getDeliveryFlag().set (0);
  30595. }
  30596. void AsyncUpdater::handleUpdateNowIfNeeded()
  30597. {
  30598. // This can only be called by the event thread.
  30599. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30600. if (getDeliveryFlag().exchange (0) != 0)
  30601. handleAsyncUpdate();
  30602. }
  30603. bool AsyncUpdater::isUpdatePending() const throw()
  30604. {
  30605. return getDeliveryFlag().value != 0;
  30606. }
  30607. END_JUCE_NAMESPACE
  30608. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30609. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30610. BEGIN_JUCE_NAMESPACE
  30611. ChangeBroadcaster::ChangeBroadcaster() throw()
  30612. {
  30613. // are you trying to create this object before or after juce has been intialised??
  30614. jassert (MessageManager::instance != 0);
  30615. callback.owner = this;
  30616. }
  30617. ChangeBroadcaster::~ChangeBroadcaster()
  30618. {
  30619. // all event-based objects must be deleted BEFORE juce is shut down!
  30620. jassert (MessageManager::instance != 0);
  30621. }
  30622. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  30623. {
  30624. // Listeners can only be safely added when the event thread is locked
  30625. // You can use a MessageManagerLock if you need to call this from another thread.
  30626. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30627. changeListeners.add (listener);
  30628. }
  30629. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  30630. {
  30631. // Listeners can only be safely added when the event thread is locked
  30632. // You can use a MessageManagerLock if you need to call this from another thread.
  30633. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30634. changeListeners.remove (listener);
  30635. }
  30636. void ChangeBroadcaster::removeAllChangeListeners()
  30637. {
  30638. // Listeners can only be safely added when the event thread is locked
  30639. // You can use a MessageManagerLock if you need to call this from another thread.
  30640. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30641. changeListeners.clear();
  30642. }
  30643. void ChangeBroadcaster::sendChangeMessage()
  30644. {
  30645. if (changeListeners.size() > 0)
  30646. callback.triggerAsyncUpdate();
  30647. }
  30648. void ChangeBroadcaster::sendSynchronousChangeMessage()
  30649. {
  30650. // This can only be called by the event thread.
  30651. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  30652. callback.cancelPendingUpdate();
  30653. callListeners();
  30654. }
  30655. void ChangeBroadcaster::dispatchPendingMessages()
  30656. {
  30657. callback.handleUpdateNowIfNeeded();
  30658. }
  30659. void ChangeBroadcaster::callListeners()
  30660. {
  30661. changeListeners.call (&ChangeListener::changeListenerCallback, this);
  30662. }
  30663. ChangeBroadcaster::ChangeBroadcasterCallback::ChangeBroadcasterCallback()
  30664. : owner (0)
  30665. {
  30666. }
  30667. void ChangeBroadcaster::ChangeBroadcasterCallback::handleAsyncUpdate()
  30668. {
  30669. jassert (owner != 0);
  30670. owner->callListeners();
  30671. }
  30672. END_JUCE_NAMESPACE
  30673. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30674. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30675. BEGIN_JUCE_NAMESPACE
  30676. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30677. const uint32 magicMessageHeaderNumber)
  30678. : Thread ("Juce IPC connection"),
  30679. callbackConnectionState (false),
  30680. useMessageThread (callbacksOnMessageThread),
  30681. magicMessageHeader (magicMessageHeaderNumber),
  30682. pipeReceiveMessageTimeout (-1)
  30683. {
  30684. }
  30685. InterprocessConnection::~InterprocessConnection()
  30686. {
  30687. callbackConnectionState = false;
  30688. disconnect();
  30689. }
  30690. bool InterprocessConnection::connectToSocket (const String& hostName,
  30691. const int portNumber,
  30692. const int timeOutMillisecs)
  30693. {
  30694. disconnect();
  30695. const ScopedLock sl (pipeAndSocketLock);
  30696. socket = new StreamingSocket();
  30697. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30698. {
  30699. connectionMadeInt();
  30700. startThread();
  30701. return true;
  30702. }
  30703. else
  30704. {
  30705. socket = 0;
  30706. return false;
  30707. }
  30708. }
  30709. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30710. const int pipeReceiveMessageTimeoutMs)
  30711. {
  30712. disconnect();
  30713. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30714. if (newPipe->openExisting (pipeName))
  30715. {
  30716. const ScopedLock sl (pipeAndSocketLock);
  30717. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30718. initialiseWithPipe (newPipe.release());
  30719. return true;
  30720. }
  30721. return false;
  30722. }
  30723. bool InterprocessConnection::createPipe (const String& pipeName,
  30724. const int pipeReceiveMessageTimeoutMs)
  30725. {
  30726. disconnect();
  30727. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30728. if (newPipe->createNewPipe (pipeName))
  30729. {
  30730. const ScopedLock sl (pipeAndSocketLock);
  30731. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30732. initialiseWithPipe (newPipe.release());
  30733. return true;
  30734. }
  30735. return false;
  30736. }
  30737. void InterprocessConnection::disconnect()
  30738. {
  30739. if (socket != 0)
  30740. socket->close();
  30741. if (pipe != 0)
  30742. {
  30743. pipe->cancelPendingReads();
  30744. pipe->close();
  30745. }
  30746. stopThread (4000);
  30747. {
  30748. const ScopedLock sl (pipeAndSocketLock);
  30749. socket = 0;
  30750. pipe = 0;
  30751. }
  30752. connectionLostInt();
  30753. }
  30754. bool InterprocessConnection::isConnected() const
  30755. {
  30756. const ScopedLock sl (pipeAndSocketLock);
  30757. return ((socket != 0 && socket->isConnected())
  30758. || (pipe != 0 && pipe->isOpen()))
  30759. && isThreadRunning();
  30760. }
  30761. const String InterprocessConnection::getConnectedHostName() const
  30762. {
  30763. if (pipe != 0)
  30764. {
  30765. return "localhost";
  30766. }
  30767. else if (socket != 0)
  30768. {
  30769. if (! socket->isLocal())
  30770. return socket->getHostName();
  30771. return "localhost";
  30772. }
  30773. return String::empty;
  30774. }
  30775. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30776. {
  30777. uint32 messageHeader[2];
  30778. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30779. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30780. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30781. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30782. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30783. int bytesWritten = 0;
  30784. const ScopedLock sl (pipeAndSocketLock);
  30785. if (socket != 0)
  30786. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30787. else if (pipe != 0)
  30788. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30789. return bytesWritten == (int) messageData.getSize();
  30790. }
  30791. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30792. {
  30793. jassert (socket == 0);
  30794. socket = socket_;
  30795. connectionMadeInt();
  30796. startThread();
  30797. }
  30798. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30799. {
  30800. jassert (pipe == 0);
  30801. pipe = pipe_;
  30802. connectionMadeInt();
  30803. startThread();
  30804. }
  30805. const int messageMagicNumber = 0xb734128b;
  30806. void InterprocessConnection::handleMessage (const Message& message)
  30807. {
  30808. if (message.intParameter1 == messageMagicNumber)
  30809. {
  30810. switch (message.intParameter2)
  30811. {
  30812. case 0:
  30813. {
  30814. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30815. messageReceived (*data);
  30816. break;
  30817. }
  30818. case 1:
  30819. connectionMade();
  30820. break;
  30821. case 2:
  30822. connectionLost();
  30823. break;
  30824. }
  30825. }
  30826. }
  30827. void InterprocessConnection::connectionMadeInt()
  30828. {
  30829. if (! callbackConnectionState)
  30830. {
  30831. callbackConnectionState = true;
  30832. if (useMessageThread)
  30833. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30834. else
  30835. connectionMade();
  30836. }
  30837. }
  30838. void InterprocessConnection::connectionLostInt()
  30839. {
  30840. if (callbackConnectionState)
  30841. {
  30842. callbackConnectionState = false;
  30843. if (useMessageThread)
  30844. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  30845. else
  30846. connectionLost();
  30847. }
  30848. }
  30849. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  30850. {
  30851. jassert (callbackConnectionState);
  30852. if (useMessageThread)
  30853. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  30854. else
  30855. messageReceived (data);
  30856. }
  30857. bool InterprocessConnection::readNextMessageInt()
  30858. {
  30859. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  30860. uint32 messageHeader[2];
  30861. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  30862. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  30863. if (bytes == sizeof (messageHeader)
  30864. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  30865. {
  30866. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  30867. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  30868. {
  30869. MemoryBlock messageData (bytesInMessage, true);
  30870. int bytesRead = 0;
  30871. while (bytesInMessage > 0)
  30872. {
  30873. if (threadShouldExit())
  30874. return false;
  30875. const int numThisTime = jmin (bytesInMessage, 65536);
  30876. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  30877. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  30878. if (bytesIn <= 0)
  30879. break;
  30880. bytesRead += bytesIn;
  30881. bytesInMessage -= bytesIn;
  30882. }
  30883. if (bytesRead >= 0)
  30884. deliverDataInt (messageData);
  30885. }
  30886. }
  30887. else if (bytes < 0)
  30888. {
  30889. {
  30890. const ScopedLock sl (pipeAndSocketLock);
  30891. socket = 0;
  30892. }
  30893. connectionLostInt();
  30894. return false;
  30895. }
  30896. return true;
  30897. }
  30898. void InterprocessConnection::run()
  30899. {
  30900. while (! threadShouldExit())
  30901. {
  30902. if (socket != 0)
  30903. {
  30904. const int ready = socket->waitUntilReady (true, 0);
  30905. if (ready < 0)
  30906. {
  30907. {
  30908. const ScopedLock sl (pipeAndSocketLock);
  30909. socket = 0;
  30910. }
  30911. connectionLostInt();
  30912. break;
  30913. }
  30914. else if (ready > 0)
  30915. {
  30916. if (! readNextMessageInt())
  30917. break;
  30918. }
  30919. else
  30920. {
  30921. Thread::sleep (2);
  30922. }
  30923. }
  30924. else if (pipe != 0)
  30925. {
  30926. if (! pipe->isOpen())
  30927. {
  30928. {
  30929. const ScopedLock sl (pipeAndSocketLock);
  30930. pipe = 0;
  30931. }
  30932. connectionLostInt();
  30933. break;
  30934. }
  30935. else
  30936. {
  30937. if (! readNextMessageInt())
  30938. break;
  30939. }
  30940. }
  30941. else
  30942. {
  30943. break;
  30944. }
  30945. }
  30946. }
  30947. END_JUCE_NAMESPACE
  30948. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  30949. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30950. BEGIN_JUCE_NAMESPACE
  30951. InterprocessConnectionServer::InterprocessConnectionServer()
  30952. : Thread ("Juce IPC server")
  30953. {
  30954. }
  30955. InterprocessConnectionServer::~InterprocessConnectionServer()
  30956. {
  30957. stop();
  30958. }
  30959. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  30960. {
  30961. stop();
  30962. socket = new StreamingSocket();
  30963. if (socket->createListener (portNumber))
  30964. {
  30965. startThread();
  30966. return true;
  30967. }
  30968. socket = 0;
  30969. return false;
  30970. }
  30971. void InterprocessConnectionServer::stop()
  30972. {
  30973. signalThreadShouldExit();
  30974. if (socket != 0)
  30975. socket->close();
  30976. stopThread (4000);
  30977. socket = 0;
  30978. }
  30979. void InterprocessConnectionServer::run()
  30980. {
  30981. while ((! threadShouldExit()) && socket != 0)
  30982. {
  30983. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  30984. if (clientSocket != 0)
  30985. {
  30986. InterprocessConnection* newConnection = createConnectionObject();
  30987. if (newConnection != 0)
  30988. newConnection->initialiseWithSocket (clientSocket.release());
  30989. }
  30990. }
  30991. }
  30992. END_JUCE_NAMESPACE
  30993. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30994. /*** Start of inlined file: juce_Message.cpp ***/
  30995. BEGIN_JUCE_NAMESPACE
  30996. Message::Message() throw()
  30997. : intParameter1 (0),
  30998. intParameter2 (0),
  30999. intParameter3 (0),
  31000. pointerParameter (0),
  31001. messageRecipient (0)
  31002. {
  31003. }
  31004. Message::Message (const int intParameter1_,
  31005. const int intParameter2_,
  31006. const int intParameter3_,
  31007. void* const pointerParameter_) throw()
  31008. : intParameter1 (intParameter1_),
  31009. intParameter2 (intParameter2_),
  31010. intParameter3 (intParameter3_),
  31011. pointerParameter (pointerParameter_),
  31012. messageRecipient (0)
  31013. {
  31014. }
  31015. Message::~Message()
  31016. {
  31017. }
  31018. END_JUCE_NAMESPACE
  31019. /*** End of inlined file: juce_Message.cpp ***/
  31020. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31021. BEGIN_JUCE_NAMESPACE
  31022. MessageListener::MessageListener() throw()
  31023. {
  31024. // are you trying to create a messagelistener before or after juce has been intialised??
  31025. jassert (MessageManager::instance != 0);
  31026. if (MessageManager::instance != 0)
  31027. MessageManager::instance->messageListeners.add (this);
  31028. }
  31029. MessageListener::~MessageListener()
  31030. {
  31031. if (MessageManager::instance != 0)
  31032. MessageManager::instance->messageListeners.removeValue (this);
  31033. }
  31034. void MessageListener::postMessage (Message* const message) const throw()
  31035. {
  31036. message->messageRecipient = const_cast <MessageListener*> (this);
  31037. if (MessageManager::instance == 0)
  31038. MessageManager::getInstance();
  31039. MessageManager::instance->postMessageToQueue (message);
  31040. }
  31041. bool MessageListener::isValidMessageListener() const throw()
  31042. {
  31043. return (MessageManager::instance != 0)
  31044. && MessageManager::instance->messageListeners.contains (this);
  31045. }
  31046. END_JUCE_NAMESPACE
  31047. /*** End of inlined file: juce_MessageListener.cpp ***/
  31048. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31049. BEGIN_JUCE_NAMESPACE
  31050. // platform-specific functions..
  31051. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31052. bool juce_postMessageToSystemQueue (Message* message);
  31053. MessageManager* MessageManager::instance = 0;
  31054. static const int quitMessageId = 0xfffff321;
  31055. MessageManager::MessageManager() throw()
  31056. : quitMessagePosted (false),
  31057. quitMessageReceived (false),
  31058. threadWithLock (0)
  31059. {
  31060. messageThreadId = Thread::getCurrentThreadId();
  31061. if (JUCEApplication::isStandaloneApp())
  31062. Thread::setCurrentThreadName ("Juce Message Thread");
  31063. }
  31064. MessageManager::~MessageManager() throw()
  31065. {
  31066. broadcaster = 0;
  31067. doPlatformSpecificShutdown();
  31068. // If you hit this assertion, then you've probably leaked some kind of MessageListener object..
  31069. jassert (messageListeners.size() == 0);
  31070. jassert (instance == this);
  31071. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31072. }
  31073. MessageManager* MessageManager::getInstance() throw()
  31074. {
  31075. if (instance == 0)
  31076. {
  31077. instance = new MessageManager();
  31078. doPlatformSpecificInitialisation();
  31079. }
  31080. return instance;
  31081. }
  31082. void MessageManager::postMessageToQueue (Message* const message)
  31083. {
  31084. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31085. Message::Ptr deleter (message); // (this will delete messages that were just created with a 0 ref count)
  31086. }
  31087. CallbackMessage::CallbackMessage() throw() {}
  31088. CallbackMessage::~CallbackMessage() {}
  31089. void CallbackMessage::post()
  31090. {
  31091. if (MessageManager::instance != 0)
  31092. MessageManager::instance->postMessageToQueue (this);
  31093. }
  31094. // not for public use..
  31095. void MessageManager::deliverMessage (Message* const message)
  31096. {
  31097. JUCE_TRY
  31098. {
  31099. MessageListener* const recipient = message->messageRecipient;
  31100. if (recipient == 0)
  31101. {
  31102. CallbackMessage* const callbackMessage = dynamic_cast <CallbackMessage*> (message);
  31103. if (callbackMessage != 0)
  31104. {
  31105. callbackMessage->messageCallback();
  31106. }
  31107. else if (message->intParameter1 == quitMessageId)
  31108. {
  31109. quitMessageReceived = true;
  31110. }
  31111. }
  31112. else if (messageListeners.contains (recipient))
  31113. {
  31114. recipient->handleMessage (*message);
  31115. }
  31116. }
  31117. JUCE_CATCH_EXCEPTION
  31118. }
  31119. #if ! (JUCE_MAC || JUCE_IOS)
  31120. void MessageManager::runDispatchLoop()
  31121. {
  31122. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31123. runDispatchLoopUntil (-1);
  31124. }
  31125. void MessageManager::stopDispatchLoop()
  31126. {
  31127. postMessageToQueue (new Message (quitMessageId, 0, 0, 0));
  31128. quitMessagePosted = true;
  31129. }
  31130. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31131. {
  31132. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31133. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31134. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31135. && ! quitMessageReceived)
  31136. {
  31137. JUCE_TRY
  31138. {
  31139. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31140. {
  31141. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31142. if (msToWait > 0)
  31143. Thread::sleep (jmin (5, msToWait));
  31144. }
  31145. }
  31146. JUCE_CATCH_EXCEPTION
  31147. }
  31148. return ! quitMessageReceived;
  31149. }
  31150. #endif
  31151. void MessageManager::deliverBroadcastMessage (const String& value)
  31152. {
  31153. if (broadcaster != 0)
  31154. broadcaster->sendActionMessage (value);
  31155. }
  31156. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31157. {
  31158. if (broadcaster == 0)
  31159. broadcaster = new ActionBroadcaster();
  31160. broadcaster->addActionListener (listener);
  31161. }
  31162. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31163. {
  31164. if (broadcaster != 0)
  31165. broadcaster->removeActionListener (listener);
  31166. }
  31167. bool MessageManager::isThisTheMessageThread() const throw()
  31168. {
  31169. return Thread::getCurrentThreadId() == messageThreadId;
  31170. }
  31171. void MessageManager::setCurrentThreadAsMessageThread()
  31172. {
  31173. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31174. if (messageThreadId != thisThread)
  31175. {
  31176. messageThreadId = thisThread;
  31177. // This is needed on windows to make sure the message window is created by this thread
  31178. doPlatformSpecificShutdown();
  31179. doPlatformSpecificInitialisation();
  31180. }
  31181. }
  31182. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31183. {
  31184. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31185. return thisThread == messageThreadId || thisThread == threadWithLock;
  31186. }
  31187. /* The only safe way to lock the message thread while another thread does
  31188. some work is by posting a special message, whose purpose is to tie up the event
  31189. loop until the other thread has finished its business.
  31190. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31191. get locked before making an event callback, because if the same OS lock gets indirectly
  31192. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31193. in Cocoa).
  31194. */
  31195. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31196. {
  31197. public:
  31198. BlockingMessage() {}
  31199. void messageCallback()
  31200. {
  31201. lockedEvent.signal();
  31202. releaseEvent.wait();
  31203. }
  31204. WaitableEvent lockedEvent, releaseEvent;
  31205. private:
  31206. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlockingMessage);
  31207. };
  31208. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31209. : locked (false)
  31210. {
  31211. init (threadToCheck, 0);
  31212. }
  31213. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31214. : locked (false)
  31215. {
  31216. init (0, jobToCheckForExitSignal);
  31217. }
  31218. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31219. {
  31220. if (MessageManager::instance != 0)
  31221. {
  31222. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31223. {
  31224. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31225. }
  31226. else
  31227. {
  31228. if (threadToCheck == 0 && job == 0)
  31229. {
  31230. MessageManager::instance->lockingLock.enter();
  31231. }
  31232. else
  31233. {
  31234. while (! MessageManager::instance->lockingLock.tryEnter())
  31235. {
  31236. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31237. || (job != 0 && job->shouldExit()))
  31238. return;
  31239. Thread::sleep (1);
  31240. }
  31241. }
  31242. blockingMessage = new BlockingMessage();
  31243. blockingMessage->post();
  31244. while (! blockingMessage->lockedEvent.wait (20))
  31245. {
  31246. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31247. || (job != 0 && job->shouldExit()))
  31248. {
  31249. blockingMessage->releaseEvent.signal();
  31250. blockingMessage = 0;
  31251. MessageManager::instance->lockingLock.exit();
  31252. return;
  31253. }
  31254. }
  31255. jassert (MessageManager::instance->threadWithLock == 0);
  31256. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31257. locked = true;
  31258. }
  31259. }
  31260. }
  31261. MessageManagerLock::~MessageManagerLock() throw()
  31262. {
  31263. if (blockingMessage != 0)
  31264. {
  31265. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31266. blockingMessage->releaseEvent.signal();
  31267. blockingMessage = 0;
  31268. if (MessageManager::instance != 0)
  31269. {
  31270. MessageManager::instance->threadWithLock = 0;
  31271. MessageManager::instance->lockingLock.exit();
  31272. }
  31273. }
  31274. }
  31275. END_JUCE_NAMESPACE
  31276. /*** End of inlined file: juce_MessageManager.cpp ***/
  31277. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31278. BEGIN_JUCE_NAMESPACE
  31279. class MultiTimer::MultiTimerCallback : public Timer
  31280. {
  31281. public:
  31282. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31283. : timerId (timerId_),
  31284. owner (owner_)
  31285. {
  31286. }
  31287. ~MultiTimerCallback()
  31288. {
  31289. }
  31290. void timerCallback()
  31291. {
  31292. owner.timerCallback (timerId);
  31293. }
  31294. const int timerId;
  31295. private:
  31296. MultiTimer& owner;
  31297. };
  31298. MultiTimer::MultiTimer() throw()
  31299. {
  31300. }
  31301. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31302. {
  31303. }
  31304. MultiTimer::~MultiTimer()
  31305. {
  31306. const ScopedLock sl (timerListLock);
  31307. timers.clear();
  31308. }
  31309. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31310. {
  31311. const ScopedLock sl (timerListLock);
  31312. for (int i = timers.size(); --i >= 0;)
  31313. {
  31314. MultiTimerCallback* const t = timers.getUnchecked(i);
  31315. if (t->timerId == timerId)
  31316. {
  31317. t->startTimer (intervalInMilliseconds);
  31318. return;
  31319. }
  31320. }
  31321. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31322. timers.add (newTimer);
  31323. newTimer->startTimer (intervalInMilliseconds);
  31324. }
  31325. void MultiTimer::stopTimer (const int timerId) throw()
  31326. {
  31327. const ScopedLock sl (timerListLock);
  31328. for (int i = timers.size(); --i >= 0;)
  31329. {
  31330. MultiTimerCallback* const t = timers.getUnchecked(i);
  31331. if (t->timerId == timerId)
  31332. t->stopTimer();
  31333. }
  31334. }
  31335. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31336. {
  31337. const ScopedLock sl (timerListLock);
  31338. for (int i = timers.size(); --i >= 0;)
  31339. {
  31340. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31341. if (t->timerId == timerId)
  31342. return t->isTimerRunning();
  31343. }
  31344. return false;
  31345. }
  31346. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31347. {
  31348. const ScopedLock sl (timerListLock);
  31349. for (int i = timers.size(); --i >= 0;)
  31350. {
  31351. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31352. if (t->timerId == timerId)
  31353. return t->getTimerInterval();
  31354. }
  31355. return 0;
  31356. }
  31357. END_JUCE_NAMESPACE
  31358. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31359. /*** Start of inlined file: juce_Timer.cpp ***/
  31360. BEGIN_JUCE_NAMESPACE
  31361. class InternalTimerThread : private Thread,
  31362. private MessageListener,
  31363. private DeletedAtShutdown,
  31364. private AsyncUpdater
  31365. {
  31366. public:
  31367. InternalTimerThread()
  31368. : Thread ("Juce Timer"),
  31369. firstTimer (0),
  31370. callbackNeeded (0)
  31371. {
  31372. triggerAsyncUpdate();
  31373. }
  31374. ~InternalTimerThread() throw()
  31375. {
  31376. stopThread (4000);
  31377. jassert (instance == this || instance == 0);
  31378. if (instance == this)
  31379. instance = 0;
  31380. }
  31381. void run()
  31382. {
  31383. uint32 lastTime = Time::getMillisecondCounter();
  31384. Message::Ptr message (new Message());
  31385. while (! threadShouldExit())
  31386. {
  31387. const uint32 now = Time::getMillisecondCounter();
  31388. if (now <= lastTime)
  31389. {
  31390. wait (2);
  31391. continue;
  31392. }
  31393. const int elapsed = now - lastTime;
  31394. lastTime = now;
  31395. const int timeUntilFirstTimer = getTimeUntilFirstTimer (elapsed);
  31396. if (timeUntilFirstTimer <= 0)
  31397. {
  31398. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31399. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31400. but if it fails it means the message-thread changed the value from under us so at least
  31401. some processing is happenening and we can just loop around and try again
  31402. */
  31403. if (callbackNeeded.compareAndSetBool (1, 0))
  31404. {
  31405. postMessage (message);
  31406. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31407. when the app has a modal loop), so this is how long to wait before assuming the
  31408. message has been lost and trying again.
  31409. */
  31410. const uint32 messageDeliveryTimeout = now + 2000;
  31411. while (callbackNeeded.get() != 0)
  31412. {
  31413. wait (4);
  31414. if (threadShouldExit())
  31415. return;
  31416. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31417. break;
  31418. }
  31419. }
  31420. }
  31421. else
  31422. {
  31423. // don't wait for too long because running this loop also helps keep the
  31424. // Time::getApproximateMillisecondTimer value stay up-to-date
  31425. wait (jlimit (1, 50, timeUntilFirstTimer));
  31426. }
  31427. }
  31428. }
  31429. void callTimers()
  31430. {
  31431. const ScopedLock sl (lock);
  31432. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31433. {
  31434. Timer* const t = firstTimer;
  31435. t->countdownMs = t->periodMs;
  31436. removeTimer (t);
  31437. addTimer (t);
  31438. const ScopedUnlock ul (lock);
  31439. JUCE_TRY
  31440. {
  31441. t->timerCallback();
  31442. }
  31443. JUCE_CATCH_EXCEPTION
  31444. }
  31445. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31446. before the boolean is set. This set should never fail since if it was false in the first place,
  31447. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31448. get a message then the value is true and the other thread can only set it to true again and
  31449. we will get another callback to set it to false.
  31450. */
  31451. callbackNeeded.set (0);
  31452. }
  31453. void handleMessage (const Message&)
  31454. {
  31455. callTimers();
  31456. }
  31457. void callTimersSynchronously()
  31458. {
  31459. if (! isThreadRunning())
  31460. {
  31461. // (This is relied on by some plugins in cases where the MM has
  31462. // had to restart and the async callback never started)
  31463. cancelPendingUpdate();
  31464. triggerAsyncUpdate();
  31465. }
  31466. callTimers();
  31467. }
  31468. static void callAnyTimersSynchronously()
  31469. {
  31470. if (InternalTimerThread::instance != 0)
  31471. InternalTimerThread::instance->callTimersSynchronously();
  31472. }
  31473. static inline void add (Timer* const tim) throw()
  31474. {
  31475. if (instance == 0)
  31476. instance = new InternalTimerThread();
  31477. const ScopedLock sl (instance->lock);
  31478. instance->addTimer (tim);
  31479. }
  31480. static inline void remove (Timer* const tim) throw()
  31481. {
  31482. if (instance != 0)
  31483. {
  31484. const ScopedLock sl (instance->lock);
  31485. instance->removeTimer (tim);
  31486. }
  31487. }
  31488. static inline void resetCounter (Timer* const tim,
  31489. const int newCounter) throw()
  31490. {
  31491. if (instance != 0)
  31492. {
  31493. tim->countdownMs = newCounter;
  31494. tim->periodMs = newCounter;
  31495. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31496. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31497. {
  31498. const ScopedLock sl (instance->lock);
  31499. instance->removeTimer (tim);
  31500. instance->addTimer (tim);
  31501. }
  31502. }
  31503. }
  31504. private:
  31505. friend class Timer;
  31506. static InternalTimerThread* instance;
  31507. static CriticalSection lock;
  31508. Timer* volatile firstTimer;
  31509. Atomic <int> callbackNeeded;
  31510. void addTimer (Timer* const t) throw()
  31511. {
  31512. #if JUCE_DEBUG
  31513. Timer* tt = firstTimer;
  31514. while (tt != 0)
  31515. {
  31516. // trying to add a timer that's already here - shouldn't get to this point,
  31517. // so if you get this assertion, let me know!
  31518. jassert (tt != t);
  31519. tt = tt->next;
  31520. }
  31521. jassert (t->previous == 0 && t->next == 0);
  31522. #endif
  31523. Timer* i = firstTimer;
  31524. if (i == 0 || i->countdownMs > t->countdownMs)
  31525. {
  31526. t->next = firstTimer;
  31527. firstTimer = t;
  31528. }
  31529. else
  31530. {
  31531. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31532. i = i->next;
  31533. jassert (i != 0);
  31534. t->next = i->next;
  31535. t->previous = i;
  31536. i->next = t;
  31537. }
  31538. if (t->next != 0)
  31539. t->next->previous = t;
  31540. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31541. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31542. notify();
  31543. }
  31544. void removeTimer (Timer* const t) throw()
  31545. {
  31546. #if JUCE_DEBUG
  31547. Timer* tt = firstTimer;
  31548. bool found = false;
  31549. while (tt != 0)
  31550. {
  31551. if (tt == t)
  31552. {
  31553. found = true;
  31554. break;
  31555. }
  31556. tt = tt->next;
  31557. }
  31558. // trying to remove a timer that's not here - shouldn't get to this point,
  31559. // so if you get this assertion, let me know!
  31560. jassert (found);
  31561. #endif
  31562. if (t->previous != 0)
  31563. {
  31564. jassert (firstTimer != t);
  31565. t->previous->next = t->next;
  31566. }
  31567. else
  31568. {
  31569. jassert (firstTimer == t);
  31570. firstTimer = t->next;
  31571. }
  31572. if (t->next != 0)
  31573. t->next->previous = t->previous;
  31574. t->next = 0;
  31575. t->previous = 0;
  31576. }
  31577. int getTimeUntilFirstTimer (const int numMillisecsElapsed) const
  31578. {
  31579. const ScopedLock sl (lock);
  31580. for (Timer* t = firstTimer; t != 0; t = t->next)
  31581. t->countdownMs -= numMillisecsElapsed;
  31582. return firstTimer != 0 ? firstTimer->countdownMs : 1000;
  31583. }
  31584. void handleAsyncUpdate()
  31585. {
  31586. startThread (7);
  31587. }
  31588. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternalTimerThread);
  31589. };
  31590. InternalTimerThread* InternalTimerThread::instance = 0;
  31591. CriticalSection InternalTimerThread::lock;
  31592. void juce_callAnyTimersSynchronously()
  31593. {
  31594. InternalTimerThread::callAnyTimersSynchronously();
  31595. }
  31596. #if JUCE_DEBUG
  31597. static SortedSet <Timer*> activeTimers;
  31598. #endif
  31599. Timer::Timer() throw()
  31600. : countdownMs (0),
  31601. periodMs (0),
  31602. previous (0),
  31603. next (0)
  31604. {
  31605. #if JUCE_DEBUG
  31606. activeTimers.add (this);
  31607. #endif
  31608. }
  31609. Timer::Timer (const Timer&) throw()
  31610. : countdownMs (0),
  31611. periodMs (0),
  31612. previous (0),
  31613. next (0)
  31614. {
  31615. #if JUCE_DEBUG
  31616. activeTimers.add (this);
  31617. #endif
  31618. }
  31619. Timer::~Timer()
  31620. {
  31621. stopTimer();
  31622. #if JUCE_DEBUG
  31623. activeTimers.removeValue (this);
  31624. #endif
  31625. }
  31626. void Timer::startTimer (const int interval) throw()
  31627. {
  31628. const ScopedLock sl (InternalTimerThread::lock);
  31629. #if JUCE_DEBUG
  31630. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31631. jassert (activeTimers.contains (this));
  31632. #endif
  31633. if (periodMs == 0)
  31634. {
  31635. countdownMs = interval;
  31636. periodMs = jmax (1, interval);
  31637. InternalTimerThread::add (this);
  31638. }
  31639. else
  31640. {
  31641. InternalTimerThread::resetCounter (this, interval);
  31642. }
  31643. }
  31644. void Timer::stopTimer() throw()
  31645. {
  31646. const ScopedLock sl (InternalTimerThread::lock);
  31647. #if JUCE_DEBUG
  31648. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31649. jassert (activeTimers.contains (this));
  31650. #endif
  31651. if (periodMs > 0)
  31652. {
  31653. InternalTimerThread::remove (this);
  31654. periodMs = 0;
  31655. }
  31656. }
  31657. END_JUCE_NAMESPACE
  31658. /*** End of inlined file: juce_Timer.cpp ***/
  31659. #endif
  31660. #if JUCE_BUILD_GUI
  31661. /*** Start of inlined file: juce_Component.cpp ***/
  31662. BEGIN_JUCE_NAMESPACE
  31663. #define CHECK_MESSAGE_MANAGER_IS_LOCKED jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31664. Component* Component::currentlyFocusedComponent = 0;
  31665. class Component::MouseListenerList
  31666. {
  31667. public:
  31668. MouseListenerList()
  31669. : numDeepMouseListeners (0)
  31670. {
  31671. }
  31672. void addListener (MouseListener* const newListener, const bool wantsEventsForAllNestedChildComponents)
  31673. {
  31674. if (! listeners.contains (newListener))
  31675. {
  31676. if (wantsEventsForAllNestedChildComponents)
  31677. {
  31678. listeners.insert (0, newListener);
  31679. ++numDeepMouseListeners;
  31680. }
  31681. else
  31682. {
  31683. listeners.add (newListener);
  31684. }
  31685. }
  31686. }
  31687. void removeListener (MouseListener* const listenerToRemove)
  31688. {
  31689. const int index = listeners.indexOf (listenerToRemove);
  31690. if (index >= 0)
  31691. {
  31692. if (index < numDeepMouseListeners)
  31693. --numDeepMouseListeners;
  31694. listeners.remove (index);
  31695. }
  31696. }
  31697. static void sendMouseEvent (Component& comp, BailOutChecker& checker,
  31698. void (MouseListener::*eventMethod) (const MouseEvent&), const MouseEvent& e)
  31699. {
  31700. if (checker.shouldBailOut())
  31701. return;
  31702. {
  31703. MouseListenerList* const list = comp.mouseListeners;
  31704. if (list != 0)
  31705. {
  31706. for (int i = list->listeners.size(); --i >= 0;)
  31707. {
  31708. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  31709. if (checker.shouldBailOut())
  31710. return;
  31711. i = jmin (i, list->listeners.size());
  31712. }
  31713. }
  31714. }
  31715. Component* p = comp.parentComponent;
  31716. while (p != 0)
  31717. {
  31718. MouseListenerList* const list = p->mouseListeners;
  31719. if (list != 0 && list->numDeepMouseListeners > 0)
  31720. {
  31721. BailOutChecker2 checker2 (checker, p);
  31722. for (int i = list->numDeepMouseListeners; --i >= 0;)
  31723. {
  31724. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  31725. if (checker2.shouldBailOut())
  31726. return;
  31727. i = jmin (i, list->numDeepMouseListeners);
  31728. }
  31729. }
  31730. p = p->parentComponent;
  31731. }
  31732. }
  31733. static void sendWheelEvent (Component& comp, BailOutChecker& checker, const MouseEvent& e,
  31734. const float wheelIncrementX, const float wheelIncrementY)
  31735. {
  31736. {
  31737. MouseListenerList* const list = comp.mouseListeners;
  31738. if (list != 0)
  31739. {
  31740. for (int i = list->listeners.size(); --i >= 0;)
  31741. {
  31742. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  31743. if (checker.shouldBailOut())
  31744. return;
  31745. i = jmin (i, list->listeners.size());
  31746. }
  31747. }
  31748. }
  31749. Component* p = comp.parentComponent;
  31750. while (p != 0)
  31751. {
  31752. MouseListenerList* const list = p->mouseListeners;
  31753. if (list != 0 && list->numDeepMouseListeners > 0)
  31754. {
  31755. BailOutChecker2 checker2 (checker, p);
  31756. for (int i = list->numDeepMouseListeners; --i >= 0;)
  31757. {
  31758. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  31759. if (checker2.shouldBailOut())
  31760. return;
  31761. i = jmin (i, list->numDeepMouseListeners);
  31762. }
  31763. }
  31764. p = p->parentComponent;
  31765. }
  31766. }
  31767. private:
  31768. Array <MouseListener*> listeners;
  31769. int numDeepMouseListeners;
  31770. class BailOutChecker2
  31771. {
  31772. public:
  31773. BailOutChecker2 (BailOutChecker& checker_, Component* const component)
  31774. : checker (checker_), safePointer (component)
  31775. {
  31776. }
  31777. bool shouldBailOut() const throw()
  31778. {
  31779. return checker.shouldBailOut() || safePointer == 0;
  31780. }
  31781. private:
  31782. BailOutChecker& checker;
  31783. const WeakReference<Component> safePointer;
  31784. JUCE_DECLARE_NON_COPYABLE (BailOutChecker2);
  31785. };
  31786. JUCE_DECLARE_NON_COPYABLE (MouseListenerList);
  31787. };
  31788. class Component::ComponentHelpers
  31789. {
  31790. public:
  31791. static void* runModalLoopCallback (void* userData)
  31792. {
  31793. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  31794. }
  31795. static const Identifier getColourPropertyId (const int colourId)
  31796. {
  31797. String s;
  31798. s.preallocateStorage (18);
  31799. s << "jcclr_" << String::toHexString (colourId);
  31800. return s;
  31801. }
  31802. static inline bool hitTest (Component& comp, const Point<int>& localPoint)
  31803. {
  31804. return isPositiveAndBelow (localPoint.getX(), comp.getWidth())
  31805. && isPositiveAndBelow (localPoint.getY(), comp.getHeight())
  31806. && comp.hitTest (localPoint.getX(), localPoint.getY());
  31807. }
  31808. static const Point<int> convertFromParentSpace (const Component& comp, const Point<int>& pointInParentSpace)
  31809. {
  31810. if (comp.affineTransform == 0)
  31811. return pointInParentSpace - comp.getPosition();
  31812. return pointInParentSpace.toFloat().transformedBy (comp.affineTransform->inverted()).toInt() - comp.getPosition();
  31813. }
  31814. static const Rectangle<int> convertFromParentSpace (const Component& comp, const Rectangle<int>& areaInParentSpace)
  31815. {
  31816. if (comp.affineTransform == 0)
  31817. return areaInParentSpace - comp.getPosition();
  31818. return areaInParentSpace.toFloat().transformed (comp.affineTransform->inverted()).getSmallestIntegerContainer() - comp.getPosition();
  31819. }
  31820. static const Point<int> convertToParentSpace (const Component& comp, const Point<int>& pointInLocalSpace)
  31821. {
  31822. if (comp.affineTransform == 0)
  31823. return pointInLocalSpace + comp.getPosition();
  31824. return (pointInLocalSpace + comp.getPosition()).toFloat().transformedBy (*comp.affineTransform).toInt();
  31825. }
  31826. static const Rectangle<int> convertToParentSpace (const Component& comp, const Rectangle<int>& areaInLocalSpace)
  31827. {
  31828. if (comp.affineTransform == 0)
  31829. return areaInLocalSpace + comp.getPosition();
  31830. return (areaInLocalSpace + comp.getPosition()).toFloat().transformed (*comp.affineTransform).getSmallestIntegerContainer();
  31831. }
  31832. template <typename Type>
  31833. static const Type convertFromDistantParentSpace (const Component* parent, const Component& target, Type coordInParent)
  31834. {
  31835. const Component* const directParent = target.getParentComponent();
  31836. jassert (directParent != 0);
  31837. if (directParent == parent)
  31838. return convertFromParentSpace (target, coordInParent);
  31839. return convertFromParentSpace (target, convertFromDistantParentSpace (parent, *directParent, coordInParent));
  31840. }
  31841. template <typename Type>
  31842. static const Type convertCoordinate (const Component* target, const Component* source, Type p)
  31843. {
  31844. while (source != 0)
  31845. {
  31846. if (source == target)
  31847. return p;
  31848. if (source->isParentOf (target))
  31849. return convertFromDistantParentSpace (source, *target, p);
  31850. if (source->isOnDesktop())
  31851. {
  31852. p = source->getPeer()->localToGlobal (p);
  31853. source = 0;
  31854. }
  31855. else
  31856. {
  31857. p = convertToParentSpace (*source, p);
  31858. source = source->getParentComponent();
  31859. }
  31860. }
  31861. jassert (source == 0);
  31862. if (target == 0)
  31863. return p;
  31864. const Component* const topLevelComp = target->getTopLevelComponent();
  31865. if (topLevelComp->isOnDesktop())
  31866. p = topLevelComp->getPeer()->globalToLocal (p);
  31867. else
  31868. p = convertFromParentSpace (*topLevelComp, p);
  31869. if (topLevelComp == target)
  31870. return p;
  31871. return convertFromDistantParentSpace (topLevelComp, *target, p);
  31872. }
  31873. static const Rectangle<int> getUnclippedArea (const Component& comp)
  31874. {
  31875. Rectangle<int> r (comp.getLocalBounds());
  31876. Component* const p = comp.getParentComponent();
  31877. if (p != 0)
  31878. r = r.getIntersection (convertFromParentSpace (comp, getUnclippedArea (*p)));
  31879. return r;
  31880. }
  31881. static void clipObscuredRegions (const Component& comp, Graphics& g, const Rectangle<int>& clipRect, const Point<int>& delta)
  31882. {
  31883. for (int i = comp.childComponentList.size(); --i >= 0;)
  31884. {
  31885. const Component& child = *comp.childComponentList.getUnchecked(i);
  31886. if (child.isVisible() && ! child.isTransformed())
  31887. {
  31888. const Rectangle<int> newClip (clipRect.getIntersection (child.bounds));
  31889. if (! newClip.isEmpty())
  31890. {
  31891. if (child.isOpaque())
  31892. {
  31893. g.excludeClipRegion (newClip + delta);
  31894. }
  31895. else
  31896. {
  31897. const Point<int> childPos (child.getPosition());
  31898. clipObscuredRegions (child, g, newClip - childPos, childPos + delta);
  31899. }
  31900. }
  31901. }
  31902. }
  31903. }
  31904. static void subtractObscuredRegions (const Component& comp, RectangleList& result,
  31905. const Point<int>& delta,
  31906. const Rectangle<int>& clipRect,
  31907. const Component* const compToAvoid)
  31908. {
  31909. for (int i = comp.childComponentList.size(); --i >= 0;)
  31910. {
  31911. const Component* const c = comp.childComponentList.getUnchecked(i);
  31912. if (c != compToAvoid && c->isVisible())
  31913. {
  31914. if (c->isOpaque())
  31915. {
  31916. Rectangle<int> childBounds (c->bounds.getIntersection (clipRect));
  31917. childBounds.translate (delta.getX(), delta.getY());
  31918. result.subtract (childBounds);
  31919. }
  31920. else
  31921. {
  31922. Rectangle<int> newClip (clipRect.getIntersection (c->bounds));
  31923. newClip.translate (-c->getX(), -c->getY());
  31924. subtractObscuredRegions (*c, result, c->getPosition() + delta,
  31925. newClip, compToAvoid);
  31926. }
  31927. }
  31928. }
  31929. }
  31930. static const Rectangle<int> getParentOrMainMonitorBounds (const Component& comp)
  31931. {
  31932. return comp.getParentComponent() != 0 ? comp.getParentComponent()->getLocalBounds()
  31933. : Desktop::getInstance().getMainMonitorArea();
  31934. }
  31935. };
  31936. Component::Component()
  31937. : parentComponent (0),
  31938. lookAndFeel (0),
  31939. effect (0),
  31940. componentFlags (0),
  31941. componentTransparency (0)
  31942. {
  31943. }
  31944. Component::Component (const String& name)
  31945. : componentName (name),
  31946. parentComponent (0),
  31947. lookAndFeel (0),
  31948. effect (0),
  31949. componentFlags (0),
  31950. componentTransparency (0)
  31951. {
  31952. }
  31953. Component::~Component()
  31954. {
  31955. #if ! JUCE_VC6 // (access to private union not allowed in VC6)
  31956. static_jassert (sizeof (flags) <= sizeof (componentFlags));
  31957. #endif
  31958. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31959. weakReferenceMaster.clear();
  31960. while (childComponentList.size() > 0)
  31961. removeChildComponent (childComponentList.size() - 1, false, true);
  31962. if (parentComponent != 0)
  31963. parentComponent->removeChildComponent (parentComponent->childComponentList.indexOf (this), true, false);
  31964. else if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  31965. giveAwayFocus (currentlyFocusedComponent != this);
  31966. if (flags.hasHeavyweightPeerFlag)
  31967. removeFromDesktop();
  31968. // Something has added some children to this component during its destructor! Not a smart idea!
  31969. jassert (childComponentList.size() == 0);
  31970. }
  31971. const WeakReference<Component>::SharedRef& Component::getWeakReference()
  31972. {
  31973. return weakReferenceMaster (this);
  31974. }
  31975. void Component::setName (const String& name)
  31976. {
  31977. // if component methods are being called from threads other than the message
  31978. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31979. CHECK_MESSAGE_MANAGER_IS_LOCKED
  31980. if (componentName != name)
  31981. {
  31982. componentName = name;
  31983. if (flags.hasHeavyweightPeerFlag)
  31984. {
  31985. ComponentPeer* const peer = getPeer();
  31986. jassert (peer != 0);
  31987. if (peer != 0)
  31988. peer->setTitle (name);
  31989. }
  31990. BailOutChecker checker (this);
  31991. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  31992. }
  31993. }
  31994. void Component::setComponentID (const String& newID)
  31995. {
  31996. componentID = newID;
  31997. }
  31998. void Component::setVisible (bool shouldBeVisible)
  31999. {
  32000. if (flags.visibleFlag != shouldBeVisible)
  32001. {
  32002. // if component methods are being called from threads other than the message
  32003. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32004. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32005. WeakReference<Component> safePointer (this);
  32006. flags.visibleFlag = shouldBeVisible;
  32007. internalRepaint (0, 0, getWidth(), getHeight());
  32008. sendFakeMouseMove();
  32009. if (! shouldBeVisible)
  32010. {
  32011. if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  32012. {
  32013. if (parentComponent != 0)
  32014. parentComponent->grabKeyboardFocus();
  32015. else
  32016. giveAwayFocus (true);
  32017. }
  32018. }
  32019. if (safePointer != 0)
  32020. {
  32021. sendVisibilityChangeMessage();
  32022. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  32023. {
  32024. ComponentPeer* const peer = getPeer();
  32025. jassert (peer != 0);
  32026. if (peer != 0)
  32027. {
  32028. peer->setVisible (shouldBeVisible);
  32029. internalHierarchyChanged();
  32030. }
  32031. }
  32032. }
  32033. }
  32034. }
  32035. void Component::visibilityChanged()
  32036. {
  32037. }
  32038. void Component::sendVisibilityChangeMessage()
  32039. {
  32040. BailOutChecker checker (this);
  32041. visibilityChanged();
  32042. if (! checker.shouldBailOut())
  32043. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  32044. }
  32045. bool Component::isShowing() const
  32046. {
  32047. if (flags.visibleFlag)
  32048. {
  32049. if (parentComponent != 0)
  32050. {
  32051. return parentComponent->isShowing();
  32052. }
  32053. else
  32054. {
  32055. const ComponentPeer* const peer = getPeer();
  32056. return peer != 0 && ! peer->isMinimised();
  32057. }
  32058. }
  32059. return false;
  32060. }
  32061. void* Component::getWindowHandle() const
  32062. {
  32063. const ComponentPeer* const peer = getPeer();
  32064. if (peer != 0)
  32065. return peer->getNativeHandle();
  32066. return 0;
  32067. }
  32068. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32069. {
  32070. // if component methods are being called from threads other than the message
  32071. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32072. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32073. if (isOpaque())
  32074. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32075. else
  32076. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32077. int currentStyleFlags = 0;
  32078. // don't use getPeer(), so that we only get the peer that's specifically
  32079. // for this comp, and not for one of its parents.
  32080. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32081. if (peer != 0)
  32082. currentStyleFlags = peer->getStyleFlags();
  32083. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32084. {
  32085. WeakReference<Component> safePointer (this);
  32086. #if JUCE_LINUX
  32087. // it's wise to give the component a non-zero size before
  32088. // putting it on the desktop, as X windows get confused by this, and
  32089. // a (1, 1) minimum size is enforced here.
  32090. setSize (jmax (1, getWidth()),
  32091. jmax (1, getHeight()));
  32092. #endif
  32093. const Point<int> topLeft (getScreenPosition());
  32094. bool wasFullscreen = false;
  32095. bool wasMinimised = false;
  32096. ComponentBoundsConstrainer* currentConstainer = 0;
  32097. Rectangle<int> oldNonFullScreenBounds;
  32098. if (peer != 0)
  32099. {
  32100. wasFullscreen = peer->isFullScreen();
  32101. wasMinimised = peer->isMinimised();
  32102. currentConstainer = peer->getConstrainer();
  32103. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32104. removeFromDesktop();
  32105. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32106. }
  32107. if (parentComponent != 0)
  32108. parentComponent->removeChildComponent (this);
  32109. if (safePointer != 0)
  32110. {
  32111. flags.hasHeavyweightPeerFlag = true;
  32112. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32113. Desktop::getInstance().addDesktopComponent (this);
  32114. bounds.setPosition (topLeft);
  32115. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32116. peer->setVisible (isVisible());
  32117. if (wasFullscreen)
  32118. {
  32119. peer->setFullScreen (true);
  32120. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32121. }
  32122. if (wasMinimised)
  32123. peer->setMinimised (true);
  32124. if (isAlwaysOnTop())
  32125. peer->setAlwaysOnTop (true);
  32126. peer->setConstrainer (currentConstainer);
  32127. repaint();
  32128. }
  32129. internalHierarchyChanged();
  32130. }
  32131. }
  32132. void Component::removeFromDesktop()
  32133. {
  32134. // if component methods are being called from threads other than the message
  32135. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32136. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32137. if (flags.hasHeavyweightPeerFlag)
  32138. {
  32139. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32140. flags.hasHeavyweightPeerFlag = false;
  32141. jassert (peer != 0);
  32142. delete peer;
  32143. Desktop::getInstance().removeDesktopComponent (this);
  32144. }
  32145. }
  32146. bool Component::isOnDesktop() const throw()
  32147. {
  32148. return flags.hasHeavyweightPeerFlag;
  32149. }
  32150. void Component::userTriedToCloseWindow()
  32151. {
  32152. /* This means that the user's trying to get rid of your window with the 'close window' system
  32153. menu option (on windows) or possibly the task manager - you should really handle this
  32154. and delete or hide your component in an appropriate way.
  32155. If you want to ignore the event and don't want to trigger this assertion, just override
  32156. this method and do nothing.
  32157. */
  32158. jassertfalse;
  32159. }
  32160. void Component::minimisationStateChanged (bool)
  32161. {
  32162. }
  32163. void Component::setOpaque (const bool shouldBeOpaque)
  32164. {
  32165. if (shouldBeOpaque != flags.opaqueFlag)
  32166. {
  32167. flags.opaqueFlag = shouldBeOpaque;
  32168. if (flags.hasHeavyweightPeerFlag)
  32169. {
  32170. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32171. if (peer != 0)
  32172. {
  32173. // to make it recreate the heavyweight window
  32174. addToDesktop (peer->getStyleFlags());
  32175. }
  32176. }
  32177. repaint();
  32178. }
  32179. }
  32180. bool Component::isOpaque() const throw()
  32181. {
  32182. return flags.opaqueFlag;
  32183. }
  32184. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32185. {
  32186. if (shouldBeBuffered != flags.bufferToImageFlag)
  32187. {
  32188. bufferedImage = Image::null;
  32189. flags.bufferToImageFlag = shouldBeBuffered;
  32190. }
  32191. }
  32192. void Component::moveChildInternal (const int sourceIndex, const int destIndex)
  32193. {
  32194. if (sourceIndex != destIndex)
  32195. {
  32196. Component* const c = childComponentList.getUnchecked (sourceIndex);
  32197. jassert (c != 0);
  32198. c->repaintParent();
  32199. childComponentList.move (sourceIndex, destIndex);
  32200. sendFakeMouseMove();
  32201. internalChildrenChanged();
  32202. }
  32203. }
  32204. void Component::toFront (const bool setAsForeground)
  32205. {
  32206. // if component methods are being called from threads other than the message
  32207. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32208. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32209. if (flags.hasHeavyweightPeerFlag)
  32210. {
  32211. ComponentPeer* const peer = getPeer();
  32212. if (peer != 0)
  32213. {
  32214. peer->toFront (setAsForeground);
  32215. if (setAsForeground && ! hasKeyboardFocus (true))
  32216. grabKeyboardFocus();
  32217. }
  32218. }
  32219. else if (parentComponent != 0)
  32220. {
  32221. const Array<Component*>& childList = parentComponent->childComponentList;
  32222. if (childList.getLast() != this)
  32223. {
  32224. const int index = childList.indexOf (this);
  32225. if (index >= 0)
  32226. {
  32227. int insertIndex = -1;
  32228. if (! flags.alwaysOnTopFlag)
  32229. {
  32230. insertIndex = childList.size() - 1;
  32231. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32232. --insertIndex;
  32233. }
  32234. parentComponent->moveChildInternal (index, insertIndex);
  32235. }
  32236. }
  32237. if (setAsForeground)
  32238. {
  32239. internalBroughtToFront();
  32240. grabKeyboardFocus();
  32241. }
  32242. }
  32243. }
  32244. void Component::toBehind (Component* const other)
  32245. {
  32246. if (other != 0 && other != this)
  32247. {
  32248. // the two components must belong to the same parent..
  32249. jassert (parentComponent == other->parentComponent);
  32250. if (parentComponent != 0)
  32251. {
  32252. const Array<Component*>& childList = parentComponent->childComponentList;
  32253. const int index = childList.indexOf (this);
  32254. if (index >= 0 && childList [index + 1] != other)
  32255. {
  32256. int otherIndex = childList.indexOf (other);
  32257. if (otherIndex >= 0)
  32258. {
  32259. if (index < otherIndex)
  32260. --otherIndex;
  32261. parentComponent->moveChildInternal (index, otherIndex);
  32262. }
  32263. }
  32264. }
  32265. else if (isOnDesktop())
  32266. {
  32267. jassert (other->isOnDesktop());
  32268. if (other->isOnDesktop())
  32269. {
  32270. ComponentPeer* const us = getPeer();
  32271. ComponentPeer* const them = other->getPeer();
  32272. jassert (us != 0 && them != 0);
  32273. if (us != 0 && them != 0)
  32274. us->toBehind (them);
  32275. }
  32276. }
  32277. }
  32278. }
  32279. void Component::toBack()
  32280. {
  32281. if (isOnDesktop())
  32282. {
  32283. jassertfalse; //xxx need to add this to native window
  32284. }
  32285. else if (parentComponent != 0)
  32286. {
  32287. const Array<Component*>& childList = parentComponent->childComponentList;
  32288. if (childList.getFirst() != this)
  32289. {
  32290. const int index = childList.indexOf (this);
  32291. if (index > 0)
  32292. {
  32293. int insertIndex = 0;
  32294. if (flags.alwaysOnTopFlag)
  32295. while (insertIndex < childList.size() && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32296. ++insertIndex;
  32297. parentComponent->moveChildInternal (index, insertIndex);
  32298. }
  32299. }
  32300. }
  32301. }
  32302. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32303. {
  32304. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32305. {
  32306. flags.alwaysOnTopFlag = shouldStayOnTop;
  32307. if (isOnDesktop())
  32308. {
  32309. ComponentPeer* const peer = getPeer();
  32310. jassert (peer != 0);
  32311. if (peer != 0)
  32312. {
  32313. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32314. {
  32315. // some kinds of peer can't change their always-on-top status, so
  32316. // for these, we'll need to create a new window
  32317. const int oldFlags = peer->getStyleFlags();
  32318. removeFromDesktop();
  32319. addToDesktop (oldFlags);
  32320. }
  32321. }
  32322. }
  32323. if (shouldStayOnTop)
  32324. toFront (false);
  32325. internalHierarchyChanged();
  32326. }
  32327. }
  32328. bool Component::isAlwaysOnTop() const throw()
  32329. {
  32330. return flags.alwaysOnTopFlag;
  32331. }
  32332. int Component::proportionOfWidth (const float proportion) const throw()
  32333. {
  32334. return roundToInt (proportion * bounds.getWidth());
  32335. }
  32336. int Component::proportionOfHeight (const float proportion) const throw()
  32337. {
  32338. return roundToInt (proportion * bounds.getHeight());
  32339. }
  32340. int Component::getParentWidth() const throw()
  32341. {
  32342. return (parentComponent != 0) ? parentComponent->getWidth()
  32343. : getParentMonitorArea().getWidth();
  32344. }
  32345. int Component::getParentHeight() const throw()
  32346. {
  32347. return (parentComponent != 0) ? parentComponent->getHeight()
  32348. : getParentMonitorArea().getHeight();
  32349. }
  32350. int Component::getScreenX() const { return getScreenPosition().getX(); }
  32351. int Component::getScreenY() const { return getScreenPosition().getY(); }
  32352. const Point<int> Component::getScreenPosition() const { return localPointToGlobal (Point<int>()); }
  32353. const Rectangle<int> Component::getScreenBounds() const { return localAreaToGlobal (getLocalBounds()); }
  32354. const Point<int> Component::getLocalPoint (const Component* source, const Point<int>& point) const
  32355. {
  32356. return ComponentHelpers::convertCoordinate (this, source, point);
  32357. }
  32358. const Rectangle<int> Component::getLocalArea (const Component* source, const Rectangle<int>& area) const
  32359. {
  32360. return ComponentHelpers::convertCoordinate (this, source, area);
  32361. }
  32362. const Point<int> Component::localPointToGlobal (const Point<int>& point) const
  32363. {
  32364. return ComponentHelpers::convertCoordinate (0, this, point);
  32365. }
  32366. const Rectangle<int> Component::localAreaToGlobal (const Rectangle<int>& area) const
  32367. {
  32368. return ComponentHelpers::convertCoordinate (0, this, area);
  32369. }
  32370. /* Deprecated methods... */
  32371. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32372. {
  32373. return localPointToGlobal (relativePosition);
  32374. }
  32375. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32376. {
  32377. return getLocalPoint (0, screenPosition);
  32378. }
  32379. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32380. {
  32381. return targetComponent == 0 ? localPointToGlobal (positionRelativeToThis)
  32382. : targetComponent->getLocalPoint (this, positionRelativeToThis);
  32383. }
  32384. void Component::setBounds (const int x, const int y, int w, int h)
  32385. {
  32386. // if component methods are being called from threads other than the message
  32387. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32388. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32389. if (w < 0) w = 0;
  32390. if (h < 0) h = 0;
  32391. const bool wasResized = (getWidth() != w || getHeight() != h);
  32392. const bool wasMoved = (getX() != x || getY() != y);
  32393. #if JUCE_DEBUG
  32394. // It's a very bad idea to try to resize a window during its paint() method!
  32395. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32396. #endif
  32397. if (wasMoved || wasResized)
  32398. {
  32399. const bool showing = isShowing();
  32400. if (showing)
  32401. {
  32402. // send a fake mouse move to trigger enter/exit messages if needed..
  32403. sendFakeMouseMove();
  32404. if (! flags.hasHeavyweightPeerFlag)
  32405. repaintParent();
  32406. }
  32407. bounds.setBounds (x, y, w, h);
  32408. if (showing)
  32409. {
  32410. if (wasResized)
  32411. repaint();
  32412. else if (! flags.hasHeavyweightPeerFlag)
  32413. repaintParent();
  32414. }
  32415. if (flags.hasHeavyweightPeerFlag)
  32416. {
  32417. ComponentPeer* const peer = getPeer();
  32418. if (peer != 0)
  32419. {
  32420. if (wasMoved && wasResized)
  32421. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32422. else if (wasMoved)
  32423. peer->setPosition (getX(), getY());
  32424. else if (wasResized)
  32425. peer->setSize (getWidth(), getHeight());
  32426. }
  32427. }
  32428. sendMovedResizedMessages (wasMoved, wasResized);
  32429. }
  32430. }
  32431. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32432. {
  32433. BailOutChecker checker (this);
  32434. if (wasMoved)
  32435. {
  32436. moved();
  32437. if (checker.shouldBailOut())
  32438. return;
  32439. }
  32440. if (wasResized)
  32441. {
  32442. resized();
  32443. if (checker.shouldBailOut())
  32444. return;
  32445. for (int i = childComponentList.size(); --i >= 0;)
  32446. {
  32447. childComponentList.getUnchecked(i)->parentSizeChanged();
  32448. if (checker.shouldBailOut())
  32449. return;
  32450. i = jmin (i, childComponentList.size());
  32451. }
  32452. }
  32453. if (parentComponent != 0)
  32454. parentComponent->childBoundsChanged (this);
  32455. if (! checker.shouldBailOut())
  32456. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32457. *this, wasMoved, wasResized);
  32458. }
  32459. void Component::setSize (const int w, const int h)
  32460. {
  32461. setBounds (getX(), getY(), w, h);
  32462. }
  32463. void Component::setTopLeftPosition (const int x, const int y)
  32464. {
  32465. setBounds (x, y, getWidth(), getHeight());
  32466. }
  32467. void Component::setTopRightPosition (const int x, const int y)
  32468. {
  32469. setTopLeftPosition (x - getWidth(), y);
  32470. }
  32471. void Component::setBounds (const Rectangle<int>& r)
  32472. {
  32473. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  32474. }
  32475. void Component::setBounds (const RelativeRectangle& newBounds)
  32476. {
  32477. newBounds.applyToComponent (*this);
  32478. }
  32479. void Component::setBoundsRelative (const float x, const float y,
  32480. const float w, const float h)
  32481. {
  32482. const int pw = getParentWidth();
  32483. const int ph = getParentHeight();
  32484. setBounds (roundToInt (x * pw),
  32485. roundToInt (y * ph),
  32486. roundToInt (w * pw),
  32487. roundToInt (h * ph));
  32488. }
  32489. void Component::setCentrePosition (const int x, const int y)
  32490. {
  32491. setTopLeftPosition (x - getWidth() / 2,
  32492. y - getHeight() / 2);
  32493. }
  32494. void Component::setCentreRelative (const float x, const float y)
  32495. {
  32496. setCentrePosition (roundToInt (getParentWidth() * x),
  32497. roundToInt (getParentHeight() * y));
  32498. }
  32499. void Component::centreWithSize (const int width, const int height)
  32500. {
  32501. const Rectangle<int> parentArea (ComponentHelpers::getParentOrMainMonitorBounds (*this));
  32502. setBounds (parentArea.getCentreX() - width / 2,
  32503. parentArea.getCentreY() - height / 2,
  32504. width, height);
  32505. }
  32506. void Component::setBoundsInset (const BorderSize<int>& borders)
  32507. {
  32508. setBounds (borders.subtractedFrom (ComponentHelpers::getParentOrMainMonitorBounds (*this)));
  32509. }
  32510. void Component::setBoundsToFit (int x, int y, int width, int height,
  32511. const Justification& justification,
  32512. const bool onlyReduceInSize)
  32513. {
  32514. // it's no good calling this method unless both the component and
  32515. // target rectangle have a finite size.
  32516. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32517. if (getWidth() > 0 && getHeight() > 0
  32518. && width > 0 && height > 0)
  32519. {
  32520. int newW, newH;
  32521. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32522. {
  32523. newW = getWidth();
  32524. newH = getHeight();
  32525. }
  32526. else
  32527. {
  32528. const double imageRatio = getHeight() / (double) getWidth();
  32529. const double targetRatio = height / (double) width;
  32530. if (imageRatio <= targetRatio)
  32531. {
  32532. newW = width;
  32533. newH = jmin (height, roundToInt (newW * imageRatio));
  32534. }
  32535. else
  32536. {
  32537. newH = height;
  32538. newW = jmin (width, roundToInt (newH / imageRatio));
  32539. }
  32540. }
  32541. if (newW > 0 && newH > 0)
  32542. setBounds (justification.appliedToRectangle (Rectangle<int> (0, 0, newW, newH),
  32543. Rectangle<int> (x, y, width, height)));
  32544. }
  32545. }
  32546. bool Component::isTransformed() const throw()
  32547. {
  32548. return affineTransform != 0;
  32549. }
  32550. void Component::setTransform (const AffineTransform& newTransform)
  32551. {
  32552. // If you pass in a transform with no inverse, the component will have no dimensions,
  32553. // and there will be all sorts of maths errors when converting coordinates.
  32554. jassert (! newTransform.isSingularity());
  32555. if (newTransform.isIdentity())
  32556. {
  32557. if (affineTransform != 0)
  32558. {
  32559. repaint();
  32560. affineTransform = 0;
  32561. repaint();
  32562. sendMovedResizedMessages (false, false);
  32563. }
  32564. }
  32565. else if (affineTransform == 0)
  32566. {
  32567. repaint();
  32568. affineTransform = new AffineTransform (newTransform);
  32569. repaint();
  32570. sendMovedResizedMessages (false, false);
  32571. }
  32572. else if (*affineTransform != newTransform)
  32573. {
  32574. repaint();
  32575. *affineTransform = newTransform;
  32576. repaint();
  32577. sendMovedResizedMessages (false, false);
  32578. }
  32579. }
  32580. const AffineTransform Component::getTransform() const
  32581. {
  32582. return affineTransform != 0 ? *affineTransform : AffineTransform::identity;
  32583. }
  32584. bool Component::hitTest (int x, int y)
  32585. {
  32586. if (! flags.ignoresMouseClicksFlag)
  32587. return true;
  32588. if (flags.allowChildMouseClicksFlag)
  32589. {
  32590. for (int i = getNumChildComponents(); --i >= 0;)
  32591. {
  32592. Component& child = *getChildComponent (i);
  32593. if (child.isVisible()
  32594. && ComponentHelpers::hitTest (child, ComponentHelpers::convertFromParentSpace (child, Point<int> (x, y))))
  32595. return true;
  32596. }
  32597. }
  32598. return false;
  32599. }
  32600. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32601. const bool allowClicksOnChildComponents) throw()
  32602. {
  32603. flags.ignoresMouseClicksFlag = ! allowClicks;
  32604. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32605. }
  32606. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32607. bool& allowsClicksOnChildComponents) const throw()
  32608. {
  32609. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32610. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32611. }
  32612. bool Component::contains (const Point<int>& point)
  32613. {
  32614. if (ComponentHelpers::hitTest (*this, point))
  32615. {
  32616. if (parentComponent != 0)
  32617. {
  32618. return parentComponent->contains (ComponentHelpers::convertToParentSpace (*this, point));
  32619. }
  32620. else if (flags.hasHeavyweightPeerFlag)
  32621. {
  32622. const ComponentPeer* const peer = getPeer();
  32623. if (peer != 0)
  32624. return peer->contains (point, true);
  32625. }
  32626. }
  32627. return false;
  32628. }
  32629. bool Component::reallyContains (const Point<int>& point, const bool returnTrueIfWithinAChild)
  32630. {
  32631. if (! contains (point))
  32632. return false;
  32633. Component* const top = getTopLevelComponent();
  32634. const Component* const compAtPosition = top->getComponentAt (top->getLocalPoint (this, point));
  32635. return (compAtPosition == this) || (returnTrueIfWithinAChild && isParentOf (compAtPosition));
  32636. }
  32637. Component* Component::getComponentAt (const Point<int>& position)
  32638. {
  32639. if (flags.visibleFlag && ComponentHelpers::hitTest (*this, position))
  32640. {
  32641. for (int i = childComponentList.size(); --i >= 0;)
  32642. {
  32643. Component* child = childComponentList.getUnchecked(i);
  32644. child = child->getComponentAt (ComponentHelpers::convertFromParentSpace (*child, position));
  32645. if (child != 0)
  32646. return child;
  32647. }
  32648. return this;
  32649. }
  32650. return 0;
  32651. }
  32652. Component* Component::getComponentAt (const int x, const int y)
  32653. {
  32654. return getComponentAt (Point<int> (x, y));
  32655. }
  32656. void Component::addChildComponent (Component* const child, int zOrder)
  32657. {
  32658. // if component methods are being called from threads other than the message
  32659. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32660. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32661. if (child != 0 && child->parentComponent != this)
  32662. {
  32663. if (child->parentComponent != 0)
  32664. child->parentComponent->removeChildComponent (child);
  32665. else
  32666. child->removeFromDesktop();
  32667. child->parentComponent = this;
  32668. if (child->isVisible())
  32669. child->repaintParent();
  32670. if (! child->isAlwaysOnTop())
  32671. {
  32672. if (zOrder < 0 || zOrder > childComponentList.size())
  32673. zOrder = childComponentList.size();
  32674. while (zOrder > 0)
  32675. {
  32676. if (! childComponentList.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  32677. break;
  32678. --zOrder;
  32679. }
  32680. }
  32681. childComponentList.insert (zOrder, child);
  32682. child->internalHierarchyChanged();
  32683. internalChildrenChanged();
  32684. }
  32685. }
  32686. void Component::addAndMakeVisible (Component* const child, int zOrder)
  32687. {
  32688. if (child != 0)
  32689. {
  32690. child->setVisible (true);
  32691. addChildComponent (child, zOrder);
  32692. }
  32693. }
  32694. void Component::removeChildComponent (Component* const child)
  32695. {
  32696. removeChildComponent (childComponentList.indexOf (child), true, true);
  32697. }
  32698. Component* Component::removeChildComponent (const int index)
  32699. {
  32700. return removeChildComponent (index, true, true);
  32701. }
  32702. Component* Component::removeChildComponent (const int index, bool sendParentEvents, const bool sendChildEvents)
  32703. {
  32704. // if component methods are being called from threads other than the message
  32705. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32706. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32707. Component* const child = childComponentList [index];
  32708. if (child != 0)
  32709. {
  32710. sendParentEvents = sendParentEvents && child->isShowing();
  32711. if (sendParentEvents)
  32712. {
  32713. sendFakeMouseMove();
  32714. child->repaintParent();
  32715. }
  32716. childComponentList.remove (index);
  32717. child->parentComponent = 0;
  32718. // (NB: there are obscure situations where child->isShowing() = false, but it still has the focus)
  32719. if (currentlyFocusedComponent == child || child->isParentOf (currentlyFocusedComponent))
  32720. {
  32721. if (sendParentEvents)
  32722. {
  32723. const WeakReference<Component> thisPointer (this);
  32724. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  32725. if (thisPointer == 0)
  32726. return child;
  32727. grabKeyboardFocus();
  32728. }
  32729. else
  32730. {
  32731. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  32732. }
  32733. }
  32734. if (sendChildEvents)
  32735. child->internalHierarchyChanged();
  32736. if (sendParentEvents)
  32737. internalChildrenChanged();
  32738. }
  32739. return child;
  32740. }
  32741. void Component::removeAllChildren()
  32742. {
  32743. while (childComponentList.size() > 0)
  32744. removeChildComponent (childComponentList.size() - 1);
  32745. }
  32746. void Component::deleteAllChildren()
  32747. {
  32748. while (childComponentList.size() > 0)
  32749. delete (removeChildComponent (childComponentList.size() - 1));
  32750. }
  32751. int Component::getNumChildComponents() const throw()
  32752. {
  32753. return childComponentList.size();
  32754. }
  32755. Component* Component::getChildComponent (const int index) const throw()
  32756. {
  32757. return childComponentList [index];
  32758. }
  32759. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32760. {
  32761. return childComponentList.indexOf (const_cast <Component*> (child));
  32762. }
  32763. Component* Component::getTopLevelComponent() const throw()
  32764. {
  32765. const Component* comp = this;
  32766. while (comp->parentComponent != 0)
  32767. comp = comp->parentComponent;
  32768. return const_cast <Component*> (comp);
  32769. }
  32770. bool Component::isParentOf (const Component* possibleChild) const throw()
  32771. {
  32772. while (possibleChild != 0)
  32773. {
  32774. possibleChild = possibleChild->parentComponent;
  32775. if (possibleChild == this)
  32776. return true;
  32777. }
  32778. return false;
  32779. }
  32780. void Component::parentHierarchyChanged()
  32781. {
  32782. }
  32783. void Component::childrenChanged()
  32784. {
  32785. }
  32786. void Component::internalChildrenChanged()
  32787. {
  32788. if (componentListeners.isEmpty())
  32789. {
  32790. childrenChanged();
  32791. }
  32792. else
  32793. {
  32794. BailOutChecker checker (this);
  32795. childrenChanged();
  32796. if (! checker.shouldBailOut())
  32797. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32798. }
  32799. }
  32800. void Component::internalHierarchyChanged()
  32801. {
  32802. BailOutChecker checker (this);
  32803. parentHierarchyChanged();
  32804. if (checker.shouldBailOut())
  32805. return;
  32806. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32807. if (checker.shouldBailOut())
  32808. return;
  32809. for (int i = childComponentList.size(); --i >= 0;)
  32810. {
  32811. childComponentList.getUnchecked (i)->internalHierarchyChanged();
  32812. if (checker.shouldBailOut())
  32813. {
  32814. // you really shouldn't delete the parent component during a callback telling you
  32815. // that it's changed..
  32816. jassertfalse;
  32817. return;
  32818. }
  32819. i = jmin (i, childComponentList.size());
  32820. }
  32821. }
  32822. int Component::runModalLoop()
  32823. {
  32824. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32825. {
  32826. // use a callback so this can be called from non-gui threads
  32827. return (int) (pointer_sized_int) MessageManager::getInstance()
  32828. ->callFunctionOnMessageThread (&ComponentHelpers::runModalLoopCallback, this);
  32829. }
  32830. if (! isCurrentlyModal())
  32831. enterModalState (true);
  32832. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32833. }
  32834. void Component::enterModalState (const bool shouldTakeKeyboardFocus, ModalComponentManager::Callback* const callback)
  32835. {
  32836. // if component methods are being called from threads other than the message
  32837. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32838. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32839. // Check for an attempt to make a component modal when it already is!
  32840. // This can cause nasty problems..
  32841. jassert (! flags.currentlyModalFlag);
  32842. if (! isCurrentlyModal())
  32843. {
  32844. ModalComponentManager::getInstance()->startModal (this, callback);
  32845. flags.currentlyModalFlag = true;
  32846. setVisible (true);
  32847. if (shouldTakeKeyboardFocus)
  32848. grabKeyboardFocus();
  32849. }
  32850. }
  32851. void Component::exitModalState (const int returnValue)
  32852. {
  32853. if (flags.currentlyModalFlag)
  32854. {
  32855. if (MessageManager::getInstance()->isThisTheMessageThread())
  32856. {
  32857. ModalComponentManager::getInstance()->endModal (this, returnValue);
  32858. flags.currentlyModalFlag = false;
  32859. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  32860. }
  32861. else
  32862. {
  32863. class ExitModalStateMessage : public CallbackMessage
  32864. {
  32865. public:
  32866. ExitModalStateMessage (Component* const target_, const int result_)
  32867. : target (target_), result (result_) {}
  32868. void messageCallback()
  32869. {
  32870. if (target.get() != 0) // (get() required for VS2003 bug)
  32871. target->exitModalState (result);
  32872. }
  32873. private:
  32874. WeakReference<Component> target;
  32875. int result;
  32876. };
  32877. (new ExitModalStateMessage (this, returnValue))->post();
  32878. }
  32879. }
  32880. }
  32881. bool Component::isCurrentlyModal() const throw()
  32882. {
  32883. return flags.currentlyModalFlag
  32884. && getCurrentlyModalComponent() == this;
  32885. }
  32886. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  32887. {
  32888. Component* const mc = getCurrentlyModalComponent();
  32889. return mc != 0
  32890. && mc != this
  32891. && (! mc->isParentOf (this))
  32892. && ! mc->canModalEventBeSentToComponent (this);
  32893. }
  32894. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  32895. {
  32896. return ModalComponentManager::getInstance()->getNumModalComponents();
  32897. }
  32898. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  32899. {
  32900. return ModalComponentManager::getInstance()->getModalComponent (index);
  32901. }
  32902. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  32903. {
  32904. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  32905. }
  32906. bool Component::isBroughtToFrontOnMouseClick() const throw()
  32907. {
  32908. return flags.bringToFrontOnClickFlag;
  32909. }
  32910. void Component::setMouseCursor (const MouseCursor& newCursor)
  32911. {
  32912. if (cursor != newCursor)
  32913. {
  32914. cursor = newCursor;
  32915. if (flags.visibleFlag)
  32916. updateMouseCursor();
  32917. }
  32918. }
  32919. const MouseCursor Component::getMouseCursor()
  32920. {
  32921. return cursor;
  32922. }
  32923. void Component::updateMouseCursor() const
  32924. {
  32925. sendFakeMouseMove();
  32926. }
  32927. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  32928. {
  32929. flags.repaintOnMouseActivityFlag = shouldRepaint;
  32930. }
  32931. void Component::setAlpha (const float newAlpha)
  32932. {
  32933. const uint8 newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0)));
  32934. if (componentTransparency != newIntAlpha)
  32935. {
  32936. componentTransparency = newIntAlpha;
  32937. if (flags.hasHeavyweightPeerFlag)
  32938. {
  32939. ComponentPeer* const peer = getPeer();
  32940. if (peer != 0)
  32941. peer->setAlpha (newAlpha);
  32942. }
  32943. else
  32944. {
  32945. repaint();
  32946. }
  32947. }
  32948. }
  32949. float Component::getAlpha() const
  32950. {
  32951. return (255 - componentTransparency) / 255.0f;
  32952. }
  32953. void Component::repaintParent()
  32954. {
  32955. if (flags.visibleFlag)
  32956. internalRepaint (0, 0, getWidth(), getHeight());
  32957. }
  32958. void Component::repaint()
  32959. {
  32960. repaint (0, 0, getWidth(), getHeight());
  32961. }
  32962. void Component::repaint (const int x, const int y,
  32963. const int w, const int h)
  32964. {
  32965. bufferedImage = Image::null;
  32966. if (flags.visibleFlag)
  32967. internalRepaint (x, y, w, h);
  32968. }
  32969. void Component::repaint (const Rectangle<int>& area)
  32970. {
  32971. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  32972. }
  32973. void Component::internalRepaint (int x, int y, int w, int h)
  32974. {
  32975. // if component methods are being called from threads other than the message
  32976. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32977. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32978. if (x < 0)
  32979. {
  32980. w += x;
  32981. x = 0;
  32982. }
  32983. if (x + w > getWidth())
  32984. w = getWidth() - x;
  32985. if (w > 0)
  32986. {
  32987. if (y < 0)
  32988. {
  32989. h += y;
  32990. y = 0;
  32991. }
  32992. if (y + h > getHeight())
  32993. h = getHeight() - y;
  32994. if (h > 0)
  32995. {
  32996. if (parentComponent != 0)
  32997. {
  32998. if (parentComponent->flags.visibleFlag)
  32999. {
  33000. if (affineTransform == 0)
  33001. {
  33002. parentComponent->internalRepaint (x + getX(), y + getY(), w, h);
  33003. }
  33004. else
  33005. {
  33006. const Rectangle<int> r (ComponentHelpers::convertToParentSpace (*this, Rectangle<int> (x, y, w, h)));
  33007. parentComponent->internalRepaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  33008. }
  33009. }
  33010. }
  33011. else if (flags.hasHeavyweightPeerFlag)
  33012. {
  33013. ComponentPeer* const peer = getPeer();
  33014. if (peer != 0)
  33015. peer->repaint (Rectangle<int> (x, y, w, h));
  33016. }
  33017. }
  33018. }
  33019. }
  33020. void Component::paintComponent (Graphics& g)
  33021. {
  33022. if (flags.bufferToImageFlag)
  33023. {
  33024. if (bufferedImage.isNull())
  33025. {
  33026. bufferedImage = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33027. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33028. Graphics imG (bufferedImage);
  33029. paint (imG);
  33030. }
  33031. g.setColour (Colours::black.withAlpha (getAlpha()));
  33032. g.drawImageAt (bufferedImage, 0, 0);
  33033. }
  33034. else
  33035. {
  33036. paint (g);
  33037. }
  33038. }
  33039. void Component::paintWithinParentContext (Graphics& g)
  33040. {
  33041. g.setOrigin (getX(), getY());
  33042. paintEntireComponent (g, false);
  33043. }
  33044. void Component::paintComponentAndChildren (Graphics& g)
  33045. {
  33046. const Rectangle<int> clipBounds (g.getClipBounds());
  33047. if (flags.dontClipGraphicsFlag)
  33048. {
  33049. paintComponent (g);
  33050. }
  33051. else
  33052. {
  33053. g.saveState();
  33054. ComponentHelpers::clipObscuredRegions (*this, g, clipBounds, Point<int>());
  33055. if (! g.isClipEmpty())
  33056. paintComponent (g);
  33057. g.restoreState();
  33058. }
  33059. for (int i = 0; i < childComponentList.size(); ++i)
  33060. {
  33061. Component& child = *childComponentList.getUnchecked (i);
  33062. if (child.isVisible())
  33063. {
  33064. if (child.affineTransform != 0)
  33065. {
  33066. g.saveState();
  33067. g.addTransform (*child.affineTransform);
  33068. if ((child.flags.dontClipGraphicsFlag && ! g.isClipEmpty()) || g.reduceClipRegion (child.getBounds()))
  33069. child.paintWithinParentContext (g);
  33070. g.restoreState();
  33071. }
  33072. else if (clipBounds.intersects (child.getBounds()))
  33073. {
  33074. g.saveState();
  33075. if (child.flags.dontClipGraphicsFlag)
  33076. {
  33077. child.paintWithinParentContext (g);
  33078. }
  33079. else if (g.reduceClipRegion (child.getBounds()))
  33080. {
  33081. bool nothingClipped = true;
  33082. for (int j = i + 1; j < childComponentList.size(); ++j)
  33083. {
  33084. const Component& sibling = *childComponentList.getUnchecked (j);
  33085. if (sibling.flags.opaqueFlag && sibling.isVisible() && sibling.affineTransform == 0)
  33086. {
  33087. nothingClipped = false;
  33088. g.excludeClipRegion (sibling.getBounds());
  33089. }
  33090. }
  33091. if (nothingClipped || ! g.isClipEmpty())
  33092. child.paintWithinParentContext (g);
  33093. }
  33094. g.restoreState();
  33095. }
  33096. }
  33097. }
  33098. g.saveState();
  33099. paintOverChildren (g);
  33100. g.restoreState();
  33101. }
  33102. void Component::paintEntireComponent (Graphics& g, const bool ignoreAlphaLevel)
  33103. {
  33104. jassert (! g.isClipEmpty());
  33105. #if JUCE_DEBUG
  33106. flags.isInsidePaintCall = true;
  33107. #endif
  33108. if (effect != 0)
  33109. {
  33110. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33111. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33112. {
  33113. Graphics g2 (effectImage);
  33114. paintComponentAndChildren (g2);
  33115. }
  33116. effect->applyEffect (effectImage, g, ignoreAlphaLevel ? 1.0f : getAlpha());
  33117. }
  33118. else if (componentTransparency > 0 && ! ignoreAlphaLevel)
  33119. {
  33120. if (componentTransparency < 255)
  33121. {
  33122. g.beginTransparencyLayer (getAlpha());
  33123. paintComponentAndChildren (g);
  33124. g.endTransparencyLayer();
  33125. }
  33126. }
  33127. else
  33128. {
  33129. paintComponentAndChildren (g);
  33130. }
  33131. #if JUCE_DEBUG
  33132. flags.isInsidePaintCall = false;
  33133. #endif
  33134. }
  33135. void Component::setPaintingIsUnclipped (const bool shouldPaintWithoutClipping) throw()
  33136. {
  33137. flags.dontClipGraphicsFlag = shouldPaintWithoutClipping;
  33138. }
  33139. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33140. const bool clipImageToComponentBounds)
  33141. {
  33142. Rectangle<int> r (areaToGrab);
  33143. if (clipImageToComponentBounds)
  33144. r = r.getIntersection (getLocalBounds());
  33145. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33146. jmax (1, r.getWidth()),
  33147. jmax (1, r.getHeight()),
  33148. true);
  33149. Graphics imageContext (componentImage);
  33150. imageContext.setOrigin (-r.getX(), -r.getY());
  33151. paintEntireComponent (imageContext, true);
  33152. return componentImage;
  33153. }
  33154. void Component::setComponentEffect (ImageEffectFilter* const newEffect)
  33155. {
  33156. if (effect != newEffect)
  33157. {
  33158. effect = newEffect;
  33159. repaint();
  33160. }
  33161. }
  33162. LookAndFeel& Component::getLookAndFeel() const throw()
  33163. {
  33164. const Component* c = this;
  33165. do
  33166. {
  33167. if (c->lookAndFeel != 0)
  33168. return *(c->lookAndFeel);
  33169. c = c->parentComponent;
  33170. }
  33171. while (c != 0);
  33172. return LookAndFeel::getDefaultLookAndFeel();
  33173. }
  33174. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33175. {
  33176. if (lookAndFeel != newLookAndFeel)
  33177. {
  33178. lookAndFeel = newLookAndFeel;
  33179. sendLookAndFeelChange();
  33180. }
  33181. }
  33182. void Component::lookAndFeelChanged()
  33183. {
  33184. }
  33185. void Component::sendLookAndFeelChange()
  33186. {
  33187. repaint();
  33188. WeakReference<Component> safePointer (this);
  33189. lookAndFeelChanged();
  33190. if (safePointer != 0)
  33191. {
  33192. for (int i = childComponentList.size(); --i >= 0;)
  33193. {
  33194. childComponentList.getUnchecked (i)->sendLookAndFeelChange();
  33195. if (safePointer == 0)
  33196. return;
  33197. i = jmin (i, childComponentList.size());
  33198. }
  33199. }
  33200. }
  33201. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33202. {
  33203. var* const v = properties.getVarPointer (ComponentHelpers::getColourPropertyId (colourId));
  33204. if (v != 0)
  33205. return Colour ((int) *v);
  33206. if (inheritFromParent && parentComponent != 0)
  33207. return parentComponent->findColour (colourId, true);
  33208. return getLookAndFeel().findColour (colourId);
  33209. }
  33210. bool Component::isColourSpecified (const int colourId) const
  33211. {
  33212. return properties.contains (ComponentHelpers::getColourPropertyId (colourId));
  33213. }
  33214. void Component::removeColour (const int colourId)
  33215. {
  33216. if (properties.remove (ComponentHelpers::getColourPropertyId (colourId)))
  33217. colourChanged();
  33218. }
  33219. void Component::setColour (const int colourId, const Colour& colour)
  33220. {
  33221. if (properties.set (ComponentHelpers::getColourPropertyId (colourId), (int) colour.getARGB()))
  33222. colourChanged();
  33223. }
  33224. void Component::copyAllExplicitColoursTo (Component& target) const
  33225. {
  33226. bool changed = false;
  33227. for (int i = properties.size(); --i >= 0;)
  33228. {
  33229. const Identifier name (properties.getName(i));
  33230. if (name.toString().startsWith ("jcclr_"))
  33231. if (target.properties.set (name, properties [name]))
  33232. changed = true;
  33233. }
  33234. if (changed)
  33235. target.colourChanged();
  33236. }
  33237. void Component::colourChanged()
  33238. {
  33239. }
  33240. MarkerList* Component::getMarkers (bool /*xAxis*/)
  33241. {
  33242. return 0;
  33243. }
  33244. Component::Positioner::Positioner (Component& component_) throw()
  33245. : component (component_)
  33246. {
  33247. }
  33248. Component::Positioner* Component::getPositioner() const throw()
  33249. {
  33250. return positioner;
  33251. }
  33252. void Component::setPositioner (Positioner* newPositioner)
  33253. {
  33254. // You can only assign a positioner to the component that it was created for!
  33255. jassert (newPositioner == 0 || this == &(newPositioner->getComponent()));
  33256. positioner = newPositioner;
  33257. }
  33258. const Rectangle<int> Component::getLocalBounds() const throw()
  33259. {
  33260. return Rectangle<int> (getWidth(), getHeight());
  33261. }
  33262. const Rectangle<int> Component::getBoundsInParent() const throw()
  33263. {
  33264. return affineTransform == 0 ? bounds
  33265. : bounds.toFloat().transformed (*affineTransform).getSmallestIntegerContainer();
  33266. }
  33267. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33268. {
  33269. result.clear();
  33270. const Rectangle<int> unclipped (ComponentHelpers::getUnclippedArea (*this));
  33271. if (! unclipped.isEmpty())
  33272. {
  33273. result.add (unclipped);
  33274. if (includeSiblings)
  33275. {
  33276. const Component* const c = getTopLevelComponent();
  33277. ComponentHelpers::subtractObscuredRegions (*c, result, getLocalPoint (c, Point<int>()),
  33278. c->getLocalBounds(), this);
  33279. }
  33280. ComponentHelpers::subtractObscuredRegions (*this, result, Point<int>(), unclipped, 0);
  33281. result.consolidate();
  33282. }
  33283. }
  33284. void Component::mouseEnter (const MouseEvent&)
  33285. {
  33286. // base class does nothing
  33287. }
  33288. void Component::mouseExit (const MouseEvent&)
  33289. {
  33290. // base class does nothing
  33291. }
  33292. void Component::mouseDown (const MouseEvent&)
  33293. {
  33294. // base class does nothing
  33295. }
  33296. void Component::mouseUp (const MouseEvent&)
  33297. {
  33298. // base class does nothing
  33299. }
  33300. void Component::mouseDrag (const MouseEvent&)
  33301. {
  33302. // base class does nothing
  33303. }
  33304. void Component::mouseMove (const MouseEvent&)
  33305. {
  33306. // base class does nothing
  33307. }
  33308. void Component::mouseDoubleClick (const MouseEvent&)
  33309. {
  33310. // base class does nothing
  33311. }
  33312. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33313. {
  33314. // the base class just passes this event up to its parent..
  33315. if (parentComponent != 0)
  33316. parentComponent->mouseWheelMove (e.getEventRelativeTo (parentComponent),
  33317. wheelIncrementX, wheelIncrementY);
  33318. }
  33319. void Component::resized()
  33320. {
  33321. // base class does nothing
  33322. }
  33323. void Component::moved()
  33324. {
  33325. // base class does nothing
  33326. }
  33327. void Component::childBoundsChanged (Component*)
  33328. {
  33329. // base class does nothing
  33330. }
  33331. void Component::parentSizeChanged()
  33332. {
  33333. // base class does nothing
  33334. }
  33335. void Component::addComponentListener (ComponentListener* const newListener)
  33336. {
  33337. // if component methods are being called from threads other than the message
  33338. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33339. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33340. componentListeners.add (newListener);
  33341. }
  33342. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33343. {
  33344. componentListeners.remove (listenerToRemove);
  33345. }
  33346. void Component::inputAttemptWhenModal()
  33347. {
  33348. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33349. getLookAndFeel().playAlertSound();
  33350. }
  33351. bool Component::canModalEventBeSentToComponent (const Component*)
  33352. {
  33353. return false;
  33354. }
  33355. void Component::internalModalInputAttempt()
  33356. {
  33357. Component* const current = getCurrentlyModalComponent();
  33358. if (current != 0)
  33359. current->inputAttemptWhenModal();
  33360. }
  33361. void Component::paint (Graphics&)
  33362. {
  33363. // all painting is done in the subclasses
  33364. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33365. }
  33366. void Component::paintOverChildren (Graphics&)
  33367. {
  33368. // all painting is done in the subclasses
  33369. }
  33370. void Component::postCommandMessage (const int commandId)
  33371. {
  33372. class CustomCommandMessage : public CallbackMessage
  33373. {
  33374. public:
  33375. CustomCommandMessage (Component* const target_, const int commandId_)
  33376. : target (target_), commandId (commandId_) {}
  33377. void messageCallback()
  33378. {
  33379. if (target.get() != 0) // (get() required for VS2003 bug)
  33380. target->handleCommandMessage (commandId);
  33381. }
  33382. private:
  33383. WeakReference<Component> target;
  33384. int commandId;
  33385. };
  33386. (new CustomCommandMessage (this, commandId))->post();
  33387. }
  33388. void Component::handleCommandMessage (int)
  33389. {
  33390. // used by subclasses
  33391. }
  33392. void Component::addMouseListener (MouseListener* const newListener,
  33393. const bool wantsEventsForAllNestedChildComponents)
  33394. {
  33395. // if component methods are being called from threads other than the message
  33396. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33397. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33398. // If you register a component as a mouselistener for itself, it'll receive all the events
  33399. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  33400. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  33401. if (mouseListeners == 0)
  33402. mouseListeners = new MouseListenerList();
  33403. mouseListeners->addListener (newListener, wantsEventsForAllNestedChildComponents);
  33404. }
  33405. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33406. {
  33407. // if component methods are being called from threads other than the message
  33408. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33409. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33410. if (mouseListeners != 0)
  33411. mouseListeners->removeListener (listenerToRemove);
  33412. }
  33413. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33414. {
  33415. if (isCurrentlyBlockedByAnotherModalComponent())
  33416. {
  33417. // if something else is modal, always just show a normal mouse cursor
  33418. source.showMouseCursor (MouseCursor::NormalCursor);
  33419. return;
  33420. }
  33421. if (! flags.mouseInsideFlag)
  33422. {
  33423. flags.mouseInsideFlag = true;
  33424. flags.mouseOverFlag = true;
  33425. flags.mouseDownFlag = false;
  33426. BailOutChecker checker (this);
  33427. if (flags.repaintOnMouseActivityFlag)
  33428. repaint();
  33429. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33430. this, this, time, relativePos, time, 0, false);
  33431. mouseEnter (me);
  33432. if (checker.shouldBailOut())
  33433. return;
  33434. Desktop& desktop = Desktop::getInstance();
  33435. desktop.resetTimer();
  33436. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33437. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseEnter, me);
  33438. }
  33439. }
  33440. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33441. {
  33442. BailOutChecker checker (this);
  33443. if (flags.mouseDownFlag)
  33444. {
  33445. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33446. if (checker.shouldBailOut())
  33447. return;
  33448. }
  33449. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33450. {
  33451. flags.mouseInsideFlag = false;
  33452. flags.mouseOverFlag = false;
  33453. flags.mouseDownFlag = false;
  33454. if (flags.repaintOnMouseActivityFlag)
  33455. repaint();
  33456. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33457. this, this, time, relativePos, time, 0, false);
  33458. mouseExit (me);
  33459. if (checker.shouldBailOut())
  33460. return;
  33461. Desktop& desktop = Desktop::getInstance();
  33462. desktop.resetTimer();
  33463. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33464. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseExit, me);
  33465. }
  33466. }
  33467. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33468. {
  33469. Desktop& desktop = Desktop::getInstance();
  33470. BailOutChecker checker (this);
  33471. if (isCurrentlyBlockedByAnotherModalComponent())
  33472. {
  33473. internalModalInputAttempt();
  33474. if (checker.shouldBailOut())
  33475. return;
  33476. // If processing the input attempt has exited the modal loop, we'll allow the event
  33477. // to be delivered..
  33478. if (isCurrentlyBlockedByAnotherModalComponent())
  33479. {
  33480. // allow blocked mouse-events to go to global listeners..
  33481. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33482. this, this, time, relativePos, time,
  33483. source.getNumberOfMultipleClicks(), false);
  33484. desktop.resetTimer();
  33485. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33486. return;
  33487. }
  33488. }
  33489. {
  33490. Component* c = this;
  33491. while (c != 0)
  33492. {
  33493. if (c->isBroughtToFrontOnMouseClick())
  33494. {
  33495. c->toFront (true);
  33496. if (checker.shouldBailOut())
  33497. return;
  33498. }
  33499. c = c->parentComponent;
  33500. }
  33501. }
  33502. if (! flags.dontFocusOnMouseClickFlag)
  33503. {
  33504. grabFocusInternal (focusChangedByMouseClick);
  33505. if (checker.shouldBailOut())
  33506. return;
  33507. }
  33508. flags.mouseDownFlag = true;
  33509. flags.mouseOverFlag = true;
  33510. if (flags.repaintOnMouseActivityFlag)
  33511. repaint();
  33512. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33513. this, this, time, relativePos, time,
  33514. source.getNumberOfMultipleClicks(), false);
  33515. mouseDown (me);
  33516. if (checker.shouldBailOut())
  33517. return;
  33518. desktop.resetTimer();
  33519. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33520. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDown, me);
  33521. }
  33522. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33523. {
  33524. if (flags.mouseDownFlag)
  33525. {
  33526. flags.mouseDownFlag = false;
  33527. BailOutChecker checker (this);
  33528. if (flags.repaintOnMouseActivityFlag)
  33529. repaint();
  33530. const MouseEvent me (source, relativePos,
  33531. oldModifiers, this, this, time,
  33532. getLocalPoint (0, source.getLastMouseDownPosition()),
  33533. source.getLastMouseDownTime(),
  33534. source.getNumberOfMultipleClicks(),
  33535. source.hasMouseMovedSignificantlySincePressed());
  33536. mouseUp (me);
  33537. if (checker.shouldBailOut())
  33538. return;
  33539. Desktop& desktop = Desktop::getInstance();
  33540. desktop.resetTimer();
  33541. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33542. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseUp, me);
  33543. if (checker.shouldBailOut())
  33544. return;
  33545. // check for double-click
  33546. if (me.getNumberOfClicks() >= 2)
  33547. {
  33548. mouseDoubleClick (me);
  33549. if (checker.shouldBailOut())
  33550. return;
  33551. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33552. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDoubleClick, me);
  33553. }
  33554. }
  33555. }
  33556. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33557. {
  33558. if (flags.mouseDownFlag)
  33559. {
  33560. flags.mouseOverFlag = reallyContains (relativePos, false);
  33561. BailOutChecker checker (this);
  33562. const MouseEvent me (source, relativePos,
  33563. source.getCurrentModifiers(), this, this, time,
  33564. getLocalPoint (0, source.getLastMouseDownPosition()),
  33565. source.getLastMouseDownTime(),
  33566. source.getNumberOfMultipleClicks(),
  33567. source.hasMouseMovedSignificantlySincePressed());
  33568. mouseDrag (me);
  33569. if (checker.shouldBailOut())
  33570. return;
  33571. Desktop& desktop = Desktop::getInstance();
  33572. desktop.resetTimer();
  33573. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33574. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDrag, me);
  33575. }
  33576. }
  33577. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33578. {
  33579. Desktop& desktop = Desktop::getInstance();
  33580. BailOutChecker checker (this);
  33581. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33582. this, this, time, relativePos, time, 0, false);
  33583. if (isCurrentlyBlockedByAnotherModalComponent())
  33584. {
  33585. // allow blocked mouse-events to go to global listeners..
  33586. desktop.sendMouseMove();
  33587. }
  33588. else
  33589. {
  33590. flags.mouseOverFlag = true;
  33591. mouseMove (me);
  33592. if (checker.shouldBailOut())
  33593. return;
  33594. desktop.resetTimer();
  33595. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33596. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseMove, me);
  33597. }
  33598. }
  33599. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33600. const Time& time, const float amountX, const float amountY)
  33601. {
  33602. Desktop& desktop = Desktop::getInstance();
  33603. BailOutChecker checker (this);
  33604. const float wheelIncrementX = amountX / 256.0f;
  33605. const float wheelIncrementY = amountY / 256.0f;
  33606. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33607. this, this, time, relativePos, time, 0, false);
  33608. if (isCurrentlyBlockedByAnotherModalComponent())
  33609. {
  33610. // allow blocked mouse-events to go to global listeners..
  33611. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33612. }
  33613. else
  33614. {
  33615. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33616. if (checker.shouldBailOut())
  33617. return;
  33618. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33619. if (! checker.shouldBailOut())
  33620. MouseListenerList::sendWheelEvent (*this, checker, me, wheelIncrementX, wheelIncrementY);
  33621. }
  33622. }
  33623. void Component::sendFakeMouseMove() const
  33624. {
  33625. MouseInputSource& mainMouse = Desktop::getInstance().getMainMouseSource();
  33626. if (! mainMouse.isDragging())
  33627. mainMouse.triggerFakeMove();
  33628. }
  33629. void Component::beginDragAutoRepeat (const int interval)
  33630. {
  33631. Desktop::getInstance().beginDragAutoRepeat (interval);
  33632. }
  33633. void Component::broughtToFront()
  33634. {
  33635. }
  33636. void Component::internalBroughtToFront()
  33637. {
  33638. if (flags.hasHeavyweightPeerFlag)
  33639. Desktop::getInstance().componentBroughtToFront (this);
  33640. BailOutChecker checker (this);
  33641. broughtToFront();
  33642. if (checker.shouldBailOut())
  33643. return;
  33644. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33645. if (checker.shouldBailOut())
  33646. return;
  33647. // When brought to the front and there's a modal component blocking this one,
  33648. // we need to bring the modal one to the front instead..
  33649. Component* const cm = getCurrentlyModalComponent();
  33650. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33651. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33652. }
  33653. void Component::focusGained (FocusChangeType)
  33654. {
  33655. // base class does nothing
  33656. }
  33657. void Component::internalFocusGain (const FocusChangeType cause)
  33658. {
  33659. internalFocusGain (cause, WeakReference<Component> (this));
  33660. }
  33661. void Component::internalFocusGain (const FocusChangeType cause, const WeakReference<Component>& safePointer)
  33662. {
  33663. focusGained (cause);
  33664. if (safePointer != 0)
  33665. internalChildFocusChange (cause, safePointer);
  33666. }
  33667. void Component::focusLost (FocusChangeType)
  33668. {
  33669. // base class does nothing
  33670. }
  33671. void Component::internalFocusLoss (const FocusChangeType cause)
  33672. {
  33673. WeakReference<Component> safePointer (this);
  33674. focusLost (focusChangedDirectly);
  33675. if (safePointer != 0)
  33676. internalChildFocusChange (cause, safePointer);
  33677. }
  33678. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33679. {
  33680. // base class does nothing
  33681. }
  33682. void Component::internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>& safePointer)
  33683. {
  33684. const bool childIsNowFocused = hasKeyboardFocus (true);
  33685. if (flags.childCompFocusedFlag != childIsNowFocused)
  33686. {
  33687. flags.childCompFocusedFlag = childIsNowFocused;
  33688. focusOfChildComponentChanged (cause);
  33689. if (safePointer == 0)
  33690. return;
  33691. }
  33692. if (parentComponent != 0)
  33693. parentComponent->internalChildFocusChange (cause, WeakReference<Component> (parentComponent));
  33694. }
  33695. bool Component::isEnabled() const throw()
  33696. {
  33697. return (! flags.isDisabledFlag)
  33698. && (parentComponent == 0 || parentComponent->isEnabled());
  33699. }
  33700. void Component::setEnabled (const bool shouldBeEnabled)
  33701. {
  33702. if (flags.isDisabledFlag == shouldBeEnabled)
  33703. {
  33704. flags.isDisabledFlag = ! shouldBeEnabled;
  33705. // if any parent components are disabled, setting our flag won't make a difference,
  33706. // so no need to send a change message
  33707. if (parentComponent == 0 || parentComponent->isEnabled())
  33708. sendEnablementChangeMessage();
  33709. }
  33710. }
  33711. void Component::sendEnablementChangeMessage()
  33712. {
  33713. WeakReference<Component> safePointer (this);
  33714. enablementChanged();
  33715. if (safePointer == 0)
  33716. return;
  33717. for (int i = getNumChildComponents(); --i >= 0;)
  33718. {
  33719. Component* const c = getChildComponent (i);
  33720. if (c != 0)
  33721. {
  33722. c->sendEnablementChangeMessage();
  33723. if (safePointer == 0)
  33724. return;
  33725. }
  33726. }
  33727. }
  33728. void Component::enablementChanged()
  33729. {
  33730. }
  33731. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  33732. {
  33733. flags.wantsFocusFlag = wantsFocus;
  33734. }
  33735. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  33736. {
  33737. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  33738. }
  33739. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  33740. {
  33741. return ! flags.dontFocusOnMouseClickFlag;
  33742. }
  33743. bool Component::getWantsKeyboardFocus() const throw()
  33744. {
  33745. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  33746. }
  33747. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  33748. {
  33749. flags.isFocusContainerFlag = shouldBeFocusContainer;
  33750. }
  33751. bool Component::isFocusContainer() const throw()
  33752. {
  33753. return flags.isFocusContainerFlag;
  33754. }
  33755. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  33756. int Component::getExplicitFocusOrder() const
  33757. {
  33758. return properties [juce_explicitFocusOrderId];
  33759. }
  33760. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  33761. {
  33762. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  33763. }
  33764. KeyboardFocusTraverser* Component::createFocusTraverser()
  33765. {
  33766. if (flags.isFocusContainerFlag || parentComponent == 0)
  33767. return new KeyboardFocusTraverser();
  33768. return parentComponent->createFocusTraverser();
  33769. }
  33770. void Component::takeKeyboardFocus (const FocusChangeType cause)
  33771. {
  33772. // give the focus to this component
  33773. if (currentlyFocusedComponent != this)
  33774. {
  33775. // get the focus onto our desktop window
  33776. ComponentPeer* const peer = getPeer();
  33777. if (peer != 0)
  33778. {
  33779. WeakReference<Component> safePointer (this);
  33780. peer->grabFocus();
  33781. if (peer->isFocused() && currentlyFocusedComponent != this)
  33782. {
  33783. WeakReference<Component> componentLosingFocus (currentlyFocusedComponent);
  33784. currentlyFocusedComponent = this;
  33785. Desktop::getInstance().triggerFocusCallback();
  33786. // call this after setting currentlyFocusedComponent so that the one that's
  33787. // losing it has a chance to see where focus is going
  33788. if (componentLosingFocus != 0)
  33789. componentLosingFocus->internalFocusLoss (cause);
  33790. if (currentlyFocusedComponent == this)
  33791. internalFocusGain (cause, safePointer);
  33792. }
  33793. }
  33794. }
  33795. }
  33796. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  33797. {
  33798. if (isShowing())
  33799. {
  33800. if (flags.wantsFocusFlag && (isEnabled() || parentComponent == 0))
  33801. {
  33802. takeKeyboardFocus (cause);
  33803. }
  33804. else
  33805. {
  33806. if (isParentOf (currentlyFocusedComponent)
  33807. && currentlyFocusedComponent->isShowing())
  33808. {
  33809. // do nothing if the focused component is actually a child of ours..
  33810. }
  33811. else
  33812. {
  33813. // find the default child component..
  33814. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33815. if (traverser != 0)
  33816. {
  33817. Component* const defaultComp = traverser->getDefaultComponent (this);
  33818. traverser = 0;
  33819. if (defaultComp != 0)
  33820. {
  33821. defaultComp->grabFocusInternal (cause, false);
  33822. return;
  33823. }
  33824. }
  33825. if (canTryParent && parentComponent != 0)
  33826. {
  33827. // if no children want it and we're allowed to try our parent comp,
  33828. // then pass up to parent, which will try our siblings.
  33829. parentComponent->grabFocusInternal (cause, true);
  33830. }
  33831. }
  33832. }
  33833. }
  33834. }
  33835. void Component::grabKeyboardFocus()
  33836. {
  33837. // if component methods are being called from threads other than the message
  33838. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33839. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33840. grabFocusInternal (focusChangedDirectly);
  33841. }
  33842. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  33843. {
  33844. // if component methods are being called from threads other than the message
  33845. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33846. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33847. if (parentComponent != 0)
  33848. {
  33849. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33850. if (traverser != 0)
  33851. {
  33852. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  33853. : traverser->getPreviousComponent (this);
  33854. traverser = 0;
  33855. if (nextComp != 0)
  33856. {
  33857. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33858. {
  33859. WeakReference<Component> nextCompPointer (nextComp);
  33860. internalModalInputAttempt();
  33861. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33862. return;
  33863. }
  33864. nextComp->grabFocusInternal (focusChangedByTabKey);
  33865. return;
  33866. }
  33867. }
  33868. parentComponent->moveKeyboardFocusToSibling (moveToNext);
  33869. }
  33870. }
  33871. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  33872. {
  33873. return (currentlyFocusedComponent == this)
  33874. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  33875. }
  33876. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  33877. {
  33878. return currentlyFocusedComponent;
  33879. }
  33880. void Component::giveAwayFocus (const bool sendFocusLossEvent)
  33881. {
  33882. Component* const componentLosingFocus = currentlyFocusedComponent;
  33883. currentlyFocusedComponent = 0;
  33884. if (sendFocusLossEvent && componentLosingFocus != 0)
  33885. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  33886. Desktop::getInstance().triggerFocusCallback();
  33887. }
  33888. bool Component::isMouseOver (const bool includeChildren) const
  33889. {
  33890. if (flags.mouseOverFlag)
  33891. return true;
  33892. if (includeChildren)
  33893. {
  33894. Desktop& desktop = Desktop::getInstance();
  33895. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  33896. {
  33897. Component* const c = desktop.getMouseSource(i)->getComponentUnderMouse();
  33898. if (isParentOf (c) && c->flags.mouseOverFlag) // (mouseOverFlag checked in case it's being dragged outside the comp)
  33899. return true;
  33900. }
  33901. }
  33902. return false;
  33903. }
  33904. bool Component::isMouseButtonDown() const throw() { return flags.mouseDownFlag; }
  33905. bool Component::isMouseOverOrDragging() const throw() { return flags.mouseOverFlag || flags.mouseDownFlag; }
  33906. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  33907. {
  33908. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  33909. }
  33910. const Point<int> Component::getMouseXYRelative() const
  33911. {
  33912. return getLocalPoint (0, Desktop::getMousePosition());
  33913. }
  33914. const Rectangle<int> Component::getParentMonitorArea() const
  33915. {
  33916. return Desktop::getInstance().getMonitorAreaContaining (getScreenBounds().getCentre());
  33917. }
  33918. void Component::addKeyListener (KeyListener* const newListener)
  33919. {
  33920. if (keyListeners == 0)
  33921. keyListeners = new Array <KeyListener*>();
  33922. keyListeners->addIfNotAlreadyThere (newListener);
  33923. }
  33924. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  33925. {
  33926. if (keyListeners != 0)
  33927. keyListeners->removeValue (listenerToRemove);
  33928. }
  33929. bool Component::keyPressed (const KeyPress&)
  33930. {
  33931. return false;
  33932. }
  33933. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  33934. {
  33935. return false;
  33936. }
  33937. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  33938. {
  33939. if (parentComponent != 0)
  33940. parentComponent->modifierKeysChanged (modifiers);
  33941. }
  33942. void Component::internalModifierKeysChanged()
  33943. {
  33944. sendFakeMouseMove();
  33945. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  33946. }
  33947. ComponentPeer* Component::getPeer() const
  33948. {
  33949. if (flags.hasHeavyweightPeerFlag)
  33950. return ComponentPeer::getPeerFor (this);
  33951. else if (parentComponent == 0)
  33952. return 0;
  33953. return parentComponent->getPeer();
  33954. }
  33955. Component::BailOutChecker::BailOutChecker (Component* const component)
  33956. : safePointer (component)
  33957. {
  33958. jassert (component != 0);
  33959. }
  33960. bool Component::BailOutChecker::shouldBailOut() const throw()
  33961. {
  33962. return safePointer == 0;
  33963. }
  33964. END_JUCE_NAMESPACE
  33965. /*** End of inlined file: juce_Component.cpp ***/
  33966. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  33967. BEGIN_JUCE_NAMESPACE
  33968. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  33969. void ComponentListener::componentBroughtToFront (Component&) {}
  33970. void ComponentListener::componentVisibilityChanged (Component&) {}
  33971. void ComponentListener::componentChildrenChanged (Component&) {}
  33972. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  33973. void ComponentListener::componentNameChanged (Component&) {}
  33974. void ComponentListener::componentBeingDeleted (Component&) {}
  33975. END_JUCE_NAMESPACE
  33976. /*** End of inlined file: juce_ComponentListener.cpp ***/
  33977. /*** Start of inlined file: juce_Desktop.cpp ***/
  33978. BEGIN_JUCE_NAMESPACE
  33979. Desktop::Desktop()
  33980. : mouseClickCounter (0),
  33981. kioskModeComponent (0),
  33982. allowedOrientations (allOrientations)
  33983. {
  33984. createMouseInputSources();
  33985. refreshMonitorSizes();
  33986. }
  33987. Desktop::~Desktop()
  33988. {
  33989. jassert (instance == this);
  33990. instance = 0;
  33991. // doh! If you don't delete all your windows before exiting, you're going to
  33992. // be leaking memory!
  33993. jassert (desktopComponents.size() == 0);
  33994. }
  33995. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  33996. {
  33997. if (instance == 0)
  33998. instance = new Desktop();
  33999. return *instance;
  34000. }
  34001. Desktop* Desktop::instance = 0;
  34002. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  34003. const bool clipToWorkArea);
  34004. void Desktop::refreshMonitorSizes()
  34005. {
  34006. Array <Rectangle<int> > oldClipped, oldUnclipped;
  34007. oldClipped.swapWithArray (monitorCoordsClipped);
  34008. oldUnclipped.swapWithArray (monitorCoordsUnclipped);
  34009. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  34010. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  34011. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  34012. if (oldClipped != monitorCoordsClipped
  34013. || oldUnclipped != monitorCoordsUnclipped)
  34014. {
  34015. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  34016. {
  34017. ComponentPeer* const p = ComponentPeer::getPeer (i);
  34018. if (p != 0)
  34019. p->handleScreenSizeChange();
  34020. }
  34021. }
  34022. }
  34023. int Desktop::getNumDisplayMonitors() const throw()
  34024. {
  34025. return monitorCoordsClipped.size();
  34026. }
  34027. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34028. {
  34029. return clippedToWorkArea ? monitorCoordsClipped [index]
  34030. : monitorCoordsUnclipped [index];
  34031. }
  34032. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34033. {
  34034. RectangleList rl;
  34035. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34036. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34037. return rl;
  34038. }
  34039. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34040. {
  34041. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34042. }
  34043. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34044. {
  34045. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34046. double bestDistance = 1.0e10;
  34047. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34048. {
  34049. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34050. if (rect.contains (position))
  34051. return rect;
  34052. const double distance = rect.getCentre().getDistanceFrom (position);
  34053. if (distance < bestDistance)
  34054. {
  34055. bestDistance = distance;
  34056. best = rect;
  34057. }
  34058. }
  34059. return best;
  34060. }
  34061. int Desktop::getNumComponents() const throw()
  34062. {
  34063. return desktopComponents.size();
  34064. }
  34065. Component* Desktop::getComponent (const int index) const throw()
  34066. {
  34067. return desktopComponents [index];
  34068. }
  34069. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34070. {
  34071. for (int i = desktopComponents.size(); --i >= 0;)
  34072. {
  34073. Component* const c = desktopComponents.getUnchecked(i);
  34074. if (c->isVisible())
  34075. {
  34076. const Point<int> relative (c->getLocalPoint (0, screenPosition));
  34077. if (c->contains (relative))
  34078. return c->getComponentAt (relative);
  34079. }
  34080. }
  34081. return 0;
  34082. }
  34083. void Desktop::addDesktopComponent (Component* const c)
  34084. {
  34085. jassert (c != 0);
  34086. jassert (! desktopComponents.contains (c));
  34087. desktopComponents.addIfNotAlreadyThere (c);
  34088. }
  34089. void Desktop::removeDesktopComponent (Component* const c)
  34090. {
  34091. desktopComponents.removeValue (c);
  34092. }
  34093. void Desktop::componentBroughtToFront (Component* const c)
  34094. {
  34095. const int index = desktopComponents.indexOf (c);
  34096. jassert (index >= 0);
  34097. if (index >= 0)
  34098. {
  34099. int newIndex = -1;
  34100. if (! c->isAlwaysOnTop())
  34101. {
  34102. newIndex = desktopComponents.size();
  34103. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34104. --newIndex;
  34105. --newIndex;
  34106. }
  34107. desktopComponents.move (index, newIndex);
  34108. }
  34109. }
  34110. const Point<int> Desktop::getMousePosition()
  34111. {
  34112. return getInstance().getMainMouseSource().getScreenPosition();
  34113. }
  34114. const Point<int> Desktop::getLastMouseDownPosition()
  34115. {
  34116. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34117. }
  34118. int Desktop::getMouseButtonClickCounter()
  34119. {
  34120. return getInstance().mouseClickCounter;
  34121. }
  34122. void Desktop::incrementMouseClickCounter() throw()
  34123. {
  34124. ++mouseClickCounter;
  34125. }
  34126. int Desktop::getNumDraggingMouseSources() const throw()
  34127. {
  34128. int num = 0;
  34129. for (int i = mouseSources.size(); --i >= 0;)
  34130. if (mouseSources.getUnchecked(i)->isDragging())
  34131. ++num;
  34132. return num;
  34133. }
  34134. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34135. {
  34136. int num = 0;
  34137. for (int i = mouseSources.size(); --i >= 0;)
  34138. {
  34139. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34140. if (mi->isDragging())
  34141. {
  34142. if (index == num)
  34143. return mi;
  34144. ++num;
  34145. }
  34146. }
  34147. return 0;
  34148. }
  34149. class MouseDragAutoRepeater : public Timer
  34150. {
  34151. public:
  34152. MouseDragAutoRepeater() {}
  34153. void timerCallback()
  34154. {
  34155. Desktop& desktop = Desktop::getInstance();
  34156. int numMiceDown = 0;
  34157. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  34158. {
  34159. MouseInputSource* const source = desktop.getMouseSource(i);
  34160. if (source->isDragging())
  34161. {
  34162. source->triggerFakeMove();
  34163. ++numMiceDown;
  34164. }
  34165. }
  34166. if (numMiceDown == 0)
  34167. desktop.beginDragAutoRepeat (0);
  34168. }
  34169. private:
  34170. JUCE_DECLARE_NON_COPYABLE (MouseDragAutoRepeater);
  34171. };
  34172. void Desktop::beginDragAutoRepeat (const int interval)
  34173. {
  34174. if (interval > 0)
  34175. {
  34176. if (dragRepeater == 0)
  34177. dragRepeater = new MouseDragAutoRepeater();
  34178. if (dragRepeater->getTimerInterval() != interval)
  34179. dragRepeater->startTimer (interval);
  34180. }
  34181. else
  34182. {
  34183. dragRepeater = 0;
  34184. }
  34185. }
  34186. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34187. {
  34188. focusListeners.add (listener);
  34189. }
  34190. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34191. {
  34192. focusListeners.remove (listener);
  34193. }
  34194. void Desktop::triggerFocusCallback()
  34195. {
  34196. triggerAsyncUpdate();
  34197. }
  34198. void Desktop::handleAsyncUpdate()
  34199. {
  34200. // The component may be deleted during this operation, but we'll use a SafePointer rather than a
  34201. // BailOutChecker so that any remaining listeners will still get a callback (with a null pointer).
  34202. WeakReference<Component> currentFocus (Component::getCurrentlyFocusedComponent());
  34203. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34204. }
  34205. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34206. {
  34207. mouseListeners.add (listener);
  34208. resetTimer();
  34209. }
  34210. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34211. {
  34212. mouseListeners.remove (listener);
  34213. resetTimer();
  34214. }
  34215. void Desktop::timerCallback()
  34216. {
  34217. if (lastFakeMouseMove != getMousePosition())
  34218. sendMouseMove();
  34219. }
  34220. void Desktop::sendMouseMove()
  34221. {
  34222. if (! mouseListeners.isEmpty())
  34223. {
  34224. startTimer (20);
  34225. lastFakeMouseMove = getMousePosition();
  34226. Component* const target = findComponentAt (lastFakeMouseMove);
  34227. if (target != 0)
  34228. {
  34229. Component::BailOutChecker checker (target);
  34230. const Point<int> pos (target->getLocalPoint (0, lastFakeMouseMove));
  34231. const Time now (Time::getCurrentTime());
  34232. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34233. target, target, now, pos, now, 0, false);
  34234. if (me.mods.isAnyMouseButtonDown())
  34235. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34236. else
  34237. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34238. }
  34239. }
  34240. }
  34241. void Desktop::resetTimer()
  34242. {
  34243. if (mouseListeners.size() == 0)
  34244. stopTimer();
  34245. else
  34246. startTimer (100);
  34247. lastFakeMouseMove = getMousePosition();
  34248. }
  34249. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34250. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34251. {
  34252. if (kioskModeComponent != componentToUse)
  34253. {
  34254. // agh! Don't delete or remove a component from the desktop while it's still the kiosk component!
  34255. jassert (kioskModeComponent == 0 || ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34256. if (kioskModeComponent != 0)
  34257. {
  34258. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34259. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34260. }
  34261. kioskModeComponent = componentToUse;
  34262. if (kioskModeComponent != 0)
  34263. {
  34264. // Only components that are already on the desktop can be put into kiosk mode!
  34265. jassert (ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34266. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34267. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34268. }
  34269. }
  34270. }
  34271. void Desktop::setOrientationsEnabled (const int newOrientations)
  34272. {
  34273. // Dodgy set of flags being passed here! Make sure you specify at least one permitted orientation.
  34274. jassert (newOrientations != 0 && (newOrientations & ~allOrientations) == 0);
  34275. allowedOrientations = newOrientations;
  34276. }
  34277. bool Desktop::isOrientationEnabled (const DisplayOrientation orientation) const throw()
  34278. {
  34279. // Make sure you only pass one valid flag in here...
  34280. jassert (orientation == upright || orientation == upsideDown || orientation == rotatedClockwise || orientation == rotatedAntiClockwise);
  34281. return (allowedOrientations & orientation) != 0;
  34282. }
  34283. END_JUCE_NAMESPACE
  34284. /*** End of inlined file: juce_Desktop.cpp ***/
  34285. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34286. BEGIN_JUCE_NAMESPACE
  34287. class ModalComponentManager::ModalItem : public ComponentMovementWatcher
  34288. {
  34289. public:
  34290. ModalItem (Component* const comp, Callback* const callback)
  34291. : ComponentMovementWatcher (comp),
  34292. component (comp), returnValue (0), isActive (true)
  34293. {
  34294. jassert (comp != 0);
  34295. if (callback != 0)
  34296. callbacks.add (callback);
  34297. }
  34298. void componentMovedOrResized (bool, bool) {}
  34299. void componentPeerChanged()
  34300. {
  34301. if (! component->isShowing())
  34302. cancel();
  34303. }
  34304. void componentVisibilityChanged()
  34305. {
  34306. if (! component->isShowing())
  34307. cancel();
  34308. }
  34309. void componentBeingDeleted (Component& comp)
  34310. {
  34311. ComponentMovementWatcher::componentBeingDeleted (comp);
  34312. if (component == &comp || comp.isParentOf (component))
  34313. cancel();
  34314. }
  34315. void cancel()
  34316. {
  34317. if (isActive)
  34318. {
  34319. isActive = false;
  34320. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34321. }
  34322. }
  34323. Component* component;
  34324. OwnedArray<Callback> callbacks;
  34325. int returnValue;
  34326. bool isActive;
  34327. private:
  34328. JUCE_DECLARE_NON_COPYABLE (ModalItem);
  34329. };
  34330. ModalComponentManager::ModalComponentManager()
  34331. {
  34332. }
  34333. ModalComponentManager::~ModalComponentManager()
  34334. {
  34335. clearSingletonInstance();
  34336. }
  34337. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34338. void ModalComponentManager::startModal (Component* component, Callback* callback)
  34339. {
  34340. if (component != 0)
  34341. stack.add (new ModalItem (component, callback));
  34342. }
  34343. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34344. {
  34345. if (callback != 0)
  34346. {
  34347. ScopedPointer<Callback> callbackDeleter (callback);
  34348. for (int i = stack.size(); --i >= 0;)
  34349. {
  34350. ModalItem* const item = stack.getUnchecked(i);
  34351. if (item->component == component)
  34352. {
  34353. item->callbacks.add (callback);
  34354. callbackDeleter.release();
  34355. break;
  34356. }
  34357. }
  34358. }
  34359. }
  34360. void ModalComponentManager::endModal (Component* component)
  34361. {
  34362. for (int i = stack.size(); --i >= 0;)
  34363. {
  34364. ModalItem* const item = stack.getUnchecked(i);
  34365. if (item->component == component)
  34366. item->cancel();
  34367. }
  34368. }
  34369. void ModalComponentManager::endModal (Component* component, int returnValue)
  34370. {
  34371. for (int i = stack.size(); --i >= 0;)
  34372. {
  34373. ModalItem* const item = stack.getUnchecked(i);
  34374. if (item->component == component)
  34375. {
  34376. item->returnValue = returnValue;
  34377. item->cancel();
  34378. }
  34379. }
  34380. }
  34381. int ModalComponentManager::getNumModalComponents() const
  34382. {
  34383. int n = 0;
  34384. for (int i = 0; i < stack.size(); ++i)
  34385. if (stack.getUnchecked(i)->isActive)
  34386. ++n;
  34387. return n;
  34388. }
  34389. Component* ModalComponentManager::getModalComponent (const int index) const
  34390. {
  34391. int n = 0;
  34392. for (int i = stack.size(); --i >= 0;)
  34393. {
  34394. const ModalItem* const item = stack.getUnchecked(i);
  34395. if (item->isActive)
  34396. if (n++ == index)
  34397. return item->component;
  34398. }
  34399. return 0;
  34400. }
  34401. bool ModalComponentManager::isModal (Component* const comp) const
  34402. {
  34403. for (int i = stack.size(); --i >= 0;)
  34404. {
  34405. const ModalItem* const item = stack.getUnchecked(i);
  34406. if (item->isActive && item->component == comp)
  34407. return true;
  34408. }
  34409. return false;
  34410. }
  34411. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34412. {
  34413. return comp == getModalComponent (0);
  34414. }
  34415. void ModalComponentManager::handleAsyncUpdate()
  34416. {
  34417. for (int i = stack.size(); --i >= 0;)
  34418. {
  34419. const ModalItem* const item = stack.getUnchecked(i);
  34420. if (! item->isActive)
  34421. {
  34422. for (int j = item->callbacks.size(); --j >= 0;)
  34423. {
  34424. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34425. if (! stack.contains (item))
  34426. break;
  34427. }
  34428. stack.removeObject (item);
  34429. }
  34430. }
  34431. }
  34432. void ModalComponentManager::bringModalComponentsToFront()
  34433. {
  34434. ComponentPeer* lastOne = 0;
  34435. for (int i = 0; i < getNumModalComponents(); ++i)
  34436. {
  34437. Component* const c = getModalComponent (i);
  34438. if (c == 0)
  34439. break;
  34440. ComponentPeer* peer = c->getPeer();
  34441. if (peer != 0 && peer != lastOne)
  34442. {
  34443. if (lastOne == 0)
  34444. {
  34445. peer->toFront (true);
  34446. peer->grabFocus();
  34447. }
  34448. else
  34449. peer->toBehind (lastOne);
  34450. lastOne = peer;
  34451. }
  34452. }
  34453. }
  34454. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34455. {
  34456. public:
  34457. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34458. ~ReturnValueRetriever() {}
  34459. void modalStateFinished (int returnValue)
  34460. {
  34461. finished = true;
  34462. value = returnValue;
  34463. }
  34464. private:
  34465. int& value;
  34466. bool& finished;
  34467. JUCE_DECLARE_NON_COPYABLE (ReturnValueRetriever);
  34468. };
  34469. int ModalComponentManager::runEventLoopForCurrentComponent()
  34470. {
  34471. // This can only be run from the message thread!
  34472. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34473. Component* currentlyModal = getModalComponent (0);
  34474. if (currentlyModal == 0)
  34475. return 0;
  34476. WeakReference<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34477. int returnValue = 0;
  34478. bool finished = false;
  34479. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34480. JUCE_TRY
  34481. {
  34482. while (! finished)
  34483. {
  34484. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34485. break;
  34486. }
  34487. }
  34488. JUCE_CATCH_EXCEPTION
  34489. if (prevFocused != 0)
  34490. prevFocused->grabKeyboardFocus();
  34491. return returnValue;
  34492. }
  34493. END_JUCE_NAMESPACE
  34494. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34495. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34496. BEGIN_JUCE_NAMESPACE
  34497. ArrowButton::ArrowButton (const String& name,
  34498. float arrowDirectionInRadians,
  34499. const Colour& arrowColour)
  34500. : Button (name),
  34501. colour (arrowColour)
  34502. {
  34503. path.lineTo (0.0f, 1.0f);
  34504. path.lineTo (1.0f, 0.5f);
  34505. path.closeSubPath();
  34506. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34507. 0.5f, 0.5f));
  34508. setComponentEffect (&shadow);
  34509. buttonStateChanged();
  34510. }
  34511. ArrowButton::~ArrowButton()
  34512. {
  34513. }
  34514. void ArrowButton::paintButton (Graphics& g,
  34515. bool /*isMouseOverButton*/,
  34516. bool /*isButtonDown*/)
  34517. {
  34518. g.setColour (colour);
  34519. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34520. (float) offset,
  34521. (float) (getWidth() - 3),
  34522. (float) (getHeight() - 3),
  34523. false));
  34524. }
  34525. void ArrowButton::buttonStateChanged()
  34526. {
  34527. offset = (isDown()) ? 1 : 0;
  34528. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34529. 0.3f, -1, 0);
  34530. }
  34531. END_JUCE_NAMESPACE
  34532. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34533. /*** Start of inlined file: juce_Button.cpp ***/
  34534. BEGIN_JUCE_NAMESPACE
  34535. class Button::RepeatTimer : public Timer
  34536. {
  34537. public:
  34538. RepeatTimer (Button& owner_) : owner (owner_) {}
  34539. void timerCallback() { owner.repeatTimerCallback(); }
  34540. private:
  34541. Button& owner;
  34542. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RepeatTimer);
  34543. };
  34544. Button::Button (const String& name)
  34545. : Component (name),
  34546. text (name),
  34547. buttonPressTime (0),
  34548. lastRepeatTime (0),
  34549. commandManagerToUse (0),
  34550. autoRepeatDelay (-1),
  34551. autoRepeatSpeed (0),
  34552. autoRepeatMinimumDelay (-1),
  34553. radioGroupId (0),
  34554. commandID (0),
  34555. connectedEdgeFlags (0),
  34556. buttonState (buttonNormal),
  34557. lastToggleState (false),
  34558. clickTogglesState (false),
  34559. needsToRelease (false),
  34560. needsRepainting (false),
  34561. isKeyDown (false),
  34562. triggerOnMouseDown (false),
  34563. generateTooltip (false)
  34564. {
  34565. setWantsKeyboardFocus (true);
  34566. isOn.addListener (this);
  34567. }
  34568. Button::~Button()
  34569. {
  34570. isOn.removeListener (this);
  34571. if (commandManagerToUse != 0)
  34572. commandManagerToUse->removeListener (this);
  34573. repeatTimer = 0;
  34574. clearShortcuts();
  34575. }
  34576. void Button::setButtonText (const String& newText)
  34577. {
  34578. if (text != newText)
  34579. {
  34580. text = newText;
  34581. repaint();
  34582. }
  34583. }
  34584. void Button::setTooltip (const String& newTooltip)
  34585. {
  34586. SettableTooltipClient::setTooltip (newTooltip);
  34587. generateTooltip = false;
  34588. }
  34589. const String Button::getTooltip()
  34590. {
  34591. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34592. {
  34593. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34594. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34595. for (int i = 0; i < keyPresses.size(); ++i)
  34596. {
  34597. const String key (keyPresses.getReference(i).getTextDescription());
  34598. tt << " [";
  34599. if (key.length() == 1)
  34600. tt << TRANS("shortcut") << ": '" << key << "']";
  34601. else
  34602. tt << key << ']';
  34603. }
  34604. return tt;
  34605. }
  34606. return SettableTooltipClient::getTooltip();
  34607. }
  34608. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34609. {
  34610. if (connectedEdgeFlags != connectedEdgeFlags_)
  34611. {
  34612. connectedEdgeFlags = connectedEdgeFlags_;
  34613. repaint();
  34614. }
  34615. }
  34616. void Button::setToggleState (const bool shouldBeOn,
  34617. const bool sendChangeNotification)
  34618. {
  34619. if (shouldBeOn != lastToggleState)
  34620. {
  34621. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34622. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34623. lastToggleState = shouldBeOn;
  34624. repaint();
  34625. WeakReference<Component> deletionWatcher (this);
  34626. if (sendChangeNotification)
  34627. {
  34628. sendClickMessage (ModifierKeys());
  34629. if (deletionWatcher == 0)
  34630. return;
  34631. }
  34632. if (lastToggleState)
  34633. {
  34634. turnOffOtherButtonsInGroup (sendChangeNotification);
  34635. if (deletionWatcher == 0)
  34636. return;
  34637. }
  34638. sendStateMessage();
  34639. }
  34640. }
  34641. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34642. {
  34643. clickTogglesState = shouldToggle;
  34644. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34645. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34646. // it is that this button represents, and the button will update its state to reflect this
  34647. // in the applicationCommandListChanged() method.
  34648. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34649. }
  34650. bool Button::getClickingTogglesState() const throw()
  34651. {
  34652. return clickTogglesState;
  34653. }
  34654. void Button::valueChanged (Value& value)
  34655. {
  34656. if (value.refersToSameSourceAs (isOn))
  34657. setToggleState (isOn.getValue(), true);
  34658. }
  34659. void Button::setRadioGroupId (const int newGroupId)
  34660. {
  34661. if (radioGroupId != newGroupId)
  34662. {
  34663. radioGroupId = newGroupId;
  34664. if (lastToggleState)
  34665. turnOffOtherButtonsInGroup (true);
  34666. }
  34667. }
  34668. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34669. {
  34670. Component* const p = getParentComponent();
  34671. if (p != 0 && radioGroupId != 0)
  34672. {
  34673. WeakReference<Component> deletionWatcher (this);
  34674. for (int i = p->getNumChildComponents(); --i >= 0;)
  34675. {
  34676. Component* const c = p->getChildComponent (i);
  34677. if (c != this)
  34678. {
  34679. Button* const b = dynamic_cast <Button*> (c);
  34680. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34681. {
  34682. b->setToggleState (false, sendChangeNotification);
  34683. if (deletionWatcher == 0)
  34684. return;
  34685. }
  34686. }
  34687. }
  34688. }
  34689. }
  34690. void Button::enablementChanged()
  34691. {
  34692. updateState();
  34693. repaint();
  34694. }
  34695. Button::ButtonState Button::updateState()
  34696. {
  34697. return updateState (isMouseOver (true), isMouseButtonDown());
  34698. }
  34699. Button::ButtonState Button::updateState (const bool over, const bool down)
  34700. {
  34701. ButtonState newState = buttonNormal;
  34702. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34703. {
  34704. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34705. newState = buttonDown;
  34706. else if (over)
  34707. newState = buttonOver;
  34708. }
  34709. setState (newState);
  34710. return newState;
  34711. }
  34712. void Button::setState (const ButtonState newState)
  34713. {
  34714. if (buttonState != newState)
  34715. {
  34716. buttonState = newState;
  34717. repaint();
  34718. if (buttonState == buttonDown)
  34719. {
  34720. buttonPressTime = Time::getApproximateMillisecondCounter();
  34721. lastRepeatTime = 0;
  34722. }
  34723. sendStateMessage();
  34724. }
  34725. }
  34726. bool Button::isDown() const throw()
  34727. {
  34728. return buttonState == buttonDown;
  34729. }
  34730. bool Button::isOver() const throw()
  34731. {
  34732. return buttonState != buttonNormal;
  34733. }
  34734. void Button::buttonStateChanged()
  34735. {
  34736. }
  34737. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34738. {
  34739. const uint32 now = Time::getApproximateMillisecondCounter();
  34740. return now > buttonPressTime ? now - buttonPressTime : 0;
  34741. }
  34742. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34743. {
  34744. triggerOnMouseDown = isTriggeredOnMouseDown;
  34745. }
  34746. void Button::clicked()
  34747. {
  34748. }
  34749. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34750. {
  34751. clicked();
  34752. }
  34753. static const int clickMessageId = 0x2f3f4f99;
  34754. void Button::triggerClick()
  34755. {
  34756. postCommandMessage (clickMessageId);
  34757. }
  34758. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34759. {
  34760. if (clickTogglesState)
  34761. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34762. sendClickMessage (modifiers);
  34763. }
  34764. void Button::flashButtonState()
  34765. {
  34766. if (isEnabled())
  34767. {
  34768. needsToRelease = true;
  34769. setState (buttonDown);
  34770. getRepeatTimer().startTimer (100);
  34771. }
  34772. }
  34773. void Button::handleCommandMessage (int commandId)
  34774. {
  34775. if (commandId == clickMessageId)
  34776. {
  34777. if (isEnabled())
  34778. {
  34779. flashButtonState();
  34780. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34781. }
  34782. }
  34783. else
  34784. {
  34785. Component::handleCommandMessage (commandId);
  34786. }
  34787. }
  34788. void Button::addListener (ButtonListener* const newListener)
  34789. {
  34790. buttonListeners.add (newListener);
  34791. }
  34792. void Button::removeListener (ButtonListener* const listener)
  34793. {
  34794. buttonListeners.remove (listener);
  34795. }
  34796. void Button::addButtonListener (ButtonListener* l) { addListener (l); }
  34797. void Button::removeButtonListener (ButtonListener* l) { removeListener (l); }
  34798. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34799. {
  34800. Component::BailOutChecker checker (this);
  34801. if (commandManagerToUse != 0 && commandID != 0)
  34802. {
  34803. ApplicationCommandTarget::InvocationInfo info (commandID);
  34804. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  34805. info.originatingComponent = this;
  34806. commandManagerToUse->invoke (info, true);
  34807. }
  34808. clicked (modifiers);
  34809. if (! checker.shouldBailOut())
  34810. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  34811. }
  34812. void Button::sendStateMessage()
  34813. {
  34814. Component::BailOutChecker checker (this);
  34815. buttonStateChanged();
  34816. if (! checker.shouldBailOut())
  34817. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  34818. }
  34819. void Button::paint (Graphics& g)
  34820. {
  34821. if (needsToRelease && isEnabled())
  34822. {
  34823. needsToRelease = false;
  34824. needsRepainting = true;
  34825. }
  34826. paintButton (g, isOver(), isDown());
  34827. }
  34828. void Button::mouseEnter (const MouseEvent&)
  34829. {
  34830. updateState (true, false);
  34831. }
  34832. void Button::mouseExit (const MouseEvent&)
  34833. {
  34834. updateState (false, false);
  34835. }
  34836. void Button::mouseDown (const MouseEvent& e)
  34837. {
  34838. updateState (true, true);
  34839. if (isDown())
  34840. {
  34841. if (autoRepeatDelay >= 0)
  34842. getRepeatTimer().startTimer (autoRepeatDelay);
  34843. if (triggerOnMouseDown)
  34844. internalClickCallback (e.mods);
  34845. }
  34846. }
  34847. void Button::mouseUp (const MouseEvent& e)
  34848. {
  34849. const bool wasDown = isDown();
  34850. updateState (isMouseOver(), false);
  34851. if (wasDown && isOver() && ! triggerOnMouseDown)
  34852. internalClickCallback (e.mods);
  34853. }
  34854. void Button::mouseDrag (const MouseEvent&)
  34855. {
  34856. const ButtonState oldState = buttonState;
  34857. updateState (isMouseOver(), true);
  34858. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  34859. getRepeatTimer().startTimer (autoRepeatSpeed);
  34860. }
  34861. void Button::focusGained (FocusChangeType)
  34862. {
  34863. updateState();
  34864. repaint();
  34865. }
  34866. void Button::focusLost (FocusChangeType)
  34867. {
  34868. updateState();
  34869. repaint();
  34870. }
  34871. void Button::visibilityChanged()
  34872. {
  34873. needsToRelease = false;
  34874. updateState();
  34875. }
  34876. void Button::parentHierarchyChanged()
  34877. {
  34878. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  34879. if (newKeySource != keySource.get())
  34880. {
  34881. if (keySource != 0)
  34882. keySource->removeKeyListener (this);
  34883. keySource = newKeySource;
  34884. if (keySource != 0)
  34885. keySource->addKeyListener (this);
  34886. }
  34887. }
  34888. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  34889. const int commandID_,
  34890. const bool generateTooltip_)
  34891. {
  34892. commandID = commandID_;
  34893. generateTooltip = generateTooltip_;
  34894. if (commandManagerToUse != commandManagerToUse_)
  34895. {
  34896. if (commandManagerToUse != 0)
  34897. commandManagerToUse->removeListener (this);
  34898. commandManagerToUse = commandManagerToUse_;
  34899. if (commandManagerToUse != 0)
  34900. commandManagerToUse->addListener (this);
  34901. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34902. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34903. // it is that this button represents, and the button will update its state to reflect this
  34904. // in the applicationCommandListChanged() method.
  34905. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34906. }
  34907. if (commandManagerToUse != 0)
  34908. applicationCommandListChanged();
  34909. else
  34910. setEnabled (true);
  34911. }
  34912. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  34913. {
  34914. if (info.commandID == commandID
  34915. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  34916. {
  34917. flashButtonState();
  34918. }
  34919. }
  34920. void Button::applicationCommandListChanged()
  34921. {
  34922. if (commandManagerToUse != 0)
  34923. {
  34924. ApplicationCommandInfo info (0);
  34925. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  34926. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  34927. if (target != 0)
  34928. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  34929. }
  34930. }
  34931. void Button::addShortcut (const KeyPress& key)
  34932. {
  34933. if (key.isValid())
  34934. {
  34935. jassert (! isRegisteredForShortcut (key)); // already registered!
  34936. shortcuts.add (key);
  34937. parentHierarchyChanged();
  34938. }
  34939. }
  34940. void Button::clearShortcuts()
  34941. {
  34942. shortcuts.clear();
  34943. parentHierarchyChanged();
  34944. }
  34945. bool Button::isShortcutPressed() const
  34946. {
  34947. if (! isCurrentlyBlockedByAnotherModalComponent())
  34948. {
  34949. for (int i = shortcuts.size(); --i >= 0;)
  34950. if (shortcuts.getReference(i).isCurrentlyDown())
  34951. return true;
  34952. }
  34953. return false;
  34954. }
  34955. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  34956. {
  34957. for (int i = shortcuts.size(); --i >= 0;)
  34958. if (key == shortcuts.getReference(i))
  34959. return true;
  34960. return false;
  34961. }
  34962. bool Button::keyStateChanged (const bool, Component*)
  34963. {
  34964. if (! isEnabled())
  34965. return false;
  34966. const bool wasDown = isKeyDown;
  34967. isKeyDown = isShortcutPressed();
  34968. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  34969. getRepeatTimer().startTimer (autoRepeatDelay);
  34970. updateState();
  34971. if (isEnabled() && wasDown && ! isKeyDown)
  34972. {
  34973. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34974. // (return immediately - this button may now have been deleted)
  34975. return true;
  34976. }
  34977. return wasDown || isKeyDown;
  34978. }
  34979. bool Button::keyPressed (const KeyPress&, Component*)
  34980. {
  34981. // returning true will avoid forwarding events for keys that we're using as shortcuts
  34982. return isShortcutPressed();
  34983. }
  34984. bool Button::keyPressed (const KeyPress& key)
  34985. {
  34986. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  34987. {
  34988. triggerClick();
  34989. return true;
  34990. }
  34991. return false;
  34992. }
  34993. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  34994. const int repeatMillisecs,
  34995. const int minimumDelayInMillisecs) throw()
  34996. {
  34997. autoRepeatDelay = initialDelayMillisecs;
  34998. autoRepeatSpeed = repeatMillisecs;
  34999. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  35000. }
  35001. void Button::repeatTimerCallback()
  35002. {
  35003. if (needsRepainting)
  35004. {
  35005. getRepeatTimer().stopTimer();
  35006. updateState();
  35007. needsRepainting = false;
  35008. }
  35009. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState() == buttonDown)))
  35010. {
  35011. int repeatSpeed = autoRepeatSpeed;
  35012. if (autoRepeatMinimumDelay >= 0)
  35013. {
  35014. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  35015. timeHeldDown *= timeHeldDown;
  35016. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  35017. }
  35018. repeatSpeed = jmax (1, repeatSpeed);
  35019. const uint32 now = Time::getMillisecondCounter();
  35020. // if we've been blocked from repeating often enough, speed up the repeat timer to compensate..
  35021. if (lastRepeatTime != 0 && (int) (now - lastRepeatTime) > repeatSpeed * 2)
  35022. repeatSpeed = jmax (1, repeatSpeed / 2);
  35023. lastRepeatTime = now;
  35024. getRepeatTimer().startTimer (repeatSpeed);
  35025. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35026. }
  35027. else if (! needsToRelease)
  35028. {
  35029. getRepeatTimer().stopTimer();
  35030. }
  35031. }
  35032. Button::RepeatTimer& Button::getRepeatTimer()
  35033. {
  35034. if (repeatTimer == 0)
  35035. repeatTimer = new RepeatTimer (*this);
  35036. return *repeatTimer;
  35037. }
  35038. END_JUCE_NAMESPACE
  35039. /*** End of inlined file: juce_Button.cpp ***/
  35040. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35041. BEGIN_JUCE_NAMESPACE
  35042. DrawableButton::DrawableButton (const String& name,
  35043. const DrawableButton::ButtonStyle buttonStyle)
  35044. : Button (name),
  35045. style (buttonStyle),
  35046. currentImage (0),
  35047. edgeIndent (3)
  35048. {
  35049. if (buttonStyle == ImageOnButtonBackground)
  35050. {
  35051. backgroundOff = Colour (0xffbbbbff);
  35052. backgroundOn = Colour (0xff3333ff);
  35053. }
  35054. else
  35055. {
  35056. backgroundOff = Colours::transparentBlack;
  35057. backgroundOn = Colour (0xaabbbbff);
  35058. }
  35059. }
  35060. DrawableButton::~DrawableButton()
  35061. {
  35062. }
  35063. void DrawableButton::setImages (const Drawable* normal,
  35064. const Drawable* over,
  35065. const Drawable* down,
  35066. const Drawable* disabled,
  35067. const Drawable* normalOn,
  35068. const Drawable* overOn,
  35069. const Drawable* downOn,
  35070. const Drawable* disabledOn)
  35071. {
  35072. jassert (normal != 0); // you really need to give it at least a normal image..
  35073. if (normal != 0) normalImage = normal->createCopy();
  35074. if (over != 0) overImage = over->createCopy();
  35075. if (down != 0) downImage = down->createCopy();
  35076. if (disabled != 0) disabledImage = disabled->createCopy();
  35077. if (normalOn != 0) normalImageOn = normalOn->createCopy();
  35078. if (overOn != 0) overImageOn = overOn->createCopy();
  35079. if (downOn != 0) downImageOn = downOn->createCopy();
  35080. if (disabledOn != 0) disabledImageOn = disabledOn->createCopy();
  35081. buttonStateChanged();
  35082. }
  35083. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35084. {
  35085. if (style != newStyle)
  35086. {
  35087. style = newStyle;
  35088. buttonStateChanged();
  35089. }
  35090. }
  35091. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35092. const Colour& toggledOnColour)
  35093. {
  35094. if (backgroundOff != toggledOffColour
  35095. || backgroundOn != toggledOnColour)
  35096. {
  35097. backgroundOff = toggledOffColour;
  35098. backgroundOn = toggledOnColour;
  35099. repaint();
  35100. }
  35101. }
  35102. const Colour& DrawableButton::getBackgroundColour() const throw()
  35103. {
  35104. return getToggleState() ? backgroundOn
  35105. : backgroundOff;
  35106. }
  35107. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35108. {
  35109. edgeIndent = numPixelsIndent;
  35110. repaint();
  35111. resized();
  35112. }
  35113. void DrawableButton::resized()
  35114. {
  35115. Button::resized();
  35116. if (currentImage != 0)
  35117. {
  35118. if (style == ImageRaw)
  35119. {
  35120. currentImage->setOriginWithOriginalSize (Point<float>());
  35121. }
  35122. else
  35123. {
  35124. Rectangle<int> imageSpace;
  35125. if (style == ImageOnButtonBackground)
  35126. {
  35127. imageSpace = getLocalBounds().reduced (getWidth() / 4, getHeight() / 4);
  35128. }
  35129. else
  35130. {
  35131. const int textH = (style == ImageAboveTextLabel) ? jmin (16, proportionOfHeight (0.25f)) : 0;
  35132. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35133. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35134. imageSpace.setBounds (indentX, indentY,
  35135. getWidth() - indentX * 2,
  35136. getHeight() - indentY * 2 - textH);
  35137. }
  35138. currentImage->setTransformToFit (imageSpace.toFloat(), RectanglePlacement::centred);
  35139. }
  35140. }
  35141. }
  35142. void DrawableButton::buttonStateChanged()
  35143. {
  35144. repaint();
  35145. Drawable* imageToDraw = 0;
  35146. float opacity = 1.0f;
  35147. if (isEnabled())
  35148. {
  35149. imageToDraw = getCurrentImage();
  35150. }
  35151. else
  35152. {
  35153. imageToDraw = getToggleState() ? disabledImageOn
  35154. : disabledImage;
  35155. if (imageToDraw == 0)
  35156. {
  35157. opacity = 0.4f;
  35158. imageToDraw = getNormalImage();
  35159. }
  35160. }
  35161. if (imageToDraw != currentImage)
  35162. {
  35163. removeChildComponent (currentImage);
  35164. currentImage = imageToDraw;
  35165. if (currentImage != 0)
  35166. {
  35167. currentImage->setInterceptsMouseClicks (false, false);
  35168. addAndMakeVisible (currentImage);
  35169. DrawableButton::resized();
  35170. }
  35171. }
  35172. if (currentImage != 0)
  35173. currentImage->setAlpha (opacity);
  35174. }
  35175. void DrawableButton::paintButton (Graphics& g,
  35176. bool isMouseOverButton,
  35177. bool isButtonDown)
  35178. {
  35179. if (style == ImageOnButtonBackground)
  35180. {
  35181. getLookAndFeel().drawButtonBackground (g, *this,
  35182. getBackgroundColour(),
  35183. isMouseOverButton,
  35184. isButtonDown);
  35185. }
  35186. else
  35187. {
  35188. g.fillAll (getBackgroundColour());
  35189. const int textH = (style == ImageAboveTextLabel)
  35190. ? jmin (16, proportionOfHeight (0.25f))
  35191. : 0;
  35192. if (textH > 0)
  35193. {
  35194. g.setFont ((float) textH);
  35195. g.setColour (findColour (DrawableButton::textColourId)
  35196. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35197. g.drawFittedText (getButtonText(),
  35198. 2, getHeight() - textH - 1,
  35199. getWidth() - 4, textH,
  35200. Justification::centred, 1);
  35201. }
  35202. }
  35203. }
  35204. Drawable* DrawableButton::getCurrentImage() const throw()
  35205. {
  35206. if (isDown())
  35207. return getDownImage();
  35208. if (isOver())
  35209. return getOverImage();
  35210. return getNormalImage();
  35211. }
  35212. Drawable* DrawableButton::getNormalImage() const throw()
  35213. {
  35214. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35215. : normalImage;
  35216. }
  35217. Drawable* DrawableButton::getOverImage() const throw()
  35218. {
  35219. Drawable* d = normalImage;
  35220. if (getToggleState())
  35221. {
  35222. if (overImageOn != 0)
  35223. d = overImageOn;
  35224. else if (normalImageOn != 0)
  35225. d = normalImageOn;
  35226. else if (overImage != 0)
  35227. d = overImage;
  35228. }
  35229. else
  35230. {
  35231. if (overImage != 0)
  35232. d = overImage;
  35233. }
  35234. return d;
  35235. }
  35236. Drawable* DrawableButton::getDownImage() const throw()
  35237. {
  35238. Drawable* d = normalImage;
  35239. if (getToggleState())
  35240. {
  35241. if (downImageOn != 0)
  35242. d = downImageOn;
  35243. else if (overImageOn != 0)
  35244. d = overImageOn;
  35245. else if (normalImageOn != 0)
  35246. d = normalImageOn;
  35247. else if (downImage != 0)
  35248. d = downImage;
  35249. else
  35250. d = getOverImage();
  35251. }
  35252. else
  35253. {
  35254. if (downImage != 0)
  35255. d = downImage;
  35256. else
  35257. d = getOverImage();
  35258. }
  35259. return d;
  35260. }
  35261. END_JUCE_NAMESPACE
  35262. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35263. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35264. BEGIN_JUCE_NAMESPACE
  35265. HyperlinkButton::HyperlinkButton (const String& linkText,
  35266. const URL& linkURL)
  35267. : Button (linkText),
  35268. url (linkURL),
  35269. font (14.0f, Font::underlined),
  35270. resizeFont (true),
  35271. justification (Justification::centred)
  35272. {
  35273. setMouseCursor (MouseCursor::PointingHandCursor);
  35274. setTooltip (linkURL.toString (false));
  35275. }
  35276. HyperlinkButton::~HyperlinkButton()
  35277. {
  35278. }
  35279. void HyperlinkButton::setFont (const Font& newFont,
  35280. const bool resizeToMatchComponentHeight,
  35281. const Justification& justificationType)
  35282. {
  35283. font = newFont;
  35284. resizeFont = resizeToMatchComponentHeight;
  35285. justification = justificationType;
  35286. repaint();
  35287. }
  35288. void HyperlinkButton::setURL (const URL& newURL) throw()
  35289. {
  35290. url = newURL;
  35291. setTooltip (newURL.toString (false));
  35292. }
  35293. const Font HyperlinkButton::getFontToUse() const
  35294. {
  35295. Font f (font);
  35296. if (resizeFont)
  35297. f.setHeight (getHeight() * 0.7f);
  35298. return f;
  35299. }
  35300. void HyperlinkButton::changeWidthToFitText()
  35301. {
  35302. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35303. }
  35304. void HyperlinkButton::colourChanged()
  35305. {
  35306. repaint();
  35307. }
  35308. void HyperlinkButton::clicked()
  35309. {
  35310. if (url.isWellFormed())
  35311. url.launchInDefaultBrowser();
  35312. }
  35313. void HyperlinkButton::paintButton (Graphics& g,
  35314. bool isMouseOverButton,
  35315. bool isButtonDown)
  35316. {
  35317. const Colour textColour (findColour (textColourId));
  35318. if (isEnabled())
  35319. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35320. : textColour);
  35321. else
  35322. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35323. g.setFont (getFontToUse());
  35324. g.drawText (getButtonText(),
  35325. 2, 0, getWidth() - 2, getHeight(),
  35326. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35327. true);
  35328. }
  35329. END_JUCE_NAMESPACE
  35330. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35331. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35332. BEGIN_JUCE_NAMESPACE
  35333. ImageButton::ImageButton (const String& text_)
  35334. : Button (text_),
  35335. scaleImageToFit (true),
  35336. preserveProportions (true),
  35337. alphaThreshold (0),
  35338. imageX (0),
  35339. imageY (0),
  35340. imageW (0),
  35341. imageH (0),
  35342. normalImage (0),
  35343. overImage (0),
  35344. downImage (0)
  35345. {
  35346. }
  35347. ImageButton::~ImageButton()
  35348. {
  35349. }
  35350. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35351. const bool rescaleImagesWhenButtonSizeChanges,
  35352. const bool preserveImageProportions,
  35353. const Image& normalImage_,
  35354. const float imageOpacityWhenNormal,
  35355. const Colour& overlayColourWhenNormal,
  35356. const Image& overImage_,
  35357. const float imageOpacityWhenOver,
  35358. const Colour& overlayColourWhenOver,
  35359. const Image& downImage_,
  35360. const float imageOpacityWhenDown,
  35361. const Colour& overlayColourWhenDown,
  35362. const float hitTestAlphaThreshold)
  35363. {
  35364. normalImage = normalImage_;
  35365. overImage = overImage_;
  35366. downImage = downImage_;
  35367. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35368. {
  35369. imageW = normalImage.getWidth();
  35370. imageH = normalImage.getHeight();
  35371. setSize (imageW, imageH);
  35372. }
  35373. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35374. preserveProportions = preserveImageProportions;
  35375. normalOpacity = imageOpacityWhenNormal;
  35376. normalOverlay = overlayColourWhenNormal;
  35377. overOpacity = imageOpacityWhenOver;
  35378. overOverlay = overlayColourWhenOver;
  35379. downOpacity = imageOpacityWhenDown;
  35380. downOverlay = overlayColourWhenDown;
  35381. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35382. repaint();
  35383. }
  35384. const Image ImageButton::getCurrentImage() const
  35385. {
  35386. if (isDown() || getToggleState())
  35387. return getDownImage();
  35388. if (isOver())
  35389. return getOverImage();
  35390. return getNormalImage();
  35391. }
  35392. const Image ImageButton::getNormalImage() const
  35393. {
  35394. return normalImage;
  35395. }
  35396. const Image ImageButton::getOverImage() const
  35397. {
  35398. return overImage.isValid() ? overImage
  35399. : normalImage;
  35400. }
  35401. const Image ImageButton::getDownImage() const
  35402. {
  35403. return downImage.isValid() ? downImage
  35404. : getOverImage();
  35405. }
  35406. void ImageButton::paintButton (Graphics& g,
  35407. bool isMouseOverButton,
  35408. bool isButtonDown)
  35409. {
  35410. if (! isEnabled())
  35411. {
  35412. isMouseOverButton = false;
  35413. isButtonDown = false;
  35414. }
  35415. Image im (getCurrentImage());
  35416. if (im.isValid())
  35417. {
  35418. const int iw = im.getWidth();
  35419. const int ih = im.getHeight();
  35420. imageW = getWidth();
  35421. imageH = getHeight();
  35422. imageX = (imageW - iw) >> 1;
  35423. imageY = (imageH - ih) >> 1;
  35424. if (scaleImageToFit)
  35425. {
  35426. if (preserveProportions)
  35427. {
  35428. int newW, newH;
  35429. const float imRatio = ih / (float)iw;
  35430. const float destRatio = imageH / (float)imageW;
  35431. if (imRatio > destRatio)
  35432. {
  35433. newW = roundToInt (imageH / imRatio);
  35434. newH = imageH;
  35435. }
  35436. else
  35437. {
  35438. newW = imageW;
  35439. newH = roundToInt (imageW * imRatio);
  35440. }
  35441. imageX = (imageW - newW) / 2;
  35442. imageY = (imageH - newH) / 2;
  35443. imageW = newW;
  35444. imageH = newH;
  35445. }
  35446. else
  35447. {
  35448. imageX = 0;
  35449. imageY = 0;
  35450. }
  35451. }
  35452. if (! scaleImageToFit)
  35453. {
  35454. imageW = iw;
  35455. imageH = ih;
  35456. }
  35457. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35458. isButtonDown ? downOverlay
  35459. : (isMouseOverButton ? overOverlay
  35460. : normalOverlay),
  35461. isButtonDown ? downOpacity
  35462. : (isMouseOverButton ? overOpacity
  35463. : normalOpacity),
  35464. *this);
  35465. }
  35466. }
  35467. bool ImageButton::hitTest (int x, int y)
  35468. {
  35469. if (alphaThreshold == 0)
  35470. return true;
  35471. Image im (getCurrentImage());
  35472. return im.isNull() || (imageW > 0 && imageH > 0
  35473. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35474. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35475. }
  35476. END_JUCE_NAMESPACE
  35477. /*** End of inlined file: juce_ImageButton.cpp ***/
  35478. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35479. BEGIN_JUCE_NAMESPACE
  35480. ShapeButton::ShapeButton (const String& text_,
  35481. const Colour& normalColour_,
  35482. const Colour& overColour_,
  35483. const Colour& downColour_)
  35484. : Button (text_),
  35485. normalColour (normalColour_),
  35486. overColour (overColour_),
  35487. downColour (downColour_),
  35488. maintainShapeProportions (false),
  35489. outlineWidth (0.0f)
  35490. {
  35491. }
  35492. ShapeButton::~ShapeButton()
  35493. {
  35494. }
  35495. void ShapeButton::setColours (const Colour& newNormalColour,
  35496. const Colour& newOverColour,
  35497. const Colour& newDownColour)
  35498. {
  35499. normalColour = newNormalColour;
  35500. overColour = newOverColour;
  35501. downColour = newDownColour;
  35502. }
  35503. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35504. const float newOutlineWidth)
  35505. {
  35506. outlineColour = newOutlineColour;
  35507. outlineWidth = newOutlineWidth;
  35508. }
  35509. void ShapeButton::setShape (const Path& newShape,
  35510. const bool resizeNowToFitThisShape,
  35511. const bool maintainShapeProportions_,
  35512. const bool hasShadow)
  35513. {
  35514. shape = newShape;
  35515. maintainShapeProportions = maintainShapeProportions_;
  35516. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35517. setComponentEffect ((hasShadow) ? &shadow : 0);
  35518. if (resizeNowToFitThisShape)
  35519. {
  35520. Rectangle<float> bounds (shape.getBounds());
  35521. if (hasShadow)
  35522. bounds.expand (4.0f, 4.0f);
  35523. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35524. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35525. 1 + (int) (bounds.getHeight() + outlineWidth));
  35526. }
  35527. }
  35528. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35529. {
  35530. if (! isEnabled())
  35531. {
  35532. isMouseOverButton = false;
  35533. isButtonDown = false;
  35534. }
  35535. g.setColour ((isButtonDown) ? downColour
  35536. : (isMouseOverButton) ? overColour
  35537. : normalColour);
  35538. int w = getWidth();
  35539. int h = getHeight();
  35540. if (getComponentEffect() != 0)
  35541. {
  35542. w -= 4;
  35543. h -= 4;
  35544. }
  35545. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35546. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35547. w - offset - outlineWidth,
  35548. h - offset - outlineWidth,
  35549. maintainShapeProportions));
  35550. g.fillPath (shape, trans);
  35551. if (outlineWidth > 0.0f)
  35552. {
  35553. g.setColour (outlineColour);
  35554. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35555. }
  35556. }
  35557. END_JUCE_NAMESPACE
  35558. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35559. /*** Start of inlined file: juce_TextButton.cpp ***/
  35560. BEGIN_JUCE_NAMESPACE
  35561. TextButton::TextButton (const String& name,
  35562. const String& toolTip)
  35563. : Button (name)
  35564. {
  35565. setTooltip (toolTip);
  35566. }
  35567. TextButton::~TextButton()
  35568. {
  35569. }
  35570. void TextButton::paintButton (Graphics& g,
  35571. bool isMouseOverButton,
  35572. bool isButtonDown)
  35573. {
  35574. getLookAndFeel().drawButtonBackground (g, *this,
  35575. findColour (getToggleState() ? buttonOnColourId
  35576. : buttonColourId),
  35577. isMouseOverButton,
  35578. isButtonDown);
  35579. getLookAndFeel().drawButtonText (g, *this,
  35580. isMouseOverButton,
  35581. isButtonDown);
  35582. }
  35583. void TextButton::colourChanged()
  35584. {
  35585. repaint();
  35586. }
  35587. const Font TextButton::getFont()
  35588. {
  35589. return Font (jmin (15.0f, getHeight() * 0.6f));
  35590. }
  35591. void TextButton::changeWidthToFitText (const int newHeight)
  35592. {
  35593. if (newHeight >= 0)
  35594. setSize (jmax (1, getWidth()), newHeight);
  35595. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35596. getHeight());
  35597. }
  35598. END_JUCE_NAMESPACE
  35599. /*** End of inlined file: juce_TextButton.cpp ***/
  35600. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35601. BEGIN_JUCE_NAMESPACE
  35602. ToggleButton::ToggleButton (const String& buttonText)
  35603. : Button (buttonText)
  35604. {
  35605. setClickingTogglesState (true);
  35606. }
  35607. ToggleButton::~ToggleButton()
  35608. {
  35609. }
  35610. void ToggleButton::paintButton (Graphics& g,
  35611. bool isMouseOverButton,
  35612. bool isButtonDown)
  35613. {
  35614. getLookAndFeel().drawToggleButton (g, *this,
  35615. isMouseOverButton,
  35616. isButtonDown);
  35617. }
  35618. void ToggleButton::changeWidthToFitText()
  35619. {
  35620. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35621. }
  35622. void ToggleButton::colourChanged()
  35623. {
  35624. repaint();
  35625. }
  35626. END_JUCE_NAMESPACE
  35627. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35628. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35629. BEGIN_JUCE_NAMESPACE
  35630. ToolbarButton::ToolbarButton (const int itemId_, const String& buttonText,
  35631. Drawable* const normalImage_, Drawable* const toggledOnImage_)
  35632. : ToolbarItemComponent (itemId_, buttonText, true),
  35633. normalImage (normalImage_),
  35634. toggledOnImage (toggledOnImage_),
  35635. currentImage (0)
  35636. {
  35637. jassert (normalImage_ != 0);
  35638. }
  35639. ToolbarButton::~ToolbarButton()
  35640. {
  35641. }
  35642. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth, bool /*isToolbarVertical*/, int& preferredSize, int& minSize, int& maxSize)
  35643. {
  35644. preferredSize = minSize = maxSize = toolbarDepth;
  35645. return true;
  35646. }
  35647. void ToolbarButton::paintButtonArea (Graphics&, int /*width*/, int /*height*/, bool /*isMouseOver*/, bool /*isMouseDown*/)
  35648. {
  35649. }
  35650. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35651. {
  35652. buttonStateChanged();
  35653. }
  35654. void ToolbarButton::updateDrawable()
  35655. {
  35656. if (currentImage != 0)
  35657. {
  35658. currentImage->setTransformToFit (getContentArea().toFloat(), RectanglePlacement::centred);
  35659. currentImage->setAlpha (isEnabled() ? 1.0f : 0.5f);
  35660. }
  35661. }
  35662. void ToolbarButton::resized()
  35663. {
  35664. ToolbarItemComponent::resized();
  35665. updateDrawable();
  35666. }
  35667. void ToolbarButton::enablementChanged()
  35668. {
  35669. ToolbarItemComponent::enablementChanged();
  35670. updateDrawable();
  35671. }
  35672. void ToolbarButton::buttonStateChanged()
  35673. {
  35674. Drawable* d = normalImage;
  35675. if (getToggleState() && toggledOnImage != 0)
  35676. d = toggledOnImage;
  35677. if (d != currentImage)
  35678. {
  35679. removeChildComponent (currentImage);
  35680. currentImage = d;
  35681. if (d != 0)
  35682. {
  35683. enablementChanged();
  35684. addAndMakeVisible (d);
  35685. updateDrawable();
  35686. }
  35687. }
  35688. }
  35689. END_JUCE_NAMESPACE
  35690. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35691. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35692. BEGIN_JUCE_NAMESPACE
  35693. class CodeDocumentLine
  35694. {
  35695. public:
  35696. CodeDocumentLine (const String::CharPointerType& line_,
  35697. const int lineLength_,
  35698. const int numNewLineChars,
  35699. const int lineStartInFile_)
  35700. : line (line_, lineLength_),
  35701. lineStartInFile (lineStartInFile_),
  35702. lineLength (lineLength_),
  35703. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35704. {
  35705. }
  35706. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35707. {
  35708. String::CharPointerType t (text.getCharPointer());
  35709. int charNumInFile = 0;
  35710. bool finished = t.isEmpty();
  35711. while (! finished)
  35712. {
  35713. String::CharPointerType startOfLine (t);
  35714. int startOfLineInFile = charNumInFile;
  35715. int lineLength = 0;
  35716. int numNewLineChars = 0;
  35717. for (;;)
  35718. {
  35719. const juce_wchar c = t.getAndAdvance();
  35720. if (c == 0)
  35721. {
  35722. finished = true;
  35723. break;
  35724. }
  35725. ++charNumInFile;
  35726. ++lineLength;
  35727. if (c == '\r')
  35728. {
  35729. ++numNewLineChars;
  35730. if (*t == '\n')
  35731. {
  35732. ++t;
  35733. ++charNumInFile;
  35734. ++lineLength;
  35735. ++numNewLineChars;
  35736. }
  35737. break;
  35738. }
  35739. if (c == '\n')
  35740. {
  35741. ++numNewLineChars;
  35742. break;
  35743. }
  35744. }
  35745. newLines.add (new CodeDocumentLine (startOfLine, lineLength,
  35746. numNewLineChars, startOfLineInFile));
  35747. }
  35748. jassert (charNumInFile == text.length());
  35749. }
  35750. bool endsWithLineBreak() const throw()
  35751. {
  35752. return lineLengthWithoutNewLines != lineLength;
  35753. }
  35754. void updateLength() throw()
  35755. {
  35756. lineLengthWithoutNewLines = lineLength = line.length();
  35757. while (lineLengthWithoutNewLines > 0
  35758. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35759. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35760. {
  35761. --lineLengthWithoutNewLines;
  35762. }
  35763. }
  35764. String line;
  35765. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35766. };
  35767. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35768. : document (document_),
  35769. currentLine (document_->lines[0]),
  35770. line (0),
  35771. position (0)
  35772. {
  35773. }
  35774. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35775. : document (other.document),
  35776. currentLine (other.currentLine),
  35777. line (other.line),
  35778. position (other.position)
  35779. {
  35780. }
  35781. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35782. {
  35783. document = other.document;
  35784. currentLine = other.currentLine;
  35785. line = other.line;
  35786. position = other.position;
  35787. return *this;
  35788. }
  35789. CodeDocument::Iterator::~Iterator() throw()
  35790. {
  35791. }
  35792. juce_wchar CodeDocument::Iterator::nextChar()
  35793. {
  35794. if (currentLine == 0)
  35795. return 0;
  35796. jassert (currentLine == document->lines.getUnchecked (line));
  35797. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35798. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35799. {
  35800. ++line;
  35801. currentLine = document->lines [line];
  35802. }
  35803. return result;
  35804. }
  35805. void CodeDocument::Iterator::skip()
  35806. {
  35807. if (currentLine != 0)
  35808. {
  35809. jassert (currentLine == document->lines.getUnchecked (line));
  35810. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35811. {
  35812. ++line;
  35813. currentLine = document->lines [line];
  35814. }
  35815. }
  35816. }
  35817. void CodeDocument::Iterator::skipToEndOfLine()
  35818. {
  35819. if (currentLine != 0)
  35820. {
  35821. jassert (currentLine == document->lines.getUnchecked (line));
  35822. ++line;
  35823. currentLine = document->lines [line];
  35824. if (currentLine != 0)
  35825. position = currentLine->lineStartInFile;
  35826. else
  35827. position = document->getNumCharacters();
  35828. }
  35829. }
  35830. juce_wchar CodeDocument::Iterator::peekNextChar() const
  35831. {
  35832. if (currentLine == 0)
  35833. return 0;
  35834. jassert (currentLine == document->lines.getUnchecked (line));
  35835. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  35836. }
  35837. void CodeDocument::Iterator::skipWhitespace()
  35838. {
  35839. while (CharacterFunctions::isWhitespace (peekNextChar()))
  35840. skip();
  35841. }
  35842. bool CodeDocument::Iterator::isEOF() const throw()
  35843. {
  35844. return currentLine == 0;
  35845. }
  35846. CodeDocument::Position::Position() throw()
  35847. : owner (0), characterPos (0), line (0),
  35848. indexInLine (0), positionMaintained (false)
  35849. {
  35850. }
  35851. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35852. const int line_, const int indexInLine_) throw()
  35853. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35854. characterPos (0), line (line_),
  35855. indexInLine (indexInLine_), positionMaintained (false)
  35856. {
  35857. setLineAndIndex (line_, indexInLine_);
  35858. }
  35859. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35860. const int characterPos_) throw()
  35861. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35862. positionMaintained (false)
  35863. {
  35864. setPosition (characterPos_);
  35865. }
  35866. CodeDocument::Position::Position (const Position& other) throw()
  35867. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  35868. indexInLine (other.indexInLine), positionMaintained (false)
  35869. {
  35870. jassert (*this == other);
  35871. }
  35872. CodeDocument::Position::~Position()
  35873. {
  35874. setPositionMaintained (false);
  35875. }
  35876. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  35877. {
  35878. if (this != &other)
  35879. {
  35880. const bool wasPositionMaintained = positionMaintained;
  35881. if (owner != other.owner)
  35882. setPositionMaintained (false);
  35883. owner = other.owner;
  35884. line = other.line;
  35885. indexInLine = other.indexInLine;
  35886. characterPos = other.characterPos;
  35887. setPositionMaintained (wasPositionMaintained);
  35888. jassert (*this == other);
  35889. }
  35890. return *this;
  35891. }
  35892. bool CodeDocument::Position::operator== (const Position& other) const throw()
  35893. {
  35894. jassert ((characterPos == other.characterPos)
  35895. == (line == other.line && indexInLine == other.indexInLine));
  35896. return characterPos == other.characterPos
  35897. && line == other.line
  35898. && indexInLine == other.indexInLine
  35899. && owner == other.owner;
  35900. }
  35901. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  35902. {
  35903. return ! operator== (other);
  35904. }
  35905. void CodeDocument::Position::setLineAndIndex (const int newLineNum, const int newIndexInLine)
  35906. {
  35907. jassert (owner != 0);
  35908. if (owner->lines.size() == 0)
  35909. {
  35910. line = 0;
  35911. indexInLine = 0;
  35912. characterPos = 0;
  35913. }
  35914. else
  35915. {
  35916. if (newLineNum >= owner->lines.size())
  35917. {
  35918. line = owner->lines.size() - 1;
  35919. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35920. jassert (l != 0);
  35921. indexInLine = l->lineLengthWithoutNewLines;
  35922. characterPos = l->lineStartInFile + indexInLine;
  35923. }
  35924. else
  35925. {
  35926. line = jmax (0, newLineNum);
  35927. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35928. jassert (l != 0);
  35929. if (l->lineLengthWithoutNewLines > 0)
  35930. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  35931. else
  35932. indexInLine = 0;
  35933. characterPos = l->lineStartInFile + indexInLine;
  35934. }
  35935. }
  35936. }
  35937. void CodeDocument::Position::setPosition (const int newPosition)
  35938. {
  35939. jassert (owner != 0);
  35940. line = 0;
  35941. indexInLine = 0;
  35942. characterPos = 0;
  35943. if (newPosition > 0)
  35944. {
  35945. int lineStart = 0;
  35946. int lineEnd = owner->lines.size();
  35947. for (;;)
  35948. {
  35949. if (lineEnd - lineStart < 4)
  35950. {
  35951. for (int i = lineStart; i < lineEnd; ++i)
  35952. {
  35953. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  35954. int index = newPosition - l->lineStartInFile;
  35955. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  35956. {
  35957. line = i;
  35958. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  35959. characterPos = l->lineStartInFile + indexInLine;
  35960. }
  35961. }
  35962. break;
  35963. }
  35964. else
  35965. {
  35966. const int midIndex = (lineStart + lineEnd + 1) / 2;
  35967. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  35968. if (newPosition >= mid->lineStartInFile)
  35969. lineStart = midIndex;
  35970. else
  35971. lineEnd = midIndex;
  35972. }
  35973. }
  35974. }
  35975. }
  35976. void CodeDocument::Position::moveBy (int characterDelta)
  35977. {
  35978. jassert (owner != 0);
  35979. if (characterDelta == 1)
  35980. {
  35981. setPosition (getPosition());
  35982. // If moving right, make sure we don't get stuck between the \r and \n characters..
  35983. if (line < owner->lines.size())
  35984. {
  35985. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35986. if (indexInLine + characterDelta < l->lineLength
  35987. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  35988. ++characterDelta;
  35989. }
  35990. }
  35991. setPosition (characterPos + characterDelta);
  35992. }
  35993. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  35994. {
  35995. CodeDocument::Position p (*this);
  35996. p.moveBy (characterDelta);
  35997. return p;
  35998. }
  35999. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  36000. {
  36001. CodeDocument::Position p (*this);
  36002. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  36003. return p;
  36004. }
  36005. const juce_wchar CodeDocument::Position::getCharacter() const
  36006. {
  36007. const CodeDocumentLine* const l = owner->lines [line];
  36008. return l == 0 ? 0 : l->line [getIndexInLine()];
  36009. }
  36010. const String CodeDocument::Position::getLineText() const
  36011. {
  36012. const CodeDocumentLine* const l = owner->lines [line];
  36013. return l == 0 ? String::empty : l->line;
  36014. }
  36015. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  36016. {
  36017. if (isMaintained != positionMaintained)
  36018. {
  36019. positionMaintained = isMaintained;
  36020. if (owner != 0)
  36021. {
  36022. if (isMaintained)
  36023. {
  36024. jassert (! owner->positionsToMaintain.contains (this));
  36025. owner->positionsToMaintain.add (this);
  36026. }
  36027. else
  36028. {
  36029. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36030. jassert (owner->positionsToMaintain.contains (this));
  36031. owner->positionsToMaintain.removeValue (this);
  36032. }
  36033. }
  36034. }
  36035. }
  36036. CodeDocument::CodeDocument()
  36037. : undoManager (std::numeric_limits<int>::max(), 10000),
  36038. currentActionIndex (0),
  36039. indexOfSavedState (-1),
  36040. maximumLineLength (-1),
  36041. newLineChars ("\r\n")
  36042. {
  36043. }
  36044. CodeDocument::~CodeDocument()
  36045. {
  36046. }
  36047. const String CodeDocument::getAllContent() const
  36048. {
  36049. return getTextBetween (Position (this, 0),
  36050. Position (this, lines.size(), 0));
  36051. }
  36052. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36053. {
  36054. if (end.getPosition() <= start.getPosition())
  36055. return String::empty;
  36056. const int startLine = start.getLineNumber();
  36057. const int endLine = end.getLineNumber();
  36058. if (startLine == endLine)
  36059. {
  36060. CodeDocumentLine* const line = lines [startLine];
  36061. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36062. }
  36063. String result;
  36064. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36065. String::Concatenator concatenator (result);
  36066. const int maxLine = jmin (lines.size() - 1, endLine);
  36067. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36068. {
  36069. const CodeDocumentLine* line = lines.getUnchecked(i);
  36070. int len = line->lineLength;
  36071. if (i == startLine)
  36072. {
  36073. const int index = start.getIndexInLine();
  36074. concatenator.append (line->line.substring (index, len));
  36075. }
  36076. else if (i == endLine)
  36077. {
  36078. len = end.getIndexInLine();
  36079. concatenator.append (line->line.substring (0, len));
  36080. }
  36081. else
  36082. {
  36083. concatenator.append (line->line);
  36084. }
  36085. }
  36086. return result;
  36087. }
  36088. int CodeDocument::getNumCharacters() const throw()
  36089. {
  36090. const CodeDocumentLine* const lastLine = lines.getLast();
  36091. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36092. }
  36093. const String CodeDocument::getLine (const int lineIndex) const throw()
  36094. {
  36095. const CodeDocumentLine* const line = lines [lineIndex];
  36096. return (line == 0) ? String::empty : line->line;
  36097. }
  36098. int CodeDocument::getMaximumLineLength() throw()
  36099. {
  36100. if (maximumLineLength < 0)
  36101. {
  36102. maximumLineLength = 0;
  36103. for (int i = lines.size(); --i >= 0;)
  36104. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36105. }
  36106. return maximumLineLength;
  36107. }
  36108. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36109. {
  36110. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36111. }
  36112. void CodeDocument::insertText (const Position& position, const String& text)
  36113. {
  36114. insert (text, position.getPosition(), true);
  36115. }
  36116. void CodeDocument::replaceAllContent (const String& newContent)
  36117. {
  36118. remove (0, getNumCharacters(), true);
  36119. insert (newContent, 0, true);
  36120. }
  36121. bool CodeDocument::loadFromStream (InputStream& stream)
  36122. {
  36123. replaceAllContent (stream.readEntireStreamAsString());
  36124. setSavePoint();
  36125. clearUndoHistory();
  36126. return true;
  36127. }
  36128. bool CodeDocument::writeToStream (OutputStream& stream)
  36129. {
  36130. for (int i = 0; i < lines.size(); ++i)
  36131. {
  36132. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36133. const char* utf8 = temp.toUTF8();
  36134. if (! stream.write (utf8, (int) strlen (utf8)))
  36135. return false;
  36136. }
  36137. return true;
  36138. }
  36139. void CodeDocument::setNewLineCharacters (const String& newLineChars_) throw()
  36140. {
  36141. jassert (newLineChars_ == "\r\n" || newLineChars_ == "\n" || newLineChars_ == "\r");
  36142. newLineChars = newLineChars_;
  36143. }
  36144. void CodeDocument::newTransaction()
  36145. {
  36146. undoManager.beginNewTransaction (String::empty);
  36147. }
  36148. void CodeDocument::undo()
  36149. {
  36150. newTransaction();
  36151. undoManager.undo();
  36152. }
  36153. void CodeDocument::redo()
  36154. {
  36155. undoManager.redo();
  36156. }
  36157. void CodeDocument::clearUndoHistory()
  36158. {
  36159. undoManager.clearUndoHistory();
  36160. }
  36161. void CodeDocument::setSavePoint() throw()
  36162. {
  36163. indexOfSavedState = currentActionIndex;
  36164. }
  36165. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36166. {
  36167. return currentActionIndex != indexOfSavedState;
  36168. }
  36169. namespace CodeDocumentHelpers
  36170. {
  36171. int getCharacterType (const juce_wchar character) throw()
  36172. {
  36173. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36174. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36175. }
  36176. }
  36177. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36178. {
  36179. Position p (position);
  36180. const int maxDistance = 256;
  36181. int i = 0;
  36182. while (i < maxDistance
  36183. && CharacterFunctions::isWhitespace (p.getCharacter())
  36184. && (i == 0 || (p.getCharacter() != '\n'
  36185. && p.getCharacter() != '\r')))
  36186. {
  36187. ++i;
  36188. p.moveBy (1);
  36189. }
  36190. if (i == 0)
  36191. {
  36192. const int type = CodeDocumentHelpers::getCharacterType (p.getCharacter());
  36193. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.getCharacter()))
  36194. {
  36195. ++i;
  36196. p.moveBy (1);
  36197. }
  36198. while (i < maxDistance
  36199. && CharacterFunctions::isWhitespace (p.getCharacter())
  36200. && (i == 0 || (p.getCharacter() != '\n'
  36201. && p.getCharacter() != '\r')))
  36202. {
  36203. ++i;
  36204. p.moveBy (1);
  36205. }
  36206. }
  36207. return p;
  36208. }
  36209. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36210. {
  36211. Position p (position);
  36212. const int maxDistance = 256;
  36213. int i = 0;
  36214. bool stoppedAtLineStart = false;
  36215. while (i < maxDistance)
  36216. {
  36217. const juce_wchar c = p.movedBy (-1).getCharacter();
  36218. if (c == '\r' || c == '\n')
  36219. {
  36220. stoppedAtLineStart = true;
  36221. if (i > 0)
  36222. break;
  36223. }
  36224. if (! CharacterFunctions::isWhitespace (c))
  36225. break;
  36226. p.moveBy (-1);
  36227. ++i;
  36228. }
  36229. if (i < maxDistance && ! stoppedAtLineStart)
  36230. {
  36231. const int type = CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter());
  36232. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter()))
  36233. {
  36234. p.moveBy (-1);
  36235. ++i;
  36236. }
  36237. }
  36238. return p;
  36239. }
  36240. void CodeDocument::checkLastLineStatus()
  36241. {
  36242. while (lines.size() > 0
  36243. && lines.getLast()->lineLength == 0
  36244. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36245. {
  36246. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36247. lines.removeLast();
  36248. }
  36249. const CodeDocumentLine* const lastLine = lines.getLast();
  36250. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36251. {
  36252. // check that there's an empty line at the end if the preceding one ends in a newline..
  36253. lines.add (new CodeDocumentLine (String::empty.getCharPointer(), 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36254. }
  36255. }
  36256. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36257. {
  36258. listeners.add (listener);
  36259. }
  36260. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36261. {
  36262. listeners.remove (listener);
  36263. }
  36264. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36265. {
  36266. Position startPos (this, startLine, 0);
  36267. Position endPos (this, endLine, 0);
  36268. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36269. }
  36270. class CodeDocumentInsertAction : public UndoableAction
  36271. {
  36272. public:
  36273. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36274. : owner (owner_),
  36275. text (text_),
  36276. insertPos (insertPos_)
  36277. {
  36278. }
  36279. bool perform()
  36280. {
  36281. owner.currentActionIndex++;
  36282. owner.insert (text, insertPos, false);
  36283. return true;
  36284. }
  36285. bool undo()
  36286. {
  36287. owner.currentActionIndex--;
  36288. owner.remove (insertPos, insertPos + text.length(), false);
  36289. return true;
  36290. }
  36291. int getSizeInUnits() { return text.length() + 32; }
  36292. private:
  36293. CodeDocument& owner;
  36294. const String text;
  36295. int insertPos;
  36296. JUCE_DECLARE_NON_COPYABLE (CodeDocumentInsertAction);
  36297. };
  36298. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36299. {
  36300. if (text.isEmpty())
  36301. return;
  36302. if (undoable)
  36303. {
  36304. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36305. }
  36306. else
  36307. {
  36308. Position pos (this, insertPos);
  36309. const int firstAffectedLine = pos.getLineNumber();
  36310. int lastAffectedLine = firstAffectedLine + 1;
  36311. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36312. String textInsideOriginalLine (text);
  36313. if (firstLine != 0)
  36314. {
  36315. const int index = pos.getIndexInLine();
  36316. textInsideOriginalLine = firstLine->line.substring (0, index)
  36317. + textInsideOriginalLine
  36318. + firstLine->line.substring (index);
  36319. }
  36320. maximumLineLength = -1;
  36321. Array <CodeDocumentLine*> newLines;
  36322. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36323. jassert (newLines.size() > 0);
  36324. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36325. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36326. lines.set (firstAffectedLine, newFirstLine);
  36327. if (newLines.size() > 1)
  36328. {
  36329. for (int i = 1; i < newLines.size(); ++i)
  36330. {
  36331. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36332. lines.insert (firstAffectedLine + i, l);
  36333. }
  36334. lastAffectedLine = lines.size();
  36335. }
  36336. int i, lineStart = newFirstLine->lineStartInFile;
  36337. for (i = firstAffectedLine; i < lines.size(); ++i)
  36338. {
  36339. CodeDocumentLine* const l = lines.getUnchecked (i);
  36340. l->lineStartInFile = lineStart;
  36341. lineStart += l->lineLength;
  36342. }
  36343. checkLastLineStatus();
  36344. const int newTextLength = text.length();
  36345. for (i = 0; i < positionsToMaintain.size(); ++i)
  36346. {
  36347. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36348. if (p->getPosition() >= insertPos)
  36349. p->setPosition (p->getPosition() + newTextLength);
  36350. }
  36351. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36352. }
  36353. }
  36354. class CodeDocumentDeleteAction : public UndoableAction
  36355. {
  36356. public:
  36357. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36358. : owner (owner_),
  36359. startPos (startPos_),
  36360. endPos (endPos_)
  36361. {
  36362. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36363. CodeDocument::Position (&owner, endPos));
  36364. }
  36365. bool perform()
  36366. {
  36367. owner.currentActionIndex++;
  36368. owner.remove (startPos, endPos, false);
  36369. return true;
  36370. }
  36371. bool undo()
  36372. {
  36373. owner.currentActionIndex--;
  36374. owner.insert (removedText, startPos, false);
  36375. return true;
  36376. }
  36377. int getSizeInUnits() { return removedText.length() + 32; }
  36378. private:
  36379. CodeDocument& owner;
  36380. int startPos, endPos;
  36381. String removedText;
  36382. JUCE_DECLARE_NON_COPYABLE (CodeDocumentDeleteAction);
  36383. };
  36384. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36385. {
  36386. if (endPos <= startPos)
  36387. return;
  36388. if (undoable)
  36389. {
  36390. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36391. }
  36392. else
  36393. {
  36394. Position startPosition (this, startPos);
  36395. Position endPosition (this, endPos);
  36396. maximumLineLength = -1;
  36397. const int firstAffectedLine = startPosition.getLineNumber();
  36398. const int endLine = endPosition.getLineNumber();
  36399. int lastAffectedLine = firstAffectedLine + 1;
  36400. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36401. if (firstAffectedLine == endLine)
  36402. {
  36403. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36404. + firstLine->line.substring (endPosition.getIndexInLine());
  36405. firstLine->updateLength();
  36406. }
  36407. else
  36408. {
  36409. lastAffectedLine = lines.size();
  36410. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36411. jassert (lastLine != 0);
  36412. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36413. + lastLine->line.substring (endPosition.getIndexInLine());
  36414. firstLine->updateLength();
  36415. int numLinesToRemove = endLine - firstAffectedLine;
  36416. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36417. }
  36418. int i;
  36419. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36420. {
  36421. CodeDocumentLine* const l = lines.getUnchecked (i);
  36422. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36423. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36424. }
  36425. checkLastLineStatus();
  36426. const int totalChars = getNumCharacters();
  36427. for (i = 0; i < positionsToMaintain.size(); ++i)
  36428. {
  36429. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36430. if (p->getPosition() > startPosition.getPosition())
  36431. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36432. if (p->getPosition() > totalChars)
  36433. p->setPosition (totalChars);
  36434. }
  36435. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36436. }
  36437. }
  36438. END_JUCE_NAMESPACE
  36439. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36440. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36441. BEGIN_JUCE_NAMESPACE
  36442. class CodeEditorComponent::CaretComponent : public Component,
  36443. public Timer
  36444. {
  36445. public:
  36446. CaretComponent (CodeEditorComponent& owner_)
  36447. : owner (owner_)
  36448. {
  36449. setAlwaysOnTop (true);
  36450. setInterceptsMouseClicks (false, false);
  36451. }
  36452. void paint (Graphics& g)
  36453. {
  36454. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36455. }
  36456. void timerCallback()
  36457. {
  36458. setVisible (shouldBeShown() && ! isVisible());
  36459. }
  36460. void updatePosition()
  36461. {
  36462. startTimer (400);
  36463. setVisible (shouldBeShown());
  36464. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36465. }
  36466. private:
  36467. CodeEditorComponent& owner;
  36468. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36469. JUCE_DECLARE_NON_COPYABLE (CaretComponent);
  36470. };
  36471. class CodeEditorComponent::CodeEditorLine
  36472. {
  36473. public:
  36474. CodeEditorLine() throw()
  36475. : highlightColumnStart (0), highlightColumnEnd (0)
  36476. {
  36477. }
  36478. bool update (CodeDocument& document, int lineNum,
  36479. CodeDocument::Iterator& source,
  36480. CodeTokeniser* analyser, const int spacesPerTab,
  36481. const CodeDocument::Position& selectionStart,
  36482. const CodeDocument::Position& selectionEnd)
  36483. {
  36484. Array <SyntaxToken> newTokens;
  36485. newTokens.ensureStorageAllocated (8);
  36486. if (analyser == 0)
  36487. {
  36488. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36489. }
  36490. else if (lineNum < document.getNumLines())
  36491. {
  36492. const CodeDocument::Position pos (&document, lineNum, 0);
  36493. createTokens (pos.getPosition(), pos.getLineText(),
  36494. source, analyser, newTokens);
  36495. }
  36496. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36497. int newHighlightStart = 0;
  36498. int newHighlightEnd = 0;
  36499. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36500. {
  36501. const String line (document.getLine (lineNum));
  36502. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36503. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36504. line, spacesPerTab);
  36505. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36506. line, spacesPerTab);
  36507. }
  36508. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36509. {
  36510. highlightColumnStart = newHighlightStart;
  36511. highlightColumnEnd = newHighlightEnd;
  36512. }
  36513. else
  36514. {
  36515. if (tokens.size() == newTokens.size())
  36516. {
  36517. bool allTheSame = true;
  36518. for (int i = newTokens.size(); --i >= 0;)
  36519. {
  36520. if (tokens.getReference(i) != newTokens.getReference(i))
  36521. {
  36522. allTheSame = false;
  36523. break;
  36524. }
  36525. }
  36526. if (allTheSame)
  36527. return false;
  36528. }
  36529. }
  36530. tokens.swapWithArray (newTokens);
  36531. return true;
  36532. }
  36533. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36534. float x, const int y, const int baselineOffset, const int lineHeight,
  36535. const Colour& highlightColour) const
  36536. {
  36537. if (highlightColumnStart < highlightColumnEnd)
  36538. {
  36539. g.setColour (highlightColour);
  36540. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36541. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36542. }
  36543. int lastType = std::numeric_limits<int>::min();
  36544. for (int i = 0; i < tokens.size(); ++i)
  36545. {
  36546. SyntaxToken& token = tokens.getReference(i);
  36547. if (lastType != token.tokenType)
  36548. {
  36549. lastType = token.tokenType;
  36550. g.setColour (owner.getColourForTokenType (lastType));
  36551. }
  36552. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36553. if (i < tokens.size() - 1)
  36554. {
  36555. if (token.width < 0)
  36556. token.width = font.getStringWidthFloat (token.text);
  36557. x += token.width;
  36558. }
  36559. }
  36560. }
  36561. private:
  36562. struct SyntaxToken
  36563. {
  36564. SyntaxToken (const String& text_, const int type) throw()
  36565. : text (text_), tokenType (type), width (-1.0f)
  36566. {
  36567. }
  36568. bool operator!= (const SyntaxToken& other) const throw()
  36569. {
  36570. return text != other.text || tokenType != other.tokenType;
  36571. }
  36572. String text;
  36573. int tokenType;
  36574. float width;
  36575. };
  36576. Array <SyntaxToken> tokens;
  36577. int highlightColumnStart, highlightColumnEnd;
  36578. static void createTokens (int startPosition, const String& lineText,
  36579. CodeDocument::Iterator& source,
  36580. CodeTokeniser* analyser,
  36581. Array <SyntaxToken>& newTokens)
  36582. {
  36583. CodeDocument::Iterator lastIterator (source);
  36584. const int lineLength = lineText.length();
  36585. for (;;)
  36586. {
  36587. int tokenType = analyser->readNextToken (source);
  36588. int tokenStart = lastIterator.getPosition();
  36589. int tokenEnd = source.getPosition();
  36590. if (tokenEnd <= tokenStart)
  36591. break;
  36592. tokenEnd -= startPosition;
  36593. if (tokenEnd > 0)
  36594. {
  36595. tokenStart -= startPosition;
  36596. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36597. tokenType));
  36598. if (tokenEnd >= lineLength)
  36599. break;
  36600. }
  36601. lastIterator = source;
  36602. }
  36603. source = lastIterator;
  36604. }
  36605. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  36606. {
  36607. int x = 0;
  36608. for (int i = 0; i < tokens.size(); ++i)
  36609. {
  36610. SyntaxToken& t = tokens.getReference(i);
  36611. for (;;)
  36612. {
  36613. int tabPos = t.text.indexOfChar ('\t');
  36614. if (tabPos < 0)
  36615. break;
  36616. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36617. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36618. }
  36619. x += t.text.length();
  36620. }
  36621. }
  36622. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36623. {
  36624. jassert (index <= line.length());
  36625. int col = 0;
  36626. for (int i = 0; i < index; ++i)
  36627. {
  36628. if (line[i] != '\t')
  36629. ++col;
  36630. else
  36631. col += spacesPerTab - (col % spacesPerTab);
  36632. }
  36633. return col;
  36634. }
  36635. };
  36636. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36637. CodeTokeniser* const codeTokeniser_)
  36638. : document (document_),
  36639. firstLineOnScreen (0),
  36640. gutter (5),
  36641. spacesPerTab (4),
  36642. lineHeight (0),
  36643. linesOnScreen (0),
  36644. columnsOnScreen (0),
  36645. scrollbarThickness (16),
  36646. columnToTryToMaintain (-1),
  36647. useSpacesForTabs (false),
  36648. xOffset (0),
  36649. verticalScrollBar (true),
  36650. horizontalScrollBar (false),
  36651. codeTokeniser (codeTokeniser_)
  36652. {
  36653. caretPos = CodeDocument::Position (&document_, 0, 0);
  36654. caretPos.setPositionMaintained (true);
  36655. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36656. selectionStart.setPositionMaintained (true);
  36657. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36658. selectionEnd.setPositionMaintained (true);
  36659. setOpaque (true);
  36660. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36661. setWantsKeyboardFocus (true);
  36662. addAndMakeVisible (&verticalScrollBar);
  36663. verticalScrollBar.setSingleStepSize (1.0);
  36664. addAndMakeVisible (&horizontalScrollBar);
  36665. horizontalScrollBar.setSingleStepSize (1.0);
  36666. addAndMakeVisible (caret = new CaretComponent (*this));
  36667. Font f (12.0f);
  36668. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36669. setFont (f);
  36670. resetToDefaultColours();
  36671. verticalScrollBar.addListener (this);
  36672. horizontalScrollBar.addListener (this);
  36673. document.addListener (this);
  36674. }
  36675. CodeEditorComponent::~CodeEditorComponent()
  36676. {
  36677. document.removeListener (this);
  36678. }
  36679. void CodeEditorComponent::loadContent (const String& newContent)
  36680. {
  36681. clearCachedIterators (0);
  36682. document.replaceAllContent (newContent);
  36683. document.clearUndoHistory();
  36684. document.setSavePoint();
  36685. caretPos.setPosition (0);
  36686. selectionStart.setPosition (0);
  36687. selectionEnd.setPosition (0);
  36688. scrollToLine (0);
  36689. }
  36690. bool CodeEditorComponent::isTextInputActive() const
  36691. {
  36692. return true;
  36693. }
  36694. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36695. const CodeDocument::Position& affectedTextEnd)
  36696. {
  36697. clearCachedIterators (affectedTextStart.getLineNumber());
  36698. triggerAsyncUpdate();
  36699. caret->updatePosition();
  36700. columnToTryToMaintain = -1;
  36701. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36702. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36703. deselectAll();
  36704. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36705. || caretPos.getPosition() < affectedTextStart.getPosition())
  36706. moveCaretTo (affectedTextStart, false);
  36707. updateScrollBars();
  36708. }
  36709. void CodeEditorComponent::resized()
  36710. {
  36711. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36712. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36713. lines.clear();
  36714. rebuildLineTokens();
  36715. caret->updatePosition();
  36716. verticalScrollBar.setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36717. horizontalScrollBar.setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36718. updateScrollBars();
  36719. }
  36720. void CodeEditorComponent::paint (Graphics& g)
  36721. {
  36722. handleUpdateNowIfNeeded();
  36723. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36724. g.reduceClipRegion (gutter, 0, verticalScrollBar.getX() - gutter, horizontalScrollBar.getY());
  36725. g.setFont (font);
  36726. const int baselineOffset = (int) font.getAscent();
  36727. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36728. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36729. const Rectangle<int> clip (g.getClipBounds());
  36730. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36731. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36732. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36733. {
  36734. lines.getUnchecked(j)->draw (*this, g, font,
  36735. (float) (gutter - xOffset * charWidth),
  36736. lineHeight * j, baselineOffset, lineHeight,
  36737. highlightColour);
  36738. }
  36739. }
  36740. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  36741. {
  36742. if (scrollbarThickness != thickness)
  36743. {
  36744. scrollbarThickness = thickness;
  36745. resized();
  36746. }
  36747. }
  36748. void CodeEditorComponent::handleAsyncUpdate()
  36749. {
  36750. rebuildLineTokens();
  36751. }
  36752. void CodeEditorComponent::rebuildLineTokens()
  36753. {
  36754. cancelPendingUpdate();
  36755. const int numNeeded = linesOnScreen + 1;
  36756. int minLineToRepaint = numNeeded;
  36757. int maxLineToRepaint = 0;
  36758. if (numNeeded != lines.size())
  36759. {
  36760. lines.clear();
  36761. for (int i = numNeeded; --i >= 0;)
  36762. lines.add (new CodeEditorLine());
  36763. minLineToRepaint = 0;
  36764. maxLineToRepaint = numNeeded;
  36765. }
  36766. jassert (numNeeded == lines.size());
  36767. CodeDocument::Iterator source (&document);
  36768. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36769. for (int i = 0; i < numNeeded; ++i)
  36770. {
  36771. CodeEditorLine* const line = lines.getUnchecked(i);
  36772. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36773. selectionStart, selectionEnd))
  36774. {
  36775. minLineToRepaint = jmin (minLineToRepaint, i);
  36776. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36777. }
  36778. }
  36779. if (minLineToRepaint <= maxLineToRepaint)
  36780. {
  36781. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36782. verticalScrollBar.getX() - gutter,
  36783. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36784. }
  36785. }
  36786. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36787. {
  36788. caretPos = newPos;
  36789. columnToTryToMaintain = -1;
  36790. if (highlighting)
  36791. {
  36792. if (dragType == notDragging)
  36793. {
  36794. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36795. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36796. dragType = draggingSelectionStart;
  36797. else
  36798. dragType = draggingSelectionEnd;
  36799. }
  36800. if (dragType == draggingSelectionStart)
  36801. {
  36802. selectionStart = caretPos;
  36803. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36804. {
  36805. const CodeDocument::Position temp (selectionStart);
  36806. selectionStart = selectionEnd;
  36807. selectionEnd = temp;
  36808. dragType = draggingSelectionEnd;
  36809. }
  36810. }
  36811. else
  36812. {
  36813. selectionEnd = caretPos;
  36814. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36815. {
  36816. const CodeDocument::Position temp (selectionStart);
  36817. selectionStart = selectionEnd;
  36818. selectionEnd = temp;
  36819. dragType = draggingSelectionStart;
  36820. }
  36821. }
  36822. triggerAsyncUpdate();
  36823. }
  36824. else
  36825. {
  36826. deselectAll();
  36827. }
  36828. caret->updatePosition();
  36829. scrollToKeepCaretOnScreen();
  36830. updateScrollBars();
  36831. }
  36832. void CodeEditorComponent::deselectAll()
  36833. {
  36834. if (selectionStart != selectionEnd)
  36835. triggerAsyncUpdate();
  36836. selectionStart = caretPos;
  36837. selectionEnd = caretPos;
  36838. }
  36839. void CodeEditorComponent::updateScrollBars()
  36840. {
  36841. verticalScrollBar.setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  36842. verticalScrollBar.setCurrentRange (firstLineOnScreen, linesOnScreen);
  36843. horizontalScrollBar.setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  36844. horizontalScrollBar.setCurrentRange (xOffset, columnsOnScreen);
  36845. }
  36846. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  36847. {
  36848. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  36849. newFirstLineOnScreen);
  36850. if (newFirstLineOnScreen != firstLineOnScreen)
  36851. {
  36852. firstLineOnScreen = newFirstLineOnScreen;
  36853. caret->updatePosition();
  36854. updateCachedIterators (firstLineOnScreen);
  36855. triggerAsyncUpdate();
  36856. }
  36857. }
  36858. void CodeEditorComponent::scrollToColumnInternal (double column)
  36859. {
  36860. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  36861. if (xOffset != newOffset)
  36862. {
  36863. xOffset = newOffset;
  36864. caret->updatePosition();
  36865. repaint();
  36866. }
  36867. }
  36868. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  36869. {
  36870. scrollToLineInternal (newFirstLineOnScreen);
  36871. updateScrollBars();
  36872. }
  36873. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  36874. {
  36875. scrollToColumnInternal (newFirstColumnOnScreen);
  36876. updateScrollBars();
  36877. }
  36878. void CodeEditorComponent::scrollBy (int deltaLines)
  36879. {
  36880. scrollToLine (firstLineOnScreen + deltaLines);
  36881. }
  36882. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  36883. {
  36884. if (caretPos.getLineNumber() < firstLineOnScreen)
  36885. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  36886. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36887. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  36888. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36889. if (column >= xOffset + columnsOnScreen - 1)
  36890. scrollToColumn (column + 1 - columnsOnScreen);
  36891. else if (column < xOffset)
  36892. scrollToColumn (column);
  36893. }
  36894. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  36895. {
  36896. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  36897. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  36898. roundToInt (charWidth),
  36899. lineHeight);
  36900. }
  36901. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  36902. {
  36903. const int line = y / lineHeight + firstLineOnScreen;
  36904. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  36905. const int index = columnToIndex (line, column);
  36906. return CodeDocument::Position (&document, line, index);
  36907. }
  36908. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  36909. {
  36910. document.deleteSection (selectionStart, selectionEnd);
  36911. if (newText.isNotEmpty())
  36912. document.insertText (caretPos, newText);
  36913. scrollToKeepCaretOnScreen();
  36914. }
  36915. void CodeEditorComponent::insertTabAtCaret()
  36916. {
  36917. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  36918. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  36919. {
  36920. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  36921. }
  36922. if (useSpacesForTabs)
  36923. {
  36924. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36925. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  36926. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  36927. }
  36928. else
  36929. {
  36930. insertTextAtCaret ("\t");
  36931. }
  36932. }
  36933. void CodeEditorComponent::cut()
  36934. {
  36935. insertTextAtCaret (String::empty);
  36936. }
  36937. void CodeEditorComponent::copy()
  36938. {
  36939. newTransaction();
  36940. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  36941. if (selection.isNotEmpty())
  36942. SystemClipboard::copyTextToClipboard (selection);
  36943. }
  36944. void CodeEditorComponent::copyThenCut()
  36945. {
  36946. copy();
  36947. cut();
  36948. newTransaction();
  36949. }
  36950. void CodeEditorComponent::paste()
  36951. {
  36952. newTransaction();
  36953. const String clip (SystemClipboard::getTextFromClipboard());
  36954. if (clip.isNotEmpty())
  36955. insertTextAtCaret (clip);
  36956. newTransaction();
  36957. }
  36958. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  36959. {
  36960. newTransaction();
  36961. if (moveInWholeWordSteps)
  36962. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  36963. else
  36964. moveCaretTo (caretPos.movedBy (-1), selecting);
  36965. }
  36966. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  36967. {
  36968. newTransaction();
  36969. if (moveInWholeWordSteps)
  36970. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  36971. else
  36972. moveCaretTo (caretPos.movedBy (1), selecting);
  36973. }
  36974. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  36975. {
  36976. CodeDocument::Position pos (caretPos);
  36977. const int newLineNum = pos.getLineNumber() + delta;
  36978. if (columnToTryToMaintain < 0)
  36979. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  36980. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  36981. const int colToMaintain = columnToTryToMaintain;
  36982. moveCaretTo (pos, selecting);
  36983. columnToTryToMaintain = colToMaintain;
  36984. }
  36985. void CodeEditorComponent::cursorDown (const bool selecting)
  36986. {
  36987. newTransaction();
  36988. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  36989. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36990. else
  36991. moveLineDelta (1, selecting);
  36992. }
  36993. void CodeEditorComponent::cursorUp (const bool selecting)
  36994. {
  36995. newTransaction();
  36996. if (caretPos.getLineNumber() == 0)
  36997. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36998. else
  36999. moveLineDelta (-1, selecting);
  37000. }
  37001. void CodeEditorComponent::pageDown (const bool selecting)
  37002. {
  37003. newTransaction();
  37004. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  37005. moveLineDelta (linesOnScreen, selecting);
  37006. }
  37007. void CodeEditorComponent::pageUp (const bool selecting)
  37008. {
  37009. newTransaction();
  37010. scrollBy (-linesOnScreen);
  37011. moveLineDelta (-linesOnScreen, selecting);
  37012. }
  37013. void CodeEditorComponent::scrollUp()
  37014. {
  37015. newTransaction();
  37016. scrollBy (1);
  37017. if (caretPos.getLineNumber() < firstLineOnScreen)
  37018. moveLineDelta (1, false);
  37019. }
  37020. void CodeEditorComponent::scrollDown()
  37021. {
  37022. newTransaction();
  37023. scrollBy (-1);
  37024. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37025. moveLineDelta (-1, false);
  37026. }
  37027. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37028. {
  37029. newTransaction();
  37030. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37031. }
  37032. namespace CodeEditorHelpers
  37033. {
  37034. int findFirstNonWhitespaceChar (const String& line) throw()
  37035. {
  37036. const int len = line.length();
  37037. for (int i = 0; i < len; ++i)
  37038. if (! CharacterFunctions::isWhitespace (line [i]))
  37039. return i;
  37040. return 0;
  37041. }
  37042. }
  37043. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37044. {
  37045. newTransaction();
  37046. int index = CodeEditorHelpers::findFirstNonWhitespaceChar (caretPos.getLineText());
  37047. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37048. index = 0;
  37049. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37050. }
  37051. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37052. {
  37053. newTransaction();
  37054. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37055. }
  37056. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37057. {
  37058. newTransaction();
  37059. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37060. }
  37061. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37062. {
  37063. if (moveInWholeWordSteps)
  37064. {
  37065. cut(); // in case something is already highlighted
  37066. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37067. }
  37068. else
  37069. {
  37070. if (selectionStart == selectionEnd)
  37071. selectionStart.moveBy (-1);
  37072. }
  37073. cut();
  37074. }
  37075. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37076. {
  37077. if (moveInWholeWordSteps)
  37078. {
  37079. cut(); // in case something is already highlighted
  37080. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37081. }
  37082. else
  37083. {
  37084. if (selectionStart == selectionEnd)
  37085. selectionEnd.moveBy (1);
  37086. else
  37087. newTransaction();
  37088. }
  37089. cut();
  37090. }
  37091. void CodeEditorComponent::selectAll()
  37092. {
  37093. newTransaction();
  37094. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37095. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37096. }
  37097. void CodeEditorComponent::undo()
  37098. {
  37099. document.undo();
  37100. scrollToKeepCaretOnScreen();
  37101. }
  37102. void CodeEditorComponent::redo()
  37103. {
  37104. document.redo();
  37105. scrollToKeepCaretOnScreen();
  37106. }
  37107. void CodeEditorComponent::newTransaction()
  37108. {
  37109. document.newTransaction();
  37110. startTimer (600);
  37111. }
  37112. void CodeEditorComponent::timerCallback()
  37113. {
  37114. newTransaction();
  37115. }
  37116. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37117. {
  37118. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37119. }
  37120. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37121. {
  37122. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37123. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37124. }
  37125. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37126. {
  37127. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37128. CodeDocument::Position (&document, range.getEnd()));
  37129. }
  37130. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37131. {
  37132. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37133. const bool shiftDown = key.getModifiers().isShiftDown();
  37134. if (key.isKeyCode (KeyPress::leftKey))
  37135. {
  37136. cursorLeft (moveInWholeWordSteps, shiftDown);
  37137. }
  37138. else if (key.isKeyCode (KeyPress::rightKey))
  37139. {
  37140. cursorRight (moveInWholeWordSteps, shiftDown);
  37141. }
  37142. else if (key.isKeyCode (KeyPress::upKey))
  37143. {
  37144. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37145. scrollDown();
  37146. #if JUCE_MAC
  37147. else if (key.getModifiers().isCommandDown())
  37148. goToStartOfDocument (shiftDown);
  37149. #endif
  37150. else
  37151. cursorUp (shiftDown);
  37152. }
  37153. else if (key.isKeyCode (KeyPress::downKey))
  37154. {
  37155. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37156. scrollUp();
  37157. #if JUCE_MAC
  37158. else if (key.getModifiers().isCommandDown())
  37159. goToEndOfDocument (shiftDown);
  37160. #endif
  37161. else
  37162. cursorDown (shiftDown);
  37163. }
  37164. else if (key.isKeyCode (KeyPress::pageDownKey))
  37165. {
  37166. pageDown (shiftDown);
  37167. }
  37168. else if (key.isKeyCode (KeyPress::pageUpKey))
  37169. {
  37170. pageUp (shiftDown);
  37171. }
  37172. else if (key.isKeyCode (KeyPress::homeKey))
  37173. {
  37174. if (moveInWholeWordSteps)
  37175. goToStartOfDocument (shiftDown);
  37176. else
  37177. goToStartOfLine (shiftDown);
  37178. }
  37179. else if (key.isKeyCode (KeyPress::endKey))
  37180. {
  37181. if (moveInWholeWordSteps)
  37182. goToEndOfDocument (shiftDown);
  37183. else
  37184. goToEndOfLine (shiftDown);
  37185. }
  37186. else if (key.isKeyCode (KeyPress::backspaceKey))
  37187. {
  37188. backspace (moveInWholeWordSteps);
  37189. }
  37190. else if (key.isKeyCode (KeyPress::deleteKey))
  37191. {
  37192. deleteForward (moveInWholeWordSteps);
  37193. }
  37194. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37195. {
  37196. copy();
  37197. }
  37198. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37199. {
  37200. copyThenCut();
  37201. }
  37202. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37203. {
  37204. paste();
  37205. }
  37206. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37207. {
  37208. undo();
  37209. }
  37210. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37211. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37212. {
  37213. redo();
  37214. }
  37215. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37216. {
  37217. selectAll();
  37218. }
  37219. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37220. {
  37221. insertTabAtCaret();
  37222. }
  37223. else if (key == KeyPress::returnKey)
  37224. {
  37225. newTransaction();
  37226. insertTextAtCaret (document.getNewLineCharacters());
  37227. }
  37228. else if (key.isKeyCode (KeyPress::escapeKey))
  37229. {
  37230. newTransaction();
  37231. }
  37232. else if (key.getTextCharacter() >= ' ')
  37233. {
  37234. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37235. }
  37236. else
  37237. {
  37238. return false;
  37239. }
  37240. return true;
  37241. }
  37242. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37243. {
  37244. newTransaction();
  37245. dragType = notDragging;
  37246. if (! e.mods.isPopupMenu())
  37247. {
  37248. beginDragAutoRepeat (100);
  37249. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37250. }
  37251. else
  37252. {
  37253. /*PopupMenu m;
  37254. addPopupMenuItems (m, &e);
  37255. const int result = m.show();
  37256. if (result != 0)
  37257. performPopupMenuAction (result);
  37258. */
  37259. }
  37260. }
  37261. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37262. {
  37263. if (! e.mods.isPopupMenu())
  37264. moveCaretTo (getPositionAt (e.x, e.y), true);
  37265. }
  37266. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37267. {
  37268. newTransaction();
  37269. beginDragAutoRepeat (0);
  37270. dragType = notDragging;
  37271. }
  37272. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37273. {
  37274. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37275. CodeDocument::Position tokenEnd (tokenStart);
  37276. if (e.getNumberOfClicks() > 2)
  37277. {
  37278. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37279. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37280. }
  37281. else
  37282. {
  37283. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37284. tokenEnd.moveBy (1);
  37285. tokenStart = tokenEnd;
  37286. while (tokenStart.getIndexInLine() > 0
  37287. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37288. tokenStart.moveBy (-1);
  37289. }
  37290. moveCaretTo (tokenEnd, false);
  37291. moveCaretTo (tokenStart, true);
  37292. }
  37293. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37294. {
  37295. if ((verticalScrollBar.isVisible() && wheelIncrementY != 0)
  37296. || (horizontalScrollBar.isVisible() && wheelIncrementX != 0))
  37297. {
  37298. verticalScrollBar.mouseWheelMove (e, 0, wheelIncrementY);
  37299. horizontalScrollBar.mouseWheelMove (e, wheelIncrementX, 0);
  37300. }
  37301. else
  37302. {
  37303. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37304. }
  37305. }
  37306. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37307. {
  37308. if (scrollBarThatHasMoved == &verticalScrollBar)
  37309. scrollToLineInternal ((int) newRangeStart);
  37310. else
  37311. scrollToColumnInternal (newRangeStart);
  37312. }
  37313. void CodeEditorComponent::focusGained (FocusChangeType)
  37314. {
  37315. caret->updatePosition();
  37316. }
  37317. void CodeEditorComponent::focusLost (FocusChangeType)
  37318. {
  37319. caret->updatePosition();
  37320. }
  37321. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37322. {
  37323. useSpacesForTabs = insertSpaces;
  37324. if (spacesPerTab != numSpaces)
  37325. {
  37326. spacesPerTab = numSpaces;
  37327. triggerAsyncUpdate();
  37328. }
  37329. }
  37330. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37331. {
  37332. const String line (document.getLine (lineNum));
  37333. jassert (index <= line.length());
  37334. int col = 0;
  37335. for (int i = 0; i < index; ++i)
  37336. {
  37337. if (line[i] != '\t')
  37338. ++col;
  37339. else
  37340. col += getTabSize() - (col % getTabSize());
  37341. }
  37342. return col;
  37343. }
  37344. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37345. {
  37346. const String line (document.getLine (lineNum));
  37347. const int lineLength = line.length();
  37348. int i, col = 0;
  37349. for (i = 0; i < lineLength; ++i)
  37350. {
  37351. if (line[i] != '\t')
  37352. ++col;
  37353. else
  37354. col += getTabSize() - (col % getTabSize());
  37355. if (col > column)
  37356. break;
  37357. }
  37358. return i;
  37359. }
  37360. void CodeEditorComponent::setFont (const Font& newFont)
  37361. {
  37362. font = newFont;
  37363. charWidth = font.getStringWidthFloat ("0");
  37364. lineHeight = roundToInt (font.getHeight());
  37365. resized();
  37366. }
  37367. void CodeEditorComponent::resetToDefaultColours()
  37368. {
  37369. coloursForTokenCategories.clear();
  37370. if (codeTokeniser != 0)
  37371. {
  37372. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37373. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37374. }
  37375. }
  37376. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37377. {
  37378. jassert (tokenType < 256);
  37379. while (coloursForTokenCategories.size() < tokenType)
  37380. coloursForTokenCategories.add (Colours::black);
  37381. coloursForTokenCategories.set (tokenType, colour);
  37382. repaint();
  37383. }
  37384. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37385. {
  37386. if (! isPositiveAndBelow (tokenType, coloursForTokenCategories.size()))
  37387. return findColour (CodeEditorComponent::defaultTextColourId);
  37388. return coloursForTokenCategories.getReference (tokenType);
  37389. }
  37390. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37391. {
  37392. int i;
  37393. for (i = cachedIterators.size(); --i >= 0;)
  37394. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37395. break;
  37396. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37397. }
  37398. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37399. {
  37400. const int maxNumCachedPositions = 5000;
  37401. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37402. if (cachedIterators.size() == 0)
  37403. cachedIterators.add (new CodeDocument::Iterator (&document));
  37404. if (codeTokeniser == 0)
  37405. return;
  37406. for (;;)
  37407. {
  37408. CodeDocument::Iterator* last = cachedIterators.getLast();
  37409. if (last->getLine() >= maxLineNum)
  37410. break;
  37411. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37412. cachedIterators.add (t);
  37413. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37414. for (;;)
  37415. {
  37416. codeTokeniser->readNextToken (*t);
  37417. if (t->getLine() >= targetLine)
  37418. break;
  37419. if (t->isEOF())
  37420. return;
  37421. }
  37422. }
  37423. }
  37424. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37425. {
  37426. if (codeTokeniser == 0)
  37427. return;
  37428. for (int i = cachedIterators.size(); --i >= 0;)
  37429. {
  37430. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37431. if (t->getPosition() <= position)
  37432. {
  37433. source = *t;
  37434. break;
  37435. }
  37436. }
  37437. while (source.getPosition() < position)
  37438. {
  37439. const CodeDocument::Iterator original (source);
  37440. codeTokeniser->readNextToken (source);
  37441. if (source.getPosition() > position || source.isEOF())
  37442. {
  37443. source = original;
  37444. break;
  37445. }
  37446. }
  37447. }
  37448. END_JUCE_NAMESPACE
  37449. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37450. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37451. BEGIN_JUCE_NAMESPACE
  37452. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37453. {
  37454. }
  37455. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37456. {
  37457. }
  37458. namespace CppTokeniser
  37459. {
  37460. bool isIdentifierStart (const juce_wchar c) throw()
  37461. {
  37462. return CharacterFunctions::isLetter (c)
  37463. || c == '_' || c == '@';
  37464. }
  37465. bool isIdentifierBody (const juce_wchar c) throw()
  37466. {
  37467. return CharacterFunctions::isLetterOrDigit (c)
  37468. || c == '_' || c == '@';
  37469. }
  37470. bool isReservedKeyword (String::CharPointerType token, const int tokenLength) throw()
  37471. {
  37472. static const char* const keywords2Char[] =
  37473. { "if", "do", "or", "id", 0 };
  37474. static const char* const keywords3Char[] =
  37475. { "for", "int", "new", "try", "xor", "and", "asm", "not", 0 };
  37476. static const char* const keywords4Char[] =
  37477. { "bool", "void", "this", "true", "long", "else", "char",
  37478. "enum", "case", "goto", "auto", 0 };
  37479. static const char* const keywords5Char[] =
  37480. { "while", "bitor", "break", "catch", "class", "compl", "const", "false",
  37481. "float", "short", "throw", "union", "using", "or_eq", 0 };
  37482. static const char* const keywords6Char[] =
  37483. { "return", "struct", "and_eq", "bitand", "delete", "double", "extern",
  37484. "friend", "inline", "not_eq", "public", "sizeof", "static", "signed",
  37485. "switch", "typeid", "wchar_t", "xor_eq", 0};
  37486. static const char* const keywordsOther[] =
  37487. { "const_cast", "continue", "default", "explicit", "mutable", "namespace",
  37488. "operator", "private", "protected", "register", "reinterpret_cast", "static_cast",
  37489. "template", "typedef", "typename", "unsigned", "virtual", "volatile",
  37490. "@implementation", "@interface", "@end", "@synthesize", "@dynamic", "@public",
  37491. "@private", "@property", "@protected", "@class", 0 };
  37492. const char* const* k;
  37493. switch (tokenLength)
  37494. {
  37495. case 2: k = keywords2Char; break;
  37496. case 3: k = keywords3Char; break;
  37497. case 4: k = keywords4Char; break;
  37498. case 5: k = keywords5Char; break;
  37499. case 6: k = keywords6Char; break;
  37500. default:
  37501. if (tokenLength < 2 || tokenLength > 16)
  37502. return false;
  37503. k = keywordsOther;
  37504. break;
  37505. }
  37506. int i = 0;
  37507. while (k[i] != 0)
  37508. {
  37509. if (token.compare (CharPointer_ASCII (k[i])) == 0)
  37510. return true;
  37511. ++i;
  37512. }
  37513. return false;
  37514. }
  37515. int parseIdentifier (CodeDocument::Iterator& source) throw()
  37516. {
  37517. int tokenLength = 0;
  37518. juce_wchar possibleIdentifier [19];
  37519. while (isIdentifierBody (source.peekNextChar()))
  37520. {
  37521. const juce_wchar c = source.nextChar();
  37522. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37523. possibleIdentifier [tokenLength] = c;
  37524. ++tokenLength;
  37525. }
  37526. if (tokenLength > 1 && tokenLength <= 16)
  37527. {
  37528. possibleIdentifier [tokenLength] = 0;
  37529. if (isReservedKeyword (CharPointer_UTF32 (possibleIdentifier), tokenLength))
  37530. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37531. }
  37532. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37533. }
  37534. bool skipNumberSuffix (CodeDocument::Iterator& source)
  37535. {
  37536. const juce_wchar c = source.peekNextChar();
  37537. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37538. source.skip();
  37539. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37540. return false;
  37541. return true;
  37542. }
  37543. bool isHexDigit (const juce_wchar c) throw()
  37544. {
  37545. return (c >= '0' && c <= '9')
  37546. || (c >= 'a' && c <= 'f')
  37547. || (c >= 'A' && c <= 'F');
  37548. }
  37549. bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37550. {
  37551. if (source.nextChar() != '0')
  37552. return false;
  37553. juce_wchar c = source.nextChar();
  37554. if (c != 'x' && c != 'X')
  37555. return false;
  37556. int numDigits = 0;
  37557. while (isHexDigit (source.peekNextChar()))
  37558. {
  37559. ++numDigits;
  37560. source.skip();
  37561. }
  37562. if (numDigits == 0)
  37563. return false;
  37564. return skipNumberSuffix (source);
  37565. }
  37566. bool isOctalDigit (const juce_wchar c) throw()
  37567. {
  37568. return c >= '0' && c <= '7';
  37569. }
  37570. bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37571. {
  37572. if (source.nextChar() != '0')
  37573. return false;
  37574. if (! isOctalDigit (source.nextChar()))
  37575. return false;
  37576. while (isOctalDigit (source.peekNextChar()))
  37577. source.skip();
  37578. return skipNumberSuffix (source);
  37579. }
  37580. bool isDecimalDigit (const juce_wchar c) throw()
  37581. {
  37582. return c >= '0' && c <= '9';
  37583. }
  37584. bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37585. {
  37586. int numChars = 0;
  37587. while (isDecimalDigit (source.peekNextChar()))
  37588. {
  37589. ++numChars;
  37590. source.skip();
  37591. }
  37592. if (numChars == 0)
  37593. return false;
  37594. return skipNumberSuffix (source);
  37595. }
  37596. bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37597. {
  37598. int numDigits = 0;
  37599. while (isDecimalDigit (source.peekNextChar()))
  37600. {
  37601. source.skip();
  37602. ++numDigits;
  37603. }
  37604. const bool hasPoint = (source.peekNextChar() == '.');
  37605. if (hasPoint)
  37606. {
  37607. source.skip();
  37608. while (isDecimalDigit (source.peekNextChar()))
  37609. {
  37610. source.skip();
  37611. ++numDigits;
  37612. }
  37613. }
  37614. if (numDigits == 0)
  37615. return false;
  37616. juce_wchar c = source.peekNextChar();
  37617. const bool hasExponent = (c == 'e' || c == 'E');
  37618. if (hasExponent)
  37619. {
  37620. source.skip();
  37621. c = source.peekNextChar();
  37622. if (c == '+' || c == '-')
  37623. source.skip();
  37624. int numExpDigits = 0;
  37625. while (isDecimalDigit (source.peekNextChar()))
  37626. {
  37627. source.skip();
  37628. ++numExpDigits;
  37629. }
  37630. if (numExpDigits == 0)
  37631. return false;
  37632. }
  37633. c = source.peekNextChar();
  37634. if (c == 'f' || c == 'F')
  37635. source.skip();
  37636. else if (! (hasExponent || hasPoint))
  37637. return false;
  37638. return true;
  37639. }
  37640. int parseNumber (CodeDocument::Iterator& source)
  37641. {
  37642. const CodeDocument::Iterator original (source);
  37643. if (parseFloatLiteral (source))
  37644. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37645. source = original;
  37646. if (parseHexLiteral (source))
  37647. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37648. source = original;
  37649. if (parseOctalLiteral (source))
  37650. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37651. source = original;
  37652. if (parseDecimalLiteral (source))
  37653. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37654. source = original;
  37655. source.skip();
  37656. return CPlusPlusCodeTokeniser::tokenType_error;
  37657. }
  37658. void skipQuotedString (CodeDocument::Iterator& source) throw()
  37659. {
  37660. const juce_wchar quote = source.nextChar();
  37661. for (;;)
  37662. {
  37663. const juce_wchar c = source.nextChar();
  37664. if (c == quote || c == 0)
  37665. break;
  37666. if (c == '\\')
  37667. source.skip();
  37668. }
  37669. }
  37670. void skipComment (CodeDocument::Iterator& source) throw()
  37671. {
  37672. bool lastWasStar = false;
  37673. for (;;)
  37674. {
  37675. const juce_wchar c = source.nextChar();
  37676. if (c == 0 || (c == '/' && lastWasStar))
  37677. break;
  37678. lastWasStar = (c == '*');
  37679. }
  37680. }
  37681. }
  37682. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37683. {
  37684. int result = tokenType_error;
  37685. source.skipWhitespace();
  37686. juce_wchar firstChar = source.peekNextChar();
  37687. switch (firstChar)
  37688. {
  37689. case 0:
  37690. source.skip();
  37691. break;
  37692. case '0':
  37693. case '1':
  37694. case '2':
  37695. case '3':
  37696. case '4':
  37697. case '5':
  37698. case '6':
  37699. case '7':
  37700. case '8':
  37701. case '9':
  37702. result = CppTokeniser::parseNumber (source);
  37703. break;
  37704. case '.':
  37705. result = CppTokeniser::parseNumber (source);
  37706. if (result == tokenType_error)
  37707. result = tokenType_punctuation;
  37708. break;
  37709. case ',':
  37710. case ';':
  37711. case ':':
  37712. source.skip();
  37713. result = tokenType_punctuation;
  37714. break;
  37715. case '(':
  37716. case ')':
  37717. case '{':
  37718. case '}':
  37719. case '[':
  37720. case ']':
  37721. source.skip();
  37722. result = tokenType_bracket;
  37723. break;
  37724. case '"':
  37725. case '\'':
  37726. CppTokeniser::skipQuotedString (source);
  37727. result = tokenType_stringLiteral;
  37728. break;
  37729. case '+':
  37730. result = tokenType_operator;
  37731. source.skip();
  37732. if (source.peekNextChar() == '+')
  37733. source.skip();
  37734. else if (source.peekNextChar() == '=')
  37735. source.skip();
  37736. break;
  37737. case '-':
  37738. source.skip();
  37739. result = CppTokeniser::parseNumber (source);
  37740. if (result == tokenType_error)
  37741. {
  37742. result = tokenType_operator;
  37743. if (source.peekNextChar() == '-')
  37744. source.skip();
  37745. else if (source.peekNextChar() == '=')
  37746. source.skip();
  37747. }
  37748. break;
  37749. case '*':
  37750. case '%':
  37751. case '=':
  37752. case '!':
  37753. result = tokenType_operator;
  37754. source.skip();
  37755. if (source.peekNextChar() == '=')
  37756. source.skip();
  37757. break;
  37758. case '/':
  37759. result = tokenType_operator;
  37760. source.skip();
  37761. if (source.peekNextChar() == '=')
  37762. {
  37763. source.skip();
  37764. }
  37765. else if (source.peekNextChar() == '/')
  37766. {
  37767. result = tokenType_comment;
  37768. source.skipToEndOfLine();
  37769. }
  37770. else if (source.peekNextChar() == '*')
  37771. {
  37772. source.skip();
  37773. result = tokenType_comment;
  37774. CppTokeniser::skipComment (source);
  37775. }
  37776. break;
  37777. case '?':
  37778. case '~':
  37779. source.skip();
  37780. result = tokenType_operator;
  37781. break;
  37782. case '<':
  37783. source.skip();
  37784. result = tokenType_operator;
  37785. if (source.peekNextChar() == '=')
  37786. {
  37787. source.skip();
  37788. }
  37789. else if (source.peekNextChar() == '<')
  37790. {
  37791. source.skip();
  37792. if (source.peekNextChar() == '=')
  37793. source.skip();
  37794. }
  37795. break;
  37796. case '>':
  37797. source.skip();
  37798. result = tokenType_operator;
  37799. if (source.peekNextChar() == '=')
  37800. {
  37801. source.skip();
  37802. }
  37803. else if (source.peekNextChar() == '<')
  37804. {
  37805. source.skip();
  37806. if (source.peekNextChar() == '=')
  37807. source.skip();
  37808. }
  37809. break;
  37810. case '|':
  37811. source.skip();
  37812. result = tokenType_operator;
  37813. if (source.peekNextChar() == '=')
  37814. {
  37815. source.skip();
  37816. }
  37817. else if (source.peekNextChar() == '|')
  37818. {
  37819. source.skip();
  37820. if (source.peekNextChar() == '=')
  37821. source.skip();
  37822. }
  37823. break;
  37824. case '&':
  37825. source.skip();
  37826. result = tokenType_operator;
  37827. if (source.peekNextChar() == '=')
  37828. {
  37829. source.skip();
  37830. }
  37831. else if (source.peekNextChar() == '&')
  37832. {
  37833. source.skip();
  37834. if (source.peekNextChar() == '=')
  37835. source.skip();
  37836. }
  37837. break;
  37838. case '^':
  37839. source.skip();
  37840. result = tokenType_operator;
  37841. if (source.peekNextChar() == '=')
  37842. {
  37843. source.skip();
  37844. }
  37845. else if (source.peekNextChar() == '^')
  37846. {
  37847. source.skip();
  37848. if (source.peekNextChar() == '=')
  37849. source.skip();
  37850. }
  37851. break;
  37852. case '#':
  37853. result = tokenType_preprocessor;
  37854. source.skipToEndOfLine();
  37855. break;
  37856. default:
  37857. if (CppTokeniser::isIdentifierStart (firstChar))
  37858. result = CppTokeniser::parseIdentifier (source);
  37859. else
  37860. source.skip();
  37861. break;
  37862. }
  37863. return result;
  37864. }
  37865. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  37866. {
  37867. const char* const types[] =
  37868. {
  37869. "Error",
  37870. "Comment",
  37871. "C++ keyword",
  37872. "Identifier",
  37873. "Integer literal",
  37874. "Float literal",
  37875. "String literal",
  37876. "Operator",
  37877. "Bracket",
  37878. "Punctuation",
  37879. "Preprocessor line",
  37880. 0
  37881. };
  37882. return StringArray (types);
  37883. }
  37884. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  37885. {
  37886. const uint32 colours[] =
  37887. {
  37888. 0xffcc0000, // error
  37889. 0xff00aa00, // comment
  37890. 0xff0000cc, // keyword
  37891. 0xff000000, // identifier
  37892. 0xff880000, // int literal
  37893. 0xff885500, // float literal
  37894. 0xff990099, // string literal
  37895. 0xff225500, // operator
  37896. 0xff000055, // bracket
  37897. 0xff004400, // punctuation
  37898. 0xff660000 // preprocessor
  37899. };
  37900. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  37901. return Colour (colours [tokenType]);
  37902. return Colours::black;
  37903. }
  37904. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  37905. {
  37906. return CppTokeniser::isReservedKeyword (token.getCharPointer(), token.length());
  37907. }
  37908. END_JUCE_NAMESPACE
  37909. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37910. /*** Start of inlined file: juce_ComboBox.cpp ***/
  37911. BEGIN_JUCE_NAMESPACE
  37912. ComboBox::ItemInfo::ItemInfo (const String& name_, int itemId_, bool isEnabled_, bool isHeading_)
  37913. : name (name_), itemId (itemId_), isEnabled (isEnabled_), isHeading (isHeading_)
  37914. {
  37915. }
  37916. bool ComboBox::ItemInfo::isSeparator() const throw()
  37917. {
  37918. return name.isEmpty();
  37919. }
  37920. bool ComboBox::ItemInfo::isRealItem() const throw()
  37921. {
  37922. return ! (isHeading || name.isEmpty());
  37923. }
  37924. ComboBox::ComboBox (const String& name)
  37925. : Component (name),
  37926. lastCurrentId (0),
  37927. isButtonDown (false),
  37928. separatorPending (false),
  37929. menuActive (false),
  37930. noChoicesMessage (TRANS("(no choices)"))
  37931. {
  37932. setRepaintsOnMouseActivity (true);
  37933. lookAndFeelChanged();
  37934. currentId.addListener (this);
  37935. }
  37936. ComboBox::~ComboBox()
  37937. {
  37938. currentId.removeListener (this);
  37939. if (menuActive)
  37940. PopupMenu::dismissAllActiveMenus();
  37941. label = 0;
  37942. }
  37943. void ComboBox::setEditableText (const bool isEditable)
  37944. {
  37945. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  37946. {
  37947. label->setEditable (isEditable, isEditable, false);
  37948. setWantsKeyboardFocus (! isEditable);
  37949. resized();
  37950. }
  37951. }
  37952. bool ComboBox::isTextEditable() const throw()
  37953. {
  37954. return label->isEditable();
  37955. }
  37956. void ComboBox::setJustificationType (const Justification& justification)
  37957. {
  37958. label->setJustificationType (justification);
  37959. }
  37960. const Justification ComboBox::getJustificationType() const throw()
  37961. {
  37962. return label->getJustificationType();
  37963. }
  37964. void ComboBox::setTooltip (const String& newTooltip)
  37965. {
  37966. SettableTooltipClient::setTooltip (newTooltip);
  37967. label->setTooltip (newTooltip);
  37968. }
  37969. void ComboBox::addItem (const String& newItemText, const int newItemId)
  37970. {
  37971. // you can't add empty strings to the list..
  37972. jassert (newItemText.isNotEmpty());
  37973. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  37974. jassert (newItemId != 0);
  37975. // you shouldn't use duplicate item IDs!
  37976. jassert (getItemForId (newItemId) == 0);
  37977. if (newItemText.isNotEmpty() && newItemId != 0)
  37978. {
  37979. if (separatorPending)
  37980. {
  37981. separatorPending = false;
  37982. items.add (new ItemInfo (String::empty, 0, false, false));
  37983. }
  37984. items.add (new ItemInfo (newItemText, newItemId, true, false));
  37985. }
  37986. }
  37987. void ComboBox::addSeparator()
  37988. {
  37989. separatorPending = (items.size() > 0);
  37990. }
  37991. void ComboBox::addSectionHeading (const String& headingName)
  37992. {
  37993. // you can't add empty strings to the list..
  37994. jassert (headingName.isNotEmpty());
  37995. if (headingName.isNotEmpty())
  37996. {
  37997. if (separatorPending)
  37998. {
  37999. separatorPending = false;
  38000. items.add (new ItemInfo (String::empty, 0, false, false));
  38001. }
  38002. items.add (new ItemInfo (headingName, 0, true, true));
  38003. }
  38004. }
  38005. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  38006. {
  38007. ItemInfo* const item = getItemForId (itemId);
  38008. if (item != 0)
  38009. item->isEnabled = shouldBeEnabled;
  38010. }
  38011. bool ComboBox::isItemEnabled (int itemId) const throw()
  38012. {
  38013. const ItemInfo* const item = getItemForId (itemId);
  38014. return item != 0 && item->isEnabled;
  38015. }
  38016. void ComboBox::changeItemText (const int itemId, const String& newText)
  38017. {
  38018. ItemInfo* const item = getItemForId (itemId);
  38019. jassert (item != 0);
  38020. if (item != 0)
  38021. item->name = newText;
  38022. }
  38023. void ComboBox::clear (const bool dontSendChangeMessage)
  38024. {
  38025. items.clear();
  38026. separatorPending = false;
  38027. if (! label->isEditable())
  38028. setSelectedItemIndex (-1, dontSendChangeMessage);
  38029. }
  38030. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38031. {
  38032. if (itemId != 0)
  38033. {
  38034. for (int i = items.size(); --i >= 0;)
  38035. if (items.getUnchecked(i)->itemId == itemId)
  38036. return items.getUnchecked(i);
  38037. }
  38038. return 0;
  38039. }
  38040. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38041. {
  38042. for (int n = 0, i = 0; i < items.size(); ++i)
  38043. {
  38044. ItemInfo* const item = items.getUnchecked(i);
  38045. if (item->isRealItem())
  38046. if (n++ == index)
  38047. return item;
  38048. }
  38049. return 0;
  38050. }
  38051. int ComboBox::getNumItems() const throw()
  38052. {
  38053. int n = 0;
  38054. for (int i = items.size(); --i >= 0;)
  38055. if (items.getUnchecked(i)->isRealItem())
  38056. ++n;
  38057. return n;
  38058. }
  38059. const String ComboBox::getItemText (const int index) const
  38060. {
  38061. const ItemInfo* const item = getItemForIndex (index);
  38062. return item != 0 ? item->name : String::empty;
  38063. }
  38064. int ComboBox::getItemId (const int index) const throw()
  38065. {
  38066. const ItemInfo* const item = getItemForIndex (index);
  38067. return item != 0 ? item->itemId : 0;
  38068. }
  38069. int ComboBox::indexOfItemId (const int itemId) const throw()
  38070. {
  38071. for (int n = 0, i = 0; i < items.size(); ++i)
  38072. {
  38073. const ItemInfo* const item = items.getUnchecked(i);
  38074. if (item->isRealItem())
  38075. {
  38076. if (item->itemId == itemId)
  38077. return n;
  38078. ++n;
  38079. }
  38080. }
  38081. return -1;
  38082. }
  38083. int ComboBox::getSelectedItemIndex() const
  38084. {
  38085. int index = indexOfItemId (currentId.getValue());
  38086. if (getText() != getItemText (index))
  38087. index = -1;
  38088. return index;
  38089. }
  38090. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38091. {
  38092. setSelectedId (getItemId (index), dontSendChangeMessage);
  38093. }
  38094. int ComboBox::getSelectedId() const throw()
  38095. {
  38096. const ItemInfo* const item = getItemForId (currentId.getValue());
  38097. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38098. }
  38099. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38100. {
  38101. const ItemInfo* const item = getItemForId (newItemId);
  38102. const String newItemText (item != 0 ? item->name : String::empty);
  38103. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38104. {
  38105. if (! dontSendChangeMessage)
  38106. triggerAsyncUpdate();
  38107. label->setText (newItemText, false);
  38108. lastCurrentId = newItemId;
  38109. currentId = newItemId;
  38110. repaint(); // for the benefit of the 'none selected' text
  38111. }
  38112. }
  38113. bool ComboBox::selectIfEnabled (const int index)
  38114. {
  38115. const ItemInfo* const item = getItemForIndex (index);
  38116. if (item != 0 && item->isEnabled)
  38117. {
  38118. setSelectedItemIndex (index);
  38119. return true;
  38120. }
  38121. return false;
  38122. }
  38123. void ComboBox::valueChanged (Value&)
  38124. {
  38125. if (lastCurrentId != (int) currentId.getValue())
  38126. setSelectedId (currentId.getValue(), false);
  38127. }
  38128. const String ComboBox::getText() const
  38129. {
  38130. return label->getText();
  38131. }
  38132. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38133. {
  38134. for (int i = items.size(); --i >= 0;)
  38135. {
  38136. const ItemInfo* const item = items.getUnchecked(i);
  38137. if (item->isRealItem()
  38138. && item->name == newText)
  38139. {
  38140. setSelectedId (item->itemId, dontSendChangeMessage);
  38141. return;
  38142. }
  38143. }
  38144. lastCurrentId = 0;
  38145. currentId = 0;
  38146. if (label->getText() != newText)
  38147. {
  38148. label->setText (newText, false);
  38149. if (! dontSendChangeMessage)
  38150. triggerAsyncUpdate();
  38151. }
  38152. repaint();
  38153. }
  38154. void ComboBox::showEditor()
  38155. {
  38156. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38157. label->showEditor();
  38158. }
  38159. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38160. {
  38161. if (textWhenNothingSelected != newMessage)
  38162. {
  38163. textWhenNothingSelected = newMessage;
  38164. repaint();
  38165. }
  38166. }
  38167. const String ComboBox::getTextWhenNothingSelected() const
  38168. {
  38169. return textWhenNothingSelected;
  38170. }
  38171. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38172. {
  38173. noChoicesMessage = newMessage;
  38174. }
  38175. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38176. {
  38177. return noChoicesMessage;
  38178. }
  38179. void ComboBox::paint (Graphics& g)
  38180. {
  38181. getLookAndFeel().drawComboBox (g, getWidth(), getHeight(), isButtonDown,
  38182. label->getRight(), 0, getWidth() - label->getRight(), getHeight(),
  38183. *this);
  38184. if (textWhenNothingSelected.isNotEmpty()
  38185. && label->getText().isEmpty()
  38186. && ! label->isBeingEdited())
  38187. {
  38188. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38189. g.setFont (label->getFont());
  38190. g.drawFittedText (textWhenNothingSelected,
  38191. label->getX() + 2, label->getY() + 1,
  38192. label->getWidth() - 4, label->getHeight() - 2,
  38193. label->getJustificationType(),
  38194. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38195. }
  38196. }
  38197. void ComboBox::resized()
  38198. {
  38199. if (getHeight() > 0 && getWidth() > 0)
  38200. getLookAndFeel().positionComboBoxText (*this, *label);
  38201. }
  38202. void ComboBox::enablementChanged()
  38203. {
  38204. repaint();
  38205. }
  38206. void ComboBox::lookAndFeelChanged()
  38207. {
  38208. repaint();
  38209. {
  38210. ScopedPointer <Label> newLabel (getLookAndFeel().createComboBoxTextBox (*this));
  38211. jassert (newLabel != 0);
  38212. if (label != 0)
  38213. {
  38214. newLabel->setEditable (label->isEditable());
  38215. newLabel->setJustificationType (label->getJustificationType());
  38216. newLabel->setTooltip (label->getTooltip());
  38217. newLabel->setText (label->getText(), false);
  38218. }
  38219. label = newLabel;
  38220. }
  38221. addAndMakeVisible (label);
  38222. label->addListener (this);
  38223. label->addMouseListener (this, false);
  38224. label->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38225. label->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38226. label->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38227. label->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38228. label->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38229. label->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38230. resized();
  38231. }
  38232. void ComboBox::colourChanged()
  38233. {
  38234. lookAndFeelChanged();
  38235. }
  38236. bool ComboBox::keyPressed (const KeyPress& key)
  38237. {
  38238. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  38239. {
  38240. int index = getSelectedItemIndex() - 1;
  38241. while (index >= 0 && ! selectIfEnabled (index))
  38242. --index;
  38243. return true;
  38244. }
  38245. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  38246. {
  38247. int index = getSelectedItemIndex() + 1;
  38248. while (index < getNumItems() && ! selectIfEnabled (index))
  38249. ++index;
  38250. return true;
  38251. }
  38252. else if (key.isKeyCode (KeyPress::returnKey))
  38253. {
  38254. showPopup();
  38255. return true;
  38256. }
  38257. return false;
  38258. }
  38259. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38260. {
  38261. // only forward key events that aren't used by this component
  38262. return isKeyDown
  38263. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38264. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38265. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38266. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38267. }
  38268. void ComboBox::focusGained (FocusChangeType) { repaint(); }
  38269. void ComboBox::focusLost (FocusChangeType) { repaint(); }
  38270. void ComboBox::labelTextChanged (Label*)
  38271. {
  38272. triggerAsyncUpdate();
  38273. }
  38274. class ComboBox::Callback : public ModalComponentManager::Callback
  38275. {
  38276. public:
  38277. Callback (ComboBox* const box_)
  38278. : box (box_)
  38279. {
  38280. }
  38281. void modalStateFinished (int returnValue)
  38282. {
  38283. if (box != 0)
  38284. {
  38285. box->menuActive = false;
  38286. if (returnValue != 0)
  38287. box->setSelectedId (returnValue);
  38288. }
  38289. }
  38290. private:
  38291. Component::SafePointer<ComboBox> box;
  38292. JUCE_DECLARE_NON_COPYABLE (Callback);
  38293. };
  38294. void ComboBox::showPopup()
  38295. {
  38296. if (! menuActive)
  38297. {
  38298. const int selectedId = getSelectedId();
  38299. PopupMenu menu;
  38300. menu.setLookAndFeel (&getLookAndFeel());
  38301. for (int i = 0; i < items.size(); ++i)
  38302. {
  38303. const ItemInfo* const item = items.getUnchecked(i);
  38304. if (item->isSeparator())
  38305. menu.addSeparator();
  38306. else if (item->isHeading)
  38307. menu.addSectionHeader (item->name);
  38308. else
  38309. menu.addItem (item->itemId, item->name,
  38310. item->isEnabled, item->itemId == selectedId);
  38311. }
  38312. if (items.size() == 0)
  38313. menu.addItem (1, noChoicesMessage, false);
  38314. menuActive = true;
  38315. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  38316. new Callback (this));
  38317. }
  38318. }
  38319. void ComboBox::mouseDown (const MouseEvent& e)
  38320. {
  38321. beginDragAutoRepeat (300);
  38322. isButtonDown = isEnabled() && ! e.mods.isPopupMenu();
  38323. if (isButtonDown && (e.eventComponent == this || ! label->isEditable()))
  38324. showPopup();
  38325. }
  38326. void ComboBox::mouseDrag (const MouseEvent& e)
  38327. {
  38328. beginDragAutoRepeat (50);
  38329. if (isButtonDown && ! e.mouseWasClicked())
  38330. showPopup();
  38331. }
  38332. void ComboBox::mouseUp (const MouseEvent& e2)
  38333. {
  38334. if (isButtonDown)
  38335. {
  38336. isButtonDown = false;
  38337. repaint();
  38338. const MouseEvent e (e2.getEventRelativeTo (this));
  38339. if (reallyContains (e.getPosition(), true)
  38340. && (e2.eventComponent == this || ! label->isEditable()))
  38341. {
  38342. showPopup();
  38343. }
  38344. }
  38345. }
  38346. void ComboBox::addListener (ComboBoxListener* const listener)
  38347. {
  38348. listeners.add (listener);
  38349. }
  38350. void ComboBox::removeListener (ComboBoxListener* const listener)
  38351. {
  38352. listeners.remove (listener);
  38353. }
  38354. void ComboBox::handleAsyncUpdate()
  38355. {
  38356. Component::BailOutChecker checker (this);
  38357. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38358. }
  38359. END_JUCE_NAMESPACE
  38360. /*** End of inlined file: juce_ComboBox.cpp ***/
  38361. /*** Start of inlined file: juce_Label.cpp ***/
  38362. BEGIN_JUCE_NAMESPACE
  38363. Label::Label (const String& componentName,
  38364. const String& labelText)
  38365. : Component (componentName),
  38366. textValue (labelText),
  38367. lastTextValue (labelText),
  38368. font (15.0f),
  38369. justification (Justification::centredLeft),
  38370. ownerComponent (0),
  38371. horizontalBorderSize (5),
  38372. verticalBorderSize (1),
  38373. minimumHorizontalScale (0.7f),
  38374. editSingleClick (false),
  38375. editDoubleClick (false),
  38376. lossOfFocusDiscardsChanges (false)
  38377. {
  38378. setColour (TextEditor::textColourId, Colours::black);
  38379. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38380. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38381. textValue.addListener (this);
  38382. }
  38383. Label::~Label()
  38384. {
  38385. textValue.removeListener (this);
  38386. if (ownerComponent != 0)
  38387. ownerComponent->removeComponentListener (this);
  38388. editor = 0;
  38389. }
  38390. void Label::setText (const String& newText,
  38391. const bool broadcastChangeMessage)
  38392. {
  38393. hideEditor (true);
  38394. if (lastTextValue != newText)
  38395. {
  38396. lastTextValue = newText;
  38397. textValue = newText;
  38398. repaint();
  38399. textWasChanged();
  38400. if (ownerComponent != 0)
  38401. componentMovedOrResized (*ownerComponent, true, true);
  38402. if (broadcastChangeMessage)
  38403. callChangeListeners();
  38404. }
  38405. }
  38406. const String Label::getText (const bool returnActiveEditorContents) const
  38407. {
  38408. return (returnActiveEditorContents && isBeingEdited())
  38409. ? editor->getText()
  38410. : textValue.toString();
  38411. }
  38412. void Label::valueChanged (Value&)
  38413. {
  38414. if (lastTextValue != textValue.toString())
  38415. setText (textValue.toString(), true);
  38416. }
  38417. void Label::setFont (const Font& newFont)
  38418. {
  38419. if (font != newFont)
  38420. {
  38421. font = newFont;
  38422. repaint();
  38423. }
  38424. }
  38425. const Font& Label::getFont() const throw()
  38426. {
  38427. return font;
  38428. }
  38429. void Label::setEditable (const bool editOnSingleClick,
  38430. const bool editOnDoubleClick,
  38431. const bool lossOfFocusDiscardsChanges_)
  38432. {
  38433. editSingleClick = editOnSingleClick;
  38434. editDoubleClick = editOnDoubleClick;
  38435. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38436. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38437. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38438. }
  38439. void Label::setJustificationType (const Justification& newJustification)
  38440. {
  38441. if (justification != newJustification)
  38442. {
  38443. justification = newJustification;
  38444. repaint();
  38445. }
  38446. }
  38447. void Label::setBorderSize (int h, int v)
  38448. {
  38449. if (horizontalBorderSize != h || verticalBorderSize != v)
  38450. {
  38451. horizontalBorderSize = h;
  38452. verticalBorderSize = v;
  38453. repaint();
  38454. }
  38455. }
  38456. Component* Label::getAttachedComponent() const
  38457. {
  38458. return static_cast<Component*> (ownerComponent);
  38459. }
  38460. void Label::attachToComponent (Component* owner,
  38461. const bool onLeft)
  38462. {
  38463. if (ownerComponent != 0)
  38464. ownerComponent->removeComponentListener (this);
  38465. ownerComponent = owner;
  38466. leftOfOwnerComp = onLeft;
  38467. if (ownerComponent != 0)
  38468. {
  38469. setVisible (owner->isVisible());
  38470. ownerComponent->addComponentListener (this);
  38471. componentParentHierarchyChanged (*ownerComponent);
  38472. componentMovedOrResized (*ownerComponent, true, true);
  38473. }
  38474. }
  38475. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38476. {
  38477. if (leftOfOwnerComp)
  38478. {
  38479. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38480. component.getHeight());
  38481. setTopRightPosition (component.getX(), component.getY());
  38482. }
  38483. else
  38484. {
  38485. setSize (component.getWidth(),
  38486. 8 + roundToInt (getFont().getHeight()));
  38487. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38488. }
  38489. }
  38490. void Label::componentParentHierarchyChanged (Component& component)
  38491. {
  38492. if (component.getParentComponent() != 0)
  38493. component.getParentComponent()->addChildComponent (this);
  38494. }
  38495. void Label::componentVisibilityChanged (Component& component)
  38496. {
  38497. setVisible (component.isVisible());
  38498. }
  38499. void Label::textWasEdited()
  38500. {
  38501. }
  38502. void Label::textWasChanged()
  38503. {
  38504. }
  38505. void Label::showEditor()
  38506. {
  38507. if (editor == 0)
  38508. {
  38509. addAndMakeVisible (editor = createEditorComponent());
  38510. editor->setText (getText(), false);
  38511. editor->addListener (this);
  38512. editor->grabKeyboardFocus();
  38513. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38514. editor->addListener (this);
  38515. resized();
  38516. repaint();
  38517. editorShown (editor);
  38518. enterModalState (false);
  38519. editor->grabKeyboardFocus();
  38520. }
  38521. }
  38522. void Label::editorShown (TextEditor*)
  38523. {
  38524. }
  38525. void Label::editorAboutToBeHidden (TextEditor*)
  38526. {
  38527. }
  38528. bool Label::updateFromTextEditorContents (TextEditor& ed)
  38529. {
  38530. const String newText (ed.getText());
  38531. if (textValue.toString() != newText)
  38532. {
  38533. lastTextValue = newText;
  38534. textValue = newText;
  38535. repaint();
  38536. textWasChanged();
  38537. if (ownerComponent != 0)
  38538. componentMovedOrResized (*ownerComponent, true, true);
  38539. return true;
  38540. }
  38541. return false;
  38542. }
  38543. void Label::hideEditor (const bool discardCurrentEditorContents)
  38544. {
  38545. if (editor != 0)
  38546. {
  38547. WeakReference<Component> deletionChecker (this);
  38548. ScopedPointer<TextEditor> outgoingEditor (editor);
  38549. editorAboutToBeHidden (outgoingEditor);
  38550. const bool changed = (! discardCurrentEditorContents)
  38551. && updateFromTextEditorContents (*outgoingEditor);
  38552. outgoingEditor = 0;
  38553. repaint();
  38554. if (changed)
  38555. textWasEdited();
  38556. if (deletionChecker != 0)
  38557. exitModalState (0);
  38558. if (changed && deletionChecker != 0)
  38559. callChangeListeners();
  38560. }
  38561. }
  38562. void Label::inputAttemptWhenModal()
  38563. {
  38564. if (editor != 0)
  38565. {
  38566. if (lossOfFocusDiscardsChanges)
  38567. textEditorEscapeKeyPressed (*editor);
  38568. else
  38569. textEditorReturnKeyPressed (*editor);
  38570. }
  38571. }
  38572. bool Label::isBeingEdited() const throw()
  38573. {
  38574. return editor != 0;
  38575. }
  38576. TextEditor* Label::createEditorComponent()
  38577. {
  38578. TextEditor* const ed = new TextEditor (getName());
  38579. ed->setFont (font);
  38580. // copy these colours from our own settings..
  38581. const int cols[] = { TextEditor::backgroundColourId,
  38582. TextEditor::textColourId,
  38583. TextEditor::highlightColourId,
  38584. TextEditor::highlightedTextColourId,
  38585. TextEditor::caretColourId,
  38586. TextEditor::outlineColourId,
  38587. TextEditor::focusedOutlineColourId,
  38588. TextEditor::shadowColourId };
  38589. for (int i = 0; i < numElementsInArray (cols); ++i)
  38590. ed->setColour (cols[i], findColour (cols[i]));
  38591. return ed;
  38592. }
  38593. void Label::paint (Graphics& g)
  38594. {
  38595. getLookAndFeel().drawLabel (g, *this);
  38596. }
  38597. void Label::mouseUp (const MouseEvent& e)
  38598. {
  38599. if (editSingleClick
  38600. && e.mouseWasClicked()
  38601. && contains (e.getPosition())
  38602. && ! e.mods.isPopupMenu())
  38603. {
  38604. showEditor();
  38605. }
  38606. }
  38607. void Label::mouseDoubleClick (const MouseEvent& e)
  38608. {
  38609. if (editDoubleClick && ! e.mods.isPopupMenu())
  38610. showEditor();
  38611. }
  38612. void Label::resized()
  38613. {
  38614. if (editor != 0)
  38615. editor->setBoundsInset (BorderSize<int> (0));
  38616. }
  38617. void Label::focusGained (FocusChangeType cause)
  38618. {
  38619. if (editSingleClick && cause == focusChangedByTabKey)
  38620. showEditor();
  38621. }
  38622. void Label::enablementChanged()
  38623. {
  38624. repaint();
  38625. }
  38626. void Label::colourChanged()
  38627. {
  38628. repaint();
  38629. }
  38630. void Label::setMinimumHorizontalScale (const float newScale)
  38631. {
  38632. if (minimumHorizontalScale != newScale)
  38633. {
  38634. minimumHorizontalScale = newScale;
  38635. repaint();
  38636. }
  38637. }
  38638. // We'll use a custom focus traverser here to make sure focus goes from the
  38639. // text editor to another component rather than back to the label itself.
  38640. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38641. {
  38642. public:
  38643. LabelKeyboardFocusTraverser() {}
  38644. Component* getNextComponent (Component* current)
  38645. {
  38646. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38647. ? current->getParentComponent() : current);
  38648. }
  38649. Component* getPreviousComponent (Component* current)
  38650. {
  38651. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38652. ? current->getParentComponent() : current);
  38653. }
  38654. };
  38655. KeyboardFocusTraverser* Label::createFocusTraverser()
  38656. {
  38657. return new LabelKeyboardFocusTraverser();
  38658. }
  38659. void Label::addListener (LabelListener* const listener)
  38660. {
  38661. listeners.add (listener);
  38662. }
  38663. void Label::removeListener (LabelListener* const listener)
  38664. {
  38665. listeners.remove (listener);
  38666. }
  38667. void Label::callChangeListeners()
  38668. {
  38669. Component::BailOutChecker checker (this);
  38670. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  38671. }
  38672. void Label::textEditorTextChanged (TextEditor& ed)
  38673. {
  38674. if (editor != 0)
  38675. {
  38676. jassert (&ed == editor);
  38677. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38678. {
  38679. if (lossOfFocusDiscardsChanges)
  38680. textEditorEscapeKeyPressed (ed);
  38681. else
  38682. textEditorReturnKeyPressed (ed);
  38683. }
  38684. }
  38685. }
  38686. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38687. {
  38688. if (editor != 0)
  38689. {
  38690. jassert (&ed == editor);
  38691. const bool changed = updateFromTextEditorContents (ed);
  38692. hideEditor (true);
  38693. if (changed)
  38694. {
  38695. WeakReference<Component> deletionChecker (this);
  38696. textWasEdited();
  38697. if (deletionChecker != 0)
  38698. callChangeListeners();
  38699. }
  38700. }
  38701. }
  38702. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38703. {
  38704. if (editor != 0)
  38705. {
  38706. jassert (&ed == editor);
  38707. (void) ed;
  38708. editor->setText (textValue.toString(), false);
  38709. hideEditor (true);
  38710. }
  38711. }
  38712. void Label::textEditorFocusLost (TextEditor& ed)
  38713. {
  38714. textEditorTextChanged (ed);
  38715. }
  38716. END_JUCE_NAMESPACE
  38717. /*** End of inlined file: juce_Label.cpp ***/
  38718. /*** Start of inlined file: juce_ListBox.cpp ***/
  38719. BEGIN_JUCE_NAMESPACE
  38720. class ListBoxRowComponent : public Component,
  38721. public TooltipClient
  38722. {
  38723. public:
  38724. ListBoxRowComponent (ListBox& owner_)
  38725. : owner (owner_), row (-1),
  38726. selected (false), isDragging (false), selectRowOnMouseUp (false)
  38727. {
  38728. }
  38729. void paint (Graphics& g)
  38730. {
  38731. if (owner.getModel() != 0)
  38732. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  38733. }
  38734. void update (const int row_, const bool selected_)
  38735. {
  38736. if (row != row_ || selected != selected_)
  38737. {
  38738. repaint();
  38739. row = row_;
  38740. selected = selected_;
  38741. }
  38742. if (owner.getModel() != 0)
  38743. {
  38744. customComponent = owner.getModel()->refreshComponentForRow (row_, selected_, customComponent.release());
  38745. if (customComponent != 0)
  38746. {
  38747. addAndMakeVisible (customComponent);
  38748. customComponent->setBounds (getLocalBounds());
  38749. }
  38750. }
  38751. }
  38752. void mouseDown (const MouseEvent& e)
  38753. {
  38754. isDragging = false;
  38755. selectRowOnMouseUp = false;
  38756. if (isEnabled())
  38757. {
  38758. if (! selected)
  38759. {
  38760. owner.selectRowsBasedOnModifierKeys (row, e.mods, false);
  38761. if (owner.getModel() != 0)
  38762. owner.getModel()->listBoxItemClicked (row, e);
  38763. }
  38764. else
  38765. {
  38766. selectRowOnMouseUp = true;
  38767. }
  38768. }
  38769. }
  38770. void mouseUp (const MouseEvent& e)
  38771. {
  38772. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38773. {
  38774. owner.selectRowsBasedOnModifierKeys (row, e.mods, true);
  38775. if (owner.getModel() != 0)
  38776. owner.getModel()->listBoxItemClicked (row, e);
  38777. }
  38778. }
  38779. void mouseDoubleClick (const MouseEvent& e)
  38780. {
  38781. if (owner.getModel() != 0 && isEnabled())
  38782. owner.getModel()->listBoxItemDoubleClicked (row, e);
  38783. }
  38784. void mouseDrag (const MouseEvent& e)
  38785. {
  38786. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38787. {
  38788. const SparseSet<int> selectedRows (owner.getSelectedRows());
  38789. if (selectedRows.size() > 0)
  38790. {
  38791. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38792. if (dragDescription.isNotEmpty())
  38793. {
  38794. isDragging = true;
  38795. owner.startDragAndDrop (e, dragDescription);
  38796. }
  38797. }
  38798. }
  38799. }
  38800. void resized()
  38801. {
  38802. if (customComponent != 0)
  38803. customComponent->setBounds (getLocalBounds());
  38804. }
  38805. const String getTooltip()
  38806. {
  38807. if (owner.getModel() != 0)
  38808. return owner.getModel()->getTooltipForRow (row);
  38809. return String::empty;
  38810. }
  38811. ScopedPointer<Component> customComponent;
  38812. private:
  38813. ListBox& owner;
  38814. int row;
  38815. bool selected, isDragging, selectRowOnMouseUp;
  38816. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBoxRowComponent);
  38817. };
  38818. class ListViewport : public Viewport
  38819. {
  38820. public:
  38821. ListViewport (ListBox& owner_)
  38822. : owner (owner_)
  38823. {
  38824. setWantsKeyboardFocus (false);
  38825. Component* const content = new Component();
  38826. setViewedComponent (content);
  38827. content->addMouseListener (this, false);
  38828. content->setWantsKeyboardFocus (false);
  38829. }
  38830. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  38831. {
  38832. return rows [row % jmax (1, rows.size())];
  38833. }
  38834. ListBoxRowComponent* getComponentForRowIfOnscreen (const int row) const throw()
  38835. {
  38836. return (row >= firstIndex && row < firstIndex + rows.size())
  38837. ? getComponentForRow (row) : 0;
  38838. }
  38839. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  38840. {
  38841. const int index = getIndexOfChildComponent (rowComponent);
  38842. const int num = rows.size();
  38843. for (int i = num; --i >= 0;)
  38844. if (((firstIndex + i) % jmax (1, num)) == index)
  38845. return firstIndex + i;
  38846. return -1;
  38847. }
  38848. void visibleAreaChanged (const Rectangle<int>&)
  38849. {
  38850. updateVisibleArea (true);
  38851. if (owner.getModel() != 0)
  38852. owner.getModel()->listWasScrolled();
  38853. }
  38854. void updateVisibleArea (const bool makeSureItUpdatesContent)
  38855. {
  38856. hasUpdated = false;
  38857. const int newX = getViewedComponent()->getX();
  38858. int newY = getViewedComponent()->getY();
  38859. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  38860. const int newH = owner.totalItems * owner.getRowHeight();
  38861. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  38862. newY = getMaximumVisibleHeight() - newH;
  38863. getViewedComponent()->setBounds (newX, newY, newW, newH);
  38864. if (makeSureItUpdatesContent && ! hasUpdated)
  38865. updateContents();
  38866. }
  38867. void updateContents()
  38868. {
  38869. hasUpdated = true;
  38870. const int rowHeight = owner.getRowHeight();
  38871. if (rowHeight > 0)
  38872. {
  38873. const int y = getViewPositionY();
  38874. const int w = getViewedComponent()->getWidth();
  38875. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  38876. rows.removeRange (numNeeded, rows.size());
  38877. while (numNeeded > rows.size())
  38878. {
  38879. ListBoxRowComponent* newRow = new ListBoxRowComponent (owner);
  38880. rows.add (newRow);
  38881. getViewedComponent()->addAndMakeVisible (newRow);
  38882. }
  38883. firstIndex = y / rowHeight;
  38884. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  38885. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  38886. for (int i = 0; i < numNeeded; ++i)
  38887. {
  38888. const int row = i + firstIndex;
  38889. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  38890. if (rowComp != 0)
  38891. {
  38892. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  38893. rowComp->update (row, owner.isRowSelected (row));
  38894. }
  38895. }
  38896. }
  38897. if (owner.headerComponent != 0)
  38898. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  38899. owner.outlineThickness,
  38900. jmax (owner.getWidth() - owner.outlineThickness * 2,
  38901. getViewedComponent()->getWidth()),
  38902. owner.headerComponent->getHeight());
  38903. }
  38904. void selectRow (const int row, const int rowHeight, const bool dontScroll,
  38905. const int lastRowSelected, const int totalItems, const bool isMouseClick)
  38906. {
  38907. hasUpdated = false;
  38908. if (row < firstWholeIndex && ! dontScroll)
  38909. {
  38910. setViewPosition (getViewPositionX(), row * rowHeight);
  38911. }
  38912. else if (row >= lastWholeIndex && ! dontScroll)
  38913. {
  38914. const int rowsOnScreen = lastWholeIndex - firstWholeIndex;
  38915. if (row >= lastRowSelected + rowsOnScreen
  38916. && rowsOnScreen < totalItems - 1
  38917. && ! isMouseClick)
  38918. {
  38919. setViewPosition (getViewPositionX(),
  38920. jlimit (0, jmax (0, totalItems - rowsOnScreen), row) * rowHeight);
  38921. }
  38922. else
  38923. {
  38924. setViewPosition (getViewPositionX(),
  38925. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  38926. }
  38927. }
  38928. if (! hasUpdated)
  38929. updateContents();
  38930. }
  38931. void scrollToEnsureRowIsOnscreen (const int row, const int rowHeight)
  38932. {
  38933. if (row < firstWholeIndex)
  38934. {
  38935. setViewPosition (getViewPositionX(), row * rowHeight);
  38936. }
  38937. else if (row >= lastWholeIndex)
  38938. {
  38939. setViewPosition (getViewPositionX(),
  38940. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  38941. }
  38942. }
  38943. void paint (Graphics& g)
  38944. {
  38945. if (isOpaque())
  38946. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  38947. }
  38948. bool keyPressed (const KeyPress& key)
  38949. {
  38950. if (key.isKeyCode (KeyPress::upKey)
  38951. || key.isKeyCode (KeyPress::downKey)
  38952. || key.isKeyCode (KeyPress::pageUpKey)
  38953. || key.isKeyCode (KeyPress::pageDownKey)
  38954. || key.isKeyCode (KeyPress::homeKey)
  38955. || key.isKeyCode (KeyPress::endKey))
  38956. {
  38957. // we want to avoid these keypresses going to the viewport, and instead allow
  38958. // them to pass up to our listbox..
  38959. return false;
  38960. }
  38961. return Viewport::keyPressed (key);
  38962. }
  38963. private:
  38964. ListBox& owner;
  38965. OwnedArray<ListBoxRowComponent> rows;
  38966. int firstIndex, firstWholeIndex, lastWholeIndex;
  38967. bool hasUpdated;
  38968. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListViewport);
  38969. };
  38970. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  38971. : Component (name),
  38972. model (model_),
  38973. totalItems (0),
  38974. rowHeight (22),
  38975. minimumRowWidth (0),
  38976. outlineThickness (0),
  38977. lastRowSelected (-1),
  38978. mouseMoveSelects (false),
  38979. multipleSelection (false),
  38980. hasDoneInitialUpdate (false)
  38981. {
  38982. addAndMakeVisible (viewport = new ListViewport (*this));
  38983. setWantsKeyboardFocus (true);
  38984. colourChanged();
  38985. }
  38986. ListBox::~ListBox()
  38987. {
  38988. headerComponent = 0;
  38989. viewport = 0;
  38990. }
  38991. void ListBox::setModel (ListBoxModel* const newModel)
  38992. {
  38993. if (model != newModel)
  38994. {
  38995. model = newModel;
  38996. repaint();
  38997. updateContent();
  38998. }
  38999. }
  39000. void ListBox::setMultipleSelectionEnabled (bool b)
  39001. {
  39002. multipleSelection = b;
  39003. }
  39004. void ListBox::setMouseMoveSelectsRows (bool b)
  39005. {
  39006. mouseMoveSelects = b;
  39007. if (b)
  39008. addMouseListener (this, true);
  39009. }
  39010. void ListBox::paint (Graphics& g)
  39011. {
  39012. if (! hasDoneInitialUpdate)
  39013. updateContent();
  39014. g.fillAll (findColour (backgroundColourId));
  39015. }
  39016. void ListBox::paintOverChildren (Graphics& g)
  39017. {
  39018. if (outlineThickness > 0)
  39019. {
  39020. g.setColour (findColour (outlineColourId));
  39021. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39022. }
  39023. }
  39024. void ListBox::resized()
  39025. {
  39026. viewport->setBoundsInset (BorderSize<int> (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39027. outlineThickness, outlineThickness, outlineThickness));
  39028. viewport->setSingleStepSizes (20, getRowHeight());
  39029. viewport->updateVisibleArea (false);
  39030. }
  39031. void ListBox::visibilityChanged()
  39032. {
  39033. viewport->updateVisibleArea (true);
  39034. }
  39035. Viewport* ListBox::getViewport() const throw()
  39036. {
  39037. return viewport;
  39038. }
  39039. void ListBox::updateContent()
  39040. {
  39041. hasDoneInitialUpdate = true;
  39042. totalItems = (model != 0) ? model->getNumRows() : 0;
  39043. bool selectionChanged = false;
  39044. if (selected.size() > 0 && selected [selected.size() - 1] >= totalItems)
  39045. {
  39046. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39047. lastRowSelected = getSelectedRow (0);
  39048. selectionChanged = true;
  39049. }
  39050. viewport->updateVisibleArea (isVisible());
  39051. viewport->resized();
  39052. if (selectionChanged && model != 0)
  39053. model->selectedRowsChanged (lastRowSelected);
  39054. }
  39055. void ListBox::selectRow (const int row,
  39056. bool dontScroll,
  39057. bool deselectOthersFirst)
  39058. {
  39059. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39060. }
  39061. void ListBox::selectRowInternal (const int row,
  39062. bool dontScroll,
  39063. bool deselectOthersFirst,
  39064. bool isMouseClick)
  39065. {
  39066. if (! multipleSelection)
  39067. deselectOthersFirst = true;
  39068. if ((! isRowSelected (row))
  39069. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39070. {
  39071. if (isPositiveAndBelow (row, totalItems))
  39072. {
  39073. if (deselectOthersFirst)
  39074. selected.clear();
  39075. selected.addRange (Range<int> (row, row + 1));
  39076. if (getHeight() == 0 || getWidth() == 0)
  39077. dontScroll = true;
  39078. viewport->selectRow (row, getRowHeight(), dontScroll,
  39079. lastRowSelected, totalItems, isMouseClick);
  39080. lastRowSelected = row;
  39081. model->selectedRowsChanged (row);
  39082. }
  39083. else
  39084. {
  39085. if (deselectOthersFirst)
  39086. deselectAllRows();
  39087. }
  39088. }
  39089. }
  39090. void ListBox::deselectRow (const int row)
  39091. {
  39092. if (selected.contains (row))
  39093. {
  39094. selected.removeRange (Range <int> (row, row + 1));
  39095. if (row == lastRowSelected)
  39096. lastRowSelected = getSelectedRow (0);
  39097. viewport->updateContents();
  39098. model->selectedRowsChanged (lastRowSelected);
  39099. }
  39100. }
  39101. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39102. const bool sendNotificationEventToModel)
  39103. {
  39104. selected = setOfRowsToBeSelected;
  39105. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39106. if (! isRowSelected (lastRowSelected))
  39107. lastRowSelected = getSelectedRow (0);
  39108. viewport->updateContents();
  39109. if ((model != 0) && sendNotificationEventToModel)
  39110. model->selectedRowsChanged (lastRowSelected);
  39111. }
  39112. const SparseSet<int> ListBox::getSelectedRows() const
  39113. {
  39114. return selected;
  39115. }
  39116. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39117. {
  39118. if (multipleSelection && (firstRow != lastRow))
  39119. {
  39120. const int numRows = totalItems - 1;
  39121. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39122. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39123. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39124. jmax (firstRow, lastRow) + 1));
  39125. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39126. }
  39127. selectRowInternal (lastRow, false, false, true);
  39128. }
  39129. void ListBox::flipRowSelection (const int row)
  39130. {
  39131. if (isRowSelected (row))
  39132. deselectRow (row);
  39133. else
  39134. selectRowInternal (row, false, false, true);
  39135. }
  39136. void ListBox::deselectAllRows()
  39137. {
  39138. if (! selected.isEmpty())
  39139. {
  39140. selected.clear();
  39141. lastRowSelected = -1;
  39142. viewport->updateContents();
  39143. if (model != 0)
  39144. model->selectedRowsChanged (lastRowSelected);
  39145. }
  39146. }
  39147. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39148. const ModifierKeys& mods,
  39149. const bool isMouseUpEvent)
  39150. {
  39151. if (multipleSelection && mods.isCommandDown())
  39152. {
  39153. flipRowSelection (row);
  39154. }
  39155. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39156. {
  39157. selectRangeOfRows (lastRowSelected, row);
  39158. }
  39159. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39160. {
  39161. selectRowInternal (row, false, ! (multipleSelection && (! isMouseUpEvent) && isRowSelected (row)), true);
  39162. }
  39163. }
  39164. int ListBox::getNumSelectedRows() const
  39165. {
  39166. return selected.size();
  39167. }
  39168. int ListBox::getSelectedRow (const int index) const
  39169. {
  39170. return (isPositiveAndBelow (index, selected.size()))
  39171. ? selected [index] : -1;
  39172. }
  39173. bool ListBox::isRowSelected (const int row) const
  39174. {
  39175. return selected.contains (row);
  39176. }
  39177. int ListBox::getLastRowSelected() const
  39178. {
  39179. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39180. }
  39181. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39182. {
  39183. if (isPositiveAndBelow (x, getWidth()))
  39184. {
  39185. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39186. if (isPositiveAndBelow (row, totalItems))
  39187. return row;
  39188. }
  39189. return -1;
  39190. }
  39191. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39192. {
  39193. if (isPositiveAndBelow (x, getWidth()))
  39194. {
  39195. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39196. return jlimit (0, totalItems, row);
  39197. }
  39198. return -1;
  39199. }
  39200. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39201. {
  39202. ListBoxRowComponent* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39203. return listRowComp != 0 ? static_cast <Component*> (listRowComp->customComponent) : 0;
  39204. }
  39205. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39206. {
  39207. return viewport->getRowNumberOfComponent (rowComponent);
  39208. }
  39209. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39210. const bool relativeToComponentTopLeft) const throw()
  39211. {
  39212. int y = viewport->getY() + rowHeight * rowNumber;
  39213. if (relativeToComponentTopLeft)
  39214. y -= viewport->getViewPositionY();
  39215. return Rectangle<int> (viewport->getX(), y,
  39216. viewport->getViewedComponent()->getWidth(), rowHeight);
  39217. }
  39218. void ListBox::setVerticalPosition (const double proportion)
  39219. {
  39220. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39221. viewport->setViewPosition (viewport->getViewPositionX(),
  39222. jmax (0, roundToInt (proportion * offscreen)));
  39223. }
  39224. double ListBox::getVerticalPosition() const
  39225. {
  39226. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39227. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39228. : 0;
  39229. }
  39230. int ListBox::getVisibleRowWidth() const throw()
  39231. {
  39232. return viewport->getViewWidth();
  39233. }
  39234. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39235. {
  39236. viewport->scrollToEnsureRowIsOnscreen (row, getRowHeight());
  39237. }
  39238. bool ListBox::keyPressed (const KeyPress& key)
  39239. {
  39240. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39241. const bool multiple = multipleSelection
  39242. && (lastRowSelected >= 0)
  39243. && (key.getModifiers().isShiftDown()
  39244. || key.getModifiers().isCtrlDown()
  39245. || key.getModifiers().isCommandDown());
  39246. if (key.isKeyCode (KeyPress::upKey))
  39247. {
  39248. if (multiple)
  39249. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39250. else
  39251. selectRow (jmax (0, lastRowSelected - 1));
  39252. }
  39253. else if (key.isKeyCode (KeyPress::returnKey)
  39254. && isRowSelected (lastRowSelected))
  39255. {
  39256. if (model != 0)
  39257. model->returnKeyPressed (lastRowSelected);
  39258. }
  39259. else if (key.isKeyCode (KeyPress::pageUpKey))
  39260. {
  39261. if (multiple)
  39262. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39263. else
  39264. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39265. }
  39266. else if (key.isKeyCode (KeyPress::pageDownKey))
  39267. {
  39268. if (multiple)
  39269. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39270. else
  39271. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39272. }
  39273. else if (key.isKeyCode (KeyPress::homeKey))
  39274. {
  39275. if (multiple && key.getModifiers().isShiftDown())
  39276. selectRangeOfRows (lastRowSelected, 0);
  39277. else
  39278. selectRow (0);
  39279. }
  39280. else if (key.isKeyCode (KeyPress::endKey))
  39281. {
  39282. if (multiple && key.getModifiers().isShiftDown())
  39283. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39284. else
  39285. selectRow (totalItems - 1);
  39286. }
  39287. else if (key.isKeyCode (KeyPress::downKey))
  39288. {
  39289. if (multiple)
  39290. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39291. else
  39292. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39293. }
  39294. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39295. && isRowSelected (lastRowSelected))
  39296. {
  39297. if (model != 0)
  39298. model->deleteKeyPressed (lastRowSelected);
  39299. }
  39300. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39301. {
  39302. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39303. }
  39304. else
  39305. {
  39306. return false;
  39307. }
  39308. return true;
  39309. }
  39310. bool ListBox::keyStateChanged (const bool isKeyDown)
  39311. {
  39312. return isKeyDown
  39313. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39314. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39315. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39316. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39317. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39318. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39319. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39320. }
  39321. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39322. {
  39323. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39324. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39325. }
  39326. void ListBox::mouseMove (const MouseEvent& e)
  39327. {
  39328. if (mouseMoveSelects)
  39329. {
  39330. const MouseEvent e2 (e.getEventRelativeTo (this));
  39331. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39332. }
  39333. }
  39334. void ListBox::mouseExit (const MouseEvent& e)
  39335. {
  39336. mouseMove (e);
  39337. }
  39338. void ListBox::mouseUp (const MouseEvent& e)
  39339. {
  39340. if (e.mouseWasClicked() && model != 0)
  39341. model->backgroundClicked();
  39342. }
  39343. void ListBox::setRowHeight (const int newHeight)
  39344. {
  39345. rowHeight = jmax (1, newHeight);
  39346. viewport->setSingleStepSizes (20, rowHeight);
  39347. updateContent();
  39348. }
  39349. int ListBox::getNumRowsOnScreen() const throw()
  39350. {
  39351. return viewport->getMaximumVisibleHeight() / rowHeight;
  39352. }
  39353. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39354. {
  39355. minimumRowWidth = newMinimumWidth;
  39356. updateContent();
  39357. }
  39358. int ListBox::getVisibleContentWidth() const throw()
  39359. {
  39360. return viewport->getMaximumVisibleWidth();
  39361. }
  39362. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39363. {
  39364. return viewport->getVerticalScrollBar();
  39365. }
  39366. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39367. {
  39368. return viewport->getHorizontalScrollBar();
  39369. }
  39370. void ListBox::colourChanged()
  39371. {
  39372. setOpaque (findColour (backgroundColourId).isOpaque());
  39373. viewport->setOpaque (isOpaque());
  39374. repaint();
  39375. }
  39376. void ListBox::setOutlineThickness (const int outlineThickness_)
  39377. {
  39378. outlineThickness = outlineThickness_;
  39379. resized();
  39380. }
  39381. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39382. {
  39383. if (headerComponent != newHeaderComponent)
  39384. {
  39385. headerComponent = newHeaderComponent;
  39386. addAndMakeVisible (newHeaderComponent);
  39387. ListBox::resized();
  39388. }
  39389. }
  39390. void ListBox::repaintRow (const int rowNumber) throw()
  39391. {
  39392. repaint (getRowPosition (rowNumber, true));
  39393. }
  39394. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39395. {
  39396. Rectangle<int> imageArea;
  39397. const int firstRow = getRowContainingPosition (0, 0);
  39398. int i;
  39399. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39400. {
  39401. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39402. if (rowComp != 0 && isRowSelected (firstRow + i))
  39403. {
  39404. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39405. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39406. imageArea = imageArea.getUnion (rowRect);
  39407. }
  39408. }
  39409. imageArea = imageArea.getIntersection (getLocalBounds());
  39410. imageX = imageArea.getX();
  39411. imageY = imageArea.getY();
  39412. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39413. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39414. {
  39415. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39416. if (rowComp != 0 && isRowSelected (firstRow + i))
  39417. {
  39418. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39419. Graphics g (snapshot);
  39420. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39421. if (g.reduceClipRegion (rowComp->getLocalBounds()))
  39422. {
  39423. g.beginTransparencyLayer (0.6f);
  39424. rowComp->paintEntireComponent (g, false);
  39425. g.endTransparencyLayer();
  39426. }
  39427. }
  39428. }
  39429. return snapshot;
  39430. }
  39431. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39432. {
  39433. DragAndDropContainer* const dragContainer
  39434. = DragAndDropContainer::findParentDragContainerFor (this);
  39435. if (dragContainer != 0)
  39436. {
  39437. int x, y;
  39438. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39439. MouseEvent e2 (e.getEventRelativeTo (this));
  39440. const Point<int> p (x - e2.x, y - e2.y);
  39441. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39442. }
  39443. else
  39444. {
  39445. // to be able to do a drag-and-drop operation, the listbox needs to
  39446. // be inside a component which is also a DragAndDropContainer.
  39447. jassertfalse;
  39448. }
  39449. }
  39450. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39451. {
  39452. (void) existingComponentToUpdate;
  39453. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39454. return 0;
  39455. }
  39456. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&) {}
  39457. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&) {}
  39458. void ListBoxModel::backgroundClicked() {}
  39459. void ListBoxModel::selectedRowsChanged (int) {}
  39460. void ListBoxModel::deleteKeyPressed (int) {}
  39461. void ListBoxModel::returnKeyPressed (int) {}
  39462. void ListBoxModel::listWasScrolled() {}
  39463. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  39464. const String ListBoxModel::getTooltipForRow (int) { return String::empty; }
  39465. END_JUCE_NAMESPACE
  39466. /*** End of inlined file: juce_ListBox.cpp ***/
  39467. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39468. BEGIN_JUCE_NAMESPACE
  39469. ProgressBar::ProgressBar (double& progress_)
  39470. : progress (progress_),
  39471. displayPercentage (true),
  39472. lastCallbackTime (0)
  39473. {
  39474. currentValue = jlimit (0.0, 1.0, progress);
  39475. }
  39476. ProgressBar::~ProgressBar()
  39477. {
  39478. }
  39479. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39480. {
  39481. displayPercentage = shouldDisplayPercentage;
  39482. repaint();
  39483. }
  39484. void ProgressBar::setTextToDisplay (const String& text)
  39485. {
  39486. displayPercentage = false;
  39487. displayedMessage = text;
  39488. }
  39489. void ProgressBar::lookAndFeelChanged()
  39490. {
  39491. setOpaque (findColour (backgroundColourId).isOpaque());
  39492. }
  39493. void ProgressBar::colourChanged()
  39494. {
  39495. lookAndFeelChanged();
  39496. }
  39497. void ProgressBar::paint (Graphics& g)
  39498. {
  39499. String text;
  39500. if (displayPercentage)
  39501. {
  39502. if (currentValue >= 0 && currentValue <= 1.0)
  39503. text << roundToInt (currentValue * 100.0) << '%';
  39504. }
  39505. else
  39506. {
  39507. text = displayedMessage;
  39508. }
  39509. getLookAndFeel().drawProgressBar (g, *this,
  39510. getWidth(), getHeight(),
  39511. currentValue, text);
  39512. }
  39513. void ProgressBar::visibilityChanged()
  39514. {
  39515. if (isVisible())
  39516. startTimer (30);
  39517. else
  39518. stopTimer();
  39519. }
  39520. void ProgressBar::timerCallback()
  39521. {
  39522. double newProgress = progress;
  39523. const uint32 now = Time::getMillisecondCounter();
  39524. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39525. lastCallbackTime = now;
  39526. if (currentValue != newProgress
  39527. || newProgress < 0 || newProgress >= 1.0
  39528. || currentMessage != displayedMessage)
  39529. {
  39530. if (currentValue < newProgress
  39531. && newProgress >= 0 && newProgress < 1.0
  39532. && currentValue >= 0 && currentValue < 1.0)
  39533. {
  39534. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39535. newProgress);
  39536. }
  39537. currentValue = newProgress;
  39538. currentMessage = displayedMessage;
  39539. repaint();
  39540. }
  39541. }
  39542. END_JUCE_NAMESPACE
  39543. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39544. /*** Start of inlined file: juce_Slider.cpp ***/
  39545. BEGIN_JUCE_NAMESPACE
  39546. class SliderPopupDisplayComponent : public BubbleComponent
  39547. {
  39548. public:
  39549. SliderPopupDisplayComponent (Slider* const owner_)
  39550. : owner (owner_),
  39551. font (15.0f, Font::bold)
  39552. {
  39553. setAlwaysOnTop (true);
  39554. }
  39555. ~SliderPopupDisplayComponent()
  39556. {
  39557. }
  39558. void paintContent (Graphics& g, int w, int h)
  39559. {
  39560. g.setFont (font);
  39561. g.setColour (Colours::black);
  39562. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39563. }
  39564. void getContentSize (int& w, int& h)
  39565. {
  39566. w = font.getStringWidth (text) + 18;
  39567. h = (int) (font.getHeight() * 1.6f);
  39568. }
  39569. void updatePosition (const String& newText)
  39570. {
  39571. if (text != newText)
  39572. {
  39573. text = newText;
  39574. repaint();
  39575. }
  39576. BubbleComponent::setPosition (owner);
  39577. }
  39578. private:
  39579. Slider* owner;
  39580. Font font;
  39581. String text;
  39582. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderPopupDisplayComponent);
  39583. };
  39584. Slider::Slider (const String& name)
  39585. : Component (name),
  39586. lastCurrentValue (0),
  39587. lastValueMin (0),
  39588. lastValueMax (0),
  39589. minimum (0),
  39590. maximum (10),
  39591. interval (0),
  39592. skewFactor (1.0),
  39593. velocityModeSensitivity (1.0),
  39594. velocityModeOffset (0.0),
  39595. velocityModeThreshold (1),
  39596. rotaryStart (float_Pi * 1.2f),
  39597. rotaryEnd (float_Pi * 2.8f),
  39598. numDecimalPlaces (7),
  39599. sliderRegionStart (0),
  39600. sliderRegionSize (1),
  39601. sliderBeingDragged (-1),
  39602. pixelsForFullDragExtent (250),
  39603. style (LinearHorizontal),
  39604. textBoxPos (TextBoxLeft),
  39605. textBoxWidth (80),
  39606. textBoxHeight (20),
  39607. incDecButtonMode (incDecButtonsNotDraggable),
  39608. editableText (true),
  39609. doubleClickToValue (false),
  39610. isVelocityBased (false),
  39611. userKeyOverridesVelocity (true),
  39612. rotaryStop (true),
  39613. incDecButtonsSideBySide (false),
  39614. sendChangeOnlyOnRelease (false),
  39615. popupDisplayEnabled (false),
  39616. menuEnabled (false),
  39617. menuShown (false),
  39618. scrollWheelEnabled (true),
  39619. snapsToMousePos (true),
  39620. popupDisplay (0),
  39621. parentForPopupDisplay (0)
  39622. {
  39623. setWantsKeyboardFocus (false);
  39624. setRepaintsOnMouseActivity (true);
  39625. lookAndFeelChanged();
  39626. updateText();
  39627. currentValue.addListener (this);
  39628. valueMin.addListener (this);
  39629. valueMax.addListener (this);
  39630. }
  39631. Slider::~Slider()
  39632. {
  39633. currentValue.removeListener (this);
  39634. valueMin.removeListener (this);
  39635. valueMax.removeListener (this);
  39636. popupDisplay = 0;
  39637. }
  39638. void Slider::handleAsyncUpdate()
  39639. {
  39640. cancelPendingUpdate();
  39641. Component::BailOutChecker checker (this);
  39642. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  39643. }
  39644. void Slider::sendDragStart()
  39645. {
  39646. startedDragging();
  39647. Component::BailOutChecker checker (this);
  39648. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39649. }
  39650. void Slider::sendDragEnd()
  39651. {
  39652. stoppedDragging();
  39653. sliderBeingDragged = -1;
  39654. Component::BailOutChecker checker (this);
  39655. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39656. }
  39657. void Slider::addListener (SliderListener* const listener)
  39658. {
  39659. listeners.add (listener);
  39660. }
  39661. void Slider::removeListener (SliderListener* const listener)
  39662. {
  39663. listeners.remove (listener);
  39664. }
  39665. void Slider::setSliderStyle (const SliderStyle newStyle)
  39666. {
  39667. if (style != newStyle)
  39668. {
  39669. style = newStyle;
  39670. repaint();
  39671. lookAndFeelChanged();
  39672. }
  39673. }
  39674. void Slider::setRotaryParameters (const float startAngleRadians,
  39675. const float endAngleRadians,
  39676. const bool stopAtEnd)
  39677. {
  39678. // make sure the values are sensible..
  39679. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39680. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39681. jassert (rotaryStart < rotaryEnd);
  39682. rotaryStart = startAngleRadians;
  39683. rotaryEnd = endAngleRadians;
  39684. rotaryStop = stopAtEnd;
  39685. }
  39686. void Slider::setVelocityBasedMode (const bool velBased)
  39687. {
  39688. isVelocityBased = velBased;
  39689. }
  39690. void Slider::setVelocityModeParameters (const double sensitivity,
  39691. const int threshold,
  39692. const double offset,
  39693. const bool userCanPressKeyToSwapMode)
  39694. {
  39695. jassert (threshold >= 0);
  39696. jassert (sensitivity > 0);
  39697. jassert (offset >= 0);
  39698. velocityModeSensitivity = sensitivity;
  39699. velocityModeOffset = offset;
  39700. velocityModeThreshold = threshold;
  39701. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39702. }
  39703. void Slider::setSkewFactor (const double factor)
  39704. {
  39705. skewFactor = factor;
  39706. }
  39707. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39708. {
  39709. if (maximum > minimum)
  39710. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39711. / (maximum - minimum));
  39712. }
  39713. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39714. {
  39715. jassert (distanceForFullScaleDrag > 0);
  39716. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39717. }
  39718. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39719. {
  39720. if (incDecButtonMode != mode)
  39721. {
  39722. incDecButtonMode = mode;
  39723. lookAndFeelChanged();
  39724. }
  39725. }
  39726. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39727. const bool isReadOnly,
  39728. const int textEntryBoxWidth,
  39729. const int textEntryBoxHeight)
  39730. {
  39731. if (textBoxPos != newPosition
  39732. || editableText != (! isReadOnly)
  39733. || textBoxWidth != textEntryBoxWidth
  39734. || textBoxHeight != textEntryBoxHeight)
  39735. {
  39736. textBoxPos = newPosition;
  39737. editableText = ! isReadOnly;
  39738. textBoxWidth = textEntryBoxWidth;
  39739. textBoxHeight = textEntryBoxHeight;
  39740. repaint();
  39741. lookAndFeelChanged();
  39742. }
  39743. }
  39744. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39745. {
  39746. editableText = shouldBeEditable;
  39747. if (valueBox != 0)
  39748. valueBox->setEditable (shouldBeEditable && isEnabled());
  39749. }
  39750. void Slider::showTextBox()
  39751. {
  39752. jassert (editableText); // this should probably be avoided in read-only sliders.
  39753. if (valueBox != 0)
  39754. valueBox->showEditor();
  39755. }
  39756. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  39757. {
  39758. if (valueBox != 0)
  39759. {
  39760. valueBox->hideEditor (discardCurrentEditorContents);
  39761. if (discardCurrentEditorContents)
  39762. updateText();
  39763. }
  39764. }
  39765. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  39766. {
  39767. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  39768. }
  39769. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  39770. {
  39771. snapsToMousePos = shouldSnapToMouse;
  39772. }
  39773. void Slider::setPopupDisplayEnabled (const bool enabled,
  39774. Component* const parentComponentToUse)
  39775. {
  39776. popupDisplayEnabled = enabled;
  39777. parentForPopupDisplay = parentComponentToUse;
  39778. }
  39779. void Slider::colourChanged()
  39780. {
  39781. lookAndFeelChanged();
  39782. }
  39783. void Slider::lookAndFeelChanged()
  39784. {
  39785. LookAndFeel& lf = getLookAndFeel();
  39786. if (textBoxPos != NoTextBox)
  39787. {
  39788. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  39789. : getTextFromValue (currentValue.getValue()));
  39790. valueBox = 0;
  39791. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  39792. valueBox->setWantsKeyboardFocus (false);
  39793. valueBox->setText (previousTextBoxContent, false);
  39794. valueBox->setEditable (editableText && isEnabled());
  39795. valueBox->addListener (this);
  39796. if (style == LinearBar)
  39797. valueBox->addMouseListener (this, false);
  39798. valueBox->setTooltip (getTooltip());
  39799. }
  39800. else
  39801. {
  39802. valueBox = 0;
  39803. }
  39804. if (style == IncDecButtons)
  39805. {
  39806. addAndMakeVisible (incButton = lf.createSliderButton (true));
  39807. incButton->addListener (this);
  39808. addAndMakeVisible (decButton = lf.createSliderButton (false));
  39809. decButton->addListener (this);
  39810. if (incDecButtonMode != incDecButtonsNotDraggable)
  39811. {
  39812. incButton->addMouseListener (this, false);
  39813. decButton->addMouseListener (this, false);
  39814. }
  39815. else
  39816. {
  39817. incButton->setRepeatSpeed (300, 100, 20);
  39818. incButton->addMouseListener (decButton, false);
  39819. decButton->setRepeatSpeed (300, 100, 20);
  39820. decButton->addMouseListener (incButton, false);
  39821. }
  39822. incButton->setTooltip (getTooltip());
  39823. decButton->setTooltip (getTooltip());
  39824. }
  39825. else
  39826. {
  39827. incButton = 0;
  39828. decButton = 0;
  39829. }
  39830. setComponentEffect (lf.getSliderEffect());
  39831. resized();
  39832. repaint();
  39833. }
  39834. void Slider::setRange (const double newMin,
  39835. const double newMax,
  39836. const double newInt)
  39837. {
  39838. if (minimum != newMin
  39839. || maximum != newMax
  39840. || interval != newInt)
  39841. {
  39842. minimum = newMin;
  39843. maximum = newMax;
  39844. interval = newInt;
  39845. // figure out the number of DPs needed to display all values at this
  39846. // interval setting.
  39847. numDecimalPlaces = 7;
  39848. if (newInt != 0)
  39849. {
  39850. int v = abs ((int) (newInt * 10000000));
  39851. while ((v % 10) == 0)
  39852. {
  39853. --numDecimalPlaces;
  39854. v /= 10;
  39855. }
  39856. }
  39857. // keep the current values inside the new range..
  39858. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39859. {
  39860. setValue (getValue(), false, false);
  39861. }
  39862. else
  39863. {
  39864. setMinValue (getMinValue(), false, false);
  39865. setMaxValue (getMaxValue(), false, false);
  39866. }
  39867. updateText();
  39868. }
  39869. }
  39870. void Slider::triggerChangeMessage (const bool synchronous)
  39871. {
  39872. if (synchronous)
  39873. handleAsyncUpdate();
  39874. else
  39875. triggerAsyncUpdate();
  39876. valueChanged();
  39877. }
  39878. void Slider::valueChanged (Value& value)
  39879. {
  39880. if (value.refersToSameSourceAs (currentValue))
  39881. {
  39882. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39883. setValue (currentValue.getValue(), false, false);
  39884. }
  39885. else if (value.refersToSameSourceAs (valueMin))
  39886. setMinValue (valueMin.getValue(), false, false, true);
  39887. else if (value.refersToSameSourceAs (valueMax))
  39888. setMaxValue (valueMax.getValue(), false, false, true);
  39889. }
  39890. double Slider::getValue() const
  39891. {
  39892. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  39893. // methods to get the two values.
  39894. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39895. return currentValue.getValue();
  39896. }
  39897. void Slider::setValue (double newValue,
  39898. const bool sendUpdateMessage,
  39899. const bool sendMessageSynchronously)
  39900. {
  39901. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  39902. // methods to set the two values.
  39903. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39904. newValue = constrainedValue (newValue);
  39905. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39906. {
  39907. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  39908. newValue = jlimit ((double) valueMin.getValue(),
  39909. (double) valueMax.getValue(),
  39910. newValue);
  39911. }
  39912. if (newValue != lastCurrentValue)
  39913. {
  39914. if (valueBox != 0)
  39915. valueBox->hideEditor (true);
  39916. lastCurrentValue = newValue;
  39917. currentValue = newValue;
  39918. updateText();
  39919. repaint();
  39920. if (popupDisplay != 0)
  39921. {
  39922. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39923. ->updatePosition (getTextFromValue (newValue));
  39924. popupDisplay->repaint();
  39925. }
  39926. if (sendUpdateMessage)
  39927. triggerChangeMessage (sendMessageSynchronously);
  39928. }
  39929. }
  39930. double Slider::getMinValue() const
  39931. {
  39932. // The minimum value only applies to sliders that are in two- or three-value mode.
  39933. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39934. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39935. return valueMin.getValue();
  39936. }
  39937. double Slider::getMaxValue() const
  39938. {
  39939. // The maximum value only applies to sliders that are in two- or three-value mode.
  39940. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39941. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39942. return valueMax.getValue();
  39943. }
  39944. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39945. {
  39946. // The minimum value only applies to sliders that are in two- or three-value mode.
  39947. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39948. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39949. newValue = constrainedValue (newValue);
  39950. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39951. {
  39952. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  39953. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39954. newValue = jmin ((double) valueMax.getValue(), newValue);
  39955. }
  39956. else
  39957. {
  39958. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  39959. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39960. newValue = jmin (lastCurrentValue, newValue);
  39961. }
  39962. if (lastValueMin != newValue)
  39963. {
  39964. lastValueMin = newValue;
  39965. valueMin = newValue;
  39966. repaint();
  39967. if (popupDisplay != 0)
  39968. {
  39969. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39970. ->updatePosition (getTextFromValue (newValue));
  39971. popupDisplay->repaint();
  39972. }
  39973. if (sendUpdateMessage)
  39974. triggerChangeMessage (sendMessageSynchronously);
  39975. }
  39976. }
  39977. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39978. {
  39979. // The maximum value only applies to sliders that are in two- or three-value mode.
  39980. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39981. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39982. newValue = constrainedValue (newValue);
  39983. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39984. {
  39985. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  39986. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39987. newValue = jmax ((double) valueMin.getValue(), newValue);
  39988. }
  39989. else
  39990. {
  39991. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  39992. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39993. newValue = jmax (lastCurrentValue, newValue);
  39994. }
  39995. if (lastValueMax != newValue)
  39996. {
  39997. lastValueMax = newValue;
  39998. valueMax = newValue;
  39999. repaint();
  40000. if (popupDisplay != 0)
  40001. {
  40002. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40003. ->updatePosition (getTextFromValue (valueMax.getValue()));
  40004. popupDisplay->repaint();
  40005. }
  40006. if (sendUpdateMessage)
  40007. triggerChangeMessage (sendMessageSynchronously);
  40008. }
  40009. }
  40010. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  40011. const double valueToSetOnDoubleClick)
  40012. {
  40013. doubleClickToValue = isDoubleClickEnabled;
  40014. doubleClickReturnValue = valueToSetOnDoubleClick;
  40015. }
  40016. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  40017. {
  40018. isEnabled_ = doubleClickToValue;
  40019. return doubleClickReturnValue;
  40020. }
  40021. void Slider::updateText()
  40022. {
  40023. if (valueBox != 0)
  40024. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40025. }
  40026. void Slider::setTextValueSuffix (const String& suffix)
  40027. {
  40028. if (textSuffix != suffix)
  40029. {
  40030. textSuffix = suffix;
  40031. updateText();
  40032. }
  40033. }
  40034. const String Slider::getTextValueSuffix() const
  40035. {
  40036. return textSuffix;
  40037. }
  40038. const String Slider::getTextFromValue (double v)
  40039. {
  40040. if (getNumDecimalPlacesToDisplay() > 0)
  40041. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40042. else
  40043. return String (roundToInt (v)) + getTextValueSuffix();
  40044. }
  40045. double Slider::getValueFromText (const String& text)
  40046. {
  40047. String t (text.trimStart());
  40048. if (t.endsWith (textSuffix))
  40049. t = t.substring (0, t.length() - textSuffix.length());
  40050. while (t.startsWithChar ('+'))
  40051. t = t.substring (1).trimStart();
  40052. return t.initialSectionContainingOnly ("0123456789.,-")
  40053. .getDoubleValue();
  40054. }
  40055. double Slider::proportionOfLengthToValue (double proportion)
  40056. {
  40057. if (skewFactor != 1.0 && proportion > 0.0)
  40058. proportion = exp (log (proportion) / skewFactor);
  40059. return minimum + (maximum - minimum) * proportion;
  40060. }
  40061. double Slider::valueToProportionOfLength (double value)
  40062. {
  40063. const double n = (value - minimum) / (maximum - minimum);
  40064. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40065. }
  40066. double Slider::snapValue (double attemptedValue, const bool)
  40067. {
  40068. return attemptedValue;
  40069. }
  40070. void Slider::startedDragging()
  40071. {
  40072. }
  40073. void Slider::stoppedDragging()
  40074. {
  40075. }
  40076. void Slider::valueChanged()
  40077. {
  40078. }
  40079. void Slider::enablementChanged()
  40080. {
  40081. repaint();
  40082. }
  40083. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40084. {
  40085. menuEnabled = menuEnabled_;
  40086. }
  40087. void Slider::setScrollWheelEnabled (const bool enabled)
  40088. {
  40089. scrollWheelEnabled = enabled;
  40090. }
  40091. void Slider::labelTextChanged (Label* label)
  40092. {
  40093. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40094. if (newValue != (double) currentValue.getValue())
  40095. {
  40096. sendDragStart();
  40097. setValue (newValue, true, true);
  40098. sendDragEnd();
  40099. }
  40100. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40101. }
  40102. void Slider::buttonClicked (Button* button)
  40103. {
  40104. if (style == IncDecButtons)
  40105. {
  40106. sendDragStart();
  40107. if (button == incButton)
  40108. setValue (snapValue (getValue() + interval, false), true, true);
  40109. else if (button == decButton)
  40110. setValue (snapValue (getValue() - interval, false), true, true);
  40111. sendDragEnd();
  40112. }
  40113. }
  40114. double Slider::constrainedValue (double value) const
  40115. {
  40116. if (interval > 0)
  40117. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40118. if (value <= minimum || maximum <= minimum)
  40119. value = minimum;
  40120. else if (value >= maximum)
  40121. value = maximum;
  40122. return value;
  40123. }
  40124. float Slider::getLinearSliderPos (const double value)
  40125. {
  40126. double sliderPosProportional;
  40127. if (maximum > minimum)
  40128. {
  40129. if (value < minimum)
  40130. {
  40131. sliderPosProportional = 0.0;
  40132. }
  40133. else if (value > maximum)
  40134. {
  40135. sliderPosProportional = 1.0;
  40136. }
  40137. else
  40138. {
  40139. sliderPosProportional = valueToProportionOfLength (value);
  40140. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40141. }
  40142. }
  40143. else
  40144. {
  40145. sliderPosProportional = 0.5;
  40146. }
  40147. if (isVertical() || style == IncDecButtons)
  40148. sliderPosProportional = 1.0 - sliderPosProportional;
  40149. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40150. }
  40151. bool Slider::isHorizontal() const
  40152. {
  40153. return style == LinearHorizontal
  40154. || style == LinearBar
  40155. || style == TwoValueHorizontal
  40156. || style == ThreeValueHorizontal;
  40157. }
  40158. bool Slider::isVertical() const
  40159. {
  40160. return style == LinearVertical
  40161. || style == TwoValueVertical
  40162. || style == ThreeValueVertical;
  40163. }
  40164. bool Slider::incDecDragDirectionIsHorizontal() const
  40165. {
  40166. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40167. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40168. }
  40169. float Slider::getPositionOfValue (const double value)
  40170. {
  40171. if (isHorizontal() || isVertical())
  40172. {
  40173. return getLinearSliderPos (value);
  40174. }
  40175. else
  40176. {
  40177. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40178. return 0.0f;
  40179. }
  40180. }
  40181. void Slider::paint (Graphics& g)
  40182. {
  40183. if (style != IncDecButtons)
  40184. {
  40185. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40186. {
  40187. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40188. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40189. getLookAndFeel().drawRotarySlider (g,
  40190. sliderRect.getX(),
  40191. sliderRect.getY(),
  40192. sliderRect.getWidth(),
  40193. sliderRect.getHeight(),
  40194. sliderPos,
  40195. rotaryStart, rotaryEnd,
  40196. *this);
  40197. }
  40198. else
  40199. {
  40200. getLookAndFeel().drawLinearSlider (g,
  40201. sliderRect.getX(),
  40202. sliderRect.getY(),
  40203. sliderRect.getWidth(),
  40204. sliderRect.getHeight(),
  40205. getLinearSliderPos (lastCurrentValue),
  40206. getLinearSliderPos (lastValueMin),
  40207. getLinearSliderPos (lastValueMax),
  40208. style,
  40209. *this);
  40210. }
  40211. if (style == LinearBar && valueBox == 0)
  40212. {
  40213. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40214. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40215. }
  40216. }
  40217. }
  40218. void Slider::resized()
  40219. {
  40220. int minXSpace = 0;
  40221. int minYSpace = 0;
  40222. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40223. minXSpace = 30;
  40224. else
  40225. minYSpace = 15;
  40226. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40227. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40228. if (style == LinearBar)
  40229. {
  40230. if (valueBox != 0)
  40231. valueBox->setBounds (getLocalBounds());
  40232. }
  40233. else
  40234. {
  40235. if (textBoxPos == NoTextBox)
  40236. {
  40237. sliderRect = getLocalBounds();
  40238. }
  40239. else if (textBoxPos == TextBoxLeft)
  40240. {
  40241. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40242. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40243. }
  40244. else if (textBoxPos == TextBoxRight)
  40245. {
  40246. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40247. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40248. }
  40249. else if (textBoxPos == TextBoxAbove)
  40250. {
  40251. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40252. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40253. }
  40254. else if (textBoxPos == TextBoxBelow)
  40255. {
  40256. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40257. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40258. }
  40259. }
  40260. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40261. if (style == LinearBar)
  40262. {
  40263. const int barIndent = 1;
  40264. sliderRegionStart = barIndent;
  40265. sliderRegionSize = getWidth() - barIndent * 2;
  40266. sliderRect.setBounds (sliderRegionStart, barIndent,
  40267. sliderRegionSize, getHeight() - barIndent * 2);
  40268. }
  40269. else if (isHorizontal())
  40270. {
  40271. sliderRegionStart = sliderRect.getX() + indent;
  40272. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40273. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40274. sliderRegionSize, sliderRect.getHeight());
  40275. }
  40276. else if (isVertical())
  40277. {
  40278. sliderRegionStart = sliderRect.getY() + indent;
  40279. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40280. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40281. sliderRect.getWidth(), sliderRegionSize);
  40282. }
  40283. else
  40284. {
  40285. sliderRegionStart = 0;
  40286. sliderRegionSize = 100;
  40287. }
  40288. if (style == IncDecButtons)
  40289. {
  40290. Rectangle<int> buttonRect (sliderRect);
  40291. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40292. buttonRect.expand (-2, 0);
  40293. else
  40294. buttonRect.expand (0, -2);
  40295. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40296. if (incDecButtonsSideBySide)
  40297. {
  40298. decButton->setBounds (buttonRect.getX(),
  40299. buttonRect.getY(),
  40300. buttonRect.getWidth() / 2,
  40301. buttonRect.getHeight());
  40302. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40303. incButton->setBounds (buttonRect.getCentreX(),
  40304. buttonRect.getY(),
  40305. buttonRect.getWidth() / 2,
  40306. buttonRect.getHeight());
  40307. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40308. }
  40309. else
  40310. {
  40311. incButton->setBounds (buttonRect.getX(),
  40312. buttonRect.getY(),
  40313. buttonRect.getWidth(),
  40314. buttonRect.getHeight() / 2);
  40315. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40316. decButton->setBounds (buttonRect.getX(),
  40317. buttonRect.getCentreY(),
  40318. buttonRect.getWidth(),
  40319. buttonRect.getHeight() / 2);
  40320. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40321. }
  40322. }
  40323. }
  40324. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40325. {
  40326. repaint();
  40327. }
  40328. void Slider::mouseDown (const MouseEvent& e)
  40329. {
  40330. mouseWasHidden = false;
  40331. incDecDragged = false;
  40332. mouseXWhenLastDragged = e.x;
  40333. mouseYWhenLastDragged = e.y;
  40334. mouseDragStartX = e.getMouseDownX();
  40335. mouseDragStartY = e.getMouseDownY();
  40336. if (isEnabled())
  40337. {
  40338. if (e.mods.isPopupMenu() && menuEnabled)
  40339. {
  40340. menuShown = true;
  40341. PopupMenu m;
  40342. m.setLookAndFeel (&getLookAndFeel());
  40343. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40344. m.addSeparator();
  40345. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40346. {
  40347. PopupMenu rotaryMenu;
  40348. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40349. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40350. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40351. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40352. }
  40353. const int r = m.show();
  40354. if (r == 1)
  40355. {
  40356. setVelocityBasedMode (! isVelocityBased);
  40357. }
  40358. else if (r == 2)
  40359. {
  40360. setSliderStyle (Rotary);
  40361. }
  40362. else if (r == 3)
  40363. {
  40364. setSliderStyle (RotaryHorizontalDrag);
  40365. }
  40366. else if (r == 4)
  40367. {
  40368. setSliderStyle (RotaryVerticalDrag);
  40369. }
  40370. }
  40371. else if (maximum > minimum)
  40372. {
  40373. menuShown = false;
  40374. if (valueBox != 0)
  40375. valueBox->hideEditor (true);
  40376. sliderBeingDragged = 0;
  40377. if (style == TwoValueHorizontal
  40378. || style == TwoValueVertical
  40379. || style == ThreeValueHorizontal
  40380. || style == ThreeValueVertical)
  40381. {
  40382. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40383. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40384. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40385. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40386. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40387. {
  40388. if (maxPosDistance <= minPosDistance)
  40389. sliderBeingDragged = 2;
  40390. else
  40391. sliderBeingDragged = 1;
  40392. }
  40393. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40394. {
  40395. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40396. sliderBeingDragged = 1;
  40397. else if (normalPosDistance >= maxPosDistance)
  40398. sliderBeingDragged = 2;
  40399. }
  40400. }
  40401. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40402. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40403. * valueToProportionOfLength (currentValue.getValue());
  40404. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40405. : ((sliderBeingDragged == 1) ? valueMin
  40406. : currentValue)).getValue();
  40407. valueOnMouseDown = valueWhenLastDragged;
  40408. if (popupDisplayEnabled)
  40409. {
  40410. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40411. popupDisplay = popup;
  40412. if (parentForPopupDisplay != 0)
  40413. {
  40414. parentForPopupDisplay->addChildComponent (popup);
  40415. }
  40416. else
  40417. {
  40418. popup->addToDesktop (0);
  40419. }
  40420. popup->setVisible (true);
  40421. }
  40422. sendDragStart();
  40423. mouseDrag (e);
  40424. }
  40425. }
  40426. }
  40427. void Slider::mouseUp (const MouseEvent&)
  40428. {
  40429. if (isEnabled()
  40430. && (! menuShown)
  40431. && (maximum > minimum)
  40432. && (style != IncDecButtons || incDecDragged))
  40433. {
  40434. restoreMouseIfHidden();
  40435. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40436. triggerChangeMessage (false);
  40437. sendDragEnd();
  40438. popupDisplay = 0;
  40439. if (style == IncDecButtons)
  40440. {
  40441. incButton->setState (Button::buttonNormal);
  40442. decButton->setState (Button::buttonNormal);
  40443. }
  40444. }
  40445. }
  40446. void Slider::restoreMouseIfHidden()
  40447. {
  40448. if (mouseWasHidden)
  40449. {
  40450. mouseWasHidden = false;
  40451. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40452. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40453. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40454. : ((sliderBeingDragged == 1) ? getMinValue()
  40455. : (double) currentValue.getValue());
  40456. Point<int> mousePos;
  40457. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40458. {
  40459. mousePos = Desktop::getLastMouseDownPosition();
  40460. if (style == RotaryHorizontalDrag)
  40461. {
  40462. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40463. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40464. }
  40465. else
  40466. {
  40467. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40468. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40469. }
  40470. }
  40471. else
  40472. {
  40473. const int pixelPos = (int) getLinearSliderPos (pos);
  40474. mousePos = localPointToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40475. isVertical() ? pixelPos : (getHeight() / 2)));
  40476. }
  40477. Desktop::setMousePosition (mousePos);
  40478. }
  40479. }
  40480. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40481. {
  40482. if (isEnabled()
  40483. && style != IncDecButtons
  40484. && style != Rotary
  40485. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40486. {
  40487. restoreMouseIfHidden();
  40488. }
  40489. }
  40490. namespace SliderHelpers
  40491. {
  40492. double smallestAngleBetween (double a1, double a2) throw()
  40493. {
  40494. return jmin (std::abs (a1 - a2),
  40495. std::abs (a1 + double_Pi * 2.0 - a2),
  40496. std::abs (a2 + double_Pi * 2.0 - a1));
  40497. }
  40498. }
  40499. void Slider::mouseDrag (const MouseEvent& e)
  40500. {
  40501. if (isEnabled()
  40502. && (! menuShown)
  40503. && (maximum > minimum))
  40504. {
  40505. if (style == Rotary)
  40506. {
  40507. int dx = e.x - sliderRect.getCentreX();
  40508. int dy = e.y - sliderRect.getCentreY();
  40509. if (dx * dx + dy * dy > 25)
  40510. {
  40511. double angle = std::atan2 ((double) dx, (double) -dy);
  40512. while (angle < 0.0)
  40513. angle += double_Pi * 2.0;
  40514. if (rotaryStop && ! e.mouseWasClicked())
  40515. {
  40516. if (std::abs (angle - lastAngle) > double_Pi)
  40517. {
  40518. if (angle >= lastAngle)
  40519. angle -= double_Pi * 2.0;
  40520. else
  40521. angle += double_Pi * 2.0;
  40522. }
  40523. if (angle >= lastAngle)
  40524. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40525. else
  40526. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40527. }
  40528. else
  40529. {
  40530. while (angle < rotaryStart)
  40531. angle += double_Pi * 2.0;
  40532. if (angle > rotaryEnd)
  40533. {
  40534. if (SliderHelpers::smallestAngleBetween (angle, rotaryStart)
  40535. <= SliderHelpers::smallestAngleBetween (angle, rotaryEnd))
  40536. angle = rotaryStart;
  40537. else
  40538. angle = rotaryEnd;
  40539. }
  40540. }
  40541. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40542. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40543. lastAngle = angle;
  40544. }
  40545. }
  40546. else
  40547. {
  40548. if (style == LinearBar && e.mouseWasClicked()
  40549. && valueBox != 0 && valueBox->isEditable())
  40550. return;
  40551. if (style == IncDecButtons && ! incDecDragged)
  40552. {
  40553. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40554. return;
  40555. incDecDragged = true;
  40556. mouseDragStartX = e.x;
  40557. mouseDragStartY = e.y;
  40558. }
  40559. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40560. : false))
  40561. || ((maximum - minimum) / sliderRegionSize < interval))
  40562. {
  40563. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40564. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40565. if (style == RotaryHorizontalDrag
  40566. || style == RotaryVerticalDrag
  40567. || style == IncDecButtons
  40568. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40569. && ! snapsToMousePos))
  40570. {
  40571. const int mouseDiff = (style == RotaryHorizontalDrag
  40572. || style == LinearHorizontal
  40573. || style == LinearBar
  40574. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40575. ? e.x - mouseDragStartX
  40576. : mouseDragStartY - e.y;
  40577. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40578. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40579. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40580. if (style == IncDecButtons)
  40581. {
  40582. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40583. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40584. }
  40585. }
  40586. else
  40587. {
  40588. if (isVertical())
  40589. scaledMousePos = 1.0 - scaledMousePos;
  40590. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40591. }
  40592. }
  40593. else
  40594. {
  40595. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40596. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40597. ? e.x - mouseXWhenLastDragged
  40598. : e.y - mouseYWhenLastDragged;
  40599. const double maxSpeed = jmax (200, sliderRegionSize);
  40600. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40601. if (speed != 0)
  40602. {
  40603. speed = 0.2 * velocityModeSensitivity
  40604. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40605. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40606. / maxSpeed))));
  40607. if (mouseDiff < 0)
  40608. speed = -speed;
  40609. if (isVertical() || style == RotaryVerticalDrag
  40610. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40611. speed = -speed;
  40612. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40613. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40614. e.source.enableUnboundedMouseMovement (true, false);
  40615. mouseWasHidden = true;
  40616. }
  40617. }
  40618. }
  40619. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40620. if (sliderBeingDragged == 0)
  40621. {
  40622. setValue (snapValue (valueWhenLastDragged, true),
  40623. ! sendChangeOnlyOnRelease, true);
  40624. }
  40625. else if (sliderBeingDragged == 1)
  40626. {
  40627. setMinValue (snapValue (valueWhenLastDragged, true),
  40628. ! sendChangeOnlyOnRelease, false, true);
  40629. if (e.mods.isShiftDown())
  40630. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40631. else
  40632. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40633. }
  40634. else
  40635. {
  40636. jassert (sliderBeingDragged == 2);
  40637. setMaxValue (snapValue (valueWhenLastDragged, true),
  40638. ! sendChangeOnlyOnRelease, false, true);
  40639. if (e.mods.isShiftDown())
  40640. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40641. else
  40642. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40643. }
  40644. mouseXWhenLastDragged = e.x;
  40645. mouseYWhenLastDragged = e.y;
  40646. }
  40647. }
  40648. void Slider::mouseDoubleClick (const MouseEvent&)
  40649. {
  40650. if (doubleClickToValue
  40651. && isEnabled()
  40652. && style != IncDecButtons
  40653. && minimum <= doubleClickReturnValue
  40654. && maximum >= doubleClickReturnValue)
  40655. {
  40656. sendDragStart();
  40657. setValue (doubleClickReturnValue, true, true);
  40658. sendDragEnd();
  40659. }
  40660. }
  40661. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40662. {
  40663. if (scrollWheelEnabled && isEnabled()
  40664. && style != TwoValueHorizontal
  40665. && style != TwoValueVertical)
  40666. {
  40667. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40668. {
  40669. if (valueBox != 0)
  40670. valueBox->hideEditor (false);
  40671. const double value = (double) currentValue.getValue();
  40672. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40673. const double currentPos = valueToProportionOfLength (value);
  40674. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40675. double delta = (newValue != value)
  40676. ? jmax (std::abs (newValue - value), interval) : 0;
  40677. if (value > newValue)
  40678. delta = -delta;
  40679. sendDragStart();
  40680. setValue (snapValue (value + delta, false), true, true);
  40681. sendDragEnd();
  40682. }
  40683. }
  40684. else
  40685. {
  40686. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40687. }
  40688. }
  40689. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  40690. {
  40691. }
  40692. void SliderListener::sliderDragEnded (Slider*)
  40693. {
  40694. }
  40695. END_JUCE_NAMESPACE
  40696. /*** End of inlined file: juce_Slider.cpp ***/
  40697. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40698. BEGIN_JUCE_NAMESPACE
  40699. class DragOverlayComp : public Component
  40700. {
  40701. public:
  40702. DragOverlayComp (const Image& image_)
  40703. : image (image_)
  40704. {
  40705. image.duplicateIfShared();
  40706. image.multiplyAllAlphas (0.8f);
  40707. setAlwaysOnTop (true);
  40708. }
  40709. void paint (Graphics& g)
  40710. {
  40711. g.drawImageAt (image, 0, 0);
  40712. }
  40713. private:
  40714. Image image;
  40715. JUCE_DECLARE_NON_COPYABLE (DragOverlayComp);
  40716. };
  40717. TableHeaderComponent::TableHeaderComponent()
  40718. : columnsChanged (false),
  40719. columnsResized (false),
  40720. sortChanged (false),
  40721. menuActive (true),
  40722. stretchToFit (false),
  40723. columnIdBeingResized (0),
  40724. columnIdBeingDragged (0),
  40725. columnIdUnderMouse (0),
  40726. lastDeliberateWidth (0)
  40727. {
  40728. }
  40729. TableHeaderComponent::~TableHeaderComponent()
  40730. {
  40731. dragOverlayComp = 0;
  40732. }
  40733. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40734. {
  40735. menuActive = hasMenu;
  40736. }
  40737. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40738. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40739. {
  40740. if (onlyCountVisibleColumns)
  40741. {
  40742. int num = 0;
  40743. for (int i = columns.size(); --i >= 0;)
  40744. if (columns.getUnchecked(i)->isVisible())
  40745. ++num;
  40746. return num;
  40747. }
  40748. else
  40749. {
  40750. return columns.size();
  40751. }
  40752. }
  40753. const String TableHeaderComponent::getColumnName (const int columnId) const
  40754. {
  40755. const ColumnInfo* const ci = getInfoForId (columnId);
  40756. return ci != 0 ? ci->name : String::empty;
  40757. }
  40758. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40759. {
  40760. ColumnInfo* const ci = getInfoForId (columnId);
  40761. if (ci != 0 && ci->name != newName)
  40762. {
  40763. ci->name = newName;
  40764. sendColumnsChanged();
  40765. }
  40766. }
  40767. void TableHeaderComponent::addColumn (const String& columnName,
  40768. const int columnId,
  40769. const int width,
  40770. const int minimumWidth,
  40771. const int maximumWidth,
  40772. const int propertyFlags,
  40773. const int insertIndex)
  40774. {
  40775. // can't have a duplicate or null ID!
  40776. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  40777. jassert (width > 0);
  40778. ColumnInfo* const ci = new ColumnInfo();
  40779. ci->name = columnName;
  40780. ci->id = columnId;
  40781. ci->width = width;
  40782. ci->lastDeliberateWidth = width;
  40783. ci->minimumWidth = minimumWidth;
  40784. ci->maximumWidth = maximumWidth;
  40785. if (ci->maximumWidth < 0)
  40786. ci->maximumWidth = std::numeric_limits<int>::max();
  40787. jassert (ci->maximumWidth >= ci->minimumWidth);
  40788. ci->propertyFlags = propertyFlags;
  40789. columns.insert (insertIndex, ci);
  40790. sendColumnsChanged();
  40791. }
  40792. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  40793. {
  40794. const int index = getIndexOfColumnId (columnIdToRemove, false);
  40795. if (index >= 0)
  40796. {
  40797. columns.remove (index);
  40798. sortChanged = true;
  40799. sendColumnsChanged();
  40800. }
  40801. }
  40802. void TableHeaderComponent::removeAllColumns()
  40803. {
  40804. if (columns.size() > 0)
  40805. {
  40806. columns.clear();
  40807. sendColumnsChanged();
  40808. }
  40809. }
  40810. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  40811. {
  40812. const int currentIndex = getIndexOfColumnId (columnId, false);
  40813. newIndex = visibleIndexToTotalIndex (newIndex);
  40814. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  40815. {
  40816. columns.move (currentIndex, newIndex);
  40817. sendColumnsChanged();
  40818. }
  40819. }
  40820. int TableHeaderComponent::getColumnWidth (const int columnId) const
  40821. {
  40822. const ColumnInfo* const ci = getInfoForId (columnId);
  40823. return ci != 0 ? ci->width : 0;
  40824. }
  40825. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  40826. {
  40827. ColumnInfo* const ci = getInfoForId (columnId);
  40828. if (ci != 0 && ci->width != newWidth)
  40829. {
  40830. const int numColumns = getNumColumns (true);
  40831. ci->lastDeliberateWidth = ci->width
  40832. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  40833. if (stretchToFit)
  40834. {
  40835. const int index = getIndexOfColumnId (columnId, true) + 1;
  40836. if (isPositiveAndBelow (index, numColumns))
  40837. {
  40838. const int x = getColumnPosition (index).getX();
  40839. if (lastDeliberateWidth == 0)
  40840. lastDeliberateWidth = getTotalWidth();
  40841. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  40842. }
  40843. }
  40844. repaint();
  40845. columnsResized = true;
  40846. triggerAsyncUpdate();
  40847. }
  40848. }
  40849. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  40850. {
  40851. int n = 0;
  40852. for (int i = 0; i < columns.size(); ++i)
  40853. {
  40854. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  40855. {
  40856. if (columns.getUnchecked(i)->id == columnId)
  40857. return n;
  40858. ++n;
  40859. }
  40860. }
  40861. return -1;
  40862. }
  40863. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  40864. {
  40865. if (onlyCountVisibleColumns)
  40866. index = visibleIndexToTotalIndex (index);
  40867. const ColumnInfo* const ci = columns [index];
  40868. return (ci != 0) ? ci->id : 0;
  40869. }
  40870. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  40871. {
  40872. int x = 0, width = 0, n = 0;
  40873. for (int i = 0; i < columns.size(); ++i)
  40874. {
  40875. x += width;
  40876. if (columns.getUnchecked(i)->isVisible())
  40877. {
  40878. width = columns.getUnchecked(i)->width;
  40879. if (n++ == index)
  40880. break;
  40881. }
  40882. else
  40883. {
  40884. width = 0;
  40885. }
  40886. }
  40887. return Rectangle<int> (x, 0, width, getHeight());
  40888. }
  40889. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  40890. {
  40891. if (xToFind >= 0)
  40892. {
  40893. int x = 0;
  40894. for (int i = 0; i < columns.size(); ++i)
  40895. {
  40896. const ColumnInfo* const ci = columns.getUnchecked(i);
  40897. if (ci->isVisible())
  40898. {
  40899. x += ci->width;
  40900. if (xToFind < x)
  40901. return ci->id;
  40902. }
  40903. }
  40904. }
  40905. return 0;
  40906. }
  40907. int TableHeaderComponent::getTotalWidth() const
  40908. {
  40909. int w = 0;
  40910. for (int i = columns.size(); --i >= 0;)
  40911. if (columns.getUnchecked(i)->isVisible())
  40912. w += columns.getUnchecked(i)->width;
  40913. return w;
  40914. }
  40915. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  40916. {
  40917. stretchToFit = shouldStretchToFit;
  40918. lastDeliberateWidth = getTotalWidth();
  40919. resized();
  40920. }
  40921. bool TableHeaderComponent::isStretchToFitActive() const
  40922. {
  40923. return stretchToFit;
  40924. }
  40925. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  40926. {
  40927. if (stretchToFit && getWidth() > 0
  40928. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  40929. {
  40930. lastDeliberateWidth = targetTotalWidth;
  40931. resizeColumnsToFit (0, targetTotalWidth);
  40932. }
  40933. }
  40934. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  40935. {
  40936. targetTotalWidth = jmax (targetTotalWidth, 0);
  40937. StretchableObjectResizer sor;
  40938. int i;
  40939. for (i = firstColumnIndex; i < columns.size(); ++i)
  40940. {
  40941. ColumnInfo* const ci = columns.getUnchecked(i);
  40942. if (ci->isVisible())
  40943. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  40944. }
  40945. sor.resizeToFit (targetTotalWidth);
  40946. int visIndex = 0;
  40947. for (i = firstColumnIndex; i < columns.size(); ++i)
  40948. {
  40949. ColumnInfo* const ci = columns.getUnchecked(i);
  40950. if (ci->isVisible())
  40951. {
  40952. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  40953. (int) std::floor (sor.getItemSize (visIndex++)));
  40954. if (newWidth != ci->width)
  40955. {
  40956. ci->width = newWidth;
  40957. repaint();
  40958. columnsResized = true;
  40959. triggerAsyncUpdate();
  40960. }
  40961. }
  40962. }
  40963. }
  40964. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  40965. {
  40966. ColumnInfo* const ci = getInfoForId (columnId);
  40967. if (ci != 0 && shouldBeVisible != ci->isVisible())
  40968. {
  40969. if (shouldBeVisible)
  40970. ci->propertyFlags |= visible;
  40971. else
  40972. ci->propertyFlags &= ~visible;
  40973. sendColumnsChanged();
  40974. resized();
  40975. }
  40976. }
  40977. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  40978. {
  40979. const ColumnInfo* const ci = getInfoForId (columnId);
  40980. return ci != 0 && ci->isVisible();
  40981. }
  40982. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  40983. {
  40984. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  40985. {
  40986. for (int i = columns.size(); --i >= 0;)
  40987. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  40988. ColumnInfo* const ci = getInfoForId (columnId);
  40989. if (ci != 0)
  40990. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  40991. reSortTable();
  40992. }
  40993. }
  40994. int TableHeaderComponent::getSortColumnId() const
  40995. {
  40996. for (int i = columns.size(); --i >= 0;)
  40997. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40998. return columns.getUnchecked(i)->id;
  40999. return 0;
  41000. }
  41001. bool TableHeaderComponent::isSortedForwards() const
  41002. {
  41003. for (int i = columns.size(); --i >= 0;)
  41004. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41005. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  41006. return true;
  41007. }
  41008. void TableHeaderComponent::reSortTable()
  41009. {
  41010. sortChanged = true;
  41011. repaint();
  41012. triggerAsyncUpdate();
  41013. }
  41014. const String TableHeaderComponent::toString() const
  41015. {
  41016. String s;
  41017. XmlElement doc ("TABLELAYOUT");
  41018. doc.setAttribute ("sortedCol", getSortColumnId());
  41019. doc.setAttribute ("sortForwards", isSortedForwards());
  41020. for (int i = 0; i < columns.size(); ++i)
  41021. {
  41022. const ColumnInfo* const ci = columns.getUnchecked (i);
  41023. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41024. e->setAttribute ("id", ci->id);
  41025. e->setAttribute ("visible", ci->isVisible());
  41026. e->setAttribute ("width", ci->width);
  41027. }
  41028. return doc.createDocument (String::empty, true, false);
  41029. }
  41030. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41031. {
  41032. ScopedPointer <XmlElement> storedXml (XmlDocument::parse (storedVersion));
  41033. int index = 0;
  41034. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41035. {
  41036. forEachXmlChildElement (*storedXml, col)
  41037. {
  41038. const int tabId = col->getIntAttribute ("id");
  41039. ColumnInfo* const ci = getInfoForId (tabId);
  41040. if (ci != 0)
  41041. {
  41042. columns.move (columns.indexOf (ci), index);
  41043. ci->width = col->getIntAttribute ("width");
  41044. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41045. }
  41046. ++index;
  41047. }
  41048. columnsResized = true;
  41049. sendColumnsChanged();
  41050. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41051. storedXml->getBoolAttribute ("sortForwards", true));
  41052. }
  41053. }
  41054. void TableHeaderComponent::addListener (Listener* const newListener)
  41055. {
  41056. listeners.addIfNotAlreadyThere (newListener);
  41057. }
  41058. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41059. {
  41060. listeners.removeValue (listenerToRemove);
  41061. }
  41062. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41063. {
  41064. const ColumnInfo* const ci = getInfoForId (columnId);
  41065. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41066. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41067. }
  41068. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41069. {
  41070. for (int i = 0; i < columns.size(); ++i)
  41071. {
  41072. const ColumnInfo* const ci = columns.getUnchecked(i);
  41073. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41074. menu.addItem (ci->id, ci->name,
  41075. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41076. isColumnVisible (ci->id));
  41077. }
  41078. }
  41079. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41080. {
  41081. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41082. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41083. }
  41084. void TableHeaderComponent::paint (Graphics& g)
  41085. {
  41086. LookAndFeel& lf = getLookAndFeel();
  41087. lf.drawTableHeaderBackground (g, *this);
  41088. const Rectangle<int> clip (g.getClipBounds());
  41089. int x = 0;
  41090. for (int i = 0; i < columns.size(); ++i)
  41091. {
  41092. const ColumnInfo* const ci = columns.getUnchecked(i);
  41093. if (ci->isVisible())
  41094. {
  41095. if (x + ci->width > clip.getX()
  41096. && (ci->id != columnIdBeingDragged
  41097. || dragOverlayComp == 0
  41098. || ! dragOverlayComp->isVisible()))
  41099. {
  41100. Graphics::ScopedSaveState ss (g);
  41101. g.setOrigin (x, 0);
  41102. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41103. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41104. ci->id == columnIdUnderMouse,
  41105. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41106. ci->propertyFlags);
  41107. }
  41108. x += ci->width;
  41109. if (x >= clip.getRight())
  41110. break;
  41111. }
  41112. }
  41113. }
  41114. void TableHeaderComponent::resized()
  41115. {
  41116. }
  41117. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41118. {
  41119. updateColumnUnderMouse (e.x, e.y);
  41120. }
  41121. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41122. {
  41123. updateColumnUnderMouse (e.x, e.y);
  41124. }
  41125. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41126. {
  41127. updateColumnUnderMouse (e.x, e.y);
  41128. }
  41129. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41130. {
  41131. repaint();
  41132. columnIdBeingResized = 0;
  41133. columnIdBeingDragged = 0;
  41134. if (columnIdUnderMouse != 0)
  41135. {
  41136. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41137. if (e.mods.isPopupMenu())
  41138. columnClicked (columnIdUnderMouse, e.mods);
  41139. }
  41140. if (menuActive && e.mods.isPopupMenu())
  41141. showColumnChooserMenu (columnIdUnderMouse);
  41142. }
  41143. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41144. {
  41145. if (columnIdBeingResized == 0
  41146. && columnIdBeingDragged == 0
  41147. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41148. {
  41149. dragOverlayComp = 0;
  41150. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41151. if (columnIdBeingResized != 0)
  41152. {
  41153. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41154. initialColumnWidth = ci->width;
  41155. }
  41156. else
  41157. {
  41158. beginDrag (e);
  41159. }
  41160. }
  41161. if (columnIdBeingResized != 0)
  41162. {
  41163. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41164. if (ci != 0)
  41165. {
  41166. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41167. initialColumnWidth + e.getDistanceFromDragStartX());
  41168. if (stretchToFit)
  41169. {
  41170. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41171. int minWidthOnRight = 0;
  41172. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41173. if (columns.getUnchecked (i)->isVisible())
  41174. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41175. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41176. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41177. }
  41178. setColumnWidth (columnIdBeingResized, w);
  41179. }
  41180. }
  41181. else if (columnIdBeingDragged != 0)
  41182. {
  41183. if (e.y >= -50 && e.y < getHeight() + 50)
  41184. {
  41185. if (dragOverlayComp != 0)
  41186. {
  41187. dragOverlayComp->setVisible (true);
  41188. dragOverlayComp->setBounds (jlimit (0,
  41189. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41190. e.x - draggingColumnOffset),
  41191. 0,
  41192. dragOverlayComp->getWidth(),
  41193. getHeight());
  41194. for (int i = columns.size(); --i >= 0;)
  41195. {
  41196. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41197. int newIndex = currentIndex;
  41198. if (newIndex > 0)
  41199. {
  41200. // if the previous column isn't draggable, we can't move our column
  41201. // past it, because that'd change the undraggable column's position..
  41202. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41203. if ((previous->propertyFlags & draggable) != 0)
  41204. {
  41205. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41206. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41207. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41208. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41209. {
  41210. --newIndex;
  41211. }
  41212. }
  41213. }
  41214. if (newIndex < columns.size() - 1)
  41215. {
  41216. // if the next column isn't draggable, we can't move our column
  41217. // past it, because that'd change the undraggable column's position..
  41218. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41219. if ((nextCol->propertyFlags & draggable) != 0)
  41220. {
  41221. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41222. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41223. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41224. > abs (dragOverlayComp->getRight() - rightOfNext))
  41225. {
  41226. ++newIndex;
  41227. }
  41228. }
  41229. }
  41230. if (newIndex != currentIndex)
  41231. moveColumn (columnIdBeingDragged, newIndex);
  41232. else
  41233. break;
  41234. }
  41235. }
  41236. }
  41237. else
  41238. {
  41239. endDrag (draggingColumnOriginalIndex);
  41240. }
  41241. }
  41242. }
  41243. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41244. {
  41245. if (columnIdBeingDragged == 0)
  41246. {
  41247. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41248. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41249. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41250. {
  41251. columnIdBeingDragged = 0;
  41252. }
  41253. else
  41254. {
  41255. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41256. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41257. const int temp = columnIdBeingDragged;
  41258. columnIdBeingDragged = 0;
  41259. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41260. columnIdBeingDragged = temp;
  41261. dragOverlayComp->setBounds (columnRect);
  41262. for (int i = listeners.size(); --i >= 0;)
  41263. {
  41264. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41265. i = jmin (i, listeners.size() - 1);
  41266. }
  41267. }
  41268. }
  41269. }
  41270. void TableHeaderComponent::endDrag (const int finalIndex)
  41271. {
  41272. if (columnIdBeingDragged != 0)
  41273. {
  41274. moveColumn (columnIdBeingDragged, finalIndex);
  41275. columnIdBeingDragged = 0;
  41276. repaint();
  41277. for (int i = listeners.size(); --i >= 0;)
  41278. {
  41279. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41280. i = jmin (i, listeners.size() - 1);
  41281. }
  41282. }
  41283. }
  41284. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41285. {
  41286. mouseDrag (e);
  41287. for (int i = columns.size(); --i >= 0;)
  41288. if (columns.getUnchecked (i)->isVisible())
  41289. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41290. columnIdBeingResized = 0;
  41291. repaint();
  41292. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41293. updateColumnUnderMouse (e.x, e.y);
  41294. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41295. columnClicked (columnIdUnderMouse, e.mods);
  41296. dragOverlayComp = 0;
  41297. }
  41298. const MouseCursor TableHeaderComponent::getMouseCursor()
  41299. {
  41300. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41301. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41302. return Component::getMouseCursor();
  41303. }
  41304. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41305. {
  41306. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41307. }
  41308. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41309. {
  41310. for (int i = columns.size(); --i >= 0;)
  41311. if (columns.getUnchecked(i)->id == id)
  41312. return columns.getUnchecked(i);
  41313. return 0;
  41314. }
  41315. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41316. {
  41317. int n = 0;
  41318. for (int i = 0; i < columns.size(); ++i)
  41319. {
  41320. if (columns.getUnchecked(i)->isVisible())
  41321. {
  41322. if (n == visibleIndex)
  41323. return i;
  41324. ++n;
  41325. }
  41326. }
  41327. return -1;
  41328. }
  41329. void TableHeaderComponent::sendColumnsChanged()
  41330. {
  41331. if (stretchToFit && lastDeliberateWidth > 0)
  41332. resizeAllColumnsToFit (lastDeliberateWidth);
  41333. repaint();
  41334. columnsChanged = true;
  41335. triggerAsyncUpdate();
  41336. }
  41337. void TableHeaderComponent::handleAsyncUpdate()
  41338. {
  41339. const bool changed = columnsChanged || sortChanged;
  41340. const bool sized = columnsResized || changed;
  41341. const bool sorted = sortChanged;
  41342. columnsChanged = false;
  41343. columnsResized = false;
  41344. sortChanged = false;
  41345. if (sorted)
  41346. {
  41347. for (int i = listeners.size(); --i >= 0;)
  41348. {
  41349. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41350. i = jmin (i, listeners.size() - 1);
  41351. }
  41352. }
  41353. if (changed)
  41354. {
  41355. for (int i = listeners.size(); --i >= 0;)
  41356. {
  41357. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41358. i = jmin (i, listeners.size() - 1);
  41359. }
  41360. }
  41361. if (sized)
  41362. {
  41363. for (int i = listeners.size(); --i >= 0;)
  41364. {
  41365. listeners.getUnchecked(i)->tableColumnsResized (this);
  41366. i = jmin (i, listeners.size() - 1);
  41367. }
  41368. }
  41369. }
  41370. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41371. {
  41372. if (isPositiveAndBelow (mouseX, getWidth()))
  41373. {
  41374. const int draggableDistance = 3;
  41375. int x = 0;
  41376. for (int i = 0; i < columns.size(); ++i)
  41377. {
  41378. const ColumnInfo* const ci = columns.getUnchecked(i);
  41379. if (ci->isVisible())
  41380. {
  41381. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41382. && (ci->propertyFlags & resizable) != 0)
  41383. return ci->id;
  41384. x += ci->width;
  41385. }
  41386. }
  41387. }
  41388. return 0;
  41389. }
  41390. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41391. {
  41392. const int newCol = (reallyContains (Point<int> (x, y), true) && getResizeDraggerAt (x) == 0)
  41393. ? getColumnIdAtX (x) : 0;
  41394. if (newCol != columnIdUnderMouse)
  41395. {
  41396. columnIdUnderMouse = newCol;
  41397. repaint();
  41398. }
  41399. }
  41400. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41401. {
  41402. PopupMenu m;
  41403. addMenuItems (m, columnIdClicked);
  41404. if (m.getNumItems() > 0)
  41405. {
  41406. m.setLookAndFeel (&getLookAndFeel());
  41407. const int result = m.show();
  41408. if (result != 0)
  41409. reactToMenuItem (result, columnIdClicked);
  41410. }
  41411. }
  41412. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41413. {
  41414. }
  41415. END_JUCE_NAMESPACE
  41416. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41417. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41418. BEGIN_JUCE_NAMESPACE
  41419. class TableListRowComp : public Component,
  41420. public TooltipClient
  41421. {
  41422. public:
  41423. TableListRowComp (TableListBox& owner_)
  41424. : owner (owner_), row (-1), isSelected (false)
  41425. {
  41426. }
  41427. void paint (Graphics& g)
  41428. {
  41429. TableListBoxModel* const model = owner.getModel();
  41430. if (model != 0)
  41431. {
  41432. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41433. const TableHeaderComponent& header = owner.getHeader();
  41434. const int numColumns = header.getNumColumns (true);
  41435. for (int i = 0; i < numColumns; ++i)
  41436. {
  41437. if (columnComponents[i] == 0)
  41438. {
  41439. const int columnId = header.getColumnIdOfIndex (i, true);
  41440. const Rectangle<int> columnRect (header.getColumnPosition(i).withHeight (getHeight()));
  41441. Graphics::ScopedSaveState ss (g);
  41442. g.reduceClipRegion (columnRect);
  41443. g.setOrigin (columnRect.getX(), 0);
  41444. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41445. }
  41446. }
  41447. }
  41448. }
  41449. void update (const int newRow, const bool isNowSelected)
  41450. {
  41451. jassert (newRow >= 0);
  41452. if (newRow != row || isNowSelected != isSelected)
  41453. {
  41454. row = newRow;
  41455. isSelected = isNowSelected;
  41456. repaint();
  41457. }
  41458. TableListBoxModel* const model = owner.getModel();
  41459. if (model != 0 && row < owner.getNumRows())
  41460. {
  41461. const Identifier columnProperty ("_tableColumnId");
  41462. const int numColumns = owner.getHeader().getNumColumns (true);
  41463. for (int i = 0; i < numColumns; ++i)
  41464. {
  41465. const int columnId = owner.getHeader().getColumnIdOfIndex (i, true);
  41466. Component* comp = columnComponents[i];
  41467. if (comp != 0 && columnId != (int) comp->getProperties() [columnProperty])
  41468. {
  41469. columnComponents.set (i, 0);
  41470. comp = 0;
  41471. }
  41472. comp = model->refreshComponentForCell (row, columnId, isSelected, comp);
  41473. columnComponents.set (i, comp, false);
  41474. if (comp != 0)
  41475. {
  41476. comp->getProperties().set (columnProperty, columnId);
  41477. addAndMakeVisible (comp);
  41478. resizeCustomComp (i);
  41479. }
  41480. }
  41481. columnComponents.removeRange (numColumns, columnComponents.size());
  41482. }
  41483. else
  41484. {
  41485. columnComponents.clear();
  41486. }
  41487. }
  41488. void resized()
  41489. {
  41490. for (int i = columnComponents.size(); --i >= 0;)
  41491. resizeCustomComp (i);
  41492. }
  41493. void resizeCustomComp (const int index)
  41494. {
  41495. Component* const c = columnComponents.getUnchecked (index);
  41496. if (c != 0)
  41497. c->setBounds (owner.getHeader().getColumnPosition (index)
  41498. .withY (0).withHeight (getHeight()));
  41499. }
  41500. void mouseDown (const MouseEvent& e)
  41501. {
  41502. isDragging = false;
  41503. selectRowOnMouseUp = false;
  41504. if (isEnabled())
  41505. {
  41506. if (! isSelected)
  41507. {
  41508. owner.selectRowsBasedOnModifierKeys (row, e.mods, false);
  41509. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41510. if (columnId != 0 && owner.getModel() != 0)
  41511. owner.getModel()->cellClicked (row, columnId, e);
  41512. }
  41513. else
  41514. {
  41515. selectRowOnMouseUp = true;
  41516. }
  41517. }
  41518. }
  41519. void mouseDrag (const MouseEvent& e)
  41520. {
  41521. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41522. {
  41523. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41524. if (selectedRows.size() > 0)
  41525. {
  41526. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41527. if (dragDescription.isNotEmpty())
  41528. {
  41529. isDragging = true;
  41530. owner.startDragAndDrop (e, dragDescription);
  41531. }
  41532. }
  41533. }
  41534. }
  41535. void mouseUp (const MouseEvent& e)
  41536. {
  41537. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41538. {
  41539. owner.selectRowsBasedOnModifierKeys (row, e.mods, true);
  41540. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41541. if (columnId != 0 && owner.getModel() != 0)
  41542. owner.getModel()->cellClicked (row, columnId, e);
  41543. }
  41544. }
  41545. void mouseDoubleClick (const MouseEvent& e)
  41546. {
  41547. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41548. if (columnId != 0 && owner.getModel() != 0)
  41549. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41550. }
  41551. const String getTooltip()
  41552. {
  41553. const int columnId = owner.getHeader().getColumnIdAtX (getMouseXYRelative().getX());
  41554. if (columnId != 0 && owner.getModel() != 0)
  41555. return owner.getModel()->getCellTooltip (row, columnId);
  41556. return String::empty;
  41557. }
  41558. Component* findChildComponentForColumn (const int columnId) const
  41559. {
  41560. return columnComponents [owner.getHeader().getIndexOfColumnId (columnId, true)];
  41561. }
  41562. private:
  41563. TableListBox& owner;
  41564. OwnedArray<Component> columnComponents;
  41565. int row;
  41566. bool isSelected, isDragging, selectRowOnMouseUp;
  41567. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListRowComp);
  41568. };
  41569. class TableListBoxHeader : public TableHeaderComponent
  41570. {
  41571. public:
  41572. TableListBoxHeader (TableListBox& owner_)
  41573. : owner (owner_)
  41574. {
  41575. }
  41576. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41577. {
  41578. if (owner.isAutoSizeMenuOptionShown())
  41579. {
  41580. menu.addItem (autoSizeColumnId, TRANS("Auto-size this column"), columnIdClicked != 0);
  41581. menu.addItem (autoSizeAllId, TRANS("Auto-size all columns"), owner.getHeader().getNumColumns (true) > 0);
  41582. menu.addSeparator();
  41583. }
  41584. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41585. }
  41586. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41587. {
  41588. switch (menuReturnId)
  41589. {
  41590. case autoSizeColumnId: owner.autoSizeColumn (columnIdClicked); break;
  41591. case autoSizeAllId: owner.autoSizeAllColumns(); break;
  41592. default: TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked); break;
  41593. }
  41594. }
  41595. private:
  41596. TableListBox& owner;
  41597. enum { autoSizeColumnId = 0xf836743, autoSizeAllId = 0xf836744 };
  41598. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBoxHeader);
  41599. };
  41600. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41601. : ListBox (name, 0),
  41602. header (0), model (model_),
  41603. autoSizeOptionsShown (true)
  41604. {
  41605. ListBox::model = this;
  41606. setHeader (new TableListBoxHeader (*this));
  41607. }
  41608. TableListBox::~TableListBox()
  41609. {
  41610. header = 0;
  41611. }
  41612. void TableListBox::setModel (TableListBoxModel* const newModel)
  41613. {
  41614. if (model != newModel)
  41615. {
  41616. model = newModel;
  41617. updateContent();
  41618. }
  41619. }
  41620. void TableListBox::setHeader (TableHeaderComponent* newHeader)
  41621. {
  41622. jassert (newHeader != 0); // you need to supply a real header for a table!
  41623. Rectangle<int> newBounds (0, 0, 100, 28);
  41624. if (header != 0)
  41625. newBounds = header->getBounds();
  41626. header = newHeader;
  41627. header->setBounds (newBounds);
  41628. setHeaderComponent (header);
  41629. header->addListener (this);
  41630. }
  41631. int TableListBox::getHeaderHeight() const
  41632. {
  41633. return header->getHeight();
  41634. }
  41635. void TableListBox::setHeaderHeight (const int newHeight)
  41636. {
  41637. header->setSize (header->getWidth(), newHeight);
  41638. resized();
  41639. }
  41640. void TableListBox::autoSizeColumn (const int columnId)
  41641. {
  41642. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41643. if (width > 0)
  41644. header->setColumnWidth (columnId, width);
  41645. }
  41646. void TableListBox::autoSizeAllColumns()
  41647. {
  41648. for (int i = 0; i < header->getNumColumns (true); ++i)
  41649. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41650. }
  41651. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41652. {
  41653. autoSizeOptionsShown = shouldBeShown;
  41654. }
  41655. bool TableListBox::isAutoSizeMenuOptionShown() const
  41656. {
  41657. return autoSizeOptionsShown;
  41658. }
  41659. const Rectangle<int> TableListBox::getCellPosition (const int columnId, const int rowNumber,
  41660. const bool relativeToComponentTopLeft) const
  41661. {
  41662. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41663. if (relativeToComponentTopLeft)
  41664. headerCell.translate (header->getX(), 0);
  41665. return getRowPosition (rowNumber, relativeToComponentTopLeft)
  41666. .withX (headerCell.getX())
  41667. .withWidth (headerCell.getWidth());
  41668. }
  41669. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  41670. {
  41671. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  41672. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  41673. }
  41674. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41675. {
  41676. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41677. if (scrollbar != 0)
  41678. {
  41679. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41680. double x = scrollbar->getCurrentRangeStart();
  41681. const double w = scrollbar->getCurrentRangeSize();
  41682. if (pos.getX() < x)
  41683. x = pos.getX();
  41684. else if (pos.getRight() > x + w)
  41685. x += jmax (0.0, pos.getRight() - (x + w));
  41686. scrollbar->setCurrentRangeStart (x);
  41687. }
  41688. }
  41689. int TableListBox::getNumRows()
  41690. {
  41691. return model != 0 ? model->getNumRows() : 0;
  41692. }
  41693. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41694. {
  41695. }
  41696. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41697. {
  41698. if (existingComponentToUpdate == 0)
  41699. existingComponentToUpdate = new TableListRowComp (*this);
  41700. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41701. return existingComponentToUpdate;
  41702. }
  41703. void TableListBox::selectedRowsChanged (int row)
  41704. {
  41705. if (model != 0)
  41706. model->selectedRowsChanged (row);
  41707. }
  41708. void TableListBox::deleteKeyPressed (int row)
  41709. {
  41710. if (model != 0)
  41711. model->deleteKeyPressed (row);
  41712. }
  41713. void TableListBox::returnKeyPressed (int row)
  41714. {
  41715. if (model != 0)
  41716. model->returnKeyPressed (row);
  41717. }
  41718. void TableListBox::backgroundClicked()
  41719. {
  41720. if (model != 0)
  41721. model->backgroundClicked();
  41722. }
  41723. void TableListBox::listWasScrolled()
  41724. {
  41725. if (model != 0)
  41726. model->listWasScrolled();
  41727. }
  41728. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41729. {
  41730. setMinimumContentWidth (header->getTotalWidth());
  41731. repaint();
  41732. updateColumnComponents();
  41733. }
  41734. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41735. {
  41736. setMinimumContentWidth (header->getTotalWidth());
  41737. repaint();
  41738. updateColumnComponents();
  41739. }
  41740. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  41741. {
  41742. if (model != 0)
  41743. model->sortOrderChanged (header->getSortColumnId(),
  41744. header->isSortedForwards());
  41745. }
  41746. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  41747. {
  41748. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  41749. repaint();
  41750. }
  41751. void TableListBox::resized()
  41752. {
  41753. ListBox::resized();
  41754. header->resizeAllColumnsToFit (getVisibleContentWidth());
  41755. setMinimumContentWidth (header->getTotalWidth());
  41756. }
  41757. void TableListBox::updateColumnComponents() const
  41758. {
  41759. const int firstRow = getRowContainingPosition (0, 0);
  41760. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  41761. {
  41762. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  41763. if (rowComp != 0)
  41764. rowComp->resized();
  41765. }
  41766. }
  41767. void TableListBoxModel::cellClicked (int, int, const MouseEvent&) {}
  41768. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&) {}
  41769. void TableListBoxModel::backgroundClicked() {}
  41770. void TableListBoxModel::sortOrderChanged (int, const bool) {}
  41771. int TableListBoxModel::getColumnAutoSizeWidth (int) { return 0; }
  41772. void TableListBoxModel::selectedRowsChanged (int) {}
  41773. void TableListBoxModel::deleteKeyPressed (int) {}
  41774. void TableListBoxModel::returnKeyPressed (int) {}
  41775. void TableListBoxModel::listWasScrolled() {}
  41776. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/) { return String::empty; }
  41777. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  41778. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  41779. {
  41780. (void) existingComponentToUpdate;
  41781. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  41782. return 0;
  41783. }
  41784. END_JUCE_NAMESPACE
  41785. /*** End of inlined file: juce_TableListBox.cpp ***/
  41786. /*** Start of inlined file: juce_TextEditor.cpp ***/
  41787. BEGIN_JUCE_NAMESPACE
  41788. // a word or space that can't be broken down any further
  41789. struct TextAtom
  41790. {
  41791. String atomText;
  41792. float width;
  41793. int numChars;
  41794. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  41795. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  41796. const String getText (const juce_wchar passwordCharacter) const
  41797. {
  41798. if (passwordCharacter == 0)
  41799. return atomText;
  41800. else
  41801. return String::repeatedString (String::charToString (passwordCharacter),
  41802. atomText.length());
  41803. }
  41804. const String getTrimmedText (const juce_wchar passwordCharacter) const
  41805. {
  41806. if (passwordCharacter == 0)
  41807. return atomText.substring (0, numChars);
  41808. else if (isNewLine())
  41809. return String::empty;
  41810. else
  41811. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  41812. }
  41813. };
  41814. // a run of text with a single font and colour
  41815. class TextEditor::UniformTextSection
  41816. {
  41817. public:
  41818. UniformTextSection (const String& text,
  41819. const Font& font_,
  41820. const Colour& colour_,
  41821. const juce_wchar passwordCharacter)
  41822. : font (font_),
  41823. colour (colour_)
  41824. {
  41825. initialiseAtoms (text, passwordCharacter);
  41826. }
  41827. UniformTextSection (const UniformTextSection& other)
  41828. : font (other.font),
  41829. colour (other.colour)
  41830. {
  41831. atoms.ensureStorageAllocated (other.atoms.size());
  41832. for (int i = 0; i < other.atoms.size(); ++i)
  41833. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  41834. }
  41835. ~UniformTextSection()
  41836. {
  41837. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  41838. }
  41839. void clear()
  41840. {
  41841. for (int i = atoms.size(); --i >= 0;)
  41842. delete getAtom(i);
  41843. atoms.clear();
  41844. }
  41845. int getNumAtoms() const
  41846. {
  41847. return atoms.size();
  41848. }
  41849. TextAtom* getAtom (const int index) const throw()
  41850. {
  41851. return atoms.getUnchecked (index);
  41852. }
  41853. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  41854. {
  41855. if (other.atoms.size() > 0)
  41856. {
  41857. TextAtom* const lastAtom = atoms.getLast();
  41858. int i = 0;
  41859. if (lastAtom != 0)
  41860. {
  41861. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  41862. {
  41863. TextAtom* const first = other.getAtom(0);
  41864. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  41865. {
  41866. lastAtom->atomText += first->atomText;
  41867. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  41868. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  41869. delete first;
  41870. ++i;
  41871. }
  41872. }
  41873. }
  41874. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  41875. while (i < other.atoms.size())
  41876. {
  41877. atoms.add (other.getAtom(i));
  41878. ++i;
  41879. }
  41880. }
  41881. }
  41882. UniformTextSection* split (const int indexToBreakAt,
  41883. const juce_wchar passwordCharacter)
  41884. {
  41885. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  41886. font, colour,
  41887. passwordCharacter);
  41888. int index = 0;
  41889. for (int i = 0; i < atoms.size(); ++i)
  41890. {
  41891. TextAtom* const atom = getAtom(i);
  41892. const int nextIndex = index + atom->numChars;
  41893. if (index == indexToBreakAt)
  41894. {
  41895. int j;
  41896. for (j = i; j < atoms.size(); ++j)
  41897. section2->atoms.add (getAtom (j));
  41898. for (j = atoms.size(); --j >= i;)
  41899. atoms.remove (j);
  41900. break;
  41901. }
  41902. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  41903. {
  41904. TextAtom* const secondAtom = new TextAtom();
  41905. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  41906. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  41907. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  41908. section2->atoms.add (secondAtom);
  41909. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  41910. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41911. atom->numChars = (uint16) (indexToBreakAt - index);
  41912. int j;
  41913. for (j = i + 1; j < atoms.size(); ++j)
  41914. section2->atoms.add (getAtom (j));
  41915. for (j = atoms.size(); --j > i;)
  41916. atoms.remove (j);
  41917. break;
  41918. }
  41919. index = nextIndex;
  41920. }
  41921. return section2;
  41922. }
  41923. void appendAllText (String::Concatenator& concatenator) const
  41924. {
  41925. for (int i = 0; i < atoms.size(); ++i)
  41926. concatenator.append (getAtom(i)->atomText);
  41927. }
  41928. void appendSubstring (String::Concatenator& concatenator,
  41929. const Range<int>& range) const
  41930. {
  41931. int index = 0;
  41932. for (int i = 0; i < atoms.size(); ++i)
  41933. {
  41934. const TextAtom* const atom = getAtom (i);
  41935. const int nextIndex = index + atom->numChars;
  41936. if (range.getStart() < nextIndex)
  41937. {
  41938. if (range.getEnd() <= index)
  41939. break;
  41940. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  41941. if (! r.isEmpty())
  41942. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  41943. }
  41944. index = nextIndex;
  41945. }
  41946. }
  41947. int getTotalLength() const
  41948. {
  41949. int total = 0;
  41950. for (int i = atoms.size(); --i >= 0;)
  41951. total += getAtom(i)->numChars;
  41952. return total;
  41953. }
  41954. void setFont (const Font& newFont,
  41955. const juce_wchar passwordCharacter)
  41956. {
  41957. if (font != newFont)
  41958. {
  41959. font = newFont;
  41960. for (int i = atoms.size(); --i >= 0;)
  41961. {
  41962. TextAtom* const atom = atoms.getUnchecked(i);
  41963. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  41964. }
  41965. }
  41966. }
  41967. Font font;
  41968. Colour colour;
  41969. private:
  41970. Array <TextAtom*> atoms;
  41971. void initialiseAtoms (const String& textToParse,
  41972. const juce_wchar passwordCharacter)
  41973. {
  41974. String::CharPointerType text (textToParse.getCharPointer());
  41975. while (! text.isEmpty())
  41976. {
  41977. int numChars = 0;
  41978. String::CharPointerType start (text);
  41979. // create a whitespace atom unless it starts with non-ws
  41980. if (text.isWhitespace() && *text != '\r' && *text != '\n')
  41981. {
  41982. do
  41983. {
  41984. ++text;
  41985. ++numChars;
  41986. }
  41987. while (text.isWhitespace() && *text != '\r' && *text != '\n');
  41988. }
  41989. else
  41990. {
  41991. if (*text == '\r')
  41992. {
  41993. ++text;
  41994. ++numChars;
  41995. if (*text == '\n')
  41996. {
  41997. ++start;
  41998. ++text;
  41999. }
  42000. }
  42001. else if (*text == '\n')
  42002. {
  42003. ++text;
  42004. ++numChars;
  42005. }
  42006. else
  42007. {
  42008. while (! (text.isEmpty() || text.isWhitespace()))
  42009. {
  42010. ++text;
  42011. ++numChars;
  42012. }
  42013. }
  42014. }
  42015. TextAtom* const atom = new TextAtom();
  42016. atom->atomText = String (start, numChars);
  42017. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42018. atom->numChars = (uint16) numChars;
  42019. atoms.add (atom);
  42020. }
  42021. }
  42022. UniformTextSection& operator= (const UniformTextSection& other);
  42023. JUCE_LEAK_DETECTOR (UniformTextSection);
  42024. };
  42025. class TextEditor::Iterator
  42026. {
  42027. public:
  42028. Iterator (const Array <UniformTextSection*>& sections_,
  42029. const float wordWrapWidth_,
  42030. const juce_wchar passwordCharacter_)
  42031. : indexInText (0),
  42032. lineY (0),
  42033. lineHeight (0),
  42034. maxDescent (0),
  42035. atomX (0),
  42036. atomRight (0),
  42037. atom (0),
  42038. currentSection (0),
  42039. sections (sections_),
  42040. sectionIndex (0),
  42041. atomIndex (0),
  42042. wordWrapWidth (wordWrapWidth_),
  42043. passwordCharacter (passwordCharacter_)
  42044. {
  42045. jassert (wordWrapWidth_ > 0);
  42046. if (sections.size() > 0)
  42047. {
  42048. currentSection = sections.getUnchecked (sectionIndex);
  42049. if (currentSection != 0)
  42050. beginNewLine();
  42051. }
  42052. }
  42053. Iterator (const Iterator& other)
  42054. : indexInText (other.indexInText),
  42055. lineY (other.lineY),
  42056. lineHeight (other.lineHeight),
  42057. maxDescent (other.maxDescent),
  42058. atomX (other.atomX),
  42059. atomRight (other.atomRight),
  42060. atom (other.atom),
  42061. currentSection (other.currentSection),
  42062. sections (other.sections),
  42063. sectionIndex (other.sectionIndex),
  42064. atomIndex (other.atomIndex),
  42065. wordWrapWidth (other.wordWrapWidth),
  42066. passwordCharacter (other.passwordCharacter),
  42067. tempAtom (other.tempAtom)
  42068. {
  42069. }
  42070. bool next()
  42071. {
  42072. if (atom == &tempAtom)
  42073. {
  42074. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42075. if (numRemaining > 0)
  42076. {
  42077. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42078. atomX = 0;
  42079. if (tempAtom.numChars > 0)
  42080. lineY += lineHeight;
  42081. indexInText += tempAtom.numChars;
  42082. GlyphArrangement g;
  42083. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42084. int split;
  42085. for (split = 0; split < g.getNumGlyphs(); ++split)
  42086. if (shouldWrap (g.getGlyph (split).getRight()))
  42087. break;
  42088. if (split > 0 && split <= numRemaining)
  42089. {
  42090. tempAtom.numChars = (uint16) split;
  42091. tempAtom.width = g.getGlyph (split - 1).getRight();
  42092. atomRight = atomX + tempAtom.width;
  42093. return true;
  42094. }
  42095. }
  42096. }
  42097. bool forceNewLine = false;
  42098. if (sectionIndex >= sections.size())
  42099. {
  42100. moveToEndOfLastAtom();
  42101. return false;
  42102. }
  42103. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42104. {
  42105. if (atomIndex >= currentSection->getNumAtoms())
  42106. {
  42107. if (++sectionIndex >= sections.size())
  42108. {
  42109. moveToEndOfLastAtom();
  42110. return false;
  42111. }
  42112. atomIndex = 0;
  42113. currentSection = sections.getUnchecked (sectionIndex);
  42114. }
  42115. else
  42116. {
  42117. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42118. if (! lastAtom->isWhitespace())
  42119. {
  42120. // handle the case where the last atom in a section is actually part of the same
  42121. // word as the first atom of the next section...
  42122. float right = atomRight + lastAtom->width;
  42123. float lineHeight2 = lineHeight;
  42124. float maxDescent2 = maxDescent;
  42125. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42126. {
  42127. const UniformTextSection* const s = sections.getUnchecked (section);
  42128. if (s->getNumAtoms() == 0)
  42129. break;
  42130. const TextAtom* const nextAtom = s->getAtom (0);
  42131. if (nextAtom->isWhitespace())
  42132. break;
  42133. right += nextAtom->width;
  42134. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42135. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42136. if (shouldWrap (right))
  42137. {
  42138. lineHeight = lineHeight2;
  42139. maxDescent = maxDescent2;
  42140. forceNewLine = true;
  42141. break;
  42142. }
  42143. if (s->getNumAtoms() > 1)
  42144. break;
  42145. }
  42146. }
  42147. }
  42148. }
  42149. if (atom != 0)
  42150. {
  42151. atomX = atomRight;
  42152. indexInText += atom->numChars;
  42153. if (atom->isNewLine())
  42154. beginNewLine();
  42155. }
  42156. atom = currentSection->getAtom (atomIndex);
  42157. atomRight = atomX + atom->width;
  42158. ++atomIndex;
  42159. if (shouldWrap (atomRight) || forceNewLine)
  42160. {
  42161. if (atom->isWhitespace())
  42162. {
  42163. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42164. atomRight = jmin (atomRight, wordWrapWidth);
  42165. }
  42166. else
  42167. {
  42168. atomRight = atom->width;
  42169. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42170. {
  42171. tempAtom = *atom;
  42172. tempAtom.width = 0;
  42173. tempAtom.numChars = 0;
  42174. atom = &tempAtom;
  42175. if (atomX > 0)
  42176. beginNewLine();
  42177. return next();
  42178. }
  42179. beginNewLine();
  42180. return true;
  42181. }
  42182. }
  42183. return true;
  42184. }
  42185. void beginNewLine()
  42186. {
  42187. atomX = 0;
  42188. lineY += lineHeight;
  42189. int tempSectionIndex = sectionIndex;
  42190. int tempAtomIndex = atomIndex;
  42191. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42192. lineHeight = section->font.getHeight();
  42193. maxDescent = section->font.getDescent();
  42194. float x = (atom != 0) ? atom->width : 0;
  42195. while (! shouldWrap (x))
  42196. {
  42197. if (tempSectionIndex >= sections.size())
  42198. break;
  42199. bool checkSize = false;
  42200. if (tempAtomIndex >= section->getNumAtoms())
  42201. {
  42202. if (++tempSectionIndex >= sections.size())
  42203. break;
  42204. tempAtomIndex = 0;
  42205. section = sections.getUnchecked (tempSectionIndex);
  42206. checkSize = true;
  42207. }
  42208. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42209. if (nextAtom == 0)
  42210. break;
  42211. x += nextAtom->width;
  42212. if (shouldWrap (x) || nextAtom->isNewLine())
  42213. break;
  42214. if (checkSize)
  42215. {
  42216. lineHeight = jmax (lineHeight, section->font.getHeight());
  42217. maxDescent = jmax (maxDescent, section->font.getDescent());
  42218. }
  42219. ++tempAtomIndex;
  42220. }
  42221. }
  42222. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42223. {
  42224. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42225. {
  42226. if (lastSection != currentSection)
  42227. {
  42228. lastSection = currentSection;
  42229. g.setColour (currentSection->colour);
  42230. g.setFont (currentSection->font);
  42231. }
  42232. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42233. GlyphArrangement ga;
  42234. ga.addLineOfText (currentSection->font,
  42235. atom->getTrimmedText (passwordCharacter),
  42236. atomX,
  42237. (float) roundToInt (lineY + lineHeight - maxDescent));
  42238. ga.draw (g);
  42239. }
  42240. }
  42241. void drawSelection (Graphics& g,
  42242. const Range<int>& selection) const
  42243. {
  42244. const int startX = roundToInt (indexToX (selection.getStart()));
  42245. const int endX = roundToInt (indexToX (selection.getEnd()));
  42246. const int y = roundToInt (lineY);
  42247. const int nextY = roundToInt (lineY + lineHeight);
  42248. g.fillRect (startX, y, endX - startX, nextY - y);
  42249. }
  42250. void drawSelectedText (Graphics& g,
  42251. const Range<int>& selection,
  42252. const Colour& selectedTextColour) const
  42253. {
  42254. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42255. {
  42256. GlyphArrangement ga;
  42257. ga.addLineOfText (currentSection->font,
  42258. atom->getTrimmedText (passwordCharacter),
  42259. atomX,
  42260. (float) roundToInt (lineY + lineHeight - maxDescent));
  42261. if (selection.getEnd() < indexInText + atom->numChars)
  42262. {
  42263. GlyphArrangement ga2 (ga);
  42264. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42265. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42266. g.setColour (currentSection->colour);
  42267. ga2.draw (g);
  42268. }
  42269. if (selection.getStart() > indexInText)
  42270. {
  42271. GlyphArrangement ga2 (ga);
  42272. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42273. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42274. g.setColour (currentSection->colour);
  42275. ga2.draw (g);
  42276. }
  42277. g.setColour (selectedTextColour);
  42278. ga.draw (g);
  42279. }
  42280. }
  42281. float indexToX (const int indexToFind) const
  42282. {
  42283. if (indexToFind <= indexInText)
  42284. return atomX;
  42285. if (indexToFind >= indexInText + atom->numChars)
  42286. return atomRight;
  42287. GlyphArrangement g;
  42288. g.addLineOfText (currentSection->font,
  42289. atom->getText (passwordCharacter),
  42290. atomX, 0.0f);
  42291. if (indexToFind - indexInText >= g.getNumGlyphs())
  42292. return atomRight;
  42293. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42294. }
  42295. int xToIndex (const float xToFind) const
  42296. {
  42297. if (xToFind <= atomX || atom->isNewLine())
  42298. return indexInText;
  42299. if (xToFind >= atomRight)
  42300. return indexInText + atom->numChars;
  42301. GlyphArrangement g;
  42302. g.addLineOfText (currentSection->font,
  42303. atom->getText (passwordCharacter),
  42304. atomX, 0.0f);
  42305. int j;
  42306. for (j = 0; j < g.getNumGlyphs(); ++j)
  42307. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42308. break;
  42309. return indexInText + j;
  42310. }
  42311. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42312. {
  42313. while (next())
  42314. {
  42315. if (indexInText + atom->numChars > index)
  42316. {
  42317. cx = indexToX (index);
  42318. cy = lineY;
  42319. lineHeight_ = lineHeight;
  42320. return true;
  42321. }
  42322. }
  42323. cx = atomX;
  42324. cy = lineY;
  42325. lineHeight_ = lineHeight;
  42326. return false;
  42327. }
  42328. int indexInText;
  42329. float lineY, lineHeight, maxDescent;
  42330. float atomX, atomRight;
  42331. const TextAtom* atom;
  42332. const UniformTextSection* currentSection;
  42333. private:
  42334. const Array <UniformTextSection*>& sections;
  42335. int sectionIndex, atomIndex;
  42336. const float wordWrapWidth;
  42337. const juce_wchar passwordCharacter;
  42338. TextAtom tempAtom;
  42339. Iterator& operator= (const Iterator&);
  42340. void moveToEndOfLastAtom()
  42341. {
  42342. if (atom != 0)
  42343. {
  42344. atomX = atomRight;
  42345. if (atom->isNewLine())
  42346. {
  42347. atomX = 0.0f;
  42348. lineY += lineHeight;
  42349. }
  42350. }
  42351. }
  42352. bool shouldWrap (const float x) const
  42353. {
  42354. return (x - 0.0001f) >= wordWrapWidth;
  42355. }
  42356. JUCE_LEAK_DETECTOR (Iterator);
  42357. };
  42358. class TextEditor::InsertAction : public UndoableAction
  42359. {
  42360. public:
  42361. InsertAction (TextEditor& owner_,
  42362. const String& text_,
  42363. const int insertIndex_,
  42364. const Font& font_,
  42365. const Colour& colour_,
  42366. const int oldCaretPos_,
  42367. const int newCaretPos_)
  42368. : owner (owner_),
  42369. text (text_),
  42370. insertIndex (insertIndex_),
  42371. oldCaretPos (oldCaretPos_),
  42372. newCaretPos (newCaretPos_),
  42373. font (font_),
  42374. colour (colour_)
  42375. {
  42376. }
  42377. bool perform()
  42378. {
  42379. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42380. return true;
  42381. }
  42382. bool undo()
  42383. {
  42384. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42385. return true;
  42386. }
  42387. int getSizeInUnits()
  42388. {
  42389. return text.length() + 16;
  42390. }
  42391. private:
  42392. TextEditor& owner;
  42393. const String text;
  42394. const int insertIndex, oldCaretPos, newCaretPos;
  42395. const Font font;
  42396. const Colour colour;
  42397. JUCE_DECLARE_NON_COPYABLE (InsertAction);
  42398. };
  42399. class TextEditor::RemoveAction : public UndoableAction
  42400. {
  42401. public:
  42402. RemoveAction (TextEditor& owner_,
  42403. const Range<int> range_,
  42404. const int oldCaretPos_,
  42405. const int newCaretPos_,
  42406. const Array <UniformTextSection*>& removedSections_)
  42407. : owner (owner_),
  42408. range (range_),
  42409. oldCaretPos (oldCaretPos_),
  42410. newCaretPos (newCaretPos_),
  42411. removedSections (removedSections_)
  42412. {
  42413. }
  42414. ~RemoveAction()
  42415. {
  42416. for (int i = removedSections.size(); --i >= 0;)
  42417. {
  42418. UniformTextSection* const section = removedSections.getUnchecked (i);
  42419. section->clear();
  42420. delete section;
  42421. }
  42422. }
  42423. bool perform()
  42424. {
  42425. owner.remove (range, 0, newCaretPos);
  42426. return true;
  42427. }
  42428. bool undo()
  42429. {
  42430. owner.reinsert (range.getStart(), removedSections);
  42431. owner.moveCursorTo (oldCaretPos, false);
  42432. return true;
  42433. }
  42434. int getSizeInUnits()
  42435. {
  42436. int n = 0;
  42437. for (int i = removedSections.size(); --i >= 0;)
  42438. n += removedSections.getUnchecked (i)->getTotalLength();
  42439. return n + 16;
  42440. }
  42441. private:
  42442. TextEditor& owner;
  42443. const Range<int> range;
  42444. const int oldCaretPos, newCaretPos;
  42445. Array <UniformTextSection*> removedSections;
  42446. JUCE_DECLARE_NON_COPYABLE (RemoveAction);
  42447. };
  42448. class TextEditor::TextHolderComponent : public Component,
  42449. public Timer,
  42450. public ValueListener
  42451. {
  42452. public:
  42453. TextHolderComponent (TextEditor& owner_)
  42454. : owner (owner_)
  42455. {
  42456. setWantsKeyboardFocus (false);
  42457. setInterceptsMouseClicks (false, true);
  42458. owner.getTextValue().addListener (this);
  42459. }
  42460. ~TextHolderComponent()
  42461. {
  42462. owner.getTextValue().removeListener (this);
  42463. }
  42464. void paint (Graphics& g)
  42465. {
  42466. owner.drawContent (g);
  42467. }
  42468. void timerCallback()
  42469. {
  42470. owner.timerCallbackInt();
  42471. }
  42472. const MouseCursor getMouseCursor()
  42473. {
  42474. return owner.getMouseCursor();
  42475. }
  42476. void valueChanged (Value&)
  42477. {
  42478. owner.textWasChangedByValue();
  42479. }
  42480. private:
  42481. TextEditor& owner;
  42482. JUCE_DECLARE_NON_COPYABLE (TextHolderComponent);
  42483. };
  42484. class TextEditorViewport : public Viewport
  42485. {
  42486. public:
  42487. TextEditorViewport (TextEditor& owner_)
  42488. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42489. {
  42490. }
  42491. void visibleAreaChanged (const Rectangle<int>&)
  42492. {
  42493. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42494. // appear and disappear, causing the wrap width to change.
  42495. {
  42496. const float wordWrapWidth = owner.getWordWrapWidth();
  42497. if (wordWrapWidth != lastWordWrapWidth)
  42498. {
  42499. lastWordWrapWidth = wordWrapWidth;
  42500. rentrant = true;
  42501. owner.updateTextHolderSize();
  42502. rentrant = false;
  42503. }
  42504. }
  42505. }
  42506. private:
  42507. TextEditor& owner;
  42508. float lastWordWrapWidth;
  42509. bool rentrant;
  42510. JUCE_DECLARE_NON_COPYABLE (TextEditorViewport);
  42511. };
  42512. namespace TextEditorDefs
  42513. {
  42514. const int flashSpeedIntervalMs = 380;
  42515. const int textChangeMessageId = 0x10003001;
  42516. const int returnKeyMessageId = 0x10003002;
  42517. const int escapeKeyMessageId = 0x10003003;
  42518. const int focusLossMessageId = 0x10003004;
  42519. const int maxActionsPerTransaction = 100;
  42520. int getCharacterCategory (const juce_wchar character)
  42521. {
  42522. return CharacterFunctions::isLetterOrDigit (character)
  42523. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  42524. }
  42525. }
  42526. TextEditor::TextEditor (const String& name,
  42527. const juce_wchar passwordCharacter_)
  42528. : Component (name),
  42529. borderSize (1, 1, 1, 3),
  42530. readOnly (false),
  42531. multiline (false),
  42532. wordWrap (false),
  42533. returnKeyStartsNewLine (false),
  42534. caretVisible (true),
  42535. popupMenuEnabled (true),
  42536. selectAllTextWhenFocused (false),
  42537. scrollbarVisible (true),
  42538. wasFocused (false),
  42539. caretFlashState (true),
  42540. keepCursorOnScreen (true),
  42541. tabKeyUsed (false),
  42542. menuActive (false),
  42543. valueTextNeedsUpdating (false),
  42544. cursorX (0),
  42545. cursorY (0),
  42546. cursorHeight (0),
  42547. maxTextLength (0),
  42548. leftIndent (4),
  42549. topIndent (4),
  42550. lastTransactionTime (0),
  42551. currentFont (14.0f),
  42552. totalNumChars (0),
  42553. caretPosition (0),
  42554. passwordCharacter (passwordCharacter_),
  42555. dragType (notDragging)
  42556. {
  42557. setOpaque (true);
  42558. addAndMakeVisible (viewport = new TextEditorViewport (*this));
  42559. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42560. viewport->setWantsKeyboardFocus (false);
  42561. viewport->setScrollBarsShown (false, false);
  42562. setMouseCursor (MouseCursor::IBeamCursor);
  42563. setWantsKeyboardFocus (true);
  42564. }
  42565. TextEditor::~TextEditor()
  42566. {
  42567. textValue.referTo (Value());
  42568. clearInternal (0);
  42569. viewport = 0;
  42570. textHolder = 0;
  42571. }
  42572. void TextEditor::newTransaction()
  42573. {
  42574. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42575. undoManager.beginNewTransaction();
  42576. }
  42577. void TextEditor::doUndoRedo (const bool isRedo)
  42578. {
  42579. if (! isReadOnly())
  42580. {
  42581. if (isRedo ? undoManager.redo()
  42582. : undoManager.undo())
  42583. {
  42584. scrollToMakeSureCursorIsVisible();
  42585. repaint();
  42586. textChanged();
  42587. }
  42588. }
  42589. }
  42590. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42591. const bool shouldWordWrap)
  42592. {
  42593. if (multiline != shouldBeMultiLine
  42594. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42595. {
  42596. multiline = shouldBeMultiLine;
  42597. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42598. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42599. scrollbarVisible && multiline);
  42600. viewport->setViewPosition (0, 0);
  42601. resized();
  42602. scrollToMakeSureCursorIsVisible();
  42603. }
  42604. }
  42605. bool TextEditor::isMultiLine() const
  42606. {
  42607. return multiline;
  42608. }
  42609. void TextEditor::setScrollbarsShown (bool shown)
  42610. {
  42611. if (scrollbarVisible != shown)
  42612. {
  42613. scrollbarVisible = shown;
  42614. shown = shown && isMultiLine();
  42615. viewport->setScrollBarsShown (shown, shown);
  42616. }
  42617. }
  42618. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42619. {
  42620. if (readOnly != shouldBeReadOnly)
  42621. {
  42622. readOnly = shouldBeReadOnly;
  42623. enablementChanged();
  42624. }
  42625. }
  42626. bool TextEditor::isReadOnly() const
  42627. {
  42628. return readOnly || ! isEnabled();
  42629. }
  42630. bool TextEditor::isTextInputActive() const
  42631. {
  42632. return ! isReadOnly();
  42633. }
  42634. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42635. {
  42636. returnKeyStartsNewLine = shouldStartNewLine;
  42637. }
  42638. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42639. {
  42640. tabKeyUsed = shouldTabKeyBeUsed;
  42641. }
  42642. void TextEditor::setPopupMenuEnabled (const bool b)
  42643. {
  42644. popupMenuEnabled = b;
  42645. }
  42646. void TextEditor::setSelectAllWhenFocused (const bool b)
  42647. {
  42648. selectAllTextWhenFocused = b;
  42649. }
  42650. const Font TextEditor::getFont() const
  42651. {
  42652. return currentFont;
  42653. }
  42654. void TextEditor::setFont (const Font& newFont)
  42655. {
  42656. currentFont = newFont;
  42657. scrollToMakeSureCursorIsVisible();
  42658. }
  42659. void TextEditor::applyFontToAllText (const Font& newFont)
  42660. {
  42661. currentFont = newFont;
  42662. const Colour overallColour (findColour (textColourId));
  42663. for (int i = sections.size(); --i >= 0;)
  42664. {
  42665. UniformTextSection* const uts = sections.getUnchecked (i);
  42666. uts->setFont (newFont, passwordCharacter);
  42667. uts->colour = overallColour;
  42668. }
  42669. coalesceSimilarSections();
  42670. updateTextHolderSize();
  42671. scrollToMakeSureCursorIsVisible();
  42672. repaint();
  42673. }
  42674. void TextEditor::colourChanged()
  42675. {
  42676. setOpaque (findColour (backgroundColourId).isOpaque());
  42677. repaint();
  42678. }
  42679. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42680. {
  42681. caretVisible = shouldCaretBeVisible;
  42682. if (shouldCaretBeVisible)
  42683. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42684. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42685. : MouseCursor::NormalCursor);
  42686. }
  42687. void TextEditor::setInputRestrictions (const int maxLen,
  42688. const String& chars)
  42689. {
  42690. maxTextLength = jmax (0, maxLen);
  42691. allowedCharacters = chars;
  42692. }
  42693. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42694. {
  42695. textToShowWhenEmpty = text;
  42696. colourForTextWhenEmpty = colourToUse;
  42697. }
  42698. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42699. {
  42700. if (passwordCharacter != newPasswordCharacter)
  42701. {
  42702. passwordCharacter = newPasswordCharacter;
  42703. resized();
  42704. repaint();
  42705. }
  42706. }
  42707. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42708. {
  42709. viewport->setScrollBarThickness (newThicknessPixels);
  42710. }
  42711. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42712. {
  42713. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42714. }
  42715. void TextEditor::clear()
  42716. {
  42717. clearInternal (0);
  42718. updateTextHolderSize();
  42719. undoManager.clearUndoHistory();
  42720. }
  42721. void TextEditor::setText (const String& newText,
  42722. const bool sendTextChangeMessage)
  42723. {
  42724. const int newLength = newText.length();
  42725. if (newLength != getTotalNumChars() || getText() != newText)
  42726. {
  42727. const int oldCursorPos = caretPosition;
  42728. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  42729. clearInternal (0);
  42730. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  42731. // if you're adding text with line-feeds to a single-line text editor, it
  42732. // ain't gonna look right!
  42733. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  42734. if (cursorWasAtEnd && ! isMultiLine())
  42735. moveCursorTo (getTotalNumChars(), false);
  42736. else
  42737. moveCursorTo (oldCursorPos, false);
  42738. if (sendTextChangeMessage)
  42739. textChanged();
  42740. updateTextHolderSize();
  42741. scrollToMakeSureCursorIsVisible();
  42742. undoManager.clearUndoHistory();
  42743. repaint();
  42744. }
  42745. }
  42746. Value& TextEditor::getTextValue()
  42747. {
  42748. if (valueTextNeedsUpdating)
  42749. {
  42750. valueTextNeedsUpdating = false;
  42751. textValue = getText();
  42752. }
  42753. return textValue;
  42754. }
  42755. void TextEditor::textWasChangedByValue()
  42756. {
  42757. if (textValue.getValueSource().getReferenceCount() > 1)
  42758. setText (textValue.getValue());
  42759. }
  42760. void TextEditor::textChanged()
  42761. {
  42762. updateTextHolderSize();
  42763. postCommandMessage (TextEditorDefs::textChangeMessageId);
  42764. if (textValue.getValueSource().getReferenceCount() > 1)
  42765. {
  42766. valueTextNeedsUpdating = false;
  42767. textValue = getText();
  42768. }
  42769. }
  42770. void TextEditor::returnPressed()
  42771. {
  42772. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  42773. }
  42774. void TextEditor::escapePressed()
  42775. {
  42776. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  42777. }
  42778. void TextEditor::addListener (TextEditorListener* const newListener)
  42779. {
  42780. listeners.add (newListener);
  42781. }
  42782. void TextEditor::removeListener (TextEditorListener* const listenerToRemove)
  42783. {
  42784. listeners.remove (listenerToRemove);
  42785. }
  42786. void TextEditor::timerCallbackInt()
  42787. {
  42788. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  42789. if (caretFlashState != newState)
  42790. {
  42791. caretFlashState = newState;
  42792. if (caretFlashState)
  42793. wasFocused = true;
  42794. if (caretVisible
  42795. && hasKeyboardFocus (false)
  42796. && ! isReadOnly())
  42797. {
  42798. repaintCaret();
  42799. }
  42800. }
  42801. const unsigned int now = Time::getApproximateMillisecondCounter();
  42802. if (now > lastTransactionTime + 200)
  42803. newTransaction();
  42804. }
  42805. void TextEditor::repaintCaret()
  42806. {
  42807. if (! findColour (caretColourId).isTransparent())
  42808. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  42809. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  42810. 4,
  42811. roundToInt (cursorHeight) + 2);
  42812. }
  42813. void TextEditor::repaintText (const Range<int>& range)
  42814. {
  42815. if (! range.isEmpty())
  42816. {
  42817. float x = 0, y = 0, lh = currentFont.getHeight();
  42818. const float wordWrapWidth = getWordWrapWidth();
  42819. if (wordWrapWidth > 0)
  42820. {
  42821. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42822. i.getCharPosition (range.getStart(), x, y, lh);
  42823. const int y1 = (int) y;
  42824. int y2;
  42825. if (range.getEnd() >= getTotalNumChars())
  42826. {
  42827. y2 = textHolder->getHeight();
  42828. }
  42829. else
  42830. {
  42831. i.getCharPosition (range.getEnd(), x, y, lh);
  42832. y2 = (int) (y + lh * 2.0f);
  42833. }
  42834. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  42835. }
  42836. }
  42837. }
  42838. void TextEditor::moveCaret (int newCaretPos)
  42839. {
  42840. if (newCaretPos < 0)
  42841. newCaretPos = 0;
  42842. else if (newCaretPos > getTotalNumChars())
  42843. newCaretPos = getTotalNumChars();
  42844. if (newCaretPos != getCaretPosition())
  42845. {
  42846. repaintCaret();
  42847. caretFlashState = true;
  42848. caretPosition = newCaretPos;
  42849. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42850. scrollToMakeSureCursorIsVisible();
  42851. repaintCaret();
  42852. }
  42853. }
  42854. void TextEditor::setCaretPosition (const int newIndex)
  42855. {
  42856. moveCursorTo (newIndex, false);
  42857. }
  42858. int TextEditor::getCaretPosition() const
  42859. {
  42860. return caretPosition;
  42861. }
  42862. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  42863. const int desiredCaretY)
  42864. {
  42865. updateCaretPosition();
  42866. int vx = roundToInt (cursorX) - desiredCaretX;
  42867. int vy = roundToInt (cursorY) - desiredCaretY;
  42868. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  42869. {
  42870. vx += desiredCaretX - proportionOfWidth (0.2f);
  42871. }
  42872. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42873. {
  42874. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42875. }
  42876. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  42877. if (! isMultiLine())
  42878. {
  42879. vy = viewport->getViewPositionY();
  42880. }
  42881. else
  42882. {
  42883. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  42884. const int curH = roundToInt (cursorHeight);
  42885. if (desiredCaretY < 0)
  42886. {
  42887. vy = jmax (0, desiredCaretY + vy);
  42888. }
  42889. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42890. {
  42891. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42892. }
  42893. }
  42894. viewport->setViewPosition (vx, vy);
  42895. }
  42896. const Rectangle<int> TextEditor::getCaretRectangle()
  42897. {
  42898. updateCaretPosition();
  42899. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  42900. roundToInt (cursorY) - viewport->getY(),
  42901. 1, roundToInt (cursorHeight));
  42902. }
  42903. float TextEditor::getWordWrapWidth() const
  42904. {
  42905. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  42906. : 1.0e10f;
  42907. }
  42908. void TextEditor::updateTextHolderSize()
  42909. {
  42910. const float wordWrapWidth = getWordWrapWidth();
  42911. if (wordWrapWidth > 0)
  42912. {
  42913. float maxWidth = 0.0f;
  42914. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42915. while (i.next())
  42916. maxWidth = jmax (maxWidth, i.atomRight);
  42917. const int w = leftIndent + roundToInt (maxWidth);
  42918. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  42919. currentFont.getHeight()));
  42920. textHolder->setSize (w + 1, h + 1);
  42921. }
  42922. }
  42923. int TextEditor::getTextWidth() const
  42924. {
  42925. return textHolder->getWidth();
  42926. }
  42927. int TextEditor::getTextHeight() const
  42928. {
  42929. return textHolder->getHeight();
  42930. }
  42931. void TextEditor::setIndents (const int newLeftIndent,
  42932. const int newTopIndent)
  42933. {
  42934. leftIndent = newLeftIndent;
  42935. topIndent = newTopIndent;
  42936. }
  42937. void TextEditor::setBorder (const BorderSize<int>& border)
  42938. {
  42939. borderSize = border;
  42940. resized();
  42941. }
  42942. const BorderSize<int> TextEditor::getBorder() const
  42943. {
  42944. return borderSize;
  42945. }
  42946. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  42947. {
  42948. keepCursorOnScreen = shouldScrollToShowCursor;
  42949. }
  42950. void TextEditor::updateCaretPosition()
  42951. {
  42952. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  42953. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  42954. }
  42955. void TextEditor::scrollToMakeSureCursorIsVisible()
  42956. {
  42957. updateCaretPosition();
  42958. if (keepCursorOnScreen)
  42959. {
  42960. int x = viewport->getViewPositionX();
  42961. int y = viewport->getViewPositionY();
  42962. const int relativeCursorX = roundToInt (cursorX) - x;
  42963. const int relativeCursorY = roundToInt (cursorY) - y;
  42964. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  42965. {
  42966. x += relativeCursorX - proportionOfWidth (0.2f);
  42967. }
  42968. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42969. {
  42970. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42971. }
  42972. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  42973. if (! isMultiLine())
  42974. {
  42975. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  42976. }
  42977. else
  42978. {
  42979. const int curH = roundToInt (cursorHeight);
  42980. if (relativeCursorY < 0)
  42981. {
  42982. y = jmax (0, relativeCursorY + y);
  42983. }
  42984. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42985. {
  42986. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42987. }
  42988. }
  42989. viewport->setViewPosition (x, y);
  42990. }
  42991. }
  42992. void TextEditor::moveCursorTo (const int newPosition,
  42993. const bool isSelecting)
  42994. {
  42995. if (isSelecting)
  42996. {
  42997. moveCaret (newPosition);
  42998. const Range<int> oldSelection (selection);
  42999. if (dragType == notDragging)
  43000. {
  43001. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  43002. dragType = draggingSelectionStart;
  43003. else
  43004. dragType = draggingSelectionEnd;
  43005. }
  43006. if (dragType == draggingSelectionStart)
  43007. {
  43008. if (getCaretPosition() >= selection.getEnd())
  43009. dragType = draggingSelectionEnd;
  43010. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  43011. }
  43012. else
  43013. {
  43014. if (getCaretPosition() < selection.getStart())
  43015. dragType = draggingSelectionStart;
  43016. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  43017. }
  43018. repaintText (selection.getUnionWith (oldSelection));
  43019. }
  43020. else
  43021. {
  43022. dragType = notDragging;
  43023. repaintText (selection);
  43024. moveCaret (newPosition);
  43025. selection = Range<int>::emptyRange (getCaretPosition());
  43026. }
  43027. }
  43028. int TextEditor::getTextIndexAt (const int x,
  43029. const int y)
  43030. {
  43031. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43032. (float) (y + viewport->getViewPositionY() - topIndent));
  43033. }
  43034. void TextEditor::insertTextAtCaret (const String& newText_)
  43035. {
  43036. String newText (newText_);
  43037. if (allowedCharacters.isNotEmpty())
  43038. newText = newText.retainCharacters (allowedCharacters);
  43039. if (! isMultiLine())
  43040. newText = newText.replaceCharacters ("\r\n", " ");
  43041. else
  43042. newText = newText.replace ("\r\n", "\n");
  43043. const int newCaretPos = selection.getStart() + newText.length();
  43044. const int insertIndex = selection.getStart();
  43045. remove (selection, getUndoManager(),
  43046. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43047. if (maxTextLength > 0)
  43048. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43049. if (newText.isNotEmpty())
  43050. insert (newText,
  43051. insertIndex,
  43052. currentFont,
  43053. findColour (textColourId),
  43054. getUndoManager(),
  43055. newCaretPos);
  43056. textChanged();
  43057. }
  43058. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43059. {
  43060. moveCursorTo (newSelection.getStart(), false);
  43061. moveCursorTo (newSelection.getEnd(), true);
  43062. }
  43063. void TextEditor::copy()
  43064. {
  43065. if (passwordCharacter == 0)
  43066. {
  43067. const String selectedText (getHighlightedText());
  43068. if (selectedText.isNotEmpty())
  43069. SystemClipboard::copyTextToClipboard (selectedText);
  43070. }
  43071. }
  43072. void TextEditor::paste()
  43073. {
  43074. if (! isReadOnly())
  43075. {
  43076. const String clip (SystemClipboard::getTextFromClipboard());
  43077. if (clip.isNotEmpty())
  43078. insertTextAtCaret (clip);
  43079. }
  43080. }
  43081. void TextEditor::cut()
  43082. {
  43083. if (! isReadOnly())
  43084. {
  43085. moveCaret (selection.getEnd());
  43086. insertTextAtCaret (String::empty);
  43087. }
  43088. }
  43089. void TextEditor::drawContent (Graphics& g)
  43090. {
  43091. const float wordWrapWidth = getWordWrapWidth();
  43092. if (wordWrapWidth > 0)
  43093. {
  43094. g.setOrigin (leftIndent, topIndent);
  43095. const Rectangle<int> clip (g.getClipBounds());
  43096. Colour selectedTextColour;
  43097. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43098. while (i.lineY + 200.0 < clip.getY() && i.next())
  43099. {}
  43100. if (! selection.isEmpty())
  43101. {
  43102. g.setColour (findColour (highlightColourId)
  43103. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43104. selectedTextColour = findColour (highlightedTextColourId);
  43105. Iterator i2 (i);
  43106. while (i2.next() && i2.lineY < clip.getBottom())
  43107. {
  43108. if (i2.lineY + i2.lineHeight >= clip.getY()
  43109. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43110. {
  43111. i2.drawSelection (g, selection);
  43112. }
  43113. }
  43114. }
  43115. const UniformTextSection* lastSection = 0;
  43116. while (i.next() && i.lineY < clip.getBottom())
  43117. {
  43118. if (i.lineY + i.lineHeight >= clip.getY())
  43119. {
  43120. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43121. {
  43122. i.drawSelectedText (g, selection, selectedTextColour);
  43123. lastSection = 0;
  43124. }
  43125. else
  43126. {
  43127. i.draw (g, lastSection);
  43128. }
  43129. }
  43130. }
  43131. }
  43132. }
  43133. void TextEditor::paint (Graphics& g)
  43134. {
  43135. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43136. }
  43137. void TextEditor::paintOverChildren (Graphics& g)
  43138. {
  43139. if (caretFlashState
  43140. && hasKeyboardFocus (false)
  43141. && caretVisible
  43142. && ! isReadOnly())
  43143. {
  43144. g.setColour (findColour (caretColourId));
  43145. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43146. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43147. 2.0f, cursorHeight);
  43148. }
  43149. if (textToShowWhenEmpty.isNotEmpty()
  43150. && (! hasKeyboardFocus (false))
  43151. && getTotalNumChars() == 0)
  43152. {
  43153. g.setColour (colourForTextWhenEmpty);
  43154. g.setFont (getFont());
  43155. if (isMultiLine())
  43156. {
  43157. g.drawText (textToShowWhenEmpty,
  43158. 0, 0, getWidth(), getHeight(),
  43159. Justification::centred, true);
  43160. }
  43161. else
  43162. {
  43163. g.drawText (textToShowWhenEmpty,
  43164. leftIndent, topIndent,
  43165. viewport->getWidth() - leftIndent,
  43166. viewport->getHeight() - topIndent,
  43167. Justification::centredLeft, true);
  43168. }
  43169. }
  43170. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43171. }
  43172. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  43173. {
  43174. public:
  43175. TextEditorMenuPerformer (TextEditor* const editor_)
  43176. : editor (editor_)
  43177. {
  43178. }
  43179. void modalStateFinished (int returnValue)
  43180. {
  43181. if (editor != 0 && returnValue != 0)
  43182. editor->performPopupMenuAction (returnValue);
  43183. }
  43184. private:
  43185. Component::SafePointer<TextEditor> editor;
  43186. JUCE_DECLARE_NON_COPYABLE (TextEditorMenuPerformer);
  43187. };
  43188. void TextEditor::mouseDown (const MouseEvent& e)
  43189. {
  43190. beginDragAutoRepeat (100);
  43191. newTransaction();
  43192. if (wasFocused || ! selectAllTextWhenFocused)
  43193. {
  43194. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43195. {
  43196. moveCursorTo (getTextIndexAt (e.x, e.y),
  43197. e.mods.isShiftDown());
  43198. }
  43199. else
  43200. {
  43201. PopupMenu m;
  43202. m.setLookAndFeel (&getLookAndFeel());
  43203. addPopupMenuItems (m, &e);
  43204. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  43205. }
  43206. }
  43207. }
  43208. void TextEditor::mouseDrag (const MouseEvent& e)
  43209. {
  43210. if (wasFocused || ! selectAllTextWhenFocused)
  43211. {
  43212. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43213. {
  43214. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43215. }
  43216. }
  43217. }
  43218. void TextEditor::mouseUp (const MouseEvent& e)
  43219. {
  43220. newTransaction();
  43221. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43222. if (wasFocused || ! selectAllTextWhenFocused)
  43223. {
  43224. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43225. {
  43226. moveCaret (getTextIndexAt (e.x, e.y));
  43227. }
  43228. }
  43229. wasFocused = true;
  43230. }
  43231. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43232. {
  43233. int tokenEnd = getTextIndexAt (e.x, e.y);
  43234. int tokenStart = tokenEnd;
  43235. if (e.getNumberOfClicks() > 3)
  43236. {
  43237. tokenStart = 0;
  43238. tokenEnd = getTotalNumChars();
  43239. }
  43240. else
  43241. {
  43242. const String t (getText());
  43243. const int totalLength = getTotalNumChars();
  43244. while (tokenEnd < totalLength)
  43245. {
  43246. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43247. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43248. ++tokenEnd;
  43249. else
  43250. break;
  43251. }
  43252. tokenStart = tokenEnd;
  43253. while (tokenStart > 0)
  43254. {
  43255. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43256. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43257. --tokenStart;
  43258. else
  43259. break;
  43260. }
  43261. if (e.getNumberOfClicks() > 2)
  43262. {
  43263. while (tokenEnd < totalLength)
  43264. {
  43265. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43266. ++tokenEnd;
  43267. else
  43268. break;
  43269. }
  43270. while (tokenStart > 0)
  43271. {
  43272. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43273. --tokenStart;
  43274. else
  43275. break;
  43276. }
  43277. }
  43278. }
  43279. moveCursorTo (tokenEnd, false);
  43280. moveCursorTo (tokenStart, true);
  43281. }
  43282. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43283. {
  43284. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43285. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43286. }
  43287. bool TextEditor::keyPressed (const KeyPress& key)
  43288. {
  43289. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43290. return false;
  43291. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43292. if (key.isKeyCode (KeyPress::leftKey)
  43293. || key.isKeyCode (KeyPress::upKey))
  43294. {
  43295. newTransaction();
  43296. int newPos;
  43297. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43298. newPos = indexAtPosition (cursorX, cursorY - 1);
  43299. else if (moveInWholeWordSteps)
  43300. newPos = findWordBreakBefore (getCaretPosition());
  43301. else
  43302. newPos = getCaretPosition() - 1;
  43303. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43304. }
  43305. else if (key.isKeyCode (KeyPress::rightKey)
  43306. || key.isKeyCode (KeyPress::downKey))
  43307. {
  43308. newTransaction();
  43309. int newPos;
  43310. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43311. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43312. else if (moveInWholeWordSteps)
  43313. newPos = findWordBreakAfter (getCaretPosition());
  43314. else
  43315. newPos = getCaretPosition() + 1;
  43316. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43317. }
  43318. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43319. {
  43320. newTransaction();
  43321. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43322. key.getModifiers().isShiftDown());
  43323. }
  43324. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43325. {
  43326. newTransaction();
  43327. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43328. key.getModifiers().isShiftDown());
  43329. }
  43330. else if (key.isKeyCode (KeyPress::homeKey))
  43331. {
  43332. newTransaction();
  43333. if (isMultiLine() && ! moveInWholeWordSteps)
  43334. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43335. key.getModifiers().isShiftDown());
  43336. else
  43337. moveCursorTo (0, key.getModifiers().isShiftDown());
  43338. }
  43339. else if (key.isKeyCode (KeyPress::endKey))
  43340. {
  43341. newTransaction();
  43342. if (isMultiLine() && ! moveInWholeWordSteps)
  43343. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43344. key.getModifiers().isShiftDown());
  43345. else
  43346. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43347. }
  43348. else if (key.isKeyCode (KeyPress::backspaceKey))
  43349. {
  43350. if (moveInWholeWordSteps)
  43351. {
  43352. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43353. }
  43354. else
  43355. {
  43356. if (selection.isEmpty() && selection.getStart() > 0)
  43357. selection.setStart (selection.getEnd() - 1);
  43358. }
  43359. cut();
  43360. }
  43361. else if (key.isKeyCode (KeyPress::deleteKey))
  43362. {
  43363. if (key.getModifiers().isShiftDown())
  43364. copy();
  43365. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43366. selection.setEnd (selection.getStart() + 1);
  43367. cut();
  43368. }
  43369. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43370. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43371. {
  43372. newTransaction();
  43373. copy();
  43374. }
  43375. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43376. {
  43377. newTransaction();
  43378. copy();
  43379. cut();
  43380. }
  43381. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43382. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43383. {
  43384. newTransaction();
  43385. paste();
  43386. }
  43387. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43388. {
  43389. newTransaction();
  43390. doUndoRedo (false);
  43391. }
  43392. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43393. {
  43394. newTransaction();
  43395. doUndoRedo (true);
  43396. }
  43397. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43398. {
  43399. newTransaction();
  43400. moveCursorTo (getTotalNumChars(), false);
  43401. moveCursorTo (0, true);
  43402. }
  43403. else if (key == KeyPress::returnKey)
  43404. {
  43405. newTransaction();
  43406. if (returnKeyStartsNewLine)
  43407. insertTextAtCaret ("\n");
  43408. else
  43409. returnPressed();
  43410. }
  43411. else if (key.isKeyCode (KeyPress::escapeKey))
  43412. {
  43413. newTransaction();
  43414. moveCursorTo (getCaretPosition(), false);
  43415. escapePressed();
  43416. }
  43417. else if (key.getTextCharacter() >= ' '
  43418. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43419. {
  43420. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43421. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43422. }
  43423. else
  43424. {
  43425. return false;
  43426. }
  43427. return true;
  43428. }
  43429. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43430. {
  43431. if (! isKeyDown)
  43432. return false;
  43433. #if JUCE_WINDOWS
  43434. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43435. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43436. #endif
  43437. // (overridden to avoid forwarding key events to the parent)
  43438. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43439. }
  43440. const int baseMenuItemID = 0x7fff0000;
  43441. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43442. {
  43443. const bool writable = ! isReadOnly();
  43444. if (passwordCharacter == 0)
  43445. {
  43446. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43447. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43448. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43449. }
  43450. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43451. m.addSeparator();
  43452. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43453. m.addSeparator();
  43454. if (getUndoManager() != 0)
  43455. {
  43456. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43457. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43458. }
  43459. }
  43460. void TextEditor::performPopupMenuAction (const int menuItemID)
  43461. {
  43462. switch (menuItemID)
  43463. {
  43464. case baseMenuItemID + 1:
  43465. copy();
  43466. cut();
  43467. break;
  43468. case baseMenuItemID + 2:
  43469. copy();
  43470. break;
  43471. case baseMenuItemID + 3:
  43472. paste();
  43473. break;
  43474. case baseMenuItemID + 4:
  43475. cut();
  43476. break;
  43477. case baseMenuItemID + 5:
  43478. moveCursorTo (getTotalNumChars(), false);
  43479. moveCursorTo (0, true);
  43480. break;
  43481. case baseMenuItemID + 6:
  43482. doUndoRedo (false);
  43483. break;
  43484. case baseMenuItemID + 7:
  43485. doUndoRedo (true);
  43486. break;
  43487. default:
  43488. break;
  43489. }
  43490. }
  43491. void TextEditor::focusGained (FocusChangeType)
  43492. {
  43493. newTransaction();
  43494. caretFlashState = true;
  43495. if (selectAllTextWhenFocused)
  43496. {
  43497. moveCursorTo (0, false);
  43498. moveCursorTo (getTotalNumChars(), true);
  43499. }
  43500. repaint();
  43501. if (caretVisible)
  43502. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43503. ComponentPeer* const peer = getPeer();
  43504. if (peer != 0 && ! isReadOnly())
  43505. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43506. }
  43507. void TextEditor::focusLost (FocusChangeType)
  43508. {
  43509. newTransaction();
  43510. wasFocused = false;
  43511. textHolder->stopTimer();
  43512. caretFlashState = false;
  43513. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43514. repaint();
  43515. }
  43516. void TextEditor::resized()
  43517. {
  43518. viewport->setBoundsInset (borderSize);
  43519. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43520. updateTextHolderSize();
  43521. if (! isMultiLine())
  43522. {
  43523. scrollToMakeSureCursorIsVisible();
  43524. }
  43525. else
  43526. {
  43527. updateCaretPosition();
  43528. }
  43529. }
  43530. void TextEditor::handleCommandMessage (const int commandId)
  43531. {
  43532. Component::BailOutChecker checker (this);
  43533. switch (commandId)
  43534. {
  43535. case TextEditorDefs::textChangeMessageId:
  43536. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  43537. break;
  43538. case TextEditorDefs::returnKeyMessageId:
  43539. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43540. break;
  43541. case TextEditorDefs::escapeKeyMessageId:
  43542. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43543. break;
  43544. case TextEditorDefs::focusLossMessageId:
  43545. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  43546. break;
  43547. default:
  43548. jassertfalse;
  43549. break;
  43550. }
  43551. }
  43552. void TextEditor::enablementChanged()
  43553. {
  43554. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43555. : MouseCursor::IBeamCursor);
  43556. repaint();
  43557. }
  43558. UndoManager* TextEditor::getUndoManager() throw()
  43559. {
  43560. return isReadOnly() ? 0 : &undoManager;
  43561. }
  43562. void TextEditor::clearInternal (UndoManager* const um)
  43563. {
  43564. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43565. }
  43566. void TextEditor::insert (const String& text,
  43567. const int insertIndex,
  43568. const Font& font,
  43569. const Colour& colour,
  43570. UndoManager* const um,
  43571. const int caretPositionToMoveTo)
  43572. {
  43573. if (text.isNotEmpty())
  43574. {
  43575. if (um != 0)
  43576. {
  43577. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43578. newTransaction();
  43579. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43580. caretPosition, caretPositionToMoveTo));
  43581. }
  43582. else
  43583. {
  43584. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43585. // a line gets moved due to word wrap
  43586. int index = 0;
  43587. int nextIndex = 0;
  43588. for (int i = 0; i < sections.size(); ++i)
  43589. {
  43590. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43591. if (insertIndex == index)
  43592. {
  43593. sections.insert (i, new UniformTextSection (text,
  43594. font, colour,
  43595. passwordCharacter));
  43596. break;
  43597. }
  43598. else if (insertIndex > index && insertIndex < nextIndex)
  43599. {
  43600. splitSection (i, insertIndex - index);
  43601. sections.insert (i + 1, new UniformTextSection (text,
  43602. font, colour,
  43603. passwordCharacter));
  43604. break;
  43605. }
  43606. index = nextIndex;
  43607. }
  43608. if (nextIndex == insertIndex)
  43609. sections.add (new UniformTextSection (text,
  43610. font, colour,
  43611. passwordCharacter));
  43612. coalesceSimilarSections();
  43613. totalNumChars = -1;
  43614. valueTextNeedsUpdating = true;
  43615. moveCursorTo (caretPositionToMoveTo, false);
  43616. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  43617. }
  43618. }
  43619. }
  43620. void TextEditor::reinsert (const int insertIndex,
  43621. const Array <UniformTextSection*>& sectionsToInsert)
  43622. {
  43623. int index = 0;
  43624. int nextIndex = 0;
  43625. for (int i = 0; i < sections.size(); ++i)
  43626. {
  43627. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43628. if (insertIndex == index)
  43629. {
  43630. for (int j = sectionsToInsert.size(); --j >= 0;)
  43631. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43632. break;
  43633. }
  43634. else if (insertIndex > index && insertIndex < nextIndex)
  43635. {
  43636. splitSection (i, insertIndex - index);
  43637. for (int j = sectionsToInsert.size(); --j >= 0;)
  43638. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43639. break;
  43640. }
  43641. index = nextIndex;
  43642. }
  43643. if (nextIndex == insertIndex)
  43644. {
  43645. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43646. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43647. }
  43648. coalesceSimilarSections();
  43649. totalNumChars = -1;
  43650. valueTextNeedsUpdating = true;
  43651. }
  43652. void TextEditor::remove (const Range<int>& range,
  43653. UndoManager* const um,
  43654. const int caretPositionToMoveTo)
  43655. {
  43656. if (! range.isEmpty())
  43657. {
  43658. int index = 0;
  43659. for (int i = 0; i < sections.size(); ++i)
  43660. {
  43661. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43662. if (range.getStart() > index && range.getStart() < nextIndex)
  43663. {
  43664. splitSection (i, range.getStart() - index);
  43665. --i;
  43666. }
  43667. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43668. {
  43669. splitSection (i, range.getEnd() - index);
  43670. --i;
  43671. }
  43672. else
  43673. {
  43674. index = nextIndex;
  43675. if (index > range.getEnd())
  43676. break;
  43677. }
  43678. }
  43679. index = 0;
  43680. if (um != 0)
  43681. {
  43682. Array <UniformTextSection*> removedSections;
  43683. for (int i = 0; i < sections.size(); ++i)
  43684. {
  43685. if (range.getEnd() <= range.getStart())
  43686. break;
  43687. UniformTextSection* const section = sections.getUnchecked (i);
  43688. const int nextIndex = index + section->getTotalLength();
  43689. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43690. removedSections.add (new UniformTextSection (*section));
  43691. index = nextIndex;
  43692. }
  43693. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43694. newTransaction();
  43695. um->perform (new RemoveAction (*this, range, caretPosition,
  43696. caretPositionToMoveTo, removedSections));
  43697. }
  43698. else
  43699. {
  43700. Range<int> remainingRange (range);
  43701. for (int i = 0; i < sections.size(); ++i)
  43702. {
  43703. UniformTextSection* const section = sections.getUnchecked (i);
  43704. const int nextIndex = index + section->getTotalLength();
  43705. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43706. {
  43707. sections.remove(i);
  43708. section->clear();
  43709. delete section;
  43710. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43711. if (remainingRange.isEmpty())
  43712. break;
  43713. --i;
  43714. }
  43715. else
  43716. {
  43717. index = nextIndex;
  43718. }
  43719. }
  43720. coalesceSimilarSections();
  43721. totalNumChars = -1;
  43722. valueTextNeedsUpdating = true;
  43723. moveCursorTo (caretPositionToMoveTo, false);
  43724. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  43725. }
  43726. }
  43727. }
  43728. const String TextEditor::getText() const
  43729. {
  43730. String t;
  43731. t.preallocateStorage (getTotalNumChars());
  43732. String::Concatenator concatenator (t);
  43733. for (int i = 0; i < sections.size(); ++i)
  43734. sections.getUnchecked (i)->appendAllText (concatenator);
  43735. return t;
  43736. }
  43737. const String TextEditor::getTextInRange (const Range<int>& range) const
  43738. {
  43739. String t;
  43740. if (! range.isEmpty())
  43741. {
  43742. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  43743. String::Concatenator concatenator (t);
  43744. int index = 0;
  43745. for (int i = 0; i < sections.size(); ++i)
  43746. {
  43747. const UniformTextSection* const s = sections.getUnchecked (i);
  43748. const int nextIndex = index + s->getTotalLength();
  43749. if (range.getStart() < nextIndex)
  43750. {
  43751. if (range.getEnd() <= index)
  43752. break;
  43753. s->appendSubstring (concatenator, range - index);
  43754. }
  43755. index = nextIndex;
  43756. }
  43757. }
  43758. return t;
  43759. }
  43760. const String TextEditor::getHighlightedText() const
  43761. {
  43762. return getTextInRange (selection);
  43763. }
  43764. int TextEditor::getTotalNumChars() const
  43765. {
  43766. if (totalNumChars < 0)
  43767. {
  43768. totalNumChars = 0;
  43769. for (int i = sections.size(); --i >= 0;)
  43770. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  43771. }
  43772. return totalNumChars;
  43773. }
  43774. bool TextEditor::isEmpty() const
  43775. {
  43776. return getTotalNumChars() == 0;
  43777. }
  43778. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  43779. {
  43780. const float wordWrapWidth = getWordWrapWidth();
  43781. if (wordWrapWidth > 0 && sections.size() > 0)
  43782. {
  43783. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43784. i.getCharPosition (index, cx, cy, lineHeight);
  43785. }
  43786. else
  43787. {
  43788. cx = cy = 0;
  43789. lineHeight = currentFont.getHeight();
  43790. }
  43791. }
  43792. int TextEditor::indexAtPosition (const float x, const float y)
  43793. {
  43794. const float wordWrapWidth = getWordWrapWidth();
  43795. if (wordWrapWidth > 0)
  43796. {
  43797. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43798. while (i.next())
  43799. {
  43800. if (i.lineY + i.lineHeight > y)
  43801. {
  43802. if (i.lineY > y)
  43803. return jmax (0, i.indexInText - 1);
  43804. if (i.atomX >= x)
  43805. return i.indexInText;
  43806. if (x < i.atomRight)
  43807. return i.xToIndex (x);
  43808. }
  43809. }
  43810. }
  43811. return getTotalNumChars();
  43812. }
  43813. int TextEditor::findWordBreakAfter (const int position) const
  43814. {
  43815. const String t (getTextInRange (Range<int> (position, position + 512)));
  43816. const int totalLength = t.length();
  43817. int i = 0;
  43818. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43819. ++i;
  43820. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  43821. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  43822. ++i;
  43823. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43824. ++i;
  43825. return position + i;
  43826. }
  43827. int TextEditor::findWordBreakBefore (const int position) const
  43828. {
  43829. if (position <= 0)
  43830. return 0;
  43831. const int startOfBuffer = jmax (0, position - 512);
  43832. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  43833. int i = position - startOfBuffer;
  43834. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  43835. --i;
  43836. if (i > 0)
  43837. {
  43838. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  43839. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  43840. --i;
  43841. }
  43842. jassert (startOfBuffer + i >= 0);
  43843. return startOfBuffer + i;
  43844. }
  43845. void TextEditor::splitSection (const int sectionIndex,
  43846. const int charToSplitAt)
  43847. {
  43848. jassert (sections[sectionIndex] != 0);
  43849. sections.insert (sectionIndex + 1,
  43850. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  43851. }
  43852. void TextEditor::coalesceSimilarSections()
  43853. {
  43854. for (int i = 0; i < sections.size() - 1; ++i)
  43855. {
  43856. UniformTextSection* const s1 = sections.getUnchecked (i);
  43857. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  43858. if (s1->font == s2->font
  43859. && s1->colour == s2->colour)
  43860. {
  43861. s1->append (*s2, passwordCharacter);
  43862. sections.remove (i + 1);
  43863. delete s2;
  43864. --i;
  43865. }
  43866. }
  43867. }
  43868. void TextEditor::Listener::textEditorTextChanged (TextEditor&) {}
  43869. void TextEditor::Listener::textEditorReturnKeyPressed (TextEditor&) {}
  43870. void TextEditor::Listener::textEditorEscapeKeyPressed (TextEditor&) {}
  43871. void TextEditor::Listener::textEditorFocusLost (TextEditor&) {}
  43872. END_JUCE_NAMESPACE
  43873. /*** End of inlined file: juce_TextEditor.cpp ***/
  43874. /*** Start of inlined file: juce_Toolbar.cpp ***/
  43875. BEGIN_JUCE_NAMESPACE
  43876. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  43877. class ToolbarSpacerComp : public ToolbarItemComponent
  43878. {
  43879. public:
  43880. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  43881. : ToolbarItemComponent (itemId_, String::empty, false),
  43882. fixedSize (fixedSize_),
  43883. drawBar (drawBar_)
  43884. {
  43885. }
  43886. ~ToolbarSpacerComp()
  43887. {
  43888. }
  43889. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  43890. int& preferredSize, int& minSize, int& maxSize)
  43891. {
  43892. if (fixedSize <= 0)
  43893. {
  43894. preferredSize = toolbarThickness * 2;
  43895. minSize = 4;
  43896. maxSize = 32768;
  43897. }
  43898. else
  43899. {
  43900. maxSize = roundToInt (toolbarThickness * fixedSize);
  43901. minSize = drawBar ? maxSize : jmin (4, maxSize);
  43902. preferredSize = maxSize;
  43903. if (getEditingMode() == editableOnPalette)
  43904. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  43905. }
  43906. return true;
  43907. }
  43908. void paintButtonArea (Graphics&, int, int, bool, bool)
  43909. {
  43910. }
  43911. void contentAreaChanged (const Rectangle<int>&)
  43912. {
  43913. }
  43914. int getResizeOrder() const throw()
  43915. {
  43916. return fixedSize <= 0 ? 0 : 1;
  43917. }
  43918. void paint (Graphics& g)
  43919. {
  43920. const int w = getWidth();
  43921. const int h = getHeight();
  43922. if (drawBar)
  43923. {
  43924. g.setColour (findColour (Toolbar::separatorColourId, true));
  43925. const float thickness = 0.2f;
  43926. if (isToolbarVertical())
  43927. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  43928. else
  43929. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  43930. }
  43931. if (getEditingMode() != normalMode && ! drawBar)
  43932. {
  43933. g.setColour (findColour (Toolbar::separatorColourId, true));
  43934. const int indentX = jmin (2, (w - 3) / 2);
  43935. const int indentY = jmin (2, (h - 3) / 2);
  43936. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  43937. if (fixedSize <= 0)
  43938. {
  43939. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  43940. if (isToolbarVertical())
  43941. {
  43942. x1 = w * 0.5f;
  43943. y1 = h * 0.4f;
  43944. x2 = x1;
  43945. y2 = indentX * 2.0f;
  43946. x3 = x1;
  43947. y3 = h * 0.6f;
  43948. x4 = x1;
  43949. y4 = h - y2;
  43950. hw = w * 0.15f;
  43951. hl = w * 0.2f;
  43952. }
  43953. else
  43954. {
  43955. x1 = w * 0.4f;
  43956. y1 = h * 0.5f;
  43957. x2 = indentX * 2.0f;
  43958. y2 = y1;
  43959. x3 = w * 0.6f;
  43960. y3 = y1;
  43961. x4 = w - x2;
  43962. y4 = y1;
  43963. hw = h * 0.15f;
  43964. hl = h * 0.2f;
  43965. }
  43966. Path p;
  43967. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  43968. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  43969. g.fillPath (p);
  43970. }
  43971. }
  43972. }
  43973. private:
  43974. const float fixedSize;
  43975. const bool drawBar;
  43976. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarSpacerComp);
  43977. };
  43978. class Toolbar::MissingItemsComponent : public PopupMenu::CustomComponent
  43979. {
  43980. public:
  43981. MissingItemsComponent (Toolbar& owner_, const int height_)
  43982. : PopupMenu::CustomComponent (true),
  43983. owner (&owner_),
  43984. height (height_)
  43985. {
  43986. for (int i = owner_.items.size(); --i >= 0;)
  43987. {
  43988. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  43989. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  43990. {
  43991. oldIndexes.insert (0, i);
  43992. addAndMakeVisible (tc, 0);
  43993. }
  43994. }
  43995. layout (400);
  43996. }
  43997. ~MissingItemsComponent()
  43998. {
  43999. if (owner != 0)
  44000. {
  44001. for (int i = 0; i < getNumChildComponents(); ++i)
  44002. {
  44003. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44004. if (tc != 0)
  44005. {
  44006. tc->setVisible (false);
  44007. const int index = oldIndexes.remove (i);
  44008. owner->addChildComponent (tc, index);
  44009. --i;
  44010. }
  44011. }
  44012. owner->resized();
  44013. }
  44014. }
  44015. void layout (const int preferredWidth)
  44016. {
  44017. const int indent = 8;
  44018. int x = indent;
  44019. int y = indent;
  44020. int maxX = 0;
  44021. for (int i = 0; i < getNumChildComponents(); ++i)
  44022. {
  44023. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44024. if (tc != 0)
  44025. {
  44026. int preferredSize = 1, minSize = 1, maxSize = 1;
  44027. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44028. {
  44029. if (x + preferredSize > preferredWidth && x > indent)
  44030. {
  44031. x = indent;
  44032. y += height;
  44033. }
  44034. tc->setBounds (x, y, preferredSize, height);
  44035. x += preferredSize;
  44036. maxX = jmax (maxX, x);
  44037. }
  44038. }
  44039. }
  44040. setSize (maxX + 8, y + height + 8);
  44041. }
  44042. void getIdealSize (int& idealWidth, int& idealHeight)
  44043. {
  44044. idealWidth = getWidth();
  44045. idealHeight = getHeight();
  44046. }
  44047. private:
  44048. Component::SafePointer<Toolbar> owner;
  44049. const int height;
  44050. Array <int> oldIndexes;
  44051. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MissingItemsComponent);
  44052. };
  44053. Toolbar::Toolbar()
  44054. : vertical (false),
  44055. isEditingActive (false),
  44056. toolbarStyle (Toolbar::iconsOnly)
  44057. {
  44058. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44059. missingItemsButton->setAlwaysOnTop (true);
  44060. missingItemsButton->addListener (this);
  44061. }
  44062. Toolbar::~Toolbar()
  44063. {
  44064. items.clear();
  44065. }
  44066. void Toolbar::setVertical (const bool shouldBeVertical)
  44067. {
  44068. if (vertical != shouldBeVertical)
  44069. {
  44070. vertical = shouldBeVertical;
  44071. resized();
  44072. }
  44073. }
  44074. void Toolbar::clear()
  44075. {
  44076. items.clear();
  44077. resized();
  44078. }
  44079. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44080. {
  44081. if (itemId == ToolbarItemFactory::separatorBarId)
  44082. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44083. else if (itemId == ToolbarItemFactory::spacerId)
  44084. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44085. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44086. return new ToolbarSpacerComp (itemId, 0, false);
  44087. return factory.createItem (itemId);
  44088. }
  44089. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44090. const int itemId,
  44091. const int insertIndex)
  44092. {
  44093. // An ID can't be zero - this might indicate a mistake somewhere?
  44094. jassert (itemId != 0);
  44095. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44096. if (tc != 0)
  44097. {
  44098. #if JUCE_DEBUG
  44099. Array <int> allowedIds;
  44100. factory.getAllToolbarItemIds (allowedIds);
  44101. // If your factory can create an item for a given ID, it must also return
  44102. // that ID from its getAllToolbarItemIds() method!
  44103. jassert (allowedIds.contains (itemId));
  44104. #endif
  44105. items.insert (insertIndex, tc);
  44106. addAndMakeVisible (tc, insertIndex);
  44107. }
  44108. }
  44109. void Toolbar::addItem (ToolbarItemFactory& factory,
  44110. const int itemId,
  44111. const int insertIndex)
  44112. {
  44113. addItemInternal (factory, itemId, insertIndex);
  44114. resized();
  44115. }
  44116. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44117. {
  44118. Array <int> ids;
  44119. factoryToUse.getDefaultItemSet (ids);
  44120. clear();
  44121. for (int i = 0; i < ids.size(); ++i)
  44122. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44123. resized();
  44124. }
  44125. void Toolbar::removeToolbarItem (const int itemIndex)
  44126. {
  44127. items.remove (itemIndex);
  44128. resized();
  44129. }
  44130. int Toolbar::getNumItems() const throw()
  44131. {
  44132. return items.size();
  44133. }
  44134. int Toolbar::getItemId (const int itemIndex) const throw()
  44135. {
  44136. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44137. return tc != 0 ? tc->getItemId() : 0;
  44138. }
  44139. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44140. {
  44141. return items [itemIndex];
  44142. }
  44143. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44144. {
  44145. for (;;)
  44146. {
  44147. index += delta;
  44148. ToolbarItemComponent* const tc = getItemComponent (index);
  44149. if (tc == 0)
  44150. break;
  44151. if (tc->isActive)
  44152. return tc;
  44153. }
  44154. return 0;
  44155. }
  44156. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44157. {
  44158. if (toolbarStyle != newStyle)
  44159. {
  44160. toolbarStyle = newStyle;
  44161. updateAllItemPositions (false);
  44162. }
  44163. }
  44164. const String Toolbar::toString() const
  44165. {
  44166. String s ("TB:");
  44167. for (int i = 0; i < getNumItems(); ++i)
  44168. s << getItemId(i) << ' ';
  44169. return s.trimEnd();
  44170. }
  44171. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44172. const String& savedVersion)
  44173. {
  44174. if (! savedVersion.startsWith ("TB:"))
  44175. return false;
  44176. StringArray tokens;
  44177. tokens.addTokens (savedVersion.substring (3), false);
  44178. clear();
  44179. for (int i = 0; i < tokens.size(); ++i)
  44180. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44181. resized();
  44182. return true;
  44183. }
  44184. void Toolbar::paint (Graphics& g)
  44185. {
  44186. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44187. }
  44188. int Toolbar::getThickness() const throw()
  44189. {
  44190. return vertical ? getWidth() : getHeight();
  44191. }
  44192. int Toolbar::getLength() const throw()
  44193. {
  44194. return vertical ? getHeight() : getWidth();
  44195. }
  44196. void Toolbar::setEditingActive (const bool active)
  44197. {
  44198. if (isEditingActive != active)
  44199. {
  44200. isEditingActive = active;
  44201. updateAllItemPositions (false);
  44202. }
  44203. }
  44204. void Toolbar::resized()
  44205. {
  44206. updateAllItemPositions (false);
  44207. }
  44208. void Toolbar::updateAllItemPositions (const bool animate)
  44209. {
  44210. if (getWidth() > 0 && getHeight() > 0)
  44211. {
  44212. StretchableObjectResizer resizer;
  44213. int i;
  44214. for (i = 0; i < items.size(); ++i)
  44215. {
  44216. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44217. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44218. : ToolbarItemComponent::normalMode);
  44219. tc->setStyle (toolbarStyle);
  44220. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44221. int preferredSize = 1, minSize = 1, maxSize = 1;
  44222. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44223. preferredSize, minSize, maxSize))
  44224. {
  44225. tc->isActive = true;
  44226. resizer.addItem (preferredSize, minSize, maxSize,
  44227. spacer != 0 ? spacer->getResizeOrder() : 2);
  44228. }
  44229. else
  44230. {
  44231. tc->isActive = false;
  44232. tc->setVisible (false);
  44233. }
  44234. }
  44235. resizer.resizeToFit (getLength());
  44236. int totalLength = 0;
  44237. for (i = 0; i < resizer.getNumItems(); ++i)
  44238. totalLength += (int) resizer.getItemSize (i);
  44239. const bool itemsOffTheEnd = totalLength > getLength();
  44240. const int extrasButtonSize = getThickness() / 2;
  44241. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44242. missingItemsButton->setVisible (itemsOffTheEnd);
  44243. missingItemsButton->setEnabled (! isEditingActive);
  44244. if (vertical)
  44245. missingItemsButton->setCentrePosition (getWidth() / 2,
  44246. getHeight() - 4 - extrasButtonSize / 2);
  44247. else
  44248. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44249. getHeight() / 2);
  44250. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44251. : missingItemsButton->getX()) - 4
  44252. : getLength();
  44253. int pos = 0, activeIndex = 0;
  44254. for (i = 0; i < items.size(); ++i)
  44255. {
  44256. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44257. if (tc->isActive)
  44258. {
  44259. const int size = (int) resizer.getItemSize (activeIndex++);
  44260. Rectangle<int> newBounds;
  44261. if (vertical)
  44262. newBounds.setBounds (0, pos, getWidth(), size);
  44263. else
  44264. newBounds.setBounds (pos, 0, size, getHeight());
  44265. if (animate)
  44266. {
  44267. Desktop::getInstance().getAnimator().animateComponent (tc, newBounds, 1.0f, 200, false, 3.0, 0.0);
  44268. }
  44269. else
  44270. {
  44271. Desktop::getInstance().getAnimator().cancelAnimation (tc, false);
  44272. tc->setBounds (newBounds);
  44273. }
  44274. pos += size;
  44275. tc->setVisible (pos <= maxLength
  44276. && ((! tc->isBeingDragged)
  44277. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44278. }
  44279. }
  44280. }
  44281. }
  44282. void Toolbar::buttonClicked (Button*)
  44283. {
  44284. jassert (missingItemsButton->isShowing());
  44285. if (missingItemsButton->isShowing())
  44286. {
  44287. PopupMenu m;
  44288. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44289. m.showAt (missingItemsButton);
  44290. }
  44291. }
  44292. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44293. Component* /*sourceComponent*/)
  44294. {
  44295. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44296. }
  44297. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44298. {
  44299. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44300. if (tc != 0)
  44301. {
  44302. if (! items.contains (tc))
  44303. {
  44304. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44305. {
  44306. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44307. if (palette != 0)
  44308. palette->replaceComponent (tc);
  44309. }
  44310. else
  44311. {
  44312. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44313. }
  44314. items.add (tc);
  44315. addChildComponent (tc);
  44316. updateAllItemPositions (true);
  44317. }
  44318. for (int i = getNumItems(); --i >= 0;)
  44319. {
  44320. const int currentIndex = items.indexOf (tc);
  44321. int newIndex = currentIndex;
  44322. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44323. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44324. const Rectangle<int> current (Desktop::getInstance().getAnimator()
  44325. .getComponentDestination (getChildComponent (newIndex)));
  44326. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44327. if (prev != 0)
  44328. {
  44329. const Rectangle<int> previousPos (Desktop::getInstance().getAnimator().getComponentDestination (prev));
  44330. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44331. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44332. {
  44333. newIndex = getIndexOfChildComponent (prev);
  44334. }
  44335. }
  44336. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44337. if (next != 0)
  44338. {
  44339. const Rectangle<int> nextPos (Desktop::getInstance().getAnimator().getComponentDestination (next));
  44340. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44341. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44342. {
  44343. newIndex = getIndexOfChildComponent (next) + 1;
  44344. }
  44345. }
  44346. if (newIndex == currentIndex)
  44347. break;
  44348. items.removeObject (tc, false);
  44349. removeChildComponent (tc);
  44350. addChildComponent (tc, newIndex);
  44351. items.insert (newIndex, tc);
  44352. updateAllItemPositions (true);
  44353. }
  44354. }
  44355. }
  44356. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44357. {
  44358. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44359. if (tc != 0 && isParentOf (tc))
  44360. {
  44361. items.removeObject (tc, false);
  44362. removeChildComponent (tc);
  44363. updateAllItemPositions (true);
  44364. }
  44365. }
  44366. void Toolbar::itemDropped (const String&, Component* sourceComponent, int, int)
  44367. {
  44368. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44369. if (tc != 0)
  44370. tc->setState (Button::buttonNormal);
  44371. }
  44372. void Toolbar::mouseDown (const MouseEvent&)
  44373. {
  44374. }
  44375. class ToolbarCustomisationDialog : public DialogWindow
  44376. {
  44377. public:
  44378. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44379. Toolbar* const toolbar_,
  44380. const int optionFlags)
  44381. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44382. toolbar (toolbar_)
  44383. {
  44384. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44385. setResizable (true, true);
  44386. setResizeLimits (400, 300, 1500, 1000);
  44387. positionNearBar();
  44388. }
  44389. ~ToolbarCustomisationDialog()
  44390. {
  44391. setContentComponent (0, true);
  44392. }
  44393. void closeButtonPressed()
  44394. {
  44395. setVisible (false);
  44396. }
  44397. bool canModalEventBeSentToComponent (const Component* comp)
  44398. {
  44399. return toolbar->isParentOf (comp);
  44400. }
  44401. void positionNearBar()
  44402. {
  44403. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44404. const int tbx = toolbar->getScreenX();
  44405. const int tby = toolbar->getScreenY();
  44406. const int gap = 8;
  44407. int x, y;
  44408. if (toolbar->isVertical())
  44409. {
  44410. y = tby;
  44411. if (tbx > screenSize.getCentreX())
  44412. x = tbx - getWidth() - gap;
  44413. else
  44414. x = tbx + toolbar->getWidth() + gap;
  44415. }
  44416. else
  44417. {
  44418. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44419. if (tby > screenSize.getCentreY())
  44420. y = tby - getHeight() - gap;
  44421. else
  44422. y = tby + toolbar->getHeight() + gap;
  44423. }
  44424. setTopLeftPosition (x, y);
  44425. }
  44426. private:
  44427. Toolbar* const toolbar;
  44428. class CustomiserPanel : public Component,
  44429. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44430. private ButtonListener
  44431. {
  44432. public:
  44433. CustomiserPanel (ToolbarItemFactory& factory_,
  44434. Toolbar* const toolbar_,
  44435. const int optionFlags)
  44436. : factory (factory_),
  44437. toolbar (toolbar_),
  44438. palette (factory_, toolbar_),
  44439. instructions (String::empty, TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\n"
  44440. "Items on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")),
  44441. defaultButton (TRANS ("Restore to default set of items"))
  44442. {
  44443. addAndMakeVisible (&palette);
  44444. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44445. | Toolbar::allowIconsWithTextChoice
  44446. | Toolbar::allowTextOnlyChoice)) != 0)
  44447. {
  44448. addAndMakeVisible (&styleBox);
  44449. styleBox.setEditableText (false);
  44450. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0) styleBox.addItem (TRANS("Show icons only"), 1);
  44451. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0) styleBox.addItem (TRANS("Show icons and descriptions"), 2);
  44452. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0) styleBox.addItem (TRANS("Show descriptions only"), 3);
  44453. int selectedStyle = 0;
  44454. switch (toolbar_->getStyle())
  44455. {
  44456. case Toolbar::iconsOnly: selectedStyle = 1; break;
  44457. case Toolbar::iconsWithText: selectedStyle = 2; break;
  44458. case Toolbar::textOnly: selectedStyle = 3; break;
  44459. }
  44460. styleBox.setSelectedId (selectedStyle);
  44461. styleBox.addListener (this);
  44462. }
  44463. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44464. {
  44465. addAndMakeVisible (&defaultButton);
  44466. defaultButton.addListener (this);
  44467. }
  44468. addAndMakeVisible (&instructions);
  44469. instructions.setFont (Font (13.0f));
  44470. setSize (500, 300);
  44471. }
  44472. void comboBoxChanged (ComboBox*)
  44473. {
  44474. switch (styleBox.getSelectedId())
  44475. {
  44476. case 1: toolbar->setStyle (Toolbar::iconsOnly); break;
  44477. case 2: toolbar->setStyle (Toolbar::iconsWithText); break;
  44478. case 3: toolbar->setStyle (Toolbar::textOnly); break;
  44479. }
  44480. palette.resized(); // to make it update the styles
  44481. }
  44482. void buttonClicked (Button*)
  44483. {
  44484. toolbar->addDefaultItems (factory);
  44485. }
  44486. void paint (Graphics& g)
  44487. {
  44488. Colour background;
  44489. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44490. if (dw != 0)
  44491. background = dw->getBackgroundColour();
  44492. g.setColour (background.contrasting().withAlpha (0.3f));
  44493. g.fillRect (palette.getX(), palette.getBottom() - 1, palette.getWidth(), 1);
  44494. }
  44495. void resized()
  44496. {
  44497. palette.setBounds (0, 0, getWidth(), getHeight() - 120);
  44498. styleBox.setBounds (10, getHeight() - 110, 200, 22);
  44499. defaultButton.changeWidthToFitText (22);
  44500. defaultButton.setTopLeftPosition (240, getHeight() - 110);
  44501. instructions.setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44502. }
  44503. private:
  44504. ToolbarItemFactory& factory;
  44505. Toolbar* const toolbar;
  44506. ToolbarItemPalette palette;
  44507. Label instructions;
  44508. ComboBox styleBox;
  44509. TextButton defaultButton;
  44510. };
  44511. };
  44512. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44513. {
  44514. setEditingActive (true);
  44515. #if JUCE_DEBUG
  44516. WeakReference<Component> checker (this);
  44517. #endif
  44518. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44519. dw.runModalLoop();
  44520. #if JUCE_DEBUG
  44521. jassert (checker != 0); // Don't delete the toolbar while it's being customised!
  44522. #endif
  44523. setEditingActive (false);
  44524. }
  44525. END_JUCE_NAMESPACE
  44526. /*** End of inlined file: juce_Toolbar.cpp ***/
  44527. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44528. BEGIN_JUCE_NAMESPACE
  44529. ToolbarItemFactory::ToolbarItemFactory()
  44530. {
  44531. }
  44532. ToolbarItemFactory::~ToolbarItemFactory()
  44533. {
  44534. }
  44535. class ItemDragAndDropOverlayComponent : public Component
  44536. {
  44537. public:
  44538. ItemDragAndDropOverlayComponent()
  44539. : isDragging (false)
  44540. {
  44541. setAlwaysOnTop (true);
  44542. setRepaintsOnMouseActivity (true);
  44543. setMouseCursor (MouseCursor::DraggingHandCursor);
  44544. }
  44545. void paint (Graphics& g)
  44546. {
  44547. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44548. if (isMouseOverOrDragging()
  44549. && tc != 0
  44550. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44551. {
  44552. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44553. g.drawRect (0, 0, getWidth(), getHeight(),
  44554. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44555. }
  44556. }
  44557. void mouseDown (const MouseEvent& e)
  44558. {
  44559. isDragging = false;
  44560. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44561. if (tc != 0)
  44562. {
  44563. tc->dragOffsetX = e.x;
  44564. tc->dragOffsetY = e.y;
  44565. }
  44566. }
  44567. void mouseDrag (const MouseEvent& e)
  44568. {
  44569. if (! (isDragging || e.mouseWasClicked()))
  44570. {
  44571. isDragging = true;
  44572. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  44573. if (dnd != 0)
  44574. {
  44575. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  44576. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44577. if (tc != 0)
  44578. {
  44579. tc->isBeingDragged = true;
  44580. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44581. tc->setVisible (false);
  44582. }
  44583. }
  44584. }
  44585. }
  44586. void mouseUp (const MouseEvent&)
  44587. {
  44588. isDragging = false;
  44589. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44590. if (tc != 0)
  44591. {
  44592. tc->isBeingDragged = false;
  44593. Toolbar* const tb = tc->getToolbar();
  44594. if (tb != 0)
  44595. tb->updateAllItemPositions (true);
  44596. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44597. delete tc;
  44598. }
  44599. }
  44600. void parentSizeChanged()
  44601. {
  44602. setBounds (0, 0, getParentWidth(), getParentHeight());
  44603. }
  44604. private:
  44605. bool isDragging;
  44606. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemDragAndDropOverlayComponent);
  44607. };
  44608. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44609. const String& labelText,
  44610. const bool isBeingUsedAsAButton_)
  44611. : Button (labelText),
  44612. itemId (itemId_),
  44613. mode (normalMode),
  44614. toolbarStyle (Toolbar::iconsOnly),
  44615. dragOffsetX (0),
  44616. dragOffsetY (0),
  44617. isActive (true),
  44618. isBeingDragged (false),
  44619. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44620. {
  44621. // Your item ID can't be 0!
  44622. jassert (itemId_ != 0);
  44623. }
  44624. ToolbarItemComponent::~ToolbarItemComponent()
  44625. {
  44626. overlayComp = 0;
  44627. }
  44628. Toolbar* ToolbarItemComponent::getToolbar() const
  44629. {
  44630. return dynamic_cast <Toolbar*> (getParentComponent());
  44631. }
  44632. bool ToolbarItemComponent::isToolbarVertical() const
  44633. {
  44634. const Toolbar* const t = getToolbar();
  44635. return t != 0 && t->isVertical();
  44636. }
  44637. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44638. {
  44639. if (toolbarStyle != newStyle)
  44640. {
  44641. toolbarStyle = newStyle;
  44642. repaint();
  44643. resized();
  44644. }
  44645. }
  44646. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44647. {
  44648. if (isBeingUsedAsAButton)
  44649. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44650. over, down, *this);
  44651. if (toolbarStyle != Toolbar::iconsOnly)
  44652. {
  44653. const int indent = contentArea.getX();
  44654. int y = indent;
  44655. int h = getHeight() - indent * 2;
  44656. if (toolbarStyle == Toolbar::iconsWithText)
  44657. {
  44658. y = contentArea.getBottom() + indent / 2;
  44659. h -= contentArea.getHeight();
  44660. }
  44661. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44662. getButtonText(), *this);
  44663. }
  44664. if (! contentArea.isEmpty())
  44665. {
  44666. Graphics::ScopedSaveState ss (g);
  44667. g.reduceClipRegion (contentArea);
  44668. g.setOrigin (contentArea.getX(), contentArea.getY());
  44669. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44670. }
  44671. }
  44672. void ToolbarItemComponent::resized()
  44673. {
  44674. if (toolbarStyle != Toolbar::textOnly)
  44675. {
  44676. const int indent = jmin (proportionOfWidth (0.08f),
  44677. proportionOfHeight (0.08f));
  44678. contentArea = Rectangle<int> (indent, indent,
  44679. getWidth() - indent * 2,
  44680. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44681. : (getHeight() - indent * 2));
  44682. }
  44683. else
  44684. {
  44685. contentArea = Rectangle<int>();
  44686. }
  44687. contentAreaChanged (contentArea);
  44688. }
  44689. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44690. {
  44691. if (mode != newMode)
  44692. {
  44693. mode = newMode;
  44694. repaint();
  44695. if (mode == normalMode)
  44696. {
  44697. overlayComp = 0;
  44698. }
  44699. else if (overlayComp == 0)
  44700. {
  44701. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44702. overlayComp->parentSizeChanged();
  44703. }
  44704. resized();
  44705. }
  44706. }
  44707. END_JUCE_NAMESPACE
  44708. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44709. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44710. BEGIN_JUCE_NAMESPACE
  44711. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44712. Toolbar* const toolbar_)
  44713. : factory (factory_),
  44714. toolbar (toolbar_)
  44715. {
  44716. Component* const itemHolder = new Component();
  44717. viewport.setViewedComponent (itemHolder);
  44718. Array <int> allIds;
  44719. factory.getAllToolbarItemIds (allIds);
  44720. for (int i = 0; i < allIds.size(); ++i)
  44721. addComponent (allIds.getUnchecked (i), -1);
  44722. addAndMakeVisible (&viewport);
  44723. }
  44724. ToolbarItemPalette::~ToolbarItemPalette()
  44725. {
  44726. }
  44727. void ToolbarItemPalette::addComponent (const int itemId, const int index)
  44728. {
  44729. ToolbarItemComponent* const tc = Toolbar::createItem (factory, itemId);
  44730. jassert (tc != 0);
  44731. if (tc != 0)
  44732. {
  44733. items.insert (index, tc);
  44734. viewport.getViewedComponent()->addAndMakeVisible (tc, index);
  44735. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  44736. }
  44737. }
  44738. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  44739. {
  44740. const int index = items.indexOf (comp);
  44741. jassert (index >= 0);
  44742. items.removeObject (comp, false);
  44743. addComponent (comp->getItemId(), index);
  44744. resized();
  44745. }
  44746. void ToolbarItemPalette::resized()
  44747. {
  44748. viewport.setBoundsInset (BorderSize<int> (1));
  44749. Component* const itemHolder = viewport.getViewedComponent();
  44750. const int indent = 8;
  44751. const int preferredWidth = viewport.getWidth() - viewport.getScrollBarThickness() - indent;
  44752. const int height = toolbar->getThickness();
  44753. int x = indent;
  44754. int y = indent;
  44755. int maxX = 0;
  44756. for (int i = 0; i < items.size(); ++i)
  44757. {
  44758. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44759. tc->setStyle (toolbar->getStyle());
  44760. int preferredSize = 1, minSize = 1, maxSize = 1;
  44761. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44762. {
  44763. if (x + preferredSize > preferredWidth && x > indent)
  44764. {
  44765. x = indent;
  44766. y += height;
  44767. }
  44768. tc->setBounds (x, y, preferredSize, height);
  44769. x += preferredSize + 8;
  44770. maxX = jmax (maxX, x);
  44771. }
  44772. }
  44773. itemHolder->setSize (maxX, y + height + 8);
  44774. }
  44775. END_JUCE_NAMESPACE
  44776. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  44777. /*** Start of inlined file: juce_TreeView.cpp ***/
  44778. BEGIN_JUCE_NAMESPACE
  44779. class TreeViewContentComponent : public Component,
  44780. public TooltipClient
  44781. {
  44782. public:
  44783. TreeViewContentComponent (TreeView& owner_)
  44784. : owner (owner_),
  44785. buttonUnderMouse (0),
  44786. isDragging (false)
  44787. {
  44788. }
  44789. void mouseDown (const MouseEvent& e)
  44790. {
  44791. updateButtonUnderMouse (e);
  44792. isDragging = false;
  44793. needSelectionOnMouseUp = false;
  44794. Rectangle<int> pos;
  44795. TreeViewItem* const item = findItemAt (e.y, pos);
  44796. if (item == 0)
  44797. return;
  44798. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  44799. // as selection clicks)
  44800. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  44801. {
  44802. if (e.x >= pos.getX() - owner.getIndentSize())
  44803. item->setOpen (! item->isOpen());
  44804. // (clicks to the left of an open/close button are ignored)
  44805. }
  44806. else
  44807. {
  44808. // mouse-down inside the body of the item..
  44809. if (! owner.isMultiSelectEnabled())
  44810. item->setSelected (true, true);
  44811. else if (item->isSelected())
  44812. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  44813. else
  44814. selectBasedOnModifiers (item, e.mods);
  44815. if (e.x >= pos.getX())
  44816. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44817. }
  44818. }
  44819. void mouseUp (const MouseEvent& e)
  44820. {
  44821. updateButtonUnderMouse (e);
  44822. if (needSelectionOnMouseUp && e.mouseWasClicked())
  44823. {
  44824. Rectangle<int> pos;
  44825. TreeViewItem* const item = findItemAt (e.y, pos);
  44826. if (item != 0)
  44827. selectBasedOnModifiers (item, e.mods);
  44828. }
  44829. }
  44830. void mouseDoubleClick (const MouseEvent& e)
  44831. {
  44832. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  44833. {
  44834. Rectangle<int> pos;
  44835. TreeViewItem* const item = findItemAt (e.y, pos);
  44836. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  44837. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44838. }
  44839. }
  44840. void mouseDrag (const MouseEvent& e)
  44841. {
  44842. if (isEnabled()
  44843. && ! (isDragging || e.mouseWasClicked()
  44844. || e.getDistanceFromDragStart() < 5
  44845. || e.mods.isPopupMenu()))
  44846. {
  44847. isDragging = true;
  44848. Rectangle<int> pos;
  44849. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  44850. if (item != 0 && e.getMouseDownX() >= pos.getX())
  44851. {
  44852. const String dragDescription (item->getDragSourceDescription());
  44853. if (dragDescription.isNotEmpty())
  44854. {
  44855. DragAndDropContainer* const dragContainer
  44856. = DragAndDropContainer::findParentDragContainerFor (this);
  44857. if (dragContainer != 0)
  44858. {
  44859. pos.setSize (pos.getWidth(), item->itemHeight);
  44860. Image dragImage (Component::createComponentSnapshot (pos, true));
  44861. dragImage.multiplyAllAlphas (0.6f);
  44862. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  44863. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  44864. }
  44865. else
  44866. {
  44867. // to be able to do a drag-and-drop operation, the treeview needs to
  44868. // be inside a component which is also a DragAndDropContainer.
  44869. jassertfalse;
  44870. }
  44871. }
  44872. }
  44873. }
  44874. }
  44875. void mouseMove (const MouseEvent& e)
  44876. {
  44877. updateButtonUnderMouse (e);
  44878. }
  44879. void mouseExit (const MouseEvent& e)
  44880. {
  44881. updateButtonUnderMouse (e);
  44882. }
  44883. void paint (Graphics& g)
  44884. {
  44885. if (owner.rootItem != 0)
  44886. {
  44887. owner.handleAsyncUpdate();
  44888. if (! owner.rootItemVisible)
  44889. g.setOrigin (0, -owner.rootItem->itemHeight);
  44890. owner.rootItem->paintRecursively (g, getWidth());
  44891. }
  44892. }
  44893. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  44894. {
  44895. if (owner.rootItem != 0)
  44896. {
  44897. owner.handleAsyncUpdate();
  44898. if (! owner.rootItemVisible)
  44899. y += owner.rootItem->itemHeight;
  44900. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  44901. if (ti != 0)
  44902. itemPosition = ti->getItemPosition (false);
  44903. return ti;
  44904. }
  44905. return 0;
  44906. }
  44907. void updateComponents()
  44908. {
  44909. const int visibleTop = -getY();
  44910. const int visibleBottom = visibleTop + getParentHeight();
  44911. {
  44912. for (int i = items.size(); --i >= 0;)
  44913. items.getUnchecked(i)->shouldKeep = false;
  44914. }
  44915. {
  44916. TreeViewItem* item = owner.rootItem;
  44917. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  44918. while (item != 0 && y < visibleBottom)
  44919. {
  44920. y += item->itemHeight;
  44921. if (y >= visibleTop)
  44922. {
  44923. RowItem* const ri = findItem (item->uid);
  44924. if (ri != 0)
  44925. {
  44926. ri->shouldKeep = true;
  44927. }
  44928. else
  44929. {
  44930. Component* const comp = item->createItemComponent();
  44931. if (comp != 0)
  44932. {
  44933. items.add (new RowItem (item, comp, item->uid));
  44934. addAndMakeVisible (comp);
  44935. }
  44936. }
  44937. }
  44938. item = item->getNextVisibleItem (true);
  44939. }
  44940. }
  44941. for (int i = items.size(); --i >= 0;)
  44942. {
  44943. RowItem* const ri = items.getUnchecked(i);
  44944. bool keep = false;
  44945. if (isParentOf (ri->component))
  44946. {
  44947. if (ri->shouldKeep)
  44948. {
  44949. Rectangle<int> pos (ri->item->getItemPosition (false));
  44950. pos.setSize (pos.getWidth(), ri->item->itemHeight);
  44951. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  44952. {
  44953. keep = true;
  44954. ri->component->setBounds (pos);
  44955. }
  44956. }
  44957. if ((! keep) && isMouseDraggingInChildCompOf (ri->component))
  44958. {
  44959. keep = true;
  44960. ri->component->setSize (0, 0);
  44961. }
  44962. }
  44963. if (! keep)
  44964. items.remove (i);
  44965. }
  44966. }
  44967. void updateButtonUnderMouse (const MouseEvent& e)
  44968. {
  44969. TreeViewItem* newItem = 0;
  44970. if (owner.openCloseButtonsVisible)
  44971. {
  44972. Rectangle<int> pos;
  44973. TreeViewItem* item = findItemAt (e.y, pos);
  44974. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  44975. {
  44976. newItem = item;
  44977. if (! newItem->mightContainSubItems())
  44978. newItem = 0;
  44979. }
  44980. }
  44981. if (buttonUnderMouse != newItem)
  44982. {
  44983. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  44984. {
  44985. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44986. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44987. }
  44988. buttonUnderMouse = newItem;
  44989. if (buttonUnderMouse != 0)
  44990. {
  44991. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44992. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44993. }
  44994. }
  44995. }
  44996. bool isMouseOverButton (TreeViewItem* const item) const throw()
  44997. {
  44998. return item == buttonUnderMouse;
  44999. }
  45000. void resized()
  45001. {
  45002. owner.itemsChanged();
  45003. }
  45004. const String getTooltip()
  45005. {
  45006. Rectangle<int> pos;
  45007. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  45008. if (item != 0)
  45009. return item->getTooltip();
  45010. return owner.getTooltip();
  45011. }
  45012. private:
  45013. TreeView& owner;
  45014. struct RowItem
  45015. {
  45016. RowItem (TreeViewItem* const item_, Component* const component_, const int itemUID)
  45017. : component (component_), item (item_), uid (itemUID), shouldKeep (true)
  45018. {
  45019. }
  45020. ~RowItem()
  45021. {
  45022. delete component.get();
  45023. }
  45024. WeakReference<Component> component;
  45025. TreeViewItem* item;
  45026. int uid;
  45027. bool shouldKeep;
  45028. };
  45029. OwnedArray <RowItem> items;
  45030. TreeViewItem* buttonUnderMouse;
  45031. bool isDragging, needSelectionOnMouseUp;
  45032. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45033. {
  45034. TreeViewItem* firstSelected = 0;
  45035. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45036. {
  45037. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45038. jassert (lastSelected != 0);
  45039. int rowStart = firstSelected->getRowNumberInTree();
  45040. int rowEnd = lastSelected->getRowNumberInTree();
  45041. if (rowStart > rowEnd)
  45042. swapVariables (rowStart, rowEnd);
  45043. int ourRow = item->getRowNumberInTree();
  45044. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45045. if (ourRow > otherEnd)
  45046. swapVariables (ourRow, otherEnd);
  45047. for (int i = ourRow; i <= otherEnd; ++i)
  45048. owner.getItemOnRow (i)->setSelected (true, false);
  45049. }
  45050. else
  45051. {
  45052. const bool cmd = modifiers.isCommandDown();
  45053. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45054. }
  45055. }
  45056. bool containsItem (TreeViewItem* const item) const throw()
  45057. {
  45058. for (int i = items.size(); --i >= 0;)
  45059. if (items.getUnchecked(i)->item == item)
  45060. return true;
  45061. return false;
  45062. }
  45063. RowItem* findItem (const int uid) const throw()
  45064. {
  45065. for (int i = items.size(); --i >= 0;)
  45066. {
  45067. RowItem* const ri = items.getUnchecked(i);
  45068. if (ri->uid == uid)
  45069. return ri;
  45070. }
  45071. return 0;
  45072. }
  45073. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45074. {
  45075. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45076. {
  45077. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45078. if (source->isDragging())
  45079. {
  45080. Component* const underMouse = source->getComponentUnderMouse();
  45081. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45082. return true;
  45083. }
  45084. }
  45085. return false;
  45086. }
  45087. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewContentComponent);
  45088. };
  45089. class TreeView::TreeViewport : public Viewport
  45090. {
  45091. public:
  45092. TreeViewport() throw() : lastX (-1) {}
  45093. void updateComponents (const bool triggerResize = false)
  45094. {
  45095. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45096. if (tvc != 0)
  45097. {
  45098. if (triggerResize)
  45099. tvc->resized();
  45100. else
  45101. tvc->updateComponents();
  45102. }
  45103. repaint();
  45104. }
  45105. void visibleAreaChanged (const Rectangle<int>& newVisibleArea)
  45106. {
  45107. const bool hasScrolledSideways = (newVisibleArea.getX() != lastX);
  45108. lastX = newVisibleArea.getX();
  45109. updateComponents (hasScrolledSideways);
  45110. }
  45111. private:
  45112. int lastX;
  45113. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewport);
  45114. };
  45115. TreeView::TreeView (const String& componentName)
  45116. : Component (componentName),
  45117. rootItem (0),
  45118. indentSize (24),
  45119. defaultOpenness (false),
  45120. needsRecalculating (true),
  45121. rootItemVisible (true),
  45122. multiSelectEnabled (false),
  45123. openCloseButtonsVisible (true)
  45124. {
  45125. addAndMakeVisible (viewport = new TreeViewport());
  45126. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45127. viewport->setWantsKeyboardFocus (false);
  45128. setWantsKeyboardFocus (true);
  45129. }
  45130. TreeView::~TreeView()
  45131. {
  45132. if (rootItem != 0)
  45133. rootItem->setOwnerView (0);
  45134. }
  45135. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45136. {
  45137. if (rootItem != newRootItem)
  45138. {
  45139. if (newRootItem != 0)
  45140. {
  45141. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45142. if (newRootItem->ownerView != 0)
  45143. newRootItem->ownerView->setRootItem (0);
  45144. }
  45145. if (rootItem != 0)
  45146. rootItem->setOwnerView (0);
  45147. rootItem = newRootItem;
  45148. if (newRootItem != 0)
  45149. newRootItem->setOwnerView (this);
  45150. needsRecalculating = true;
  45151. handleAsyncUpdate();
  45152. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45153. {
  45154. rootItem->setOpen (false); // force a re-open
  45155. rootItem->setOpen (true);
  45156. }
  45157. }
  45158. }
  45159. void TreeView::deleteRootItem()
  45160. {
  45161. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45162. setRootItem (0);
  45163. }
  45164. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45165. {
  45166. rootItemVisible = shouldBeVisible;
  45167. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45168. {
  45169. rootItem->setOpen (false); // force a re-open
  45170. rootItem->setOpen (true);
  45171. }
  45172. itemsChanged();
  45173. }
  45174. void TreeView::colourChanged()
  45175. {
  45176. setOpaque (findColour (backgroundColourId).isOpaque());
  45177. repaint();
  45178. }
  45179. void TreeView::setIndentSize (const int newIndentSize)
  45180. {
  45181. if (indentSize != newIndentSize)
  45182. {
  45183. indentSize = newIndentSize;
  45184. resized();
  45185. }
  45186. }
  45187. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45188. {
  45189. if (defaultOpenness != isOpenByDefault)
  45190. {
  45191. defaultOpenness = isOpenByDefault;
  45192. itemsChanged();
  45193. }
  45194. }
  45195. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45196. {
  45197. multiSelectEnabled = canMultiSelect;
  45198. }
  45199. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45200. {
  45201. if (openCloseButtonsVisible != shouldBeVisible)
  45202. {
  45203. openCloseButtonsVisible = shouldBeVisible;
  45204. itemsChanged();
  45205. }
  45206. }
  45207. Viewport* TreeView::getViewport() const throw()
  45208. {
  45209. return viewport;
  45210. }
  45211. void TreeView::clearSelectedItems()
  45212. {
  45213. if (rootItem != 0)
  45214. rootItem->deselectAllRecursively();
  45215. }
  45216. int TreeView::getNumSelectedItems (int maximumDepthToSearchTo) const throw()
  45217. {
  45218. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively (maximumDepthToSearchTo) : 0;
  45219. }
  45220. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45221. {
  45222. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45223. }
  45224. int TreeView::getNumRowsInTree() const
  45225. {
  45226. if (rootItem != 0)
  45227. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45228. return 0;
  45229. }
  45230. TreeViewItem* TreeView::getItemOnRow (int index) const
  45231. {
  45232. if (! rootItemVisible)
  45233. ++index;
  45234. if (rootItem != 0 && index >= 0)
  45235. return rootItem->getItemOnRow (index);
  45236. return 0;
  45237. }
  45238. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45239. {
  45240. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45241. Rectangle<int> pos;
  45242. return tc->findItemAt (tc->getLocalPoint (this, Point<int> (0, y)).getY(), pos);
  45243. }
  45244. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45245. {
  45246. if (rootItem == 0)
  45247. return 0;
  45248. return rootItem->findItemFromIdentifierString (identifierString);
  45249. }
  45250. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45251. {
  45252. XmlElement* e = 0;
  45253. if (rootItem != 0)
  45254. {
  45255. e = rootItem->getOpennessState();
  45256. if (e != 0 && alsoIncludeScrollPosition)
  45257. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45258. }
  45259. return e;
  45260. }
  45261. void TreeView::restoreOpennessState (const XmlElement& newState)
  45262. {
  45263. if (rootItem != 0)
  45264. {
  45265. rootItem->restoreOpennessState (newState);
  45266. if (newState.hasAttribute ("scrollPos"))
  45267. viewport->setViewPosition (viewport->getViewPositionX(),
  45268. newState.getIntAttribute ("scrollPos"));
  45269. }
  45270. }
  45271. void TreeView::paint (Graphics& g)
  45272. {
  45273. g.fillAll (findColour (backgroundColourId));
  45274. }
  45275. void TreeView::resized()
  45276. {
  45277. viewport->setBounds (getLocalBounds());
  45278. itemsChanged();
  45279. handleAsyncUpdate();
  45280. }
  45281. void TreeView::enablementChanged()
  45282. {
  45283. repaint();
  45284. }
  45285. void TreeView::moveSelectedRow (int delta)
  45286. {
  45287. if (delta == 0)
  45288. return;
  45289. int rowSelected = 0;
  45290. TreeViewItem* const firstSelected = getSelectedItem (0);
  45291. if (firstSelected != 0)
  45292. rowSelected = firstSelected->getRowNumberInTree();
  45293. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  45294. for (;;)
  45295. {
  45296. TreeViewItem* item = getItemOnRow (rowSelected);
  45297. if (item != 0)
  45298. {
  45299. if (! item->canBeSelected())
  45300. {
  45301. // if the row we want to highlight doesn't allow it, try skipping
  45302. // to the next item..
  45303. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  45304. rowSelected + (delta < 0 ? -1 : 1));
  45305. if (rowSelected != nextRowToTry)
  45306. {
  45307. rowSelected = nextRowToTry;
  45308. continue;
  45309. }
  45310. else
  45311. {
  45312. break;
  45313. }
  45314. }
  45315. item->setSelected (true, true);
  45316. scrollToKeepItemVisible (item);
  45317. }
  45318. break;
  45319. }
  45320. }
  45321. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  45322. {
  45323. if (item != 0 && item->ownerView == this)
  45324. {
  45325. handleAsyncUpdate();
  45326. item = item->getDeepestOpenParentItem();
  45327. int y = item->y;
  45328. int viewTop = viewport->getViewPositionY();
  45329. if (y < viewTop)
  45330. {
  45331. viewport->setViewPosition (viewport->getViewPositionX(), y);
  45332. }
  45333. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  45334. {
  45335. viewport->setViewPosition (viewport->getViewPositionX(),
  45336. (y + item->itemHeight) - viewport->getViewHeight());
  45337. }
  45338. }
  45339. }
  45340. bool TreeView::keyPressed (const KeyPress& key)
  45341. {
  45342. if (key.isKeyCode (KeyPress::upKey))
  45343. {
  45344. moveSelectedRow (-1);
  45345. }
  45346. else if (key.isKeyCode (KeyPress::downKey))
  45347. {
  45348. moveSelectedRow (1);
  45349. }
  45350. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45351. {
  45352. if (rootItem != 0)
  45353. {
  45354. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45355. if (key.isKeyCode (KeyPress::pageUpKey))
  45356. rowsOnScreen = -rowsOnScreen;
  45357. moveSelectedRow (rowsOnScreen);
  45358. }
  45359. }
  45360. else if (key.isKeyCode (KeyPress::homeKey))
  45361. {
  45362. moveSelectedRow (-0x3fffffff);
  45363. }
  45364. else if (key.isKeyCode (KeyPress::endKey))
  45365. {
  45366. moveSelectedRow (0x3fffffff);
  45367. }
  45368. else if (key.isKeyCode (KeyPress::returnKey))
  45369. {
  45370. TreeViewItem* const firstSelected = getSelectedItem (0);
  45371. if (firstSelected != 0)
  45372. firstSelected->setOpen (! firstSelected->isOpen());
  45373. }
  45374. else if (key.isKeyCode (KeyPress::leftKey))
  45375. {
  45376. TreeViewItem* const firstSelected = getSelectedItem (0);
  45377. if (firstSelected != 0)
  45378. {
  45379. if (firstSelected->isOpen())
  45380. {
  45381. firstSelected->setOpen (false);
  45382. }
  45383. else
  45384. {
  45385. TreeViewItem* parent = firstSelected->parentItem;
  45386. if ((! rootItemVisible) && parent == rootItem)
  45387. parent = 0;
  45388. if (parent != 0)
  45389. {
  45390. parent->setSelected (true, true);
  45391. scrollToKeepItemVisible (parent);
  45392. }
  45393. }
  45394. }
  45395. }
  45396. else if (key.isKeyCode (KeyPress::rightKey))
  45397. {
  45398. TreeViewItem* const firstSelected = getSelectedItem (0);
  45399. if (firstSelected != 0)
  45400. {
  45401. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45402. moveSelectedRow (1);
  45403. else
  45404. firstSelected->setOpen (true);
  45405. }
  45406. }
  45407. else
  45408. {
  45409. return false;
  45410. }
  45411. return true;
  45412. }
  45413. void TreeView::itemsChanged() throw()
  45414. {
  45415. needsRecalculating = true;
  45416. repaint();
  45417. triggerAsyncUpdate();
  45418. }
  45419. void TreeView::handleAsyncUpdate()
  45420. {
  45421. if (needsRecalculating)
  45422. {
  45423. needsRecalculating = false;
  45424. const ScopedLock sl (nodeAlterationLock);
  45425. if (rootItem != 0)
  45426. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45427. viewport->updateComponents();
  45428. if (rootItem != 0)
  45429. {
  45430. viewport->getViewedComponent()
  45431. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45432. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45433. }
  45434. else
  45435. {
  45436. viewport->getViewedComponent()->setSize (0, 0);
  45437. }
  45438. }
  45439. }
  45440. class TreeView::InsertPointHighlight : public Component
  45441. {
  45442. public:
  45443. InsertPointHighlight()
  45444. : lastItem (0)
  45445. {
  45446. setSize (100, 12);
  45447. setAlwaysOnTop (true);
  45448. setInterceptsMouseClicks (false, false);
  45449. }
  45450. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45451. {
  45452. lastItem = item;
  45453. lastIndex = insertIndex;
  45454. const int offset = getHeight() / 2;
  45455. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45456. }
  45457. void paint (Graphics& g)
  45458. {
  45459. Path p;
  45460. const float h = (float) getHeight();
  45461. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45462. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45463. p.lineTo ((float) getWidth(), h / 2.0f);
  45464. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45465. g.strokePath (p, PathStrokeType (2.0f));
  45466. }
  45467. TreeViewItem* lastItem;
  45468. int lastIndex;
  45469. private:
  45470. JUCE_DECLARE_NON_COPYABLE (InsertPointHighlight);
  45471. };
  45472. class TreeView::TargetGroupHighlight : public Component
  45473. {
  45474. public:
  45475. TargetGroupHighlight()
  45476. {
  45477. setAlwaysOnTop (true);
  45478. setInterceptsMouseClicks (false, false);
  45479. }
  45480. void setTargetPosition (TreeViewItem* const item) throw()
  45481. {
  45482. Rectangle<int> r (item->getItemPosition (true));
  45483. r.setHeight (item->getItemHeight());
  45484. setBounds (r);
  45485. }
  45486. void paint (Graphics& g)
  45487. {
  45488. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45489. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45490. }
  45491. private:
  45492. JUCE_DECLARE_NON_COPYABLE (TargetGroupHighlight);
  45493. };
  45494. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45495. {
  45496. beginDragAutoRepeat (100);
  45497. if (dragInsertPointHighlight == 0)
  45498. {
  45499. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45500. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45501. }
  45502. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45503. dragTargetGroupHighlight->setTargetPosition (item);
  45504. }
  45505. void TreeView::hideDragHighlight() throw()
  45506. {
  45507. dragInsertPointHighlight = 0;
  45508. dragTargetGroupHighlight = 0;
  45509. }
  45510. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45511. const StringArray& files, const String& sourceDescription,
  45512. Component* sourceComponent) const throw()
  45513. {
  45514. insertIndex = 0;
  45515. TreeViewItem* item = getItemAt (y);
  45516. if (item == 0)
  45517. return 0;
  45518. Rectangle<int> itemPos (item->getItemPosition (true));
  45519. insertIndex = item->getIndexInParent();
  45520. const int oldY = y;
  45521. y = itemPos.getY();
  45522. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45523. {
  45524. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45525. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45526. {
  45527. // Check if we're trying to drag into an empty group item..
  45528. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45529. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45530. {
  45531. insertIndex = 0;
  45532. x = itemPos.getX() + getIndentSize();
  45533. y = itemPos.getBottom();
  45534. return item;
  45535. }
  45536. }
  45537. }
  45538. if (oldY > itemPos.getCentreY())
  45539. {
  45540. y += item->getItemHeight();
  45541. while (item->isLastOfSiblings() && item->parentItem != 0
  45542. && item->parentItem->parentItem != 0)
  45543. {
  45544. if (x > itemPos.getX())
  45545. break;
  45546. item = item->parentItem;
  45547. itemPos = item->getItemPosition (true);
  45548. insertIndex = item->getIndexInParent();
  45549. }
  45550. ++insertIndex;
  45551. }
  45552. x = itemPos.getX();
  45553. return item->parentItem;
  45554. }
  45555. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45556. {
  45557. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45558. int insertIndex;
  45559. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45560. if (item != 0)
  45561. {
  45562. if (scrolled || dragInsertPointHighlight == 0
  45563. || dragInsertPointHighlight->lastItem != item
  45564. || dragInsertPointHighlight->lastIndex != insertIndex)
  45565. {
  45566. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45567. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45568. showDragHighlight (item, insertIndex, x, y);
  45569. else
  45570. hideDragHighlight();
  45571. }
  45572. }
  45573. else
  45574. {
  45575. hideDragHighlight();
  45576. }
  45577. }
  45578. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45579. {
  45580. hideDragHighlight();
  45581. int insertIndex;
  45582. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45583. if (item != 0)
  45584. {
  45585. if (files.size() > 0)
  45586. {
  45587. if (item->isInterestedInFileDrag (files))
  45588. item->filesDropped (files, insertIndex);
  45589. }
  45590. else
  45591. {
  45592. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45593. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45594. }
  45595. }
  45596. }
  45597. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45598. {
  45599. return true;
  45600. }
  45601. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45602. {
  45603. fileDragMove (files, x, y);
  45604. }
  45605. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45606. {
  45607. handleDrag (files, String::empty, 0, x, y);
  45608. }
  45609. void TreeView::fileDragExit (const StringArray&)
  45610. {
  45611. hideDragHighlight();
  45612. }
  45613. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45614. {
  45615. handleDrop (files, String::empty, 0, x, y);
  45616. }
  45617. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45618. {
  45619. return true;
  45620. }
  45621. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45622. {
  45623. itemDragMove (sourceDescription, sourceComponent, x, y);
  45624. }
  45625. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45626. {
  45627. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45628. }
  45629. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45630. {
  45631. hideDragHighlight();
  45632. }
  45633. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45634. {
  45635. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45636. }
  45637. enum TreeViewOpenness
  45638. {
  45639. opennessDefault = 0,
  45640. opennessClosed = 1,
  45641. opennessOpen = 2
  45642. };
  45643. TreeViewItem::TreeViewItem()
  45644. : ownerView (0),
  45645. parentItem (0),
  45646. y (0),
  45647. itemHeight (0),
  45648. totalHeight (0),
  45649. selected (false),
  45650. redrawNeeded (true),
  45651. drawLinesInside (true),
  45652. drawsInLeftMargin (false),
  45653. openness (opennessDefault)
  45654. {
  45655. static int nextUID = 0;
  45656. uid = nextUID++;
  45657. }
  45658. TreeViewItem::~TreeViewItem()
  45659. {
  45660. }
  45661. const String TreeViewItem::getUniqueName() const
  45662. {
  45663. return String::empty;
  45664. }
  45665. void TreeViewItem::itemOpennessChanged (bool)
  45666. {
  45667. }
  45668. int TreeViewItem::getNumSubItems() const throw()
  45669. {
  45670. return subItems.size();
  45671. }
  45672. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45673. {
  45674. return subItems [index];
  45675. }
  45676. void TreeViewItem::clearSubItems()
  45677. {
  45678. if (subItems.size() > 0)
  45679. {
  45680. if (ownerView != 0)
  45681. {
  45682. const ScopedLock sl (ownerView->nodeAlterationLock);
  45683. subItems.clear();
  45684. treeHasChanged();
  45685. }
  45686. else
  45687. {
  45688. subItems.clear();
  45689. }
  45690. }
  45691. }
  45692. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45693. {
  45694. if (newItem != 0)
  45695. {
  45696. newItem->parentItem = this;
  45697. newItem->setOwnerView (ownerView);
  45698. newItem->y = 0;
  45699. newItem->itemHeight = newItem->getItemHeight();
  45700. newItem->totalHeight = 0;
  45701. newItem->itemWidth = newItem->getItemWidth();
  45702. newItem->totalWidth = 0;
  45703. if (ownerView != 0)
  45704. {
  45705. const ScopedLock sl (ownerView->nodeAlterationLock);
  45706. subItems.insert (insertPosition, newItem);
  45707. treeHasChanged();
  45708. if (newItem->isOpen())
  45709. newItem->itemOpennessChanged (true);
  45710. }
  45711. else
  45712. {
  45713. subItems.insert (insertPosition, newItem);
  45714. if (newItem->isOpen())
  45715. newItem->itemOpennessChanged (true);
  45716. }
  45717. }
  45718. }
  45719. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45720. {
  45721. if (ownerView != 0)
  45722. {
  45723. const ScopedLock sl (ownerView->nodeAlterationLock);
  45724. if (isPositiveAndBelow (index, subItems.size()))
  45725. {
  45726. subItems.remove (index, deleteItem);
  45727. treeHasChanged();
  45728. }
  45729. }
  45730. else
  45731. {
  45732. subItems.remove (index, deleteItem);
  45733. }
  45734. }
  45735. bool TreeViewItem::isOpen() const throw()
  45736. {
  45737. if (openness == opennessDefault)
  45738. return ownerView != 0 && ownerView->defaultOpenness;
  45739. else
  45740. return openness == opennessOpen;
  45741. }
  45742. void TreeViewItem::setOpen (const bool shouldBeOpen)
  45743. {
  45744. if (isOpen() != shouldBeOpen)
  45745. {
  45746. openness = shouldBeOpen ? opennessOpen
  45747. : opennessClosed;
  45748. treeHasChanged();
  45749. itemOpennessChanged (isOpen());
  45750. }
  45751. }
  45752. bool TreeViewItem::isSelected() const throw()
  45753. {
  45754. return selected;
  45755. }
  45756. void TreeViewItem::deselectAllRecursively()
  45757. {
  45758. setSelected (false, false);
  45759. for (int i = 0; i < subItems.size(); ++i)
  45760. subItems.getUnchecked(i)->deselectAllRecursively();
  45761. }
  45762. void TreeViewItem::setSelected (const bool shouldBeSelected,
  45763. const bool deselectOtherItemsFirst)
  45764. {
  45765. if (shouldBeSelected && ! canBeSelected())
  45766. return;
  45767. if (deselectOtherItemsFirst)
  45768. getTopLevelItem()->deselectAllRecursively();
  45769. if (shouldBeSelected != selected)
  45770. {
  45771. selected = shouldBeSelected;
  45772. if (ownerView != 0)
  45773. ownerView->repaint();
  45774. itemSelectionChanged (shouldBeSelected);
  45775. }
  45776. }
  45777. void TreeViewItem::paintItem (Graphics&, int, int)
  45778. {
  45779. }
  45780. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  45781. {
  45782. ownerView->getLookAndFeel()
  45783. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  45784. }
  45785. void TreeViewItem::itemClicked (const MouseEvent&)
  45786. {
  45787. }
  45788. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  45789. {
  45790. if (mightContainSubItems())
  45791. setOpen (! isOpen());
  45792. }
  45793. void TreeViewItem::itemSelectionChanged (bool)
  45794. {
  45795. }
  45796. const String TreeViewItem::getTooltip()
  45797. {
  45798. return String::empty;
  45799. }
  45800. const String TreeViewItem::getDragSourceDescription()
  45801. {
  45802. return String::empty;
  45803. }
  45804. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  45805. {
  45806. return false;
  45807. }
  45808. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  45809. {
  45810. }
  45811. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45812. {
  45813. return false;
  45814. }
  45815. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  45816. {
  45817. }
  45818. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  45819. {
  45820. const int indentX = getIndentX();
  45821. int width = itemWidth;
  45822. if (ownerView != 0 && width < 0)
  45823. width = ownerView->viewport->getViewWidth() - indentX;
  45824. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  45825. if (relativeToTreeViewTopLeft)
  45826. r -= ownerView->viewport->getViewPosition();
  45827. return r;
  45828. }
  45829. void TreeViewItem::treeHasChanged() const throw()
  45830. {
  45831. if (ownerView != 0)
  45832. ownerView->itemsChanged();
  45833. }
  45834. void TreeViewItem::repaintItem() const
  45835. {
  45836. if (ownerView != 0 && areAllParentsOpen())
  45837. {
  45838. Rectangle<int> r (getItemPosition (true));
  45839. r.setLeft (0);
  45840. ownerView->viewport->repaint (r);
  45841. }
  45842. }
  45843. bool TreeViewItem::areAllParentsOpen() const throw()
  45844. {
  45845. return parentItem == 0
  45846. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  45847. }
  45848. void TreeViewItem::updatePositions (int newY)
  45849. {
  45850. y = newY;
  45851. itemHeight = getItemHeight();
  45852. totalHeight = itemHeight;
  45853. itemWidth = getItemWidth();
  45854. totalWidth = jmax (itemWidth, 0) + getIndentX();
  45855. if (isOpen())
  45856. {
  45857. newY += totalHeight;
  45858. for (int i = 0; i < subItems.size(); ++i)
  45859. {
  45860. TreeViewItem* const ti = subItems.getUnchecked(i);
  45861. ti->updatePositions (newY);
  45862. newY += ti->totalHeight;
  45863. totalHeight += ti->totalHeight;
  45864. totalWidth = jmax (totalWidth, ti->totalWidth);
  45865. }
  45866. }
  45867. }
  45868. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  45869. {
  45870. TreeViewItem* result = this;
  45871. TreeViewItem* item = this;
  45872. while (item->parentItem != 0)
  45873. {
  45874. item = item->parentItem;
  45875. if (! item->isOpen())
  45876. result = item;
  45877. }
  45878. return result;
  45879. }
  45880. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  45881. {
  45882. ownerView = newOwner;
  45883. for (int i = subItems.size(); --i >= 0;)
  45884. subItems.getUnchecked(i)->setOwnerView (newOwner);
  45885. }
  45886. int TreeViewItem::getIndentX() const throw()
  45887. {
  45888. const int indentWidth = ownerView->getIndentSize();
  45889. int x = ownerView->rootItemVisible ? indentWidth : 0;
  45890. if (! ownerView->openCloseButtonsVisible)
  45891. x -= indentWidth;
  45892. TreeViewItem* p = parentItem;
  45893. while (p != 0)
  45894. {
  45895. x += indentWidth;
  45896. p = p->parentItem;
  45897. }
  45898. return x;
  45899. }
  45900. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  45901. {
  45902. drawsInLeftMargin = canDrawInLeftMargin;
  45903. }
  45904. void TreeViewItem::paintRecursively (Graphics& g, int width)
  45905. {
  45906. jassert (ownerView != 0);
  45907. if (ownerView == 0)
  45908. return;
  45909. const int indent = getIndentX();
  45910. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  45911. {
  45912. Graphics::ScopedSaveState ss (g);
  45913. g.setOrigin (indent, 0);
  45914. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  45915. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  45916. paintItem (g, itemW, itemHeight);
  45917. }
  45918. g.setColour (ownerView->findColour (TreeView::linesColourId));
  45919. const float halfH = itemHeight * 0.5f;
  45920. int depth = 0;
  45921. TreeViewItem* p = parentItem;
  45922. while (p != 0)
  45923. {
  45924. ++depth;
  45925. p = p->parentItem;
  45926. }
  45927. if (! ownerView->rootItemVisible)
  45928. --depth;
  45929. const int indentWidth = ownerView->getIndentSize();
  45930. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  45931. {
  45932. float x = (depth + 0.5f) * indentWidth;
  45933. if (depth >= 0)
  45934. {
  45935. if (parentItem != 0 && parentItem->drawLinesInside)
  45936. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  45937. if ((parentItem != 0 && parentItem->drawLinesInside)
  45938. || (parentItem == 0 && drawLinesInside))
  45939. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  45940. }
  45941. p = parentItem;
  45942. int d = depth;
  45943. while (p != 0 && --d >= 0)
  45944. {
  45945. x -= (float) indentWidth;
  45946. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  45947. && ! p->isLastOfSiblings())
  45948. {
  45949. g.drawLine (x, 0, x, (float) itemHeight);
  45950. }
  45951. p = p->parentItem;
  45952. }
  45953. if (mightContainSubItems())
  45954. {
  45955. Graphics::ScopedSaveState ss (g);
  45956. g.setOrigin (depth * indentWidth, 0);
  45957. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  45958. paintOpenCloseButton (g, indentWidth, itemHeight,
  45959. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  45960. ->isMouseOverButton (this));
  45961. }
  45962. }
  45963. if (isOpen())
  45964. {
  45965. const Rectangle<int> clip (g.getClipBounds());
  45966. for (int i = 0; i < subItems.size(); ++i)
  45967. {
  45968. TreeViewItem* const ti = subItems.getUnchecked(i);
  45969. const int relY = ti->y - y;
  45970. if (relY >= clip.getBottom())
  45971. break;
  45972. if (relY + ti->totalHeight >= clip.getY())
  45973. {
  45974. Graphics::ScopedSaveState ss (g);
  45975. g.setOrigin (0, relY);
  45976. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  45977. ti->paintRecursively (g, width);
  45978. }
  45979. }
  45980. }
  45981. }
  45982. bool TreeViewItem::isLastOfSiblings() const throw()
  45983. {
  45984. return parentItem == 0
  45985. || parentItem->subItems.getLast() == this;
  45986. }
  45987. int TreeViewItem::getIndexInParent() const throw()
  45988. {
  45989. return parentItem == 0 ? 0
  45990. : parentItem->subItems.indexOf (this);
  45991. }
  45992. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  45993. {
  45994. return parentItem == 0 ? this
  45995. : parentItem->getTopLevelItem();
  45996. }
  45997. int TreeViewItem::getNumRows() const throw()
  45998. {
  45999. int num = 1;
  46000. if (isOpen())
  46001. {
  46002. for (int i = subItems.size(); --i >= 0;)
  46003. num += subItems.getUnchecked(i)->getNumRows();
  46004. }
  46005. return num;
  46006. }
  46007. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  46008. {
  46009. if (index == 0)
  46010. return this;
  46011. if (index > 0 && isOpen())
  46012. {
  46013. --index;
  46014. for (int i = 0; i < subItems.size(); ++i)
  46015. {
  46016. TreeViewItem* const item = subItems.getUnchecked(i);
  46017. if (index == 0)
  46018. return item;
  46019. const int numRows = item->getNumRows();
  46020. if (numRows > index)
  46021. return item->getItemOnRow (index);
  46022. index -= numRows;
  46023. }
  46024. }
  46025. return 0;
  46026. }
  46027. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46028. {
  46029. if (isPositiveAndBelow (targetY, totalHeight))
  46030. {
  46031. const int h = itemHeight;
  46032. if (targetY < h)
  46033. return this;
  46034. if (isOpen())
  46035. {
  46036. targetY -= h;
  46037. for (int i = 0; i < subItems.size(); ++i)
  46038. {
  46039. TreeViewItem* const ti = subItems.getUnchecked(i);
  46040. if (targetY < ti->totalHeight)
  46041. return ti->findItemRecursively (targetY);
  46042. targetY -= ti->totalHeight;
  46043. }
  46044. }
  46045. }
  46046. return 0;
  46047. }
  46048. int TreeViewItem::countSelectedItemsRecursively (int depth) const throw()
  46049. {
  46050. int total = isSelected() ? 1 : 0;
  46051. if (depth != 0)
  46052. for (int i = subItems.size(); --i >= 0;)
  46053. total += subItems.getUnchecked(i)->countSelectedItemsRecursively (depth - 1);
  46054. return total;
  46055. }
  46056. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46057. {
  46058. if (isSelected())
  46059. {
  46060. if (index == 0)
  46061. return this;
  46062. --index;
  46063. }
  46064. if (index >= 0)
  46065. {
  46066. for (int i = 0; i < subItems.size(); ++i)
  46067. {
  46068. TreeViewItem* const item = subItems.getUnchecked(i);
  46069. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46070. if (found != 0)
  46071. return found;
  46072. index -= item->countSelectedItemsRecursively (-1);
  46073. }
  46074. }
  46075. return 0;
  46076. }
  46077. int TreeViewItem::getRowNumberInTree() const throw()
  46078. {
  46079. if (parentItem != 0 && ownerView != 0)
  46080. {
  46081. int n = 1 + parentItem->getRowNumberInTree();
  46082. int ourIndex = parentItem->subItems.indexOf (this);
  46083. jassert (ourIndex >= 0);
  46084. while (--ourIndex >= 0)
  46085. n += parentItem->subItems [ourIndex]->getNumRows();
  46086. if (parentItem->parentItem == 0
  46087. && ! ownerView->rootItemVisible)
  46088. --n;
  46089. return n;
  46090. }
  46091. else
  46092. {
  46093. return 0;
  46094. }
  46095. }
  46096. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46097. {
  46098. drawLinesInside = drawLines;
  46099. }
  46100. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46101. {
  46102. if (recurse && isOpen() && subItems.size() > 0)
  46103. return subItems [0];
  46104. if (parentItem != 0)
  46105. {
  46106. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46107. if (nextIndex >= parentItem->subItems.size())
  46108. return parentItem->getNextVisibleItem (false);
  46109. return parentItem->subItems [nextIndex];
  46110. }
  46111. return 0;
  46112. }
  46113. const String TreeViewItem::getItemIdentifierString() const
  46114. {
  46115. String s;
  46116. if (parentItem != 0)
  46117. s = parentItem->getItemIdentifierString();
  46118. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46119. }
  46120. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46121. {
  46122. const String thisId (getUniqueName());
  46123. if (thisId == identifierString)
  46124. return this;
  46125. if (identifierString.startsWith (thisId + "/"))
  46126. {
  46127. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46128. bool wasOpen = isOpen();
  46129. setOpen (true);
  46130. for (int i = subItems.size(); --i >= 0;)
  46131. {
  46132. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46133. if (item != 0)
  46134. return item;
  46135. }
  46136. setOpen (wasOpen);
  46137. }
  46138. return 0;
  46139. }
  46140. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46141. {
  46142. if (e.hasTagName ("CLOSED"))
  46143. {
  46144. setOpen (false);
  46145. }
  46146. else if (e.hasTagName ("OPEN"))
  46147. {
  46148. setOpen (true);
  46149. forEachXmlChildElement (e, n)
  46150. {
  46151. const String id (n->getStringAttribute ("id"));
  46152. for (int i = 0; i < subItems.size(); ++i)
  46153. {
  46154. TreeViewItem* const ti = subItems.getUnchecked(i);
  46155. if (ti->getUniqueName() == id)
  46156. {
  46157. ti->restoreOpennessState (*n);
  46158. break;
  46159. }
  46160. }
  46161. }
  46162. }
  46163. }
  46164. XmlElement* TreeViewItem::getOpennessState() const throw()
  46165. {
  46166. const String name (getUniqueName());
  46167. if (name.isNotEmpty())
  46168. {
  46169. XmlElement* e;
  46170. if (isOpen())
  46171. {
  46172. e = new XmlElement ("OPEN");
  46173. for (int i = 0; i < subItems.size(); ++i)
  46174. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46175. }
  46176. else
  46177. {
  46178. e = new XmlElement ("CLOSED");
  46179. }
  46180. e->setAttribute ("id", name);
  46181. return e;
  46182. }
  46183. else
  46184. {
  46185. // trying to save the openness for an element that has no name - this won't
  46186. // work because it needs the names to identify what to open.
  46187. jassertfalse;
  46188. }
  46189. return 0;
  46190. }
  46191. TreeViewItem::OpennessRestorer::OpennessRestorer (TreeViewItem& treeViewItem_)
  46192. : treeViewItem (treeViewItem_),
  46193. oldOpenness (treeViewItem_.getOpennessState())
  46194. {
  46195. }
  46196. TreeViewItem::OpennessRestorer::~OpennessRestorer()
  46197. {
  46198. if (oldOpenness != 0)
  46199. treeViewItem.restoreOpennessState (*oldOpenness);
  46200. }
  46201. END_JUCE_NAMESPACE
  46202. /*** End of inlined file: juce_TreeView.cpp ***/
  46203. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46204. BEGIN_JUCE_NAMESPACE
  46205. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46206. : fileList (listToShow)
  46207. {
  46208. }
  46209. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46210. {
  46211. }
  46212. FileBrowserListener::~FileBrowserListener()
  46213. {
  46214. }
  46215. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46216. {
  46217. listeners.add (listener);
  46218. }
  46219. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46220. {
  46221. listeners.remove (listener);
  46222. }
  46223. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46224. {
  46225. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46226. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46227. }
  46228. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46229. {
  46230. if (fileList.getDirectory().exists())
  46231. {
  46232. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46233. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46234. }
  46235. }
  46236. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46237. {
  46238. if (fileList.getDirectory().exists())
  46239. {
  46240. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46241. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46242. }
  46243. }
  46244. END_JUCE_NAMESPACE
  46245. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46246. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46247. BEGIN_JUCE_NAMESPACE
  46248. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46249. TimeSliceThread& thread_)
  46250. : fileFilter (fileFilter_),
  46251. thread (thread_),
  46252. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46253. fileFindHandle (0),
  46254. shouldStop (true)
  46255. {
  46256. }
  46257. DirectoryContentsList::~DirectoryContentsList()
  46258. {
  46259. clear();
  46260. }
  46261. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46262. {
  46263. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46264. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46265. }
  46266. bool DirectoryContentsList::ignoresHiddenFiles() const
  46267. {
  46268. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46269. }
  46270. const File& DirectoryContentsList::getDirectory() const
  46271. {
  46272. return root;
  46273. }
  46274. void DirectoryContentsList::setDirectory (const File& directory,
  46275. const bool includeDirectories,
  46276. const bool includeFiles)
  46277. {
  46278. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46279. if (directory != root)
  46280. {
  46281. clear();
  46282. root = directory;
  46283. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46284. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46285. }
  46286. int newFlags = fileTypeFlags;
  46287. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46288. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46289. setTypeFlags (newFlags);
  46290. }
  46291. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46292. {
  46293. if (fileTypeFlags != newFlags)
  46294. {
  46295. fileTypeFlags = newFlags;
  46296. refresh();
  46297. }
  46298. }
  46299. void DirectoryContentsList::clear()
  46300. {
  46301. shouldStop = true;
  46302. thread.removeTimeSliceClient (this);
  46303. fileFindHandle = 0;
  46304. if (files.size() > 0)
  46305. {
  46306. files.clear();
  46307. changed();
  46308. }
  46309. }
  46310. void DirectoryContentsList::refresh()
  46311. {
  46312. clear();
  46313. if (root.isDirectory())
  46314. {
  46315. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46316. shouldStop = false;
  46317. thread.addTimeSliceClient (this);
  46318. }
  46319. }
  46320. int DirectoryContentsList::getNumFiles() const
  46321. {
  46322. return files.size();
  46323. }
  46324. bool DirectoryContentsList::getFileInfo (const int index,
  46325. FileInfo& result) const
  46326. {
  46327. const ScopedLock sl (fileListLock);
  46328. const FileInfo* const info = files [index];
  46329. if (info != 0)
  46330. {
  46331. result = *info;
  46332. return true;
  46333. }
  46334. return false;
  46335. }
  46336. const File DirectoryContentsList::getFile (const int index) const
  46337. {
  46338. const ScopedLock sl (fileListLock);
  46339. const FileInfo* const info = files [index];
  46340. if (info != 0)
  46341. return root.getChildFile (info->filename);
  46342. return File::nonexistent;
  46343. }
  46344. bool DirectoryContentsList::isStillLoading() const
  46345. {
  46346. return fileFindHandle != 0;
  46347. }
  46348. void DirectoryContentsList::changed()
  46349. {
  46350. sendChangeMessage();
  46351. }
  46352. int DirectoryContentsList::useTimeSlice()
  46353. {
  46354. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46355. bool hasChanged = false;
  46356. for (int i = 100; --i >= 0;)
  46357. {
  46358. if (! checkNextFile (hasChanged))
  46359. {
  46360. if (hasChanged)
  46361. changed();
  46362. return 500;
  46363. }
  46364. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46365. break;
  46366. }
  46367. if (hasChanged)
  46368. changed();
  46369. return 0;
  46370. }
  46371. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46372. {
  46373. if (fileFindHandle != 0)
  46374. {
  46375. bool fileFoundIsDir, isHidden, isReadOnly;
  46376. int64 fileSize;
  46377. Time modTime, creationTime;
  46378. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46379. &modTime, &creationTime, &isReadOnly))
  46380. {
  46381. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46382. fileSize, modTime, creationTime, isReadOnly))
  46383. {
  46384. hasChanged = true;
  46385. }
  46386. return true;
  46387. }
  46388. else
  46389. {
  46390. fileFindHandle = 0;
  46391. }
  46392. }
  46393. return false;
  46394. }
  46395. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46396. const DirectoryContentsList::FileInfo* const second)
  46397. {
  46398. #if JUCE_WINDOWS
  46399. if (first->isDirectory != second->isDirectory)
  46400. return first->isDirectory ? -1 : 1;
  46401. #endif
  46402. return first->filename.compareIgnoreCase (second->filename);
  46403. }
  46404. bool DirectoryContentsList::addFile (const File& file,
  46405. const bool isDir,
  46406. const int64 fileSize,
  46407. const Time& modTime,
  46408. const Time& creationTime,
  46409. const bool isReadOnly)
  46410. {
  46411. if (fileFilter == 0
  46412. || ((! isDir) && fileFilter->isFileSuitable (file))
  46413. || (isDir && fileFilter->isDirectorySuitable (file)))
  46414. {
  46415. ScopedPointer <FileInfo> info (new FileInfo());
  46416. info->filename = file.getFileName();
  46417. info->fileSize = fileSize;
  46418. info->modificationTime = modTime;
  46419. info->creationTime = creationTime;
  46420. info->isDirectory = isDir;
  46421. info->isReadOnly = isReadOnly;
  46422. const ScopedLock sl (fileListLock);
  46423. for (int i = files.size(); --i >= 0;)
  46424. if (files.getUnchecked(i)->filename == info->filename)
  46425. return false;
  46426. files.addSorted (*this, info.release());
  46427. return true;
  46428. }
  46429. return false;
  46430. }
  46431. END_JUCE_NAMESPACE
  46432. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46433. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46434. BEGIN_JUCE_NAMESPACE
  46435. FileBrowserComponent::FileBrowserComponent (int flags_,
  46436. const File& initialFileOrDirectory,
  46437. const FileFilter* fileFilter_,
  46438. FilePreviewComponent* previewComp_)
  46439. : FileFilter (String::empty),
  46440. fileFilter (fileFilter_),
  46441. flags (flags_),
  46442. previewComp (previewComp_),
  46443. currentPathBox ("path"),
  46444. fileLabel ("f", TRANS ("file:")),
  46445. thread ("Juce FileBrowser")
  46446. {
  46447. // You need to specify one or other of the open/save flags..
  46448. jassert ((flags & (saveMode | openMode)) != 0);
  46449. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46450. // You need to specify at least one of these flags..
  46451. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46452. String filename;
  46453. if (initialFileOrDirectory == File::nonexistent)
  46454. {
  46455. currentRoot = File::getCurrentWorkingDirectory();
  46456. }
  46457. else if (initialFileOrDirectory.isDirectory())
  46458. {
  46459. currentRoot = initialFileOrDirectory;
  46460. }
  46461. else
  46462. {
  46463. chosenFiles.add (initialFileOrDirectory);
  46464. currentRoot = initialFileOrDirectory.getParentDirectory();
  46465. filename = initialFileOrDirectory.getFileName();
  46466. }
  46467. fileList = new DirectoryContentsList (this, thread);
  46468. if ((flags & useTreeView) != 0)
  46469. {
  46470. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46471. fileListComponent = tree;
  46472. if ((flags & canSelectMultipleItems) != 0)
  46473. tree->setMultiSelectEnabled (true);
  46474. addAndMakeVisible (tree);
  46475. }
  46476. else
  46477. {
  46478. FileListComponent* const list = new FileListComponent (*fileList);
  46479. fileListComponent = list;
  46480. list->setOutlineThickness (1);
  46481. if ((flags & canSelectMultipleItems) != 0)
  46482. list->setMultipleSelectionEnabled (true);
  46483. addAndMakeVisible (list);
  46484. }
  46485. fileListComponent->addListener (this);
  46486. addAndMakeVisible (&currentPathBox);
  46487. currentPathBox.setEditableText (true);
  46488. StringArray rootNames, rootPaths;
  46489. getRoots (rootNames, rootPaths);
  46490. for (int i = 0; i < rootNames.size(); ++i)
  46491. {
  46492. if (rootNames[i].isEmpty())
  46493. currentPathBox.addSeparator();
  46494. else
  46495. currentPathBox.addItem (rootNames[i], i + 1);
  46496. }
  46497. currentPathBox.addSeparator();
  46498. currentPathBox.addListener (this);
  46499. addAndMakeVisible (&filenameBox);
  46500. filenameBox.setMultiLine (false);
  46501. filenameBox.setSelectAllWhenFocused (true);
  46502. filenameBox.setText (filename, false);
  46503. filenameBox.addListener (this);
  46504. filenameBox.setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46505. addAndMakeVisible (&fileLabel);
  46506. fileLabel.attachToComponent (&filenameBox, true);
  46507. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46508. goUpButton->addListener (this);
  46509. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46510. if (previewComp != 0)
  46511. addAndMakeVisible (previewComp);
  46512. setRoot (currentRoot);
  46513. thread.startThread (4);
  46514. }
  46515. FileBrowserComponent::~FileBrowserComponent()
  46516. {
  46517. fileListComponent = 0;
  46518. fileList = 0;
  46519. thread.stopThread (10000);
  46520. }
  46521. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46522. {
  46523. listeners.add (newListener);
  46524. }
  46525. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46526. {
  46527. listeners.remove (listener);
  46528. }
  46529. bool FileBrowserComponent::isSaveMode() const throw()
  46530. {
  46531. return (flags & saveMode) != 0;
  46532. }
  46533. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46534. {
  46535. if (chosenFiles.size() == 0 && currentFileIsValid())
  46536. return 1;
  46537. return chosenFiles.size();
  46538. }
  46539. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46540. {
  46541. if ((flags & canSelectDirectories) != 0 && filenameBox.getText().isEmpty())
  46542. return currentRoot;
  46543. if (! filenameBox.isReadOnly())
  46544. return currentRoot.getChildFile (filenameBox.getText());
  46545. return chosenFiles[index];
  46546. }
  46547. bool FileBrowserComponent::currentFileIsValid() const
  46548. {
  46549. if (isSaveMode())
  46550. return ! getSelectedFile (0).isDirectory();
  46551. else
  46552. return getSelectedFile (0).exists();
  46553. }
  46554. const File FileBrowserComponent::getHighlightedFile() const throw()
  46555. {
  46556. return fileListComponent->getSelectedFile (0);
  46557. }
  46558. void FileBrowserComponent::deselectAllFiles()
  46559. {
  46560. fileListComponent->deselectAllFiles();
  46561. }
  46562. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46563. {
  46564. return (flags & canSelectFiles) != 0 && (fileFilter == 0 || fileFilter->isFileSuitable (file));
  46565. }
  46566. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46567. {
  46568. return true;
  46569. }
  46570. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  46571. {
  46572. if (f.isDirectory())
  46573. return (flags & canSelectDirectories) != 0
  46574. && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46575. return (flags & canSelectFiles) != 0 && f.exists()
  46576. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46577. }
  46578. const File FileBrowserComponent::getRoot() const
  46579. {
  46580. return currentRoot;
  46581. }
  46582. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46583. {
  46584. if (currentRoot != newRootDirectory)
  46585. {
  46586. fileListComponent->scrollToTop();
  46587. String path (newRootDirectory.getFullPathName());
  46588. if (path.isEmpty())
  46589. path = File::separatorString;
  46590. StringArray rootNames, rootPaths;
  46591. getRoots (rootNames, rootPaths);
  46592. if (! rootPaths.contains (path, true))
  46593. {
  46594. bool alreadyListed = false;
  46595. for (int i = currentPathBox.getNumItems(); --i >= 0;)
  46596. {
  46597. if (currentPathBox.getItemText (i).equalsIgnoreCase (path))
  46598. {
  46599. alreadyListed = true;
  46600. break;
  46601. }
  46602. }
  46603. if (! alreadyListed)
  46604. currentPathBox.addItem (path, currentPathBox.getNumItems() + 2);
  46605. }
  46606. }
  46607. currentRoot = newRootDirectory;
  46608. fileList->setDirectory (currentRoot, true, true);
  46609. String currentRootName (currentRoot.getFullPathName());
  46610. if (currentRootName.isEmpty())
  46611. currentRootName = File::separatorString;
  46612. currentPathBox.setText (currentRootName, true);
  46613. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46614. && currentRoot.getParentDirectory() != currentRoot);
  46615. }
  46616. void FileBrowserComponent::goUp()
  46617. {
  46618. setRoot (getRoot().getParentDirectory());
  46619. }
  46620. void FileBrowserComponent::refresh()
  46621. {
  46622. fileList->refresh();
  46623. }
  46624. void FileBrowserComponent::setFileFilter (const FileFilter* const newFileFilter)
  46625. {
  46626. if (fileFilter != newFileFilter)
  46627. {
  46628. fileFilter = newFileFilter;
  46629. refresh();
  46630. }
  46631. }
  46632. const String FileBrowserComponent::getActionVerb() const
  46633. {
  46634. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46635. }
  46636. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46637. {
  46638. return previewComp;
  46639. }
  46640. void FileBrowserComponent::resized()
  46641. {
  46642. getLookAndFeel()
  46643. .layoutFileBrowserComponent (*this, fileListComponent, previewComp,
  46644. &currentPathBox, &filenameBox, goUpButton);
  46645. }
  46646. void FileBrowserComponent::sendListenerChangeMessage()
  46647. {
  46648. Component::BailOutChecker checker (this);
  46649. if (previewComp != 0)
  46650. previewComp->selectedFileChanged (getSelectedFile (0));
  46651. // You shouldn't delete the browser when the file gets changed!
  46652. jassert (! checker.shouldBailOut());
  46653. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46654. }
  46655. void FileBrowserComponent::selectionChanged()
  46656. {
  46657. StringArray newFilenames;
  46658. bool resetChosenFiles = true;
  46659. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46660. {
  46661. const File f (fileListComponent->getSelectedFile (i));
  46662. if (isFileOrDirSuitable (f))
  46663. {
  46664. if (resetChosenFiles)
  46665. {
  46666. chosenFiles.clear();
  46667. resetChosenFiles = false;
  46668. }
  46669. chosenFiles.add (f);
  46670. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46671. }
  46672. }
  46673. if (newFilenames.size() > 0)
  46674. filenameBox.setText (newFilenames.joinIntoString (", "), false);
  46675. sendListenerChangeMessage();
  46676. }
  46677. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46678. {
  46679. Component::BailOutChecker checker (this);
  46680. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46681. }
  46682. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46683. {
  46684. if (f.isDirectory())
  46685. {
  46686. setRoot (f);
  46687. if ((flags & canSelectDirectories) != 0)
  46688. filenameBox.setText (String::empty);
  46689. }
  46690. else
  46691. {
  46692. Component::BailOutChecker checker (this);
  46693. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46694. }
  46695. }
  46696. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46697. {
  46698. (void) key;
  46699. #if JUCE_LINUX || JUCE_WINDOWS
  46700. if (key.getModifiers().isCommandDown()
  46701. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46702. {
  46703. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46704. fileList->refresh();
  46705. return true;
  46706. }
  46707. #endif
  46708. return false;
  46709. }
  46710. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46711. {
  46712. sendListenerChangeMessage();
  46713. }
  46714. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46715. {
  46716. if (filenameBox.getText().containsChar (File::separator))
  46717. {
  46718. const File f (currentRoot.getChildFile (filenameBox.getText()));
  46719. if (f.isDirectory())
  46720. {
  46721. setRoot (f);
  46722. chosenFiles.clear();
  46723. filenameBox.setText (String::empty);
  46724. }
  46725. else
  46726. {
  46727. setRoot (f.getParentDirectory());
  46728. chosenFiles.clear();
  46729. chosenFiles.add (f);
  46730. filenameBox.setText (f.getFileName());
  46731. }
  46732. }
  46733. else
  46734. {
  46735. fileDoubleClicked (getSelectedFile (0));
  46736. }
  46737. }
  46738. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46739. {
  46740. }
  46741. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46742. {
  46743. if (! isSaveMode())
  46744. selectionChanged();
  46745. }
  46746. void FileBrowserComponent::buttonClicked (Button*)
  46747. {
  46748. goUp();
  46749. }
  46750. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  46751. {
  46752. const String newText (currentPathBox.getText().trim().unquoted());
  46753. if (newText.isNotEmpty())
  46754. {
  46755. const int index = currentPathBox.getSelectedId() - 1;
  46756. StringArray rootNames, rootPaths;
  46757. getRoots (rootNames, rootPaths);
  46758. if (rootPaths [index].isNotEmpty())
  46759. {
  46760. setRoot (File (rootPaths [index]));
  46761. }
  46762. else
  46763. {
  46764. File f (newText);
  46765. for (;;)
  46766. {
  46767. if (f.isDirectory())
  46768. {
  46769. setRoot (f);
  46770. break;
  46771. }
  46772. if (f.getParentDirectory() == f)
  46773. break;
  46774. f = f.getParentDirectory();
  46775. }
  46776. }
  46777. }
  46778. }
  46779. void FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  46780. {
  46781. #if JUCE_WINDOWS
  46782. Array<File> roots;
  46783. File::findFileSystemRoots (roots);
  46784. rootPaths.clear();
  46785. for (int i = 0; i < roots.size(); ++i)
  46786. {
  46787. const File& drive = roots.getReference(i);
  46788. String name (drive.getFullPathName());
  46789. rootPaths.add (name);
  46790. if (drive.isOnHardDisk())
  46791. {
  46792. String volume (drive.getVolumeLabel());
  46793. if (volume.isEmpty())
  46794. volume = TRANS("Hard Drive");
  46795. name << " [" << volume << ']';
  46796. }
  46797. else if (drive.isOnCDRomDrive())
  46798. {
  46799. name << TRANS(" [CD/DVD drive]");
  46800. }
  46801. rootNames.add (name);
  46802. }
  46803. rootPaths.add (String::empty);
  46804. rootNames.add (String::empty);
  46805. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46806. rootNames.add ("Documents");
  46807. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46808. rootNames.add ("Desktop");
  46809. #endif
  46810. #if JUCE_MAC
  46811. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46812. rootNames.add ("Home folder");
  46813. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46814. rootNames.add ("Documents");
  46815. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46816. rootNames.add ("Desktop");
  46817. rootPaths.add (String::empty);
  46818. rootNames.add (String::empty);
  46819. Array <File> volumes;
  46820. File vol ("/Volumes");
  46821. vol.findChildFiles (volumes, File::findDirectories, false);
  46822. for (int i = 0; i < volumes.size(); ++i)
  46823. {
  46824. const File& volume = volumes.getReference(i);
  46825. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  46826. {
  46827. rootPaths.add (volume.getFullPathName());
  46828. rootNames.add (volume.getFileName());
  46829. }
  46830. }
  46831. #endif
  46832. #if JUCE_LINUX
  46833. rootPaths.add ("/");
  46834. rootNames.add ("/");
  46835. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46836. rootNames.add ("Home folder");
  46837. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46838. rootNames.add ("Desktop");
  46839. #endif
  46840. }
  46841. END_JUCE_NAMESPACE
  46842. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  46843. /*** Start of inlined file: juce_FileChooser.cpp ***/
  46844. BEGIN_JUCE_NAMESPACE
  46845. FileChooser::FileChooser (const String& chooserBoxTitle,
  46846. const File& currentFileOrDirectory,
  46847. const String& fileFilters,
  46848. const bool useNativeDialogBox_)
  46849. : title (chooserBoxTitle),
  46850. filters (fileFilters),
  46851. startingFile (currentFileOrDirectory),
  46852. useNativeDialogBox (useNativeDialogBox_)
  46853. {
  46854. #if JUCE_LINUX
  46855. useNativeDialogBox = false;
  46856. #endif
  46857. if (! fileFilters.containsNonWhitespaceChars())
  46858. filters = "*";
  46859. }
  46860. FileChooser::~FileChooser()
  46861. {
  46862. }
  46863. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  46864. {
  46865. return showDialog (false, true, false, false, false, previewComponent);
  46866. }
  46867. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  46868. {
  46869. return showDialog (false, true, false, false, true, previewComponent);
  46870. }
  46871. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  46872. {
  46873. return showDialog (true, true, false, false, true, previewComponent);
  46874. }
  46875. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  46876. {
  46877. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  46878. }
  46879. bool FileChooser::browseForDirectory()
  46880. {
  46881. return showDialog (true, false, false, false, false, 0);
  46882. }
  46883. const File FileChooser::getResult() const
  46884. {
  46885. // if you've used a multiple-file select, you should use the getResults() method
  46886. // to retrieve all the files that were chosen.
  46887. jassert (results.size() <= 1);
  46888. return results.getFirst();
  46889. }
  46890. const Array<File>& FileChooser::getResults() const
  46891. {
  46892. return results;
  46893. }
  46894. bool FileChooser::showDialog (const bool selectsDirectories,
  46895. const bool selectsFiles,
  46896. const bool isSave,
  46897. const bool warnAboutOverwritingExistingFiles,
  46898. const bool selectMultipleFiles,
  46899. FilePreviewComponent* const previewComponent)
  46900. {
  46901. WeakReference<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  46902. results.clear();
  46903. // the preview component needs to be the right size before you pass it in here..
  46904. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  46905. && previewComponent->getHeight() > 10));
  46906. #if JUCE_WINDOWS
  46907. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  46908. #elif JUCE_MAC
  46909. if (useNativeDialogBox && (previewComponent == 0))
  46910. #else
  46911. if (false)
  46912. #endif
  46913. {
  46914. showPlatformDialog (results, title, startingFile, filters,
  46915. selectsDirectories, selectsFiles, isSave,
  46916. warnAboutOverwritingExistingFiles,
  46917. selectMultipleFiles,
  46918. previewComponent);
  46919. }
  46920. else
  46921. {
  46922. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  46923. selectsDirectories ? "*" : String::empty,
  46924. String::empty);
  46925. int flags = isSave ? FileBrowserComponent::saveMode
  46926. : FileBrowserComponent::openMode;
  46927. if (selectsFiles)
  46928. flags |= FileBrowserComponent::canSelectFiles;
  46929. if (selectsDirectories)
  46930. {
  46931. flags |= FileBrowserComponent::canSelectDirectories;
  46932. if (! isSave)
  46933. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  46934. }
  46935. if (selectMultipleFiles)
  46936. flags |= FileBrowserComponent::canSelectMultipleItems;
  46937. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  46938. FileChooserDialogBox box (title, String::empty,
  46939. browserComponent,
  46940. warnAboutOverwritingExistingFiles,
  46941. browserComponent.findColour (AlertWindow::backgroundColourId));
  46942. if (box.show())
  46943. {
  46944. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  46945. results.add (browserComponent.getSelectedFile (i));
  46946. }
  46947. }
  46948. if (previouslyFocused != 0)
  46949. previouslyFocused->grabKeyboardFocus();
  46950. return results.size() > 0;
  46951. }
  46952. FilePreviewComponent::FilePreviewComponent()
  46953. {
  46954. }
  46955. FilePreviewComponent::~FilePreviewComponent()
  46956. {
  46957. }
  46958. END_JUCE_NAMESPACE
  46959. /*** End of inlined file: juce_FileChooser.cpp ***/
  46960. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  46961. BEGIN_JUCE_NAMESPACE
  46962. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  46963. const String& instructions,
  46964. FileBrowserComponent& chooserComponent,
  46965. const bool warnAboutOverwritingExistingFiles_,
  46966. const Colour& backgroundColour)
  46967. : ResizableWindow (name, backgroundColour, true),
  46968. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  46969. {
  46970. setContentComponent (content = new ContentComponent (name, instructions, chooserComponent));
  46971. setResizable (true, true);
  46972. setResizeLimits (300, 300, 1200, 1000);
  46973. content->okButton.addListener (this);
  46974. content->cancelButton.addListener (this);
  46975. content->newFolderButton.addListener (this);
  46976. content->chooserComponent.addListener (this);
  46977. selectionChanged();
  46978. }
  46979. FileChooserDialogBox::~FileChooserDialogBox()
  46980. {
  46981. content->chooserComponent.removeListener (this);
  46982. }
  46983. bool FileChooserDialogBox::show (int w, int h)
  46984. {
  46985. return showAt (-1, -1, w, h);
  46986. }
  46987. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  46988. {
  46989. if (w <= 0)
  46990. {
  46991. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  46992. if (previewComp != 0)
  46993. w = 400 + previewComp->getWidth();
  46994. else
  46995. w = 600;
  46996. }
  46997. if (h <= 0)
  46998. h = 500;
  46999. if (x < 0 || y < 0)
  47000. centreWithSize (w, h);
  47001. else
  47002. setBounds (x, y, w, h);
  47003. const bool ok = (runModalLoop() != 0);
  47004. setVisible (false);
  47005. return ok;
  47006. }
  47007. void FileChooserDialogBox::buttonClicked (Button* button)
  47008. {
  47009. if (button == &(content->okButton))
  47010. {
  47011. okButtonPressed();
  47012. }
  47013. else if (button == &(content->cancelButton))
  47014. {
  47015. closeButtonPressed();
  47016. }
  47017. else if (button == &(content->newFolderButton))
  47018. {
  47019. createNewFolder();
  47020. }
  47021. }
  47022. void FileChooserDialogBox::closeButtonPressed()
  47023. {
  47024. setVisible (false);
  47025. }
  47026. void FileChooserDialogBox::selectionChanged()
  47027. {
  47028. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47029. content->newFolderButton.setVisible (content->chooserComponent.isSaveMode()
  47030. && content->chooserComponent.getRoot().isDirectory());
  47031. }
  47032. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47033. {
  47034. }
  47035. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47036. {
  47037. selectionChanged();
  47038. content->okButton.triggerClick();
  47039. }
  47040. void FileChooserDialogBox::okButtonPressed()
  47041. {
  47042. if ((! (warnAboutOverwritingExistingFiles
  47043. && content->chooserComponent.isSaveMode()
  47044. && content->chooserComponent.getSelectedFile(0).exists()))
  47045. || AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47046. TRANS("File already exists"),
  47047. TRANS("There's already a file called:")
  47048. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47049. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47050. TRANS("overwrite"),
  47051. TRANS("cancel")))
  47052. {
  47053. exitModalState (1);
  47054. }
  47055. }
  47056. void FileChooserDialogBox::createNewFolder()
  47057. {
  47058. File parent (content->chooserComponent.getRoot());
  47059. if (parent.isDirectory())
  47060. {
  47061. AlertWindow aw (TRANS("New Folder"),
  47062. TRANS("Please enter the name for the folder"),
  47063. AlertWindow::NoIcon, this);
  47064. aw.addTextEditor ("name", String::empty, String::empty, false);
  47065. aw.addButton (TRANS("ok"), 1, KeyPress::returnKey);
  47066. aw.addButton (TRANS("cancel"), KeyPress::escapeKey);
  47067. if (aw.runModalLoop() != 0)
  47068. {
  47069. aw.setVisible (false);
  47070. const String name (File::createLegalFileName (aw.getTextEditorContents ("name")));
  47071. if (! name.isEmpty())
  47072. {
  47073. if (! parent.getChildFile (name).createDirectory())
  47074. {
  47075. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  47076. TRANS ("New Folder"),
  47077. TRANS ("Couldn't create the folder!"));
  47078. }
  47079. content->chooserComponent.refresh();
  47080. }
  47081. }
  47082. }
  47083. }
  47084. FileChooserDialogBox::ContentComponent::ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47085. : Component (name), instructions (instructions_),
  47086. chooserComponent (chooserComponent_),
  47087. okButton (chooserComponent_.getActionVerb()),
  47088. cancelButton (TRANS ("Cancel")),
  47089. newFolderButton (TRANS ("New Folder"))
  47090. {
  47091. addAndMakeVisible (&chooserComponent);
  47092. addAndMakeVisible (&okButton);
  47093. okButton.addShortcut (KeyPress::returnKey);
  47094. addAndMakeVisible (&cancelButton);
  47095. cancelButton.addShortcut (KeyPress::escapeKey);
  47096. addChildComponent (&newFolderButton);
  47097. setInterceptsMouseClicks (false, true);
  47098. }
  47099. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  47100. {
  47101. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47102. text.draw (g);
  47103. }
  47104. void FileChooserDialogBox::ContentComponent::resized()
  47105. {
  47106. const int buttonHeight = 26;
  47107. Rectangle<int> area (getLocalBounds());
  47108. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47109. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47110. area.removeFromTop (roundToInt (bb.getBottom()) + 10);
  47111. chooserComponent.setBounds (area.removeFromTop (area.getHeight() - buttonHeight - 20));
  47112. Rectangle<int> buttonArea (area.reduced (16, 10));
  47113. okButton.changeWidthToFitText (buttonHeight);
  47114. okButton.setBounds (buttonArea.removeFromRight (okButton.getWidth() + 16));
  47115. buttonArea.removeFromRight (16);
  47116. cancelButton.changeWidthToFitText (buttonHeight);
  47117. cancelButton.setBounds (buttonArea.removeFromRight (cancelButton.getWidth()));
  47118. newFolderButton.changeWidthToFitText (buttonHeight);
  47119. newFolderButton.setBounds (buttonArea.removeFromLeft (newFolderButton.getWidth()));
  47120. }
  47121. END_JUCE_NAMESPACE
  47122. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47123. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47124. BEGIN_JUCE_NAMESPACE
  47125. FileFilter::FileFilter (const String& filterDescription)
  47126. : description (filterDescription)
  47127. {
  47128. }
  47129. FileFilter::~FileFilter()
  47130. {
  47131. }
  47132. const String& FileFilter::getDescription() const throw()
  47133. {
  47134. return description;
  47135. }
  47136. END_JUCE_NAMESPACE
  47137. /*** End of inlined file: juce_FileFilter.cpp ***/
  47138. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47139. BEGIN_JUCE_NAMESPACE
  47140. const Image juce_createIconForFile (const File& file);
  47141. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47142. : ListBox (String::empty, 0),
  47143. DirectoryContentsDisplayComponent (listToShow)
  47144. {
  47145. setModel (this);
  47146. fileList.addChangeListener (this);
  47147. }
  47148. FileListComponent::~FileListComponent()
  47149. {
  47150. fileList.removeChangeListener (this);
  47151. }
  47152. int FileListComponent::getNumSelectedFiles() const
  47153. {
  47154. return getNumSelectedRows();
  47155. }
  47156. const File FileListComponent::getSelectedFile (int index) const
  47157. {
  47158. return fileList.getFile (getSelectedRow (index));
  47159. }
  47160. void FileListComponent::deselectAllFiles()
  47161. {
  47162. deselectAllRows();
  47163. }
  47164. void FileListComponent::scrollToTop()
  47165. {
  47166. getVerticalScrollBar()->setCurrentRangeStart (0);
  47167. }
  47168. void FileListComponent::changeListenerCallback (ChangeBroadcaster*)
  47169. {
  47170. updateContent();
  47171. if (lastDirectory != fileList.getDirectory())
  47172. {
  47173. lastDirectory = fileList.getDirectory();
  47174. deselectAllRows();
  47175. }
  47176. }
  47177. class FileListItemComponent : public Component,
  47178. public TimeSliceClient,
  47179. public AsyncUpdater
  47180. {
  47181. public:
  47182. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47183. : owner (owner_), thread (thread_), index (0), highlighted (false)
  47184. {
  47185. }
  47186. ~FileListItemComponent()
  47187. {
  47188. thread.removeTimeSliceClient (this);
  47189. }
  47190. void paint (Graphics& g)
  47191. {
  47192. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47193. file.getFileName(),
  47194. &icon, fileSize, modTime,
  47195. isDirectory, highlighted,
  47196. index, owner);
  47197. }
  47198. void mouseDown (const MouseEvent& e)
  47199. {
  47200. owner.selectRowsBasedOnModifierKeys (index, e.mods, false);
  47201. owner.sendMouseClickMessage (file, e);
  47202. }
  47203. void mouseDoubleClick (const MouseEvent&)
  47204. {
  47205. owner.sendDoubleClickMessage (file);
  47206. }
  47207. void update (const File& root,
  47208. const DirectoryContentsList::FileInfo* const fileInfo,
  47209. const int index_,
  47210. const bool highlighted_)
  47211. {
  47212. thread.removeTimeSliceClient (this);
  47213. if (highlighted_ != highlighted || index_ != index)
  47214. {
  47215. index = index_;
  47216. highlighted = highlighted_;
  47217. repaint();
  47218. }
  47219. File newFile;
  47220. String newFileSize, newModTime;
  47221. if (fileInfo != 0)
  47222. {
  47223. newFile = root.getChildFile (fileInfo->filename);
  47224. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47225. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47226. }
  47227. if (newFile != file
  47228. || fileSize != newFileSize
  47229. || modTime != newModTime)
  47230. {
  47231. file = newFile;
  47232. fileSize = newFileSize;
  47233. modTime = newModTime;
  47234. icon = Image::null;
  47235. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47236. repaint();
  47237. }
  47238. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47239. {
  47240. updateIcon (true);
  47241. if (! icon.isValid())
  47242. thread.addTimeSliceClient (this);
  47243. }
  47244. }
  47245. int useTimeSlice()
  47246. {
  47247. updateIcon (false);
  47248. return -1;
  47249. }
  47250. void handleAsyncUpdate()
  47251. {
  47252. repaint();
  47253. }
  47254. private:
  47255. FileListComponent& owner;
  47256. TimeSliceThread& thread;
  47257. File file;
  47258. String fileSize, modTime;
  47259. Image icon;
  47260. int index;
  47261. bool highlighted, isDirectory;
  47262. void updateIcon (const bool onlyUpdateIfCached)
  47263. {
  47264. if (icon.isNull())
  47265. {
  47266. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47267. Image im (ImageCache::getFromHashCode (hashCode));
  47268. if (im.isNull() && ! onlyUpdateIfCached)
  47269. {
  47270. im = juce_createIconForFile (file);
  47271. if (im.isValid())
  47272. ImageCache::addImageToCache (im, hashCode);
  47273. }
  47274. if (im.isValid())
  47275. {
  47276. icon = im;
  47277. triggerAsyncUpdate();
  47278. }
  47279. }
  47280. }
  47281. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListItemComponent);
  47282. };
  47283. int FileListComponent::getNumRows()
  47284. {
  47285. return fileList.getNumFiles();
  47286. }
  47287. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47288. {
  47289. }
  47290. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47291. {
  47292. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47293. if (comp == 0)
  47294. {
  47295. delete existingComponentToUpdate;
  47296. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47297. }
  47298. DirectoryContentsList::FileInfo fileInfo;
  47299. if (fileList.getFileInfo (row, fileInfo))
  47300. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47301. else
  47302. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47303. return comp;
  47304. }
  47305. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47306. {
  47307. sendSelectionChangeMessage();
  47308. }
  47309. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47310. {
  47311. }
  47312. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47313. {
  47314. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47315. }
  47316. END_JUCE_NAMESPACE
  47317. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47318. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47319. BEGIN_JUCE_NAMESPACE
  47320. FilenameComponent::FilenameComponent (const String& name,
  47321. const File& currentFile,
  47322. const bool canEditFilename,
  47323. const bool isDirectory,
  47324. const bool isForSaving,
  47325. const String& fileBrowserWildcard,
  47326. const String& enforcedSuffix_,
  47327. const String& textWhenNothingSelected)
  47328. : Component (name),
  47329. maxRecentFiles (30),
  47330. isDir (isDirectory),
  47331. isSaving (isForSaving),
  47332. isFileDragOver (false),
  47333. wildcard (fileBrowserWildcard),
  47334. enforcedSuffix (enforcedSuffix_)
  47335. {
  47336. addAndMakeVisible (&filenameBox);
  47337. filenameBox.setEditableText (canEditFilename);
  47338. filenameBox.addListener (this);
  47339. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47340. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47341. setBrowseButtonText ("...");
  47342. setCurrentFile (currentFile, true);
  47343. }
  47344. FilenameComponent::~FilenameComponent()
  47345. {
  47346. }
  47347. void FilenameComponent::paintOverChildren (Graphics& g)
  47348. {
  47349. if (isFileDragOver)
  47350. {
  47351. g.setColour (Colours::red.withAlpha (0.2f));
  47352. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47353. }
  47354. }
  47355. void FilenameComponent::resized()
  47356. {
  47357. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47358. }
  47359. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47360. {
  47361. browseButtonText = newBrowseButtonText;
  47362. lookAndFeelChanged();
  47363. }
  47364. void FilenameComponent::lookAndFeelChanged()
  47365. {
  47366. browseButton = 0;
  47367. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47368. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47369. resized();
  47370. browseButton->addListener (this);
  47371. }
  47372. void FilenameComponent::setTooltip (const String& newTooltip)
  47373. {
  47374. SettableTooltipClient::setTooltip (newTooltip);
  47375. filenameBox.setTooltip (newTooltip);
  47376. }
  47377. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47378. {
  47379. defaultBrowseFile = newDefaultDirectory;
  47380. }
  47381. void FilenameComponent::buttonClicked (Button*)
  47382. {
  47383. FileChooser fc (TRANS("Choose a new file"),
  47384. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47385. : getCurrentFile(),
  47386. wildcard);
  47387. if (isDir ? fc.browseForDirectory()
  47388. : (isSaving ? fc.browseForFileToSave (false)
  47389. : fc.browseForFileToOpen()))
  47390. {
  47391. setCurrentFile (fc.getResult(), true);
  47392. }
  47393. }
  47394. void FilenameComponent::comboBoxChanged (ComboBox*)
  47395. {
  47396. setCurrentFile (getCurrentFile(), true);
  47397. }
  47398. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47399. {
  47400. return true;
  47401. }
  47402. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47403. {
  47404. isFileDragOver = false;
  47405. repaint();
  47406. const File f (filenames[0]);
  47407. if (f.exists() && (f.isDirectory() == isDir))
  47408. setCurrentFile (f, true);
  47409. }
  47410. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47411. {
  47412. isFileDragOver = true;
  47413. repaint();
  47414. }
  47415. void FilenameComponent::fileDragExit (const StringArray&)
  47416. {
  47417. isFileDragOver = false;
  47418. repaint();
  47419. }
  47420. const File FilenameComponent::getCurrentFile() const
  47421. {
  47422. File f (filenameBox.getText());
  47423. if (enforcedSuffix.isNotEmpty())
  47424. f = f.withFileExtension (enforcedSuffix);
  47425. return f;
  47426. }
  47427. void FilenameComponent::setCurrentFile (File newFile,
  47428. const bool addToRecentlyUsedList,
  47429. const bool sendChangeNotification)
  47430. {
  47431. if (enforcedSuffix.isNotEmpty())
  47432. newFile = newFile.withFileExtension (enforcedSuffix);
  47433. if (newFile.getFullPathName() != lastFilename)
  47434. {
  47435. lastFilename = newFile.getFullPathName();
  47436. if (addToRecentlyUsedList)
  47437. addRecentlyUsedFile (newFile);
  47438. filenameBox.setText (lastFilename, true);
  47439. if (sendChangeNotification)
  47440. triggerAsyncUpdate();
  47441. }
  47442. }
  47443. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47444. {
  47445. filenameBox.setEditableText (shouldBeEditable);
  47446. }
  47447. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47448. {
  47449. StringArray names;
  47450. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47451. names.add (filenameBox.getItemText (i));
  47452. return names;
  47453. }
  47454. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47455. {
  47456. if (filenames != getRecentlyUsedFilenames())
  47457. {
  47458. filenameBox.clear();
  47459. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47460. filenameBox.addItem (filenames[i], i + 1);
  47461. }
  47462. }
  47463. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47464. {
  47465. maxRecentFiles = jmax (1, newMaximum);
  47466. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47467. }
  47468. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47469. {
  47470. StringArray files (getRecentlyUsedFilenames());
  47471. if (file.getFullPathName().isNotEmpty())
  47472. {
  47473. files.removeString (file.getFullPathName(), true);
  47474. files.insert (0, file.getFullPathName());
  47475. setRecentlyUsedFilenames (files);
  47476. }
  47477. }
  47478. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47479. {
  47480. listeners.add (listener);
  47481. }
  47482. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47483. {
  47484. listeners.remove (listener);
  47485. }
  47486. void FilenameComponent::handleAsyncUpdate()
  47487. {
  47488. Component::BailOutChecker checker (this);
  47489. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47490. }
  47491. END_JUCE_NAMESPACE
  47492. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47493. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47494. BEGIN_JUCE_NAMESPACE
  47495. FileSearchPathListComponent::FileSearchPathListComponent()
  47496. : addButton ("+"),
  47497. removeButton ("-"),
  47498. changeButton (TRANS ("change...")),
  47499. upButton (String::empty, DrawableButton::ImageOnButtonBackground),
  47500. downButton (String::empty, DrawableButton::ImageOnButtonBackground)
  47501. {
  47502. listBox.setModel (this);
  47503. addAndMakeVisible (&listBox);
  47504. listBox.setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47505. listBox.setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47506. listBox.setOutlineThickness (1);
  47507. addAndMakeVisible (&addButton);
  47508. addButton.addListener (this);
  47509. addButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47510. addAndMakeVisible (&removeButton);
  47511. removeButton.addListener (this);
  47512. removeButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47513. addAndMakeVisible (&changeButton);
  47514. changeButton.addListener (this);
  47515. addAndMakeVisible (&upButton);
  47516. upButton.addListener (this);
  47517. {
  47518. Path arrowPath;
  47519. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47520. DrawablePath arrowImage;
  47521. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47522. arrowImage.setPath (arrowPath);
  47523. upButton.setImages (&arrowImage);
  47524. }
  47525. addAndMakeVisible (&downButton);
  47526. downButton.addListener (this);
  47527. {
  47528. Path arrowPath;
  47529. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47530. DrawablePath arrowImage;
  47531. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47532. arrowImage.setPath (arrowPath);
  47533. downButton.setImages (&arrowImage);
  47534. }
  47535. updateButtons();
  47536. }
  47537. FileSearchPathListComponent::~FileSearchPathListComponent()
  47538. {
  47539. }
  47540. void FileSearchPathListComponent::updateButtons()
  47541. {
  47542. const bool anythingSelected = listBox.getNumSelectedRows() > 0;
  47543. removeButton.setEnabled (anythingSelected);
  47544. changeButton.setEnabled (anythingSelected);
  47545. upButton.setEnabled (anythingSelected);
  47546. downButton.setEnabled (anythingSelected);
  47547. }
  47548. void FileSearchPathListComponent::changed()
  47549. {
  47550. listBox.updateContent();
  47551. listBox.repaint();
  47552. updateButtons();
  47553. }
  47554. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47555. {
  47556. if (newPath.toString() != path.toString())
  47557. {
  47558. path = newPath;
  47559. changed();
  47560. }
  47561. }
  47562. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47563. {
  47564. defaultBrowseTarget = newDefaultDirectory;
  47565. }
  47566. int FileSearchPathListComponent::getNumRows()
  47567. {
  47568. return path.getNumPaths();
  47569. }
  47570. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47571. {
  47572. if (rowIsSelected)
  47573. g.fillAll (findColour (TextEditor::highlightColourId));
  47574. g.setColour (findColour (ListBox::textColourId));
  47575. Font f (height * 0.7f);
  47576. f.setHorizontalScale (0.9f);
  47577. g.setFont (f);
  47578. g.drawText (path [rowNumber].getFullPathName(),
  47579. 4, 0, width - 6, height,
  47580. Justification::centredLeft, true);
  47581. }
  47582. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47583. {
  47584. if (isPositiveAndBelow (row, path.getNumPaths()))
  47585. {
  47586. path.remove (row);
  47587. changed();
  47588. }
  47589. }
  47590. void FileSearchPathListComponent::returnKeyPressed (int row)
  47591. {
  47592. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47593. if (chooser.browseForDirectory())
  47594. {
  47595. path.remove (row);
  47596. path.add (chooser.getResult(), row);
  47597. changed();
  47598. }
  47599. }
  47600. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47601. {
  47602. returnKeyPressed (row);
  47603. }
  47604. void FileSearchPathListComponent::selectedRowsChanged (int)
  47605. {
  47606. updateButtons();
  47607. }
  47608. void FileSearchPathListComponent::paint (Graphics& g)
  47609. {
  47610. g.fillAll (findColour (backgroundColourId));
  47611. }
  47612. void FileSearchPathListComponent::resized()
  47613. {
  47614. const int buttonH = 22;
  47615. const int buttonY = getHeight() - buttonH - 4;
  47616. listBox.setBounds (2, 2, getWidth() - 4, buttonY - 5);
  47617. addButton.setBounds (2, buttonY, buttonH, buttonH);
  47618. removeButton.setBounds (addButton.getRight(), buttonY, buttonH, buttonH);
  47619. changeButton.changeWidthToFitText (buttonH);
  47620. downButton.setSize (buttonH * 2, buttonH);
  47621. upButton.setSize (buttonH * 2, buttonH);
  47622. downButton.setTopRightPosition (getWidth() - 2, buttonY);
  47623. upButton.setTopRightPosition (downButton.getX() - 4, buttonY);
  47624. changeButton.setTopRightPosition (upButton.getX() - 8, buttonY);
  47625. }
  47626. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47627. {
  47628. return true;
  47629. }
  47630. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47631. {
  47632. for (int i = filenames.size(); --i >= 0;)
  47633. {
  47634. const File f (filenames[i]);
  47635. if (f.isDirectory())
  47636. {
  47637. const int row = listBox.getRowContainingPosition (0, mouseY - listBox.getY());
  47638. path.add (f, row);
  47639. changed();
  47640. }
  47641. }
  47642. }
  47643. void FileSearchPathListComponent::buttonClicked (Button* button)
  47644. {
  47645. const int currentRow = listBox.getSelectedRow();
  47646. if (button == &removeButton)
  47647. {
  47648. deleteKeyPressed (currentRow);
  47649. }
  47650. else if (button == &addButton)
  47651. {
  47652. File start (defaultBrowseTarget);
  47653. if (start == File::nonexistent)
  47654. start = path [0];
  47655. if (start == File::nonexistent)
  47656. start = File::getCurrentWorkingDirectory();
  47657. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47658. if (chooser.browseForDirectory())
  47659. {
  47660. path.add (chooser.getResult(), currentRow);
  47661. }
  47662. }
  47663. else if (button == &changeButton)
  47664. {
  47665. returnKeyPressed (currentRow);
  47666. }
  47667. else if (button == &upButton)
  47668. {
  47669. if (currentRow > 0 && currentRow < path.getNumPaths())
  47670. {
  47671. const File f (path[currentRow]);
  47672. path.remove (currentRow);
  47673. path.add (f, currentRow - 1);
  47674. listBox.selectRow (currentRow - 1);
  47675. }
  47676. }
  47677. else if (button == &downButton)
  47678. {
  47679. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47680. {
  47681. const File f (path[currentRow]);
  47682. path.remove (currentRow);
  47683. path.add (f, currentRow + 1);
  47684. listBox.selectRow (currentRow + 1);
  47685. }
  47686. }
  47687. changed();
  47688. }
  47689. END_JUCE_NAMESPACE
  47690. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47691. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47692. BEGIN_JUCE_NAMESPACE
  47693. const Image juce_createIconForFile (const File& file);
  47694. class FileListTreeItem : public TreeViewItem,
  47695. public TimeSliceClient,
  47696. public AsyncUpdater,
  47697. public ChangeListener
  47698. {
  47699. public:
  47700. FileListTreeItem (FileTreeComponent& owner_,
  47701. DirectoryContentsList* const parentContentsList_,
  47702. const int indexInContentsList_,
  47703. const File& file_,
  47704. TimeSliceThread& thread_)
  47705. : file (file_),
  47706. owner (owner_),
  47707. parentContentsList (parentContentsList_),
  47708. indexInContentsList (indexInContentsList_),
  47709. subContentsList (0),
  47710. canDeleteSubContentsList (false),
  47711. thread (thread_),
  47712. icon (0)
  47713. {
  47714. DirectoryContentsList::FileInfo fileInfo;
  47715. if (parentContentsList_ != 0
  47716. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47717. {
  47718. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47719. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47720. isDirectory = fileInfo.isDirectory;
  47721. }
  47722. else
  47723. {
  47724. isDirectory = true;
  47725. }
  47726. }
  47727. ~FileListTreeItem()
  47728. {
  47729. thread.removeTimeSliceClient (this);
  47730. clearSubItems();
  47731. if (canDeleteSubContentsList)
  47732. delete subContentsList;
  47733. }
  47734. bool mightContainSubItems() { return isDirectory; }
  47735. const String getUniqueName() const { return file.getFullPathName(); }
  47736. int getItemHeight() const { return 22; }
  47737. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47738. void itemOpennessChanged (bool isNowOpen)
  47739. {
  47740. if (isNowOpen)
  47741. {
  47742. clearSubItems();
  47743. isDirectory = file.isDirectory();
  47744. if (isDirectory)
  47745. {
  47746. if (subContentsList == 0)
  47747. {
  47748. jassert (parentContentsList != 0);
  47749. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  47750. l->setDirectory (file, true, true);
  47751. setSubContentsList (l);
  47752. canDeleteSubContentsList = true;
  47753. }
  47754. changeListenerCallback (0);
  47755. }
  47756. }
  47757. }
  47758. void setSubContentsList (DirectoryContentsList* newList)
  47759. {
  47760. jassert (subContentsList == 0);
  47761. subContentsList = newList;
  47762. newList->addChangeListener (this);
  47763. }
  47764. void changeListenerCallback (ChangeBroadcaster*)
  47765. {
  47766. clearSubItems();
  47767. if (isOpen() && subContentsList != 0)
  47768. {
  47769. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  47770. {
  47771. FileListTreeItem* const item
  47772. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  47773. addSubItem (item);
  47774. }
  47775. }
  47776. }
  47777. void paintItem (Graphics& g, int width, int height)
  47778. {
  47779. if (file != File::nonexistent)
  47780. {
  47781. updateIcon (true);
  47782. if (icon.isNull())
  47783. thread.addTimeSliceClient (this);
  47784. }
  47785. owner.getLookAndFeel()
  47786. .drawFileBrowserRow (g, width, height,
  47787. file.getFileName(),
  47788. &icon, fileSize, modTime,
  47789. isDirectory, isSelected(),
  47790. indexInContentsList, owner);
  47791. }
  47792. void itemClicked (const MouseEvent& e)
  47793. {
  47794. owner.sendMouseClickMessage (file, e);
  47795. }
  47796. void itemDoubleClicked (const MouseEvent& e)
  47797. {
  47798. TreeViewItem::itemDoubleClicked (e);
  47799. owner.sendDoubleClickMessage (file);
  47800. }
  47801. void itemSelectionChanged (bool)
  47802. {
  47803. owner.sendSelectionChangeMessage();
  47804. }
  47805. int useTimeSlice()
  47806. {
  47807. updateIcon (false);
  47808. return -1;
  47809. }
  47810. void handleAsyncUpdate()
  47811. {
  47812. owner.repaint();
  47813. }
  47814. const File file;
  47815. private:
  47816. FileTreeComponent& owner;
  47817. DirectoryContentsList* parentContentsList;
  47818. int indexInContentsList;
  47819. DirectoryContentsList* subContentsList;
  47820. bool isDirectory, canDeleteSubContentsList;
  47821. TimeSliceThread& thread;
  47822. Image icon;
  47823. String fileSize;
  47824. String modTime;
  47825. void updateIcon (const bool onlyUpdateIfCached)
  47826. {
  47827. if (icon.isNull())
  47828. {
  47829. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47830. Image im (ImageCache::getFromHashCode (hashCode));
  47831. if (im.isNull() && ! onlyUpdateIfCached)
  47832. {
  47833. im = juce_createIconForFile (file);
  47834. if (im.isValid())
  47835. ImageCache::addImageToCache (im, hashCode);
  47836. }
  47837. if (im.isValid())
  47838. {
  47839. icon = im;
  47840. triggerAsyncUpdate();
  47841. }
  47842. }
  47843. }
  47844. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListTreeItem);
  47845. };
  47846. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  47847. : DirectoryContentsDisplayComponent (listToShow)
  47848. {
  47849. FileListTreeItem* const root
  47850. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  47851. listToShow.getTimeSliceThread());
  47852. root->setSubContentsList (&listToShow);
  47853. setRootItemVisible (false);
  47854. setRootItem (root);
  47855. }
  47856. FileTreeComponent::~FileTreeComponent()
  47857. {
  47858. deleteRootItem();
  47859. }
  47860. const File FileTreeComponent::getSelectedFile (const int index) const
  47861. {
  47862. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  47863. return item != 0 ? item->file
  47864. : File::nonexistent;
  47865. }
  47866. void FileTreeComponent::deselectAllFiles()
  47867. {
  47868. clearSelectedItems();
  47869. }
  47870. void FileTreeComponent::scrollToTop()
  47871. {
  47872. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  47873. }
  47874. void FileTreeComponent::setDragAndDropDescription (const String& description)
  47875. {
  47876. dragAndDropDescription = description;
  47877. }
  47878. END_JUCE_NAMESPACE
  47879. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  47880. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  47881. BEGIN_JUCE_NAMESPACE
  47882. ImagePreviewComponent::ImagePreviewComponent()
  47883. {
  47884. }
  47885. ImagePreviewComponent::~ImagePreviewComponent()
  47886. {
  47887. }
  47888. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  47889. {
  47890. const int availableW = proportionOfWidth (0.97f);
  47891. const int availableH = getHeight() - 13 * 4;
  47892. const double scale = jmin (1.0,
  47893. availableW / (double) w,
  47894. availableH / (double) h);
  47895. w = roundToInt (scale * w);
  47896. h = roundToInt (scale * h);
  47897. }
  47898. void ImagePreviewComponent::selectedFileChanged (const File& file)
  47899. {
  47900. if (fileToLoad != file)
  47901. {
  47902. fileToLoad = file;
  47903. startTimer (100);
  47904. }
  47905. }
  47906. void ImagePreviewComponent::timerCallback()
  47907. {
  47908. stopTimer();
  47909. currentThumbnail = Image::null;
  47910. currentDetails = String::empty;
  47911. repaint();
  47912. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  47913. if (in != 0)
  47914. {
  47915. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  47916. if (format != 0)
  47917. {
  47918. currentThumbnail = format->decodeImage (*in);
  47919. if (currentThumbnail.isValid())
  47920. {
  47921. int w = currentThumbnail.getWidth();
  47922. int h = currentThumbnail.getHeight();
  47923. currentDetails
  47924. << fileToLoad.getFileName() << "\n"
  47925. << format->getFormatName() << "\n"
  47926. << w << " x " << h << " pixels\n"
  47927. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  47928. getThumbSize (w, h);
  47929. currentThumbnail = currentThumbnail.rescaled (w, h);
  47930. }
  47931. }
  47932. }
  47933. }
  47934. void ImagePreviewComponent::paint (Graphics& g)
  47935. {
  47936. if (currentThumbnail.isValid())
  47937. {
  47938. g.setFont (13.0f);
  47939. int w = currentThumbnail.getWidth();
  47940. int h = currentThumbnail.getHeight();
  47941. getThumbSize (w, h);
  47942. const int numLines = 4;
  47943. const int totalH = 13 * numLines + h + 4;
  47944. const int y = (getHeight() - totalH) / 2;
  47945. g.drawImageWithin (currentThumbnail,
  47946. (getWidth() - w) / 2, y, w, h,
  47947. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  47948. false);
  47949. g.drawFittedText (currentDetails,
  47950. 0, y + h + 4, getWidth(), 100,
  47951. Justification::centredTop, numLines);
  47952. }
  47953. }
  47954. END_JUCE_NAMESPACE
  47955. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  47956. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  47957. BEGIN_JUCE_NAMESPACE
  47958. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  47959. const String& directoryWildcardPatterns,
  47960. const String& description_)
  47961. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  47962. : (description_ + " (" + fileWildcardPatterns + ")"))
  47963. {
  47964. parse (fileWildcardPatterns, fileWildcards);
  47965. parse (directoryWildcardPatterns, directoryWildcards);
  47966. }
  47967. WildcardFileFilter::~WildcardFileFilter()
  47968. {
  47969. }
  47970. bool WildcardFileFilter::isFileSuitable (const File& file) const
  47971. {
  47972. return match (file, fileWildcards);
  47973. }
  47974. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  47975. {
  47976. return match (file, directoryWildcards);
  47977. }
  47978. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  47979. {
  47980. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  47981. result.trim();
  47982. result.removeEmptyStrings();
  47983. // special case for *.*, because people use it to mean "any file", but it
  47984. // would actually ignore files with no extension.
  47985. for (int i = result.size(); --i >= 0;)
  47986. if (result[i] == "*.*")
  47987. result.set (i, "*");
  47988. }
  47989. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  47990. {
  47991. const String filename (file.getFileName());
  47992. for (int i = wildcards.size(); --i >= 0;)
  47993. if (filename.matchesWildcard (wildcards[i], true))
  47994. return true;
  47995. return false;
  47996. }
  47997. END_JUCE_NAMESPACE
  47998. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  47999. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48000. BEGIN_JUCE_NAMESPACE
  48001. KeyboardFocusTraverser::KeyboardFocusTraverser()
  48002. {
  48003. }
  48004. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  48005. {
  48006. }
  48007. namespace KeyboardFocusHelpers
  48008. {
  48009. // This will sort a set of components, so that they are ordered in terms of
  48010. // left-to-right and then top-to-bottom.
  48011. class ScreenPositionComparator
  48012. {
  48013. public:
  48014. ScreenPositionComparator() {}
  48015. static int compareElements (const Component* const first, const Component* const second)
  48016. {
  48017. int explicitOrder1 = first->getExplicitFocusOrder();
  48018. if (explicitOrder1 <= 0)
  48019. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48020. int explicitOrder2 = second->getExplicitFocusOrder();
  48021. if (explicitOrder2 <= 0)
  48022. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48023. if (explicitOrder1 != explicitOrder2)
  48024. return explicitOrder1 - explicitOrder2;
  48025. const int diff = first->getY() - second->getY();
  48026. return (diff == 0) ? first->getX() - second->getX()
  48027. : diff;
  48028. }
  48029. };
  48030. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48031. {
  48032. if (parent->getNumChildComponents() > 0)
  48033. {
  48034. Array <Component*> localComps;
  48035. ScreenPositionComparator comparator;
  48036. int i;
  48037. for (i = parent->getNumChildComponents(); --i >= 0;)
  48038. {
  48039. Component* const c = parent->getChildComponent (i);
  48040. if (c->isVisible() && c->isEnabled())
  48041. localComps.addSorted (comparator, c);
  48042. }
  48043. for (i = 0; i < localComps.size(); ++i)
  48044. {
  48045. Component* const c = localComps.getUnchecked (i);
  48046. if (c->getWantsKeyboardFocus())
  48047. comps.add (c);
  48048. if (! c->isFocusContainer())
  48049. findAllFocusableComponents (c, comps);
  48050. }
  48051. }
  48052. }
  48053. }
  48054. namespace KeyboardFocusHelpers
  48055. {
  48056. Component* getIncrementedComponent (Component* const current, const int delta)
  48057. {
  48058. Component* focusContainer = current->getParentComponent();
  48059. if (focusContainer != 0)
  48060. {
  48061. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48062. focusContainer = focusContainer->getParentComponent();
  48063. if (focusContainer != 0)
  48064. {
  48065. Array <Component*> comps;
  48066. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48067. if (comps.size() > 0)
  48068. {
  48069. const int index = comps.indexOf (current);
  48070. return comps [(index + comps.size() + delta) % comps.size()];
  48071. }
  48072. }
  48073. }
  48074. return 0;
  48075. }
  48076. }
  48077. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48078. {
  48079. return KeyboardFocusHelpers::getIncrementedComponent (current, 1);
  48080. }
  48081. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48082. {
  48083. return KeyboardFocusHelpers::getIncrementedComponent (current, -1);
  48084. }
  48085. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48086. {
  48087. Array <Component*> comps;
  48088. if (parentComponent != 0)
  48089. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48090. return comps.getFirst();
  48091. }
  48092. END_JUCE_NAMESPACE
  48093. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48094. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48095. BEGIN_JUCE_NAMESPACE
  48096. bool KeyListener::keyStateChanged (const bool, Component*)
  48097. {
  48098. return false;
  48099. }
  48100. END_JUCE_NAMESPACE
  48101. /*** End of inlined file: juce_KeyListener.cpp ***/
  48102. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48103. BEGIN_JUCE_NAMESPACE
  48104. // N.B. these two includes are put here deliberately to avoid problems with
  48105. // old GCCs failing on long include paths
  48106. class KeyMappingEditorComponent::ChangeKeyButton : public Button
  48107. {
  48108. public:
  48109. ChangeKeyButton (KeyMappingEditorComponent& owner_,
  48110. const CommandID commandID_,
  48111. const String& keyName,
  48112. const int keyNum_)
  48113. : Button (keyName),
  48114. owner (owner_),
  48115. commandID (commandID_),
  48116. keyNum (keyNum_)
  48117. {
  48118. setWantsKeyboardFocus (false);
  48119. setTriggeredOnMouseDown (keyNum >= 0);
  48120. setTooltip (keyNum_ < 0 ? TRANS("adds a new key-mapping")
  48121. : TRANS("click to change this key-mapping"));
  48122. }
  48123. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48124. {
  48125. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48126. keyNum >= 0 ? getName() : String::empty);
  48127. }
  48128. void clicked()
  48129. {
  48130. if (keyNum >= 0)
  48131. {
  48132. // existing key clicked..
  48133. PopupMenu m;
  48134. m.addItem (1, TRANS("change this key-mapping"));
  48135. m.addSeparator();
  48136. m.addItem (2, TRANS("remove this key-mapping"));
  48137. switch (m.show())
  48138. {
  48139. case 1: assignNewKey(); break;
  48140. case 2: owner.getMappings().removeKeyPress (commandID, keyNum); break;
  48141. default: break;
  48142. }
  48143. }
  48144. else
  48145. {
  48146. assignNewKey(); // + button pressed..
  48147. }
  48148. }
  48149. void fitToContent (const int h) throw()
  48150. {
  48151. if (keyNum < 0)
  48152. {
  48153. setSize (h, h);
  48154. }
  48155. else
  48156. {
  48157. Font f (h * 0.6f);
  48158. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48159. }
  48160. }
  48161. class KeyEntryWindow : public AlertWindow
  48162. {
  48163. public:
  48164. KeyEntryWindow (KeyMappingEditorComponent& owner_)
  48165. : AlertWindow (TRANS("New key-mapping"),
  48166. TRANS("Please press a key combination now..."),
  48167. AlertWindow::NoIcon),
  48168. owner (owner_)
  48169. {
  48170. addButton (TRANS("Ok"), 1);
  48171. addButton (TRANS("Cancel"), 0);
  48172. // (avoid return + escape keys getting processed by the buttons..)
  48173. for (int i = getNumChildComponents(); --i >= 0;)
  48174. getChildComponent (i)->setWantsKeyboardFocus (false);
  48175. setWantsKeyboardFocus (true);
  48176. grabKeyboardFocus();
  48177. }
  48178. bool keyPressed (const KeyPress& key)
  48179. {
  48180. lastPress = key;
  48181. String message (TRANS("Key: ") + owner.getDescriptionForKeyPress (key));
  48182. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (key);
  48183. if (previousCommand != 0)
  48184. message << "\n\n" << TRANS("(Currently assigned to \"")
  48185. << owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand) << "\")";
  48186. setMessage (message);
  48187. return true;
  48188. }
  48189. bool keyStateChanged (bool)
  48190. {
  48191. return true;
  48192. }
  48193. KeyPress lastPress;
  48194. private:
  48195. KeyMappingEditorComponent& owner;
  48196. JUCE_DECLARE_NON_COPYABLE (KeyEntryWindow);
  48197. };
  48198. void assignNewKey()
  48199. {
  48200. KeyEntryWindow entryWindow (owner);
  48201. if (entryWindow.runModalLoop() != 0)
  48202. {
  48203. entryWindow.setVisible (false);
  48204. if (entryWindow.lastPress.isValid())
  48205. {
  48206. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (entryWindow.lastPress);
  48207. if (previousCommand == 0
  48208. || AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48209. TRANS("Change key-mapping"),
  48210. TRANS("This key is already assigned to the command \"")
  48211. + owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand)
  48212. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48213. TRANS("Re-assign"),
  48214. TRANS("Cancel")))
  48215. {
  48216. owner.getMappings().removeKeyPress (entryWindow.lastPress);
  48217. if (keyNum >= 0)
  48218. owner.getMappings().removeKeyPress (commandID, keyNum);
  48219. owner.getMappings().addKeyPress (commandID, entryWindow.lastPress, keyNum);
  48220. }
  48221. }
  48222. }
  48223. }
  48224. private:
  48225. KeyMappingEditorComponent& owner;
  48226. const CommandID commandID;
  48227. const int keyNum;
  48228. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChangeKeyButton);
  48229. };
  48230. class KeyMappingEditorComponent::ItemComponent : public Component
  48231. {
  48232. public:
  48233. ItemComponent (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48234. : owner (owner_), commandID (commandID_)
  48235. {
  48236. setInterceptsMouseClicks (false, true);
  48237. const bool isReadOnly = owner.isCommandReadOnly (commandID);
  48238. const Array <KeyPress> keyPresses (owner.getMappings().getKeyPressesAssignedToCommand (commandID));
  48239. for (int i = 0; i < jmin ((int) maxNumAssignments, keyPresses.size()); ++i)
  48240. addKeyPressButton (owner.getDescriptionForKeyPress (keyPresses.getReference (i)), i, isReadOnly);
  48241. addKeyPressButton (String::empty, -1, isReadOnly);
  48242. }
  48243. void addKeyPressButton (const String& desc, const int index, const bool isReadOnly)
  48244. {
  48245. ChangeKeyButton* const b = new ChangeKeyButton (owner, commandID, desc, index);
  48246. keyChangeButtons.add (b);
  48247. b->setEnabled (! isReadOnly);
  48248. b->setVisible (keyChangeButtons.size() <= (int) maxNumAssignments);
  48249. addChildComponent (b);
  48250. }
  48251. void paint (Graphics& g)
  48252. {
  48253. g.setFont (getHeight() * 0.7f);
  48254. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48255. g.drawFittedText (owner.getMappings().getCommandManager()->getNameOfCommand (commandID),
  48256. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48257. Justification::centredLeft, true);
  48258. }
  48259. void resized()
  48260. {
  48261. int x = getWidth() - 4;
  48262. for (int i = keyChangeButtons.size(); --i >= 0;)
  48263. {
  48264. ChangeKeyButton* const b = keyChangeButtons.getUnchecked(i);
  48265. b->fitToContent (getHeight() - 2);
  48266. b->setTopRightPosition (x, 1);
  48267. x = b->getX() - 5;
  48268. }
  48269. }
  48270. private:
  48271. KeyMappingEditorComponent& owner;
  48272. OwnedArray<ChangeKeyButton> keyChangeButtons;
  48273. const CommandID commandID;
  48274. enum { maxNumAssignments = 3 };
  48275. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  48276. };
  48277. class KeyMappingEditorComponent::MappingItem : public TreeViewItem
  48278. {
  48279. public:
  48280. MappingItem (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48281. : owner (owner_), commandID (commandID_)
  48282. {
  48283. }
  48284. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48285. bool mightContainSubItems() { return false; }
  48286. int getItemHeight() const { return 20; }
  48287. Component* createItemComponent()
  48288. {
  48289. return new ItemComponent (owner, commandID);
  48290. }
  48291. private:
  48292. KeyMappingEditorComponent& owner;
  48293. const CommandID commandID;
  48294. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MappingItem);
  48295. };
  48296. class KeyMappingEditorComponent::CategoryItem : public TreeViewItem
  48297. {
  48298. public:
  48299. CategoryItem (KeyMappingEditorComponent& owner_, const String& name)
  48300. : owner (owner_), categoryName (name)
  48301. {
  48302. }
  48303. const String getUniqueName() const { return categoryName + "_cat"; }
  48304. bool mightContainSubItems() { return true; }
  48305. int getItemHeight() const { return 28; }
  48306. void paintItem (Graphics& g, int width, int height)
  48307. {
  48308. g.setFont (height * 0.6f, Font::bold);
  48309. g.setColour (owner.findColour (KeyMappingEditorComponent::textColourId));
  48310. g.drawText (categoryName,
  48311. 2, 0, width - 2, height,
  48312. Justification::centredLeft, true);
  48313. }
  48314. void itemOpennessChanged (bool isNowOpen)
  48315. {
  48316. if (isNowOpen)
  48317. {
  48318. if (getNumSubItems() == 0)
  48319. {
  48320. Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categoryName));
  48321. for (int i = 0; i < commands.size(); ++i)
  48322. {
  48323. if (owner.shouldCommandBeIncluded (commands[i]))
  48324. addSubItem (new MappingItem (owner, commands[i]));
  48325. }
  48326. }
  48327. }
  48328. else
  48329. {
  48330. clearSubItems();
  48331. }
  48332. }
  48333. private:
  48334. KeyMappingEditorComponent& owner;
  48335. String categoryName;
  48336. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CategoryItem);
  48337. };
  48338. class KeyMappingEditorComponent::TopLevelItem : public TreeViewItem,
  48339. public ChangeListener,
  48340. public ButtonListener
  48341. {
  48342. public:
  48343. TopLevelItem (KeyMappingEditorComponent& owner_)
  48344. : owner (owner_)
  48345. {
  48346. setLinesDrawnForSubItems (false);
  48347. owner.getMappings().addChangeListener (this);
  48348. }
  48349. ~TopLevelItem()
  48350. {
  48351. owner.getMappings().removeChangeListener (this);
  48352. }
  48353. bool mightContainSubItems() { return true; }
  48354. const String getUniqueName() const { return "keys"; }
  48355. void changeListenerCallback (ChangeBroadcaster*)
  48356. {
  48357. const OpennessRestorer openness (*this);
  48358. clearSubItems();
  48359. const StringArray categories (owner.getMappings().getCommandManager()->getCommandCategories());
  48360. for (int i = 0; i < categories.size(); ++i)
  48361. {
  48362. const Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categories[i]));
  48363. int count = 0;
  48364. for (int j = 0; j < commands.size(); ++j)
  48365. if (owner.shouldCommandBeIncluded (commands[j]))
  48366. ++count;
  48367. if (count > 0)
  48368. addSubItem (new CategoryItem (owner, categories[i]));
  48369. }
  48370. }
  48371. void buttonClicked (Button*)
  48372. {
  48373. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48374. TRANS("Reset to defaults"),
  48375. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48376. TRANS("Reset")))
  48377. {
  48378. owner.getMappings().resetToDefaultMappings();
  48379. }
  48380. }
  48381. private:
  48382. KeyMappingEditorComponent& owner;
  48383. };
  48384. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet& mappingManager,
  48385. const bool showResetToDefaultButton)
  48386. : mappings (mappingManager),
  48387. resetButton (TRANS ("reset to defaults"))
  48388. {
  48389. treeItem = new TopLevelItem (*this);
  48390. if (showResetToDefaultButton)
  48391. {
  48392. addAndMakeVisible (&resetButton);
  48393. resetButton.addListener (treeItem);
  48394. }
  48395. addAndMakeVisible (&tree);
  48396. tree.setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48397. tree.setRootItemVisible (false);
  48398. tree.setDefaultOpenness (true);
  48399. tree.setRootItem (treeItem);
  48400. }
  48401. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48402. {
  48403. tree.setRootItem (0);
  48404. }
  48405. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48406. const Colour& textColour)
  48407. {
  48408. setColour (backgroundColourId, mainBackground);
  48409. setColour (textColourId, textColour);
  48410. tree.setColour (TreeView::backgroundColourId, mainBackground);
  48411. }
  48412. void KeyMappingEditorComponent::parentHierarchyChanged()
  48413. {
  48414. treeItem->changeListenerCallback (0);
  48415. }
  48416. void KeyMappingEditorComponent::resized()
  48417. {
  48418. int h = getHeight();
  48419. if (resetButton.isVisible())
  48420. {
  48421. const int buttonHeight = 20;
  48422. h -= buttonHeight + 8;
  48423. int x = getWidth() - 8;
  48424. resetButton.changeWidthToFitText (buttonHeight);
  48425. resetButton.setTopRightPosition (x, h + 6);
  48426. }
  48427. tree.setBounds (0, 0, getWidth(), h);
  48428. }
  48429. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48430. {
  48431. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48432. return ci != 0 && (ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0;
  48433. }
  48434. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48435. {
  48436. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48437. return ci != 0 && (ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0;
  48438. }
  48439. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48440. {
  48441. return key.getTextDescription();
  48442. }
  48443. END_JUCE_NAMESPACE
  48444. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48445. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48446. BEGIN_JUCE_NAMESPACE
  48447. KeyPress::KeyPress() throw()
  48448. : keyCode (0),
  48449. mods (0),
  48450. textCharacter (0)
  48451. {
  48452. }
  48453. KeyPress::KeyPress (const int keyCode_,
  48454. const ModifierKeys& mods_,
  48455. const juce_wchar textCharacter_) throw()
  48456. : keyCode (keyCode_),
  48457. mods (mods_),
  48458. textCharacter (textCharacter_)
  48459. {
  48460. }
  48461. KeyPress::KeyPress (const int keyCode_) throw()
  48462. : keyCode (keyCode_),
  48463. textCharacter (0)
  48464. {
  48465. }
  48466. KeyPress::KeyPress (const KeyPress& other) throw()
  48467. : keyCode (other.keyCode),
  48468. mods (other.mods),
  48469. textCharacter (other.textCharacter)
  48470. {
  48471. }
  48472. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48473. {
  48474. keyCode = other.keyCode;
  48475. mods = other.mods;
  48476. textCharacter = other.textCharacter;
  48477. return *this;
  48478. }
  48479. bool KeyPress::operator== (const KeyPress& other) const throw()
  48480. {
  48481. return mods.getRawFlags() == other.mods.getRawFlags()
  48482. && (textCharacter == other.textCharacter
  48483. || textCharacter == 0
  48484. || other.textCharacter == 0)
  48485. && (keyCode == other.keyCode
  48486. || (keyCode < 256
  48487. && other.keyCode < 256
  48488. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48489. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48490. }
  48491. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48492. {
  48493. return ! operator== (other);
  48494. }
  48495. bool KeyPress::isCurrentlyDown() const
  48496. {
  48497. return isKeyCurrentlyDown (keyCode)
  48498. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48499. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48500. }
  48501. namespace KeyPressHelpers
  48502. {
  48503. struct KeyNameAndCode
  48504. {
  48505. const char* name;
  48506. int code;
  48507. };
  48508. const KeyNameAndCode translations[] =
  48509. {
  48510. { "spacebar", KeyPress::spaceKey },
  48511. { "return", KeyPress::returnKey },
  48512. { "escape", KeyPress::escapeKey },
  48513. { "backspace", KeyPress::backspaceKey },
  48514. { "cursor left", KeyPress::leftKey },
  48515. { "cursor right", KeyPress::rightKey },
  48516. { "cursor up", KeyPress::upKey },
  48517. { "cursor down", KeyPress::downKey },
  48518. { "page up", KeyPress::pageUpKey },
  48519. { "page down", KeyPress::pageDownKey },
  48520. { "home", KeyPress::homeKey },
  48521. { "end", KeyPress::endKey },
  48522. { "delete", KeyPress::deleteKey },
  48523. { "insert", KeyPress::insertKey },
  48524. { "tab", KeyPress::tabKey },
  48525. { "play", KeyPress::playKey },
  48526. { "stop", KeyPress::stopKey },
  48527. { "fast forward", KeyPress::fastForwardKey },
  48528. { "rewind", KeyPress::rewindKey }
  48529. };
  48530. const String numberPadPrefix() { return "numpad "; }
  48531. }
  48532. const KeyPress KeyPress::createFromDescription (const String& desc)
  48533. {
  48534. int modifiers = 0;
  48535. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48536. || desc.containsWholeWordIgnoreCase ("control")
  48537. || desc.containsWholeWordIgnoreCase ("ctl"))
  48538. modifiers |= ModifierKeys::ctrlModifier;
  48539. if (desc.containsWholeWordIgnoreCase ("shift")
  48540. || desc.containsWholeWordIgnoreCase ("shft"))
  48541. modifiers |= ModifierKeys::shiftModifier;
  48542. if (desc.containsWholeWordIgnoreCase ("alt")
  48543. || desc.containsWholeWordIgnoreCase ("option"))
  48544. modifiers |= ModifierKeys::altModifier;
  48545. if (desc.containsWholeWordIgnoreCase ("command")
  48546. || desc.containsWholeWordIgnoreCase ("cmd"))
  48547. modifiers |= ModifierKeys::commandModifier;
  48548. int key = 0;
  48549. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48550. {
  48551. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48552. {
  48553. key = KeyPressHelpers::translations[i].code;
  48554. break;
  48555. }
  48556. }
  48557. if (key == 0)
  48558. {
  48559. // see if it's a numpad key..
  48560. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48561. {
  48562. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48563. if (lastChar >= '0' && lastChar <= '9')
  48564. key = numberPad0 + lastChar - '0';
  48565. else if (lastChar == '+')
  48566. key = numberPadAdd;
  48567. else if (lastChar == '-')
  48568. key = numberPadSubtract;
  48569. else if (lastChar == '*')
  48570. key = numberPadMultiply;
  48571. else if (lastChar == '/')
  48572. key = numberPadDivide;
  48573. else if (lastChar == '.')
  48574. key = numberPadDecimalPoint;
  48575. else if (lastChar == '=')
  48576. key = numberPadEquals;
  48577. else if (desc.endsWith ("separator"))
  48578. key = numberPadSeparator;
  48579. else if (desc.endsWith ("delete"))
  48580. key = numberPadDelete;
  48581. }
  48582. if (key == 0)
  48583. {
  48584. // see if it's a function key..
  48585. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  48586. for (int i = 1; i <= 12; ++i)
  48587. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48588. key = F1Key + i - 1;
  48589. if (key == 0)
  48590. {
  48591. // give up and use the hex code..
  48592. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48593. .toLowerCase()
  48594. .retainCharacters ("0123456789abcdef")
  48595. .getHexValue32();
  48596. if (hexCode > 0)
  48597. key = hexCode;
  48598. else
  48599. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48600. }
  48601. }
  48602. }
  48603. return KeyPress (key, ModifierKeys (modifiers), 0);
  48604. }
  48605. const String KeyPress::getTextDescription() const
  48606. {
  48607. String desc;
  48608. if (keyCode > 0)
  48609. {
  48610. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48611. // want to store it as being a slash, not shift+whatever.
  48612. if (textCharacter == '/')
  48613. return "/";
  48614. if (mods.isCtrlDown())
  48615. desc << "ctrl + ";
  48616. if (mods.isShiftDown())
  48617. desc << "shift + ";
  48618. #if JUCE_MAC
  48619. // only do this on the mac, because on Windows ctrl and command are the same,
  48620. // and this would get confusing
  48621. if (mods.isCommandDown())
  48622. desc << "command + ";
  48623. if (mods.isAltDown())
  48624. desc << "option + ";
  48625. #else
  48626. if (mods.isAltDown())
  48627. desc << "alt + ";
  48628. #endif
  48629. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48630. if (keyCode == KeyPressHelpers::translations[i].code)
  48631. return desc + KeyPressHelpers::translations[i].name;
  48632. if (keyCode >= F1Key && keyCode <= F16Key)
  48633. desc << 'F' << (1 + keyCode - F1Key);
  48634. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48635. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48636. else if (keyCode >= 33 && keyCode < 176)
  48637. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48638. else if (keyCode == numberPadAdd)
  48639. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48640. else if (keyCode == numberPadSubtract)
  48641. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48642. else if (keyCode == numberPadMultiply)
  48643. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48644. else if (keyCode == numberPadDivide)
  48645. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48646. else if (keyCode == numberPadSeparator)
  48647. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48648. else if (keyCode == numberPadDecimalPoint)
  48649. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48650. else if (keyCode == numberPadDelete)
  48651. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48652. else
  48653. desc << '#' << String::toHexString (keyCode);
  48654. }
  48655. return desc;
  48656. }
  48657. END_JUCE_NAMESPACE
  48658. /*** End of inlined file: juce_KeyPress.cpp ***/
  48659. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48660. BEGIN_JUCE_NAMESPACE
  48661. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48662. : commandManager (commandManager_)
  48663. {
  48664. // A manager is needed to get the descriptions of commands, and will be called when
  48665. // a command is invoked. So you can't leave this null..
  48666. jassert (commandManager_ != 0);
  48667. Desktop::getInstance().addFocusChangeListener (this);
  48668. }
  48669. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48670. : commandManager (other.commandManager)
  48671. {
  48672. Desktop::getInstance().addFocusChangeListener (this);
  48673. }
  48674. KeyPressMappingSet::~KeyPressMappingSet()
  48675. {
  48676. Desktop::getInstance().removeFocusChangeListener (this);
  48677. }
  48678. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48679. {
  48680. for (int i = 0; i < mappings.size(); ++i)
  48681. if (mappings.getUnchecked(i)->commandID == commandID)
  48682. return mappings.getUnchecked (i)->keypresses;
  48683. return Array <KeyPress> ();
  48684. }
  48685. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48686. const KeyPress& newKeyPress,
  48687. int insertIndex)
  48688. {
  48689. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48690. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48691. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48692. && ! newKeyPress.getModifiers().isShiftDown()));
  48693. if (findCommandForKeyPress (newKeyPress) != commandID)
  48694. {
  48695. removeKeyPress (newKeyPress);
  48696. if (newKeyPress.isValid())
  48697. {
  48698. for (int i = mappings.size(); --i >= 0;)
  48699. {
  48700. if (mappings.getUnchecked(i)->commandID == commandID)
  48701. {
  48702. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48703. sendChangeMessage();
  48704. return;
  48705. }
  48706. }
  48707. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48708. if (ci != 0)
  48709. {
  48710. CommandMapping* const cm = new CommandMapping();
  48711. cm->commandID = commandID;
  48712. cm->keypresses.add (newKeyPress);
  48713. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48714. mappings.add (cm);
  48715. sendChangeMessage();
  48716. }
  48717. }
  48718. }
  48719. }
  48720. void KeyPressMappingSet::resetToDefaultMappings()
  48721. {
  48722. mappings.clear();
  48723. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48724. {
  48725. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48726. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48727. {
  48728. addKeyPress (ci->commandID,
  48729. ci->defaultKeypresses.getReference (j));
  48730. }
  48731. }
  48732. sendChangeMessage();
  48733. }
  48734. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48735. {
  48736. clearAllKeyPresses (commandID);
  48737. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48738. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48739. {
  48740. addKeyPress (ci->commandID,
  48741. ci->defaultKeypresses.getReference (j));
  48742. }
  48743. }
  48744. void KeyPressMappingSet::clearAllKeyPresses()
  48745. {
  48746. if (mappings.size() > 0)
  48747. {
  48748. sendChangeMessage();
  48749. mappings.clear();
  48750. }
  48751. }
  48752. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  48753. {
  48754. for (int i = mappings.size(); --i >= 0;)
  48755. {
  48756. if (mappings.getUnchecked(i)->commandID == commandID)
  48757. {
  48758. mappings.remove (i);
  48759. sendChangeMessage();
  48760. }
  48761. }
  48762. }
  48763. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  48764. {
  48765. if (keypress.isValid())
  48766. {
  48767. for (int i = mappings.size(); --i >= 0;)
  48768. {
  48769. CommandMapping* const cm = mappings.getUnchecked(i);
  48770. for (int j = cm->keypresses.size(); --j >= 0;)
  48771. {
  48772. if (keypress == cm->keypresses [j])
  48773. {
  48774. cm->keypresses.remove (j);
  48775. sendChangeMessage();
  48776. }
  48777. }
  48778. }
  48779. }
  48780. }
  48781. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  48782. {
  48783. for (int i = mappings.size(); --i >= 0;)
  48784. {
  48785. if (mappings.getUnchecked(i)->commandID == commandID)
  48786. {
  48787. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  48788. sendChangeMessage();
  48789. break;
  48790. }
  48791. }
  48792. }
  48793. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  48794. {
  48795. for (int i = 0; i < mappings.size(); ++i)
  48796. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  48797. return mappings.getUnchecked(i)->commandID;
  48798. return 0;
  48799. }
  48800. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  48801. {
  48802. for (int i = mappings.size(); --i >= 0;)
  48803. if (mappings.getUnchecked(i)->commandID == commandID)
  48804. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  48805. return false;
  48806. }
  48807. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  48808. const KeyPress& key,
  48809. const bool isKeyDown,
  48810. const int millisecsSinceKeyPressed,
  48811. Component* const originatingComponent) const
  48812. {
  48813. ApplicationCommandTarget::InvocationInfo info (commandID);
  48814. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  48815. info.isKeyDown = isKeyDown;
  48816. info.keyPress = key;
  48817. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  48818. info.originatingComponent = originatingComponent;
  48819. commandManager->invoke (info, false);
  48820. }
  48821. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  48822. {
  48823. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  48824. {
  48825. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  48826. {
  48827. // if the XML was created as a set of differences from the default mappings,
  48828. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  48829. resetToDefaultMappings();
  48830. }
  48831. else
  48832. {
  48833. // if the XML was created calling createXml (false), then we need to clear all
  48834. // the keys and treat the xml as describing the entire set of mappings.
  48835. clearAllKeyPresses();
  48836. }
  48837. forEachXmlChildElement (xmlVersion, map)
  48838. {
  48839. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  48840. if (commandId != 0)
  48841. {
  48842. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  48843. if (map->hasTagName ("MAPPING"))
  48844. {
  48845. addKeyPress (commandId, key);
  48846. }
  48847. else if (map->hasTagName ("UNMAPPING"))
  48848. {
  48849. if (containsMapping (commandId, key))
  48850. removeKeyPress (key);
  48851. }
  48852. }
  48853. }
  48854. return true;
  48855. }
  48856. return false;
  48857. }
  48858. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  48859. {
  48860. ScopedPointer <KeyPressMappingSet> defaultSet;
  48861. if (saveDifferencesFromDefaultSet)
  48862. {
  48863. defaultSet = new KeyPressMappingSet (commandManager);
  48864. defaultSet->resetToDefaultMappings();
  48865. }
  48866. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  48867. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  48868. int i;
  48869. for (i = 0; i < mappings.size(); ++i)
  48870. {
  48871. const CommandMapping* const cm = mappings.getUnchecked(i);
  48872. for (int j = 0; j < cm->keypresses.size(); ++j)
  48873. {
  48874. if (defaultSet == 0
  48875. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48876. {
  48877. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  48878. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48879. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48880. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48881. }
  48882. }
  48883. }
  48884. if (defaultSet != 0)
  48885. {
  48886. for (i = 0; i < defaultSet->mappings.size(); ++i)
  48887. {
  48888. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  48889. for (int j = 0; j < cm->keypresses.size(); ++j)
  48890. {
  48891. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48892. {
  48893. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  48894. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48895. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48896. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48897. }
  48898. }
  48899. }
  48900. }
  48901. return doc;
  48902. }
  48903. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  48904. Component* originatingComponent)
  48905. {
  48906. bool used = false;
  48907. const CommandID commandID = findCommandForKeyPress (key);
  48908. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48909. if (ci != 0
  48910. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  48911. {
  48912. ApplicationCommandInfo info (0);
  48913. if (commandManager->getTargetForCommand (commandID, info) != 0
  48914. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  48915. {
  48916. invokeCommand (commandID, key, true, 0, originatingComponent);
  48917. used = true;
  48918. }
  48919. else
  48920. {
  48921. if (originatingComponent != 0)
  48922. originatingComponent->getLookAndFeel().playAlertSound();
  48923. }
  48924. }
  48925. return used;
  48926. }
  48927. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  48928. {
  48929. bool used = false;
  48930. const uint32 now = Time::getMillisecondCounter();
  48931. for (int i = mappings.size(); --i >= 0;)
  48932. {
  48933. CommandMapping* const cm = mappings.getUnchecked(i);
  48934. if (cm->wantsKeyUpDownCallbacks)
  48935. {
  48936. for (int j = cm->keypresses.size(); --j >= 0;)
  48937. {
  48938. const KeyPress key (cm->keypresses.getReference (j));
  48939. const bool isDown = key.isCurrentlyDown();
  48940. int keyPressEntryIndex = 0;
  48941. bool wasDown = false;
  48942. for (int k = keysDown.size(); --k >= 0;)
  48943. {
  48944. if (key == keysDown.getUnchecked(k)->key)
  48945. {
  48946. keyPressEntryIndex = k;
  48947. wasDown = true;
  48948. used = true;
  48949. break;
  48950. }
  48951. }
  48952. if (isDown != wasDown)
  48953. {
  48954. int millisecs = 0;
  48955. if (isDown)
  48956. {
  48957. KeyPressTime* const k = new KeyPressTime();
  48958. k->key = key;
  48959. k->timeWhenPressed = now;
  48960. keysDown.add (k);
  48961. }
  48962. else
  48963. {
  48964. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  48965. if (now > pressTime)
  48966. millisecs = now - pressTime;
  48967. keysDown.remove (keyPressEntryIndex);
  48968. }
  48969. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  48970. used = true;
  48971. }
  48972. }
  48973. }
  48974. }
  48975. return used;
  48976. }
  48977. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  48978. {
  48979. if (focusedComponent != 0)
  48980. focusedComponent->keyStateChanged (false);
  48981. }
  48982. END_JUCE_NAMESPACE
  48983. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  48984. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  48985. BEGIN_JUCE_NAMESPACE
  48986. ModifierKeys::ModifierKeys (const int flags_) throw()
  48987. : flags (flags_)
  48988. {
  48989. }
  48990. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  48991. : flags (other.flags)
  48992. {
  48993. }
  48994. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  48995. {
  48996. flags = other.flags;
  48997. return *this;
  48998. }
  48999. ModifierKeys ModifierKeys::currentModifiers;
  49000. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  49001. {
  49002. return currentModifiers;
  49003. }
  49004. int ModifierKeys::getNumMouseButtonsDown() const throw()
  49005. {
  49006. int num = 0;
  49007. if (isLeftButtonDown()) ++num;
  49008. if (isRightButtonDown()) ++num;
  49009. if (isMiddleButtonDown()) ++num;
  49010. return num;
  49011. }
  49012. END_JUCE_NAMESPACE
  49013. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  49014. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  49015. BEGIN_JUCE_NAMESPACE
  49016. class ComponentAnimator::AnimationTask
  49017. {
  49018. public:
  49019. AnimationTask (Component* const comp)
  49020. : component (comp)
  49021. {
  49022. }
  49023. void reset (const Rectangle<int>& finalBounds,
  49024. float finalAlpha,
  49025. int millisecondsToSpendMoving,
  49026. bool useProxyComponent,
  49027. double startSpeed_, double endSpeed_)
  49028. {
  49029. msElapsed = 0;
  49030. msTotal = jmax (1, millisecondsToSpendMoving);
  49031. lastProgress = 0;
  49032. destination = finalBounds;
  49033. destAlpha = finalAlpha;
  49034. isMoving = (finalBounds != component->getBounds());
  49035. isChangingAlpha = (finalAlpha != component->getAlpha());
  49036. left = component->getX();
  49037. top = component->getY();
  49038. right = component->getRight();
  49039. bottom = component->getBottom();
  49040. alpha = component->getAlpha();
  49041. const double invTotalDistance = 4.0 / (startSpeed_ + endSpeed_ + 2.0);
  49042. startSpeed = jmax (0.0, startSpeed_ * invTotalDistance);
  49043. midSpeed = invTotalDistance;
  49044. endSpeed = jmax (0.0, endSpeed_ * invTotalDistance);
  49045. if (useProxyComponent)
  49046. proxy = new ProxyComponent (*component);
  49047. else
  49048. proxy = 0;
  49049. component->setVisible (! useProxyComponent);
  49050. }
  49051. bool useTimeslice (const int elapsed)
  49052. {
  49053. Component* const c = proxy != 0 ? static_cast <Component*> (proxy)
  49054. : static_cast <Component*> (component);
  49055. if (c != 0)
  49056. {
  49057. msElapsed += elapsed;
  49058. double newProgress = msElapsed / (double) msTotal;
  49059. if (newProgress >= 0 && newProgress < 1.0)
  49060. {
  49061. newProgress = timeToDistance (newProgress);
  49062. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49063. jassert (newProgress >= lastProgress);
  49064. lastProgress = newProgress;
  49065. if (delta < 1.0)
  49066. {
  49067. bool stillBusy = false;
  49068. if (isMoving)
  49069. {
  49070. left += (destination.getX() - left) * delta;
  49071. top += (destination.getY() - top) * delta;
  49072. right += (destination.getRight() - right) * delta;
  49073. bottom += (destination.getBottom() - bottom) * delta;
  49074. const Rectangle<int> newBounds (roundToInt (left),
  49075. roundToInt (top),
  49076. roundToInt (right - left),
  49077. roundToInt (bottom - top));
  49078. if (newBounds != destination)
  49079. {
  49080. c->setBounds (newBounds);
  49081. stillBusy = true;
  49082. }
  49083. }
  49084. if (isChangingAlpha)
  49085. {
  49086. alpha += (destAlpha - alpha) * delta;
  49087. c->setAlpha ((float) alpha);
  49088. stillBusy = true;
  49089. }
  49090. if (stillBusy)
  49091. return true;
  49092. }
  49093. }
  49094. }
  49095. moveToFinalDestination();
  49096. return false;
  49097. }
  49098. void moveToFinalDestination()
  49099. {
  49100. if (component != 0)
  49101. {
  49102. component->setAlpha ((float) destAlpha);
  49103. component->setBounds (destination);
  49104. }
  49105. }
  49106. class ProxyComponent : public Component
  49107. {
  49108. public:
  49109. ProxyComponent (Component& component)
  49110. : image (component.createComponentSnapshot (component.getLocalBounds()))
  49111. {
  49112. setBounds (component.getBounds());
  49113. setAlpha (component.getAlpha());
  49114. setInterceptsMouseClicks (false, false);
  49115. Component* const parent = component.getParentComponent();
  49116. if (parent != 0)
  49117. parent->addAndMakeVisible (this);
  49118. else if (component.isOnDesktop() && component.getPeer() != 0)
  49119. addToDesktop (component.getPeer()->getStyleFlags());
  49120. else
  49121. jassertfalse; // seem to be trying to animate a component that's not visible..
  49122. setVisible (true);
  49123. toBehind (&component);
  49124. }
  49125. void paint (Graphics& g)
  49126. {
  49127. g.setOpacity (1.0f);
  49128. g.drawImage (image, 0, 0, getWidth(), getHeight(),
  49129. 0, 0, image.getWidth(), image.getHeight());
  49130. }
  49131. private:
  49132. Image image;
  49133. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProxyComponent);
  49134. };
  49135. WeakReference<Component> component;
  49136. ScopedPointer<Component> proxy;
  49137. Rectangle<int> destination;
  49138. double destAlpha;
  49139. int msElapsed, msTotal;
  49140. double startSpeed, midSpeed, endSpeed, lastProgress;
  49141. double left, top, right, bottom, alpha;
  49142. bool isMoving, isChangingAlpha;
  49143. private:
  49144. double timeToDistance (const double time) const throw()
  49145. {
  49146. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49147. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49148. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49149. }
  49150. };
  49151. ComponentAnimator::ComponentAnimator()
  49152. : lastTime (0)
  49153. {
  49154. }
  49155. ComponentAnimator::~ComponentAnimator()
  49156. {
  49157. }
  49158. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49159. {
  49160. for (int i = tasks.size(); --i >= 0;)
  49161. if (component == tasks.getUnchecked(i)->component.get())
  49162. return tasks.getUnchecked(i);
  49163. return 0;
  49164. }
  49165. void ComponentAnimator::animateComponent (Component* const component,
  49166. const Rectangle<int>& finalBounds,
  49167. const float finalAlpha,
  49168. const int millisecondsToSpendMoving,
  49169. const bool useProxyComponent,
  49170. const double startSpeed,
  49171. const double endSpeed)
  49172. {
  49173. // the speeds must be 0 or greater!
  49174. jassert (startSpeed >= 0 && endSpeed >= 0)
  49175. if (component != 0)
  49176. {
  49177. AnimationTask* at = findTaskFor (component);
  49178. if (at == 0)
  49179. {
  49180. at = new AnimationTask (component);
  49181. tasks.add (at);
  49182. sendChangeMessage();
  49183. }
  49184. at->reset (finalBounds, finalAlpha, millisecondsToSpendMoving,
  49185. useProxyComponent, startSpeed, endSpeed);
  49186. if (! isTimerRunning())
  49187. {
  49188. lastTime = Time::getMillisecondCounter();
  49189. startTimer (1000 / 50);
  49190. }
  49191. }
  49192. }
  49193. void ComponentAnimator::fadeOut (Component* component, int millisecondsToTake)
  49194. {
  49195. if (component != 0)
  49196. {
  49197. if (component->isShowing() && millisecondsToTake > 0)
  49198. animateComponent (component, component->getBounds(), 0.0f, millisecondsToTake, true, 1.0, 1.0);
  49199. component->setVisible (false);
  49200. }
  49201. }
  49202. void ComponentAnimator::fadeIn (Component* component, int millisecondsToTake)
  49203. {
  49204. if (component != 0 && ! (component->isVisible() && component->getAlpha() == 1.0f))
  49205. {
  49206. component->setAlpha (0.0f);
  49207. component->setVisible (true);
  49208. animateComponent (component, component->getBounds(), 1.0f, millisecondsToTake, false, 1.0, 1.0);
  49209. }
  49210. }
  49211. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49212. {
  49213. if (tasks.size() > 0)
  49214. {
  49215. if (moveComponentsToTheirFinalPositions)
  49216. for (int i = tasks.size(); --i >= 0;)
  49217. tasks.getUnchecked(i)->moveToFinalDestination();
  49218. tasks.clear();
  49219. sendChangeMessage();
  49220. }
  49221. }
  49222. void ComponentAnimator::cancelAnimation (Component* const component,
  49223. const bool moveComponentToItsFinalPosition)
  49224. {
  49225. AnimationTask* const at = findTaskFor (component);
  49226. if (at != 0)
  49227. {
  49228. if (moveComponentToItsFinalPosition)
  49229. at->moveToFinalDestination();
  49230. tasks.removeObject (at);
  49231. sendChangeMessage();
  49232. }
  49233. }
  49234. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49235. {
  49236. jassert (component != 0);
  49237. AnimationTask* const at = findTaskFor (component);
  49238. if (at != 0)
  49239. return at->destination;
  49240. return component->getBounds();
  49241. }
  49242. bool ComponentAnimator::isAnimating (Component* component) const
  49243. {
  49244. return findTaskFor (component) != 0;
  49245. }
  49246. void ComponentAnimator::timerCallback()
  49247. {
  49248. const uint32 timeNow = Time::getMillisecondCounter();
  49249. if (lastTime == 0 || lastTime == timeNow)
  49250. lastTime = timeNow;
  49251. const int elapsed = timeNow - lastTime;
  49252. for (int i = tasks.size(); --i >= 0;)
  49253. {
  49254. if (! tasks.getUnchecked(i)->useTimeslice (elapsed))
  49255. {
  49256. tasks.remove (i);
  49257. sendChangeMessage();
  49258. }
  49259. }
  49260. lastTime = timeNow;
  49261. if (tasks.size() == 0)
  49262. stopTimer();
  49263. }
  49264. END_JUCE_NAMESPACE
  49265. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49266. /*** Start of inlined file: juce_ComponentBuilder.cpp ***/
  49267. BEGIN_JUCE_NAMESPACE
  49268. namespace ComponentBuilderHelpers
  49269. {
  49270. const String getStateId (const ValueTree& state)
  49271. {
  49272. return state [ComponentBuilder::idProperty].toString();
  49273. }
  49274. Component* findComponentWithID (OwnedArray<Component>& components, const String& compId)
  49275. {
  49276. jassert (compId.isNotEmpty());
  49277. for (int i = components.size(); --i >= 0;)
  49278. {
  49279. Component* const c = components.getUnchecked (i);
  49280. if (c->getComponentID() == compId)
  49281. return components.removeAndReturn (i);
  49282. }
  49283. return 0;
  49284. }
  49285. Component* findComponentWithID (Component* const c, const String& compId)
  49286. {
  49287. jassert (compId.isNotEmpty());
  49288. if (c->getComponentID() == compId)
  49289. return c;
  49290. for (int i = c->getNumChildComponents(); --i >= 0;)
  49291. {
  49292. Component* const child = findComponentWithID (c->getChildComponent (i), compId);
  49293. if (child != 0)
  49294. return child;
  49295. }
  49296. return 0;
  49297. }
  49298. Component* createNewComponent (ComponentBuilder::TypeHandler& type,
  49299. const ValueTree& state, Component* parent)
  49300. {
  49301. Component* const c = type.addNewComponentFromState (state, parent);
  49302. jassert (c != 0 && c->getParentComponent() == parent);
  49303. c->setComponentID (getStateId (state));
  49304. return c;
  49305. }
  49306. void updateComponent (ComponentBuilder& builder, const ValueTree& state)
  49307. {
  49308. Component* topLevelComp = builder.getManagedComponent();
  49309. if (topLevelComp != 0)
  49310. {
  49311. ComponentBuilder::TypeHandler* const type = builder.getHandlerForState (state);
  49312. const String uid (getStateId (state));
  49313. if (type == 0 || uid.isEmpty())
  49314. {
  49315. // ..handle the case where a child of the actual state node has changed.
  49316. if (state.getParent().isValid())
  49317. updateComponent (builder, state.getParent());
  49318. }
  49319. else
  49320. {
  49321. Component* const changedComp = findComponentWithID (topLevelComp, uid);
  49322. if (changedComp != 0)
  49323. type->updateComponentFromState (changedComp, state);
  49324. }
  49325. }
  49326. }
  49327. }
  49328. const Identifier ComponentBuilder::idProperty ("id");
  49329. ComponentBuilder::ComponentBuilder (const ValueTree& state_)
  49330. : state (state_), imageProvider (0)
  49331. {
  49332. state.addListener (this);
  49333. }
  49334. ComponentBuilder::~ComponentBuilder()
  49335. {
  49336. state.removeListener (this);
  49337. #if JUCE_DEBUG
  49338. // Don't delete the managed component!! The builder owns that component, and will delete
  49339. // it automatically when it gets deleted.
  49340. jassert (componentRef.get() == static_cast <Component*> (component));
  49341. #endif
  49342. }
  49343. Component* ComponentBuilder::getManagedComponent()
  49344. {
  49345. if (component == 0)
  49346. {
  49347. component = createComponent();
  49348. #if JUCE_DEBUG
  49349. componentRef = component;
  49350. #endif
  49351. }
  49352. return component;
  49353. }
  49354. Component* ComponentBuilder::createComponent()
  49355. {
  49356. jassert (types.size() > 0); // You need to register all the necessary types before you can load a component!
  49357. TypeHandler* const type = getHandlerForState (state);
  49358. jassert (type != 0); // trying to create a component from an unknown type of ValueTree
  49359. return type != 0 ? ComponentBuilderHelpers::createNewComponent (*type, state, 0) : 0;
  49360. }
  49361. void ComponentBuilder::registerTypeHandler (ComponentBuilder::TypeHandler* const type)
  49362. {
  49363. jassert (type != 0);
  49364. // Don't try to move your types around! Once a type has been added to a builder, the
  49365. // builder owns it, and you should leave it alone!
  49366. jassert (type->builder == 0);
  49367. types.add (type);
  49368. type->builder = this;
  49369. }
  49370. ComponentBuilder::TypeHandler* ComponentBuilder::getHandlerForState (const ValueTree& s) const
  49371. {
  49372. const Identifier targetType (s.getType());
  49373. for (int i = 0; i < types.size(); ++i)
  49374. {
  49375. TypeHandler* const t = types.getUnchecked(i);
  49376. if (t->getType() == targetType)
  49377. return t;
  49378. }
  49379. return 0;
  49380. }
  49381. int ComponentBuilder::getNumHandlers() const throw()
  49382. {
  49383. return types.size();
  49384. }
  49385. ComponentBuilder::TypeHandler* ComponentBuilder::getHandler (const int index) const throw()
  49386. {
  49387. return types [index];
  49388. }
  49389. void ComponentBuilder::setImageProvider (ImageProvider* newImageProvider) throw()
  49390. {
  49391. imageProvider = newImageProvider;
  49392. }
  49393. ComponentBuilder::ImageProvider* ComponentBuilder::getImageProvider() const throw()
  49394. {
  49395. return imageProvider;
  49396. }
  49397. void ComponentBuilder::valueTreePropertyChanged (ValueTree& tree, const Identifier&)
  49398. {
  49399. ComponentBuilderHelpers::updateComponent (*this, tree);
  49400. }
  49401. void ComponentBuilder::valueTreeChildAdded (ValueTree& tree, ValueTree&)
  49402. {
  49403. ComponentBuilderHelpers::updateComponent (*this, tree);
  49404. }
  49405. void ComponentBuilder::valueTreeChildRemoved (ValueTree& tree, ValueTree&)
  49406. {
  49407. ComponentBuilderHelpers::updateComponent (*this, tree);
  49408. }
  49409. void ComponentBuilder::valueTreeChildOrderChanged (ValueTree& tree)
  49410. {
  49411. ComponentBuilderHelpers::updateComponent (*this, tree);
  49412. }
  49413. void ComponentBuilder::valueTreeParentChanged (ValueTree& tree)
  49414. {
  49415. ComponentBuilderHelpers::updateComponent (*this, tree);
  49416. }
  49417. ComponentBuilder::TypeHandler::TypeHandler (const Identifier& valueTreeType_)
  49418. : builder (0), valueTreeType (valueTreeType_)
  49419. {
  49420. }
  49421. ComponentBuilder::TypeHandler::~TypeHandler()
  49422. {
  49423. }
  49424. ComponentBuilder* ComponentBuilder::TypeHandler::getBuilder() const throw()
  49425. {
  49426. // A type handler needs to be registered with a ComponentBuilder before using it!
  49427. jassert (builder != 0);
  49428. return builder;
  49429. }
  49430. void ComponentBuilder::updateChildComponents (Component& parent, const ValueTree& children)
  49431. {
  49432. using namespace ComponentBuilderHelpers;
  49433. const int numExistingChildComps = parent.getNumChildComponents();
  49434. Array <Component*> componentsInOrder;
  49435. componentsInOrder.ensureStorageAllocated (numExistingChildComps);
  49436. {
  49437. OwnedArray<Component> existingComponents;
  49438. existingComponents.ensureStorageAllocated (numExistingChildComps);
  49439. int i;
  49440. for (i = 0; i < numExistingChildComps; ++i)
  49441. existingComponents.add (parent.getChildComponent (i));
  49442. const int newNumChildren = children.getNumChildren();
  49443. for (i = 0; i < newNumChildren; ++i)
  49444. {
  49445. const ValueTree childState (children.getChild (i));
  49446. ComponentBuilder::TypeHandler* const type = getHandlerForState (childState);
  49447. jassert (type != 0);
  49448. if (type != 0)
  49449. {
  49450. Component* c = findComponentWithID (existingComponents, getStateId (childState));
  49451. if (c == 0)
  49452. c = createNewComponent (*type, childState, &parent);
  49453. componentsInOrder.add (c);
  49454. }
  49455. }
  49456. // (remaining unused items in existingComponents get deleted here as it goes out of scope)
  49457. }
  49458. // Make sure the z-order is correct..
  49459. if (componentsInOrder.size() > 0)
  49460. {
  49461. componentsInOrder.getLast()->toFront (false);
  49462. for (int i = componentsInOrder.size() - 1; --i >= 0;)
  49463. componentsInOrder.getUnchecked(i)->toBehind (componentsInOrder.getUnchecked (i + 1));
  49464. }
  49465. }
  49466. END_JUCE_NAMESPACE
  49467. /*** End of inlined file: juce_ComponentBuilder.cpp ***/
  49468. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49469. BEGIN_JUCE_NAMESPACE
  49470. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49471. : minW (0),
  49472. maxW (0x3fffffff),
  49473. minH (0),
  49474. maxH (0x3fffffff),
  49475. minOffTop (0),
  49476. minOffLeft (0),
  49477. minOffBottom (0),
  49478. minOffRight (0),
  49479. aspectRatio (0.0)
  49480. {
  49481. }
  49482. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49483. {
  49484. }
  49485. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49486. {
  49487. minW = minimumWidth;
  49488. }
  49489. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49490. {
  49491. maxW = maximumWidth;
  49492. }
  49493. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49494. {
  49495. minH = minimumHeight;
  49496. }
  49497. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49498. {
  49499. maxH = maximumHeight;
  49500. }
  49501. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49502. {
  49503. jassert (maxW >= minimumWidth);
  49504. jassert (maxH >= minimumHeight);
  49505. jassert (minimumWidth > 0 && minimumHeight > 0);
  49506. minW = minimumWidth;
  49507. minH = minimumHeight;
  49508. if (minW > maxW)
  49509. maxW = minW;
  49510. if (minH > maxH)
  49511. maxH = minH;
  49512. }
  49513. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49514. {
  49515. jassert (maximumWidth >= minW);
  49516. jassert (maximumHeight >= minH);
  49517. jassert (maximumWidth > 0 && maximumHeight > 0);
  49518. maxW = jmax (minW, maximumWidth);
  49519. maxH = jmax (minH, maximumHeight);
  49520. }
  49521. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49522. const int minimumHeight,
  49523. const int maximumWidth,
  49524. const int maximumHeight) throw()
  49525. {
  49526. jassert (maximumWidth >= minimumWidth);
  49527. jassert (maximumHeight >= minimumHeight);
  49528. jassert (maximumWidth > 0 && maximumHeight > 0);
  49529. jassert (minimumWidth > 0 && minimumHeight > 0);
  49530. minW = jmax (0, minimumWidth);
  49531. minH = jmax (0, minimumHeight);
  49532. maxW = jmax (minW, maximumWidth);
  49533. maxH = jmax (minH, maximumHeight);
  49534. }
  49535. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49536. const int minimumWhenOffTheLeft,
  49537. const int minimumWhenOffTheBottom,
  49538. const int minimumWhenOffTheRight) throw()
  49539. {
  49540. minOffTop = minimumWhenOffTheTop;
  49541. minOffLeft = minimumWhenOffTheLeft;
  49542. minOffBottom = minimumWhenOffTheBottom;
  49543. minOffRight = minimumWhenOffTheRight;
  49544. }
  49545. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49546. {
  49547. aspectRatio = jmax (0.0, widthOverHeight);
  49548. }
  49549. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49550. {
  49551. return aspectRatio;
  49552. }
  49553. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49554. const Rectangle<int>& targetBounds,
  49555. const bool isStretchingTop,
  49556. const bool isStretchingLeft,
  49557. const bool isStretchingBottom,
  49558. const bool isStretchingRight)
  49559. {
  49560. jassert (component != 0);
  49561. Rectangle<int> limits, bounds (targetBounds);
  49562. BorderSize<int> border;
  49563. Component* const parent = component->getParentComponent();
  49564. if (parent == 0)
  49565. {
  49566. ComponentPeer* peer = component->getPeer();
  49567. if (peer != 0)
  49568. border = peer->getFrameSize();
  49569. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49570. }
  49571. else
  49572. {
  49573. limits.setSize (parent->getWidth(), parent->getHeight());
  49574. }
  49575. border.addTo (bounds);
  49576. checkBounds (bounds,
  49577. border.addedTo (component->getBounds()), limits,
  49578. isStretchingTop, isStretchingLeft,
  49579. isStretchingBottom, isStretchingRight);
  49580. border.subtractFrom (bounds);
  49581. applyBoundsToComponent (component, bounds);
  49582. }
  49583. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49584. {
  49585. setBoundsForComponent (component, component->getBounds(),
  49586. false, false, false, false);
  49587. }
  49588. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49589. const Rectangle<int>& bounds)
  49590. {
  49591. component->setBounds (bounds);
  49592. }
  49593. void ComponentBoundsConstrainer::resizeStart()
  49594. {
  49595. }
  49596. void ComponentBoundsConstrainer::resizeEnd()
  49597. {
  49598. }
  49599. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49600. const Rectangle<int>& old,
  49601. const Rectangle<int>& limits,
  49602. const bool isStretchingTop,
  49603. const bool isStretchingLeft,
  49604. const bool isStretchingBottom,
  49605. const bool isStretchingRight)
  49606. {
  49607. // constrain the size if it's being stretched..
  49608. if (isStretchingLeft)
  49609. bounds.setLeft (jlimit (old.getRight() - maxW, old.getRight() - minW, bounds.getX()));
  49610. if (isStretchingRight)
  49611. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49612. if (isStretchingTop)
  49613. bounds.setTop (jlimit (old.getBottom() - maxH, old.getBottom() - minH, bounds.getY()));
  49614. if (isStretchingBottom)
  49615. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49616. if (bounds.isEmpty())
  49617. return;
  49618. if (minOffTop > 0)
  49619. {
  49620. const int limit = limits.getY() + jmin (minOffTop - bounds.getHeight(), 0);
  49621. if (bounds.getY() < limit)
  49622. {
  49623. if (isStretchingTop)
  49624. bounds.setTop (limits.getY());
  49625. else
  49626. bounds.setY (limit);
  49627. }
  49628. }
  49629. if (minOffLeft > 0)
  49630. {
  49631. const int limit = limits.getX() + jmin (minOffLeft - bounds.getWidth(), 0);
  49632. if (bounds.getX() < limit)
  49633. {
  49634. if (isStretchingLeft)
  49635. bounds.setLeft (limits.getX());
  49636. else
  49637. bounds.setX (limit);
  49638. }
  49639. }
  49640. if (minOffBottom > 0)
  49641. {
  49642. const int limit = limits.getBottom() - jmin (minOffBottom, bounds.getHeight());
  49643. if (bounds.getY() > limit)
  49644. {
  49645. if (isStretchingBottom)
  49646. bounds.setBottom (limits.getBottom());
  49647. else
  49648. bounds.setY (limit);
  49649. }
  49650. }
  49651. if (minOffRight > 0)
  49652. {
  49653. const int limit = limits.getRight() - jmin (minOffRight, bounds.getWidth());
  49654. if (bounds.getX() > limit)
  49655. {
  49656. if (isStretchingRight)
  49657. bounds.setRight (limits.getRight());
  49658. else
  49659. bounds.setX (limit);
  49660. }
  49661. }
  49662. // constrain the aspect ratio if one has been specified..
  49663. if (aspectRatio > 0.0)
  49664. {
  49665. bool adjustWidth;
  49666. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49667. {
  49668. adjustWidth = true;
  49669. }
  49670. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49671. {
  49672. adjustWidth = false;
  49673. }
  49674. else
  49675. {
  49676. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49677. const double newRatio = std::abs (bounds.getWidth() / (double) bounds.getHeight());
  49678. adjustWidth = (oldRatio > newRatio);
  49679. }
  49680. if (adjustWidth)
  49681. {
  49682. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49683. if (bounds.getWidth() > maxW || bounds.getWidth() < minW)
  49684. {
  49685. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49686. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49687. }
  49688. }
  49689. else
  49690. {
  49691. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49692. if (bounds.getHeight() > maxH || bounds.getHeight() < minH)
  49693. {
  49694. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49695. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49696. }
  49697. }
  49698. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49699. {
  49700. bounds.setX (old.getX() + (old.getWidth() - bounds.getWidth()) / 2);
  49701. }
  49702. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49703. {
  49704. bounds.setY (old.getY() + (old.getHeight() - bounds.getHeight()) / 2);
  49705. }
  49706. else
  49707. {
  49708. if (isStretchingLeft)
  49709. bounds.setX (old.getRight() - bounds.getWidth());
  49710. if (isStretchingTop)
  49711. bounds.setY (old.getBottom() - bounds.getHeight());
  49712. }
  49713. }
  49714. jassert (! bounds.isEmpty());
  49715. }
  49716. END_JUCE_NAMESPACE
  49717. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49718. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49719. BEGIN_JUCE_NAMESPACE
  49720. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49721. : component (component_),
  49722. lastPeer (0),
  49723. reentrant (false),
  49724. wasShowing (component_->isShowing())
  49725. {
  49726. jassert (component != 0); // can't use this with a null pointer..
  49727. component->addComponentListener (this);
  49728. registerWithParentComps();
  49729. }
  49730. ComponentMovementWatcher::~ComponentMovementWatcher()
  49731. {
  49732. if (component != 0)
  49733. component->removeComponentListener (this);
  49734. unregister();
  49735. }
  49736. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49737. {
  49738. if (component != 0 && ! reentrant)
  49739. {
  49740. const ScopedValueSetter<bool> setter (reentrant, true);
  49741. ComponentPeer* const peer = component->getPeer();
  49742. if (peer != lastPeer)
  49743. {
  49744. componentPeerChanged();
  49745. if (component == 0)
  49746. return;
  49747. lastPeer = peer;
  49748. }
  49749. unregister();
  49750. registerWithParentComps();
  49751. componentMovedOrResized (*component, true, true);
  49752. if (component != 0)
  49753. componentVisibilityChanged (*component);
  49754. }
  49755. }
  49756. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49757. {
  49758. if (component != 0)
  49759. {
  49760. if (wasMoved)
  49761. {
  49762. const Point<int> pos (component->getTopLevelComponent()->getLocalPoint (component, Point<int>()));
  49763. wasMoved = lastBounds.getPosition() != pos;
  49764. lastBounds.setPosition (pos);
  49765. }
  49766. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49767. lastBounds.setSize (component->getWidth(), component->getHeight());
  49768. if (wasMoved || wasResized)
  49769. componentMovedOrResized (wasMoved, wasResized);
  49770. }
  49771. }
  49772. void ComponentMovementWatcher::componentBeingDeleted (Component& comp)
  49773. {
  49774. registeredParentComps.removeValue (&comp);
  49775. if (component == &comp)
  49776. unregister();
  49777. }
  49778. void ComponentMovementWatcher::componentVisibilityChanged (Component&)
  49779. {
  49780. if (component != 0)
  49781. {
  49782. const bool isShowingNow = component->isShowing();
  49783. if (wasShowing != isShowingNow)
  49784. {
  49785. wasShowing = isShowingNow;
  49786. componentVisibilityChanged();
  49787. }
  49788. }
  49789. }
  49790. void ComponentMovementWatcher::registerWithParentComps()
  49791. {
  49792. Component* p = component->getParentComponent();
  49793. while (p != 0)
  49794. {
  49795. p->addComponentListener (this);
  49796. registeredParentComps.add (p);
  49797. p = p->getParentComponent();
  49798. }
  49799. }
  49800. void ComponentMovementWatcher::unregister()
  49801. {
  49802. for (int i = registeredParentComps.size(); --i >= 0;)
  49803. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49804. registeredParentComps.clear();
  49805. }
  49806. END_JUCE_NAMESPACE
  49807. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49808. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49809. BEGIN_JUCE_NAMESPACE
  49810. GroupComponent::GroupComponent (const String& componentName,
  49811. const String& labelText)
  49812. : Component (componentName),
  49813. text (labelText),
  49814. justification (Justification::left)
  49815. {
  49816. setInterceptsMouseClicks (false, true);
  49817. }
  49818. GroupComponent::~GroupComponent()
  49819. {
  49820. }
  49821. void GroupComponent::setText (const String& newText)
  49822. {
  49823. if (text != newText)
  49824. {
  49825. text = newText;
  49826. repaint();
  49827. }
  49828. }
  49829. const String GroupComponent::getText() const
  49830. {
  49831. return text;
  49832. }
  49833. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49834. {
  49835. if (justification != newJustification)
  49836. {
  49837. justification = newJustification;
  49838. repaint();
  49839. }
  49840. }
  49841. void GroupComponent::paint (Graphics& g)
  49842. {
  49843. getLookAndFeel()
  49844. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49845. text, justification,
  49846. *this);
  49847. }
  49848. void GroupComponent::enablementChanged()
  49849. {
  49850. repaint();
  49851. }
  49852. void GroupComponent::colourChanged()
  49853. {
  49854. repaint();
  49855. }
  49856. END_JUCE_NAMESPACE
  49857. /*** End of inlined file: juce_GroupComponent.cpp ***/
  49858. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  49859. BEGIN_JUCE_NAMESPACE
  49860. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  49861. : DocumentWindow (String::empty, backgroundColour,
  49862. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  49863. {
  49864. }
  49865. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  49866. {
  49867. }
  49868. void MultiDocumentPanelWindow::maximiseButtonPressed()
  49869. {
  49870. MultiDocumentPanel* const owner = getOwner();
  49871. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49872. if (owner != 0)
  49873. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  49874. }
  49875. void MultiDocumentPanelWindow::closeButtonPressed()
  49876. {
  49877. MultiDocumentPanel* const owner = getOwner();
  49878. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49879. if (owner != 0)
  49880. owner->closeDocument (getContentComponent(), true);
  49881. }
  49882. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  49883. {
  49884. DocumentWindow::activeWindowStatusChanged();
  49885. updateOrder();
  49886. }
  49887. void MultiDocumentPanelWindow::broughtToFront()
  49888. {
  49889. DocumentWindow::broughtToFront();
  49890. updateOrder();
  49891. }
  49892. void MultiDocumentPanelWindow::updateOrder()
  49893. {
  49894. MultiDocumentPanel* const owner = getOwner();
  49895. if (owner != 0)
  49896. owner->updateOrder();
  49897. }
  49898. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  49899. {
  49900. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49901. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49902. }
  49903. class MDITabbedComponentInternal : public TabbedComponent
  49904. {
  49905. public:
  49906. MDITabbedComponentInternal()
  49907. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  49908. {
  49909. }
  49910. ~MDITabbedComponentInternal()
  49911. {
  49912. }
  49913. void currentTabChanged (int, const String&)
  49914. {
  49915. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49916. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49917. if (owner != 0)
  49918. owner->updateOrder();
  49919. }
  49920. };
  49921. MultiDocumentPanel::MultiDocumentPanel()
  49922. : mode (MaximisedWindowsWithTabs),
  49923. backgroundColour (Colours::lightblue),
  49924. maximumNumDocuments (0),
  49925. numDocsBeforeTabsUsed (0)
  49926. {
  49927. setOpaque (true);
  49928. }
  49929. MultiDocumentPanel::~MultiDocumentPanel()
  49930. {
  49931. closeAllDocuments (false);
  49932. }
  49933. namespace MultiDocHelpers
  49934. {
  49935. bool shouldDeleteComp (Component* const c)
  49936. {
  49937. return c->getProperties() ["mdiDocumentDelete_"];
  49938. }
  49939. }
  49940. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  49941. {
  49942. while (components.size() > 0)
  49943. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  49944. return false;
  49945. return true;
  49946. }
  49947. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  49948. {
  49949. return new MultiDocumentPanelWindow (backgroundColour);
  49950. }
  49951. void MultiDocumentPanel::addWindow (Component* component)
  49952. {
  49953. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  49954. dw->setResizable (true, false);
  49955. dw->setContentComponent (component, false, true);
  49956. dw->setName (component->getName());
  49957. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  49958. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  49959. int x = 4;
  49960. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  49961. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  49962. x += 16;
  49963. dw->setTopLeftPosition (x, x);
  49964. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  49965. if (pos.toString().isNotEmpty())
  49966. dw->restoreWindowStateFromString (pos.toString());
  49967. addAndMakeVisible (dw);
  49968. dw->toFront (true);
  49969. }
  49970. bool MultiDocumentPanel::addDocument (Component* const component,
  49971. const Colour& docColour,
  49972. const bool deleteWhenRemoved)
  49973. {
  49974. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  49975. // with a frame-within-a-frame! Just pass in the bare content component.
  49976. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  49977. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  49978. return false;
  49979. components.add (component);
  49980. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  49981. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  49982. component->addComponentListener (this);
  49983. if (mode == FloatingWindows)
  49984. {
  49985. if (isFullscreenWhenOneDocument())
  49986. {
  49987. if (components.size() == 1)
  49988. {
  49989. addAndMakeVisible (component);
  49990. }
  49991. else
  49992. {
  49993. if (components.size() == 2)
  49994. addWindow (components.getFirst());
  49995. addWindow (component);
  49996. }
  49997. }
  49998. else
  49999. {
  50000. addWindow (component);
  50001. }
  50002. }
  50003. else
  50004. {
  50005. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  50006. {
  50007. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  50008. Array <Component*> temp (components);
  50009. for (int i = 0; i < temp.size(); ++i)
  50010. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  50011. resized();
  50012. }
  50013. else
  50014. {
  50015. if (tabComponent != 0)
  50016. tabComponent->addTab (component->getName(), docColour, component, false);
  50017. else
  50018. addAndMakeVisible (component);
  50019. }
  50020. setActiveDocument (component);
  50021. }
  50022. resized();
  50023. activeDocumentChanged();
  50024. return true;
  50025. }
  50026. bool MultiDocumentPanel::closeDocument (Component* component,
  50027. const bool checkItsOkToCloseFirst)
  50028. {
  50029. if (components.contains (component))
  50030. {
  50031. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50032. return false;
  50033. component->removeComponentListener (this);
  50034. const bool shouldDelete = MultiDocHelpers::shouldDeleteComp (component);
  50035. component->getProperties().remove ("mdiDocumentDelete_");
  50036. component->getProperties().remove ("mdiDocumentBkg_");
  50037. if (mode == FloatingWindows)
  50038. {
  50039. for (int i = getNumChildComponents(); --i >= 0;)
  50040. {
  50041. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50042. if (dw != 0 && dw->getContentComponent() == component)
  50043. {
  50044. dw->setContentComponent (0, false);
  50045. delete dw;
  50046. break;
  50047. }
  50048. }
  50049. if (shouldDelete)
  50050. delete component;
  50051. components.removeValue (component);
  50052. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50053. {
  50054. for (int i = getNumChildComponents(); --i >= 0;)
  50055. {
  50056. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50057. if (dw != 0)
  50058. {
  50059. dw->setContentComponent (0, false);
  50060. delete dw;
  50061. }
  50062. }
  50063. addAndMakeVisible (components.getFirst());
  50064. }
  50065. }
  50066. else
  50067. {
  50068. jassert (components.indexOf (component) >= 0);
  50069. if (tabComponent != 0)
  50070. {
  50071. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50072. if (tabComponent->getTabContentComponent (i) == component)
  50073. tabComponent->removeTab (i);
  50074. }
  50075. else
  50076. {
  50077. removeChildComponent (component);
  50078. }
  50079. if (shouldDelete)
  50080. delete component;
  50081. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50082. tabComponent = 0;
  50083. components.removeValue (component);
  50084. if (components.size() > 0 && tabComponent == 0)
  50085. addAndMakeVisible (components.getFirst());
  50086. }
  50087. resized();
  50088. activeDocumentChanged();
  50089. }
  50090. else
  50091. {
  50092. jassertfalse;
  50093. }
  50094. return true;
  50095. }
  50096. int MultiDocumentPanel::getNumDocuments() const throw()
  50097. {
  50098. return components.size();
  50099. }
  50100. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50101. {
  50102. return components [index];
  50103. }
  50104. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50105. {
  50106. if (mode == FloatingWindows)
  50107. {
  50108. for (int i = getNumChildComponents(); --i >= 0;)
  50109. {
  50110. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50111. if (dw != 0 && dw->isActiveWindow())
  50112. return dw->getContentComponent();
  50113. }
  50114. }
  50115. return components.getLast();
  50116. }
  50117. void MultiDocumentPanel::setActiveDocument (Component* component)
  50118. {
  50119. if (mode == FloatingWindows)
  50120. {
  50121. component = getContainerComp (component);
  50122. if (component != 0)
  50123. component->toFront (true);
  50124. }
  50125. else if (tabComponent != 0)
  50126. {
  50127. jassert (components.indexOf (component) >= 0);
  50128. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50129. {
  50130. if (tabComponent->getTabContentComponent (i) == component)
  50131. {
  50132. tabComponent->setCurrentTabIndex (i);
  50133. break;
  50134. }
  50135. }
  50136. }
  50137. else
  50138. {
  50139. component->grabKeyboardFocus();
  50140. }
  50141. }
  50142. void MultiDocumentPanel::activeDocumentChanged()
  50143. {
  50144. }
  50145. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50146. {
  50147. maximumNumDocuments = newNumber;
  50148. }
  50149. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50150. {
  50151. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50152. }
  50153. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50154. {
  50155. return numDocsBeforeTabsUsed != 0;
  50156. }
  50157. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50158. {
  50159. if (mode != newLayoutMode)
  50160. {
  50161. mode = newLayoutMode;
  50162. if (mode == FloatingWindows)
  50163. {
  50164. tabComponent = 0;
  50165. }
  50166. else
  50167. {
  50168. for (int i = getNumChildComponents(); --i >= 0;)
  50169. {
  50170. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50171. if (dw != 0)
  50172. {
  50173. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50174. dw->setContentComponent (0, false);
  50175. delete dw;
  50176. }
  50177. }
  50178. }
  50179. resized();
  50180. const Array <Component*> tempComps (components);
  50181. components.clear();
  50182. for (int i = 0; i < tempComps.size(); ++i)
  50183. {
  50184. Component* const c = tempComps.getUnchecked(i);
  50185. addDocument (c,
  50186. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50187. MultiDocHelpers::shouldDeleteComp (c));
  50188. }
  50189. }
  50190. }
  50191. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50192. {
  50193. if (backgroundColour != newBackgroundColour)
  50194. {
  50195. backgroundColour = newBackgroundColour;
  50196. setOpaque (newBackgroundColour.isOpaque());
  50197. repaint();
  50198. }
  50199. }
  50200. void MultiDocumentPanel::paint (Graphics& g)
  50201. {
  50202. g.fillAll (backgroundColour);
  50203. }
  50204. void MultiDocumentPanel::resized()
  50205. {
  50206. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50207. {
  50208. for (int i = getNumChildComponents(); --i >= 0;)
  50209. getChildComponent (i)->setBounds (getLocalBounds());
  50210. }
  50211. setWantsKeyboardFocus (components.size() == 0);
  50212. }
  50213. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50214. {
  50215. if (mode == FloatingWindows)
  50216. {
  50217. for (int i = 0; i < getNumChildComponents(); ++i)
  50218. {
  50219. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50220. if (dw != 0 && dw->getContentComponent() == c)
  50221. {
  50222. c = dw;
  50223. break;
  50224. }
  50225. }
  50226. }
  50227. return c;
  50228. }
  50229. void MultiDocumentPanel::componentNameChanged (Component&)
  50230. {
  50231. if (mode == FloatingWindows)
  50232. {
  50233. for (int i = 0; i < getNumChildComponents(); ++i)
  50234. {
  50235. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50236. if (dw != 0)
  50237. dw->setName (dw->getContentComponent()->getName());
  50238. }
  50239. }
  50240. else if (tabComponent != 0)
  50241. {
  50242. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50243. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50244. }
  50245. }
  50246. void MultiDocumentPanel::updateOrder()
  50247. {
  50248. const Array <Component*> oldList (components);
  50249. if (mode == FloatingWindows)
  50250. {
  50251. components.clear();
  50252. for (int i = 0; i < getNumChildComponents(); ++i)
  50253. {
  50254. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50255. if (dw != 0)
  50256. components.add (dw->getContentComponent());
  50257. }
  50258. }
  50259. else
  50260. {
  50261. if (tabComponent != 0)
  50262. {
  50263. Component* const current = tabComponent->getCurrentContentComponent();
  50264. if (current != 0)
  50265. {
  50266. components.removeValue (current);
  50267. components.add (current);
  50268. }
  50269. }
  50270. }
  50271. if (components != oldList)
  50272. activeDocumentChanged();
  50273. }
  50274. END_JUCE_NAMESPACE
  50275. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50276. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50277. BEGIN_JUCE_NAMESPACE
  50278. ResizableBorderComponent::Zone::Zone (const int zoneFlags) throw()
  50279. : zone (zoneFlags)
  50280. {}
  50281. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw()
  50282. : zone (other.zone)
  50283. {}
  50284. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw()
  50285. {
  50286. zone = other.zone;
  50287. return *this;
  50288. }
  50289. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50290. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50291. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50292. const BorderSize<int>& border,
  50293. const Point<int>& position)
  50294. {
  50295. int z = 0;
  50296. if (totalSize.contains (position)
  50297. && ! border.subtractedFrom (totalSize).contains (position))
  50298. {
  50299. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50300. if (position.getX() < jmax (border.getLeft(), minW) && border.getLeft() > 0)
  50301. z |= left;
  50302. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW) && border.getRight() > 0)
  50303. z |= right;
  50304. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50305. if (position.getY() < jmax (border.getTop(), minH) && border.getTop() > 0)
  50306. z |= top;
  50307. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH) && border.getBottom() > 0)
  50308. z |= bottom;
  50309. }
  50310. return Zone (z);
  50311. }
  50312. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50313. {
  50314. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50315. switch (zone)
  50316. {
  50317. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50318. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50319. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50320. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50321. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50322. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50323. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50324. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50325. default: break;
  50326. }
  50327. return mc;
  50328. }
  50329. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50330. ComponentBoundsConstrainer* const constrainer_)
  50331. : component (componentToResize),
  50332. constrainer (constrainer_),
  50333. borderSize (5),
  50334. mouseZone (0)
  50335. {
  50336. }
  50337. ResizableBorderComponent::~ResizableBorderComponent()
  50338. {
  50339. }
  50340. void ResizableBorderComponent::paint (Graphics& g)
  50341. {
  50342. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50343. }
  50344. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50345. {
  50346. updateMouseZone (e);
  50347. }
  50348. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50349. {
  50350. updateMouseZone (e);
  50351. }
  50352. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50353. {
  50354. if (component == 0)
  50355. {
  50356. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50357. return;
  50358. }
  50359. updateMouseZone (e);
  50360. originalBounds = component->getBounds();
  50361. if (constrainer != 0)
  50362. constrainer->resizeStart();
  50363. }
  50364. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50365. {
  50366. if (component == 0)
  50367. {
  50368. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50369. return;
  50370. }
  50371. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50372. if (constrainer != 0)
  50373. constrainer->setBoundsForComponent (component, bounds,
  50374. mouseZone.isDraggingTopEdge(),
  50375. mouseZone.isDraggingLeftEdge(),
  50376. mouseZone.isDraggingBottomEdge(),
  50377. mouseZone.isDraggingRightEdge());
  50378. else
  50379. component->setBounds (bounds);
  50380. }
  50381. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50382. {
  50383. if (constrainer != 0)
  50384. constrainer->resizeEnd();
  50385. }
  50386. bool ResizableBorderComponent::hitTest (int x, int y)
  50387. {
  50388. return x < borderSize.getLeft()
  50389. || x >= getWidth() - borderSize.getRight()
  50390. || y < borderSize.getTop()
  50391. || y >= getHeight() - borderSize.getBottom();
  50392. }
  50393. void ResizableBorderComponent::setBorderThickness (const BorderSize<int>& newBorderSize)
  50394. {
  50395. if (borderSize != newBorderSize)
  50396. {
  50397. borderSize = newBorderSize;
  50398. repaint();
  50399. }
  50400. }
  50401. const BorderSize<int> ResizableBorderComponent::getBorderThickness() const
  50402. {
  50403. return borderSize;
  50404. }
  50405. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50406. {
  50407. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50408. if (mouseZone != newZone)
  50409. {
  50410. mouseZone = newZone;
  50411. setMouseCursor (newZone.getMouseCursor());
  50412. }
  50413. }
  50414. END_JUCE_NAMESPACE
  50415. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50416. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50417. BEGIN_JUCE_NAMESPACE
  50418. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50419. ComponentBoundsConstrainer* const constrainer_)
  50420. : component (componentToResize),
  50421. constrainer (constrainer_)
  50422. {
  50423. setRepaintsOnMouseActivity (true);
  50424. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50425. }
  50426. ResizableCornerComponent::~ResizableCornerComponent()
  50427. {
  50428. }
  50429. void ResizableCornerComponent::paint (Graphics& g)
  50430. {
  50431. getLookAndFeel()
  50432. .drawCornerResizer (g, getWidth(), getHeight(),
  50433. isMouseOverOrDragging(),
  50434. isMouseButtonDown());
  50435. }
  50436. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50437. {
  50438. if (component == 0)
  50439. {
  50440. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50441. return;
  50442. }
  50443. originalBounds = component->getBounds();
  50444. if (constrainer != 0)
  50445. constrainer->resizeStart();
  50446. }
  50447. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50448. {
  50449. if (component == 0)
  50450. {
  50451. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50452. return;
  50453. }
  50454. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50455. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50456. if (constrainer != 0)
  50457. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50458. else
  50459. component->setBounds (r);
  50460. }
  50461. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50462. {
  50463. if (constrainer != 0)
  50464. constrainer->resizeStart();
  50465. }
  50466. bool ResizableCornerComponent::hitTest (int x, int y)
  50467. {
  50468. if (getWidth() <= 0)
  50469. return false;
  50470. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50471. return y >= yAtX - getHeight() / 4;
  50472. }
  50473. END_JUCE_NAMESPACE
  50474. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50475. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50476. BEGIN_JUCE_NAMESPACE
  50477. class ScrollBar::ScrollbarButton : public Button
  50478. {
  50479. public:
  50480. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50481. : Button (String::empty),
  50482. direction (direction_),
  50483. owner (owner_)
  50484. {
  50485. setWantsKeyboardFocus (false);
  50486. }
  50487. void paintButton (Graphics& g, bool over, bool down)
  50488. {
  50489. getLookAndFeel()
  50490. .drawScrollbarButton (g, owner,
  50491. getWidth(), getHeight(),
  50492. direction,
  50493. owner.isVertical(),
  50494. over, down);
  50495. }
  50496. void clicked()
  50497. {
  50498. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50499. }
  50500. int direction;
  50501. private:
  50502. ScrollBar& owner;
  50503. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollbarButton);
  50504. };
  50505. ScrollBar::ScrollBar (const bool vertical_,
  50506. const bool buttonsAreVisible)
  50507. : totalRange (0.0, 1.0),
  50508. visibleRange (0.0, 0.1),
  50509. singleStepSize (0.1),
  50510. thumbAreaStart (0),
  50511. thumbAreaSize (0),
  50512. thumbStart (0),
  50513. thumbSize (0),
  50514. initialDelayInMillisecs (100),
  50515. repeatDelayInMillisecs (50),
  50516. minimumDelayInMillisecs (10),
  50517. vertical (vertical_),
  50518. isDraggingThumb (false),
  50519. autohides (true)
  50520. {
  50521. setButtonVisibility (buttonsAreVisible);
  50522. setRepaintsOnMouseActivity (true);
  50523. setFocusContainer (true);
  50524. }
  50525. ScrollBar::~ScrollBar()
  50526. {
  50527. upButton = 0;
  50528. downButton = 0;
  50529. }
  50530. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50531. {
  50532. if (totalRange != newRangeLimit)
  50533. {
  50534. totalRange = newRangeLimit;
  50535. setCurrentRange (visibleRange);
  50536. updateThumbPosition();
  50537. }
  50538. }
  50539. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50540. {
  50541. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50542. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50543. }
  50544. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50545. {
  50546. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50547. if (visibleRange != constrainedRange)
  50548. {
  50549. visibleRange = constrainedRange;
  50550. updateThumbPosition();
  50551. triggerAsyncUpdate();
  50552. }
  50553. }
  50554. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50555. {
  50556. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50557. }
  50558. void ScrollBar::setCurrentRangeStart (const double newStart)
  50559. {
  50560. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50561. }
  50562. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50563. {
  50564. singleStepSize = newSingleStepSize;
  50565. }
  50566. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50567. {
  50568. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50569. }
  50570. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50571. {
  50572. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50573. }
  50574. void ScrollBar::scrollToTop()
  50575. {
  50576. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50577. }
  50578. void ScrollBar::scrollToBottom()
  50579. {
  50580. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50581. }
  50582. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50583. const int repeatDelayInMillisecs_,
  50584. const int minimumDelayInMillisecs_)
  50585. {
  50586. initialDelayInMillisecs = initialDelayInMillisecs_;
  50587. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50588. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50589. if (upButton != 0)
  50590. {
  50591. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50592. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50593. }
  50594. }
  50595. void ScrollBar::addListener (Listener* const listener)
  50596. {
  50597. listeners.add (listener);
  50598. }
  50599. void ScrollBar::removeListener (Listener* const listener)
  50600. {
  50601. listeners.remove (listener);
  50602. }
  50603. void ScrollBar::handleAsyncUpdate()
  50604. {
  50605. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50606. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50607. }
  50608. void ScrollBar::updateThumbPosition()
  50609. {
  50610. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50611. : thumbAreaSize);
  50612. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50613. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50614. if (newThumbSize > thumbAreaSize)
  50615. newThumbSize = thumbAreaSize;
  50616. int newThumbStart = thumbAreaStart;
  50617. if (totalRange.getLength() > visibleRange.getLength())
  50618. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50619. / (totalRange.getLength() - visibleRange.getLength()));
  50620. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50621. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50622. {
  50623. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50624. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50625. if (vertical)
  50626. repaint (0, repaintStart, getWidth(), repaintSize);
  50627. else
  50628. repaint (repaintStart, 0, repaintSize, getHeight());
  50629. thumbStart = newThumbStart;
  50630. thumbSize = newThumbSize;
  50631. }
  50632. }
  50633. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50634. {
  50635. if (vertical != shouldBeVertical)
  50636. {
  50637. vertical = shouldBeVertical;
  50638. if (upButton != 0)
  50639. {
  50640. upButton->direction = vertical ? 0 : 3;
  50641. downButton->direction = vertical ? 2 : 1;
  50642. }
  50643. updateThumbPosition();
  50644. }
  50645. }
  50646. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50647. {
  50648. upButton = 0;
  50649. downButton = 0;
  50650. if (buttonsAreVisible)
  50651. {
  50652. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50653. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50654. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50655. }
  50656. updateThumbPosition();
  50657. }
  50658. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50659. {
  50660. autohides = shouldHideWhenFullRange;
  50661. updateThumbPosition();
  50662. }
  50663. bool ScrollBar::autoHides() const throw()
  50664. {
  50665. return autohides;
  50666. }
  50667. void ScrollBar::paint (Graphics& g)
  50668. {
  50669. if (thumbAreaSize > 0)
  50670. {
  50671. LookAndFeel& lf = getLookAndFeel();
  50672. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50673. ? thumbSize : 0;
  50674. if (vertical)
  50675. {
  50676. lf.drawScrollbar (g, *this,
  50677. 0, thumbAreaStart,
  50678. getWidth(), thumbAreaSize,
  50679. vertical,
  50680. thumbStart, thumb,
  50681. isMouseOver(), isMouseButtonDown());
  50682. }
  50683. else
  50684. {
  50685. lf.drawScrollbar (g, *this,
  50686. thumbAreaStart, 0,
  50687. thumbAreaSize, getHeight(),
  50688. vertical,
  50689. thumbStart, thumb,
  50690. isMouseOver(), isMouseButtonDown());
  50691. }
  50692. }
  50693. }
  50694. void ScrollBar::lookAndFeelChanged()
  50695. {
  50696. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50697. }
  50698. void ScrollBar::resized()
  50699. {
  50700. const int length = ((vertical) ? getHeight() : getWidth());
  50701. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50702. : 0;
  50703. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50704. {
  50705. thumbAreaStart = length >> 1;
  50706. thumbAreaSize = 0;
  50707. }
  50708. else
  50709. {
  50710. thumbAreaStart = buttonSize;
  50711. thumbAreaSize = length - (buttonSize << 1);
  50712. }
  50713. if (upButton != 0)
  50714. {
  50715. if (vertical)
  50716. {
  50717. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50718. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50719. }
  50720. else
  50721. {
  50722. upButton->setBounds (0, 0, buttonSize, getHeight());
  50723. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50724. }
  50725. }
  50726. updateThumbPosition();
  50727. }
  50728. void ScrollBar::mouseDown (const MouseEvent& e)
  50729. {
  50730. isDraggingThumb = false;
  50731. lastMousePos = vertical ? e.y : e.x;
  50732. dragStartMousePos = lastMousePos;
  50733. dragStartRange = visibleRange.getStart();
  50734. if (dragStartMousePos < thumbStart)
  50735. {
  50736. moveScrollbarInPages (-1);
  50737. startTimer (400);
  50738. }
  50739. else if (dragStartMousePos >= thumbStart + thumbSize)
  50740. {
  50741. moveScrollbarInPages (1);
  50742. startTimer (400);
  50743. }
  50744. else
  50745. {
  50746. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50747. && (thumbAreaSize > thumbSize);
  50748. }
  50749. }
  50750. void ScrollBar::mouseDrag (const MouseEvent& e)
  50751. {
  50752. const int mousePos = vertical ? e.y : e.x;
  50753. if (isDraggingThumb && lastMousePos != mousePos)
  50754. {
  50755. const int deltaPixels = mousePos - dragStartMousePos;
  50756. setCurrentRangeStart (dragStartRange
  50757. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50758. / (thumbAreaSize - thumbSize));
  50759. }
  50760. lastMousePos = mousePos;
  50761. }
  50762. void ScrollBar::mouseUp (const MouseEvent&)
  50763. {
  50764. isDraggingThumb = false;
  50765. stopTimer();
  50766. repaint();
  50767. }
  50768. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50769. float wheelIncrementX,
  50770. float wheelIncrementY)
  50771. {
  50772. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50773. if (increment < 0)
  50774. increment = jmin (increment * 10.0f, -1.0f);
  50775. else if (increment > 0)
  50776. increment = jmax (increment * 10.0f, 1.0f);
  50777. setCurrentRange (visibleRange - singleStepSize * increment);
  50778. }
  50779. void ScrollBar::timerCallback()
  50780. {
  50781. if (isMouseButtonDown())
  50782. {
  50783. startTimer (40);
  50784. if (lastMousePos < thumbStart)
  50785. setCurrentRange (visibleRange - visibleRange.getLength());
  50786. else if (lastMousePos > thumbStart + thumbSize)
  50787. setCurrentRangeStart (visibleRange.getEnd());
  50788. }
  50789. else
  50790. {
  50791. stopTimer();
  50792. }
  50793. }
  50794. bool ScrollBar::keyPressed (const KeyPress& key)
  50795. {
  50796. if (! isVisible())
  50797. return false;
  50798. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50799. moveScrollbarInSteps (-1);
  50800. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50801. moveScrollbarInSteps (1);
  50802. else if (key.isKeyCode (KeyPress::pageUpKey))
  50803. moveScrollbarInPages (-1);
  50804. else if (key.isKeyCode (KeyPress::pageDownKey))
  50805. moveScrollbarInPages (1);
  50806. else if (key.isKeyCode (KeyPress::homeKey))
  50807. scrollToTop();
  50808. else if (key.isKeyCode (KeyPress::endKey))
  50809. scrollToBottom();
  50810. else
  50811. return false;
  50812. return true;
  50813. }
  50814. END_JUCE_NAMESPACE
  50815. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50816. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50817. BEGIN_JUCE_NAMESPACE
  50818. StretchableLayoutManager::StretchableLayoutManager()
  50819. : totalSize (0)
  50820. {
  50821. }
  50822. StretchableLayoutManager::~StretchableLayoutManager()
  50823. {
  50824. }
  50825. void StretchableLayoutManager::clearAllItems()
  50826. {
  50827. items.clear();
  50828. totalSize = 0;
  50829. }
  50830. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  50831. const double minimumSize,
  50832. const double maximumSize,
  50833. const double preferredSize)
  50834. {
  50835. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  50836. if (layout == 0)
  50837. {
  50838. layout = new ItemLayoutProperties();
  50839. layout->itemIndex = itemIndex;
  50840. int i;
  50841. for (i = 0; i < items.size(); ++i)
  50842. if (items.getUnchecked (i)->itemIndex > itemIndex)
  50843. break;
  50844. items.insert (i, layout);
  50845. }
  50846. layout->minSize = minimumSize;
  50847. layout->maxSize = maximumSize;
  50848. layout->preferredSize = preferredSize;
  50849. layout->currentSize = 0;
  50850. }
  50851. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  50852. double& minimumSize,
  50853. double& maximumSize,
  50854. double& preferredSize) const
  50855. {
  50856. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50857. if (layout != 0)
  50858. {
  50859. minimumSize = layout->minSize;
  50860. maximumSize = layout->maxSize;
  50861. preferredSize = layout->preferredSize;
  50862. return true;
  50863. }
  50864. return false;
  50865. }
  50866. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  50867. {
  50868. totalSize = newTotalSize;
  50869. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  50870. }
  50871. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  50872. {
  50873. int pos = 0;
  50874. for (int i = 0; i < itemIndex; ++i)
  50875. {
  50876. const ItemLayoutProperties* const layout = getInfoFor (i);
  50877. if (layout != 0)
  50878. pos += layout->currentSize;
  50879. }
  50880. return pos;
  50881. }
  50882. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  50883. {
  50884. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50885. if (layout != 0)
  50886. return layout->currentSize;
  50887. return 0;
  50888. }
  50889. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50890. {
  50891. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50892. if (layout != 0)
  50893. return -layout->currentSize / (double) totalSize;
  50894. return 0;
  50895. }
  50896. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50897. int newPosition)
  50898. {
  50899. for (int i = items.size(); --i >= 0;)
  50900. {
  50901. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50902. if (layout->itemIndex == itemIndex)
  50903. {
  50904. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50905. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50906. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  50907. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  50908. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  50909. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  50910. endPos += layout->currentSize;
  50911. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  50912. updatePrefSizesToMatchCurrentPositions();
  50913. break;
  50914. }
  50915. }
  50916. }
  50917. void StretchableLayoutManager::layOutComponents (Component** const components,
  50918. int numComponents,
  50919. int x, int y, int w, int h,
  50920. const bool vertically,
  50921. const bool resizeOtherDimension)
  50922. {
  50923. setTotalSize (vertically ? h : w);
  50924. int pos = vertically ? y : x;
  50925. for (int i = 0; i < numComponents; ++i)
  50926. {
  50927. const ItemLayoutProperties* const layout = getInfoFor (i);
  50928. if (layout != 0)
  50929. {
  50930. Component* const c = components[i];
  50931. if (c != 0)
  50932. {
  50933. if (i == numComponents - 1)
  50934. {
  50935. // if it's the last item, crop it to exactly fit the available space..
  50936. if (resizeOtherDimension)
  50937. {
  50938. if (vertically)
  50939. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  50940. else
  50941. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  50942. }
  50943. else
  50944. {
  50945. if (vertically)
  50946. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  50947. else
  50948. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  50949. }
  50950. }
  50951. else
  50952. {
  50953. if (resizeOtherDimension)
  50954. {
  50955. if (vertically)
  50956. c->setBounds (x, pos, w, layout->currentSize);
  50957. else
  50958. c->setBounds (pos, y, layout->currentSize, h);
  50959. }
  50960. else
  50961. {
  50962. if (vertically)
  50963. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  50964. else
  50965. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  50966. }
  50967. }
  50968. }
  50969. pos += layout->currentSize;
  50970. }
  50971. }
  50972. }
  50973. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  50974. {
  50975. for (int i = items.size(); --i >= 0;)
  50976. if (items.getUnchecked(i)->itemIndex == itemIndex)
  50977. return items.getUnchecked(i);
  50978. return 0;
  50979. }
  50980. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  50981. const int endIndex,
  50982. const int availableSpace,
  50983. int startPos)
  50984. {
  50985. // calculate the total sizes
  50986. int i;
  50987. double totalIdealSize = 0.0;
  50988. int totalMinimums = 0;
  50989. for (i = startIndex; i < endIndex; ++i)
  50990. {
  50991. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50992. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  50993. totalMinimums += layout->currentSize;
  50994. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  50995. }
  50996. if (totalIdealSize <= 0)
  50997. totalIdealSize = 1.0;
  50998. // now calc the best sizes..
  50999. int extraSpace = availableSpace - totalMinimums;
  51000. while (extraSpace > 0)
  51001. {
  51002. int numWantingMoreSpace = 0;
  51003. int numHavingTakenExtraSpace = 0;
  51004. // first figure out how many comps want a slice of the extra space..
  51005. for (i = startIndex; i < endIndex; ++i)
  51006. {
  51007. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51008. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51009. const int bestSize = jlimit (layout->currentSize,
  51010. jmax (layout->currentSize,
  51011. sizeToRealSize (layout->maxSize, totalSize)),
  51012. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51013. if (bestSize > layout->currentSize)
  51014. ++numWantingMoreSpace;
  51015. }
  51016. // ..share out the extra space..
  51017. for (i = startIndex; i < endIndex; ++i)
  51018. {
  51019. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51020. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51021. int bestSize = jlimit (layout->currentSize,
  51022. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51023. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51024. const int extraWanted = bestSize - layout->currentSize;
  51025. if (extraWanted > 0)
  51026. {
  51027. const int extraAllowed = jmin (extraWanted,
  51028. extraSpace / jmax (1, numWantingMoreSpace));
  51029. if (extraAllowed > 0)
  51030. {
  51031. ++numHavingTakenExtraSpace;
  51032. --numWantingMoreSpace;
  51033. layout->currentSize += extraAllowed;
  51034. extraSpace -= extraAllowed;
  51035. }
  51036. }
  51037. }
  51038. if (numHavingTakenExtraSpace <= 0)
  51039. break;
  51040. }
  51041. // ..and calculate the end position
  51042. for (i = startIndex; i < endIndex; ++i)
  51043. {
  51044. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51045. startPos += layout->currentSize;
  51046. }
  51047. return startPos;
  51048. }
  51049. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51050. const int endIndex) const
  51051. {
  51052. int totalMinimums = 0;
  51053. for (int i = startIndex; i < endIndex; ++i)
  51054. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51055. return totalMinimums;
  51056. }
  51057. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51058. {
  51059. int totalMaximums = 0;
  51060. for (int i = startIndex; i < endIndex; ++i)
  51061. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51062. return totalMaximums;
  51063. }
  51064. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51065. {
  51066. for (int i = 0; i < items.size(); ++i)
  51067. {
  51068. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51069. layout->preferredSize
  51070. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51071. : getItemCurrentAbsoluteSize (i);
  51072. }
  51073. }
  51074. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51075. {
  51076. if (size < 0)
  51077. size *= -totalSpace;
  51078. return roundToInt (size);
  51079. }
  51080. END_JUCE_NAMESPACE
  51081. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51082. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51083. BEGIN_JUCE_NAMESPACE
  51084. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51085. const int itemIndex_,
  51086. const bool isVertical_)
  51087. : layout (layout_),
  51088. itemIndex (itemIndex_),
  51089. isVertical (isVertical_)
  51090. {
  51091. setRepaintsOnMouseActivity (true);
  51092. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51093. : MouseCursor::UpDownResizeCursor));
  51094. }
  51095. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51096. {
  51097. }
  51098. void StretchableLayoutResizerBar::paint (Graphics& g)
  51099. {
  51100. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51101. getWidth(), getHeight(),
  51102. isVertical,
  51103. isMouseOver(),
  51104. isMouseButtonDown());
  51105. }
  51106. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51107. {
  51108. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51109. }
  51110. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51111. {
  51112. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51113. : e.getDistanceFromDragStartY());
  51114. if (layout->getItemCurrentPosition (itemIndex) != desiredPos)
  51115. {
  51116. layout->setItemPosition (itemIndex, desiredPos);
  51117. hasBeenMoved();
  51118. }
  51119. }
  51120. void StretchableLayoutResizerBar::hasBeenMoved()
  51121. {
  51122. if (getParentComponent() != 0)
  51123. getParentComponent()->resized();
  51124. }
  51125. END_JUCE_NAMESPACE
  51126. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51127. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51128. BEGIN_JUCE_NAMESPACE
  51129. StretchableObjectResizer::StretchableObjectResizer()
  51130. {
  51131. }
  51132. StretchableObjectResizer::~StretchableObjectResizer()
  51133. {
  51134. }
  51135. void StretchableObjectResizer::addItem (const double size,
  51136. const double minSize, const double maxSize,
  51137. const int order)
  51138. {
  51139. // the order must be >= 0 but less than the maximum integer value.
  51140. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51141. Item* const item = new Item();
  51142. item->size = size;
  51143. item->minSize = minSize;
  51144. item->maxSize = maxSize;
  51145. item->order = order;
  51146. items.add (item);
  51147. }
  51148. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51149. {
  51150. const Item* const it = items [index];
  51151. return it != 0 ? it->size : 0;
  51152. }
  51153. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51154. {
  51155. int order = 0;
  51156. for (;;)
  51157. {
  51158. double currentSize = 0;
  51159. double minSize = 0;
  51160. double maxSize = 0;
  51161. int nextHighestOrder = std::numeric_limits<int>::max();
  51162. for (int i = 0; i < items.size(); ++i)
  51163. {
  51164. const Item* const it = items.getUnchecked(i);
  51165. currentSize += it->size;
  51166. if (it->order <= order)
  51167. {
  51168. minSize += it->minSize;
  51169. maxSize += it->maxSize;
  51170. }
  51171. else
  51172. {
  51173. minSize += it->size;
  51174. maxSize += it->size;
  51175. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51176. }
  51177. }
  51178. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51179. if (thisIterationTarget >= currentSize)
  51180. {
  51181. const double availableExtraSpace = maxSize - currentSize;
  51182. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51183. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51184. for (int i = 0; i < items.size(); ++i)
  51185. {
  51186. Item* const it = items.getUnchecked(i);
  51187. if (it->order <= order)
  51188. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51189. }
  51190. }
  51191. else
  51192. {
  51193. const double amountOfSlack = currentSize - minSize;
  51194. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51195. const double scale = targetAmountOfSlack / amountOfSlack;
  51196. for (int i = 0; i < items.size(); ++i)
  51197. {
  51198. Item* const it = items.getUnchecked(i);
  51199. if (it->order <= order)
  51200. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51201. }
  51202. }
  51203. if (nextHighestOrder < std::numeric_limits<int>::max())
  51204. order = nextHighestOrder;
  51205. else
  51206. break;
  51207. }
  51208. }
  51209. END_JUCE_NAMESPACE
  51210. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51211. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51212. BEGIN_JUCE_NAMESPACE
  51213. TabBarButton::TabBarButton (const String& name, TabbedButtonBar& owner_)
  51214. : Button (name),
  51215. owner (owner_),
  51216. overlapPixels (0)
  51217. {
  51218. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51219. setComponentEffect (&shadow);
  51220. setWantsKeyboardFocus (false);
  51221. }
  51222. TabBarButton::~TabBarButton()
  51223. {
  51224. }
  51225. int TabBarButton::getIndex() const
  51226. {
  51227. return owner.indexOfTabButton (this);
  51228. }
  51229. void TabBarButton::paintButton (Graphics& g,
  51230. bool isMouseOverButton,
  51231. bool isButtonDown)
  51232. {
  51233. const Rectangle<int> area (getActiveArea());
  51234. g.setOrigin (area.getX(), area.getY());
  51235. getLookAndFeel()
  51236. .drawTabButton (g, area.getWidth(), area.getHeight(),
  51237. owner.getTabBackgroundColour (getIndex()),
  51238. getIndex(), getButtonText(), *this,
  51239. owner.getOrientation(),
  51240. isMouseOverButton, isButtonDown,
  51241. getToggleState());
  51242. }
  51243. void TabBarButton::clicked (const ModifierKeys& mods)
  51244. {
  51245. if (mods.isPopupMenu())
  51246. owner.popupMenuClickOnTab (getIndex(), getButtonText());
  51247. else
  51248. owner.setCurrentTabIndex (getIndex());
  51249. }
  51250. bool TabBarButton::hitTest (int mx, int my)
  51251. {
  51252. const Rectangle<int> area (getActiveArea());
  51253. if (owner.getOrientation() == TabbedButtonBar::TabsAtLeft
  51254. || owner.getOrientation() == TabbedButtonBar::TabsAtRight)
  51255. {
  51256. if (isPositiveAndBelow (mx, getWidth())
  51257. && my >= area.getY() + overlapPixels
  51258. && my < area.getBottom() - overlapPixels)
  51259. return true;
  51260. }
  51261. else
  51262. {
  51263. if (mx >= area.getX() + overlapPixels && mx < area.getRight() - overlapPixels
  51264. && isPositiveAndBelow (my, getHeight()))
  51265. return true;
  51266. }
  51267. Path p;
  51268. getLookAndFeel()
  51269. .createTabButtonShape (p, area.getWidth(), area.getHeight(), getIndex(), getButtonText(), *this,
  51270. owner.getOrientation(), false, false, getToggleState());
  51271. return p.contains ((float) (mx - area.getX()),
  51272. (float) (my - area.getY()));
  51273. }
  51274. int TabBarButton::getBestTabLength (const int depth)
  51275. {
  51276. return jlimit (depth * 2,
  51277. depth * 7,
  51278. getLookAndFeel().getTabButtonBestWidth (getIndex(), getButtonText(), depth, *this));
  51279. }
  51280. const Rectangle<int> TabBarButton::getActiveArea()
  51281. {
  51282. Rectangle<int> r (getLocalBounds());
  51283. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51284. if (owner.getOrientation() != TabbedButtonBar::TabsAtLeft) r.removeFromRight (spaceAroundImage);
  51285. if (owner.getOrientation() != TabbedButtonBar::TabsAtRight) r.removeFromLeft (spaceAroundImage);
  51286. if (owner.getOrientation() != TabbedButtonBar::TabsAtBottom) r.removeFromTop (spaceAroundImage);
  51287. if (owner.getOrientation() != TabbedButtonBar::TabsAtTop) r.removeFromBottom (spaceAroundImage);
  51288. return r;
  51289. }
  51290. class TabbedButtonBar::BehindFrontTabComp : public Component,
  51291. public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  51292. {
  51293. public:
  51294. BehindFrontTabComp (TabbedButtonBar& owner_)
  51295. : owner (owner_)
  51296. {
  51297. setInterceptsMouseClicks (false, false);
  51298. }
  51299. void paint (Graphics& g)
  51300. {
  51301. getLookAndFeel().drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51302. owner, owner.getOrientation());
  51303. }
  51304. void enablementChanged()
  51305. {
  51306. repaint();
  51307. }
  51308. void buttonClicked (Button*)
  51309. {
  51310. owner.showExtraItemsMenu();
  51311. }
  51312. private:
  51313. TabbedButtonBar& owner;
  51314. JUCE_DECLARE_NON_COPYABLE (BehindFrontTabComp);
  51315. };
  51316. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51317. : orientation (orientation_),
  51318. minimumScale (0.7),
  51319. currentTabIndex (-1)
  51320. {
  51321. setInterceptsMouseClicks (false, true);
  51322. addAndMakeVisible (behindFrontTab = new BehindFrontTabComp (*this));
  51323. setFocusContainer (true);
  51324. }
  51325. TabbedButtonBar::~TabbedButtonBar()
  51326. {
  51327. tabs.clear();
  51328. extraTabsButton = 0;
  51329. }
  51330. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51331. {
  51332. orientation = newOrientation;
  51333. for (int i = getNumChildComponents(); --i >= 0;)
  51334. getChildComponent (i)->resized();
  51335. resized();
  51336. }
  51337. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int /*index*/)
  51338. {
  51339. return new TabBarButton (name, *this);
  51340. }
  51341. void TabbedButtonBar::setMinimumTabScaleFactor (double newMinimumScale)
  51342. {
  51343. minimumScale = newMinimumScale;
  51344. resized();
  51345. }
  51346. void TabbedButtonBar::clearTabs()
  51347. {
  51348. tabs.clear();
  51349. extraTabsButton = 0;
  51350. setCurrentTabIndex (-1);
  51351. }
  51352. void TabbedButtonBar::addTab (const String& tabName,
  51353. const Colour& tabBackgroundColour,
  51354. int insertIndex)
  51355. {
  51356. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51357. if (tabName.isNotEmpty())
  51358. {
  51359. if (! isPositiveAndBelow (insertIndex, tabs.size()))
  51360. insertIndex = tabs.size();
  51361. TabInfo* newTab = new TabInfo();
  51362. newTab->name = tabName;
  51363. newTab->colour = tabBackgroundColour;
  51364. newTab->component = createTabButton (tabName, insertIndex);
  51365. jassert (newTab->component != 0);
  51366. tabs.insert (insertIndex, newTab);
  51367. addAndMakeVisible (newTab->component, insertIndex);
  51368. resized();
  51369. if (currentTabIndex < 0)
  51370. setCurrentTabIndex (0);
  51371. }
  51372. }
  51373. void TabbedButtonBar::setTabName (const int tabIndex, const String& newName)
  51374. {
  51375. TabInfo* const tab = tabs [tabIndex];
  51376. if (tab != 0 && tab->name != newName)
  51377. {
  51378. tab->name = newName;
  51379. tab->component->setButtonText (newName);
  51380. resized();
  51381. }
  51382. }
  51383. void TabbedButtonBar::removeTab (const int tabIndex)
  51384. {
  51385. if (tabs [tabIndex] != 0)
  51386. {
  51387. const int oldTabIndex = currentTabIndex;
  51388. if (currentTabIndex == tabIndex)
  51389. currentTabIndex = -1;
  51390. tabs.remove (tabIndex);
  51391. resized();
  51392. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51393. }
  51394. }
  51395. void TabbedButtonBar::moveTab (const int currentIndex, const int newIndex)
  51396. {
  51397. tabs.move (currentIndex, newIndex);
  51398. resized();
  51399. }
  51400. int TabbedButtonBar::getNumTabs() const
  51401. {
  51402. return tabs.size();
  51403. }
  51404. const String TabbedButtonBar::getCurrentTabName() const
  51405. {
  51406. TabInfo* tab = tabs [currentTabIndex];
  51407. return tab == 0 ? String::empty : tab->name;
  51408. }
  51409. const StringArray TabbedButtonBar::getTabNames() const
  51410. {
  51411. StringArray names;
  51412. for (int i = 0; i < tabs.size(); ++i)
  51413. names.add (tabs.getUnchecked(i)->name);
  51414. return names;
  51415. }
  51416. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51417. {
  51418. if (currentTabIndex != newIndex)
  51419. {
  51420. if (! isPositiveAndBelow (newIndex, tabs.size()))
  51421. newIndex = -1;
  51422. currentTabIndex = newIndex;
  51423. for (int i = 0; i < tabs.size(); ++i)
  51424. {
  51425. TabBarButton* tb = tabs.getUnchecked(i)->component;
  51426. tb->setToggleState (i == newIndex, false);
  51427. }
  51428. resized();
  51429. if (sendChangeMessage_)
  51430. sendChangeMessage();
  51431. currentTabChanged (newIndex, getCurrentTabName());
  51432. }
  51433. }
  51434. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51435. {
  51436. TabInfo* const tab = tabs[index];
  51437. return tab == 0 ? 0 : static_cast <TabBarButton*> (tab->component);
  51438. }
  51439. int TabbedButtonBar::indexOfTabButton (const TabBarButton* button) const
  51440. {
  51441. for (int i = tabs.size(); --i >= 0;)
  51442. if (tabs.getUnchecked(i)->component == button)
  51443. return i;
  51444. return -1;
  51445. }
  51446. void TabbedButtonBar::lookAndFeelChanged()
  51447. {
  51448. extraTabsButton = 0;
  51449. resized();
  51450. }
  51451. void TabbedButtonBar::resized()
  51452. {
  51453. int depth = getWidth();
  51454. int length = getHeight();
  51455. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51456. swapVariables (depth, length);
  51457. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51458. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51459. int i, totalLength = overlap;
  51460. int numVisibleButtons = tabs.size();
  51461. for (i = 0; i < tabs.size(); ++i)
  51462. {
  51463. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51464. totalLength += tb->getBestTabLength (depth) - overlap;
  51465. tb->overlapPixels = overlap / 2;
  51466. }
  51467. double scale = 1.0;
  51468. if (totalLength > length)
  51469. scale = jmax (minimumScale, length / (double) totalLength);
  51470. const bool isTooBig = totalLength * scale > length;
  51471. int tabsButtonPos = 0;
  51472. if (isTooBig)
  51473. {
  51474. if (extraTabsButton == 0)
  51475. {
  51476. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51477. extraTabsButton->addListener (behindFrontTab);
  51478. extraTabsButton->setAlwaysOnTop (true);
  51479. extraTabsButton->setTriggeredOnMouseDown (true);
  51480. }
  51481. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51482. extraTabsButton->setSize (buttonSize, buttonSize);
  51483. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51484. {
  51485. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51486. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51487. }
  51488. else
  51489. {
  51490. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51491. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51492. }
  51493. totalLength = 0;
  51494. for (i = 0; i < tabs.size(); ++i)
  51495. {
  51496. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51497. const int newLength = totalLength + tb->getBestTabLength (depth);
  51498. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51499. {
  51500. totalLength += overlap;
  51501. break;
  51502. }
  51503. numVisibleButtons = i + 1;
  51504. totalLength = newLength - overlap;
  51505. }
  51506. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51507. }
  51508. else
  51509. {
  51510. extraTabsButton = 0;
  51511. }
  51512. int pos = 0;
  51513. TabBarButton* frontTab = 0;
  51514. for (i = 0; i < tabs.size(); ++i)
  51515. {
  51516. TabBarButton* const tb = getTabButton (i);
  51517. if (tb != 0)
  51518. {
  51519. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51520. if (i < numVisibleButtons)
  51521. {
  51522. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51523. tb->setBounds (pos, 0, bestLength, getHeight());
  51524. else
  51525. tb->setBounds (0, pos, getWidth(), bestLength);
  51526. tb->toBack();
  51527. if (i == currentTabIndex)
  51528. frontTab = tb;
  51529. tb->setVisible (true);
  51530. }
  51531. else
  51532. {
  51533. tb->setVisible (false);
  51534. }
  51535. pos += bestLength - overlap;
  51536. }
  51537. }
  51538. behindFrontTab->setBounds (getLocalBounds());
  51539. if (frontTab != 0)
  51540. {
  51541. frontTab->toFront (false);
  51542. behindFrontTab->toBehind (frontTab);
  51543. }
  51544. }
  51545. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51546. {
  51547. TabInfo* const tab = tabs [tabIndex];
  51548. return tab == 0 ? Colours::white : tab->colour;
  51549. }
  51550. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51551. {
  51552. TabInfo* const tab = tabs [tabIndex];
  51553. if (tab != 0 && tab->colour != newColour)
  51554. {
  51555. tab->colour = newColour;
  51556. repaint();
  51557. }
  51558. }
  51559. void TabbedButtonBar::showExtraItemsMenu()
  51560. {
  51561. PopupMenu m;
  51562. for (int i = 0; i < tabs.size(); ++i)
  51563. {
  51564. const TabInfo* const tab = tabs.getUnchecked(i);
  51565. if (! tab->component->isVisible())
  51566. m.addItem (i + 1, tab->name, true, i == currentTabIndex);
  51567. }
  51568. const int res = m.showAt (extraTabsButton);
  51569. if (res != 0)
  51570. setCurrentTabIndex (res - 1);
  51571. }
  51572. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51573. {
  51574. }
  51575. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51576. {
  51577. }
  51578. END_JUCE_NAMESPACE
  51579. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51580. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51581. BEGIN_JUCE_NAMESPACE
  51582. namespace TabbedComponentHelpers
  51583. {
  51584. const Identifier deleteComponentId ("deleteByTabComp_");
  51585. void deleteIfNecessary (Component* const comp)
  51586. {
  51587. if (comp != 0 && (bool) comp->getProperties() [deleteComponentId])
  51588. delete comp;
  51589. }
  51590. const Rectangle<int> getTabArea (Rectangle<int>& content, BorderSize<int>& outline,
  51591. const TabbedButtonBar::Orientation orientation, const int tabDepth)
  51592. {
  51593. switch (orientation)
  51594. {
  51595. case TabbedButtonBar::TabsAtTop: outline.setTop (0); return content.removeFromTop (tabDepth);
  51596. case TabbedButtonBar::TabsAtBottom: outline.setBottom (0); return content.removeFromBottom (tabDepth);
  51597. case TabbedButtonBar::TabsAtLeft: outline.setLeft (0); return content.removeFromLeft (tabDepth);
  51598. case TabbedButtonBar::TabsAtRight: outline.setRight (0); return content.removeFromRight (tabDepth);
  51599. default: jassertfalse; break;
  51600. }
  51601. return Rectangle<int>();
  51602. }
  51603. }
  51604. class TabbedComponent::ButtonBar : public TabbedButtonBar
  51605. {
  51606. public:
  51607. ButtonBar (TabbedComponent& owner_, const TabbedButtonBar::Orientation orientation_)
  51608. : TabbedButtonBar (orientation_),
  51609. owner (owner_)
  51610. {
  51611. }
  51612. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51613. {
  51614. owner.changeCallback (newCurrentTabIndex, newTabName);
  51615. }
  51616. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51617. {
  51618. owner.popupMenuClickOnTab (tabIndex, tabName);
  51619. }
  51620. const Colour getTabBackgroundColour (const int tabIndex)
  51621. {
  51622. return owner.tabs->getTabBackgroundColour (tabIndex);
  51623. }
  51624. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51625. {
  51626. return owner.createTabButton (tabName, tabIndex);
  51627. }
  51628. private:
  51629. TabbedComponent& owner;
  51630. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonBar);
  51631. };
  51632. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51633. : tabDepth (30),
  51634. outlineThickness (1),
  51635. edgeIndent (0)
  51636. {
  51637. addAndMakeVisible (tabs = new ButtonBar (*this, orientation));
  51638. }
  51639. TabbedComponent::~TabbedComponent()
  51640. {
  51641. clearTabs();
  51642. tabs = 0;
  51643. }
  51644. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51645. {
  51646. tabs->setOrientation (orientation);
  51647. resized();
  51648. }
  51649. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51650. {
  51651. return tabs->getOrientation();
  51652. }
  51653. void TabbedComponent::setTabBarDepth (const int newDepth)
  51654. {
  51655. if (tabDepth != newDepth)
  51656. {
  51657. tabDepth = newDepth;
  51658. resized();
  51659. }
  51660. }
  51661. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int /*tabIndex*/)
  51662. {
  51663. return new TabBarButton (tabName, *tabs);
  51664. }
  51665. void TabbedComponent::clearTabs()
  51666. {
  51667. if (panelComponent != 0)
  51668. {
  51669. panelComponent->setVisible (false);
  51670. removeChildComponent (panelComponent);
  51671. panelComponent = 0;
  51672. }
  51673. tabs->clearTabs();
  51674. for (int i = contentComponents.size(); --i >= 0;)
  51675. TabbedComponentHelpers::deleteIfNecessary (contentComponents.getReference (i));
  51676. contentComponents.clear();
  51677. }
  51678. void TabbedComponent::addTab (const String& tabName,
  51679. const Colour& tabBackgroundColour,
  51680. Component* const contentComponent,
  51681. const bool deleteComponentWhenNotNeeded,
  51682. const int insertIndex)
  51683. {
  51684. contentComponents.insert (insertIndex, WeakReference<Component> (contentComponent));
  51685. if (deleteComponentWhenNotNeeded && contentComponent != 0)
  51686. contentComponent->getProperties().set (TabbedComponentHelpers::deleteComponentId, true);
  51687. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51688. }
  51689. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51690. {
  51691. tabs->setTabName (tabIndex, newName);
  51692. }
  51693. void TabbedComponent::removeTab (const int tabIndex)
  51694. {
  51695. if (isPositiveAndBelow (tabIndex, contentComponents.size()))
  51696. {
  51697. TabbedComponentHelpers::deleteIfNecessary (contentComponents.getReference (tabIndex));
  51698. contentComponents.remove (tabIndex);
  51699. tabs->removeTab (tabIndex);
  51700. }
  51701. }
  51702. int TabbedComponent::getNumTabs() const
  51703. {
  51704. return tabs->getNumTabs();
  51705. }
  51706. const StringArray TabbedComponent::getTabNames() const
  51707. {
  51708. return tabs->getTabNames();
  51709. }
  51710. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51711. {
  51712. return contentComponents [tabIndex];
  51713. }
  51714. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51715. {
  51716. return tabs->getTabBackgroundColour (tabIndex);
  51717. }
  51718. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51719. {
  51720. tabs->setTabBackgroundColour (tabIndex, newColour);
  51721. if (getCurrentTabIndex() == tabIndex)
  51722. repaint();
  51723. }
  51724. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51725. {
  51726. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51727. }
  51728. int TabbedComponent::getCurrentTabIndex() const
  51729. {
  51730. return tabs->getCurrentTabIndex();
  51731. }
  51732. const String TabbedComponent::getCurrentTabName() const
  51733. {
  51734. return tabs->getCurrentTabName();
  51735. }
  51736. void TabbedComponent::setOutline (const int thickness)
  51737. {
  51738. outlineThickness = thickness;
  51739. resized();
  51740. repaint();
  51741. }
  51742. void TabbedComponent::setIndent (const int indentThickness)
  51743. {
  51744. edgeIndent = indentThickness;
  51745. resized();
  51746. repaint();
  51747. }
  51748. void TabbedComponent::paint (Graphics& g)
  51749. {
  51750. g.fillAll (findColour (backgroundColourId));
  51751. Rectangle<int> content (getLocalBounds());
  51752. BorderSize<int> outline (outlineThickness);
  51753. TabbedComponentHelpers::getTabArea (content, outline, getOrientation(), tabDepth);
  51754. g.reduceClipRegion (content);
  51755. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51756. if (outlineThickness > 0)
  51757. {
  51758. RectangleList rl (content);
  51759. rl.subtract (outline.subtractedFrom (content));
  51760. g.reduceClipRegion (rl);
  51761. g.fillAll (findColour (outlineColourId));
  51762. }
  51763. }
  51764. void TabbedComponent::resized()
  51765. {
  51766. Rectangle<int> content (getLocalBounds());
  51767. BorderSize<int> outline (outlineThickness);
  51768. tabs->setBounds (TabbedComponentHelpers::getTabArea (content, outline, getOrientation(), tabDepth));
  51769. content = BorderSize<int> (edgeIndent).subtractedFrom (outline.subtractedFrom (content));
  51770. for (int i = contentComponents.size(); --i >= 0;)
  51771. if (contentComponents.getReference (i) != 0)
  51772. contentComponents.getReference (i)->setBounds (content);
  51773. }
  51774. void TabbedComponent::lookAndFeelChanged()
  51775. {
  51776. for (int i = contentComponents.size(); --i >= 0;)
  51777. if (contentComponents.getReference (i) != 0)
  51778. contentComponents.getReference (i)->lookAndFeelChanged();
  51779. }
  51780. void TabbedComponent::changeCallback (const int newCurrentTabIndex, const String& newTabName)
  51781. {
  51782. if (panelComponent != 0)
  51783. {
  51784. panelComponent->setVisible (false);
  51785. removeChildComponent (panelComponent);
  51786. panelComponent = 0;
  51787. }
  51788. if (getCurrentTabIndex() >= 0)
  51789. {
  51790. panelComponent = getTabContentComponent (getCurrentTabIndex());
  51791. if (panelComponent != 0)
  51792. {
  51793. // do these ops as two stages instead of addAndMakeVisible() so that the
  51794. // component has always got a parent when it gets the visibilityChanged() callback
  51795. addChildComponent (panelComponent);
  51796. panelComponent->setVisible (true);
  51797. panelComponent->toFront (true);
  51798. }
  51799. repaint();
  51800. }
  51801. resized();
  51802. currentTabChanged (newCurrentTabIndex, newTabName);
  51803. }
  51804. void TabbedComponent::currentTabChanged (const int, const String&) {}
  51805. void TabbedComponent::popupMenuClickOnTab (const int, const String&) {}
  51806. END_JUCE_NAMESPACE
  51807. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  51808. /*** Start of inlined file: juce_Viewport.cpp ***/
  51809. BEGIN_JUCE_NAMESPACE
  51810. Viewport::Viewport (const String& componentName)
  51811. : Component (componentName),
  51812. scrollBarThickness (0),
  51813. singleStepX (16),
  51814. singleStepY (16),
  51815. showHScrollbar (true),
  51816. showVScrollbar (true),
  51817. verticalScrollBar (true),
  51818. horizontalScrollBar (false)
  51819. {
  51820. // content holder is used to clip the contents so they don't overlap the scrollbars
  51821. addAndMakeVisible (&contentHolder);
  51822. contentHolder.setInterceptsMouseClicks (false, true);
  51823. addChildComponent (&verticalScrollBar);
  51824. addChildComponent (&horizontalScrollBar);
  51825. verticalScrollBar.addListener (this);
  51826. horizontalScrollBar.addListener (this);
  51827. setInterceptsMouseClicks (false, true);
  51828. setWantsKeyboardFocus (true);
  51829. }
  51830. Viewport::~Viewport()
  51831. {
  51832. deleteContentComp();
  51833. }
  51834. void Viewport::visibleAreaChanged (const Rectangle<int>&)
  51835. {
  51836. }
  51837. void Viewport::deleteContentComp()
  51838. {
  51839. // This sets the content comp to a null pointer before deleting the old one, in case
  51840. // anything tries to use the old one while it's in mid-deletion..
  51841. ScopedPointer<Component> oldCompDeleter (contentComp);
  51842. contentComp = 0;
  51843. }
  51844. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51845. {
  51846. if (contentComp.get() != newViewedComponent)
  51847. {
  51848. deleteContentComp();
  51849. contentComp = newViewedComponent;
  51850. if (contentComp != 0)
  51851. {
  51852. contentHolder.addAndMakeVisible (contentComp);
  51853. setViewPosition (0, 0);
  51854. contentComp->addComponentListener (this);
  51855. }
  51856. updateVisibleArea();
  51857. }
  51858. }
  51859. int Viewport::getMaximumVisibleWidth() const { return contentHolder.getWidth(); }
  51860. int Viewport::getMaximumVisibleHeight() const { return contentHolder.getHeight(); }
  51861. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51862. {
  51863. if (contentComp != 0)
  51864. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  51865. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  51866. }
  51867. void Viewport::setViewPosition (const Point<int>& newPosition)
  51868. {
  51869. setViewPosition (newPosition.getX(), newPosition.getY());
  51870. }
  51871. void Viewport::setViewPositionProportionately (const double x, const double y)
  51872. {
  51873. if (contentComp != 0)
  51874. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51875. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51876. }
  51877. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  51878. {
  51879. if (contentComp != 0)
  51880. {
  51881. int dx = 0, dy = 0;
  51882. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  51883. {
  51884. if (mouseX < activeBorderThickness)
  51885. dx = activeBorderThickness - mouseX;
  51886. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  51887. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  51888. if (dx < 0)
  51889. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  51890. else
  51891. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51892. }
  51893. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  51894. {
  51895. if (mouseY < activeBorderThickness)
  51896. dy = activeBorderThickness - mouseY;
  51897. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  51898. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  51899. if (dy < 0)
  51900. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  51901. else
  51902. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  51903. }
  51904. if (dx != 0 || dy != 0)
  51905. {
  51906. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  51907. contentComp->getY() + dy);
  51908. return true;
  51909. }
  51910. }
  51911. return false;
  51912. }
  51913. void Viewport::componentMovedOrResized (Component&, bool, bool)
  51914. {
  51915. updateVisibleArea();
  51916. }
  51917. void Viewport::resized()
  51918. {
  51919. updateVisibleArea();
  51920. }
  51921. void Viewport::updateVisibleArea()
  51922. {
  51923. const int scrollbarWidth = getScrollBarThickness();
  51924. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  51925. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  51926. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  51927. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  51928. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  51929. Rectangle<int> contentArea (getLocalBounds());
  51930. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  51931. {
  51932. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  51933. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  51934. if (vBarVisible)
  51935. contentArea.setWidth (getWidth() - scrollbarWidth);
  51936. if (hBarVisible)
  51937. contentArea.setHeight (getHeight() - scrollbarWidth);
  51938. if (! contentArea.contains (contentComp->getBounds()))
  51939. {
  51940. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  51941. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  51942. }
  51943. }
  51944. if (vBarVisible)
  51945. contentArea.setWidth (getWidth() - scrollbarWidth);
  51946. if (hBarVisible)
  51947. contentArea.setHeight (getHeight() - scrollbarWidth);
  51948. contentHolder.setBounds (contentArea);
  51949. Rectangle<int> contentBounds;
  51950. if (contentComp != 0)
  51951. contentBounds = contentHolder.getLocalArea (contentComp, contentComp->getLocalBounds());
  51952. Point<int> visibleOrigin (-contentBounds.getPosition());
  51953. if (hBarVisible)
  51954. {
  51955. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  51956. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  51957. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  51958. horizontalScrollBar.setSingleStepSize (singleStepX);
  51959. horizontalScrollBar.cancelPendingUpdate();
  51960. }
  51961. else if (canShowHBar)
  51962. {
  51963. visibleOrigin.setX (0);
  51964. }
  51965. if (vBarVisible)
  51966. {
  51967. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  51968. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  51969. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  51970. verticalScrollBar.setSingleStepSize (singleStepY);
  51971. verticalScrollBar.cancelPendingUpdate();
  51972. }
  51973. else if (canShowVBar)
  51974. {
  51975. visibleOrigin.setY (0);
  51976. }
  51977. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  51978. horizontalScrollBar.setVisible (hBarVisible);
  51979. verticalScrollBar.setVisible (vBarVisible);
  51980. setViewPosition (visibleOrigin);
  51981. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  51982. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  51983. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  51984. if (lastVisibleArea != visibleArea)
  51985. {
  51986. lastVisibleArea = visibleArea;
  51987. visibleAreaChanged (visibleArea);
  51988. }
  51989. horizontalScrollBar.handleUpdateNowIfNeeded();
  51990. verticalScrollBar.handleUpdateNowIfNeeded();
  51991. }
  51992. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  51993. {
  51994. if (singleStepX != stepX || singleStepY != stepY)
  51995. {
  51996. singleStepX = stepX;
  51997. singleStepY = stepY;
  51998. updateVisibleArea();
  51999. }
  52000. }
  52001. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  52002. const bool showHorizontalScrollbarIfNeeded)
  52003. {
  52004. if (showVScrollbar != showVerticalScrollbarIfNeeded
  52005. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  52006. {
  52007. showVScrollbar = showVerticalScrollbarIfNeeded;
  52008. showHScrollbar = showHorizontalScrollbarIfNeeded;
  52009. updateVisibleArea();
  52010. }
  52011. }
  52012. void Viewport::setScrollBarThickness (const int thickness)
  52013. {
  52014. if (scrollBarThickness != thickness)
  52015. {
  52016. scrollBarThickness = thickness;
  52017. updateVisibleArea();
  52018. }
  52019. }
  52020. int Viewport::getScrollBarThickness() const
  52021. {
  52022. return scrollBarThickness > 0 ? scrollBarThickness
  52023. : getLookAndFeel().getDefaultScrollbarWidth();
  52024. }
  52025. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52026. {
  52027. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52028. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52029. }
  52030. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52031. {
  52032. const int newRangeStartInt = roundToInt (newRangeStart);
  52033. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52034. {
  52035. setViewPosition (newRangeStartInt, getViewPositionY());
  52036. }
  52037. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52038. {
  52039. setViewPosition (getViewPositionX(), newRangeStartInt);
  52040. }
  52041. }
  52042. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52043. {
  52044. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52045. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52046. }
  52047. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52048. {
  52049. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52050. {
  52051. const bool hasVertBar = verticalScrollBar.isVisible();
  52052. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52053. if (hasHorzBar || hasVertBar)
  52054. {
  52055. if (wheelIncrementX != 0)
  52056. {
  52057. wheelIncrementX *= 14.0f * singleStepX;
  52058. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52059. : jmax (wheelIncrementX, 1.0f);
  52060. }
  52061. if (wheelIncrementY != 0)
  52062. {
  52063. wheelIncrementY *= 14.0f * singleStepY;
  52064. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52065. : jmax (wheelIncrementY, 1.0f);
  52066. }
  52067. Point<int> pos (getViewPosition());
  52068. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52069. {
  52070. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52071. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52072. }
  52073. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52074. {
  52075. if (wheelIncrementX == 0 && ! hasVertBar)
  52076. wheelIncrementX = wheelIncrementY;
  52077. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52078. }
  52079. else if (hasVertBar && wheelIncrementY != 0)
  52080. {
  52081. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52082. }
  52083. if (pos != getViewPosition())
  52084. {
  52085. setViewPosition (pos);
  52086. return true;
  52087. }
  52088. }
  52089. }
  52090. return false;
  52091. }
  52092. bool Viewport::keyPressed (const KeyPress& key)
  52093. {
  52094. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52095. || key.isKeyCode (KeyPress::downKey)
  52096. || key.isKeyCode (KeyPress::pageUpKey)
  52097. || key.isKeyCode (KeyPress::pageDownKey)
  52098. || key.isKeyCode (KeyPress::homeKey)
  52099. || key.isKeyCode (KeyPress::endKey);
  52100. if (verticalScrollBar.isVisible() && isUpDownKey)
  52101. return verticalScrollBar.keyPressed (key);
  52102. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52103. || key.isKeyCode (KeyPress::rightKey);
  52104. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52105. return horizontalScrollBar.keyPressed (key);
  52106. return false;
  52107. }
  52108. END_JUCE_NAMESPACE
  52109. /*** End of inlined file: juce_Viewport.cpp ***/
  52110. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52111. BEGIN_JUCE_NAMESPACE
  52112. namespace LookAndFeelHelpers
  52113. {
  52114. void createRoundedPath (Path& p,
  52115. const float x, const float y,
  52116. const float w, const float h,
  52117. const float cs,
  52118. const bool curveTopLeft, const bool curveTopRight,
  52119. const bool curveBottomLeft, const bool curveBottomRight) throw()
  52120. {
  52121. const float cs2 = 2.0f * cs;
  52122. if (curveTopLeft)
  52123. {
  52124. p.startNewSubPath (x, y + cs);
  52125. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  52126. }
  52127. else
  52128. {
  52129. p.startNewSubPath (x, y);
  52130. }
  52131. if (curveTopRight)
  52132. {
  52133. p.lineTo (x + w - cs, y);
  52134. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  52135. }
  52136. else
  52137. {
  52138. p.lineTo (x + w, y);
  52139. }
  52140. if (curveBottomRight)
  52141. {
  52142. p.lineTo (x + w, y + h - cs);
  52143. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  52144. }
  52145. else
  52146. {
  52147. p.lineTo (x + w, y + h);
  52148. }
  52149. if (curveBottomLeft)
  52150. {
  52151. p.lineTo (x + cs, y + h);
  52152. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  52153. }
  52154. else
  52155. {
  52156. p.lineTo (x, y + h);
  52157. }
  52158. p.closeSubPath();
  52159. }
  52160. const Colour createBaseColour (const Colour& buttonColour,
  52161. const bool hasKeyboardFocus,
  52162. const bool isMouseOverButton,
  52163. const bool isButtonDown) throw()
  52164. {
  52165. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52166. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52167. if (isButtonDown)
  52168. return baseColour.contrasting (0.2f);
  52169. else if (isMouseOverButton)
  52170. return baseColour.contrasting (0.1f);
  52171. return baseColour;
  52172. }
  52173. const TextLayout layoutTooltipText (const String& text) throw()
  52174. {
  52175. const float tooltipFontSize = 12.0f;
  52176. const int maxToolTipWidth = 400;
  52177. const Font f (tooltipFontSize, Font::bold);
  52178. TextLayout tl (text, f);
  52179. tl.layout (maxToolTipWidth, Justification::left, true);
  52180. return tl;
  52181. }
  52182. LookAndFeel* defaultLF = 0;
  52183. LookAndFeel* currentDefaultLF = 0;
  52184. }
  52185. LookAndFeel::LookAndFeel()
  52186. {
  52187. /* if this fails it means you're trying to create a LookAndFeel object before
  52188. the static Colours have been initialised. That ain't gonna work. It probably
  52189. means that you're using a static LookAndFeel object and that your compiler has
  52190. decided to intialise it before the Colours class.
  52191. */
  52192. jassert (Colours::white == Colour (0xffffffff));
  52193. // set up the standard set of colours..
  52194. const int textButtonColour = 0xffbbbbff;
  52195. const int textHighlightColour = 0x401111ee;
  52196. const int standardOutlineColour = 0xb2808080;
  52197. static const int standardColours[] =
  52198. {
  52199. TextButton::buttonColourId, textButtonColour,
  52200. TextButton::buttonOnColourId, 0xff4444ff,
  52201. TextButton::textColourOnId, 0xff000000,
  52202. TextButton::textColourOffId, 0xff000000,
  52203. ComboBox::buttonColourId, 0xffbbbbff,
  52204. ComboBox::outlineColourId, standardOutlineColour,
  52205. ToggleButton::textColourId, 0xff000000,
  52206. TextEditor::backgroundColourId, 0xffffffff,
  52207. TextEditor::textColourId, 0xff000000,
  52208. TextEditor::highlightColourId, textHighlightColour,
  52209. TextEditor::highlightedTextColourId, 0xff000000,
  52210. TextEditor::caretColourId, 0xff000000,
  52211. TextEditor::outlineColourId, 0x00000000,
  52212. TextEditor::focusedOutlineColourId, textButtonColour,
  52213. TextEditor::shadowColourId, 0x38000000,
  52214. Label::backgroundColourId, 0x00000000,
  52215. Label::textColourId, 0xff000000,
  52216. Label::outlineColourId, 0x00000000,
  52217. ScrollBar::backgroundColourId, 0x00000000,
  52218. ScrollBar::thumbColourId, 0xffffffff,
  52219. TreeView::linesColourId, 0x4c000000,
  52220. TreeView::backgroundColourId, 0x00000000,
  52221. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52222. PopupMenu::backgroundColourId, 0xffffffff,
  52223. PopupMenu::textColourId, 0xff000000,
  52224. PopupMenu::headerTextColourId, 0xff000000,
  52225. PopupMenu::highlightedTextColourId, 0xffffffff,
  52226. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52227. ComboBox::textColourId, 0xff000000,
  52228. ComboBox::backgroundColourId, 0xffffffff,
  52229. ComboBox::arrowColourId, 0x99000000,
  52230. ListBox::backgroundColourId, 0xffffffff,
  52231. ListBox::outlineColourId, standardOutlineColour,
  52232. ListBox::textColourId, 0xff000000,
  52233. Slider::backgroundColourId, 0x00000000,
  52234. Slider::thumbColourId, textButtonColour,
  52235. Slider::trackColourId, 0x7fffffff,
  52236. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52237. Slider::rotarySliderOutlineColourId, 0x66000000,
  52238. Slider::textBoxTextColourId, 0xff000000,
  52239. Slider::textBoxBackgroundColourId, 0xffffffff,
  52240. Slider::textBoxHighlightColourId, textHighlightColour,
  52241. Slider::textBoxOutlineColourId, standardOutlineColour,
  52242. ResizableWindow::backgroundColourId, 0xff777777,
  52243. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52244. AlertWindow::backgroundColourId, 0xffededed,
  52245. AlertWindow::textColourId, 0xff000000,
  52246. AlertWindow::outlineColourId, 0xff666666,
  52247. ProgressBar::backgroundColourId, 0xffeeeeee,
  52248. ProgressBar::foregroundColourId, 0xffaaaaee,
  52249. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52250. TooltipWindow::textColourId, 0xff000000,
  52251. TooltipWindow::outlineColourId, 0x4c000000,
  52252. TabbedComponent::backgroundColourId, 0x00000000,
  52253. TabbedComponent::outlineColourId, 0xff777777,
  52254. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52255. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52256. Toolbar::backgroundColourId, 0xfff6f8f9,
  52257. Toolbar::separatorColourId, 0x4c000000,
  52258. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52259. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52260. Toolbar::labelTextColourId, 0xff000000,
  52261. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52262. HyperlinkButton::textColourId, 0xcc1111ee,
  52263. GroupComponent::outlineColourId, 0x66000000,
  52264. GroupComponent::textColourId, 0xff000000,
  52265. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52266. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52267. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52268. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52269. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52270. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52271. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52272. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52273. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52274. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52275. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52276. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52277. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52278. CodeEditorComponent::caretColourId, 0xff000000,
  52279. CodeEditorComponent::highlightColourId, textHighlightColour,
  52280. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52281. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52282. ColourSelector::labelTextColourId, 0xff000000,
  52283. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52284. KeyMappingEditorComponent::textColourId, 0xff000000,
  52285. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52286. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52287. DrawableButton::textColourId, 0xff000000,
  52288. };
  52289. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52290. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52291. static String defaultSansName, defaultSerifName, defaultFixedName, defaultFallback;
  52292. if (defaultSansName.isEmpty())
  52293. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName, defaultFallback);
  52294. defaultSans = defaultSansName;
  52295. defaultSerif = defaultSerifName;
  52296. defaultFixed = defaultFixedName;
  52297. Font::setFallbackFontName (defaultFallback);
  52298. }
  52299. LookAndFeel::~LookAndFeel()
  52300. {
  52301. if (this == LookAndFeelHelpers::currentDefaultLF)
  52302. setDefaultLookAndFeel (0);
  52303. }
  52304. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52305. {
  52306. const int index = colourIds.indexOf (colourId);
  52307. if (index >= 0)
  52308. return colours [index];
  52309. jassertfalse;
  52310. return Colours::black;
  52311. }
  52312. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52313. {
  52314. const int index = colourIds.indexOf (colourId);
  52315. if (index >= 0)
  52316. {
  52317. colours.set (index, colour);
  52318. }
  52319. else
  52320. {
  52321. colourIds.add (colourId);
  52322. colours.add (colour);
  52323. }
  52324. }
  52325. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52326. {
  52327. return colourIds.contains (colourId);
  52328. }
  52329. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52330. {
  52331. // if this happens, your app hasn't initialised itself properly.. if you're
  52332. // trying to hack your own main() function, have a look at
  52333. // JUCEApplication::initialiseForGUI()
  52334. jassert (LookAndFeelHelpers::currentDefaultLF != 0);
  52335. return *LookAndFeelHelpers::currentDefaultLF;
  52336. }
  52337. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52338. {
  52339. using namespace LookAndFeelHelpers;
  52340. if (newDefaultLookAndFeel == 0)
  52341. {
  52342. if (defaultLF == 0)
  52343. defaultLF = new LookAndFeel();
  52344. newDefaultLookAndFeel = defaultLF;
  52345. }
  52346. LookAndFeelHelpers::currentDefaultLF = newDefaultLookAndFeel;
  52347. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52348. {
  52349. Component* const c = Desktop::getInstance().getComponent (i);
  52350. if (c != 0)
  52351. c->sendLookAndFeelChange();
  52352. }
  52353. }
  52354. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52355. {
  52356. using namespace LookAndFeelHelpers;
  52357. if (currentDefaultLF == defaultLF)
  52358. currentDefaultLF = 0;
  52359. deleteAndZero (defaultLF);
  52360. }
  52361. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52362. {
  52363. String faceName (font.getTypefaceName());
  52364. if (faceName == Font::getDefaultSansSerifFontName())
  52365. faceName = defaultSans;
  52366. else if (faceName == Font::getDefaultSerifFontName())
  52367. faceName = defaultSerif;
  52368. else if (faceName == Font::getDefaultMonospacedFontName())
  52369. faceName = defaultFixed;
  52370. Font f (font);
  52371. f.setTypefaceName (faceName);
  52372. return Typeface::createSystemTypefaceFor (f);
  52373. }
  52374. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52375. {
  52376. defaultSans = newName;
  52377. }
  52378. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52379. {
  52380. return component.getMouseCursor();
  52381. }
  52382. void LookAndFeel::drawButtonBackground (Graphics& g,
  52383. Button& button,
  52384. const Colour& backgroundColour,
  52385. bool isMouseOverButton,
  52386. bool isButtonDown)
  52387. {
  52388. const int width = button.getWidth();
  52389. const int height = button.getHeight();
  52390. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52391. const float halfThickness = outlineThickness * 0.5f;
  52392. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52393. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52394. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52395. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52396. const Colour baseColour (LookAndFeelHelpers::createBaseColour (backgroundColour,
  52397. button.hasKeyboardFocus (true),
  52398. isMouseOverButton, isButtonDown)
  52399. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52400. drawGlassLozenge (g,
  52401. indentL,
  52402. indentT,
  52403. width - indentL - indentR,
  52404. height - indentT - indentB,
  52405. baseColour, outlineThickness, -1.0f,
  52406. button.isConnectedOnLeft(),
  52407. button.isConnectedOnRight(),
  52408. button.isConnectedOnTop(),
  52409. button.isConnectedOnBottom());
  52410. }
  52411. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52412. {
  52413. return button.getFont();
  52414. }
  52415. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52416. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52417. {
  52418. Font font (getFontForTextButton (button));
  52419. g.setFont (font);
  52420. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52421. : TextButton::textColourOffId)
  52422. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52423. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52424. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52425. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52426. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52427. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52428. g.drawFittedText (button.getButtonText(),
  52429. leftIndent,
  52430. yIndent,
  52431. button.getWidth() - leftIndent - rightIndent,
  52432. button.getHeight() - yIndent * 2,
  52433. Justification::centred, 2);
  52434. }
  52435. void LookAndFeel::drawTickBox (Graphics& g,
  52436. Component& component,
  52437. float x, float y, float w, float h,
  52438. const bool ticked,
  52439. const bool isEnabled,
  52440. const bool isMouseOverButton,
  52441. const bool isButtonDown)
  52442. {
  52443. const float boxSize = w * 0.7f;
  52444. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52445. LookAndFeelHelpers::createBaseColour (component.findColour (TextButton::buttonColourId)
  52446. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52447. true, isMouseOverButton, isButtonDown),
  52448. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52449. if (ticked)
  52450. {
  52451. Path tick;
  52452. tick.startNewSubPath (1.5f, 3.0f);
  52453. tick.lineTo (3.0f, 6.0f);
  52454. tick.lineTo (6.0f, 0.0f);
  52455. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52456. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52457. .translated (x, y));
  52458. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52459. }
  52460. }
  52461. void LookAndFeel::drawToggleButton (Graphics& g,
  52462. ToggleButton& button,
  52463. bool isMouseOverButton,
  52464. bool isButtonDown)
  52465. {
  52466. if (button.hasKeyboardFocus (true))
  52467. {
  52468. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52469. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52470. }
  52471. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52472. const float tickWidth = fontSize * 1.1f;
  52473. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52474. tickWidth, tickWidth,
  52475. button.getToggleState(),
  52476. button.isEnabled(),
  52477. isMouseOverButton,
  52478. isButtonDown);
  52479. g.setColour (button.findColour (ToggleButton::textColourId));
  52480. g.setFont (fontSize);
  52481. if (! button.isEnabled())
  52482. g.setOpacity (0.5f);
  52483. const int textX = (int) tickWidth + 5;
  52484. g.drawFittedText (button.getButtonText(),
  52485. textX, 0,
  52486. button.getWidth() - textX - 2, button.getHeight(),
  52487. Justification::centredLeft, 10);
  52488. }
  52489. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52490. {
  52491. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52492. const int tickWidth = jmin (24, button.getHeight());
  52493. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52494. button.getHeight());
  52495. }
  52496. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52497. const String& message,
  52498. const String& button1,
  52499. const String& button2,
  52500. const String& button3,
  52501. AlertWindow::AlertIconType iconType,
  52502. int numButtons,
  52503. Component* associatedComponent)
  52504. {
  52505. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52506. if (numButtons == 1)
  52507. {
  52508. aw->addButton (button1, 0,
  52509. KeyPress (KeyPress::escapeKey, 0, 0),
  52510. KeyPress (KeyPress::returnKey, 0, 0));
  52511. }
  52512. else
  52513. {
  52514. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52515. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52516. if (button1ShortCut == button2ShortCut)
  52517. button2ShortCut = KeyPress();
  52518. if (numButtons == 2)
  52519. {
  52520. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52521. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52522. }
  52523. else if (numButtons == 3)
  52524. {
  52525. aw->addButton (button1, 1, button1ShortCut);
  52526. aw->addButton (button2, 2, button2ShortCut);
  52527. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52528. }
  52529. }
  52530. return aw;
  52531. }
  52532. void LookAndFeel::drawAlertBox (Graphics& g,
  52533. AlertWindow& alert,
  52534. const Rectangle<int>& textArea,
  52535. TextLayout& textLayout)
  52536. {
  52537. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52538. int iconSpaceUsed = 0;
  52539. Justification alignment (Justification::horizontallyCentred);
  52540. const int iconWidth = 80;
  52541. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52542. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52543. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52544. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52545. iconSize, iconSize);
  52546. if (alert.getAlertType() != AlertWindow::NoIcon)
  52547. {
  52548. Path icon;
  52549. uint32 colour;
  52550. char character;
  52551. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52552. {
  52553. colour = 0x55ff5555;
  52554. character = '!';
  52555. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52556. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52557. (float) iconRect.getX(), (float) iconRect.getBottom());
  52558. icon = icon.createPathWithRoundedCorners (5.0f);
  52559. }
  52560. else
  52561. {
  52562. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52563. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52564. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52565. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52566. }
  52567. GlyphArrangement ga;
  52568. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52569. String::charToString (character),
  52570. (float) iconRect.getX(), (float) iconRect.getY(),
  52571. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52572. Justification::centred, false);
  52573. ga.createPath (icon);
  52574. icon.setUsingNonZeroWinding (false);
  52575. g.setColour (Colour (colour));
  52576. g.fillPath (icon);
  52577. iconSpaceUsed = iconWidth;
  52578. alignment = Justification::left;
  52579. }
  52580. g.setColour (alert.findColour (AlertWindow::textColourId));
  52581. textLayout.drawWithin (g,
  52582. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52583. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52584. alignment.getFlags() | Justification::top);
  52585. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52586. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52587. }
  52588. int LookAndFeel::getAlertBoxWindowFlags()
  52589. {
  52590. return ComponentPeer::windowAppearsOnTaskbar
  52591. | ComponentPeer::windowHasDropShadow;
  52592. }
  52593. int LookAndFeel::getAlertWindowButtonHeight()
  52594. {
  52595. return 28;
  52596. }
  52597. const Font LookAndFeel::getAlertWindowMessageFont()
  52598. {
  52599. return Font (15.0f);
  52600. }
  52601. const Font LookAndFeel::getAlertWindowFont()
  52602. {
  52603. return Font (12.0f);
  52604. }
  52605. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52606. int width, int height,
  52607. double progress, const String& textToShow)
  52608. {
  52609. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52610. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52611. g.fillAll (background);
  52612. if (progress >= 0.0f && progress < 1.0f)
  52613. {
  52614. drawGlassLozenge (g, 1.0f, 1.0f,
  52615. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52616. (float) (height - 2),
  52617. foreground,
  52618. 0.5f, 0.0f,
  52619. true, true, true, true);
  52620. }
  52621. else
  52622. {
  52623. // spinning bar..
  52624. g.setColour (foreground);
  52625. const int stripeWidth = height * 2;
  52626. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52627. Path p;
  52628. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52629. p.addQuadrilateral (x, 0.0f,
  52630. x + stripeWidth * 0.5f, 0.0f,
  52631. x, (float) height,
  52632. x - stripeWidth * 0.5f, (float) height);
  52633. Image im (Image::ARGB, width, height, true);
  52634. {
  52635. Graphics g2 (im);
  52636. drawGlassLozenge (g2, 1.0f, 1.0f,
  52637. (float) (width - 2),
  52638. (float) (height - 2),
  52639. foreground,
  52640. 0.5f, 0.0f,
  52641. true, true, true, true);
  52642. }
  52643. g.setTiledImageFill (im, 0, 0, 0.85f);
  52644. g.fillPath (p);
  52645. }
  52646. if (textToShow.isNotEmpty())
  52647. {
  52648. g.setColour (Colour::contrasting (background, foreground));
  52649. g.setFont (height * 0.6f);
  52650. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52651. }
  52652. }
  52653. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52654. {
  52655. const float radius = jmin (w, h) * 0.4f;
  52656. const float thickness = radius * 0.15f;
  52657. Path p;
  52658. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52659. radius * 0.6f, thickness,
  52660. thickness * 0.5f);
  52661. const float cx = x + w * 0.5f;
  52662. const float cy = y + h * 0.5f;
  52663. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52664. for (int i = 0; i < 12; ++i)
  52665. {
  52666. const int n = (i + 12 - animationIndex) % 12;
  52667. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52668. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52669. .translated (cx, cy));
  52670. }
  52671. }
  52672. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52673. ScrollBar& scrollbar,
  52674. int width, int height,
  52675. int buttonDirection,
  52676. bool /*isScrollbarVertical*/,
  52677. bool /*isMouseOverButton*/,
  52678. bool isButtonDown)
  52679. {
  52680. Path p;
  52681. if (buttonDirection == 0)
  52682. p.addTriangle (width * 0.5f, height * 0.2f,
  52683. width * 0.1f, height * 0.7f,
  52684. width * 0.9f, height * 0.7f);
  52685. else if (buttonDirection == 1)
  52686. p.addTriangle (width * 0.8f, height * 0.5f,
  52687. width * 0.3f, height * 0.1f,
  52688. width * 0.3f, height * 0.9f);
  52689. else if (buttonDirection == 2)
  52690. p.addTriangle (width * 0.5f, height * 0.8f,
  52691. width * 0.1f, height * 0.3f,
  52692. width * 0.9f, height * 0.3f);
  52693. else if (buttonDirection == 3)
  52694. p.addTriangle (width * 0.2f, height * 0.5f,
  52695. width * 0.7f, height * 0.1f,
  52696. width * 0.7f, height * 0.9f);
  52697. if (isButtonDown)
  52698. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52699. else
  52700. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52701. g.fillPath (p);
  52702. g.setColour (Colour (0x80000000));
  52703. g.strokePath (p, PathStrokeType (0.5f));
  52704. }
  52705. void LookAndFeel::drawScrollbar (Graphics& g,
  52706. ScrollBar& scrollbar,
  52707. int x, int y,
  52708. int width, int height,
  52709. bool isScrollbarVertical,
  52710. int thumbStartPosition,
  52711. int thumbSize,
  52712. bool /*isMouseOver*/,
  52713. bool /*isMouseDown*/)
  52714. {
  52715. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52716. Path slotPath, thumbPath;
  52717. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52718. const float slotIndentx2 = slotIndent * 2.0f;
  52719. const float thumbIndent = slotIndent + 1.0f;
  52720. const float thumbIndentx2 = thumbIndent * 2.0f;
  52721. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52722. if (isScrollbarVertical)
  52723. {
  52724. slotPath.addRoundedRectangle (x + slotIndent,
  52725. y + slotIndent,
  52726. width - slotIndentx2,
  52727. height - slotIndentx2,
  52728. (width - slotIndentx2) * 0.5f);
  52729. if (thumbSize > 0)
  52730. thumbPath.addRoundedRectangle (x + thumbIndent,
  52731. thumbStartPosition + thumbIndent,
  52732. width - thumbIndentx2,
  52733. thumbSize - thumbIndentx2,
  52734. (width - thumbIndentx2) * 0.5f);
  52735. gx1 = (float) x;
  52736. gx2 = x + width * 0.7f;
  52737. }
  52738. else
  52739. {
  52740. slotPath.addRoundedRectangle (x + slotIndent,
  52741. y + slotIndent,
  52742. width - slotIndentx2,
  52743. height - slotIndentx2,
  52744. (height - slotIndentx2) * 0.5f);
  52745. if (thumbSize > 0)
  52746. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52747. y + thumbIndent,
  52748. thumbSize - thumbIndentx2,
  52749. height - thumbIndentx2,
  52750. (height - thumbIndentx2) * 0.5f);
  52751. gy1 = (float) y;
  52752. gy2 = y + height * 0.7f;
  52753. }
  52754. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52755. Colour trackColour1, trackColour2;
  52756. if (scrollbar.isColourSpecified (ScrollBar::trackColourId))
  52757. {
  52758. trackColour1 = trackColour2 = scrollbar.findColour (ScrollBar::trackColourId);
  52759. }
  52760. else
  52761. {
  52762. trackColour1 = thumbColour.overlaidWith (Colour (0x44000000));
  52763. trackColour2 = thumbColour.overlaidWith (Colour (0x19000000));
  52764. }
  52765. g.setGradientFill (ColourGradient (trackColour1, gx1, gy1,
  52766. trackColour2, gx2, gy2, false));
  52767. g.fillPath (slotPath);
  52768. if (isScrollbarVertical)
  52769. {
  52770. gx1 = x + width * 0.6f;
  52771. gx2 = (float) x + width;
  52772. }
  52773. else
  52774. {
  52775. gy1 = y + height * 0.6f;
  52776. gy2 = (float) y + height;
  52777. }
  52778. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52779. Colour (0x19000000), gx2, gy2, false));
  52780. g.fillPath (slotPath);
  52781. g.setColour (thumbColour);
  52782. g.fillPath (thumbPath);
  52783. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52784. Colours::transparentBlack, gx2, gy2, false));
  52785. g.saveState();
  52786. if (isScrollbarVertical)
  52787. g.reduceClipRegion (x + width / 2, y, width, height);
  52788. else
  52789. g.reduceClipRegion (x, y + height / 2, width, height);
  52790. g.fillPath (thumbPath);
  52791. g.restoreState();
  52792. g.setColour (Colour (0x4c000000));
  52793. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52794. }
  52795. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52796. {
  52797. return 0;
  52798. }
  52799. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52800. {
  52801. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52802. }
  52803. int LookAndFeel::getDefaultScrollbarWidth()
  52804. {
  52805. return 18;
  52806. }
  52807. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52808. {
  52809. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52810. : scrollbar.getHeight());
  52811. }
  52812. const Path LookAndFeel::getTickShape (const float height)
  52813. {
  52814. static const unsigned char tickShapeData[] =
  52815. {
  52816. 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,
  52817. 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,
  52818. 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,
  52819. 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,
  52820. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  52821. };
  52822. Path p;
  52823. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  52824. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52825. return p;
  52826. }
  52827. const Path LookAndFeel::getCrossShape (const float height)
  52828. {
  52829. static const unsigned char crossShapeData[] =
  52830. {
  52831. 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,
  52832. 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,
  52833. 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,
  52834. 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,
  52835. 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,
  52836. 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,
  52837. 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
  52838. };
  52839. Path p;
  52840. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  52841. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52842. return p;
  52843. }
  52844. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  52845. {
  52846. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  52847. x += (w - boxSize) >> 1;
  52848. y += (h - boxSize) >> 1;
  52849. w = boxSize;
  52850. h = boxSize;
  52851. g.setColour (Colour (0xe5ffffff));
  52852. g.fillRect (x, y, w, h);
  52853. g.setColour (Colour (0x80000000));
  52854. g.drawRect (x, y, w, h);
  52855. const float size = boxSize / 2 + 1.0f;
  52856. const float centre = (float) (boxSize / 2);
  52857. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  52858. if (isPlus)
  52859. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  52860. }
  52861. void LookAndFeel::drawBubble (Graphics& g,
  52862. float tipX, float tipY,
  52863. float boxX, float boxY,
  52864. float boxW, float boxH)
  52865. {
  52866. int side = 0;
  52867. if (tipX < boxX)
  52868. side = 1;
  52869. else if (tipX > boxX + boxW)
  52870. side = 3;
  52871. else if (tipY > boxY + boxH)
  52872. side = 2;
  52873. const float indent = 2.0f;
  52874. Path p;
  52875. p.addBubble (boxX + indent,
  52876. boxY + indent,
  52877. boxW - indent * 2.0f,
  52878. boxH - indent * 2.0f,
  52879. 5.0f,
  52880. tipX, tipY,
  52881. side,
  52882. 0.5f,
  52883. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  52884. //xxx need to take comp as param for colour
  52885. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  52886. g.fillPath (p);
  52887. //xxx as above
  52888. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  52889. g.strokePath (p, PathStrokeType (1.33f));
  52890. }
  52891. const Font LookAndFeel::getPopupMenuFont()
  52892. {
  52893. return Font (17.0f);
  52894. }
  52895. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  52896. const bool isSeparator,
  52897. int standardMenuItemHeight,
  52898. int& idealWidth,
  52899. int& idealHeight)
  52900. {
  52901. if (isSeparator)
  52902. {
  52903. idealWidth = 50;
  52904. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  52905. }
  52906. else
  52907. {
  52908. Font font (getPopupMenuFont());
  52909. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  52910. font.setHeight (standardMenuItemHeight / 1.3f);
  52911. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  52912. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  52913. }
  52914. }
  52915. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  52916. {
  52917. const Colour background (findColour (PopupMenu::backgroundColourId));
  52918. g.fillAll (background);
  52919. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  52920. for (int i = 0; i < height; i += 3)
  52921. g.fillRect (0, i, width, 1);
  52922. #if ! JUCE_MAC
  52923. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  52924. g.drawRect (0, 0, width, height);
  52925. #endif
  52926. }
  52927. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  52928. int width, int height,
  52929. bool isScrollUpArrow)
  52930. {
  52931. const Colour background (findColour (PopupMenu::backgroundColourId));
  52932. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  52933. background.withAlpha (0.0f),
  52934. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  52935. false));
  52936. g.fillRect (1, 1, width - 2, height - 2);
  52937. const float hw = width * 0.5f;
  52938. const float arrowW = height * 0.3f;
  52939. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  52940. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  52941. Path p;
  52942. p.addTriangle (hw - arrowW, y1,
  52943. hw + arrowW, y1,
  52944. hw, y2);
  52945. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  52946. g.fillPath (p);
  52947. }
  52948. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  52949. int width, int height,
  52950. const bool isSeparator,
  52951. const bool isActive,
  52952. const bool isHighlighted,
  52953. const bool isTicked,
  52954. const bool hasSubMenu,
  52955. const String& text,
  52956. const String& shortcutKeyText,
  52957. Image* image,
  52958. const Colour* const textColourToUse)
  52959. {
  52960. const float halfH = height * 0.5f;
  52961. if (isSeparator)
  52962. {
  52963. const float separatorIndent = 5.5f;
  52964. g.setColour (Colour (0x33000000));
  52965. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  52966. g.setColour (Colour (0x66ffffff));
  52967. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  52968. }
  52969. else
  52970. {
  52971. Colour textColour (findColour (PopupMenu::textColourId));
  52972. if (textColourToUse != 0)
  52973. textColour = *textColourToUse;
  52974. if (isHighlighted)
  52975. {
  52976. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  52977. g.fillRect (1, 1, width - 2, height - 2);
  52978. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  52979. }
  52980. else
  52981. {
  52982. g.setColour (textColour);
  52983. }
  52984. if (! isActive)
  52985. g.setOpacity (0.3f);
  52986. Font font (getPopupMenuFont());
  52987. if (font.getHeight() > height / 1.3f)
  52988. font.setHeight (height / 1.3f);
  52989. g.setFont (font);
  52990. const int leftBorder = (height * 5) / 4;
  52991. const int rightBorder = 4;
  52992. if (image != 0)
  52993. {
  52994. g.drawImageWithin (*image,
  52995. 2, 1, leftBorder - 4, height - 2,
  52996. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  52997. }
  52998. else if (isTicked)
  52999. {
  53000. const Path tick (getTickShape (1.0f));
  53001. const float th = font.getAscent();
  53002. const float ty = halfH - th * 0.5f;
  53003. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  53004. th, true));
  53005. }
  53006. g.drawFittedText (text,
  53007. leftBorder, 0,
  53008. width - (leftBorder + rightBorder), height,
  53009. Justification::centredLeft, 1);
  53010. if (shortcutKeyText.isNotEmpty())
  53011. {
  53012. Font f2 (font);
  53013. f2.setHeight (f2.getHeight() * 0.75f);
  53014. f2.setHorizontalScale (0.95f);
  53015. g.setFont (f2);
  53016. g.drawText (shortcutKeyText,
  53017. leftBorder,
  53018. 0,
  53019. width - (leftBorder + rightBorder + 4),
  53020. height,
  53021. Justification::centredRight,
  53022. true);
  53023. }
  53024. if (hasSubMenu)
  53025. {
  53026. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53027. const float x = width - height * 0.6f;
  53028. Path p;
  53029. p.addTriangle (x, halfH - arrowH * 0.5f,
  53030. x, halfH + arrowH * 0.5f,
  53031. x + arrowH * 0.6f, halfH);
  53032. g.fillPath (p);
  53033. }
  53034. }
  53035. }
  53036. int LookAndFeel::getMenuWindowFlags()
  53037. {
  53038. return ComponentPeer::windowHasDropShadow;
  53039. }
  53040. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53041. bool, MenuBarComponent& menuBar)
  53042. {
  53043. const Colour baseColour (LookAndFeelHelpers::createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53044. if (menuBar.isEnabled())
  53045. {
  53046. drawShinyButtonShape (g,
  53047. -4.0f, 0.0f,
  53048. width + 8.0f, (float) height,
  53049. 0.0f,
  53050. baseColour,
  53051. 0.4f,
  53052. true, true, true, true);
  53053. }
  53054. else
  53055. {
  53056. g.fillAll (baseColour);
  53057. }
  53058. }
  53059. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53060. {
  53061. return Font (menuBar.getHeight() * 0.7f);
  53062. }
  53063. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53064. {
  53065. return getMenuBarFont (menuBar, itemIndex, itemText)
  53066. .getStringWidth (itemText) + menuBar.getHeight();
  53067. }
  53068. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53069. int width, int height,
  53070. int itemIndex,
  53071. const String& itemText,
  53072. bool isMouseOverItem,
  53073. bool isMenuOpen,
  53074. bool /*isMouseOverBar*/,
  53075. MenuBarComponent& menuBar)
  53076. {
  53077. if (! menuBar.isEnabled())
  53078. {
  53079. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53080. .withMultipliedAlpha (0.5f));
  53081. }
  53082. else if (isMenuOpen || isMouseOverItem)
  53083. {
  53084. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53085. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53086. }
  53087. else
  53088. {
  53089. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53090. }
  53091. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53092. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53093. }
  53094. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53095. TextEditor& textEditor)
  53096. {
  53097. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53098. }
  53099. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53100. {
  53101. if (textEditor.isEnabled())
  53102. {
  53103. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53104. {
  53105. const int border = 2;
  53106. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53107. g.drawRect (0, 0, width, height, border);
  53108. g.setOpacity (1.0f);
  53109. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53110. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53111. }
  53112. else
  53113. {
  53114. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53115. g.drawRect (0, 0, width, height);
  53116. g.setOpacity (1.0f);
  53117. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53118. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53119. }
  53120. }
  53121. }
  53122. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53123. const bool isButtonDown,
  53124. int buttonX, int buttonY,
  53125. int buttonW, int buttonH,
  53126. ComboBox& box)
  53127. {
  53128. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53129. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53130. {
  53131. g.setColour (box.findColour (TextButton::buttonColourId));
  53132. g.drawRect (0, 0, width, height, 2);
  53133. }
  53134. else
  53135. {
  53136. g.setColour (box.findColour (ComboBox::outlineColourId));
  53137. g.drawRect (0, 0, width, height);
  53138. }
  53139. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53140. const Colour baseColour (LookAndFeelHelpers::createBaseColour (box.findColour (ComboBox::buttonColourId),
  53141. box.hasKeyboardFocus (true),
  53142. false, isButtonDown)
  53143. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53144. drawGlassLozenge (g,
  53145. buttonX + outlineThickness, buttonY + outlineThickness,
  53146. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53147. baseColour, outlineThickness, -1.0f,
  53148. true, true, true, true);
  53149. if (box.isEnabled())
  53150. {
  53151. const float arrowX = 0.3f;
  53152. const float arrowH = 0.2f;
  53153. Path p;
  53154. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53155. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53156. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53157. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53158. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53159. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53160. g.setColour (box.findColour (ComboBox::arrowColourId));
  53161. g.fillPath (p);
  53162. }
  53163. }
  53164. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53165. {
  53166. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53167. }
  53168. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53169. {
  53170. return new Label (String::empty, String::empty);
  53171. }
  53172. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53173. {
  53174. label.setBounds (1, 1,
  53175. box.getWidth() + 3 - box.getHeight(),
  53176. box.getHeight() - 2);
  53177. label.setFont (getComboBoxFont (box));
  53178. }
  53179. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53180. {
  53181. g.fillAll (label.findColour (Label::backgroundColourId));
  53182. if (! label.isBeingEdited())
  53183. {
  53184. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53185. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53186. g.setFont (label.getFont());
  53187. g.drawFittedText (label.getText(),
  53188. label.getHorizontalBorderSize(),
  53189. label.getVerticalBorderSize(),
  53190. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53191. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53192. label.getJustificationType(),
  53193. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53194. label.getMinimumHorizontalScale());
  53195. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53196. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53197. }
  53198. else if (label.isEnabled())
  53199. {
  53200. g.setColour (label.findColour (Label::outlineColourId));
  53201. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53202. }
  53203. }
  53204. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53205. int x, int y,
  53206. int width, int height,
  53207. float /*sliderPos*/,
  53208. float /*minSliderPos*/,
  53209. float /*maxSliderPos*/,
  53210. const Slider::SliderStyle /*style*/,
  53211. Slider& slider)
  53212. {
  53213. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53214. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53215. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53216. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53217. Path indent;
  53218. if (slider.isHorizontal())
  53219. {
  53220. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53221. const float ih = sliderRadius;
  53222. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53223. gradCol2, 0.0f, iy + ih, false));
  53224. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53225. width + sliderRadius, ih,
  53226. 5.0f);
  53227. g.fillPath (indent);
  53228. }
  53229. else
  53230. {
  53231. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53232. const float iw = sliderRadius;
  53233. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53234. gradCol2, ix + iw, 0.0f, false));
  53235. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53236. iw, height + sliderRadius,
  53237. 5.0f);
  53238. g.fillPath (indent);
  53239. }
  53240. g.setColour (Colour (0x4c000000));
  53241. g.strokePath (indent, PathStrokeType (0.5f));
  53242. }
  53243. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53244. int x, int y,
  53245. int width, int height,
  53246. float sliderPos,
  53247. float minSliderPos,
  53248. float maxSliderPos,
  53249. const Slider::SliderStyle style,
  53250. Slider& slider)
  53251. {
  53252. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53253. Colour knobColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId),
  53254. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53255. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53256. slider.isMouseButtonDown() && slider.isEnabled()));
  53257. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53258. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53259. {
  53260. float kx, ky;
  53261. if (style == Slider::LinearVertical)
  53262. {
  53263. kx = x + width * 0.5f;
  53264. ky = sliderPos;
  53265. }
  53266. else
  53267. {
  53268. kx = sliderPos;
  53269. ky = y + height * 0.5f;
  53270. }
  53271. drawGlassSphere (g,
  53272. kx - sliderRadius,
  53273. ky - sliderRadius,
  53274. sliderRadius * 2.0f,
  53275. knobColour, outlineThickness);
  53276. }
  53277. else
  53278. {
  53279. if (style == Slider::ThreeValueVertical)
  53280. {
  53281. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53282. sliderPos - sliderRadius,
  53283. sliderRadius * 2.0f,
  53284. knobColour, outlineThickness);
  53285. }
  53286. else if (style == Slider::ThreeValueHorizontal)
  53287. {
  53288. drawGlassSphere (g,sliderPos - sliderRadius,
  53289. y + height * 0.5f - sliderRadius,
  53290. sliderRadius * 2.0f,
  53291. knobColour, outlineThickness);
  53292. }
  53293. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53294. {
  53295. const float sr = jmin (sliderRadius, width * 0.4f);
  53296. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53297. minSliderPos - sliderRadius,
  53298. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53299. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53300. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53301. }
  53302. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53303. {
  53304. const float sr = jmin (sliderRadius, height * 0.4f);
  53305. drawGlassPointer (g, minSliderPos - sr,
  53306. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53307. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53308. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53309. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53310. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53311. }
  53312. }
  53313. }
  53314. void LookAndFeel::drawLinearSlider (Graphics& g,
  53315. int x, int y,
  53316. int width, int height,
  53317. float sliderPos,
  53318. float minSliderPos,
  53319. float maxSliderPos,
  53320. const Slider::SliderStyle style,
  53321. Slider& slider)
  53322. {
  53323. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53324. if (style == Slider::LinearBar)
  53325. {
  53326. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53327. Colour baseColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId)
  53328. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53329. false, isMouseOver,
  53330. isMouseOver || slider.isMouseButtonDown()));
  53331. drawShinyButtonShape (g,
  53332. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53333. baseColour,
  53334. slider.isEnabled() ? 0.9f : 0.3f,
  53335. true, true, true, true);
  53336. }
  53337. else
  53338. {
  53339. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53340. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53341. }
  53342. }
  53343. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53344. {
  53345. return jmin (7,
  53346. slider.getHeight() / 2,
  53347. slider.getWidth() / 2) + 2;
  53348. }
  53349. void LookAndFeel::drawRotarySlider (Graphics& g,
  53350. int x, int y,
  53351. int width, int height,
  53352. float sliderPos,
  53353. const float rotaryStartAngle,
  53354. const float rotaryEndAngle,
  53355. Slider& slider)
  53356. {
  53357. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53358. const float centreX = x + width * 0.5f;
  53359. const float centreY = y + height * 0.5f;
  53360. const float rx = centreX - radius;
  53361. const float ry = centreY - radius;
  53362. const float rw = radius * 2.0f;
  53363. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53364. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53365. if (radius > 12.0f)
  53366. {
  53367. if (slider.isEnabled())
  53368. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53369. else
  53370. g.setColour (Colour (0x80808080));
  53371. const float thickness = 0.7f;
  53372. {
  53373. Path filledArc;
  53374. filledArc.addPieSegment (rx, ry, rw, rw,
  53375. rotaryStartAngle,
  53376. angle,
  53377. thickness);
  53378. g.fillPath (filledArc);
  53379. }
  53380. if (thickness > 0)
  53381. {
  53382. const float innerRadius = radius * 0.2f;
  53383. Path p;
  53384. p.addTriangle (-innerRadius, 0.0f,
  53385. 0.0f, -radius * thickness * 1.1f,
  53386. innerRadius, 0.0f);
  53387. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53388. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53389. }
  53390. if (slider.isEnabled())
  53391. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53392. else
  53393. g.setColour (Colour (0x80808080));
  53394. Path outlineArc;
  53395. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53396. outlineArc.closeSubPath();
  53397. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53398. }
  53399. else
  53400. {
  53401. if (slider.isEnabled())
  53402. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53403. else
  53404. g.setColour (Colour (0x80808080));
  53405. Path p;
  53406. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53407. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53408. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53409. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53410. }
  53411. }
  53412. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53413. {
  53414. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53415. }
  53416. class SliderLabelComp : public Label
  53417. {
  53418. public:
  53419. SliderLabelComp() : Label (String::empty, String::empty) {}
  53420. ~SliderLabelComp() {}
  53421. void mouseWheelMove (const MouseEvent&, float, float) {}
  53422. };
  53423. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53424. {
  53425. Label* const l = new SliderLabelComp();
  53426. l->setJustificationType (Justification::centred);
  53427. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53428. l->setColour (Label::backgroundColourId,
  53429. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53430. : slider.findColour (Slider::textBoxBackgroundColourId));
  53431. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53432. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53433. l->setColour (TextEditor::backgroundColourId,
  53434. slider.findColour (Slider::textBoxBackgroundColourId)
  53435. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53436. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53437. return l;
  53438. }
  53439. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53440. {
  53441. return 0;
  53442. }
  53443. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53444. {
  53445. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (tipText));
  53446. width = tl.getWidth() + 14;
  53447. height = tl.getHeight() + 6;
  53448. }
  53449. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53450. {
  53451. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53452. const Colour textCol (findColour (TooltipWindow::textColourId));
  53453. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53454. g.setColour (findColour (TooltipWindow::outlineColourId));
  53455. g.drawRect (0, 0, width, height, 1);
  53456. #endif
  53457. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (text));
  53458. g.setColour (findColour (TooltipWindow::textColourId));
  53459. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53460. }
  53461. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53462. {
  53463. return new TextButton (text, TRANS("click to browse for a different file"));
  53464. }
  53465. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53466. ComboBox* filenameBox,
  53467. Button* browseButton)
  53468. {
  53469. browseButton->setSize (80, filenameComp.getHeight());
  53470. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53471. if (tb != 0)
  53472. tb->changeWidthToFitText();
  53473. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53474. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53475. }
  53476. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53477. int imageX, int imageY, int imageW, int imageH,
  53478. const Colour& overlayColour,
  53479. float imageOpacity,
  53480. ImageButton& button)
  53481. {
  53482. if (! button.isEnabled())
  53483. imageOpacity *= 0.3f;
  53484. if (! overlayColour.isOpaque())
  53485. {
  53486. g.setOpacity (imageOpacity);
  53487. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53488. 0, 0, image->getWidth(), image->getHeight(), false);
  53489. }
  53490. if (! overlayColour.isTransparent())
  53491. {
  53492. g.setColour (overlayColour);
  53493. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53494. 0, 0, image->getWidth(), image->getHeight(), true);
  53495. }
  53496. }
  53497. void LookAndFeel::drawCornerResizer (Graphics& g,
  53498. int w, int h,
  53499. bool /*isMouseOver*/,
  53500. bool /*isMouseDragging*/)
  53501. {
  53502. const float lineThickness = jmin (w, h) * 0.075f;
  53503. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53504. {
  53505. g.setColour (Colours::lightgrey);
  53506. g.drawLine (w * i,
  53507. h + 1.0f,
  53508. w + 1.0f,
  53509. h * i,
  53510. lineThickness);
  53511. g.setColour (Colours::darkgrey);
  53512. g.drawLine (w * i + lineThickness,
  53513. h + 1.0f,
  53514. w + 1.0f,
  53515. h * i + lineThickness,
  53516. lineThickness);
  53517. }
  53518. }
  53519. void LookAndFeel::drawResizableFrame (Graphics& g, int w, int h, const BorderSize<int>& border)
  53520. {
  53521. if (! border.isEmpty())
  53522. {
  53523. const Rectangle<int> fullSize (0, 0, w, h);
  53524. const Rectangle<int> centreArea (border.subtractedFrom (fullSize));
  53525. g.saveState();
  53526. g.excludeClipRegion (centreArea);
  53527. g.setColour (Colour (0x50000000));
  53528. g.drawRect (fullSize);
  53529. g.setColour (Colour (0x19000000));
  53530. g.drawRect (centreArea.expanded (1, 1));
  53531. g.restoreState();
  53532. }
  53533. }
  53534. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53535. const BorderSize<int>& /*border*/, ResizableWindow& window)
  53536. {
  53537. g.fillAll (window.getBackgroundColour());
  53538. }
  53539. void LookAndFeel::drawResizableWindowBorder (Graphics&, int /*w*/, int /*h*/,
  53540. const BorderSize<int>& /*border*/, ResizableWindow&)
  53541. {
  53542. }
  53543. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53544. Graphics& g, int w, int h,
  53545. int titleSpaceX, int titleSpaceW,
  53546. const Image* icon,
  53547. bool drawTitleTextOnLeft)
  53548. {
  53549. const bool isActive = window.isActiveWindow();
  53550. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53551. 0.0f, 0.0f,
  53552. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53553. 0.0f, (float) h, false));
  53554. g.fillAll();
  53555. Font font (h * 0.65f, Font::bold);
  53556. g.setFont (font);
  53557. int textW = font.getStringWidth (window.getName());
  53558. int iconW = 0;
  53559. int iconH = 0;
  53560. if (icon != 0)
  53561. {
  53562. iconH = (int) font.getHeight();
  53563. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53564. }
  53565. textW = jmin (titleSpaceW, textW + iconW);
  53566. int textX = drawTitleTextOnLeft ? titleSpaceX
  53567. : jmax (titleSpaceX, (w - textW) / 2);
  53568. if (textX + textW > titleSpaceX + titleSpaceW)
  53569. textX = titleSpaceX + titleSpaceW - textW;
  53570. if (icon != 0)
  53571. {
  53572. g.setOpacity (isActive ? 1.0f : 0.6f);
  53573. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53574. RectanglePlacement::centred, false);
  53575. textX += iconW;
  53576. textW -= iconW;
  53577. }
  53578. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53579. g.setColour (findColour (DocumentWindow::textColourId));
  53580. else
  53581. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53582. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53583. }
  53584. class GlassWindowButton : public Button
  53585. {
  53586. public:
  53587. GlassWindowButton (const String& name, const Colour& col,
  53588. const Path& normalShape_,
  53589. const Path& toggledShape_) throw()
  53590. : Button (name),
  53591. colour (col),
  53592. normalShape (normalShape_),
  53593. toggledShape (toggledShape_)
  53594. {
  53595. }
  53596. ~GlassWindowButton()
  53597. {
  53598. }
  53599. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53600. {
  53601. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53602. if (! isEnabled())
  53603. alpha *= 0.5f;
  53604. float x = 0, y = 0, diam;
  53605. if (getWidth() < getHeight())
  53606. {
  53607. diam = (float) getWidth();
  53608. y = (getHeight() - getWidth()) * 0.5f;
  53609. }
  53610. else
  53611. {
  53612. diam = (float) getHeight();
  53613. y = (getWidth() - getHeight()) * 0.5f;
  53614. }
  53615. x += diam * 0.05f;
  53616. y += diam * 0.05f;
  53617. diam *= 0.9f;
  53618. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53619. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53620. g.fillEllipse (x, y, diam, diam);
  53621. x += 2.0f;
  53622. y += 2.0f;
  53623. diam -= 4.0f;
  53624. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53625. Path& p = getToggleState() ? toggledShape : normalShape;
  53626. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53627. diam * 0.4f, diam * 0.4f, true));
  53628. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53629. g.fillPath (p, t);
  53630. }
  53631. private:
  53632. Colour colour;
  53633. Path normalShape, toggledShape;
  53634. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlassWindowButton);
  53635. };
  53636. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53637. {
  53638. Path shape;
  53639. const float crossThickness = 0.25f;
  53640. if (buttonType == DocumentWindow::closeButton)
  53641. {
  53642. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53643. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53644. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53645. }
  53646. else if (buttonType == DocumentWindow::minimiseButton)
  53647. {
  53648. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53649. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53650. }
  53651. else if (buttonType == DocumentWindow::maximiseButton)
  53652. {
  53653. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53654. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53655. Path fullscreenShape;
  53656. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53657. fullscreenShape.lineTo (0.0f, 100.0f);
  53658. fullscreenShape.lineTo (0.0f, 0.0f);
  53659. fullscreenShape.lineTo (100.0f, 0.0f);
  53660. fullscreenShape.lineTo (100.0f, 45.0f);
  53661. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53662. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53663. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53664. }
  53665. jassertfalse;
  53666. return 0;
  53667. }
  53668. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53669. int titleBarX,
  53670. int titleBarY,
  53671. int titleBarW,
  53672. int titleBarH,
  53673. Button* minimiseButton,
  53674. Button* maximiseButton,
  53675. Button* closeButton,
  53676. bool positionTitleBarButtonsOnLeft)
  53677. {
  53678. const int buttonW = titleBarH - titleBarH / 8;
  53679. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53680. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53681. if (closeButton != 0)
  53682. {
  53683. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53684. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53685. }
  53686. if (positionTitleBarButtonsOnLeft)
  53687. swapVariables (minimiseButton, maximiseButton);
  53688. if (maximiseButton != 0)
  53689. {
  53690. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53691. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53692. }
  53693. if (minimiseButton != 0)
  53694. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53695. }
  53696. int LookAndFeel::getDefaultMenuBarHeight()
  53697. {
  53698. return 24;
  53699. }
  53700. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53701. {
  53702. return new DropShadower (0.4f, 1, 5, 10);
  53703. }
  53704. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53705. int w, int h,
  53706. bool /*isVerticalBar*/,
  53707. bool isMouseOver,
  53708. bool isMouseDragging)
  53709. {
  53710. float alpha = 0.5f;
  53711. if (isMouseOver || isMouseDragging)
  53712. {
  53713. g.fillAll (Colour (0x190000ff));
  53714. alpha = 1.0f;
  53715. }
  53716. const float cx = w * 0.5f;
  53717. const float cy = h * 0.5f;
  53718. const float cr = jmin (w, h) * 0.4f;
  53719. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53720. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53721. true));
  53722. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53723. }
  53724. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53725. const String& text,
  53726. const Justification& position,
  53727. GroupComponent& group)
  53728. {
  53729. const float textH = 15.0f;
  53730. const float indent = 3.0f;
  53731. const float textEdgeGap = 4.0f;
  53732. float cs = 5.0f;
  53733. Font f (textH);
  53734. Path p;
  53735. float x = indent;
  53736. float y = f.getAscent() - 3.0f;
  53737. float w = jmax (0.0f, width - x * 2.0f);
  53738. float h = jmax (0.0f, height - y - indent);
  53739. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53740. const float cs2 = 2.0f * cs;
  53741. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53742. float textX = cs + textEdgeGap;
  53743. if (position.testFlags (Justification::horizontallyCentred))
  53744. textX = cs + (w - cs2 - textW) * 0.5f;
  53745. else if (position.testFlags (Justification::right))
  53746. textX = w - cs - textW - textEdgeGap;
  53747. p.startNewSubPath (x + textX + textW, y);
  53748. p.lineTo (x + w - cs, y);
  53749. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53750. p.lineTo (x + w, y + h - cs);
  53751. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53752. p.lineTo (x + cs, y + h);
  53753. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53754. p.lineTo (x, y + cs);
  53755. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53756. p.lineTo (x + textX, y);
  53757. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53758. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53759. .withMultipliedAlpha (alpha));
  53760. g.strokePath (p, PathStrokeType (2.0f));
  53761. g.setColour (group.findColour (GroupComponent::textColourId)
  53762. .withMultipliedAlpha (alpha));
  53763. g.setFont (f);
  53764. g.drawText (text,
  53765. roundToInt (x + textX), 0,
  53766. roundToInt (textW),
  53767. roundToInt (textH),
  53768. Justification::centred, true);
  53769. }
  53770. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53771. {
  53772. return 1 + tabDepth / 3;
  53773. }
  53774. int LookAndFeel::getTabButtonSpaceAroundImage()
  53775. {
  53776. return 4;
  53777. }
  53778. void LookAndFeel::createTabButtonShape (Path& p,
  53779. int width, int height,
  53780. int /*tabIndex*/,
  53781. const String& /*text*/,
  53782. Button& /*button*/,
  53783. TabbedButtonBar::Orientation orientation,
  53784. const bool /*isMouseOver*/,
  53785. const bool /*isMouseDown*/,
  53786. const bool /*isFrontTab*/)
  53787. {
  53788. const float w = (float) width;
  53789. const float h = (float) height;
  53790. float length = w;
  53791. float depth = h;
  53792. if (orientation == TabbedButtonBar::TabsAtLeft
  53793. || orientation == TabbedButtonBar::TabsAtRight)
  53794. {
  53795. swapVariables (length, depth);
  53796. }
  53797. const float indent = (float) getTabButtonOverlap ((int) depth);
  53798. const float overhang = 4.0f;
  53799. if (orientation == TabbedButtonBar::TabsAtLeft)
  53800. {
  53801. p.startNewSubPath (w, 0.0f);
  53802. p.lineTo (0.0f, indent);
  53803. p.lineTo (0.0f, h - indent);
  53804. p.lineTo (w, h);
  53805. p.lineTo (w + overhang, h + overhang);
  53806. p.lineTo (w + overhang, -overhang);
  53807. }
  53808. else if (orientation == TabbedButtonBar::TabsAtRight)
  53809. {
  53810. p.startNewSubPath (0.0f, 0.0f);
  53811. p.lineTo (w, indent);
  53812. p.lineTo (w, h - indent);
  53813. p.lineTo (0.0f, h);
  53814. p.lineTo (-overhang, h + overhang);
  53815. p.lineTo (-overhang, -overhang);
  53816. }
  53817. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53818. {
  53819. p.startNewSubPath (0.0f, 0.0f);
  53820. p.lineTo (indent, h);
  53821. p.lineTo (w - indent, h);
  53822. p.lineTo (w, 0.0f);
  53823. p.lineTo (w + overhang, -overhang);
  53824. p.lineTo (-overhang, -overhang);
  53825. }
  53826. else
  53827. {
  53828. p.startNewSubPath (0.0f, h);
  53829. p.lineTo (indent, 0.0f);
  53830. p.lineTo (w - indent, 0.0f);
  53831. p.lineTo (w, h);
  53832. p.lineTo (w + overhang, h + overhang);
  53833. p.lineTo (-overhang, h + overhang);
  53834. }
  53835. p.closeSubPath();
  53836. p = p.createPathWithRoundedCorners (3.0f);
  53837. }
  53838. void LookAndFeel::fillTabButtonShape (Graphics& g,
  53839. const Path& path,
  53840. const Colour& preferredColour,
  53841. int /*tabIndex*/,
  53842. const String& /*text*/,
  53843. Button& button,
  53844. TabbedButtonBar::Orientation /*orientation*/,
  53845. const bool /*isMouseOver*/,
  53846. const bool /*isMouseDown*/,
  53847. const bool isFrontTab)
  53848. {
  53849. g.setColour (isFrontTab ? preferredColour
  53850. : preferredColour.withMultipliedAlpha (0.9f));
  53851. g.fillPath (path);
  53852. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  53853. : TabbedButtonBar::tabOutlineColourId, false)
  53854. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  53855. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  53856. }
  53857. void LookAndFeel::drawTabButtonText (Graphics& g,
  53858. int x, int y, int w, int h,
  53859. const Colour& preferredBackgroundColour,
  53860. int /*tabIndex*/,
  53861. const String& text,
  53862. Button& button,
  53863. TabbedButtonBar::Orientation orientation,
  53864. const bool isMouseOver,
  53865. const bool isMouseDown,
  53866. const bool isFrontTab)
  53867. {
  53868. int length = w;
  53869. int depth = h;
  53870. if (orientation == TabbedButtonBar::TabsAtLeft
  53871. || orientation == TabbedButtonBar::TabsAtRight)
  53872. {
  53873. swapVariables (length, depth);
  53874. }
  53875. Font font (depth * 0.6f);
  53876. font.setUnderline (button.hasKeyboardFocus (false));
  53877. GlyphArrangement textLayout;
  53878. textLayout.addFittedText (font, text.trim(),
  53879. 0.0f, 0.0f, (float) length, (float) depth,
  53880. Justification::centred,
  53881. jmax (1, depth / 12));
  53882. AffineTransform transform;
  53883. if (orientation == TabbedButtonBar::TabsAtLeft)
  53884. {
  53885. transform = transform.rotated (float_Pi * -0.5f)
  53886. .translated ((float) x, (float) (y + h));
  53887. }
  53888. else if (orientation == TabbedButtonBar::TabsAtRight)
  53889. {
  53890. transform = transform.rotated (float_Pi * 0.5f)
  53891. .translated ((float) (x + w), (float) y);
  53892. }
  53893. else
  53894. {
  53895. transform = transform.translated ((float) x, (float) y);
  53896. }
  53897. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  53898. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  53899. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  53900. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  53901. else
  53902. g.setColour (preferredBackgroundColour.contrasting());
  53903. if (! (isMouseOver || isMouseDown))
  53904. g.setOpacity (0.8f);
  53905. if (! button.isEnabled())
  53906. g.setOpacity (0.3f);
  53907. textLayout.draw (g, transform);
  53908. }
  53909. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  53910. const String& text,
  53911. int tabDepth,
  53912. Button&)
  53913. {
  53914. Font f (tabDepth * 0.6f);
  53915. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  53916. }
  53917. void LookAndFeel::drawTabButton (Graphics& g,
  53918. int w, int h,
  53919. const Colour& preferredColour,
  53920. int tabIndex,
  53921. const String& text,
  53922. Button& button,
  53923. TabbedButtonBar::Orientation orientation,
  53924. const bool isMouseOver,
  53925. const bool isMouseDown,
  53926. const bool isFrontTab)
  53927. {
  53928. int length = w;
  53929. int depth = h;
  53930. if (orientation == TabbedButtonBar::TabsAtLeft
  53931. || orientation == TabbedButtonBar::TabsAtRight)
  53932. {
  53933. swapVariables (length, depth);
  53934. }
  53935. Path tabShape;
  53936. createTabButtonShape (tabShape, w, h,
  53937. tabIndex, text, button, orientation,
  53938. isMouseOver, isMouseDown, isFrontTab);
  53939. fillTabButtonShape (g, tabShape, preferredColour,
  53940. tabIndex, text, button, orientation,
  53941. isMouseOver, isMouseDown, isFrontTab);
  53942. const int indent = getTabButtonOverlap (depth);
  53943. int x = 0, y = 0;
  53944. if (orientation == TabbedButtonBar::TabsAtLeft
  53945. || orientation == TabbedButtonBar::TabsAtRight)
  53946. {
  53947. y += indent;
  53948. h -= indent * 2;
  53949. }
  53950. else
  53951. {
  53952. x += indent;
  53953. w -= indent * 2;
  53954. }
  53955. drawTabButtonText (g, x, y, w, h, preferredColour,
  53956. tabIndex, text, button, orientation,
  53957. isMouseOver, isMouseDown, isFrontTab);
  53958. }
  53959. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  53960. int w, int h,
  53961. TabbedButtonBar& tabBar,
  53962. TabbedButtonBar::Orientation orientation)
  53963. {
  53964. const float shadowSize = 0.2f;
  53965. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  53966. Rectangle<int> shadowRect;
  53967. if (orientation == TabbedButtonBar::TabsAtLeft)
  53968. {
  53969. x1 = (float) w;
  53970. x2 = w * (1.0f - shadowSize);
  53971. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  53972. }
  53973. else if (orientation == TabbedButtonBar::TabsAtRight)
  53974. {
  53975. x2 = w * shadowSize;
  53976. shadowRect.setBounds (0, 0, (int) x2, h);
  53977. }
  53978. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53979. {
  53980. y2 = h * shadowSize;
  53981. shadowRect.setBounds (0, 0, w, (int) y2);
  53982. }
  53983. else
  53984. {
  53985. y1 = (float) h;
  53986. y2 = h * (1.0f - shadowSize);
  53987. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  53988. }
  53989. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  53990. Colours::transparentBlack, x2, y2, false));
  53991. shadowRect.expand (2, 2);
  53992. g.fillRect (shadowRect);
  53993. g.setColour (Colour (0x80000000));
  53994. if (orientation == TabbedButtonBar::TabsAtLeft)
  53995. {
  53996. g.fillRect (w - 1, 0, 1, h);
  53997. }
  53998. else if (orientation == TabbedButtonBar::TabsAtRight)
  53999. {
  54000. g.fillRect (0, 0, 1, h);
  54001. }
  54002. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54003. {
  54004. g.fillRect (0, 0, w, 1);
  54005. }
  54006. else
  54007. {
  54008. g.fillRect (0, h - 1, w, 1);
  54009. }
  54010. }
  54011. Button* LookAndFeel::createTabBarExtrasButton()
  54012. {
  54013. const float thickness = 7.0f;
  54014. const float indent = 22.0f;
  54015. Path p;
  54016. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  54017. DrawablePath ellipse;
  54018. ellipse.setPath (p);
  54019. ellipse.setFill (Colour (0x99ffffff));
  54020. p.clear();
  54021. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54022. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54023. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54024. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54025. p.setUsingNonZeroWinding (false);
  54026. DrawablePath dp;
  54027. dp.setPath (p);
  54028. dp.setFill (Colour (0x59000000));
  54029. DrawableComposite normalImage;
  54030. normalImage.addAndMakeVisible (ellipse.createCopy());
  54031. normalImage.addAndMakeVisible (dp.createCopy());
  54032. dp.setFill (Colour (0xcc000000));
  54033. DrawableComposite overImage;
  54034. overImage.addAndMakeVisible (ellipse.createCopy());
  54035. overImage.addAndMakeVisible (dp.createCopy());
  54036. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54037. db->setImages (&normalImage, &overImage, 0);
  54038. return db;
  54039. }
  54040. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54041. {
  54042. g.fillAll (Colours::white);
  54043. const int w = header.getWidth();
  54044. const int h = header.getHeight();
  54045. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54046. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54047. false));
  54048. g.fillRect (0, h / 2, w, h);
  54049. g.setColour (Colour (0x33000000));
  54050. g.fillRect (0, h - 1, w, 1);
  54051. for (int i = header.getNumColumns (true); --i >= 0;)
  54052. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54053. }
  54054. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54055. int width, int height,
  54056. bool isMouseOver, bool isMouseDown,
  54057. int columnFlags)
  54058. {
  54059. if (isMouseDown)
  54060. g.fillAll (Colour (0x8899aadd));
  54061. else if (isMouseOver)
  54062. g.fillAll (Colour (0x5599aadd));
  54063. int rightOfText = width - 4;
  54064. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54065. {
  54066. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54067. const float bottom = height - top;
  54068. const float w = height * 0.5f;
  54069. const float x = rightOfText - (w * 1.25f);
  54070. rightOfText = (int) x;
  54071. Path sortArrow;
  54072. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54073. g.setColour (Colour (0x99000000));
  54074. g.fillPath (sortArrow);
  54075. }
  54076. g.setColour (Colours::black);
  54077. g.setFont (height * 0.5f, Font::bold);
  54078. const int textX = 4;
  54079. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54080. }
  54081. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54082. {
  54083. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54084. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54085. background.darker (0.1f),
  54086. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54087. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54088. false));
  54089. g.fillAll();
  54090. }
  54091. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54092. {
  54093. return createTabBarExtrasButton();
  54094. }
  54095. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54096. bool isMouseOver, bool isMouseDown,
  54097. ToolbarItemComponent& component)
  54098. {
  54099. if (isMouseDown)
  54100. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54101. else if (isMouseOver)
  54102. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54103. }
  54104. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54105. const String& text, ToolbarItemComponent& component)
  54106. {
  54107. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54108. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54109. const float fontHeight = jmin (14.0f, height * 0.85f);
  54110. g.setFont (fontHeight);
  54111. g.drawFittedText (text,
  54112. x, y, width, height,
  54113. Justification::centred,
  54114. jmax (1, height / (int) fontHeight));
  54115. }
  54116. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54117. bool isOpen, int width, int height)
  54118. {
  54119. const int buttonSize = (height * 3) / 4;
  54120. const int buttonIndent = (height - buttonSize) / 2;
  54121. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54122. const int textX = buttonIndent * 2 + buttonSize + 2;
  54123. g.setColour (Colours::black);
  54124. g.setFont (height * 0.7f, Font::bold);
  54125. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54126. }
  54127. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54128. PropertyComponent&)
  54129. {
  54130. g.setColour (Colour (0x66ffffff));
  54131. g.fillRect (0, 0, width, height - 1);
  54132. }
  54133. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54134. PropertyComponent& component)
  54135. {
  54136. g.setColour (Colours::black);
  54137. if (! component.isEnabled())
  54138. g.setOpacity (0.6f);
  54139. g.setFont (jmin (height, 24) * 0.65f);
  54140. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54141. g.drawFittedText (component.getName(),
  54142. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54143. Justification::centredLeft, 2);
  54144. }
  54145. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54146. {
  54147. return Rectangle<int> (component.getWidth() / 3, 1,
  54148. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54149. }
  54150. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54151. {
  54152. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54153. {
  54154. Graphics g2 (content);
  54155. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54156. g2.fillPath (path);
  54157. g2.setColour (Colours::white.withAlpha (0.8f));
  54158. g2.strokePath (path, PathStrokeType (2.0f));
  54159. }
  54160. DropShadowEffect shadow;
  54161. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54162. shadow.applyEffect (content, g, 1.0f);
  54163. }
  54164. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54165. const String& instructions,
  54166. GlyphArrangement& text,
  54167. int width)
  54168. {
  54169. text.clear();
  54170. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54171. 8.0f, 22.0f, width - 16.0f,
  54172. Justification::centred);
  54173. text.addJustifiedText (Font (14.0f), instructions,
  54174. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54175. Justification::centred);
  54176. }
  54177. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54178. const String& filename, Image* icon,
  54179. const String& fileSizeDescription,
  54180. const String& fileTimeDescription,
  54181. const bool isDirectory,
  54182. const bool isItemSelected,
  54183. const int /*itemIndex*/,
  54184. DirectoryContentsDisplayComponent&)
  54185. {
  54186. if (isItemSelected)
  54187. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54188. const int x = 32;
  54189. g.setColour (Colours::black);
  54190. if (icon != 0 && icon->isValid())
  54191. {
  54192. g.drawImageWithin (*icon, 2, 2, x - 4, height - 4,
  54193. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54194. false);
  54195. }
  54196. else
  54197. {
  54198. const Drawable* d = isDirectory ? getDefaultFolderImage()
  54199. : getDefaultDocumentFileImage();
  54200. if (d != 0)
  54201. d->drawWithin (g, Rectangle<float> (2.0f, 2.0f, x - 4.0f, height - 4.0f),
  54202. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, 1.0f);
  54203. }
  54204. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54205. g.setFont (height * 0.7f);
  54206. if (width > 450 && ! isDirectory)
  54207. {
  54208. const int sizeX = roundToInt (width * 0.7f);
  54209. const int dateX = roundToInt (width * 0.8f);
  54210. g.drawFittedText (filename,
  54211. x, 0, sizeX - x, height,
  54212. Justification::centredLeft, 1);
  54213. g.setFont (height * 0.5f);
  54214. g.setColour (Colours::darkgrey);
  54215. if (! isDirectory)
  54216. {
  54217. g.drawFittedText (fileSizeDescription,
  54218. sizeX, 0, dateX - sizeX - 8, height,
  54219. Justification::centredRight, 1);
  54220. g.drawFittedText (fileTimeDescription,
  54221. dateX, 0, width - 8 - dateX, height,
  54222. Justification::centredRight, 1);
  54223. }
  54224. }
  54225. else
  54226. {
  54227. g.drawFittedText (filename,
  54228. x, 0, width - x, height,
  54229. Justification::centredLeft, 1);
  54230. }
  54231. }
  54232. Button* LookAndFeel::createFileBrowserGoUpButton()
  54233. {
  54234. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54235. Path arrowPath;
  54236. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54237. DrawablePath arrowImage;
  54238. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54239. arrowImage.setPath (arrowPath);
  54240. goUpButton->setImages (&arrowImage);
  54241. return goUpButton;
  54242. }
  54243. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54244. DirectoryContentsDisplayComponent* fileListComponent,
  54245. FilePreviewComponent* previewComp,
  54246. ComboBox* currentPathBox,
  54247. TextEditor* filenameBox,
  54248. Button* goUpButton)
  54249. {
  54250. const int x = 8;
  54251. int w = browserComp.getWidth() - x - x;
  54252. if (previewComp != 0)
  54253. {
  54254. const int previewWidth = w / 3;
  54255. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54256. w -= previewWidth + 4;
  54257. }
  54258. int y = 4;
  54259. const int controlsHeight = 22;
  54260. const int bottomSectionHeight = controlsHeight + 8;
  54261. const int upButtonWidth = 50;
  54262. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54263. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54264. y += controlsHeight + 4;
  54265. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54266. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54267. y = listAsComp->getBottom() + 4;
  54268. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54269. }
  54270. // Pulls a drawable out of compressed valuetree data..
  54271. Drawable* LookAndFeel::loadDrawableFromData (const void* data, size_t numBytes)
  54272. {
  54273. MemoryInputStream m (data, numBytes, false);
  54274. GZIPDecompressorInputStream gz (m);
  54275. ValueTree drawable (ValueTree::readFromStream (gz));
  54276. return Drawable::createFromValueTree (drawable.getChild (0), 0);
  54277. }
  54278. const Drawable* LookAndFeel::getDefaultFolderImage()
  54279. {
  54280. if (folderImage == 0)
  54281. {
  54282. static const unsigned char drawableData[] =
  54283. { 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,
  54284. 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,
  54285. 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,
  54286. 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,
  54287. 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,
  54288. 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,
  54289. 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,
  54290. 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,
  54291. 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,
  54292. 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,
  54293. 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,
  54294. 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,
  54295. 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,
  54296. 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,
  54297. 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 };
  54298. folderImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54299. }
  54300. return folderImage;
  54301. }
  54302. const Drawable* LookAndFeel::getDefaultDocumentFileImage()
  54303. {
  54304. if (documentImage == 0)
  54305. {
  54306. static const unsigned char drawableData[] =
  54307. { 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,
  54308. 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,
  54309. 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,
  54310. 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,
  54311. 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,
  54312. 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,
  54313. 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,
  54314. 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,
  54315. 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,
  54316. 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,
  54317. 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,
  54318. 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,
  54319. 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,
  54320. 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,
  54321. 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,
  54322. 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,
  54323. 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,
  54324. 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,
  54325. 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,
  54326. 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,
  54327. 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,
  54328. 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,
  54329. 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 };
  54330. documentImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54331. }
  54332. return documentImage;
  54333. }
  54334. void LookAndFeel::playAlertSound()
  54335. {
  54336. PlatformUtilities::beep();
  54337. }
  54338. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54339. {
  54340. g.setColour (Colours::white.withAlpha (0.7f));
  54341. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54342. g.setColour (Colours::black.withAlpha (0.2f));
  54343. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54344. const int totalBlocks = 7;
  54345. const int numBlocks = roundToInt (totalBlocks * level);
  54346. const float w = (width - 6.0f) / (float) totalBlocks;
  54347. for (int i = 0; i < totalBlocks; ++i)
  54348. {
  54349. if (i >= numBlocks)
  54350. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54351. else
  54352. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54353. : Colours::red);
  54354. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54355. }
  54356. }
  54357. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54358. {
  54359. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54360. if (keyDescription.isNotEmpty())
  54361. {
  54362. if (button.isEnabled())
  54363. {
  54364. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54365. g.fillAll (textColour.withAlpha (alpha));
  54366. g.setOpacity (0.3f);
  54367. g.drawBevel (0, 0, width, height, 2);
  54368. }
  54369. g.setColour (textColour);
  54370. g.setFont (height * 0.6f);
  54371. g.drawFittedText (keyDescription,
  54372. 3, 0, width - 6, height,
  54373. Justification::centred, 1);
  54374. }
  54375. else
  54376. {
  54377. const float thickness = 7.0f;
  54378. const float indent = 22.0f;
  54379. Path p;
  54380. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54381. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54382. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54383. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54384. p.setUsingNonZeroWinding (false);
  54385. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54386. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54387. }
  54388. if (button.hasKeyboardFocus (false))
  54389. {
  54390. g.setColour (textColour.withAlpha (0.4f));
  54391. g.drawRect (0, 0, width, height);
  54392. }
  54393. }
  54394. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54395. float x, float y, float w, float h,
  54396. float maxCornerSize,
  54397. const Colour& baseColour,
  54398. const float strokeWidth,
  54399. const bool flatOnLeft,
  54400. const bool flatOnRight,
  54401. const bool flatOnTop,
  54402. const bool flatOnBottom) throw()
  54403. {
  54404. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54405. return;
  54406. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54407. Path outline;
  54408. LookAndFeelHelpers::createRoundedPath (outline, x, y, w, h, cs,
  54409. ! (flatOnLeft || flatOnTop),
  54410. ! (flatOnRight || flatOnTop),
  54411. ! (flatOnLeft || flatOnBottom),
  54412. ! (flatOnRight || flatOnBottom));
  54413. ColourGradient cg (baseColour, 0.0f, y,
  54414. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54415. false);
  54416. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54417. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54418. g.setGradientFill (cg);
  54419. g.fillPath (outline);
  54420. g.setColour (Colour (0x80000000));
  54421. g.strokePath (outline, PathStrokeType (strokeWidth));
  54422. }
  54423. void LookAndFeel::drawGlassSphere (Graphics& g,
  54424. const float x, const float y,
  54425. const float diameter,
  54426. const Colour& colour,
  54427. const float outlineThickness) throw()
  54428. {
  54429. if (diameter <= outlineThickness)
  54430. return;
  54431. Path p;
  54432. p.addEllipse (x, y, diameter, diameter);
  54433. {
  54434. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54435. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54436. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54437. g.setGradientFill (cg);
  54438. g.fillPath (p);
  54439. }
  54440. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54441. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54442. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54443. ColourGradient cg (Colours::transparentBlack,
  54444. x + diameter * 0.5f, y + diameter * 0.5f,
  54445. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54446. x, y + diameter * 0.5f, true);
  54447. cg.addColour (0.7, Colours::transparentBlack);
  54448. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54449. g.setGradientFill (cg);
  54450. g.fillPath (p);
  54451. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54452. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54453. }
  54454. void LookAndFeel::drawGlassPointer (Graphics& g,
  54455. const float x, const float y,
  54456. const float diameter,
  54457. const Colour& colour, const float outlineThickness,
  54458. const int direction) throw()
  54459. {
  54460. if (diameter <= outlineThickness)
  54461. return;
  54462. Path p;
  54463. p.startNewSubPath (x + diameter * 0.5f, y);
  54464. p.lineTo (x + diameter, y + diameter * 0.6f);
  54465. p.lineTo (x + diameter, y + diameter);
  54466. p.lineTo (x, y + diameter);
  54467. p.lineTo (x, y + diameter * 0.6f);
  54468. p.closeSubPath();
  54469. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54470. {
  54471. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54472. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54473. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54474. g.setGradientFill (cg);
  54475. g.fillPath (p);
  54476. }
  54477. ColourGradient cg (Colours::transparentBlack,
  54478. x + diameter * 0.5f, y + diameter * 0.5f,
  54479. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54480. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54481. cg.addColour (0.5, Colours::transparentBlack);
  54482. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54483. g.setGradientFill (cg);
  54484. g.fillPath (p);
  54485. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54486. g.strokePath (p, PathStrokeType (outlineThickness));
  54487. }
  54488. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54489. const float x, const float y,
  54490. const float width, const float height,
  54491. const Colour& colour,
  54492. const float outlineThickness,
  54493. const float cornerSize,
  54494. const bool flatOnLeft,
  54495. const bool flatOnRight,
  54496. const bool flatOnTop,
  54497. const bool flatOnBottom) throw()
  54498. {
  54499. if (width <= outlineThickness || height <= outlineThickness)
  54500. return;
  54501. const int intX = (int) x;
  54502. const int intY = (int) y;
  54503. const int intW = (int) width;
  54504. const int intH = (int) height;
  54505. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54506. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54507. const int intEdge = (int) edgeBlurRadius;
  54508. Path outline;
  54509. LookAndFeelHelpers::createRoundedPath (outline, x, y, width, height, cs,
  54510. ! (flatOnLeft || flatOnTop),
  54511. ! (flatOnRight || flatOnTop),
  54512. ! (flatOnLeft || flatOnBottom),
  54513. ! (flatOnRight || flatOnBottom));
  54514. {
  54515. ColourGradient cg (colour.darker (0.2f), 0, y,
  54516. colour.darker (0.2f), 0, y + height, false);
  54517. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54518. cg.addColour (0.4, colour);
  54519. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54520. g.setGradientFill (cg);
  54521. g.fillPath (outline);
  54522. }
  54523. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54524. colour.darker (0.2f), x, y + height * 0.5f, true);
  54525. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54526. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54527. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54528. {
  54529. g.saveState();
  54530. g.setGradientFill (cg);
  54531. g.reduceClipRegion (intX, intY, intEdge, intH);
  54532. g.fillPath (outline);
  54533. g.restoreState();
  54534. }
  54535. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54536. {
  54537. cg.point1.setX (x + width - edgeBlurRadius);
  54538. cg.point2.setX (x + width);
  54539. g.saveState();
  54540. g.setGradientFill (cg);
  54541. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54542. g.fillPath (outline);
  54543. g.restoreState();
  54544. }
  54545. {
  54546. const float leftIndent = flatOnTop || flatOnLeft ? 0.0f : cs * 0.4f;
  54547. const float rightIndent = flatOnTop || flatOnRight ? 0.0f : cs * 0.4f;
  54548. Path highlight;
  54549. LookAndFeelHelpers::createRoundedPath (highlight,
  54550. x + leftIndent,
  54551. y + cs * 0.1f,
  54552. width - (leftIndent + rightIndent),
  54553. height * 0.4f, cs * 0.4f,
  54554. ! (flatOnLeft || flatOnTop),
  54555. ! (flatOnRight || flatOnTop),
  54556. ! (flatOnLeft || flatOnBottom),
  54557. ! (flatOnRight || flatOnBottom));
  54558. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54559. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54560. g.fillPath (highlight);
  54561. }
  54562. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54563. g.strokePath (outline, PathStrokeType (outlineThickness));
  54564. }
  54565. END_JUCE_NAMESPACE
  54566. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54567. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54568. BEGIN_JUCE_NAMESPACE
  54569. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54570. {
  54571. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54572. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54573. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54574. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54575. setColour (Slider::thumbColourId, Colours::white);
  54576. setColour (Slider::trackColourId, Colour (0x7f000000));
  54577. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54578. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54579. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54580. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54581. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54582. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54583. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54584. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54585. }
  54586. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54587. {
  54588. }
  54589. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54590. Button& button,
  54591. const Colour& backgroundColour,
  54592. bool isMouseOverButton,
  54593. bool isButtonDown)
  54594. {
  54595. const int width = button.getWidth();
  54596. const int height = button.getHeight();
  54597. const float indent = 2.0f;
  54598. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54599. roundToInt (height * 0.4f));
  54600. Path p;
  54601. p.addRoundedRectangle (indent, indent,
  54602. width - indent * 2.0f,
  54603. height - indent * 2.0f,
  54604. (float) cornerSize);
  54605. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54606. if (isMouseOverButton)
  54607. {
  54608. if (isButtonDown)
  54609. bc = bc.brighter();
  54610. else if (bc.getBrightness() > 0.5f)
  54611. bc = bc.darker (0.1f);
  54612. else
  54613. bc = bc.brighter (0.1f);
  54614. }
  54615. g.setColour (bc);
  54616. g.fillPath (p);
  54617. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54618. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54619. }
  54620. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54621. Component& /*component*/,
  54622. float x, float y, float w, float h,
  54623. const bool ticked,
  54624. const bool isEnabled,
  54625. const bool /*isMouseOverButton*/,
  54626. const bool isButtonDown)
  54627. {
  54628. Path box;
  54629. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54630. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54631. : Colours::lightgrey.withAlpha (0.1f));
  54632. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54633. g.fillPath (box, trans);
  54634. g.setColour (Colours::black.withAlpha (0.6f));
  54635. g.strokePath (box, PathStrokeType (0.9f), trans);
  54636. if (ticked)
  54637. {
  54638. Path tick;
  54639. tick.startNewSubPath (1.5f, 3.0f);
  54640. tick.lineTo (3.0f, 6.0f);
  54641. tick.lineTo (6.0f, 0.0f);
  54642. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54643. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54644. }
  54645. }
  54646. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54647. ToggleButton& button,
  54648. bool isMouseOverButton,
  54649. bool isButtonDown)
  54650. {
  54651. if (button.hasKeyboardFocus (true))
  54652. {
  54653. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54654. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54655. }
  54656. const int tickWidth = jmin (20, button.getHeight() - 4);
  54657. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54658. (float) tickWidth, (float) tickWidth,
  54659. button.getToggleState(),
  54660. button.isEnabled(),
  54661. isMouseOverButton,
  54662. isButtonDown);
  54663. g.setColour (button.findColour (ToggleButton::textColourId));
  54664. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54665. if (! button.isEnabled())
  54666. g.setOpacity (0.5f);
  54667. const int textX = tickWidth + 5;
  54668. g.drawFittedText (button.getButtonText(),
  54669. textX, 4,
  54670. button.getWidth() - textX - 2, button.getHeight() - 8,
  54671. Justification::centredLeft, 10);
  54672. }
  54673. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54674. int width, int height,
  54675. double progress, const String& textToShow)
  54676. {
  54677. if (progress < 0 || progress >= 1.0)
  54678. {
  54679. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54680. }
  54681. else
  54682. {
  54683. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54684. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54685. g.fillAll (background);
  54686. g.setColour (foreground);
  54687. g.fillRect (1, 1,
  54688. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54689. height - 2);
  54690. if (textToShow.isNotEmpty())
  54691. {
  54692. g.setColour (Colour::contrasting (background, foreground));
  54693. g.setFont (height * 0.6f);
  54694. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54695. }
  54696. }
  54697. }
  54698. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54699. ScrollBar& bar,
  54700. int width, int height,
  54701. int buttonDirection,
  54702. bool isScrollbarVertical,
  54703. bool isMouseOverButton,
  54704. bool isButtonDown)
  54705. {
  54706. if (isScrollbarVertical)
  54707. width -= 2;
  54708. else
  54709. height -= 2;
  54710. Path p;
  54711. if (buttonDirection == 0)
  54712. p.addTriangle (width * 0.5f, height * 0.2f,
  54713. width * 0.1f, height * 0.7f,
  54714. width * 0.9f, height * 0.7f);
  54715. else if (buttonDirection == 1)
  54716. p.addTriangle (width * 0.8f, height * 0.5f,
  54717. width * 0.3f, height * 0.1f,
  54718. width * 0.3f, height * 0.9f);
  54719. else if (buttonDirection == 2)
  54720. p.addTriangle (width * 0.5f, height * 0.8f,
  54721. width * 0.1f, height * 0.3f,
  54722. width * 0.9f, height * 0.3f);
  54723. else if (buttonDirection == 3)
  54724. p.addTriangle (width * 0.2f, height * 0.5f,
  54725. width * 0.7f, height * 0.1f,
  54726. width * 0.7f, height * 0.9f);
  54727. if (isButtonDown)
  54728. g.setColour (Colours::white);
  54729. else if (isMouseOverButton)
  54730. g.setColour (Colours::white.withAlpha (0.7f));
  54731. else
  54732. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54733. g.fillPath (p);
  54734. g.setColour (Colours::black.withAlpha (0.5f));
  54735. g.strokePath (p, PathStrokeType (0.5f));
  54736. }
  54737. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54738. ScrollBar& bar,
  54739. int x, int y,
  54740. int width, int height,
  54741. bool isScrollbarVertical,
  54742. int thumbStartPosition,
  54743. int thumbSize,
  54744. bool isMouseOver,
  54745. bool isMouseDown)
  54746. {
  54747. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54748. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54749. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54750. if (thumbSize > 0.0f)
  54751. {
  54752. Rectangle<int> thumb;
  54753. if (isScrollbarVertical)
  54754. {
  54755. width -= 2;
  54756. g.fillRect (x + roundToInt (width * 0.35f), y,
  54757. roundToInt (width * 0.3f), height);
  54758. thumb.setBounds (x + 1, thumbStartPosition,
  54759. width - 2, thumbSize);
  54760. }
  54761. else
  54762. {
  54763. height -= 2;
  54764. g.fillRect (x, y + roundToInt (height * 0.35f),
  54765. width, roundToInt (height * 0.3f));
  54766. thumb.setBounds (thumbStartPosition, y + 1,
  54767. thumbSize, height - 2);
  54768. }
  54769. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54770. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54771. g.fillRect (thumb);
  54772. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54773. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54774. if (thumbSize > 16)
  54775. {
  54776. for (int i = 3; --i >= 0;)
  54777. {
  54778. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54779. g.setColour (Colours::black.withAlpha (0.15f));
  54780. if (isScrollbarVertical)
  54781. {
  54782. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  54783. g.setColour (Colours::white.withAlpha (0.15f));
  54784. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  54785. }
  54786. else
  54787. {
  54788. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  54789. g.setColour (Colours::white.withAlpha (0.15f));
  54790. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  54791. }
  54792. }
  54793. }
  54794. }
  54795. }
  54796. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  54797. {
  54798. return &scrollbarShadow;
  54799. }
  54800. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  54801. {
  54802. g.fillAll (findColour (PopupMenu::backgroundColourId));
  54803. g.setColour (Colours::black.withAlpha (0.6f));
  54804. g.drawRect (0, 0, width, height);
  54805. }
  54806. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  54807. bool, MenuBarComponent& menuBar)
  54808. {
  54809. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  54810. }
  54811. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  54812. {
  54813. if (textEditor.isEnabled())
  54814. {
  54815. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  54816. g.drawRect (0, 0, width, height);
  54817. }
  54818. }
  54819. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  54820. const bool isButtonDown,
  54821. int buttonX, int buttonY,
  54822. int buttonW, int buttonH,
  54823. ComboBox& box)
  54824. {
  54825. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  54826. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  54827. : ComboBox::backgroundColourId));
  54828. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  54829. g.setColour (box.findColour (ComboBox::outlineColourId));
  54830. g.drawRect (0, 0, width, height);
  54831. const float arrowX = 0.2f;
  54832. const float arrowH = 0.3f;
  54833. if (box.isEnabled())
  54834. {
  54835. Path p;
  54836. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  54837. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  54838. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  54839. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  54840. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  54841. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  54842. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  54843. : ComboBox::buttonColourId));
  54844. g.fillPath (p);
  54845. }
  54846. }
  54847. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  54848. {
  54849. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  54850. f.setHorizontalScale (0.9f);
  54851. return f;
  54852. }
  54853. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  54854. {
  54855. Path p;
  54856. p.addTriangle (x1, y1, x2, y2, x3, y3);
  54857. g.setColour (fill);
  54858. g.fillPath (p);
  54859. g.setColour (outline);
  54860. g.strokePath (p, PathStrokeType (0.3f));
  54861. }
  54862. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  54863. int x, int y,
  54864. int w, int h,
  54865. float sliderPos,
  54866. float minSliderPos,
  54867. float maxSliderPos,
  54868. const Slider::SliderStyle style,
  54869. Slider& slider)
  54870. {
  54871. g.fillAll (slider.findColour (Slider::backgroundColourId));
  54872. if (style == Slider::LinearBar)
  54873. {
  54874. g.setColour (slider.findColour (Slider::thumbColourId));
  54875. g.fillRect (x, y, (int) sliderPos - x, h);
  54876. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  54877. g.drawRect (x, y, (int) sliderPos - x, h);
  54878. }
  54879. else
  54880. {
  54881. g.setColour (slider.findColour (Slider::trackColourId)
  54882. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  54883. if (slider.isHorizontal())
  54884. {
  54885. g.fillRect (x, y + roundToInt (h * 0.6f),
  54886. w, roundToInt (h * 0.2f));
  54887. }
  54888. else
  54889. {
  54890. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  54891. jmin (4, roundToInt (w * 0.2f)), h);
  54892. }
  54893. float alpha = 0.35f;
  54894. if (slider.isEnabled())
  54895. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  54896. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  54897. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  54898. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  54899. {
  54900. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  54901. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  54902. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  54903. fill, outline);
  54904. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  54905. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  54906. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  54907. fill, outline);
  54908. }
  54909. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  54910. {
  54911. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54912. minSliderPos - 7.0f, y + h * 0.9f ,
  54913. minSliderPos, y + h * 0.9f,
  54914. fill, outline);
  54915. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54916. maxSliderPos, y + h * 0.9f,
  54917. maxSliderPos + 7.0f, y + h * 0.9f,
  54918. fill, outline);
  54919. }
  54920. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  54921. {
  54922. drawTriangle (g, sliderPos, y + h * 0.9f,
  54923. sliderPos - 7.0f, y + h * 0.2f,
  54924. sliderPos + 7.0f, y + h * 0.2f,
  54925. fill, outline);
  54926. }
  54927. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  54928. {
  54929. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  54930. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  54931. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  54932. fill, outline);
  54933. }
  54934. }
  54935. }
  54936. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  54937. {
  54938. if (isIncrement)
  54939. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  54940. else
  54941. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  54942. }
  54943. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  54944. {
  54945. return &scrollbarShadow;
  54946. }
  54947. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  54948. {
  54949. return 8;
  54950. }
  54951. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  54952. int w, int h,
  54953. bool isMouseOver,
  54954. bool isMouseDragging)
  54955. {
  54956. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  54957. : Colours::darkgrey);
  54958. const float lineThickness = jmin (w, h) * 0.1f;
  54959. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  54960. {
  54961. g.drawLine (w * i,
  54962. h + 1.0f,
  54963. w + 1.0f,
  54964. h * i,
  54965. lineThickness);
  54966. }
  54967. }
  54968. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  54969. {
  54970. Path shape;
  54971. if (buttonType == DocumentWindow::closeButton)
  54972. {
  54973. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  54974. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  54975. ShapeButton* const b = new ShapeButton ("close",
  54976. Colour (0x7fff3333),
  54977. Colour (0xd7ff3333),
  54978. Colour (0xf7ff3333));
  54979. b->setShape (shape, true, true, true);
  54980. return b;
  54981. }
  54982. else if (buttonType == DocumentWindow::minimiseButton)
  54983. {
  54984. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54985. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  54986. DrawablePath dp;
  54987. dp.setPath (shape);
  54988. dp.setFill (Colours::black.withAlpha (0.3f));
  54989. b->setImages (&dp);
  54990. return b;
  54991. }
  54992. else if (buttonType == DocumentWindow::maximiseButton)
  54993. {
  54994. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  54995. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54996. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  54997. DrawablePath dp;
  54998. dp.setPath (shape);
  54999. dp.setFill (Colours::black.withAlpha (0.3f));
  55000. b->setImages (&dp);
  55001. return b;
  55002. }
  55003. jassertfalse;
  55004. return 0;
  55005. }
  55006. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  55007. int titleBarX,
  55008. int titleBarY,
  55009. int titleBarW,
  55010. int titleBarH,
  55011. Button* minimiseButton,
  55012. Button* maximiseButton,
  55013. Button* closeButton,
  55014. bool positionTitleBarButtonsOnLeft)
  55015. {
  55016. titleBarY += titleBarH / 8;
  55017. titleBarH -= titleBarH / 4;
  55018. const int buttonW = titleBarH;
  55019. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55020. : titleBarX + titleBarW - buttonW - 4;
  55021. if (closeButton != 0)
  55022. {
  55023. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55024. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55025. : -(buttonW + buttonW / 5);
  55026. }
  55027. if (positionTitleBarButtonsOnLeft)
  55028. swapVariables (minimiseButton, maximiseButton);
  55029. if (maximiseButton != 0)
  55030. {
  55031. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55032. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55033. }
  55034. if (minimiseButton != 0)
  55035. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55036. }
  55037. END_JUCE_NAMESPACE
  55038. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55039. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55040. BEGIN_JUCE_NAMESPACE
  55041. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55042. : model (0),
  55043. itemUnderMouse (-1),
  55044. currentPopupIndex (-1),
  55045. topLevelIndexClicked (0),
  55046. lastMouseX (0),
  55047. lastMouseY (0)
  55048. {
  55049. setRepaintsOnMouseActivity (true);
  55050. setWantsKeyboardFocus (false);
  55051. setMouseClickGrabsKeyboardFocus (false);
  55052. setModel (model_);
  55053. }
  55054. MenuBarComponent::~MenuBarComponent()
  55055. {
  55056. setModel (0);
  55057. Desktop::getInstance().removeGlobalMouseListener (this);
  55058. }
  55059. MenuBarModel* MenuBarComponent::getModel() const throw()
  55060. {
  55061. return model;
  55062. }
  55063. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55064. {
  55065. if (model != newModel)
  55066. {
  55067. if (model != 0)
  55068. model->removeListener (this);
  55069. model = newModel;
  55070. if (model != 0)
  55071. model->addListener (this);
  55072. repaint();
  55073. menuBarItemsChanged (0);
  55074. }
  55075. }
  55076. void MenuBarComponent::paint (Graphics& g)
  55077. {
  55078. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55079. getLookAndFeel().drawMenuBarBackground (g,
  55080. getWidth(),
  55081. getHeight(),
  55082. isMouseOverBar,
  55083. *this);
  55084. if (model != 0)
  55085. {
  55086. for (int i = 0; i < menuNames.size(); ++i)
  55087. {
  55088. Graphics::ScopedSaveState ss (g);
  55089. g.setOrigin (xPositions [i], 0);
  55090. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55091. getLookAndFeel().drawMenuBarItem (g,
  55092. xPositions[i + 1] - xPositions[i],
  55093. getHeight(),
  55094. i,
  55095. menuNames[i],
  55096. i == itemUnderMouse,
  55097. i == currentPopupIndex,
  55098. isMouseOverBar,
  55099. *this);
  55100. }
  55101. }
  55102. }
  55103. void MenuBarComponent::resized()
  55104. {
  55105. xPositions.clear();
  55106. int x = 0;
  55107. xPositions.add (x);
  55108. for (int i = 0; i < menuNames.size(); ++i)
  55109. {
  55110. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55111. xPositions.add (x);
  55112. }
  55113. }
  55114. int MenuBarComponent::getItemAt (const int x, const int y)
  55115. {
  55116. for (int i = 0; i < xPositions.size(); ++i)
  55117. if (x >= xPositions[i] && x < xPositions[i + 1])
  55118. return reallyContains (Point<int> (x, y), true) ? i : -1;
  55119. return -1;
  55120. }
  55121. void MenuBarComponent::repaintMenuItem (int index)
  55122. {
  55123. if (isPositiveAndBelow (index, xPositions.size()))
  55124. {
  55125. const int x1 = xPositions [index];
  55126. const int x2 = xPositions [index + 1];
  55127. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55128. }
  55129. }
  55130. void MenuBarComponent::setItemUnderMouse (const int index)
  55131. {
  55132. if (itemUnderMouse != index)
  55133. {
  55134. repaintMenuItem (itemUnderMouse);
  55135. itemUnderMouse = index;
  55136. repaintMenuItem (itemUnderMouse);
  55137. }
  55138. }
  55139. void MenuBarComponent::setOpenItem (int index)
  55140. {
  55141. if (currentPopupIndex != index)
  55142. {
  55143. repaintMenuItem (currentPopupIndex);
  55144. currentPopupIndex = index;
  55145. repaintMenuItem (currentPopupIndex);
  55146. if (index >= 0)
  55147. Desktop::getInstance().addGlobalMouseListener (this);
  55148. else
  55149. Desktop::getInstance().removeGlobalMouseListener (this);
  55150. }
  55151. }
  55152. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55153. {
  55154. setItemUnderMouse (getItemAt (x, y));
  55155. }
  55156. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  55157. {
  55158. public:
  55159. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  55160. : bar (bar_), topLevelIndex (topLevelIndex_)
  55161. {
  55162. }
  55163. void modalStateFinished (int returnValue)
  55164. {
  55165. if (bar != 0)
  55166. bar->menuDismissed (topLevelIndex, returnValue);
  55167. }
  55168. private:
  55169. Component::SafePointer<MenuBarComponent> bar;
  55170. const int topLevelIndex;
  55171. JUCE_DECLARE_NON_COPYABLE (AsyncCallback);
  55172. };
  55173. void MenuBarComponent::showMenu (int index)
  55174. {
  55175. if (index != currentPopupIndex)
  55176. {
  55177. PopupMenu::dismissAllActiveMenus();
  55178. menuBarItemsChanged (0);
  55179. setOpenItem (index);
  55180. setItemUnderMouse (index);
  55181. if (index >= 0)
  55182. {
  55183. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55184. menuNames [itemUnderMouse]));
  55185. if (m.lookAndFeel == 0)
  55186. m.setLookAndFeel (&getLookAndFeel());
  55187. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55188. m.showMenu (localAreaToGlobal (itemPos),
  55189. 0, itemPos.getWidth(), 0, 0, this,
  55190. new AsyncCallback (this, index));
  55191. }
  55192. }
  55193. }
  55194. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55195. {
  55196. topLevelIndexClicked = topLevelIndex;
  55197. postCommandMessage (itemId);
  55198. }
  55199. void MenuBarComponent::handleCommandMessage (int commandId)
  55200. {
  55201. const Point<int> mousePos (getMouseXYRelative());
  55202. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55203. if (currentPopupIndex == topLevelIndexClicked)
  55204. setOpenItem (-1);
  55205. if (commandId != 0 && model != 0)
  55206. model->menuItemSelected (commandId, topLevelIndexClicked);
  55207. }
  55208. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55209. {
  55210. if (e.eventComponent == this)
  55211. updateItemUnderMouse (e.x, e.y);
  55212. }
  55213. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55214. {
  55215. if (e.eventComponent == this)
  55216. updateItemUnderMouse (e.x, e.y);
  55217. }
  55218. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55219. {
  55220. if (currentPopupIndex < 0)
  55221. {
  55222. const MouseEvent e2 (e.getEventRelativeTo (this));
  55223. updateItemUnderMouse (e2.x, e2.y);
  55224. currentPopupIndex = -2;
  55225. showMenu (itemUnderMouse);
  55226. }
  55227. }
  55228. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55229. {
  55230. const MouseEvent e2 (e.getEventRelativeTo (this));
  55231. const int item = getItemAt (e2.x, e2.y);
  55232. if (item >= 0)
  55233. showMenu (item);
  55234. }
  55235. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55236. {
  55237. const MouseEvent e2 (e.getEventRelativeTo (this));
  55238. updateItemUnderMouse (e2.x, e2.y);
  55239. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55240. {
  55241. setOpenItem (-1);
  55242. PopupMenu::dismissAllActiveMenus();
  55243. }
  55244. }
  55245. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55246. {
  55247. const MouseEvent e2 (e.getEventRelativeTo (this));
  55248. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55249. {
  55250. if (currentPopupIndex >= 0)
  55251. {
  55252. const int item = getItemAt (e2.x, e2.y);
  55253. if (item >= 0)
  55254. showMenu (item);
  55255. }
  55256. else
  55257. {
  55258. updateItemUnderMouse (e2.x, e2.y);
  55259. }
  55260. lastMouseX = e2.x;
  55261. lastMouseY = e2.y;
  55262. }
  55263. }
  55264. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55265. {
  55266. bool used = false;
  55267. const int numMenus = menuNames.size();
  55268. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55269. if (key.isKeyCode (KeyPress::leftKey))
  55270. {
  55271. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55272. used = true;
  55273. }
  55274. else if (key.isKeyCode (KeyPress::rightKey))
  55275. {
  55276. showMenu ((currentIndex + 1) % numMenus);
  55277. used = true;
  55278. }
  55279. return used;
  55280. }
  55281. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55282. {
  55283. StringArray newNames;
  55284. if (model != 0)
  55285. newNames = model->getMenuBarNames();
  55286. if (newNames != menuNames)
  55287. {
  55288. menuNames = newNames;
  55289. repaint();
  55290. resized();
  55291. }
  55292. }
  55293. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55294. const ApplicationCommandTarget::InvocationInfo& info)
  55295. {
  55296. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55297. return;
  55298. for (int i = 0; i < menuNames.size(); ++i)
  55299. {
  55300. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55301. if (menu.containsCommandItem (info.commandID))
  55302. {
  55303. setItemUnderMouse (i);
  55304. startTimer (200);
  55305. break;
  55306. }
  55307. }
  55308. }
  55309. void MenuBarComponent::timerCallback()
  55310. {
  55311. stopTimer();
  55312. const Point<int> mousePos (getMouseXYRelative());
  55313. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55314. }
  55315. END_JUCE_NAMESPACE
  55316. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55317. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55318. BEGIN_JUCE_NAMESPACE
  55319. MenuBarModel::MenuBarModel() throw()
  55320. : manager (0)
  55321. {
  55322. }
  55323. MenuBarModel::~MenuBarModel()
  55324. {
  55325. setApplicationCommandManagerToWatch (0);
  55326. }
  55327. void MenuBarModel::menuItemsChanged()
  55328. {
  55329. triggerAsyncUpdate();
  55330. }
  55331. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55332. {
  55333. if (manager != newManager)
  55334. {
  55335. if (manager != 0)
  55336. manager->removeListener (this);
  55337. manager = newManager;
  55338. if (manager != 0)
  55339. manager->addListener (this);
  55340. }
  55341. }
  55342. void MenuBarModel::addListener (Listener* const newListener) throw()
  55343. {
  55344. listeners.add (newListener);
  55345. }
  55346. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55347. {
  55348. // Trying to remove a listener that isn't on the list!
  55349. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55350. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55351. jassert (listeners.contains (listenerToRemove));
  55352. listeners.remove (listenerToRemove);
  55353. }
  55354. void MenuBarModel::handleAsyncUpdate()
  55355. {
  55356. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55357. }
  55358. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55359. {
  55360. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55361. }
  55362. void MenuBarModel::applicationCommandListChanged()
  55363. {
  55364. menuItemsChanged();
  55365. }
  55366. END_JUCE_NAMESPACE
  55367. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55368. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55369. BEGIN_JUCE_NAMESPACE
  55370. class PopupMenu::Item
  55371. {
  55372. public:
  55373. Item()
  55374. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55375. usesColour (false), customComp (0), commandManager (0)
  55376. {
  55377. }
  55378. Item (const int itemId_,
  55379. const String& text_,
  55380. const bool active_,
  55381. const bool isTicked_,
  55382. const Image& im,
  55383. const Colour& textColour_,
  55384. const bool usesColour_,
  55385. CustomComponent* const customComp_,
  55386. const PopupMenu* const subMenu_,
  55387. ApplicationCommandManager* const commandManager_)
  55388. : itemId (itemId_), text (text_), textColour (textColour_),
  55389. active (active_), isSeparator (false), isTicked (isTicked_),
  55390. usesColour (usesColour_), image (im), customComp (customComp_),
  55391. commandManager (commandManager_)
  55392. {
  55393. if (subMenu_ != 0)
  55394. subMenu = new PopupMenu (*subMenu_);
  55395. if (commandManager_ != 0 && itemId_ != 0)
  55396. {
  55397. String shortcutKey;
  55398. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55399. ->getKeyPressesAssignedToCommand (itemId_));
  55400. for (int i = 0; i < keyPresses.size(); ++i)
  55401. {
  55402. const String key (keyPresses.getReference(i).getTextDescription());
  55403. if (shortcutKey.isNotEmpty())
  55404. shortcutKey << ", ";
  55405. if (key.length() == 1)
  55406. shortcutKey << "shortcut: '" << key << '\'';
  55407. else
  55408. shortcutKey << key;
  55409. }
  55410. shortcutKey = shortcutKey.trim();
  55411. if (shortcutKey.isNotEmpty())
  55412. text << "<end>" << shortcutKey;
  55413. }
  55414. }
  55415. Item (const Item& other)
  55416. : itemId (other.itemId),
  55417. text (other.text),
  55418. textColour (other.textColour),
  55419. active (other.active),
  55420. isSeparator (other.isSeparator),
  55421. isTicked (other.isTicked),
  55422. usesColour (other.usesColour),
  55423. image (other.image),
  55424. customComp (other.customComp),
  55425. commandManager (other.commandManager)
  55426. {
  55427. if (other.subMenu != 0)
  55428. subMenu = new PopupMenu (*(other.subMenu));
  55429. }
  55430. bool canBeTriggered() const throw() { return active && ! (isSeparator || (subMenu != 0)); }
  55431. bool hasActiveSubMenu() const throw() { return active && (subMenu != 0); }
  55432. const int itemId;
  55433. String text;
  55434. const Colour textColour;
  55435. const bool active, isSeparator, isTicked, usesColour;
  55436. Image image;
  55437. ReferenceCountedObjectPtr <CustomComponent> customComp;
  55438. ScopedPointer <PopupMenu> subMenu;
  55439. ApplicationCommandManager* const commandManager;
  55440. private:
  55441. Item& operator= (const Item&);
  55442. JUCE_LEAK_DETECTOR (Item);
  55443. };
  55444. class PopupMenu::ItemComponent : public Component
  55445. {
  55446. public:
  55447. ItemComponent (const PopupMenu::Item& itemInfo_, int standardItemHeight, Component* const parent)
  55448. : itemInfo (itemInfo_),
  55449. isHighlighted (false)
  55450. {
  55451. if (itemInfo.customComp != 0)
  55452. addAndMakeVisible (itemInfo.customComp);
  55453. parent->addAndMakeVisible (this);
  55454. int itemW = 80;
  55455. int itemH = 16;
  55456. getIdealSize (itemW, itemH, standardItemHeight);
  55457. setSize (itemW, jlimit (2, 600, itemH));
  55458. addMouseListener (parent, false);
  55459. }
  55460. ~ItemComponent()
  55461. {
  55462. if (itemInfo.customComp != 0)
  55463. removeChildComponent (itemInfo.customComp);
  55464. }
  55465. void getIdealSize (int& idealWidth, int& idealHeight, const int standardItemHeight)
  55466. {
  55467. if (itemInfo.customComp != 0)
  55468. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55469. else
  55470. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55471. itemInfo.isSeparator,
  55472. standardItemHeight,
  55473. idealWidth, idealHeight);
  55474. }
  55475. void paint (Graphics& g)
  55476. {
  55477. if (itemInfo.customComp == 0)
  55478. {
  55479. String mainText (itemInfo.text);
  55480. String endText;
  55481. const int endIndex = mainText.indexOf ("<end>");
  55482. if (endIndex >= 0)
  55483. {
  55484. endText = mainText.substring (endIndex + 5).trim();
  55485. mainText = mainText.substring (0, endIndex);
  55486. }
  55487. getLookAndFeel()
  55488. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55489. itemInfo.isSeparator,
  55490. itemInfo.active,
  55491. isHighlighted,
  55492. itemInfo.isTicked,
  55493. itemInfo.subMenu != 0,
  55494. mainText, endText,
  55495. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55496. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55497. }
  55498. }
  55499. void resized()
  55500. {
  55501. if (getNumChildComponents() > 0)
  55502. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55503. }
  55504. void setHighlighted (bool shouldBeHighlighted)
  55505. {
  55506. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55507. if (isHighlighted != shouldBeHighlighted)
  55508. {
  55509. isHighlighted = shouldBeHighlighted;
  55510. if (itemInfo.customComp != 0)
  55511. itemInfo.customComp->setHighlighted (shouldBeHighlighted);
  55512. repaint();
  55513. }
  55514. }
  55515. PopupMenu::Item itemInfo;
  55516. private:
  55517. bool isHighlighted;
  55518. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  55519. };
  55520. namespace PopupMenuSettings
  55521. {
  55522. const int scrollZone = 24;
  55523. const int borderSize = 2;
  55524. const int timerInterval = 50;
  55525. const int dismissCommandId = 0x6287345f;
  55526. }
  55527. class PopupMenu::Window : public Component,
  55528. private Timer
  55529. {
  55530. public:
  55531. Window (const PopupMenu& menu, Window* const owner_, const Rectangle<int>& target,
  55532. const bool alignToRectangle, const int itemIdThatMustBeVisible,
  55533. const int minimumWidth_, const int maximumNumColumns_,
  55534. const int standardItemHeight_, const bool dismissOnMouseUp_,
  55535. ApplicationCommandManager** const managerOfChosenCommand_,
  55536. Component* const componentAttachedTo_)
  55537. : Component ("menu"),
  55538. owner (owner_),
  55539. activeSubMenu (0),
  55540. managerOfChosenCommand (managerOfChosenCommand_),
  55541. componentAttachedTo (componentAttachedTo_),
  55542. componentAttachedToOriginal (componentAttachedTo_),
  55543. minimumWidth (minimumWidth_),
  55544. maximumNumColumns (maximumNumColumns_),
  55545. standardItemHeight (standardItemHeight_),
  55546. isOver (false),
  55547. hasBeenOver (false),
  55548. isDown (false),
  55549. needsToScroll (false),
  55550. dismissOnMouseUp (dismissOnMouseUp_),
  55551. hideOnExit (false),
  55552. disableMouseMoves (false),
  55553. hasAnyJuceCompHadFocus (false),
  55554. numColumns (0),
  55555. contentHeight (0),
  55556. childYOffset (0),
  55557. menuCreationTime (Time::getMillisecondCounter()),
  55558. lastMouseMoveTime (0),
  55559. timeEnteredCurrentChildComp (0),
  55560. scrollAcceleration (1.0)
  55561. {
  55562. lastFocused = lastScroll = menuCreationTime;
  55563. setWantsKeyboardFocus (false);
  55564. setMouseClickGrabsKeyboardFocus (false);
  55565. setAlwaysOnTop (true);
  55566. setLookAndFeel (menu.lookAndFeel);
  55567. setOpaque (getLookAndFeel().findColour (PopupMenu::backgroundColourId).isOpaque() || ! Desktop::canUseSemiTransparentWindows());
  55568. for (int i = 0; i < menu.items.size(); ++i)
  55569. items.add (new PopupMenu::ItemComponent (*menu.items.getUnchecked(i), standardItemHeight, this));
  55570. calculateWindowPos (target, alignToRectangle);
  55571. setTopLeftPosition (windowPos.getX(), windowPos.getY());
  55572. updateYPositions();
  55573. if (itemIdThatMustBeVisible != 0)
  55574. {
  55575. const int y = target.getY() - windowPos.getY();
  55576. ensureItemIsVisible (itemIdThatMustBeVisible,
  55577. isPositiveAndBelow (y, windowPos.getHeight()) ? y : -1);
  55578. }
  55579. resizeToBestWindowPos();
  55580. addToDesktop (ComponentPeer::windowIsTemporary | getLookAndFeel().getMenuWindowFlags());
  55581. getActiveWindows().add (this);
  55582. Desktop::getInstance().addGlobalMouseListener (this);
  55583. }
  55584. ~Window()
  55585. {
  55586. getActiveWindows().removeValue (this);
  55587. Desktop::getInstance().removeGlobalMouseListener (this);
  55588. activeSubMenu = 0;
  55589. items.clear();
  55590. }
  55591. static Window* create (const PopupMenu& menu,
  55592. bool dismissOnMouseUp,
  55593. Window* const owner_,
  55594. const Rectangle<int>& target,
  55595. int minimumWidth,
  55596. int maximumNumColumns,
  55597. int standardItemHeight,
  55598. bool alignToRectangle,
  55599. int itemIdThatMustBeVisible,
  55600. ApplicationCommandManager** managerOfChosenCommand,
  55601. Component* componentAttachedTo)
  55602. {
  55603. if (menu.items.size() > 0)
  55604. return new Window (menu, owner_, target, alignToRectangle, itemIdThatMustBeVisible,
  55605. minimumWidth, maximumNumColumns, standardItemHeight, dismissOnMouseUp,
  55606. managerOfChosenCommand, componentAttachedTo);
  55607. return 0;
  55608. }
  55609. void paint (Graphics& g)
  55610. {
  55611. if (isOpaque())
  55612. g.fillAll (Colours::white);
  55613. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55614. }
  55615. void paintOverChildren (Graphics& g)
  55616. {
  55617. if (isScrolling())
  55618. {
  55619. LookAndFeel& lf = getLookAndFeel();
  55620. if (isScrollZoneActive (false))
  55621. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55622. if (isScrollZoneActive (true))
  55623. {
  55624. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55625. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55626. }
  55627. }
  55628. }
  55629. bool isScrollZoneActive (bool bottomOne) const
  55630. {
  55631. return isScrolling()
  55632. && (bottomOne ? childYOffset < contentHeight - windowPos.getHeight()
  55633. : childYOffset > 0);
  55634. }
  55635. // hide this and all sub-comps
  55636. void hide (const PopupMenu::Item* const item, const bool makeInvisible)
  55637. {
  55638. if (isVisible())
  55639. {
  55640. activeSubMenu = 0;
  55641. currentChild = 0;
  55642. exitModalState (item != 0 ? item->itemId : 0);
  55643. if (makeInvisible)
  55644. setVisible (false);
  55645. if (item != 0
  55646. && item->commandManager != 0
  55647. && item->itemId != 0)
  55648. {
  55649. *managerOfChosenCommand = item->commandManager;
  55650. }
  55651. }
  55652. }
  55653. void dismissMenu (const PopupMenu::Item* const item)
  55654. {
  55655. if (owner != 0)
  55656. {
  55657. owner->dismissMenu (item);
  55658. }
  55659. else
  55660. {
  55661. if (item != 0)
  55662. {
  55663. // need a copy of this on the stack as the one passed in will get deleted during this call
  55664. const PopupMenu::Item mi (*item);
  55665. hide (&mi, false);
  55666. }
  55667. else
  55668. {
  55669. hide (0, false);
  55670. }
  55671. }
  55672. }
  55673. void mouseMove (const MouseEvent&) { timerCallback(); }
  55674. void mouseDown (const MouseEvent&) { timerCallback(); }
  55675. void mouseDrag (const MouseEvent&) { timerCallback(); }
  55676. void mouseUp (const MouseEvent&) { timerCallback(); }
  55677. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55678. {
  55679. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55680. lastMouse = Point<int> (-1, -1);
  55681. }
  55682. bool keyPressed (const KeyPress& key)
  55683. {
  55684. if (key.isKeyCode (KeyPress::downKey))
  55685. {
  55686. selectNextItem (1);
  55687. }
  55688. else if (key.isKeyCode (KeyPress::upKey))
  55689. {
  55690. selectNextItem (-1);
  55691. }
  55692. else if (key.isKeyCode (KeyPress::leftKey))
  55693. {
  55694. if (owner != 0)
  55695. {
  55696. Component::SafePointer<Window> parentWindow (owner);
  55697. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55698. hide (0, true);
  55699. if (parentWindow != 0)
  55700. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55701. disableTimerUntilMouseMoves();
  55702. }
  55703. else if (componentAttachedTo != 0)
  55704. {
  55705. componentAttachedTo->keyPressed (key);
  55706. }
  55707. }
  55708. else if (key.isKeyCode (KeyPress::rightKey))
  55709. {
  55710. disableTimerUntilMouseMoves();
  55711. if (showSubMenuFor (currentChild))
  55712. {
  55713. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55714. activeSubMenu->selectNextItem (1);
  55715. }
  55716. else if (componentAttachedTo != 0)
  55717. {
  55718. componentAttachedTo->keyPressed (key);
  55719. }
  55720. }
  55721. else if (key.isKeyCode (KeyPress::returnKey))
  55722. {
  55723. triggerCurrentlyHighlightedItem();
  55724. }
  55725. else if (key.isKeyCode (KeyPress::escapeKey))
  55726. {
  55727. dismissMenu (0);
  55728. }
  55729. else
  55730. {
  55731. return false;
  55732. }
  55733. return true;
  55734. }
  55735. void inputAttemptWhenModal()
  55736. {
  55737. WeakReference<Component> deletionChecker (this);
  55738. timerCallback();
  55739. if (deletionChecker != 0 && ! isOverAnyMenu())
  55740. {
  55741. if (componentAttachedTo != 0)
  55742. {
  55743. // we want to dismiss the menu, but if we do it synchronously, then
  55744. // the mouse-click will be allowed to pass through. That's good, except
  55745. // when the user clicks on the button that orginally popped the menu up,
  55746. // as they'll expect the menu to go away, and in fact it'll just
  55747. // come back. So only dismiss synchronously if they're not on the original
  55748. // comp that we're attached to.
  55749. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  55750. if (componentAttachedTo->reallyContains (mousePos, true))
  55751. {
  55752. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  55753. return;
  55754. }
  55755. }
  55756. dismissMenu (0);
  55757. }
  55758. }
  55759. void handleCommandMessage (int commandId)
  55760. {
  55761. Component::handleCommandMessage (commandId);
  55762. if (commandId == PopupMenuSettings::dismissCommandId)
  55763. dismissMenu (0);
  55764. }
  55765. void timerCallback()
  55766. {
  55767. if (! isVisible())
  55768. return;
  55769. if (componentAttachedTo != componentAttachedToOriginal)
  55770. {
  55771. dismissMenu (0);
  55772. return;
  55773. }
  55774. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  55775. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  55776. return;
  55777. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  55778. // move rather than a real timer callback
  55779. const Point<int> globalMousePos (Desktop::getMousePosition());
  55780. const Point<int> localMousePos (getLocalPoint (0, globalMousePos));
  55781. const uint32 now = Time::getMillisecondCounter();
  55782. if (now > timeEnteredCurrentChildComp + 100
  55783. && reallyContains (localMousePos, true)
  55784. && currentChild != 0
  55785. && (! disableMouseMoves)
  55786. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  55787. {
  55788. showSubMenuFor (currentChild);
  55789. }
  55790. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  55791. {
  55792. highlightItemUnderMouse (globalMousePos, localMousePos);
  55793. }
  55794. bool overScrollArea = false;
  55795. if (isScrolling()
  55796. && (isOver || (isDown && isPositiveAndBelow (localMousePos.getX(), getWidth())))
  55797. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55798. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55799. {
  55800. if (now > lastScroll + 20)
  55801. {
  55802. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55803. int amount = 0;
  55804. for (int i = 0; i < items.size() && amount == 0; ++i)
  55805. amount = ((int) scrollAcceleration) * items.getUnchecked(i)->getHeight();
  55806. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55807. lastScroll = now;
  55808. }
  55809. overScrollArea = true;
  55810. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55811. }
  55812. else
  55813. {
  55814. scrollAcceleration = 1.0;
  55815. }
  55816. const bool wasDown = isDown;
  55817. bool isOverAny = isOverAnyMenu();
  55818. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55819. {
  55820. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55821. isOverAny = isOverAnyMenu();
  55822. }
  55823. if (hideOnExit && hasBeenOver && ! isOverAny)
  55824. {
  55825. hide (0, true);
  55826. }
  55827. else
  55828. {
  55829. isDown = hasBeenOver
  55830. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55831. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55832. bool anyFocused = Process::isForegroundProcess();
  55833. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55834. {
  55835. // because no component at all may have focus, our test here will
  55836. // only be triggered when something has focus and then loses it.
  55837. anyFocused = ! hasAnyJuceCompHadFocus;
  55838. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55839. {
  55840. if (ComponentPeer::getPeer (i)->isFocused())
  55841. {
  55842. anyFocused = true;
  55843. hasAnyJuceCompHadFocus = true;
  55844. break;
  55845. }
  55846. }
  55847. }
  55848. if (! anyFocused)
  55849. {
  55850. if (now > lastFocused + 10)
  55851. {
  55852. wasHiddenBecauseOfAppChange() = true;
  55853. dismissMenu (0);
  55854. return; // may have been deleted by the previous call..
  55855. }
  55856. }
  55857. else if (wasDown && now > menuCreationTime + 250
  55858. && ! (isDown || overScrollArea))
  55859. {
  55860. isOver = reallyContains (localMousePos, true);
  55861. if (isOver)
  55862. {
  55863. triggerCurrentlyHighlightedItem();
  55864. }
  55865. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55866. {
  55867. dismissMenu (0);
  55868. }
  55869. return; // may have been deleted by the previous calls..
  55870. }
  55871. else
  55872. {
  55873. lastFocused = now;
  55874. }
  55875. }
  55876. }
  55877. static Array<Window*>& getActiveWindows()
  55878. {
  55879. static Array<Window*> activeMenuWindows;
  55880. return activeMenuWindows;
  55881. }
  55882. static bool& wasHiddenBecauseOfAppChange() throw()
  55883. {
  55884. static bool b = false;
  55885. return b;
  55886. }
  55887. private:
  55888. Window* owner;
  55889. OwnedArray <PopupMenu::ItemComponent> items;
  55890. Component::SafePointer<PopupMenu::ItemComponent> currentChild;
  55891. ScopedPointer <Window> activeSubMenu;
  55892. ApplicationCommandManager** managerOfChosenCommand;
  55893. WeakReference<Component> componentAttachedTo;
  55894. Component* componentAttachedToOriginal;
  55895. Rectangle<int> windowPos;
  55896. Point<int> lastMouse;
  55897. int minimumWidth, maximumNumColumns, standardItemHeight;
  55898. bool isOver, hasBeenOver, isDown, needsToScroll;
  55899. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  55900. int numColumns, contentHeight, childYOffset;
  55901. Array <int> columnWidths;
  55902. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  55903. double scrollAcceleration;
  55904. bool overlaps (const Rectangle<int>& r) const
  55905. {
  55906. return r.intersects (getBounds())
  55907. || (owner != 0 && owner->overlaps (r));
  55908. }
  55909. bool isOverAnyMenu() const
  55910. {
  55911. return (owner != 0) ? owner->isOverAnyMenu()
  55912. : isOverChildren();
  55913. }
  55914. bool isOverChildren() const
  55915. {
  55916. return isVisible()
  55917. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  55918. }
  55919. void updateMouseOverStatus (const Point<int>& globalMousePos)
  55920. {
  55921. const Point<int> relPos (getLocalPoint (0, globalMousePos));
  55922. isOver = reallyContains (relPos, true);
  55923. if (activeSubMenu != 0)
  55924. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55925. }
  55926. bool treeContains (const Window* const window) const throw()
  55927. {
  55928. const Window* mw = this;
  55929. while (mw->owner != 0)
  55930. mw = mw->owner;
  55931. while (mw != 0)
  55932. {
  55933. if (mw == window)
  55934. return true;
  55935. mw = mw->activeSubMenu;
  55936. }
  55937. return false;
  55938. }
  55939. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  55940. {
  55941. const Rectangle<int> mon (Desktop::getInstance()
  55942. .getMonitorAreaContaining (target.getCentre(),
  55943. #if JUCE_MAC
  55944. true));
  55945. #else
  55946. false)); // on windows, don't stop the menu overlapping the taskbar
  55947. #endif
  55948. int x, y, widthToUse, heightToUse;
  55949. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  55950. if (alignToRectangle)
  55951. {
  55952. x = target.getX();
  55953. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  55954. const int spaceOver = target.getY() - mon.getY();
  55955. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  55956. y = target.getBottom();
  55957. else
  55958. y = target.getY() - heightToUse;
  55959. }
  55960. else
  55961. {
  55962. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  55963. if (owner != 0)
  55964. {
  55965. if (owner->owner != 0)
  55966. {
  55967. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  55968. > owner->owner->getX() + owner->owner->getWidth() / 2);
  55969. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  55970. tendTowardsRight = true;
  55971. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  55972. tendTowardsRight = false;
  55973. }
  55974. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  55975. {
  55976. tendTowardsRight = true;
  55977. }
  55978. }
  55979. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  55980. target.getX() - mon.getX()) - 32;
  55981. if (biggestSpace < widthToUse)
  55982. {
  55983. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  55984. if (numColumns > 1)
  55985. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  55986. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  55987. }
  55988. if (tendTowardsRight)
  55989. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  55990. else
  55991. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  55992. y = target.getY();
  55993. if (target.getCentreY() > mon.getCentreY())
  55994. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  55995. }
  55996. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  55997. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  55998. windowPos.setBounds (x, y, widthToUse, heightToUse);
  55999. // sets this flag if it's big enough to obscure any of its parent menus
  56000. hideOnExit = (owner != 0)
  56001. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  56002. }
  56003. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  56004. {
  56005. numColumns = 0;
  56006. contentHeight = 0;
  56007. const int maxMenuH = getParentHeight() - 24;
  56008. int totalW;
  56009. do
  56010. {
  56011. ++numColumns;
  56012. totalW = workOutBestSize (maxMenuW);
  56013. if (totalW > maxMenuW)
  56014. {
  56015. numColumns = jmax (1, numColumns - 1);
  56016. totalW = workOutBestSize (maxMenuW); // to update col widths
  56017. break;
  56018. }
  56019. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56020. {
  56021. break;
  56022. }
  56023. } while (numColumns < maximumNumColumns);
  56024. const int actualH = jmin (contentHeight, maxMenuH);
  56025. needsToScroll = contentHeight > actualH;
  56026. width = updateYPositions();
  56027. height = actualH + PopupMenuSettings::borderSize * 2;
  56028. }
  56029. int workOutBestSize (const int maxMenuW)
  56030. {
  56031. int totalW = 0;
  56032. contentHeight = 0;
  56033. int childNum = 0;
  56034. for (int col = 0; col < numColumns; ++col)
  56035. {
  56036. int i, colW = 50, colH = 0;
  56037. const int numChildren = jmin (items.size() - childNum,
  56038. (items.size() + numColumns - 1) / numColumns);
  56039. for (i = numChildren; --i >= 0;)
  56040. {
  56041. colW = jmax (colW, items.getUnchecked (childNum + i)->getWidth());
  56042. colH += items.getUnchecked (childNum + i)->getHeight();
  56043. }
  56044. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56045. columnWidths.set (col, colW);
  56046. totalW += colW;
  56047. contentHeight = jmax (contentHeight, colH);
  56048. childNum += numChildren;
  56049. }
  56050. if (totalW < minimumWidth)
  56051. {
  56052. totalW = minimumWidth;
  56053. for (int col = 0; col < numColumns; ++col)
  56054. columnWidths.set (0, totalW / numColumns);
  56055. }
  56056. return totalW;
  56057. }
  56058. void ensureItemIsVisible (const int itemId, int wantedY)
  56059. {
  56060. jassert (itemId != 0)
  56061. for (int i = items.size(); --i >= 0;)
  56062. {
  56063. PopupMenu::ItemComponent* const m = items.getUnchecked(i);
  56064. if (m != 0
  56065. && m->itemInfo.itemId == itemId
  56066. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56067. {
  56068. const int currentY = m->getY();
  56069. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56070. {
  56071. if (wantedY < 0)
  56072. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56073. jmax (PopupMenuSettings::scrollZone,
  56074. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56075. currentY);
  56076. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56077. int deltaY = wantedY - currentY;
  56078. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56079. jmin (windowPos.getHeight(), mon.getHeight()));
  56080. const int newY = jlimit (mon.getY(),
  56081. mon.getBottom() - windowPos.getHeight(),
  56082. windowPos.getY() + deltaY);
  56083. deltaY -= newY - windowPos.getY();
  56084. childYOffset -= deltaY;
  56085. windowPos.setPosition (windowPos.getX(), newY);
  56086. updateYPositions();
  56087. }
  56088. break;
  56089. }
  56090. }
  56091. }
  56092. void resizeToBestWindowPos()
  56093. {
  56094. Rectangle<int> r (windowPos);
  56095. if (childYOffset < 0)
  56096. {
  56097. r.setBounds (r.getX(), r.getY() - childYOffset,
  56098. r.getWidth(), r.getHeight() + childYOffset);
  56099. }
  56100. else if (childYOffset > 0)
  56101. {
  56102. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56103. if (spaceAtBottom > 0)
  56104. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56105. }
  56106. setBounds (r);
  56107. updateYPositions();
  56108. }
  56109. void alterChildYPos (const int delta)
  56110. {
  56111. if (isScrolling())
  56112. {
  56113. childYOffset += delta;
  56114. if (delta < 0)
  56115. {
  56116. childYOffset = jmax (childYOffset, 0);
  56117. }
  56118. else if (delta > 0)
  56119. {
  56120. childYOffset = jmin (childYOffset,
  56121. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56122. }
  56123. updateYPositions();
  56124. }
  56125. else
  56126. {
  56127. childYOffset = 0;
  56128. }
  56129. resizeToBestWindowPos();
  56130. repaint();
  56131. }
  56132. int updateYPositions()
  56133. {
  56134. int x = 0;
  56135. int childNum = 0;
  56136. for (int col = 0; col < numColumns; ++col)
  56137. {
  56138. const int numChildren = jmin (items.size() - childNum,
  56139. (items.size() + numColumns - 1) / numColumns);
  56140. const int colW = columnWidths [col];
  56141. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56142. for (int i = 0; i < numChildren; ++i)
  56143. {
  56144. Component* const c = items.getUnchecked (childNum + i);
  56145. c->setBounds (x, y, colW, c->getHeight());
  56146. y += c->getHeight();
  56147. }
  56148. x += colW;
  56149. childNum += numChildren;
  56150. }
  56151. return x;
  56152. }
  56153. bool isScrolling() const throw()
  56154. {
  56155. return childYOffset != 0 || needsToScroll;
  56156. }
  56157. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56158. {
  56159. if (currentChild != 0)
  56160. currentChild->setHighlighted (false);
  56161. currentChild = child;
  56162. if (currentChild != 0)
  56163. {
  56164. currentChild->setHighlighted (true);
  56165. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56166. }
  56167. }
  56168. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56169. {
  56170. activeSubMenu = 0;
  56171. if (childComp != 0 && childComp->itemInfo.hasActiveSubMenu())
  56172. {
  56173. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56174. dismissOnMouseUp,
  56175. this,
  56176. childComp->getScreenBounds(),
  56177. 0, maximumNumColumns,
  56178. standardItemHeight,
  56179. false, 0, managerOfChosenCommand,
  56180. componentAttachedTo);
  56181. if (activeSubMenu != 0)
  56182. {
  56183. activeSubMenu->setVisible (true);
  56184. activeSubMenu->enterModalState (false);
  56185. activeSubMenu->toFront (false);
  56186. return true;
  56187. }
  56188. }
  56189. return false;
  56190. }
  56191. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56192. {
  56193. isOver = reallyContains (localMousePos, true);
  56194. if (isOver)
  56195. hasBeenOver = true;
  56196. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56197. {
  56198. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56199. if (disableMouseMoves && isOver)
  56200. disableMouseMoves = false;
  56201. }
  56202. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56203. return;
  56204. bool isMovingTowardsMenu = false;
  56205. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56206. {
  56207. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56208. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56209. // extends from the last mouse pos to the submenu's rectangle..
  56210. float subX = (float) activeSubMenu->getScreenX();
  56211. if (activeSubMenu->getX() > getX())
  56212. {
  56213. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56214. }
  56215. else
  56216. {
  56217. lastMouse += Point<int> (2, 0);
  56218. subX += activeSubMenu->getWidth();
  56219. }
  56220. Path areaTowardsSubMenu;
  56221. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(), (float) lastMouse.getY(),
  56222. subX, (float) activeSubMenu->getScreenY(),
  56223. subX, (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56224. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56225. }
  56226. lastMouse = globalMousePos;
  56227. if (! isMovingTowardsMenu)
  56228. {
  56229. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56230. if (c == this)
  56231. c = 0;
  56232. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56233. if (mic == 0 && c != 0)
  56234. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56235. if (mic != currentChild
  56236. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56237. {
  56238. if (isOver && (c != 0) && (activeSubMenu != 0))
  56239. activeSubMenu->hide (0, true);
  56240. if (! isOver)
  56241. mic = 0;
  56242. setCurrentlyHighlightedChild (mic);
  56243. }
  56244. }
  56245. }
  56246. void triggerCurrentlyHighlightedItem()
  56247. {
  56248. if (currentChild != 0
  56249. && currentChild->itemInfo.canBeTriggered()
  56250. && (currentChild->itemInfo.customComp == 0
  56251. || currentChild->itemInfo.customComp->isTriggeredAutomatically()))
  56252. {
  56253. dismissMenu (&currentChild->itemInfo);
  56254. }
  56255. }
  56256. void selectNextItem (const int delta)
  56257. {
  56258. disableTimerUntilMouseMoves();
  56259. PopupMenu::ItemComponent* mic = 0;
  56260. bool wasLastOne = (currentChild == 0);
  56261. const int numItems = items.size();
  56262. for (int i = 0; i < numItems + 1; ++i)
  56263. {
  56264. int index = (delta > 0) ? i : (numItems - 1 - i);
  56265. index = (index + numItems) % numItems;
  56266. mic = items.getUnchecked (index);
  56267. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56268. && wasLastOne)
  56269. break;
  56270. if (mic == currentChild)
  56271. wasLastOne = true;
  56272. }
  56273. setCurrentlyHighlightedChild (mic);
  56274. }
  56275. void disableTimerUntilMouseMoves()
  56276. {
  56277. disableMouseMoves = true;
  56278. if (owner != 0)
  56279. owner->disableTimerUntilMouseMoves();
  56280. }
  56281. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Window);
  56282. };
  56283. PopupMenu::PopupMenu()
  56284. : lookAndFeel (0),
  56285. separatorPending (false)
  56286. {
  56287. }
  56288. PopupMenu::PopupMenu (const PopupMenu& other)
  56289. : lookAndFeel (other.lookAndFeel),
  56290. separatorPending (false)
  56291. {
  56292. items.addCopiesOf (other.items);
  56293. }
  56294. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56295. {
  56296. if (this != &other)
  56297. {
  56298. lookAndFeel = other.lookAndFeel;
  56299. clear();
  56300. items.addCopiesOf (other.items);
  56301. }
  56302. return *this;
  56303. }
  56304. PopupMenu::~PopupMenu()
  56305. {
  56306. clear();
  56307. }
  56308. void PopupMenu::clear()
  56309. {
  56310. items.clear();
  56311. separatorPending = false;
  56312. }
  56313. void PopupMenu::addSeparatorIfPending()
  56314. {
  56315. if (separatorPending)
  56316. {
  56317. separatorPending = false;
  56318. if (items.size() > 0)
  56319. items.add (new Item());
  56320. }
  56321. }
  56322. void PopupMenu::addItem (const int itemResultId, const String& itemText,
  56323. const bool isActive, const bool isTicked, const Image& iconToUse)
  56324. {
  56325. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56326. // didn't pick anything, so you shouldn't use it as the id
  56327. // for an item..
  56328. addSeparatorIfPending();
  56329. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56330. Colours::black, false, 0, 0, 0));
  56331. }
  56332. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56333. const int commandID,
  56334. const String& displayName)
  56335. {
  56336. jassert (commandManager != 0 && commandID != 0);
  56337. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56338. if (registeredInfo != 0)
  56339. {
  56340. ApplicationCommandInfo info (*registeredInfo);
  56341. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56342. addSeparatorIfPending();
  56343. items.add (new Item (commandID,
  56344. displayName.isNotEmpty() ? displayName
  56345. : info.shortName,
  56346. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56347. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56348. Image::null,
  56349. Colours::black,
  56350. false,
  56351. 0, 0,
  56352. commandManager));
  56353. }
  56354. }
  56355. void PopupMenu::addColouredItem (const int itemResultId,
  56356. const String& itemText,
  56357. const Colour& itemTextColour,
  56358. const bool isActive,
  56359. const bool isTicked,
  56360. const Image& iconToUse)
  56361. {
  56362. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56363. // didn't pick anything, so you shouldn't use it as the id
  56364. // for an item..
  56365. addSeparatorIfPending();
  56366. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56367. itemTextColour, true, 0, 0, 0));
  56368. }
  56369. void PopupMenu::addCustomItem (const int itemResultId, CustomComponent* const customComponent)
  56370. {
  56371. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56372. // didn't pick anything, so you shouldn't use it as the id
  56373. // for an item..
  56374. addSeparatorIfPending();
  56375. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56376. Colours::black, false, customComponent, 0, 0));
  56377. }
  56378. class NormalComponentWrapper : public PopupMenu::CustomComponent
  56379. {
  56380. public:
  56381. NormalComponentWrapper (Component* const comp, const int w, const int h,
  56382. const bool triggerMenuItemAutomaticallyWhenClicked)
  56383. : PopupMenu::CustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56384. width (w), height (h)
  56385. {
  56386. addAndMakeVisible (comp);
  56387. }
  56388. void getIdealSize (int& idealWidth, int& idealHeight)
  56389. {
  56390. idealWidth = width;
  56391. idealHeight = height;
  56392. }
  56393. void resized()
  56394. {
  56395. if (getChildComponent(0) != 0)
  56396. getChildComponent(0)->setBounds (getLocalBounds());
  56397. }
  56398. private:
  56399. const int width, height;
  56400. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NormalComponentWrapper);
  56401. };
  56402. void PopupMenu::addCustomItem (const int itemResultId,
  56403. Component* customComponent,
  56404. int idealWidth, int idealHeight,
  56405. const bool triggerMenuItemAutomaticallyWhenClicked)
  56406. {
  56407. addCustomItem (itemResultId,
  56408. new NormalComponentWrapper (customComponent, idealWidth, idealHeight,
  56409. triggerMenuItemAutomaticallyWhenClicked));
  56410. }
  56411. void PopupMenu::addSubMenu (const String& subMenuName,
  56412. const PopupMenu& subMenu,
  56413. const bool isActive,
  56414. const Image& iconToUse,
  56415. const bool isTicked)
  56416. {
  56417. addSeparatorIfPending();
  56418. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56419. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56420. }
  56421. void PopupMenu::addSeparator()
  56422. {
  56423. separatorPending = true;
  56424. }
  56425. class HeaderItemComponent : public PopupMenu::CustomComponent
  56426. {
  56427. public:
  56428. HeaderItemComponent (const String& name)
  56429. : PopupMenu::CustomComponent (false)
  56430. {
  56431. setName (name);
  56432. }
  56433. void paint (Graphics& g)
  56434. {
  56435. Font f (getLookAndFeel().getPopupMenuFont());
  56436. f.setBold (true);
  56437. g.setFont (f);
  56438. g.setColour (findColour (PopupMenu::headerTextColourId));
  56439. g.drawFittedText (getName(),
  56440. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56441. Justification::bottomLeft, 1);
  56442. }
  56443. void getIdealSize (int& idealWidth, int& idealHeight)
  56444. {
  56445. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56446. idealHeight += idealHeight / 2;
  56447. idealWidth += idealWidth / 4;
  56448. }
  56449. private:
  56450. JUCE_LEAK_DETECTOR (HeaderItemComponent);
  56451. };
  56452. void PopupMenu::addSectionHeader (const String& title)
  56453. {
  56454. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56455. }
  56456. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56457. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56458. {
  56459. public:
  56460. PopupMenuCompletionCallback()
  56461. : managerOfChosenCommand (0)
  56462. {
  56463. }
  56464. void modalStateFinished (int result)
  56465. {
  56466. if (managerOfChosenCommand != 0 && result != 0)
  56467. {
  56468. ApplicationCommandTarget::InvocationInfo info (result);
  56469. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56470. managerOfChosenCommand->invoke (info, true);
  56471. }
  56472. // (this would be the place to fade out the component, if that's what's required)
  56473. component = 0;
  56474. }
  56475. ApplicationCommandManager* managerOfChosenCommand;
  56476. ScopedPointer<Component> component;
  56477. private:
  56478. JUCE_DECLARE_NON_COPYABLE (PopupMenuCompletionCallback);
  56479. };
  56480. int PopupMenu::showMenu (const Rectangle<int>& target,
  56481. const int itemIdThatMustBeVisible,
  56482. const int minimumWidth,
  56483. const int maximumNumColumns,
  56484. const int standardItemHeight,
  56485. Component* const componentAttachedTo,
  56486. ModalComponentManager::Callback* userCallback)
  56487. {
  56488. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56489. WeakReference<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  56490. WeakReference<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  56491. Window::wasHiddenBecauseOfAppChange() = false;
  56492. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  56493. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  56494. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56495. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  56496. standardItemHeight, ! target.isEmpty(), itemIdThatMustBeVisible,
  56497. &callback->managerOfChosenCommand, componentAttachedTo);
  56498. if (callback->component == 0)
  56499. return 0;
  56500. callback->component->enterModalState (false, userCallbackDeleter.release());
  56501. callback->component->toFront (false); // need to do this after making it modal, or it could
  56502. // be stuck behind other comps that are already modal..
  56503. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  56504. callbackDeleter.release();
  56505. if (userCallback != 0)
  56506. return 0;
  56507. const int result = callback->component->runModalLoop();
  56508. if (! Window::wasHiddenBecauseOfAppChange())
  56509. {
  56510. if (prevTopLevel != 0)
  56511. prevTopLevel->toFront (true);
  56512. if (prevFocused != 0)
  56513. prevFocused->grabKeyboardFocus();
  56514. }
  56515. return result;
  56516. }
  56517. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56518. const int minimumWidth, const int maximumNumColumns,
  56519. const int standardItemHeight,
  56520. ModalComponentManager::Callback* callback)
  56521. {
  56522. return showMenu (Rectangle<int>().withPosition (Desktop::getMousePosition()),
  56523. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56524. standardItemHeight, 0, callback);
  56525. }
  56526. int PopupMenu::showAt (const Rectangle<int>& screenAreaToAttachTo,
  56527. const int itemIdThatMustBeVisible,
  56528. const int minimumWidth, const int maximumNumColumns,
  56529. const int standardItemHeight,
  56530. ModalComponentManager::Callback* callback)
  56531. {
  56532. return showMenu (screenAreaToAttachTo,
  56533. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56534. standardItemHeight, 0, callback);
  56535. }
  56536. int PopupMenu::showAt (Component* componentToAttachTo,
  56537. const int itemIdThatMustBeVisible,
  56538. const int minimumWidth, const int maximumNumColumns,
  56539. const int standardItemHeight,
  56540. ModalComponentManager::Callback* callback)
  56541. {
  56542. if (componentToAttachTo != 0)
  56543. {
  56544. return showMenu (componentToAttachTo->getScreenBounds(),
  56545. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56546. standardItemHeight, componentToAttachTo, callback);
  56547. }
  56548. else
  56549. {
  56550. return show (itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56551. standardItemHeight, callback);
  56552. }
  56553. }
  56554. bool JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56555. {
  56556. const int numWindows = Window::getActiveWindows().size();
  56557. for (int i = numWindows; --i >= 0;)
  56558. {
  56559. Window* const pmw = Window::getActiveWindows()[i];
  56560. if (pmw != 0)
  56561. pmw->dismissMenu (0);
  56562. }
  56563. return numWindows > 0;
  56564. }
  56565. int PopupMenu::getNumItems() const throw()
  56566. {
  56567. int num = 0;
  56568. for (int i = items.size(); --i >= 0;)
  56569. if (! (items.getUnchecked(i))->isSeparator)
  56570. ++num;
  56571. return num;
  56572. }
  56573. bool PopupMenu::containsCommandItem (const int commandID) const
  56574. {
  56575. for (int i = items.size(); --i >= 0;)
  56576. {
  56577. const Item* mi = items.getUnchecked (i);
  56578. if ((mi->itemId == commandID && mi->commandManager != 0)
  56579. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56580. {
  56581. return true;
  56582. }
  56583. }
  56584. return false;
  56585. }
  56586. bool PopupMenu::containsAnyActiveItems() const throw()
  56587. {
  56588. for (int i = items.size(); --i >= 0;)
  56589. {
  56590. const Item* const mi = items.getUnchecked (i);
  56591. if (mi->subMenu != 0)
  56592. {
  56593. if (mi->subMenu->containsAnyActiveItems())
  56594. return true;
  56595. }
  56596. else if (mi->active)
  56597. {
  56598. return true;
  56599. }
  56600. }
  56601. return false;
  56602. }
  56603. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56604. {
  56605. lookAndFeel = newLookAndFeel;
  56606. }
  56607. PopupMenu::CustomComponent::CustomComponent (const bool isTriggeredAutomatically_)
  56608. : isHighlighted (false),
  56609. triggeredAutomatically (isTriggeredAutomatically_)
  56610. {
  56611. }
  56612. PopupMenu::CustomComponent::~CustomComponent()
  56613. {
  56614. }
  56615. void PopupMenu::CustomComponent::setHighlighted (bool shouldBeHighlighted)
  56616. {
  56617. isHighlighted = shouldBeHighlighted;
  56618. repaint();
  56619. }
  56620. void PopupMenu::CustomComponent::triggerMenuItem()
  56621. {
  56622. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56623. if (mic != 0)
  56624. {
  56625. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56626. if (pmw != 0)
  56627. {
  56628. pmw->dismissMenu (&mic->itemInfo);
  56629. }
  56630. else
  56631. {
  56632. // something must have gone wrong with the component hierarchy if this happens..
  56633. jassertfalse;
  56634. }
  56635. }
  56636. else
  56637. {
  56638. // why isn't this component inside a menu? Not much point triggering the item if
  56639. // there's no menu.
  56640. jassertfalse;
  56641. }
  56642. }
  56643. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56644. : subMenu (0),
  56645. itemId (0),
  56646. isSeparator (false),
  56647. isTicked (false),
  56648. isEnabled (false),
  56649. isCustomComponent (false),
  56650. isSectionHeader (false),
  56651. customColour (0),
  56652. customImage (0),
  56653. menu (menu_),
  56654. index (0)
  56655. {
  56656. }
  56657. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56658. {
  56659. }
  56660. bool PopupMenu::MenuItemIterator::next()
  56661. {
  56662. if (index >= menu.items.size())
  56663. return false;
  56664. const Item* const item = menu.items.getUnchecked (index);
  56665. ++index;
  56666. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56667. subMenu = item->subMenu;
  56668. itemId = item->itemId;
  56669. isSeparator = item->isSeparator;
  56670. isTicked = item->isTicked;
  56671. isEnabled = item->active;
  56672. isSectionHeader = dynamic_cast <HeaderItemComponent*> (static_cast <CustomComponent*> (item->customComp)) != 0;
  56673. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56674. customColour = item->usesColour ? &(item->textColour) : 0;
  56675. customImage = item->image;
  56676. commandManager = item->commandManager;
  56677. return true;
  56678. }
  56679. END_JUCE_NAMESPACE
  56680. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56681. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56682. BEGIN_JUCE_NAMESPACE
  56683. ComponentDragger::ComponentDragger()
  56684. {
  56685. }
  56686. ComponentDragger::~ComponentDragger()
  56687. {
  56688. }
  56689. void ComponentDragger::startDraggingComponent (Component* const componentToDrag, const MouseEvent& e)
  56690. {
  56691. jassert (componentToDrag != 0);
  56692. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  56693. if (componentToDrag != 0)
  56694. mouseDownWithinTarget = e.getEventRelativeTo (componentToDrag).getMouseDownPosition();
  56695. }
  56696. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e,
  56697. ComponentBoundsConstrainer* const constrainer)
  56698. {
  56699. jassert (componentToDrag != 0);
  56700. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  56701. if (componentToDrag != 0)
  56702. {
  56703. Rectangle<int> bounds (componentToDrag->getBounds());
  56704. // If the component is a window, multiple mouse events can get queued while it's in the same position,
  56705. // so their coordinates become wrong after the first one moves the window, so in that case, we'll use
  56706. // the current mouse position instead of the one that the event contains...
  56707. if (componentToDrag->isOnDesktop())
  56708. bounds += componentToDrag->getMouseXYRelative() - mouseDownWithinTarget;
  56709. else
  56710. bounds += e.getEventRelativeTo (componentToDrag).getPosition() - mouseDownWithinTarget;
  56711. if (constrainer != 0)
  56712. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  56713. else
  56714. componentToDrag->setBounds (bounds);
  56715. }
  56716. }
  56717. END_JUCE_NAMESPACE
  56718. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56719. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56720. BEGIN_JUCE_NAMESPACE
  56721. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56722. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56723. class DragImageComponent : public Component,
  56724. public Timer
  56725. {
  56726. public:
  56727. DragImageComponent (const Image& im,
  56728. const String& desc,
  56729. Component* const sourceComponent,
  56730. Component* const mouseDragSource_,
  56731. DragAndDropContainer* const o,
  56732. const Point<int>& imageOffset_)
  56733. : image (im),
  56734. source (sourceComponent),
  56735. mouseDragSource (mouseDragSource_),
  56736. owner (o),
  56737. dragDesc (desc),
  56738. imageOffset (imageOffset_),
  56739. hasCheckedForExternalDrag (false),
  56740. drawImage (true)
  56741. {
  56742. setSize (im.getWidth(), im.getHeight());
  56743. if (mouseDragSource == 0)
  56744. mouseDragSource = source;
  56745. mouseDragSource->addMouseListener (this, false);
  56746. startTimer (200);
  56747. setInterceptsMouseClicks (false, false);
  56748. setAlwaysOnTop (true);
  56749. }
  56750. ~DragImageComponent()
  56751. {
  56752. if (owner->dragImageComponent == this)
  56753. owner->dragImageComponent.release();
  56754. if (mouseDragSource != 0)
  56755. {
  56756. mouseDragSource->removeMouseListener (this);
  56757. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56758. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56759. }
  56760. }
  56761. void paint (Graphics& g)
  56762. {
  56763. if (isOpaque())
  56764. g.fillAll (Colours::white);
  56765. if (drawImage)
  56766. {
  56767. g.setOpacity (1.0f);
  56768. g.drawImageAt (image, 0, 0);
  56769. }
  56770. }
  56771. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56772. {
  56773. Component* hit = getParentComponent();
  56774. if (hit == 0)
  56775. {
  56776. hit = Desktop::getInstance().findComponentAt (screenPos);
  56777. }
  56778. else
  56779. {
  56780. const Point<int> relPos (hit->getLocalPoint (0, screenPos));
  56781. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56782. }
  56783. // (note: use a local copy of the dragDesc member in case the callback runs
  56784. // a modal loop and deletes this object before the method completes)
  56785. const String dragDescLocal (dragDesc);
  56786. while (hit != 0)
  56787. {
  56788. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56789. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56790. {
  56791. relativePos = hit->getLocalPoint (0, screenPos);
  56792. return ddt;
  56793. }
  56794. hit = hit->getParentComponent();
  56795. }
  56796. return 0;
  56797. }
  56798. void mouseUp (const MouseEvent& e)
  56799. {
  56800. if (e.originalComponent != this)
  56801. {
  56802. if (mouseDragSource != 0)
  56803. mouseDragSource->removeMouseListener (this);
  56804. bool dropAccepted = false;
  56805. DragAndDropTarget* ddt = 0;
  56806. Point<int> relPos;
  56807. if (isVisible())
  56808. {
  56809. setVisible (false);
  56810. ddt = findTarget (e.getScreenPosition(), relPos);
  56811. // fade this component and remove it - it'll be deleted later by the timer callback
  56812. dropAccepted = ddt != 0;
  56813. setVisible (true);
  56814. if (dropAccepted || source == 0)
  56815. {
  56816. Desktop::getInstance().getAnimator().fadeOut (this, 120);
  56817. }
  56818. else
  56819. {
  56820. const Point<int> target (source->localPointToGlobal (source->getLocalBounds().getCentre()));
  56821. const Point<int> ourCentre (localPointToGlobal (getLocalBounds().getCentre()));
  56822. Desktop::getInstance().getAnimator().animateComponent (this,
  56823. getBounds() + (target - ourCentre),
  56824. 0.0f, 120,
  56825. true, 1.0, 1.0);
  56826. }
  56827. }
  56828. if (getParentComponent() != 0)
  56829. getParentComponent()->removeChildComponent (this);
  56830. if (dropAccepted && ddt != 0)
  56831. {
  56832. // (note: use a local copy of the dragDesc member in case the callback runs
  56833. // a modal loop and deletes this object before the method completes)
  56834. const String dragDescLocal (dragDesc);
  56835. currentlyOverComp = 0;
  56836. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56837. }
  56838. // careful - this object could now be deleted..
  56839. }
  56840. }
  56841. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56842. {
  56843. // (note: use a local copy of the dragDesc member in case the callback runs
  56844. // a modal loop and deletes this object before it returns)
  56845. const String dragDescLocal (dragDesc);
  56846. Point<int> newPos (screenPos + imageOffset);
  56847. if (getParentComponent() != 0)
  56848. newPos = getParentComponent()->getLocalPoint (0, newPos);
  56849. //if (newX != getX() || newY != getY())
  56850. {
  56851. setTopLeftPosition (newPos.getX(), newPos.getY());
  56852. Point<int> relPos;
  56853. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56854. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56855. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56856. if (ddtComp != currentlyOverComp)
  56857. {
  56858. if (currentlyOverComp != 0 && source != 0
  56859. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56860. {
  56861. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56862. }
  56863. currentlyOverComp = ddtComp;
  56864. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56865. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56866. }
  56867. DragAndDropTarget* target = getCurrentlyOver();
  56868. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  56869. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56870. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  56871. {
  56872. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56873. {
  56874. hasCheckedForExternalDrag = true;
  56875. StringArray files;
  56876. bool canMoveFiles = false;
  56877. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56878. && files.size() > 0)
  56879. {
  56880. WeakReference<Component> cdw (this);
  56881. setVisible (false);
  56882. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56883. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56884. if (cdw != 0)
  56885. delete this;
  56886. return;
  56887. }
  56888. }
  56889. }
  56890. }
  56891. }
  56892. void mouseDrag (const MouseEvent& e)
  56893. {
  56894. if (e.originalComponent != this)
  56895. updateLocation (true, e.getScreenPosition());
  56896. }
  56897. void timerCallback()
  56898. {
  56899. if (source == 0)
  56900. {
  56901. delete this;
  56902. }
  56903. else if (! isMouseButtonDownAnywhere())
  56904. {
  56905. if (mouseDragSource != 0)
  56906. mouseDragSource->removeMouseListener (this);
  56907. delete this;
  56908. }
  56909. }
  56910. private:
  56911. Image image;
  56912. WeakReference<Component> source;
  56913. WeakReference<Component> mouseDragSource;
  56914. DragAndDropContainer* const owner;
  56915. WeakReference<Component> currentlyOverComp;
  56916. DragAndDropTarget* getCurrentlyOver()
  56917. {
  56918. return dynamic_cast <DragAndDropTarget*> (currentlyOverComp.get());
  56919. }
  56920. String dragDesc;
  56921. const Point<int> imageOffset;
  56922. bool hasCheckedForExternalDrag, drawImage;
  56923. JUCE_DECLARE_NON_COPYABLE (DragImageComponent);
  56924. };
  56925. DragAndDropContainer::DragAndDropContainer()
  56926. {
  56927. }
  56928. DragAndDropContainer::~DragAndDropContainer()
  56929. {
  56930. dragImageComponent = 0;
  56931. }
  56932. void DragAndDropContainer::startDragging (const String& sourceDescription,
  56933. Component* sourceComponent,
  56934. const Image& dragImage_,
  56935. const bool allowDraggingToExternalWindows,
  56936. const Point<int>* imageOffsetFromMouse)
  56937. {
  56938. Image dragImage (dragImage_);
  56939. if (dragImageComponent == 0)
  56940. {
  56941. Component* const thisComp = dynamic_cast <Component*> (this);
  56942. if (thisComp == 0)
  56943. {
  56944. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  56945. return;
  56946. }
  56947. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  56948. if (draggingSource == 0 || ! draggingSource->isDragging())
  56949. {
  56950. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  56951. return;
  56952. }
  56953. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  56954. Point<int> imageOffset;
  56955. if (dragImage.isNull())
  56956. {
  56957. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  56958. .convertedToFormat (Image::ARGB);
  56959. dragImage.multiplyAllAlphas (0.6f);
  56960. const int lo = 150;
  56961. const int hi = 400;
  56962. Point<int> relPos (sourceComponent->getLocalPoint (0, lastMouseDown));
  56963. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  56964. for (int y = dragImage.getHeight(); --y >= 0;)
  56965. {
  56966. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  56967. for (int x = dragImage.getWidth(); --x >= 0;)
  56968. {
  56969. const int dx = x - clipped.getX();
  56970. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  56971. if (distance > lo)
  56972. {
  56973. const float alpha = (distance > hi) ? 0
  56974. : (hi - distance) / (float) (hi - lo)
  56975. + Random::getSystemRandom().nextFloat() * 0.008f;
  56976. dragImage.multiplyAlphaAt (x, y, alpha);
  56977. }
  56978. }
  56979. }
  56980. imageOffset = -clipped;
  56981. }
  56982. else
  56983. {
  56984. if (imageOffsetFromMouse == 0)
  56985. imageOffset = -dragImage.getBounds().getCentre();
  56986. else
  56987. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  56988. }
  56989. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  56990. draggingSource->getComponentUnderMouse(), this, imageOffset);
  56991. currentDragDesc = sourceDescription;
  56992. if (allowDraggingToExternalWindows)
  56993. {
  56994. if (! Desktop::canUseSemiTransparentWindows())
  56995. dragImageComponent->setOpaque (true);
  56996. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56997. | ComponentPeer::windowIsTemporary
  56998. | ComponentPeer::windowIgnoresKeyPresses);
  56999. }
  57000. else
  57001. thisComp->addChildComponent (dragImageComponent);
  57002. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  57003. dragImageComponent->setVisible (true);
  57004. }
  57005. }
  57006. bool DragAndDropContainer::isDragAndDropActive() const
  57007. {
  57008. return dragImageComponent != 0;
  57009. }
  57010. const String DragAndDropContainer::getCurrentDragDescription() const
  57011. {
  57012. return (dragImageComponent != 0) ? currentDragDesc
  57013. : String::empty;
  57014. }
  57015. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  57016. {
  57017. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  57018. }
  57019. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57020. {
  57021. return false;
  57022. }
  57023. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57024. {
  57025. }
  57026. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57027. {
  57028. }
  57029. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57030. {
  57031. }
  57032. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57033. {
  57034. return true;
  57035. }
  57036. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57037. {
  57038. }
  57039. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57040. {
  57041. }
  57042. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57043. {
  57044. }
  57045. END_JUCE_NAMESPACE
  57046. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57047. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57048. BEGIN_JUCE_NAMESPACE
  57049. class MouseCursor::SharedCursorHandle
  57050. {
  57051. public:
  57052. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57053. : handle (createStandardMouseCursor (type)),
  57054. refCount (1),
  57055. standardType (type),
  57056. isStandard (true)
  57057. {
  57058. }
  57059. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57060. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57061. refCount (1),
  57062. standardType (MouseCursor::NormalCursor),
  57063. isStandard (false)
  57064. {
  57065. }
  57066. ~SharedCursorHandle()
  57067. {
  57068. deleteMouseCursor (handle, isStandard);
  57069. }
  57070. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57071. {
  57072. const ScopedLock sl (getLock());
  57073. for (int i = 0; i < getCursors().size(); ++i)
  57074. {
  57075. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57076. if (sc->standardType == type)
  57077. return sc->retain();
  57078. }
  57079. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57080. getCursors().add (sc);
  57081. return sc;
  57082. }
  57083. SharedCursorHandle* retain() throw()
  57084. {
  57085. ++refCount;
  57086. return this;
  57087. }
  57088. void release()
  57089. {
  57090. if (--refCount == 0)
  57091. {
  57092. if (isStandard)
  57093. {
  57094. const ScopedLock sl (getLock());
  57095. getCursors().removeValue (this);
  57096. }
  57097. delete this;
  57098. }
  57099. }
  57100. void* getHandle() const throw() { return handle; }
  57101. private:
  57102. void* const handle;
  57103. Atomic <int> refCount;
  57104. const MouseCursor::StandardCursorType standardType;
  57105. const bool isStandard;
  57106. static CriticalSection& getLock()
  57107. {
  57108. static CriticalSection lock;
  57109. return lock;
  57110. }
  57111. static Array <SharedCursorHandle*>& getCursors()
  57112. {
  57113. static Array <SharedCursorHandle*> cursors;
  57114. return cursors;
  57115. }
  57116. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SharedCursorHandle);
  57117. };
  57118. MouseCursor::MouseCursor()
  57119. : cursorHandle (0)
  57120. {
  57121. }
  57122. MouseCursor::MouseCursor (const StandardCursorType type)
  57123. : cursorHandle (type != MouseCursor::NormalCursor ? SharedCursorHandle::createStandard (type) : 0)
  57124. {
  57125. }
  57126. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57127. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57128. {
  57129. }
  57130. MouseCursor::MouseCursor (const MouseCursor& other)
  57131. : cursorHandle (other.cursorHandle == 0 ? 0 : other.cursorHandle->retain())
  57132. {
  57133. }
  57134. MouseCursor::~MouseCursor()
  57135. {
  57136. if (cursorHandle != 0)
  57137. cursorHandle->release();
  57138. }
  57139. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57140. {
  57141. if (other.cursorHandle != 0)
  57142. other.cursorHandle->retain();
  57143. if (cursorHandle != 0)
  57144. cursorHandle->release();
  57145. cursorHandle = other.cursorHandle;
  57146. return *this;
  57147. }
  57148. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57149. {
  57150. return getHandle() == other.getHandle();
  57151. }
  57152. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57153. {
  57154. return getHandle() != other.getHandle();
  57155. }
  57156. void* MouseCursor::getHandle() const throw()
  57157. {
  57158. return cursorHandle != 0 ? cursorHandle->getHandle() : 0;
  57159. }
  57160. void MouseCursor::showWaitCursor()
  57161. {
  57162. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57163. }
  57164. void MouseCursor::hideWaitCursor()
  57165. {
  57166. Desktop::getInstance().getMainMouseSource().revealCursor();
  57167. }
  57168. END_JUCE_NAMESPACE
  57169. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57170. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57171. BEGIN_JUCE_NAMESPACE
  57172. MouseEvent::MouseEvent (MouseInputSource& source_,
  57173. const Point<int>& position,
  57174. const ModifierKeys& mods_,
  57175. Component* const eventComponent_,
  57176. Component* const originator,
  57177. const Time& eventTime_,
  57178. const Point<int> mouseDownPos_,
  57179. const Time& mouseDownTime_,
  57180. const int numberOfClicks_,
  57181. const bool mouseWasDragged) throw()
  57182. : x (position.getX()),
  57183. y (position.getY()),
  57184. mods (mods_),
  57185. eventComponent (eventComponent_),
  57186. originalComponent (originator),
  57187. eventTime (eventTime_),
  57188. source (source_),
  57189. mouseDownPos (mouseDownPos_),
  57190. mouseDownTime (mouseDownTime_),
  57191. numberOfClicks (numberOfClicks_),
  57192. wasMovedSinceMouseDown (mouseWasDragged)
  57193. {
  57194. }
  57195. MouseEvent::~MouseEvent() throw()
  57196. {
  57197. }
  57198. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57199. {
  57200. if (otherComponent == 0)
  57201. {
  57202. jassertfalse;
  57203. return *this;
  57204. }
  57205. return MouseEvent (source, otherComponent->getLocalPoint (eventComponent, getPosition()),
  57206. mods, otherComponent, originalComponent, eventTime,
  57207. otherComponent->getLocalPoint (eventComponent, mouseDownPos),
  57208. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57209. }
  57210. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57211. {
  57212. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57213. eventTime, mouseDownPos, mouseDownTime,
  57214. numberOfClicks, wasMovedSinceMouseDown);
  57215. }
  57216. bool MouseEvent::mouseWasClicked() const throw()
  57217. {
  57218. return ! wasMovedSinceMouseDown;
  57219. }
  57220. int MouseEvent::getMouseDownX() const throw()
  57221. {
  57222. return mouseDownPos.getX();
  57223. }
  57224. int MouseEvent::getMouseDownY() const throw()
  57225. {
  57226. return mouseDownPos.getY();
  57227. }
  57228. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57229. {
  57230. return mouseDownPos;
  57231. }
  57232. int MouseEvent::getDistanceFromDragStartX() const throw()
  57233. {
  57234. return x - mouseDownPos.getX();
  57235. }
  57236. int MouseEvent::getDistanceFromDragStartY() const throw()
  57237. {
  57238. return y - mouseDownPos.getY();
  57239. }
  57240. int MouseEvent::getDistanceFromDragStart() const throw()
  57241. {
  57242. return mouseDownPos.getDistanceFrom (getPosition());
  57243. }
  57244. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57245. {
  57246. return getPosition() - mouseDownPos;
  57247. }
  57248. int MouseEvent::getLengthOfMousePress() const throw()
  57249. {
  57250. if (mouseDownTime.toMilliseconds() > 0)
  57251. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57252. return 0;
  57253. }
  57254. const Point<int> MouseEvent::getPosition() const throw()
  57255. {
  57256. return Point<int> (x, y);
  57257. }
  57258. int MouseEvent::getScreenX() const
  57259. {
  57260. return getScreenPosition().getX();
  57261. }
  57262. int MouseEvent::getScreenY() const
  57263. {
  57264. return getScreenPosition().getY();
  57265. }
  57266. const Point<int> MouseEvent::getScreenPosition() const
  57267. {
  57268. return eventComponent->localPointToGlobal (Point<int> (x, y));
  57269. }
  57270. int MouseEvent::getMouseDownScreenX() const
  57271. {
  57272. return getMouseDownScreenPosition().getX();
  57273. }
  57274. int MouseEvent::getMouseDownScreenY() const
  57275. {
  57276. return getMouseDownScreenPosition().getY();
  57277. }
  57278. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57279. {
  57280. return eventComponent->localPointToGlobal (mouseDownPos);
  57281. }
  57282. int MouseEvent::doubleClickTimeOutMs = 400;
  57283. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57284. {
  57285. doubleClickTimeOutMs = newTime;
  57286. }
  57287. int MouseEvent::getDoubleClickTimeout() throw()
  57288. {
  57289. return doubleClickTimeOutMs;
  57290. }
  57291. END_JUCE_NAMESPACE
  57292. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57293. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57294. BEGIN_JUCE_NAMESPACE
  57295. class MouseInputSourceInternal : public AsyncUpdater
  57296. {
  57297. public:
  57298. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57299. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0),
  57300. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57301. mouseEventCounter (0)
  57302. {
  57303. }
  57304. bool isDragging() const throw()
  57305. {
  57306. return buttonState.isAnyMouseButtonDown();
  57307. }
  57308. Component* getComponentUnderMouse() const
  57309. {
  57310. return static_cast <Component*> (componentUnderMouse);
  57311. }
  57312. const ModifierKeys getCurrentModifiers() const
  57313. {
  57314. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57315. }
  57316. ComponentPeer* getPeer()
  57317. {
  57318. if (! ComponentPeer::isValidPeer (lastPeer))
  57319. lastPeer = 0;
  57320. return lastPeer;
  57321. }
  57322. Component* findComponentAt (const Point<int>& screenPos)
  57323. {
  57324. ComponentPeer* const peer = getPeer();
  57325. if (peer != 0)
  57326. {
  57327. Component* const comp = peer->getComponent();
  57328. const Point<int> relativePos (comp->getLocalPoint (0, screenPos));
  57329. // (the contains() call is needed to test for overlapping desktop windows)
  57330. if (comp->contains (relativePos))
  57331. return comp->getComponentAt (relativePos);
  57332. }
  57333. return 0;
  57334. }
  57335. const Point<int> getScreenPosition() const
  57336. {
  57337. // This needs to return the live position if possible, but it mustn't update the lastScreenPos
  57338. // value, because that can cause continuity problems.
  57339. return unboundedMouseOffset + (isMouseDevice ? MouseInputSource::getCurrentMousePosition()
  57340. : lastScreenPos);
  57341. }
  57342. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const Time& time)
  57343. {
  57344. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57345. comp->internalMouseEnter (source, comp->getLocalPoint (0, screenPos), time);
  57346. }
  57347. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const Time& time)
  57348. {
  57349. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57350. comp->internalMouseExit (source, comp->getLocalPoint (0, screenPos), time);
  57351. }
  57352. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const Time& time)
  57353. {
  57354. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57355. comp->internalMouseMove (source, comp->getLocalPoint (0, screenPos), time);
  57356. }
  57357. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const Time& time)
  57358. {
  57359. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57360. comp->internalMouseDown (source, comp->getLocalPoint (0, screenPos), time);
  57361. }
  57362. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const Time& time)
  57363. {
  57364. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57365. comp->internalMouseDrag (source, comp->getLocalPoint (0, screenPos), time);
  57366. }
  57367. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const Time& time)
  57368. {
  57369. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57370. comp->internalMouseUp (source, comp->getLocalPoint (0, screenPos), time, getCurrentModifiers());
  57371. }
  57372. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const Time& time, float x, float y)
  57373. {
  57374. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57375. comp->internalMouseWheel (source, comp->getLocalPoint (0, screenPos), time, x, y);
  57376. }
  57377. // (returns true if the button change caused a modal event loop)
  57378. bool setButtons (const Point<int>& screenPos, const Time& time, const ModifierKeys& newButtonState)
  57379. {
  57380. if (buttonState == newButtonState)
  57381. return false;
  57382. setScreenPos (screenPos, time, false);
  57383. // (ignore secondary clicks when there's already a button down)
  57384. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57385. {
  57386. buttonState = newButtonState;
  57387. return false;
  57388. }
  57389. const int lastCounter = mouseEventCounter;
  57390. if (buttonState.isAnyMouseButtonDown())
  57391. {
  57392. Component* const current = getComponentUnderMouse();
  57393. if (current != 0)
  57394. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57395. enableUnboundedMouseMovement (false, false);
  57396. }
  57397. buttonState = newButtonState;
  57398. if (buttonState.isAnyMouseButtonDown())
  57399. {
  57400. Desktop::getInstance().incrementMouseClickCounter();
  57401. Component* const current = getComponentUnderMouse();
  57402. if (current != 0)
  57403. {
  57404. registerMouseDown (screenPos, time, current, buttonState);
  57405. sendMouseDown (current, screenPos, time);
  57406. }
  57407. }
  57408. return lastCounter != mouseEventCounter;
  57409. }
  57410. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const Time& time)
  57411. {
  57412. Component* current = getComponentUnderMouse();
  57413. if (newComponent != current)
  57414. {
  57415. WeakReference<Component> safeNewComp (newComponent);
  57416. const ModifierKeys originalButtonState (buttonState);
  57417. if (current != 0)
  57418. {
  57419. setButtons (screenPos, time, ModifierKeys());
  57420. sendMouseExit (current, screenPos, time);
  57421. buttonState = originalButtonState;
  57422. }
  57423. componentUnderMouse = safeNewComp;
  57424. current = getComponentUnderMouse();
  57425. if (current != 0)
  57426. sendMouseEnter (current, screenPos, time);
  57427. revealCursor (false);
  57428. setButtons (screenPos, time, originalButtonState);
  57429. }
  57430. }
  57431. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const Time& time)
  57432. {
  57433. ModifierKeys::updateCurrentModifiers();
  57434. if (newPeer != lastPeer)
  57435. {
  57436. setComponentUnderMouse (0, screenPos, time);
  57437. lastPeer = newPeer;
  57438. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57439. }
  57440. }
  57441. void setScreenPos (const Point<int>& newScreenPos, const Time& time, const bool forceUpdate)
  57442. {
  57443. if (! isDragging())
  57444. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57445. if (newScreenPos != lastScreenPos || forceUpdate)
  57446. {
  57447. cancelPendingUpdate();
  57448. lastScreenPos = newScreenPos;
  57449. Component* const current = getComponentUnderMouse();
  57450. if (current != 0)
  57451. {
  57452. if (isDragging())
  57453. {
  57454. registerMouseDrag (newScreenPos);
  57455. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57456. if (isUnboundedMouseModeOn)
  57457. handleUnboundedDrag (current);
  57458. }
  57459. else
  57460. {
  57461. sendMouseMove (current, newScreenPos, time);
  57462. }
  57463. }
  57464. revealCursor (false);
  57465. }
  57466. }
  57467. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const Time& time, const ModifierKeys& newMods)
  57468. {
  57469. jassert (newPeer != 0);
  57470. lastTime = time;
  57471. ++mouseEventCounter;
  57472. const Point<int> screenPos (newPeer->localToGlobal (positionWithinPeer));
  57473. if (isDragging() && newMods.isAnyMouseButtonDown())
  57474. {
  57475. setScreenPos (screenPos, time, false);
  57476. }
  57477. else
  57478. {
  57479. setPeer (newPeer, screenPos, time);
  57480. ComponentPeer* peer = getPeer();
  57481. if (peer != 0)
  57482. {
  57483. if (setButtons (screenPos, time, newMods))
  57484. return; // some modal events have been dispatched, so the current event is now out-of-date
  57485. peer = getPeer();
  57486. if (peer != 0)
  57487. setScreenPos (screenPos, time, false);
  57488. }
  57489. }
  57490. }
  57491. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const Time& time, float x, float y)
  57492. {
  57493. jassert (peer != 0);
  57494. lastTime = time;
  57495. ++mouseEventCounter;
  57496. const Point<int> screenPos (peer->localToGlobal (positionWithinPeer));
  57497. setPeer (peer, screenPos, time);
  57498. setScreenPos (screenPos, time, false);
  57499. triggerFakeMove();
  57500. if (! isDragging())
  57501. {
  57502. Component* current = getComponentUnderMouse();
  57503. if (current != 0)
  57504. sendMouseWheel (current, screenPos, time, x, y);
  57505. }
  57506. }
  57507. const Time getLastMouseDownTime() const throw()
  57508. {
  57509. return Time (mouseDowns[0].time);
  57510. }
  57511. const Point<int> getLastMouseDownPosition() const throw()
  57512. {
  57513. return mouseDowns[0].position;
  57514. }
  57515. int getNumberOfMultipleClicks() const throw()
  57516. {
  57517. int numClicks = 0;
  57518. if (mouseDowns[0].time != Time())
  57519. {
  57520. if (! mouseMovedSignificantlySincePressed)
  57521. ++numClicks;
  57522. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57523. {
  57524. if (mouseDowns[0].canBePartOfMultipleClickWith (mouseDowns[i], (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))))
  57525. ++numClicks;
  57526. else
  57527. break;
  57528. }
  57529. }
  57530. return numClicks;
  57531. }
  57532. bool hasMouseMovedSignificantlySincePressed() const throw()
  57533. {
  57534. return mouseMovedSignificantlySincePressed
  57535. || lastTime > mouseDowns[0].time + RelativeTime::milliseconds (300);
  57536. }
  57537. void triggerFakeMove()
  57538. {
  57539. triggerAsyncUpdate();
  57540. }
  57541. void handleAsyncUpdate()
  57542. {
  57543. setScreenPos (lastScreenPos, jmax (lastTime, Time::getCurrentTime()), true);
  57544. }
  57545. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57546. {
  57547. enable = enable && isDragging();
  57548. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57549. if (enable != isUnboundedMouseModeOn)
  57550. {
  57551. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57552. {
  57553. // when released, return the mouse to within the component's bounds
  57554. Component* current = getComponentUnderMouse();
  57555. if (current != 0)
  57556. Desktop::setMousePosition (current->getScreenBounds()
  57557. .getConstrainedPoint (lastScreenPos));
  57558. }
  57559. isUnboundedMouseModeOn = enable;
  57560. unboundedMouseOffset = Point<int>();
  57561. revealCursor (true);
  57562. }
  57563. }
  57564. void handleUnboundedDrag (Component* current)
  57565. {
  57566. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57567. if (! screenArea.contains (lastScreenPos))
  57568. {
  57569. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57570. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57571. Desktop::setMousePosition (componentCentre);
  57572. }
  57573. else if (isCursorVisibleUntilOffscreen
  57574. && (! unboundedMouseOffset.isOrigin())
  57575. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57576. {
  57577. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57578. unboundedMouseOffset = Point<int>();
  57579. }
  57580. }
  57581. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57582. {
  57583. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57584. {
  57585. cursor = MouseCursor::NoCursor;
  57586. forcedUpdate = true;
  57587. }
  57588. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57589. {
  57590. currentCursorHandle = cursor.getHandle();
  57591. cursor.showInWindow (getPeer());
  57592. }
  57593. }
  57594. void hideCursor()
  57595. {
  57596. showMouseCursor (MouseCursor::NoCursor, true);
  57597. }
  57598. void revealCursor (bool forcedUpdate)
  57599. {
  57600. MouseCursor mc (MouseCursor::NormalCursor);
  57601. Component* current = getComponentUnderMouse();
  57602. if (current != 0)
  57603. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57604. showMouseCursor (mc, forcedUpdate);
  57605. }
  57606. const int index;
  57607. const bool isMouseDevice;
  57608. Point<int> lastScreenPos;
  57609. ModifierKeys buttonState;
  57610. private:
  57611. MouseInputSource& source;
  57612. WeakReference<Component> componentUnderMouse;
  57613. ComponentPeer* lastPeer;
  57614. Point<int> unboundedMouseOffset;
  57615. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57616. void* currentCursorHandle;
  57617. int mouseEventCounter;
  57618. struct RecentMouseDown
  57619. {
  57620. RecentMouseDown() : component (0)
  57621. {
  57622. }
  57623. Point<int> position;
  57624. Time time;
  57625. Component* component;
  57626. ModifierKeys buttons;
  57627. bool canBePartOfMultipleClickWith (const RecentMouseDown& other, const int maxTimeBetweenMs) const
  57628. {
  57629. return time - other.time < RelativeTime::milliseconds (maxTimeBetweenMs)
  57630. && abs (position.getX() - other.position.getX()) < 8
  57631. && abs (position.getY() - other.position.getY()) < 8
  57632. && buttons == other.buttons;;
  57633. }
  57634. };
  57635. RecentMouseDown mouseDowns[4];
  57636. bool mouseMovedSignificantlySincePressed;
  57637. Time lastTime;
  57638. void registerMouseDown (const Point<int>& screenPos, const Time& time,
  57639. Component* const component, const ModifierKeys& modifiers) throw()
  57640. {
  57641. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57642. mouseDowns[i] = mouseDowns[i - 1];
  57643. mouseDowns[0].position = screenPos;
  57644. mouseDowns[0].time = time;
  57645. mouseDowns[0].component = component;
  57646. mouseDowns[0].buttons = modifiers.withOnlyMouseButtons();
  57647. mouseMovedSignificantlySincePressed = false;
  57648. }
  57649. void registerMouseDrag (const Point<int>& screenPos) throw()
  57650. {
  57651. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57652. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57653. }
  57654. JUCE_DECLARE_NON_COPYABLE (MouseInputSourceInternal);
  57655. };
  57656. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57657. {
  57658. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57659. }
  57660. MouseInputSource::~MouseInputSource()
  57661. {
  57662. }
  57663. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57664. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57665. bool MouseInputSource::canHover() const { return isMouse(); }
  57666. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57667. int MouseInputSource::getIndex() const { return pimpl->index; }
  57668. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57669. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57670. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57671. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57672. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57673. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57674. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57675. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57676. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57677. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57678. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57679. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57680. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57681. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57682. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57683. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57684. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57685. {
  57686. pimpl->handleEvent (peer, positionWithinPeer, Time (time), mods.withOnlyMouseButtons());
  57687. }
  57688. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57689. {
  57690. pimpl->handleWheel (peer, positionWithinPeer, Time (time), x, y);
  57691. }
  57692. END_JUCE_NAMESPACE
  57693. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57694. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57695. BEGIN_JUCE_NAMESPACE
  57696. void MouseListener::mouseEnter (const MouseEvent&)
  57697. {
  57698. }
  57699. void MouseListener::mouseExit (const MouseEvent&)
  57700. {
  57701. }
  57702. void MouseListener::mouseDown (const MouseEvent&)
  57703. {
  57704. }
  57705. void MouseListener::mouseUp (const MouseEvent&)
  57706. {
  57707. }
  57708. void MouseListener::mouseDrag (const MouseEvent&)
  57709. {
  57710. }
  57711. void MouseListener::mouseMove (const MouseEvent&)
  57712. {
  57713. }
  57714. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57715. {
  57716. }
  57717. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57718. {
  57719. }
  57720. END_JUCE_NAMESPACE
  57721. /*** End of inlined file: juce_MouseListener.cpp ***/
  57722. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57723. BEGIN_JUCE_NAMESPACE
  57724. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57725. const String& buttonTextWhenTrue,
  57726. const String& buttonTextWhenFalse)
  57727. : PropertyComponent (name),
  57728. onText (buttonTextWhenTrue),
  57729. offText (buttonTextWhenFalse)
  57730. {
  57731. addAndMakeVisible (&button);
  57732. button.setClickingTogglesState (false);
  57733. button.addListener (this);
  57734. }
  57735. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57736. const String& name,
  57737. const String& buttonText)
  57738. : PropertyComponent (name),
  57739. onText (buttonText),
  57740. offText (buttonText)
  57741. {
  57742. addAndMakeVisible (&button);
  57743. button.setClickingTogglesState (false);
  57744. button.setButtonText (buttonText);
  57745. button.getToggleStateValue().referTo (valueToControl);
  57746. button.setClickingTogglesState (true);
  57747. }
  57748. BooleanPropertyComponent::~BooleanPropertyComponent()
  57749. {
  57750. }
  57751. void BooleanPropertyComponent::setState (const bool newState)
  57752. {
  57753. button.setToggleState (newState, true);
  57754. }
  57755. bool BooleanPropertyComponent::getState() const
  57756. {
  57757. return button.getToggleState();
  57758. }
  57759. void BooleanPropertyComponent::paint (Graphics& g)
  57760. {
  57761. PropertyComponent::paint (g);
  57762. g.setColour (Colours::white);
  57763. g.fillRect (button.getBounds());
  57764. g.setColour (findColour (ComboBox::outlineColourId));
  57765. g.drawRect (button.getBounds());
  57766. }
  57767. void BooleanPropertyComponent::refresh()
  57768. {
  57769. button.setToggleState (getState(), false);
  57770. button.setButtonText (button.getToggleState() ? onText : offText);
  57771. }
  57772. void BooleanPropertyComponent::buttonClicked (Button*)
  57773. {
  57774. setState (! getState());
  57775. }
  57776. END_JUCE_NAMESPACE
  57777. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57778. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57779. BEGIN_JUCE_NAMESPACE
  57780. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57781. const bool triggerOnMouseDown)
  57782. : PropertyComponent (name)
  57783. {
  57784. addAndMakeVisible (&button);
  57785. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  57786. button.addListener (this);
  57787. }
  57788. ButtonPropertyComponent::~ButtonPropertyComponent()
  57789. {
  57790. }
  57791. void ButtonPropertyComponent::refresh()
  57792. {
  57793. button.setButtonText (getButtonText());
  57794. }
  57795. void ButtonPropertyComponent::buttonClicked (Button*)
  57796. {
  57797. buttonClicked();
  57798. }
  57799. END_JUCE_NAMESPACE
  57800. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57801. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57802. BEGIN_JUCE_NAMESPACE
  57803. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  57804. public ValueListener
  57805. {
  57806. public:
  57807. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  57808. : sourceValue (sourceValue_),
  57809. mappings (mappings_)
  57810. {
  57811. sourceValue.addListener (this);
  57812. }
  57813. ~RemapperValueSource() {}
  57814. const var getValue() const
  57815. {
  57816. return mappings.indexOf (sourceValue.getValue()) + 1;
  57817. }
  57818. void setValue (const var& newValue)
  57819. {
  57820. const var remappedVal (mappings [(int) newValue - 1]);
  57821. if (remappedVal != sourceValue)
  57822. sourceValue = remappedVal;
  57823. }
  57824. void valueChanged (Value&)
  57825. {
  57826. sendChangeMessage (true);
  57827. }
  57828. protected:
  57829. Value sourceValue;
  57830. Array<var> mappings;
  57831. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RemapperValueSource);
  57832. };
  57833. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  57834. : PropertyComponent (name),
  57835. isCustomClass (true)
  57836. {
  57837. }
  57838. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  57839. const String& name,
  57840. const StringArray& choices_,
  57841. const Array <var>& correspondingValues)
  57842. : PropertyComponent (name),
  57843. choices (choices_),
  57844. isCustomClass (false)
  57845. {
  57846. // The array of corresponding values must contain one value for each of the items in
  57847. // the choices array!
  57848. jassert (correspondingValues.size() == choices.size());
  57849. createComboBox();
  57850. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  57851. }
  57852. ChoicePropertyComponent::~ChoicePropertyComponent()
  57853. {
  57854. }
  57855. void ChoicePropertyComponent::createComboBox()
  57856. {
  57857. addAndMakeVisible (&comboBox);
  57858. for (int i = 0; i < choices.size(); ++i)
  57859. {
  57860. if (choices[i].isNotEmpty())
  57861. comboBox.addItem (choices[i], i + 1);
  57862. else
  57863. comboBox.addSeparator();
  57864. }
  57865. comboBox.setEditableText (false);
  57866. }
  57867. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  57868. {
  57869. jassertfalse; // you need to override this method in your subclass!
  57870. }
  57871. int ChoicePropertyComponent::getIndex() const
  57872. {
  57873. jassertfalse; // you need to override this method in your subclass!
  57874. return -1;
  57875. }
  57876. const StringArray& ChoicePropertyComponent::getChoices() const
  57877. {
  57878. return choices;
  57879. }
  57880. void ChoicePropertyComponent::refresh()
  57881. {
  57882. if (isCustomClass)
  57883. {
  57884. if (! comboBox.isVisible())
  57885. {
  57886. createComboBox();
  57887. comboBox.addListener (this);
  57888. }
  57889. comboBox.setSelectedId (getIndex() + 1, true);
  57890. }
  57891. }
  57892. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  57893. {
  57894. if (isCustomClass)
  57895. {
  57896. const int newIndex = comboBox.getSelectedId() - 1;
  57897. if (newIndex != getIndex())
  57898. setIndex (newIndex);
  57899. }
  57900. }
  57901. END_JUCE_NAMESPACE
  57902. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57903. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  57904. BEGIN_JUCE_NAMESPACE
  57905. PropertyComponent::PropertyComponent (const String& name,
  57906. const int preferredHeight_)
  57907. : Component (name),
  57908. preferredHeight (preferredHeight_)
  57909. {
  57910. jassert (name.isNotEmpty());
  57911. }
  57912. PropertyComponent::~PropertyComponent()
  57913. {
  57914. }
  57915. void PropertyComponent::paint (Graphics& g)
  57916. {
  57917. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  57918. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  57919. }
  57920. void PropertyComponent::resized()
  57921. {
  57922. if (getNumChildComponents() > 0)
  57923. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  57924. }
  57925. void PropertyComponent::enablementChanged()
  57926. {
  57927. repaint();
  57928. }
  57929. END_JUCE_NAMESPACE
  57930. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  57931. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  57932. BEGIN_JUCE_NAMESPACE
  57933. class PropertySectionComponent : public Component
  57934. {
  57935. public:
  57936. PropertySectionComponent (const String& sectionTitle,
  57937. const Array <PropertyComponent*>& newProperties,
  57938. const bool sectionIsOpen_)
  57939. : Component (sectionTitle),
  57940. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  57941. sectionIsOpen (sectionIsOpen_)
  57942. {
  57943. propertyComps.addArray (newProperties);
  57944. for (int i = propertyComps.size(); --i >= 0;)
  57945. {
  57946. addAndMakeVisible (propertyComps.getUnchecked(i));
  57947. propertyComps.getUnchecked(i)->refresh();
  57948. }
  57949. }
  57950. ~PropertySectionComponent()
  57951. {
  57952. propertyComps.clear();
  57953. }
  57954. void paint (Graphics& g)
  57955. {
  57956. if (titleHeight > 0)
  57957. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  57958. }
  57959. void resized()
  57960. {
  57961. int y = titleHeight;
  57962. for (int i = 0; i < propertyComps.size(); ++i)
  57963. {
  57964. PropertyComponent* const pec = propertyComps.getUnchecked (i);
  57965. pec->setBounds (1, y, getWidth() - 2, pec->getPreferredHeight());
  57966. y = pec->getBottom();
  57967. }
  57968. }
  57969. int getPreferredHeight() const
  57970. {
  57971. int y = titleHeight;
  57972. if (isOpen())
  57973. {
  57974. for (int i = propertyComps.size(); --i >= 0;)
  57975. y += propertyComps.getUnchecked(i)->getPreferredHeight();
  57976. }
  57977. return y;
  57978. }
  57979. void setOpen (const bool open)
  57980. {
  57981. if (sectionIsOpen != open)
  57982. {
  57983. sectionIsOpen = open;
  57984. for (int i = propertyComps.size(); --i >= 0;)
  57985. propertyComps.getUnchecked(i)->setVisible (open);
  57986. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  57987. if (pp != 0)
  57988. pp->resized();
  57989. }
  57990. }
  57991. bool isOpen() const
  57992. {
  57993. return sectionIsOpen;
  57994. }
  57995. void refreshAll() const
  57996. {
  57997. for (int i = propertyComps.size(); --i >= 0;)
  57998. propertyComps.getUnchecked (i)->refresh();
  57999. }
  58000. void mouseUp (const MouseEvent& e)
  58001. {
  58002. if (e.getMouseDownX() < titleHeight
  58003. && e.x < titleHeight
  58004. && e.y < titleHeight
  58005. && e.getNumberOfClicks() != 2)
  58006. {
  58007. setOpen (! isOpen());
  58008. }
  58009. }
  58010. void mouseDoubleClick (const MouseEvent& e)
  58011. {
  58012. if (e.y < titleHeight)
  58013. setOpen (! isOpen());
  58014. }
  58015. private:
  58016. OwnedArray <PropertyComponent> propertyComps;
  58017. int titleHeight;
  58018. bool sectionIsOpen;
  58019. JUCE_DECLARE_NON_COPYABLE (PropertySectionComponent);
  58020. };
  58021. class PropertyPanel::PropertyHolderComponent : public Component
  58022. {
  58023. public:
  58024. PropertyHolderComponent() {}
  58025. void paint (Graphics&) {}
  58026. void updateLayout (int width)
  58027. {
  58028. int y = 0;
  58029. for (int i = 0; i < sections.size(); ++i)
  58030. {
  58031. PropertySectionComponent* const section = sections.getUnchecked(i);
  58032. section->setBounds (0, y, width, section->getPreferredHeight());
  58033. y = section->getBottom();
  58034. }
  58035. setSize (width, y);
  58036. repaint();
  58037. }
  58038. void refreshAll() const
  58039. {
  58040. for (int i = 0; i < sections.size(); ++i)
  58041. sections.getUnchecked(i)->refreshAll();
  58042. }
  58043. void clear()
  58044. {
  58045. sections.clear();
  58046. }
  58047. void addSection (PropertySectionComponent* newSection)
  58048. {
  58049. sections.add (newSection);
  58050. addAndMakeVisible (newSection, 0);
  58051. }
  58052. int getNumSections() const throw() { return sections.size(); }
  58053. PropertySectionComponent* getSection (const int index) const { return sections [index]; }
  58054. private:
  58055. OwnedArray<PropertySectionComponent> sections;
  58056. JUCE_DECLARE_NON_COPYABLE (PropertyHolderComponent);
  58057. };
  58058. PropertyPanel::PropertyPanel()
  58059. {
  58060. messageWhenEmpty = TRANS("(nothing selected)");
  58061. addAndMakeVisible (&viewport);
  58062. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58063. viewport.setFocusContainer (true);
  58064. }
  58065. PropertyPanel::~PropertyPanel()
  58066. {
  58067. clear();
  58068. }
  58069. void PropertyPanel::paint (Graphics& g)
  58070. {
  58071. if (propertyHolderComponent->getNumSections() == 0)
  58072. {
  58073. g.setColour (Colours::black.withAlpha (0.5f));
  58074. g.setFont (14.0f);
  58075. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58076. Justification::centred, true);
  58077. }
  58078. }
  58079. void PropertyPanel::resized()
  58080. {
  58081. viewport.setBounds (getLocalBounds());
  58082. updatePropHolderLayout();
  58083. }
  58084. void PropertyPanel::clear()
  58085. {
  58086. if (propertyHolderComponent->getNumSections() > 0)
  58087. {
  58088. propertyHolderComponent->clear();
  58089. repaint();
  58090. }
  58091. }
  58092. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58093. {
  58094. if (propertyHolderComponent->getNumSections() == 0)
  58095. repaint();
  58096. propertyHolderComponent->addSection (new PropertySectionComponent (String::empty, newProperties, true));
  58097. updatePropHolderLayout();
  58098. }
  58099. void PropertyPanel::addSection (const String& sectionTitle,
  58100. const Array <PropertyComponent*>& newProperties,
  58101. const bool shouldBeOpen)
  58102. {
  58103. jassert (sectionTitle.isNotEmpty());
  58104. if (propertyHolderComponent->getNumSections() == 0)
  58105. repaint();
  58106. propertyHolderComponent->addSection (new PropertySectionComponent (sectionTitle, newProperties, shouldBeOpen));
  58107. updatePropHolderLayout();
  58108. }
  58109. void PropertyPanel::updatePropHolderLayout() const
  58110. {
  58111. const int maxWidth = viewport.getMaximumVisibleWidth();
  58112. propertyHolderComponent->updateLayout (maxWidth);
  58113. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58114. if (maxWidth != newMaxWidth)
  58115. {
  58116. // need to do this twice because of scrollbars changing the size, etc.
  58117. propertyHolderComponent->updateLayout (newMaxWidth);
  58118. }
  58119. }
  58120. void PropertyPanel::refreshAll() const
  58121. {
  58122. propertyHolderComponent->refreshAll();
  58123. }
  58124. const StringArray PropertyPanel::getSectionNames() const
  58125. {
  58126. StringArray s;
  58127. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58128. {
  58129. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58130. if (section->getName().isNotEmpty())
  58131. s.add (section->getName());
  58132. }
  58133. return s;
  58134. }
  58135. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58136. {
  58137. int index = 0;
  58138. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58139. {
  58140. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58141. if (section->getName().isNotEmpty())
  58142. {
  58143. if (index == sectionIndex)
  58144. return section->isOpen();
  58145. ++index;
  58146. }
  58147. }
  58148. return false;
  58149. }
  58150. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58151. {
  58152. int index = 0;
  58153. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58154. {
  58155. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58156. if (section->getName().isNotEmpty())
  58157. {
  58158. if (index == sectionIndex)
  58159. {
  58160. section->setOpen (shouldBeOpen);
  58161. break;
  58162. }
  58163. ++index;
  58164. }
  58165. }
  58166. }
  58167. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58168. {
  58169. int index = 0;
  58170. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58171. {
  58172. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58173. if (section->getName().isNotEmpty())
  58174. {
  58175. if (index == sectionIndex)
  58176. {
  58177. section->setEnabled (shouldBeEnabled);
  58178. break;
  58179. }
  58180. ++index;
  58181. }
  58182. }
  58183. }
  58184. XmlElement* PropertyPanel::getOpennessState() const
  58185. {
  58186. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58187. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58188. const StringArray sections (getSectionNames());
  58189. for (int i = 0; i < sections.size(); ++i)
  58190. {
  58191. if (sections[i].isNotEmpty())
  58192. {
  58193. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58194. e->setAttribute ("name", sections[i]);
  58195. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58196. }
  58197. }
  58198. return xml;
  58199. }
  58200. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58201. {
  58202. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58203. {
  58204. const StringArray sections (getSectionNames());
  58205. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58206. {
  58207. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58208. e->getBoolAttribute ("open"));
  58209. }
  58210. viewport.setViewPosition (viewport.getViewPositionX(),
  58211. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58212. }
  58213. }
  58214. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58215. {
  58216. if (messageWhenEmpty != newMessage)
  58217. {
  58218. messageWhenEmpty = newMessage;
  58219. repaint();
  58220. }
  58221. }
  58222. const String& PropertyPanel::getMessageWhenEmpty() const
  58223. {
  58224. return messageWhenEmpty;
  58225. }
  58226. END_JUCE_NAMESPACE
  58227. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58228. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58229. BEGIN_JUCE_NAMESPACE
  58230. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58231. const double rangeMin,
  58232. const double rangeMax,
  58233. const double interval,
  58234. const double skewFactor)
  58235. : PropertyComponent (name)
  58236. {
  58237. addAndMakeVisible (&slider);
  58238. slider.setRange (rangeMin, rangeMax, interval);
  58239. slider.setSkewFactor (skewFactor);
  58240. slider.setSliderStyle (Slider::LinearBar);
  58241. slider.addListener (this);
  58242. }
  58243. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58244. const String& name,
  58245. const double rangeMin,
  58246. const double rangeMax,
  58247. const double interval,
  58248. const double skewFactor)
  58249. : PropertyComponent (name)
  58250. {
  58251. addAndMakeVisible (&slider);
  58252. slider.setRange (rangeMin, rangeMax, interval);
  58253. slider.setSkewFactor (skewFactor);
  58254. slider.setSliderStyle (Slider::LinearBar);
  58255. slider.getValueObject().referTo (valueToControl);
  58256. }
  58257. SliderPropertyComponent::~SliderPropertyComponent()
  58258. {
  58259. }
  58260. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58261. {
  58262. }
  58263. double SliderPropertyComponent::getValue() const
  58264. {
  58265. return slider.getValue();
  58266. }
  58267. void SliderPropertyComponent::refresh()
  58268. {
  58269. slider.setValue (getValue(), false);
  58270. }
  58271. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58272. {
  58273. if (getValue() != slider.getValue())
  58274. setValue (slider.getValue());
  58275. }
  58276. END_JUCE_NAMESPACE
  58277. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58278. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58279. BEGIN_JUCE_NAMESPACE
  58280. class TextPropLabel : public Label
  58281. {
  58282. public:
  58283. TextPropLabel (TextPropertyComponent& owner_,
  58284. const int maxChars_, const bool isMultiline_)
  58285. : Label (String::empty, String::empty),
  58286. owner (owner_),
  58287. maxChars (maxChars_),
  58288. isMultiline (isMultiline_)
  58289. {
  58290. setEditable (true, true, false);
  58291. setColour (backgroundColourId, Colours::white);
  58292. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58293. }
  58294. TextEditor* createEditorComponent()
  58295. {
  58296. TextEditor* const textEditor = Label::createEditorComponent();
  58297. textEditor->setInputRestrictions (maxChars);
  58298. if (isMultiline)
  58299. {
  58300. textEditor->setMultiLine (true, true);
  58301. textEditor->setReturnKeyStartsNewLine (true);
  58302. }
  58303. return textEditor;
  58304. }
  58305. void textWasEdited()
  58306. {
  58307. owner.textWasEdited();
  58308. }
  58309. private:
  58310. TextPropertyComponent& owner;
  58311. int maxChars;
  58312. bool isMultiline;
  58313. };
  58314. TextPropertyComponent::TextPropertyComponent (const String& name,
  58315. const int maxNumChars,
  58316. const bool isMultiLine)
  58317. : PropertyComponent (name)
  58318. {
  58319. createEditor (maxNumChars, isMultiLine);
  58320. }
  58321. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58322. const String& name,
  58323. const int maxNumChars,
  58324. const bool isMultiLine)
  58325. : PropertyComponent (name)
  58326. {
  58327. createEditor (maxNumChars, isMultiLine);
  58328. textEditor->getTextValue().referTo (valueToControl);
  58329. }
  58330. TextPropertyComponent::~TextPropertyComponent()
  58331. {
  58332. }
  58333. void TextPropertyComponent::setText (const String& newText)
  58334. {
  58335. textEditor->setText (newText, true);
  58336. }
  58337. const String TextPropertyComponent::getText() const
  58338. {
  58339. return textEditor->getText();
  58340. }
  58341. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58342. {
  58343. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58344. if (isMultiLine)
  58345. {
  58346. textEditor->setJustificationType (Justification::topLeft);
  58347. preferredHeight = 120;
  58348. }
  58349. }
  58350. void TextPropertyComponent::refresh()
  58351. {
  58352. textEditor->setText (getText(), false);
  58353. }
  58354. void TextPropertyComponent::textWasEdited()
  58355. {
  58356. const String newText (textEditor->getText());
  58357. if (getText() != newText)
  58358. setText (newText);
  58359. }
  58360. END_JUCE_NAMESPACE
  58361. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58362. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58363. BEGIN_JUCE_NAMESPACE
  58364. class SimpleDeviceManagerInputLevelMeter : public Component,
  58365. public Timer
  58366. {
  58367. public:
  58368. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58369. : manager (manager_),
  58370. level (0)
  58371. {
  58372. startTimer (50);
  58373. manager->enableInputLevelMeasurement (true);
  58374. }
  58375. ~SimpleDeviceManagerInputLevelMeter()
  58376. {
  58377. manager->enableInputLevelMeasurement (false);
  58378. }
  58379. void timerCallback()
  58380. {
  58381. const float newLevel = (float) manager->getCurrentInputLevel();
  58382. if (std::abs (level - newLevel) > 0.005f)
  58383. {
  58384. level = newLevel;
  58385. repaint();
  58386. }
  58387. }
  58388. void paint (Graphics& g)
  58389. {
  58390. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58391. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58392. }
  58393. private:
  58394. AudioDeviceManager* const manager;
  58395. float level;
  58396. JUCE_DECLARE_NON_COPYABLE (SimpleDeviceManagerInputLevelMeter);
  58397. };
  58398. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58399. public ListBoxModel
  58400. {
  58401. public:
  58402. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58403. const String& noItemsMessage_,
  58404. const int minNumber_,
  58405. const int maxNumber_)
  58406. : ListBox (String::empty, 0),
  58407. deviceManager (deviceManager_),
  58408. noItemsMessage (noItemsMessage_),
  58409. minNumber (minNumber_),
  58410. maxNumber (maxNumber_)
  58411. {
  58412. items = MidiInput::getDevices();
  58413. setModel (this);
  58414. setOutlineThickness (1);
  58415. }
  58416. ~MidiInputSelectorComponentListBox()
  58417. {
  58418. }
  58419. int getNumRows()
  58420. {
  58421. return items.size();
  58422. }
  58423. void paintListBoxItem (int row,
  58424. Graphics& g,
  58425. int width, int height,
  58426. bool rowIsSelected)
  58427. {
  58428. if (isPositiveAndBelow (row, items.size()))
  58429. {
  58430. if (rowIsSelected)
  58431. g.fillAll (findColour (TextEditor::highlightColourId)
  58432. .withMultipliedAlpha (0.3f));
  58433. const String item (items [row]);
  58434. bool enabled = deviceManager.isMidiInputEnabled (item);
  58435. const int x = getTickX();
  58436. const float tickW = height * 0.75f;
  58437. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58438. enabled, true, true, false);
  58439. g.setFont (height * 0.6f);
  58440. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58441. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58442. }
  58443. }
  58444. void listBoxItemClicked (int row, const MouseEvent& e)
  58445. {
  58446. selectRow (row);
  58447. if (e.x < getTickX())
  58448. flipEnablement (row);
  58449. }
  58450. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58451. {
  58452. flipEnablement (row);
  58453. }
  58454. void returnKeyPressed (int row)
  58455. {
  58456. flipEnablement (row);
  58457. }
  58458. void paint (Graphics& g)
  58459. {
  58460. ListBox::paint (g);
  58461. if (items.size() == 0)
  58462. {
  58463. g.setColour (Colours::grey);
  58464. g.setFont (13.0f);
  58465. g.drawText (noItemsMessage,
  58466. 0, 0, getWidth(), getHeight() / 2,
  58467. Justification::centred, true);
  58468. }
  58469. }
  58470. int getBestHeight (const int preferredHeight)
  58471. {
  58472. const int extra = getOutlineThickness() * 2;
  58473. return jmax (getRowHeight() * 2 + extra,
  58474. jmin (getRowHeight() * getNumRows() + extra,
  58475. preferredHeight));
  58476. }
  58477. private:
  58478. AudioDeviceManager& deviceManager;
  58479. const String noItemsMessage;
  58480. StringArray items;
  58481. int minNumber, maxNumber;
  58482. void flipEnablement (const int row)
  58483. {
  58484. if (isPositiveAndBelow (row, items.size()))
  58485. {
  58486. const String item (items [row]);
  58487. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58488. }
  58489. }
  58490. int getTickX() const
  58491. {
  58492. return getRowHeight() + 5;
  58493. }
  58494. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputSelectorComponentListBox);
  58495. };
  58496. class AudioDeviceSettingsPanel : public Component,
  58497. public ChangeListener,
  58498. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  58499. public ButtonListener
  58500. {
  58501. public:
  58502. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58503. AudioIODeviceType::DeviceSetupDetails& setup_,
  58504. const bool hideAdvancedOptionsWithButton)
  58505. : type (type_),
  58506. setup (setup_)
  58507. {
  58508. if (hideAdvancedOptionsWithButton)
  58509. {
  58510. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58511. showAdvancedSettingsButton->addListener (this);
  58512. }
  58513. type->scanForDevices();
  58514. setup.manager->addChangeListener (this);
  58515. changeListenerCallback (0);
  58516. }
  58517. ~AudioDeviceSettingsPanel()
  58518. {
  58519. setup.manager->removeChangeListener (this);
  58520. }
  58521. void resized()
  58522. {
  58523. const int lx = proportionOfWidth (0.35f);
  58524. const int w = proportionOfWidth (0.4f);
  58525. const int h = 24;
  58526. const int space = 6;
  58527. const int dh = h + space;
  58528. int y = 0;
  58529. if (outputDeviceDropDown != 0)
  58530. {
  58531. outputDeviceDropDown->setBounds (lx, y, w, h);
  58532. if (testButton != 0)
  58533. testButton->setBounds (proportionOfWidth (0.77f),
  58534. outputDeviceDropDown->getY(),
  58535. proportionOfWidth (0.18f),
  58536. h);
  58537. y += dh;
  58538. }
  58539. if (inputDeviceDropDown != 0)
  58540. {
  58541. inputDeviceDropDown->setBounds (lx, y, w, h);
  58542. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58543. inputDeviceDropDown->getY(),
  58544. proportionOfWidth (0.18f),
  58545. h);
  58546. y += dh;
  58547. }
  58548. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58549. if (outputChanList != 0)
  58550. {
  58551. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58552. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58553. y += bh + space;
  58554. }
  58555. if (inputChanList != 0)
  58556. {
  58557. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58558. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58559. y += bh + space;
  58560. }
  58561. y += space * 2;
  58562. if (showAdvancedSettingsButton != 0)
  58563. {
  58564. showAdvancedSettingsButton->changeWidthToFitText (h);
  58565. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58566. }
  58567. if (sampleRateDropDown != 0)
  58568. {
  58569. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58570. || ! showAdvancedSettingsButton->isVisible());
  58571. sampleRateDropDown->setBounds (lx, y, w, h);
  58572. y += dh;
  58573. }
  58574. if (bufferSizeDropDown != 0)
  58575. {
  58576. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58577. || ! showAdvancedSettingsButton->isVisible());
  58578. bufferSizeDropDown->setBounds (lx, y, w, h);
  58579. y += dh;
  58580. }
  58581. if (showUIButton != 0)
  58582. {
  58583. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58584. || ! showAdvancedSettingsButton->isVisible());
  58585. showUIButton->changeWidthToFitText (h);
  58586. showUIButton->setTopLeftPosition (lx, y);
  58587. }
  58588. }
  58589. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58590. {
  58591. if (comboBoxThatHasChanged == 0)
  58592. return;
  58593. AudioDeviceManager::AudioDeviceSetup config;
  58594. setup.manager->getAudioDeviceSetup (config);
  58595. String error;
  58596. if (comboBoxThatHasChanged == outputDeviceDropDown
  58597. || comboBoxThatHasChanged == inputDeviceDropDown)
  58598. {
  58599. if (outputDeviceDropDown != 0)
  58600. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58601. : outputDeviceDropDown->getText();
  58602. if (inputDeviceDropDown != 0)
  58603. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58604. : inputDeviceDropDown->getText();
  58605. if (! type->hasSeparateInputsAndOutputs())
  58606. config.inputDeviceName = config.outputDeviceName;
  58607. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58608. config.useDefaultInputChannels = true;
  58609. else
  58610. config.useDefaultOutputChannels = true;
  58611. error = setup.manager->setAudioDeviceSetup (config, true);
  58612. showCorrectDeviceName (inputDeviceDropDown, true);
  58613. showCorrectDeviceName (outputDeviceDropDown, false);
  58614. updateControlPanelButton();
  58615. resized();
  58616. }
  58617. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58618. {
  58619. if (sampleRateDropDown->getSelectedId() > 0)
  58620. {
  58621. config.sampleRate = sampleRateDropDown->getSelectedId();
  58622. error = setup.manager->setAudioDeviceSetup (config, true);
  58623. }
  58624. }
  58625. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58626. {
  58627. if (bufferSizeDropDown->getSelectedId() > 0)
  58628. {
  58629. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58630. error = setup.manager->setAudioDeviceSetup (config, true);
  58631. }
  58632. }
  58633. if (error.isNotEmpty())
  58634. {
  58635. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58636. "Error when trying to open audio device!",
  58637. error);
  58638. }
  58639. }
  58640. void buttonClicked (Button* button)
  58641. {
  58642. if (button == showAdvancedSettingsButton)
  58643. {
  58644. showAdvancedSettingsButton->setVisible (false);
  58645. resized();
  58646. }
  58647. else if (button == showUIButton)
  58648. {
  58649. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58650. if (device != 0 && device->showControlPanel())
  58651. {
  58652. setup.manager->closeAudioDevice();
  58653. setup.manager->restartLastAudioDevice();
  58654. getTopLevelComponent()->toFront (true);
  58655. }
  58656. }
  58657. else if (button == testButton && testButton != 0)
  58658. {
  58659. setup.manager->playTestSound();
  58660. }
  58661. }
  58662. void updateControlPanelButton()
  58663. {
  58664. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58665. showUIButton = 0;
  58666. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58667. {
  58668. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58669. TRANS ("opens the device's own control panel")));
  58670. showUIButton->addListener (this);
  58671. }
  58672. resized();
  58673. }
  58674. void changeListenerCallback (ChangeBroadcaster*)
  58675. {
  58676. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58677. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58678. {
  58679. if (outputDeviceDropDown == 0)
  58680. {
  58681. outputDeviceDropDown = new ComboBox (String::empty);
  58682. outputDeviceDropDown->addListener (this);
  58683. addAndMakeVisible (outputDeviceDropDown);
  58684. outputDeviceLabel = new Label (String::empty,
  58685. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58686. : TRANS ("device:"));
  58687. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58688. if (setup.maxNumOutputChannels > 0)
  58689. {
  58690. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58691. testButton->addListener (this);
  58692. }
  58693. }
  58694. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58695. }
  58696. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58697. {
  58698. if (inputDeviceDropDown == 0)
  58699. {
  58700. inputDeviceDropDown = new ComboBox (String::empty);
  58701. inputDeviceDropDown->addListener (this);
  58702. addAndMakeVisible (inputDeviceDropDown);
  58703. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58704. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58705. addAndMakeVisible (inputLevelMeter
  58706. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58707. }
  58708. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58709. }
  58710. updateControlPanelButton();
  58711. showCorrectDeviceName (inputDeviceDropDown, true);
  58712. showCorrectDeviceName (outputDeviceDropDown, false);
  58713. if (currentDevice != 0)
  58714. {
  58715. if (setup.maxNumOutputChannels > 0
  58716. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58717. {
  58718. if (outputChanList == 0)
  58719. {
  58720. addAndMakeVisible (outputChanList
  58721. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58722. TRANS ("(no audio output channels found)")));
  58723. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58724. outputChanLabel->attachToComponent (outputChanList, true);
  58725. }
  58726. outputChanList->refresh();
  58727. }
  58728. else
  58729. {
  58730. outputChanLabel = 0;
  58731. outputChanList = 0;
  58732. }
  58733. if (setup.maxNumInputChannels > 0
  58734. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58735. {
  58736. if (inputChanList == 0)
  58737. {
  58738. addAndMakeVisible (inputChanList
  58739. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58740. TRANS ("(no audio input channels found)")));
  58741. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58742. inputChanLabel->attachToComponent (inputChanList, true);
  58743. }
  58744. inputChanList->refresh();
  58745. }
  58746. else
  58747. {
  58748. inputChanLabel = 0;
  58749. inputChanList = 0;
  58750. }
  58751. // sample rate..
  58752. {
  58753. if (sampleRateDropDown == 0)
  58754. {
  58755. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58756. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58757. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58758. }
  58759. else
  58760. {
  58761. sampleRateDropDown->clear();
  58762. sampleRateDropDown->removeListener (this);
  58763. }
  58764. const int numRates = currentDevice->getNumSampleRates();
  58765. for (int i = 0; i < numRates; ++i)
  58766. {
  58767. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58768. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58769. }
  58770. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58771. sampleRateDropDown->addListener (this);
  58772. }
  58773. // buffer size
  58774. {
  58775. if (bufferSizeDropDown == 0)
  58776. {
  58777. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58778. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58779. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58780. }
  58781. else
  58782. {
  58783. bufferSizeDropDown->clear();
  58784. bufferSizeDropDown->removeListener (this);
  58785. }
  58786. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58787. double currentRate = currentDevice->getCurrentSampleRate();
  58788. if (currentRate == 0)
  58789. currentRate = 48000.0;
  58790. for (int i = 0; i < numBufferSizes; ++i)
  58791. {
  58792. const int bs = currentDevice->getBufferSizeSamples (i);
  58793. bufferSizeDropDown->addItem (String (bs)
  58794. + " samples ("
  58795. + String (bs * 1000.0 / currentRate, 1)
  58796. + " ms)",
  58797. bs);
  58798. }
  58799. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  58800. bufferSizeDropDown->addListener (this);
  58801. }
  58802. }
  58803. else
  58804. {
  58805. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  58806. sampleRateLabel = 0;
  58807. bufferSizeLabel = 0;
  58808. sampleRateDropDown = 0;
  58809. bufferSizeDropDown = 0;
  58810. if (outputDeviceDropDown != 0)
  58811. outputDeviceDropDown->setSelectedId (-1, true);
  58812. if (inputDeviceDropDown != 0)
  58813. inputDeviceDropDown->setSelectedId (-1, true);
  58814. }
  58815. resized();
  58816. setSize (getWidth(), getLowestY() + 4);
  58817. }
  58818. private:
  58819. AudioIODeviceType* const type;
  58820. const AudioIODeviceType::DeviceSetupDetails setup;
  58821. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  58822. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  58823. ScopedPointer<TextButton> testButton;
  58824. ScopedPointer<Component> inputLevelMeter;
  58825. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  58826. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  58827. {
  58828. if (box != 0)
  58829. {
  58830. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  58831. const int index = type->getIndexOfDevice (currentDevice, isInput);
  58832. box->setSelectedId (index + 1, true);
  58833. if (testButton != 0 && ! isInput)
  58834. testButton->setEnabled (index >= 0);
  58835. }
  58836. }
  58837. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  58838. {
  58839. const StringArray devs (type->getDeviceNames (isInputs));
  58840. combo.clear (true);
  58841. for (int i = 0; i < devs.size(); ++i)
  58842. combo.addItem (devs[i], i + 1);
  58843. combo.addItem (TRANS("<< none >>"), -1);
  58844. combo.setSelectedId (-1, true);
  58845. }
  58846. int getLowestY() const
  58847. {
  58848. int y = 0;
  58849. for (int i = getNumChildComponents(); --i >= 0;)
  58850. y = jmax (y, getChildComponent (i)->getBottom());
  58851. return y;
  58852. }
  58853. public:
  58854. class ChannelSelectorListBox : public ListBox,
  58855. public ListBoxModel
  58856. {
  58857. public:
  58858. enum BoxType
  58859. {
  58860. audioInputType,
  58861. audioOutputType
  58862. };
  58863. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  58864. const BoxType type_,
  58865. const String& noItemsMessage_)
  58866. : ListBox (String::empty, 0),
  58867. setup (setup_),
  58868. type (type_),
  58869. noItemsMessage (noItemsMessage_)
  58870. {
  58871. refresh();
  58872. setModel (this);
  58873. setOutlineThickness (1);
  58874. }
  58875. ~ChannelSelectorListBox()
  58876. {
  58877. }
  58878. void refresh()
  58879. {
  58880. items.clear();
  58881. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58882. if (currentDevice != 0)
  58883. {
  58884. if (type == audioInputType)
  58885. items = currentDevice->getInputChannelNames();
  58886. else if (type == audioOutputType)
  58887. items = currentDevice->getOutputChannelNames();
  58888. if (setup.useStereoPairs)
  58889. {
  58890. StringArray pairs;
  58891. for (int i = 0; i < items.size(); i += 2)
  58892. {
  58893. const String name (items[i]);
  58894. const String name2 (items[i + 1]);
  58895. String commonBit;
  58896. for (int j = 0; j < name.length(); ++j)
  58897. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  58898. commonBit = name.substring (0, j);
  58899. // Make sure we only split the name at a space, because otherwise, things
  58900. // like "input 11" + "input 12" would become "input 11 + 2"
  58901. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  58902. commonBit = commonBit.dropLastCharacters (1);
  58903. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  58904. }
  58905. items = pairs;
  58906. }
  58907. }
  58908. updateContent();
  58909. repaint();
  58910. }
  58911. int getNumRows()
  58912. {
  58913. return items.size();
  58914. }
  58915. void paintListBoxItem (int row,
  58916. Graphics& g,
  58917. int width, int height,
  58918. bool rowIsSelected)
  58919. {
  58920. if (isPositiveAndBelow (row, items.size()))
  58921. {
  58922. if (rowIsSelected)
  58923. g.fillAll (findColour (TextEditor::highlightColourId)
  58924. .withMultipliedAlpha (0.3f));
  58925. const String item (items [row]);
  58926. bool enabled = false;
  58927. AudioDeviceManager::AudioDeviceSetup config;
  58928. setup.manager->getAudioDeviceSetup (config);
  58929. if (setup.useStereoPairs)
  58930. {
  58931. if (type == audioInputType)
  58932. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  58933. else if (type == audioOutputType)
  58934. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  58935. }
  58936. else
  58937. {
  58938. if (type == audioInputType)
  58939. enabled = config.inputChannels [row];
  58940. else if (type == audioOutputType)
  58941. enabled = config.outputChannels [row];
  58942. }
  58943. const int x = getTickX();
  58944. const float tickW = height * 0.75f;
  58945. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58946. enabled, true, true, false);
  58947. g.setFont (height * 0.6f);
  58948. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58949. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58950. }
  58951. }
  58952. void listBoxItemClicked (int row, const MouseEvent& e)
  58953. {
  58954. selectRow (row);
  58955. if (e.x < getTickX())
  58956. flipEnablement (row);
  58957. }
  58958. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58959. {
  58960. flipEnablement (row);
  58961. }
  58962. void returnKeyPressed (int row)
  58963. {
  58964. flipEnablement (row);
  58965. }
  58966. void paint (Graphics& g)
  58967. {
  58968. ListBox::paint (g);
  58969. if (items.size() == 0)
  58970. {
  58971. g.setColour (Colours::grey);
  58972. g.setFont (13.0f);
  58973. g.drawText (noItemsMessage,
  58974. 0, 0, getWidth(), getHeight() / 2,
  58975. Justification::centred, true);
  58976. }
  58977. }
  58978. int getBestHeight (int maxHeight)
  58979. {
  58980. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  58981. getNumRows())
  58982. + getOutlineThickness() * 2;
  58983. }
  58984. private:
  58985. const AudioIODeviceType::DeviceSetupDetails setup;
  58986. const BoxType type;
  58987. const String noItemsMessage;
  58988. StringArray items;
  58989. void flipEnablement (const int row)
  58990. {
  58991. jassert (type == audioInputType || type == audioOutputType);
  58992. if (isPositiveAndBelow (row, items.size()))
  58993. {
  58994. AudioDeviceManager::AudioDeviceSetup config;
  58995. setup.manager->getAudioDeviceSetup (config);
  58996. if (setup.useStereoPairs)
  58997. {
  58998. BigInteger bits;
  58999. BigInteger& original = (type == audioInputType ? config.inputChannels
  59000. : config.outputChannels);
  59001. int i;
  59002. for (i = 0; i < 256; i += 2)
  59003. bits.setBit (i / 2, original [i] || original [i + 1]);
  59004. if (type == audioInputType)
  59005. {
  59006. config.useDefaultInputChannels = false;
  59007. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  59008. }
  59009. else
  59010. {
  59011. config.useDefaultOutputChannels = false;
  59012. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  59013. }
  59014. for (i = 0; i < 256; ++i)
  59015. original.setBit (i, bits [i / 2]);
  59016. }
  59017. else
  59018. {
  59019. if (type == audioInputType)
  59020. {
  59021. config.useDefaultInputChannels = false;
  59022. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59023. }
  59024. else
  59025. {
  59026. config.useDefaultOutputChannels = false;
  59027. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59028. }
  59029. }
  59030. String error (setup.manager->setAudioDeviceSetup (config, true));
  59031. if (! error.isEmpty())
  59032. {
  59033. //xxx
  59034. }
  59035. }
  59036. }
  59037. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59038. {
  59039. const int numActive = chans.countNumberOfSetBits();
  59040. if (chans [index])
  59041. {
  59042. if (numActive > minNumber)
  59043. chans.setBit (index, false);
  59044. }
  59045. else
  59046. {
  59047. if (numActive >= maxNumber)
  59048. {
  59049. const int firstActiveChan = chans.findNextSetBit();
  59050. chans.setBit (index > firstActiveChan
  59051. ? firstActiveChan : chans.getHighestBit(),
  59052. false);
  59053. }
  59054. chans.setBit (index, true);
  59055. }
  59056. }
  59057. int getTickX() const
  59058. {
  59059. return getRowHeight() + 5;
  59060. }
  59061. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelSelectorListBox);
  59062. };
  59063. private:
  59064. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59065. JUCE_DECLARE_NON_COPYABLE (AudioDeviceSettingsPanel);
  59066. };
  59067. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59068. const int minInputChannels_,
  59069. const int maxInputChannels_,
  59070. const int minOutputChannels_,
  59071. const int maxOutputChannels_,
  59072. const bool showMidiInputOptions,
  59073. const bool showMidiOutputSelector,
  59074. const bool showChannelsAsStereoPairs_,
  59075. const bool hideAdvancedOptionsWithButton_)
  59076. : deviceManager (deviceManager_),
  59077. deviceTypeDropDown (0),
  59078. deviceTypeDropDownLabel (0),
  59079. minOutputChannels (minOutputChannels_),
  59080. maxOutputChannels (maxOutputChannels_),
  59081. minInputChannels (minInputChannels_),
  59082. maxInputChannels (maxInputChannels_),
  59083. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59084. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59085. {
  59086. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59087. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59088. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59089. {
  59090. deviceTypeDropDown = new ComboBox (String::empty);
  59091. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59092. {
  59093. deviceTypeDropDown
  59094. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59095. i + 1);
  59096. }
  59097. addAndMakeVisible (deviceTypeDropDown);
  59098. deviceTypeDropDown->addListener (this);
  59099. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59100. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59101. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59102. }
  59103. if (showMidiInputOptions)
  59104. {
  59105. addAndMakeVisible (midiInputsList
  59106. = new MidiInputSelectorComponentListBox (deviceManager,
  59107. TRANS("(no midi inputs available)"),
  59108. 0, 0));
  59109. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59110. midiInputsLabel->setJustificationType (Justification::topRight);
  59111. midiInputsLabel->attachToComponent (midiInputsList, true);
  59112. }
  59113. else
  59114. {
  59115. midiInputsList = 0;
  59116. midiInputsLabel = 0;
  59117. }
  59118. if (showMidiOutputSelector)
  59119. {
  59120. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59121. midiOutputSelector->addListener (this);
  59122. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59123. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59124. }
  59125. else
  59126. {
  59127. midiOutputSelector = 0;
  59128. midiOutputLabel = 0;
  59129. }
  59130. deviceManager_.addChangeListener (this);
  59131. changeListenerCallback (0);
  59132. }
  59133. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59134. {
  59135. deviceManager.removeChangeListener (this);
  59136. }
  59137. void AudioDeviceSelectorComponent::resized()
  59138. {
  59139. const int lx = proportionOfWidth (0.35f);
  59140. const int w = proportionOfWidth (0.4f);
  59141. const int h = 24;
  59142. const int space = 6;
  59143. const int dh = h + space;
  59144. int y = 15;
  59145. if (deviceTypeDropDown != 0)
  59146. {
  59147. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59148. y += dh + space * 2;
  59149. }
  59150. if (audioDeviceSettingsComp != 0)
  59151. {
  59152. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59153. y += audioDeviceSettingsComp->getHeight() + space;
  59154. }
  59155. if (midiInputsList != 0)
  59156. {
  59157. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59158. midiInputsList->setBounds (lx, y, w, bh);
  59159. y += bh + space;
  59160. }
  59161. if (midiOutputSelector != 0)
  59162. midiOutputSelector->setBounds (lx, y, w, h);
  59163. }
  59164. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59165. {
  59166. if (child == audioDeviceSettingsComp)
  59167. resized();
  59168. }
  59169. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59170. {
  59171. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59172. if (device != 0 && device->hasControlPanel())
  59173. {
  59174. if (device->showControlPanel())
  59175. deviceManager.restartLastAudioDevice();
  59176. getTopLevelComponent()->toFront (true);
  59177. }
  59178. }
  59179. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59180. {
  59181. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59182. {
  59183. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59184. if (type != 0)
  59185. {
  59186. audioDeviceSettingsComp = 0;
  59187. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59188. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59189. }
  59190. }
  59191. else if (comboBoxThatHasChanged == midiOutputSelector)
  59192. {
  59193. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59194. }
  59195. }
  59196. void AudioDeviceSelectorComponent::changeListenerCallback (ChangeBroadcaster*)
  59197. {
  59198. if (deviceTypeDropDown != 0)
  59199. {
  59200. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59201. }
  59202. if (audioDeviceSettingsComp == 0
  59203. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59204. {
  59205. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59206. audioDeviceSettingsComp = 0;
  59207. AudioIODeviceType* const type
  59208. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59209. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59210. if (type != 0)
  59211. {
  59212. AudioIODeviceType::DeviceSetupDetails details;
  59213. details.manager = &deviceManager;
  59214. details.minNumInputChannels = minInputChannels;
  59215. details.maxNumInputChannels = maxInputChannels;
  59216. details.minNumOutputChannels = minOutputChannels;
  59217. details.maxNumOutputChannels = maxOutputChannels;
  59218. details.useStereoPairs = showChannelsAsStereoPairs;
  59219. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59220. if (audioDeviceSettingsComp != 0)
  59221. {
  59222. addAndMakeVisible (audioDeviceSettingsComp);
  59223. audioDeviceSettingsComp->resized();
  59224. }
  59225. }
  59226. }
  59227. if (midiInputsList != 0)
  59228. {
  59229. midiInputsList->updateContent();
  59230. midiInputsList->repaint();
  59231. }
  59232. if (midiOutputSelector != 0)
  59233. {
  59234. midiOutputSelector->clear();
  59235. const StringArray midiOuts (MidiOutput::getDevices());
  59236. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59237. midiOutputSelector->addSeparator();
  59238. for (int i = 0; i < midiOuts.size(); ++i)
  59239. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59240. int current = -1;
  59241. if (deviceManager.getDefaultMidiOutput() != 0)
  59242. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59243. midiOutputSelector->setSelectedId (current, true);
  59244. }
  59245. resized();
  59246. }
  59247. END_JUCE_NAMESPACE
  59248. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59249. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59250. BEGIN_JUCE_NAMESPACE
  59251. BubbleComponent::BubbleComponent()
  59252. : side (0),
  59253. allowablePlacements (above | below | left | right),
  59254. arrowTipX (0.0f),
  59255. arrowTipY (0.0f)
  59256. {
  59257. setInterceptsMouseClicks (false, false);
  59258. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59259. setComponentEffect (&shadow);
  59260. }
  59261. BubbleComponent::~BubbleComponent()
  59262. {
  59263. }
  59264. void BubbleComponent::paint (Graphics& g)
  59265. {
  59266. int x = content.getX();
  59267. int y = content.getY();
  59268. int w = content.getWidth();
  59269. int h = content.getHeight();
  59270. int cw, ch;
  59271. getContentSize (cw, ch);
  59272. if (side == 3)
  59273. x += w - cw;
  59274. else if (side != 1)
  59275. x += (w - cw) / 2;
  59276. w = cw;
  59277. if (side == 2)
  59278. y += h - ch;
  59279. else if (side != 0)
  59280. y += (h - ch) / 2;
  59281. h = ch;
  59282. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59283. (float) x, (float) y,
  59284. (float) w, (float) h);
  59285. const int cx = x + (w - cw) / 2;
  59286. const int cy = y + (h - ch) / 2;
  59287. const int indent = 3;
  59288. g.setOrigin (cx + indent, cy + indent);
  59289. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59290. paintContent (g, cw - indent * 2, ch - indent * 2);
  59291. }
  59292. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59293. {
  59294. allowablePlacements = newPlacement;
  59295. }
  59296. void BubbleComponent::setPosition (Component* componentToPointTo)
  59297. {
  59298. jassert (componentToPointTo != 0);
  59299. Point<int> pos;
  59300. if (getParentComponent() != 0)
  59301. pos = getParentComponent()->getLocalPoint (componentToPointTo, pos);
  59302. else
  59303. pos = componentToPointTo->localPointToGlobal (pos);
  59304. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59305. }
  59306. void BubbleComponent::setPosition (const int arrowTipX_,
  59307. const int arrowTipY_)
  59308. {
  59309. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59310. }
  59311. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59312. {
  59313. Rectangle<int> availableSpace (getParentComponent() != 0 ? getParentComponent()->getLocalBounds()
  59314. : getParentMonitorArea());
  59315. int x = 0;
  59316. int y = 0;
  59317. int w = 150;
  59318. int h = 30;
  59319. getContentSize (w, h);
  59320. w += 30;
  59321. h += 30;
  59322. const float edgeIndent = 2.0f;
  59323. const int arrowLength = jmin (10, h / 3, w / 3);
  59324. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59325. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59326. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59327. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59328. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59329. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59330. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59331. {
  59332. spaceLeft = spaceRight = 0;
  59333. }
  59334. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59335. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59336. {
  59337. spaceAbove = spaceBelow = 0;
  59338. }
  59339. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59340. {
  59341. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59342. arrowTipX = w * 0.5f;
  59343. content.setSize (w, h - arrowLength);
  59344. if (spaceAbove >= spaceBelow)
  59345. {
  59346. // above
  59347. y = rectangleToPointTo.getY() - h;
  59348. content.setPosition (0, 0);
  59349. arrowTipY = h - edgeIndent;
  59350. side = 2;
  59351. }
  59352. else
  59353. {
  59354. // below
  59355. y = rectangleToPointTo.getBottom();
  59356. content.setPosition (0, arrowLength);
  59357. arrowTipY = edgeIndent;
  59358. side = 0;
  59359. }
  59360. }
  59361. else
  59362. {
  59363. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59364. arrowTipY = h * 0.5f;
  59365. content.setSize (w - arrowLength, h);
  59366. if (spaceLeft > spaceRight)
  59367. {
  59368. // on the left
  59369. x = rectangleToPointTo.getX() - w;
  59370. content.setPosition (0, 0);
  59371. arrowTipX = w - edgeIndent;
  59372. side = 3;
  59373. }
  59374. else
  59375. {
  59376. // on the right
  59377. x = rectangleToPointTo.getRight();
  59378. content.setPosition (arrowLength, 0);
  59379. arrowTipX = edgeIndent;
  59380. side = 1;
  59381. }
  59382. }
  59383. setBounds (x, y, w, h);
  59384. }
  59385. END_JUCE_NAMESPACE
  59386. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59387. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59388. BEGIN_JUCE_NAMESPACE
  59389. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59390. : fadeOutLength (fadeOutLengthMs),
  59391. deleteAfterUse (false)
  59392. {
  59393. }
  59394. BubbleMessageComponent::~BubbleMessageComponent()
  59395. {
  59396. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59397. }
  59398. void BubbleMessageComponent::showAt (int x, int y,
  59399. const String& text,
  59400. const int numMillisecondsBeforeRemoving,
  59401. const bool removeWhenMouseClicked,
  59402. const bool deleteSelfAfterUse)
  59403. {
  59404. textLayout.clear();
  59405. textLayout.setText (text, Font (14.0f));
  59406. textLayout.layout (256, Justification::centredLeft, true);
  59407. setPosition (x, y);
  59408. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59409. }
  59410. void BubbleMessageComponent::showAt (Component* const component,
  59411. const String& text,
  59412. const int numMillisecondsBeforeRemoving,
  59413. const bool removeWhenMouseClicked,
  59414. const bool deleteSelfAfterUse)
  59415. {
  59416. textLayout.clear();
  59417. textLayout.setText (text, Font (14.0f));
  59418. textLayout.layout (256, Justification::centredLeft, true);
  59419. setPosition (component);
  59420. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59421. }
  59422. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59423. const bool removeWhenMouseClicked,
  59424. const bool deleteSelfAfterUse)
  59425. {
  59426. setVisible (true);
  59427. deleteAfterUse = deleteSelfAfterUse;
  59428. if (numMillisecondsBeforeRemoving > 0)
  59429. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59430. else
  59431. expiryTime = 0;
  59432. startTimer (77);
  59433. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59434. if (! (removeWhenMouseClicked && isShowing()))
  59435. mouseClickCounter += 0xfffff;
  59436. repaint();
  59437. }
  59438. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59439. {
  59440. w = textLayout.getWidth() + 16;
  59441. h = textLayout.getHeight() + 16;
  59442. }
  59443. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59444. {
  59445. g.setColour (findColour (TooltipWindow::textColourId));
  59446. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59447. }
  59448. void BubbleMessageComponent::timerCallback()
  59449. {
  59450. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59451. {
  59452. stopTimer();
  59453. setVisible (false);
  59454. if (deleteAfterUse)
  59455. delete this;
  59456. }
  59457. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59458. {
  59459. stopTimer();
  59460. if (deleteAfterUse)
  59461. delete this;
  59462. else
  59463. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59464. }
  59465. }
  59466. END_JUCE_NAMESPACE
  59467. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59468. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59469. BEGIN_JUCE_NAMESPACE
  59470. class ColourComponentSlider : public Slider
  59471. {
  59472. public:
  59473. ColourComponentSlider (const String& name)
  59474. : Slider (name)
  59475. {
  59476. setRange (0.0, 255.0, 1.0);
  59477. }
  59478. const String getTextFromValue (double value)
  59479. {
  59480. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59481. }
  59482. double getValueFromText (const String& text)
  59483. {
  59484. return (double) text.getHexValue32();
  59485. }
  59486. private:
  59487. JUCE_DECLARE_NON_COPYABLE (ColourComponentSlider);
  59488. };
  59489. class ColourSpaceMarker : public Component
  59490. {
  59491. public:
  59492. ColourSpaceMarker()
  59493. {
  59494. setInterceptsMouseClicks (false, false);
  59495. }
  59496. void paint (Graphics& g)
  59497. {
  59498. g.setColour (Colour::greyLevel (0.1f));
  59499. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59500. g.setColour (Colour::greyLevel (0.9f));
  59501. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59502. }
  59503. private:
  59504. JUCE_DECLARE_NON_COPYABLE (ColourSpaceMarker);
  59505. };
  59506. class ColourSelector::ColourSpaceView : public Component
  59507. {
  59508. public:
  59509. ColourSpaceView (ColourSelector& owner_,
  59510. float& h_, float& s_, float& v_,
  59511. const int edgeSize)
  59512. : owner (owner_),
  59513. h (h_), s (s_), v (v_),
  59514. lastHue (0.0f),
  59515. edge (edgeSize)
  59516. {
  59517. addAndMakeVisible (&marker);
  59518. setMouseCursor (MouseCursor::CrosshairCursor);
  59519. }
  59520. void paint (Graphics& g)
  59521. {
  59522. if (colours.isNull())
  59523. {
  59524. const int width = getWidth() / 2;
  59525. const int height = getHeight() / 2;
  59526. colours = Image (Image::RGB, width, height, false);
  59527. Image::BitmapData pixels (colours, true);
  59528. for (int y = 0; y < height; ++y)
  59529. {
  59530. const float val = 1.0f - y / (float) height;
  59531. for (int x = 0; x < width; ++x)
  59532. {
  59533. const float sat = x / (float) width;
  59534. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59535. }
  59536. }
  59537. }
  59538. g.setOpacity (1.0f);
  59539. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59540. 0, 0, colours.getWidth(), colours.getHeight());
  59541. }
  59542. void mouseDown (const MouseEvent& e)
  59543. {
  59544. mouseDrag (e);
  59545. }
  59546. void mouseDrag (const MouseEvent& e)
  59547. {
  59548. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59549. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59550. owner.setSV (sat, val);
  59551. }
  59552. void updateIfNeeded()
  59553. {
  59554. if (lastHue != h)
  59555. {
  59556. lastHue = h;
  59557. colours = Image::null;
  59558. repaint();
  59559. }
  59560. updateMarker();
  59561. }
  59562. void resized()
  59563. {
  59564. colours = Image::null;
  59565. updateMarker();
  59566. }
  59567. private:
  59568. ColourSelector& owner;
  59569. float& h;
  59570. float& s;
  59571. float& v;
  59572. float lastHue;
  59573. ColourSpaceMarker marker;
  59574. const int edge;
  59575. Image colours;
  59576. void updateMarker()
  59577. {
  59578. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59579. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59580. edge * 2, edge * 2);
  59581. }
  59582. JUCE_DECLARE_NON_COPYABLE (ColourSpaceView);
  59583. };
  59584. class HueSelectorMarker : public Component
  59585. {
  59586. public:
  59587. HueSelectorMarker()
  59588. {
  59589. setInterceptsMouseClicks (false, false);
  59590. }
  59591. void paint (Graphics& g)
  59592. {
  59593. Path p;
  59594. p.addTriangle (1.0f, 1.0f,
  59595. getWidth() * 0.3f, getHeight() * 0.5f,
  59596. 1.0f, getHeight() - 1.0f);
  59597. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59598. getWidth() * 0.7f, getHeight() * 0.5f,
  59599. getWidth() - 1.0f, getHeight() - 1.0f);
  59600. g.setColour (Colours::white.withAlpha (0.75f));
  59601. g.fillPath (p);
  59602. g.setColour (Colours::black.withAlpha (0.75f));
  59603. g.strokePath (p, PathStrokeType (1.2f));
  59604. }
  59605. private:
  59606. JUCE_DECLARE_NON_COPYABLE (HueSelectorMarker);
  59607. };
  59608. class ColourSelector::HueSelectorComp : public Component
  59609. {
  59610. public:
  59611. HueSelectorComp (ColourSelector& owner_,
  59612. float& h_, float& s_, float& v_,
  59613. const int edgeSize)
  59614. : owner (owner_),
  59615. h (h_), s (s_), v (v_),
  59616. lastHue (0.0f),
  59617. edge (edgeSize)
  59618. {
  59619. addAndMakeVisible (&marker);
  59620. }
  59621. void paint (Graphics& g)
  59622. {
  59623. const float yScale = 1.0f / (getHeight() - edge * 2);
  59624. const Rectangle<int> clip (g.getClipBounds());
  59625. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59626. {
  59627. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59628. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59629. }
  59630. }
  59631. void resized()
  59632. {
  59633. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59634. getWidth(), edge * 2);
  59635. }
  59636. void mouseDown (const MouseEvent& e)
  59637. {
  59638. mouseDrag (e);
  59639. }
  59640. void mouseDrag (const MouseEvent& e)
  59641. {
  59642. owner.setHue ((e.y - edge) / (float) (getHeight() - edge * 2));
  59643. }
  59644. void updateIfNeeded()
  59645. {
  59646. resized();
  59647. }
  59648. private:
  59649. ColourSelector& owner;
  59650. float& h;
  59651. float& s;
  59652. float& v;
  59653. float lastHue;
  59654. HueSelectorMarker marker;
  59655. const int edge;
  59656. JUCE_DECLARE_NON_COPYABLE (HueSelectorComp);
  59657. };
  59658. class ColourSelector::SwatchComponent : public Component
  59659. {
  59660. public:
  59661. SwatchComponent (ColourSelector& owner_, int index_)
  59662. : owner (owner_), index (index_)
  59663. {
  59664. }
  59665. void paint (Graphics& g)
  59666. {
  59667. const Colour colour (owner.getSwatchColour (index));
  59668. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  59669. Colour (0xffdddddd).overlaidWith (colour),
  59670. Colour (0xffffffff).overlaidWith (colour));
  59671. }
  59672. void mouseDown (const MouseEvent&)
  59673. {
  59674. PopupMenu m;
  59675. m.addItem (1, TRANS("Use this swatch as the current colour"));
  59676. m.addSeparator();
  59677. m.addItem (2, TRANS("Set this swatch to the current colour"));
  59678. const int r = m.showAt (this);
  59679. if (r == 1)
  59680. {
  59681. owner.setCurrentColour (owner.getSwatchColour (index));
  59682. }
  59683. else if (r == 2)
  59684. {
  59685. if (owner.getSwatchColour (index) != owner.getCurrentColour())
  59686. {
  59687. owner.setSwatchColour (index, owner.getCurrentColour());
  59688. repaint();
  59689. }
  59690. }
  59691. }
  59692. private:
  59693. ColourSelector& owner;
  59694. const int index;
  59695. JUCE_DECLARE_NON_COPYABLE (SwatchComponent);
  59696. };
  59697. ColourSelector::ColourSelector (const int flags_,
  59698. const int edgeGap_,
  59699. const int gapAroundColourSpaceComponent)
  59700. : colour (Colours::white),
  59701. flags (flags_),
  59702. edgeGap (edgeGap_)
  59703. {
  59704. // not much point having a selector with no components in it!
  59705. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59706. updateHSV();
  59707. if ((flags & showSliders) != 0)
  59708. {
  59709. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59710. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59711. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59712. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59713. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59714. for (int i = 4; --i >= 0;)
  59715. sliders[i]->addListener (this);
  59716. }
  59717. if ((flags & showColourspace) != 0)
  59718. {
  59719. addAndMakeVisible (colourSpace = new ColourSpaceView (*this, h, s, v, gapAroundColourSpaceComponent));
  59720. addAndMakeVisible (hueSelector = new HueSelectorComp (*this, h, s, v, gapAroundColourSpaceComponent));
  59721. }
  59722. update();
  59723. }
  59724. ColourSelector::~ColourSelector()
  59725. {
  59726. dispatchPendingMessages();
  59727. swatchComponents.clear();
  59728. }
  59729. const Colour ColourSelector::getCurrentColour() const
  59730. {
  59731. return ((flags & showAlphaChannel) != 0) ? colour
  59732. : colour.withAlpha ((uint8) 0xff);
  59733. }
  59734. void ColourSelector::setCurrentColour (const Colour& c)
  59735. {
  59736. if (c != colour)
  59737. {
  59738. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59739. updateHSV();
  59740. update();
  59741. }
  59742. }
  59743. void ColourSelector::setHue (float newH)
  59744. {
  59745. newH = jlimit (0.0f, 1.0f, newH);
  59746. if (h != newH)
  59747. {
  59748. h = newH;
  59749. colour = Colour (h, s, v, colour.getFloatAlpha());
  59750. update();
  59751. }
  59752. }
  59753. void ColourSelector::setSV (float newS, float newV)
  59754. {
  59755. newS = jlimit (0.0f, 1.0f, newS);
  59756. newV = jlimit (0.0f, 1.0f, newV);
  59757. if (s != newS || v != newV)
  59758. {
  59759. s = newS;
  59760. v = newV;
  59761. colour = Colour (h, s, v, colour.getFloatAlpha());
  59762. update();
  59763. }
  59764. }
  59765. void ColourSelector::updateHSV()
  59766. {
  59767. colour.getHSB (h, s, v);
  59768. }
  59769. void ColourSelector::update()
  59770. {
  59771. if (sliders[0] != 0)
  59772. {
  59773. sliders[0]->setValue ((int) colour.getRed());
  59774. sliders[1]->setValue ((int) colour.getGreen());
  59775. sliders[2]->setValue ((int) colour.getBlue());
  59776. sliders[3]->setValue ((int) colour.getAlpha());
  59777. }
  59778. if (colourSpace != 0)
  59779. {
  59780. colourSpace->updateIfNeeded();
  59781. hueSelector->updateIfNeeded();
  59782. }
  59783. if ((flags & showColourAtTop) != 0)
  59784. repaint (previewArea);
  59785. sendChangeMessage();
  59786. }
  59787. void ColourSelector::paint (Graphics& g)
  59788. {
  59789. g.fillAll (findColour (backgroundColourId));
  59790. if ((flags & showColourAtTop) != 0)
  59791. {
  59792. const Colour currentColour (getCurrentColour());
  59793. g.fillCheckerBoard (previewArea, 10, 10,
  59794. Colour (0xffdddddd).overlaidWith (currentColour),
  59795. Colour (0xffffffff).overlaidWith (currentColour));
  59796. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  59797. g.setFont (14.0f, true);
  59798. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  59799. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  59800. Justification::centred, false);
  59801. }
  59802. if ((flags & showSliders) != 0)
  59803. {
  59804. g.setColour (findColour (labelTextColourId));
  59805. g.setFont (11.0f);
  59806. for (int i = 4; --i >= 0;)
  59807. {
  59808. if (sliders[i]->isVisible())
  59809. g.drawText (sliders[i]->getName() + ":",
  59810. 0, sliders[i]->getY(),
  59811. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  59812. Justification::centredRight, false);
  59813. }
  59814. }
  59815. }
  59816. void ColourSelector::resized()
  59817. {
  59818. const int swatchesPerRow = 8;
  59819. const int swatchHeight = 22;
  59820. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  59821. const int numSwatches = getNumSwatches();
  59822. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  59823. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  59824. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  59825. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  59826. int y = topSpace;
  59827. if ((flags & showColourspace) != 0)
  59828. {
  59829. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  59830. colourSpace->setBounds (edgeGap, y,
  59831. getWidth() - hueWidth - edgeGap - 4,
  59832. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  59833. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  59834. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  59835. colourSpace->getHeight());
  59836. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  59837. }
  59838. if ((flags & showSliders) != 0)
  59839. {
  59840. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  59841. for (int i = 0; i < numSliders; ++i)
  59842. {
  59843. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  59844. proportionOfWidth (0.72f), sliderHeight - 2);
  59845. y += sliderHeight;
  59846. }
  59847. }
  59848. if (numSwatches > 0)
  59849. {
  59850. const int startX = 8;
  59851. const int xGap = 4;
  59852. const int yGap = 4;
  59853. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  59854. y += edgeGap;
  59855. if (swatchComponents.size() != numSwatches)
  59856. {
  59857. swatchComponents.clear();
  59858. for (int i = 0; i < numSwatches; ++i)
  59859. {
  59860. SwatchComponent* const sc = new SwatchComponent (*this, i);
  59861. swatchComponents.add (sc);
  59862. addAndMakeVisible (sc);
  59863. }
  59864. }
  59865. int x = startX;
  59866. for (int i = 0; i < swatchComponents.size(); ++i)
  59867. {
  59868. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  59869. sc->setBounds (x + xGap / 2,
  59870. y + yGap / 2,
  59871. swatchWidth - xGap,
  59872. swatchHeight - yGap);
  59873. if (((i + 1) % swatchesPerRow) == 0)
  59874. {
  59875. x = startX;
  59876. y += swatchHeight;
  59877. }
  59878. else
  59879. {
  59880. x += swatchWidth;
  59881. }
  59882. }
  59883. }
  59884. }
  59885. void ColourSelector::sliderValueChanged (Slider*)
  59886. {
  59887. if (sliders[0] != 0)
  59888. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  59889. (uint8) sliders[1]->getValue(),
  59890. (uint8) sliders[2]->getValue(),
  59891. (uint8) sliders[3]->getValue()));
  59892. }
  59893. int ColourSelector::getNumSwatches() const
  59894. {
  59895. return 0;
  59896. }
  59897. const Colour ColourSelector::getSwatchColour (const int) const
  59898. {
  59899. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59900. return Colours::black;
  59901. }
  59902. void ColourSelector::setSwatchColour (const int, const Colour&) const
  59903. {
  59904. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59905. }
  59906. END_JUCE_NAMESPACE
  59907. /*** End of inlined file: juce_ColourSelector.cpp ***/
  59908. /*** Start of inlined file: juce_DropShadower.cpp ***/
  59909. BEGIN_JUCE_NAMESPACE
  59910. class ShadowWindow : public Component
  59911. {
  59912. public:
  59913. ShadowWindow (Component& owner, const int type_, const Image shadowImageSections [12])
  59914. : topLeft (shadowImageSections [type_ * 3]),
  59915. bottomRight (shadowImageSections [type_ * 3 + 1]),
  59916. filler (shadowImageSections [type_ * 3 + 2]),
  59917. type (type_)
  59918. {
  59919. setInterceptsMouseClicks (false, false);
  59920. if (owner.isOnDesktop())
  59921. {
  59922. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  59923. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  59924. | ComponentPeer::windowIsTemporary
  59925. | ComponentPeer::windowIgnoresKeyPresses);
  59926. }
  59927. else if (owner.getParentComponent() != 0)
  59928. {
  59929. owner.getParentComponent()->addChildComponent (this);
  59930. }
  59931. }
  59932. void paint (Graphics& g)
  59933. {
  59934. g.setOpacity (1.0f);
  59935. if (type < 2)
  59936. {
  59937. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  59938. g.drawImage (topLeft,
  59939. 0, 0, topLeft.getWidth(), imH,
  59940. 0, 0, topLeft.getWidth(), imH);
  59941. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  59942. g.drawImage (bottomRight,
  59943. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  59944. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  59945. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59946. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  59947. }
  59948. else
  59949. {
  59950. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  59951. g.drawImage (topLeft,
  59952. 0, 0, imW, topLeft.getHeight(),
  59953. 0, 0, imW, topLeft.getHeight());
  59954. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  59955. g.drawImage (bottomRight,
  59956. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  59957. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  59958. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59959. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  59960. }
  59961. }
  59962. void resized()
  59963. {
  59964. repaint(); // (needed for correct repainting)
  59965. }
  59966. private:
  59967. const Image topLeft, bottomRight, filler;
  59968. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  59969. JUCE_DECLARE_NON_COPYABLE (ShadowWindow);
  59970. };
  59971. DropShadower::DropShadower (const float alpha_,
  59972. const int xOffset_,
  59973. const int yOffset_,
  59974. const float blurRadius_)
  59975. : owner (0),
  59976. xOffset (xOffset_),
  59977. yOffset (yOffset_),
  59978. alpha (alpha_),
  59979. blurRadius (blurRadius_),
  59980. reentrant (false)
  59981. {
  59982. }
  59983. DropShadower::~DropShadower()
  59984. {
  59985. if (owner != 0)
  59986. owner->removeComponentListener (this);
  59987. reentrant = true;
  59988. shadowWindows.clear();
  59989. }
  59990. void DropShadower::setOwner (Component* componentToFollow)
  59991. {
  59992. if (componentToFollow != owner)
  59993. {
  59994. if (owner != 0)
  59995. owner->removeComponentListener (this);
  59996. // (the component can't be null)
  59997. jassert (componentToFollow != 0);
  59998. owner = componentToFollow;
  59999. jassert (owner != 0);
  60000. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  60001. owner->addComponentListener (this);
  60002. updateShadows();
  60003. }
  60004. }
  60005. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  60006. {
  60007. updateShadows();
  60008. }
  60009. void DropShadower::componentBroughtToFront (Component&)
  60010. {
  60011. bringShadowWindowsToFront();
  60012. }
  60013. void DropShadower::componentParentHierarchyChanged (Component&)
  60014. {
  60015. shadowWindows.clear();
  60016. updateShadows();
  60017. }
  60018. void DropShadower::componentVisibilityChanged (Component&)
  60019. {
  60020. updateShadows();
  60021. }
  60022. void DropShadower::updateShadows()
  60023. {
  60024. if (reentrant || owner == 0)
  60025. return;
  60026. ComponentPeer* const peer = owner->getPeer();
  60027. const bool isOwnerVisible = owner->isVisible() && (peer == 0 || ! peer->isMinimised());
  60028. const bool createShadowWindows = shadowWindows.size() == 0
  60029. && owner->getWidth() > 0
  60030. && owner->getHeight() > 0
  60031. && isOwnerVisible
  60032. && (Desktop::canUseSemiTransparentWindows()
  60033. || owner->getParentComponent() != 0);
  60034. {
  60035. const ScopedValueSetter<bool> setter (reentrant, true, false);
  60036. const int shadowEdge = jmax (xOffset, yOffset) + (int) blurRadius;
  60037. if (createShadowWindows)
  60038. {
  60039. // keep a cached version of the image to save doing the gaussian too often
  60040. String imageId;
  60041. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60042. const int hash = imageId.hashCode();
  60043. Image bigIm (ImageCache::getFromHashCode (hash));
  60044. if (bigIm.isNull())
  60045. {
  60046. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60047. Graphics bigG (bigIm);
  60048. bigG.setColour (Colours::black.withAlpha (alpha));
  60049. bigG.fillRect (shadowEdge + xOffset,
  60050. shadowEdge + yOffset,
  60051. bigIm.getWidth() - (shadowEdge * 2),
  60052. bigIm.getHeight() - (shadowEdge * 2));
  60053. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60054. blurKernel.createGaussianBlur (blurRadius);
  60055. blurKernel.applyToImage (bigIm, bigIm,
  60056. Rectangle<int> (xOffset, yOffset,
  60057. bigIm.getWidth(), bigIm.getHeight()));
  60058. ImageCache::addImageToCache (bigIm, hash);
  60059. }
  60060. const int iw = bigIm.getWidth();
  60061. const int ih = bigIm.getHeight();
  60062. const int shadowEdge2 = shadowEdge * 2;
  60063. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60064. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60065. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60066. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60067. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60068. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60069. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60070. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60071. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60072. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60073. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60074. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60075. for (int i = 0; i < 4; ++i)
  60076. shadowWindows.add (new ShadowWindow (*owner, i, shadowImageSections));
  60077. }
  60078. if (shadowWindows.size() >= 4)
  60079. {
  60080. for (int i = shadowWindows.size(); --i >= 0;)
  60081. {
  60082. shadowWindows.getUnchecked(i)->setAlwaysOnTop (owner->isAlwaysOnTop());
  60083. shadowWindows.getUnchecked(i)->setVisible (isOwnerVisible);
  60084. }
  60085. const int x = owner->getX();
  60086. const int y = owner->getY() - shadowEdge;
  60087. const int w = owner->getWidth();
  60088. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60089. shadowWindows.getUnchecked(0)->setBounds (x - shadowEdge, y, shadowEdge, h);
  60090. shadowWindows.getUnchecked(1)->setBounds (x + w, y, shadowEdge, h);
  60091. shadowWindows.getUnchecked(2)->setBounds (x, y, w, shadowEdge);
  60092. shadowWindows.getUnchecked(3)->setBounds (x, owner->getBottom(), w, shadowEdge);
  60093. }
  60094. }
  60095. if (createShadowWindows)
  60096. bringShadowWindowsToFront();
  60097. }
  60098. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60099. const int sx, const int sy)
  60100. {
  60101. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60102. Graphics g (shadowImageSections[num]);
  60103. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60104. }
  60105. void DropShadower::bringShadowWindowsToFront()
  60106. {
  60107. if (! reentrant)
  60108. {
  60109. updateShadows();
  60110. const ScopedValueSetter<bool> setter (reentrant, true, false);
  60111. for (int i = shadowWindows.size(); --i >= 0;)
  60112. shadowWindows.getUnchecked(i)->toBehind (owner);
  60113. }
  60114. }
  60115. END_JUCE_NAMESPACE
  60116. /*** End of inlined file: juce_DropShadower.cpp ***/
  60117. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60118. BEGIN_JUCE_NAMESPACE
  60119. class MidiKeyboardUpDownButton : public Button
  60120. {
  60121. public:
  60122. MidiKeyboardUpDownButton (MidiKeyboardComponent& owner_, const int delta_)
  60123. : Button (String::empty),
  60124. owner (owner_),
  60125. delta (delta_)
  60126. {
  60127. setOpaque (true);
  60128. }
  60129. void clicked()
  60130. {
  60131. int note = owner.getLowestVisibleKey();
  60132. if (delta < 0)
  60133. note = (note - 1) / 12;
  60134. else
  60135. note = note / 12 + 1;
  60136. owner.setLowestVisibleKey (note * 12);
  60137. }
  60138. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  60139. {
  60140. owner.drawUpDownButton (g, getWidth(), getHeight(),
  60141. isMouseOverButton, isButtonDown,
  60142. delta > 0);
  60143. }
  60144. private:
  60145. MidiKeyboardComponent& owner;
  60146. const int delta;
  60147. JUCE_DECLARE_NON_COPYABLE (MidiKeyboardUpDownButton);
  60148. };
  60149. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60150. const Orientation orientation_)
  60151. : state (state_),
  60152. xOffset (0),
  60153. blackNoteLength (1),
  60154. keyWidth (16.0f),
  60155. orientation (orientation_),
  60156. midiChannel (1),
  60157. midiInChannelMask (0xffff),
  60158. velocity (1.0f),
  60159. noteUnderMouse (-1),
  60160. mouseDownNote (-1),
  60161. rangeStart (0),
  60162. rangeEnd (127),
  60163. firstKey (12 * 4),
  60164. canScroll (true),
  60165. mouseDragging (false),
  60166. useMousePositionForVelocity (true),
  60167. keyMappingOctave (6),
  60168. octaveNumForMiddleC (3)
  60169. {
  60170. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (*this, -1));
  60171. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (*this, 1));
  60172. // initialise with a default set of querty key-mappings..
  60173. const char* const keymap = "awsedftgyhujkolp;";
  60174. for (int i = String (keymap).length(); --i >= 0;)
  60175. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60176. setOpaque (true);
  60177. setWantsKeyboardFocus (true);
  60178. state.addListener (this);
  60179. }
  60180. MidiKeyboardComponent::~MidiKeyboardComponent()
  60181. {
  60182. state.removeListener (this);
  60183. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60184. }
  60185. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60186. {
  60187. keyWidth = widthInPixels;
  60188. resized();
  60189. }
  60190. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60191. {
  60192. if (orientation != newOrientation)
  60193. {
  60194. orientation = newOrientation;
  60195. resized();
  60196. }
  60197. }
  60198. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60199. const int highestNote)
  60200. {
  60201. jassert (lowestNote >= 0 && lowestNote <= 127);
  60202. jassert (highestNote >= 0 && highestNote <= 127);
  60203. jassert (lowestNote <= highestNote);
  60204. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60205. {
  60206. rangeStart = jlimit (0, 127, lowestNote);
  60207. rangeEnd = jlimit (0, 127, highestNote);
  60208. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60209. resized();
  60210. }
  60211. }
  60212. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60213. {
  60214. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60215. if (noteNumber != firstKey)
  60216. {
  60217. firstKey = noteNumber;
  60218. sendChangeMessage();
  60219. resized();
  60220. }
  60221. }
  60222. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60223. {
  60224. if (canScroll != canScroll_)
  60225. {
  60226. canScroll = canScroll_;
  60227. resized();
  60228. }
  60229. }
  60230. void MidiKeyboardComponent::colourChanged()
  60231. {
  60232. repaint();
  60233. }
  60234. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60235. {
  60236. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60237. if (midiChannel != midiChannelNumber)
  60238. {
  60239. resetAnyKeysInUse();
  60240. midiChannel = jlimit (1, 16, midiChannelNumber);
  60241. }
  60242. }
  60243. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60244. {
  60245. midiInChannelMask = midiChannelMask;
  60246. triggerAsyncUpdate();
  60247. }
  60248. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60249. {
  60250. velocity = jlimit (0.0f, 1.0f, velocity_);
  60251. useMousePositionForVelocity = useMousePositionForVelocity_;
  60252. }
  60253. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60254. {
  60255. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60256. static const float blackNoteWidth = 0.7f;
  60257. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60258. 1.0f, 2 - blackNoteWidth * 0.4f,
  60259. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60260. 4.0f, 5 - blackNoteWidth * 0.5f,
  60261. 5.0f, 6 - blackNoteWidth * 0.3f,
  60262. 6.0f };
  60263. static const float widths[] = { 1.0f, blackNoteWidth,
  60264. 1.0f, blackNoteWidth,
  60265. 1.0f, 1.0f, blackNoteWidth,
  60266. 1.0f, blackNoteWidth,
  60267. 1.0f, blackNoteWidth,
  60268. 1.0f };
  60269. const int octave = midiNoteNumber / 12;
  60270. const int note = midiNoteNumber % 12;
  60271. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60272. w = roundToInt (widths [note] * keyWidth_);
  60273. }
  60274. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60275. {
  60276. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60277. int rx, rw;
  60278. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60279. x -= xOffset + rx;
  60280. }
  60281. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60282. {
  60283. int x, y;
  60284. getKeyPos (midiNoteNumber, x, y);
  60285. return x;
  60286. }
  60287. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60288. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  60289. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60290. {
  60291. if (! reallyContains (pos, false))
  60292. return -1;
  60293. Point<int> p (pos);
  60294. if (orientation != horizontalKeyboard)
  60295. {
  60296. p = Point<int> (p.getY(), p.getX());
  60297. if (orientation == verticalKeyboardFacingLeft)
  60298. p = Point<int> (p.getX(), getWidth() - p.getY());
  60299. else
  60300. p = Point<int> (getHeight() - p.getX(), p.getY());
  60301. }
  60302. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60303. }
  60304. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60305. {
  60306. if (pos.getY() < blackNoteLength)
  60307. {
  60308. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60309. {
  60310. for (int i = 0; i < 5; ++i)
  60311. {
  60312. const int note = octaveStart + blackNotes [i];
  60313. if (note >= rangeStart && note <= rangeEnd)
  60314. {
  60315. int kx, kw;
  60316. getKeyPos (note, kx, kw);
  60317. kx += xOffset;
  60318. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60319. {
  60320. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60321. return note;
  60322. }
  60323. }
  60324. }
  60325. }
  60326. }
  60327. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60328. {
  60329. for (int i = 0; i < 7; ++i)
  60330. {
  60331. const int note = octaveStart + whiteNotes [i];
  60332. if (note >= rangeStart && note <= rangeEnd)
  60333. {
  60334. int kx, kw;
  60335. getKeyPos (note, kx, kw);
  60336. kx += xOffset;
  60337. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60338. {
  60339. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60340. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60341. return note;
  60342. }
  60343. }
  60344. }
  60345. }
  60346. mousePositionVelocity = 0;
  60347. return -1;
  60348. }
  60349. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60350. {
  60351. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60352. {
  60353. int x, w;
  60354. getKeyPos (noteNum, x, w);
  60355. if (orientation == horizontalKeyboard)
  60356. repaint (x, 0, w, getHeight());
  60357. else if (orientation == verticalKeyboardFacingLeft)
  60358. repaint (0, x, getWidth(), w);
  60359. else if (orientation == verticalKeyboardFacingRight)
  60360. repaint (0, getHeight() - x - w, getWidth(), w);
  60361. }
  60362. }
  60363. void MidiKeyboardComponent::paint (Graphics& g)
  60364. {
  60365. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60366. const Colour lineColour (findColour (keySeparatorLineColourId));
  60367. const Colour textColour (findColour (textLabelColourId));
  60368. int x, w, octave;
  60369. for (octave = 0; octave < 128; octave += 12)
  60370. {
  60371. for (int white = 0; white < 7; ++white)
  60372. {
  60373. const int noteNum = octave + whiteNotes [white];
  60374. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60375. {
  60376. getKeyPos (noteNum, x, w);
  60377. if (orientation == horizontalKeyboard)
  60378. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60379. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60380. noteUnderMouse == noteNum,
  60381. lineColour, textColour);
  60382. else if (orientation == verticalKeyboardFacingLeft)
  60383. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60384. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60385. noteUnderMouse == noteNum,
  60386. lineColour, textColour);
  60387. else if (orientation == verticalKeyboardFacingRight)
  60388. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60389. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60390. noteUnderMouse == noteNum,
  60391. lineColour, textColour);
  60392. }
  60393. }
  60394. }
  60395. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60396. if (orientation == verticalKeyboardFacingLeft)
  60397. {
  60398. x1 = getWidth() - 1.0f;
  60399. x2 = getWidth() - 5.0f;
  60400. }
  60401. else if (orientation == verticalKeyboardFacingRight)
  60402. x2 = 5.0f;
  60403. else
  60404. y2 = 5.0f;
  60405. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60406. Colours::transparentBlack, x2, y2, false));
  60407. getKeyPos (rangeEnd, x, w);
  60408. x += w;
  60409. if (orientation == verticalKeyboardFacingLeft)
  60410. g.fillRect (getWidth() - 5, 0, 5, x);
  60411. else if (orientation == verticalKeyboardFacingRight)
  60412. g.fillRect (0, 0, 5, x);
  60413. else
  60414. g.fillRect (0, 0, x, 5);
  60415. g.setColour (lineColour);
  60416. if (orientation == verticalKeyboardFacingLeft)
  60417. g.fillRect (0, 0, 1, x);
  60418. else if (orientation == verticalKeyboardFacingRight)
  60419. g.fillRect (getWidth() - 1, 0, 1, x);
  60420. else
  60421. g.fillRect (0, getHeight() - 1, x, 1);
  60422. const Colour blackNoteColour (findColour (blackNoteColourId));
  60423. for (octave = 0; octave < 128; octave += 12)
  60424. {
  60425. for (int black = 0; black < 5; ++black)
  60426. {
  60427. const int noteNum = octave + blackNotes [black];
  60428. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60429. {
  60430. getKeyPos (noteNum, x, w);
  60431. if (orientation == horizontalKeyboard)
  60432. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60433. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60434. noteUnderMouse == noteNum,
  60435. blackNoteColour);
  60436. else if (orientation == verticalKeyboardFacingLeft)
  60437. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60438. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60439. noteUnderMouse == noteNum,
  60440. blackNoteColour);
  60441. else if (orientation == verticalKeyboardFacingRight)
  60442. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60443. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60444. noteUnderMouse == noteNum,
  60445. blackNoteColour);
  60446. }
  60447. }
  60448. }
  60449. }
  60450. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60451. Graphics& g, int x, int y, int w, int h,
  60452. bool isDown, bool isOver,
  60453. const Colour& lineColour,
  60454. const Colour& textColour)
  60455. {
  60456. Colour c (Colours::transparentWhite);
  60457. if (isDown)
  60458. c = findColour (keyDownOverlayColourId);
  60459. if (isOver)
  60460. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60461. g.setColour (c);
  60462. g.fillRect (x, y, w, h);
  60463. const String text (getWhiteNoteText (midiNoteNumber));
  60464. if (! text.isEmpty())
  60465. {
  60466. g.setColour (textColour);
  60467. Font f (jmin (12.0f, keyWidth * 0.9f));
  60468. f.setHorizontalScale (0.8f);
  60469. g.setFont (f);
  60470. Justification justification (Justification::centredBottom);
  60471. if (orientation == verticalKeyboardFacingLeft)
  60472. justification = Justification::centredLeft;
  60473. else if (orientation == verticalKeyboardFacingRight)
  60474. justification = Justification::centredRight;
  60475. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60476. }
  60477. g.setColour (lineColour);
  60478. if (orientation == horizontalKeyboard)
  60479. g.fillRect (x, y, 1, h);
  60480. else if (orientation == verticalKeyboardFacingLeft)
  60481. g.fillRect (x, y, w, 1);
  60482. else if (orientation == verticalKeyboardFacingRight)
  60483. g.fillRect (x, y + h - 1, w, 1);
  60484. if (midiNoteNumber == rangeEnd)
  60485. {
  60486. if (orientation == horizontalKeyboard)
  60487. g.fillRect (x + w, y, 1, h);
  60488. else if (orientation == verticalKeyboardFacingLeft)
  60489. g.fillRect (x, y + h, w, 1);
  60490. else if (orientation == verticalKeyboardFacingRight)
  60491. g.fillRect (x, y - 1, w, 1);
  60492. }
  60493. }
  60494. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60495. Graphics& g, int x, int y, int w, int h,
  60496. bool isDown, bool isOver,
  60497. const Colour& noteFillColour)
  60498. {
  60499. Colour c (noteFillColour);
  60500. if (isDown)
  60501. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60502. if (isOver)
  60503. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60504. g.setColour (c);
  60505. g.fillRect (x, y, w, h);
  60506. if (isDown)
  60507. {
  60508. g.setColour (noteFillColour);
  60509. g.drawRect (x, y, w, h);
  60510. }
  60511. else
  60512. {
  60513. const int xIndent = jmax (1, jmin (w, h) / 8);
  60514. g.setColour (c.brighter());
  60515. if (orientation == horizontalKeyboard)
  60516. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60517. else if (orientation == verticalKeyboardFacingLeft)
  60518. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60519. else if (orientation == verticalKeyboardFacingRight)
  60520. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60521. }
  60522. }
  60523. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60524. {
  60525. octaveNumForMiddleC = octaveNumForMiddleC_;
  60526. repaint();
  60527. }
  60528. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60529. {
  60530. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60531. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60532. return String::empty;
  60533. }
  60534. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60535. const bool isMouseOver_,
  60536. const bool isButtonDown,
  60537. const bool movesOctavesUp)
  60538. {
  60539. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60540. float angle;
  60541. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60542. angle = movesOctavesUp ? 0.0f : 0.5f;
  60543. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60544. angle = movesOctavesUp ? 0.25f : 0.75f;
  60545. else
  60546. angle = movesOctavesUp ? 0.75f : 0.25f;
  60547. Path path;
  60548. path.lineTo (0.0f, 1.0f);
  60549. path.lineTo (1.0f, 0.5f);
  60550. path.closeSubPath();
  60551. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60552. g.setColour (findColour (upDownButtonArrowColourId)
  60553. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  60554. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60555. w - 2.0f,
  60556. h - 2.0f,
  60557. true));
  60558. }
  60559. void MidiKeyboardComponent::resized()
  60560. {
  60561. int w = getWidth();
  60562. int h = getHeight();
  60563. if (w > 0 && h > 0)
  60564. {
  60565. if (orientation != horizontalKeyboard)
  60566. swapVariables (w, h);
  60567. blackNoteLength = roundToInt (h * 0.7f);
  60568. int kx2, kw2;
  60569. getKeyPos (rangeEnd, kx2, kw2);
  60570. kx2 += kw2;
  60571. if (firstKey != rangeStart)
  60572. {
  60573. int kx1, kw1;
  60574. getKeyPos (rangeStart, kx1, kw1);
  60575. if (kx2 - kx1 <= w)
  60576. {
  60577. firstKey = rangeStart;
  60578. sendChangeMessage();
  60579. repaint();
  60580. }
  60581. }
  60582. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60583. scrollDown->setVisible (showScrollButtons);
  60584. scrollUp->setVisible (showScrollButtons);
  60585. xOffset = 0;
  60586. if (showScrollButtons)
  60587. {
  60588. const int scrollButtonW = jmin (12, w / 2);
  60589. if (orientation == horizontalKeyboard)
  60590. {
  60591. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60592. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60593. }
  60594. else if (orientation == verticalKeyboardFacingLeft)
  60595. {
  60596. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  60597. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60598. }
  60599. else if (orientation == verticalKeyboardFacingRight)
  60600. {
  60601. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60602. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  60603. }
  60604. int endOfLastKey, kw;
  60605. getKeyPos (rangeEnd, endOfLastKey, kw);
  60606. endOfLastKey += kw;
  60607. float mousePositionVelocity;
  60608. const int spaceAvailable = w - scrollButtonW * 2;
  60609. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  60610. if (lastStartKey >= 0 && firstKey > lastStartKey)
  60611. {
  60612. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  60613. sendChangeMessage();
  60614. }
  60615. int newOffset = 0;
  60616. getKeyPos (firstKey, newOffset, kw);
  60617. xOffset = newOffset - scrollButtonW;
  60618. }
  60619. else
  60620. {
  60621. firstKey = rangeStart;
  60622. }
  60623. timerCallback();
  60624. repaint();
  60625. }
  60626. }
  60627. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  60628. {
  60629. triggerAsyncUpdate();
  60630. }
  60631. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  60632. {
  60633. triggerAsyncUpdate();
  60634. }
  60635. void MidiKeyboardComponent::handleAsyncUpdate()
  60636. {
  60637. for (int i = rangeStart; i <= rangeEnd; ++i)
  60638. {
  60639. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  60640. {
  60641. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  60642. repaintNote (i);
  60643. }
  60644. }
  60645. }
  60646. void MidiKeyboardComponent::resetAnyKeysInUse()
  60647. {
  60648. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  60649. {
  60650. state.allNotesOff (midiChannel);
  60651. keysPressed.clear();
  60652. mouseDownNote = -1;
  60653. }
  60654. }
  60655. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  60656. {
  60657. float mousePositionVelocity = 0.0f;
  60658. const int newNote = (mouseDragging || isMouseOver())
  60659. ? xyToNote (pos, mousePositionVelocity) : -1;
  60660. if (noteUnderMouse != newNote)
  60661. {
  60662. if (mouseDownNote >= 0)
  60663. {
  60664. state.noteOff (midiChannel, mouseDownNote);
  60665. mouseDownNote = -1;
  60666. }
  60667. if (mouseDragging && newNote >= 0)
  60668. {
  60669. if (! useMousePositionForVelocity)
  60670. mousePositionVelocity = 1.0f;
  60671. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  60672. mouseDownNote = newNote;
  60673. }
  60674. repaintNote (noteUnderMouse);
  60675. noteUnderMouse = newNote;
  60676. repaintNote (noteUnderMouse);
  60677. }
  60678. else if (mouseDownNote >= 0 && ! mouseDragging)
  60679. {
  60680. state.noteOff (midiChannel, mouseDownNote);
  60681. mouseDownNote = -1;
  60682. }
  60683. }
  60684. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  60685. {
  60686. updateNoteUnderMouse (e.getPosition());
  60687. stopTimer();
  60688. }
  60689. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  60690. {
  60691. float mousePositionVelocity;
  60692. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60693. if (newNote >= 0)
  60694. mouseDraggedToKey (newNote, e);
  60695. updateNoteUnderMouse (e.getPosition());
  60696. }
  60697. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  60698. {
  60699. return true;
  60700. }
  60701. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  60702. {
  60703. }
  60704. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  60705. {
  60706. float mousePositionVelocity;
  60707. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60708. mouseDragging = false;
  60709. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  60710. {
  60711. repaintNote (noteUnderMouse);
  60712. noteUnderMouse = -1;
  60713. mouseDragging = true;
  60714. updateNoteUnderMouse (e.getPosition());
  60715. startTimer (500);
  60716. }
  60717. }
  60718. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  60719. {
  60720. mouseDragging = false;
  60721. updateNoteUnderMouse (e.getPosition());
  60722. stopTimer();
  60723. }
  60724. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  60725. {
  60726. updateNoteUnderMouse (e.getPosition());
  60727. }
  60728. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  60729. {
  60730. updateNoteUnderMouse (e.getPosition());
  60731. }
  60732. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  60733. {
  60734. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  60735. }
  60736. void MidiKeyboardComponent::timerCallback()
  60737. {
  60738. updateNoteUnderMouse (getMouseXYRelative());
  60739. }
  60740. void MidiKeyboardComponent::clearKeyMappings()
  60741. {
  60742. resetAnyKeysInUse();
  60743. keyPressNotes.clear();
  60744. keyPresses.clear();
  60745. }
  60746. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  60747. const int midiNoteOffsetFromC)
  60748. {
  60749. removeKeyPressForNote (midiNoteOffsetFromC);
  60750. keyPressNotes.add (midiNoteOffsetFromC);
  60751. keyPresses.add (key);
  60752. }
  60753. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  60754. {
  60755. for (int i = keyPressNotes.size(); --i >= 0;)
  60756. {
  60757. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  60758. {
  60759. keyPressNotes.remove (i);
  60760. keyPresses.remove (i);
  60761. }
  60762. }
  60763. }
  60764. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  60765. {
  60766. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  60767. keyMappingOctave = newOctaveNumber;
  60768. }
  60769. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  60770. {
  60771. bool keyPressUsed = false;
  60772. for (int i = keyPresses.size(); --i >= 0;)
  60773. {
  60774. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  60775. if (keyPresses.getReference(i).isCurrentlyDown())
  60776. {
  60777. if (! keysPressed [note])
  60778. {
  60779. keysPressed.setBit (note);
  60780. state.noteOn (midiChannel, note, velocity);
  60781. keyPressUsed = true;
  60782. }
  60783. }
  60784. else
  60785. {
  60786. if (keysPressed [note])
  60787. {
  60788. keysPressed.clearBit (note);
  60789. state.noteOff (midiChannel, note);
  60790. keyPressUsed = true;
  60791. }
  60792. }
  60793. }
  60794. return keyPressUsed;
  60795. }
  60796. void MidiKeyboardComponent::focusLost (FocusChangeType)
  60797. {
  60798. resetAnyKeysInUse();
  60799. }
  60800. END_JUCE_NAMESPACE
  60801. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60802. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  60803. #if JUCE_OPENGL
  60804. BEGIN_JUCE_NAMESPACE
  60805. extern void juce_glViewport (const int w, const int h);
  60806. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  60807. const int alphaBits_,
  60808. const int depthBufferBits_,
  60809. const int stencilBufferBits_)
  60810. : redBits (bitsPerRGBComponent),
  60811. greenBits (bitsPerRGBComponent),
  60812. blueBits (bitsPerRGBComponent),
  60813. alphaBits (alphaBits_),
  60814. depthBufferBits (depthBufferBits_),
  60815. stencilBufferBits (stencilBufferBits_),
  60816. accumulationBufferRedBits (0),
  60817. accumulationBufferGreenBits (0),
  60818. accumulationBufferBlueBits (0),
  60819. accumulationBufferAlphaBits (0),
  60820. fullSceneAntiAliasingNumSamples (0)
  60821. {
  60822. }
  60823. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  60824. : redBits (other.redBits),
  60825. greenBits (other.greenBits),
  60826. blueBits (other.blueBits),
  60827. alphaBits (other.alphaBits),
  60828. depthBufferBits (other.depthBufferBits),
  60829. stencilBufferBits (other.stencilBufferBits),
  60830. accumulationBufferRedBits (other.accumulationBufferRedBits),
  60831. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  60832. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  60833. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  60834. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  60835. {
  60836. }
  60837. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  60838. {
  60839. redBits = other.redBits;
  60840. greenBits = other.greenBits;
  60841. blueBits = other.blueBits;
  60842. alphaBits = other.alphaBits;
  60843. depthBufferBits = other.depthBufferBits;
  60844. stencilBufferBits = other.stencilBufferBits;
  60845. accumulationBufferRedBits = other.accumulationBufferRedBits;
  60846. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  60847. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  60848. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  60849. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  60850. return *this;
  60851. }
  60852. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  60853. {
  60854. return redBits == other.redBits
  60855. && greenBits == other.greenBits
  60856. && blueBits == other.blueBits
  60857. && alphaBits == other.alphaBits
  60858. && depthBufferBits == other.depthBufferBits
  60859. && stencilBufferBits == other.stencilBufferBits
  60860. && accumulationBufferRedBits == other.accumulationBufferRedBits
  60861. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  60862. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  60863. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  60864. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  60865. }
  60866. static Array<OpenGLContext*> knownContexts;
  60867. OpenGLContext::OpenGLContext() throw()
  60868. {
  60869. knownContexts.add (this);
  60870. }
  60871. OpenGLContext::~OpenGLContext()
  60872. {
  60873. knownContexts.removeValue (this);
  60874. }
  60875. OpenGLContext* OpenGLContext::getCurrentContext()
  60876. {
  60877. for (int i = knownContexts.size(); --i >= 0;)
  60878. {
  60879. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  60880. if (oglc->isActive())
  60881. return oglc;
  60882. }
  60883. return 0;
  60884. }
  60885. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  60886. {
  60887. public:
  60888. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  60889. : ComponentMovementWatcher (owner_),
  60890. owner (owner_)
  60891. {
  60892. }
  60893. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  60894. {
  60895. owner->updateContextPosition();
  60896. }
  60897. void componentPeerChanged()
  60898. {
  60899. const ScopedLock sl (owner->getContextLock());
  60900. owner->deleteContext();
  60901. }
  60902. void componentVisibilityChanged()
  60903. {
  60904. if (! owner->isShowing())
  60905. {
  60906. const ScopedLock sl (owner->getContextLock());
  60907. owner->deleteContext();
  60908. }
  60909. }
  60910. private:
  60911. OpenGLComponent* const owner;
  60912. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLComponentWatcher);
  60913. };
  60914. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  60915. : type (type_),
  60916. contextToShareListsWith (0),
  60917. needToUpdateViewport (true)
  60918. {
  60919. setOpaque (true);
  60920. componentWatcher = new OpenGLComponentWatcher (this);
  60921. }
  60922. OpenGLComponent::~OpenGLComponent()
  60923. {
  60924. deleteContext();
  60925. componentWatcher = 0;
  60926. }
  60927. void OpenGLComponent::deleteContext()
  60928. {
  60929. const ScopedLock sl (contextLock);
  60930. context = 0;
  60931. }
  60932. void OpenGLComponent::updateContextPosition()
  60933. {
  60934. needToUpdateViewport = true;
  60935. if (getWidth() > 0 && getHeight() > 0)
  60936. {
  60937. Component* const topComp = getTopLevelComponent();
  60938. if (topComp->getPeer() != 0)
  60939. {
  60940. const ScopedLock sl (contextLock);
  60941. if (context != 0)
  60942. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  60943. getScreenY() - topComp->getScreenY(),
  60944. getWidth(),
  60945. getHeight(),
  60946. topComp->getHeight());
  60947. }
  60948. }
  60949. }
  60950. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  60951. {
  60952. OpenGLPixelFormat pf;
  60953. const ScopedLock sl (contextLock);
  60954. if (context != 0)
  60955. pf = context->getPixelFormat();
  60956. return pf;
  60957. }
  60958. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  60959. {
  60960. if (! (preferredPixelFormat == formatToUse))
  60961. {
  60962. const ScopedLock sl (contextLock);
  60963. deleteContext();
  60964. preferredPixelFormat = formatToUse;
  60965. }
  60966. }
  60967. void OpenGLComponent::shareWith (OpenGLContext* c)
  60968. {
  60969. if (contextToShareListsWith != c)
  60970. {
  60971. const ScopedLock sl (contextLock);
  60972. deleteContext();
  60973. contextToShareListsWith = c;
  60974. }
  60975. }
  60976. bool OpenGLComponent::makeCurrentContextActive()
  60977. {
  60978. if (context == 0)
  60979. {
  60980. const ScopedLock sl (contextLock);
  60981. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  60982. {
  60983. context = createContext();
  60984. if (context != 0)
  60985. {
  60986. updateContextPosition();
  60987. if (context->makeActive())
  60988. newOpenGLContextCreated();
  60989. }
  60990. }
  60991. }
  60992. return context != 0 && context->makeActive();
  60993. }
  60994. void OpenGLComponent::makeCurrentContextInactive()
  60995. {
  60996. if (context != 0)
  60997. context->makeInactive();
  60998. }
  60999. bool OpenGLComponent::isActiveContext() const throw()
  61000. {
  61001. return context != 0 && context->isActive();
  61002. }
  61003. void OpenGLComponent::swapBuffers()
  61004. {
  61005. if (context != 0)
  61006. context->swapBuffers();
  61007. }
  61008. void OpenGLComponent::paint (Graphics&)
  61009. {
  61010. if (renderAndSwapBuffers())
  61011. {
  61012. ComponentPeer* const peer = getPeer();
  61013. if (peer != 0)
  61014. {
  61015. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  61016. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  61017. }
  61018. }
  61019. }
  61020. bool OpenGLComponent::renderAndSwapBuffers()
  61021. {
  61022. const ScopedLock sl (contextLock);
  61023. if (! makeCurrentContextActive())
  61024. return false;
  61025. if (needToUpdateViewport)
  61026. {
  61027. needToUpdateViewport = false;
  61028. juce_glViewport (getWidth(), getHeight());
  61029. }
  61030. renderOpenGL();
  61031. swapBuffers();
  61032. return true;
  61033. }
  61034. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61035. {
  61036. Component::internalRepaint (x, y, w, h);
  61037. if (context != 0)
  61038. context->repaint();
  61039. }
  61040. END_JUCE_NAMESPACE
  61041. #endif
  61042. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61043. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61044. BEGIN_JUCE_NAMESPACE
  61045. PreferencesPanel::PreferencesPanel()
  61046. : buttonSize (70)
  61047. {
  61048. }
  61049. PreferencesPanel::~PreferencesPanel()
  61050. {
  61051. }
  61052. void PreferencesPanel::addSettingsPage (const String& title,
  61053. const Drawable* icon,
  61054. const Drawable* overIcon,
  61055. const Drawable* downIcon)
  61056. {
  61057. DrawableButton* const button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61058. buttons.add (button);
  61059. button->setImages (icon, overIcon, downIcon);
  61060. button->setRadioGroupId (1);
  61061. button->addListener (this);
  61062. button->setClickingTogglesState (true);
  61063. button->setWantsKeyboardFocus (false);
  61064. addAndMakeVisible (button);
  61065. resized();
  61066. if (currentPage == 0)
  61067. setCurrentPage (title);
  61068. }
  61069. void PreferencesPanel::addSettingsPage (const String& title, const void* imageData, const int imageDataSize)
  61070. {
  61071. DrawableImage icon, iconOver, iconDown;
  61072. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61073. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61074. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61075. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61076. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61077. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61078. }
  61079. void PreferencesPanel::showInDialogBox (const String& dialogTitle, int dialogWidth, int dialogHeight, const Colour& backgroundColour)
  61080. {
  61081. setSize (dialogWidth, dialogHeight);
  61082. DialogWindow::showModalDialog (dialogTitle, this, 0, backgroundColour, false);
  61083. }
  61084. void PreferencesPanel::resized()
  61085. {
  61086. for (int i = 0; i < buttons.size(); ++i)
  61087. buttons.getUnchecked(i)->setBounds (i * buttonSize, 0, buttonSize, buttonSize);
  61088. if (currentPage != 0)
  61089. currentPage->setBounds (getLocalBounds().withTop (buttonSize + 5));
  61090. }
  61091. void PreferencesPanel::paint (Graphics& g)
  61092. {
  61093. g.setColour (Colours::grey);
  61094. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61095. }
  61096. void PreferencesPanel::setCurrentPage (const String& pageName)
  61097. {
  61098. if (currentPageName != pageName)
  61099. {
  61100. currentPageName = pageName;
  61101. currentPage = 0;
  61102. currentPage = createComponentForPage (pageName);
  61103. if (currentPage != 0)
  61104. {
  61105. addAndMakeVisible (currentPage);
  61106. currentPage->toBack();
  61107. resized();
  61108. }
  61109. for (int i = 0; i < buttons.size(); ++i)
  61110. {
  61111. if (buttons.getUnchecked(i)->getName() == pageName)
  61112. {
  61113. buttons.getUnchecked(i)->setToggleState (true, false);
  61114. break;
  61115. }
  61116. }
  61117. }
  61118. }
  61119. void PreferencesPanel::buttonClicked (Button*)
  61120. {
  61121. for (int i = 0; i < buttons.size(); ++i)
  61122. {
  61123. if (buttons.getUnchecked(i)->getToggleState())
  61124. {
  61125. setCurrentPage (buttons.getUnchecked(i)->getName());
  61126. break;
  61127. }
  61128. }
  61129. }
  61130. END_JUCE_NAMESPACE
  61131. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61132. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61133. #if JUCE_WINDOWS || JUCE_LINUX
  61134. BEGIN_JUCE_NAMESPACE
  61135. SystemTrayIconComponent::SystemTrayIconComponent()
  61136. {
  61137. addToDesktop (0);
  61138. }
  61139. SystemTrayIconComponent::~SystemTrayIconComponent()
  61140. {
  61141. }
  61142. END_JUCE_NAMESPACE
  61143. #endif
  61144. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61145. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61146. BEGIN_JUCE_NAMESPACE
  61147. class AlertWindowTextEditor : public TextEditor
  61148. {
  61149. public:
  61150. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61151. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61152. {
  61153. setSelectAllWhenFocused (true);
  61154. }
  61155. void returnPressed()
  61156. {
  61157. // pass these up the component hierarchy to be trigger the buttons
  61158. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61159. }
  61160. void escapePressed()
  61161. {
  61162. // pass these up the component hierarchy to be trigger the buttons
  61163. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61164. }
  61165. private:
  61166. JUCE_DECLARE_NON_COPYABLE (AlertWindowTextEditor);
  61167. static juce_wchar getDefaultPasswordChar() throw()
  61168. {
  61169. #if JUCE_LINUX
  61170. return 0x2022;
  61171. #else
  61172. return 0x25cf;
  61173. #endif
  61174. }
  61175. };
  61176. AlertWindow::AlertWindow (const String& title,
  61177. const String& message,
  61178. AlertIconType iconType,
  61179. Component* associatedComponent_)
  61180. : TopLevelWindow (title, true),
  61181. alertIconType (iconType),
  61182. associatedComponent (associatedComponent_)
  61183. {
  61184. if (message.isEmpty())
  61185. text = " "; // to force an update if the message is empty
  61186. setMessage (message);
  61187. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61188. {
  61189. Component* const c = Desktop::getInstance().getComponent (i);
  61190. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61191. {
  61192. setAlwaysOnTop (true);
  61193. break;
  61194. }
  61195. }
  61196. if (! JUCEApplication::isStandaloneApp())
  61197. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61198. lookAndFeelChanged();
  61199. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61200. }
  61201. AlertWindow::~AlertWindow()
  61202. {
  61203. removeAllChildren();
  61204. }
  61205. void AlertWindow::userTriedToCloseWindow()
  61206. {
  61207. exitModalState (0);
  61208. }
  61209. void AlertWindow::setMessage (const String& message)
  61210. {
  61211. const String newMessage (message.substring (0, 2048));
  61212. if (text != newMessage)
  61213. {
  61214. text = newMessage;
  61215. font = getLookAndFeel().getAlertWindowMessageFont();
  61216. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61217. textLayout.setText (getName() + "\n\n", titleFont);
  61218. textLayout.appendText (text, font);
  61219. updateLayout (true);
  61220. repaint();
  61221. }
  61222. }
  61223. void AlertWindow::buttonClicked (Button* button)
  61224. {
  61225. if (button->getParentComponent() != 0)
  61226. button->getParentComponent()->exitModalState (button->getCommandID());
  61227. }
  61228. void AlertWindow::addButton (const String& name,
  61229. const int returnValue,
  61230. const KeyPress& shortcutKey1,
  61231. const KeyPress& shortcutKey2)
  61232. {
  61233. TextButton* const b = new TextButton (name, String::empty);
  61234. buttons.add (b);
  61235. b->setWantsKeyboardFocus (true);
  61236. b->setMouseClickGrabsKeyboardFocus (false);
  61237. b->setCommandToTrigger (0, returnValue, false);
  61238. b->addShortcut (shortcutKey1);
  61239. b->addShortcut (shortcutKey2);
  61240. b->addListener (this);
  61241. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61242. addAndMakeVisible (b, 0);
  61243. updateLayout (false);
  61244. }
  61245. int AlertWindow::getNumButtons() const
  61246. {
  61247. return buttons.size();
  61248. }
  61249. void AlertWindow::triggerButtonClick (const String& buttonName)
  61250. {
  61251. for (int i = buttons.size(); --i >= 0;)
  61252. {
  61253. TextButton* const b = buttons.getUnchecked(i);
  61254. if (buttonName == b->getName())
  61255. {
  61256. b->triggerClick();
  61257. break;
  61258. }
  61259. }
  61260. }
  61261. void AlertWindow::addTextEditor (const String& name,
  61262. const String& initialContents,
  61263. const String& onScreenLabel,
  61264. const bool isPasswordBox)
  61265. {
  61266. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61267. textBoxes.add (tc);
  61268. allComps.add (tc);
  61269. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61270. tc->setFont (font);
  61271. tc->setText (initialContents);
  61272. tc->setCaretPosition (initialContents.length());
  61273. addAndMakeVisible (tc);
  61274. textboxNames.add (onScreenLabel);
  61275. updateLayout (false);
  61276. }
  61277. TextEditor* AlertWindow::getTextEditor (const String& nameOfTextEditor) const
  61278. {
  61279. for (int i = textBoxes.size(); --i >= 0;)
  61280. if (textBoxes.getUnchecked(i)->getName() == nameOfTextEditor)
  61281. return textBoxes.getUnchecked(i);
  61282. return 0;
  61283. }
  61284. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61285. {
  61286. TextEditor* const t = getTextEditor (nameOfTextEditor);
  61287. return t != 0 ? t->getText() : String::empty;
  61288. }
  61289. void AlertWindow::addComboBox (const String& name,
  61290. const StringArray& items,
  61291. const String& onScreenLabel)
  61292. {
  61293. ComboBox* const cb = new ComboBox (name);
  61294. comboBoxes.add (cb);
  61295. allComps.add (cb);
  61296. for (int i = 0; i < items.size(); ++i)
  61297. cb->addItem (items[i], i + 1);
  61298. addAndMakeVisible (cb);
  61299. cb->setSelectedItemIndex (0);
  61300. comboBoxNames.add (onScreenLabel);
  61301. updateLayout (false);
  61302. }
  61303. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61304. {
  61305. for (int i = comboBoxes.size(); --i >= 0;)
  61306. if (comboBoxes.getUnchecked(i)->getName() == nameOfList)
  61307. return comboBoxes.getUnchecked(i);
  61308. return 0;
  61309. }
  61310. class AlertTextComp : public TextEditor
  61311. {
  61312. public:
  61313. AlertTextComp (const String& message,
  61314. const Font& font)
  61315. {
  61316. setReadOnly (true);
  61317. setMultiLine (true, true);
  61318. setCaretVisible (false);
  61319. setScrollbarsShown (true);
  61320. lookAndFeelChanged();
  61321. setWantsKeyboardFocus (false);
  61322. setFont (font);
  61323. setText (message, false);
  61324. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61325. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61326. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61327. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61328. }
  61329. ~AlertTextComp()
  61330. {
  61331. }
  61332. int getPreferredWidth() const throw() { return bestWidth; }
  61333. void updateLayout (const int width)
  61334. {
  61335. TextLayout text;
  61336. text.appendText (getText(), getFont());
  61337. text.layout (width - 8, Justification::topLeft, true);
  61338. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61339. }
  61340. private:
  61341. int bestWidth;
  61342. JUCE_DECLARE_NON_COPYABLE (AlertTextComp);
  61343. };
  61344. void AlertWindow::addTextBlock (const String& textBlock)
  61345. {
  61346. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61347. textBlocks.add (c);
  61348. allComps.add (c);
  61349. addAndMakeVisible (c);
  61350. updateLayout (false);
  61351. }
  61352. void AlertWindow::addProgressBarComponent (double& progressValue)
  61353. {
  61354. ProgressBar* const pb = new ProgressBar (progressValue);
  61355. progressBars.add (pb);
  61356. allComps.add (pb);
  61357. addAndMakeVisible (pb);
  61358. updateLayout (false);
  61359. }
  61360. void AlertWindow::addCustomComponent (Component* const component)
  61361. {
  61362. customComps.add (component);
  61363. allComps.add (component);
  61364. addAndMakeVisible (component);
  61365. updateLayout (false);
  61366. }
  61367. int AlertWindow::getNumCustomComponents() const
  61368. {
  61369. return customComps.size();
  61370. }
  61371. Component* AlertWindow::getCustomComponent (const int index) const
  61372. {
  61373. return customComps [index];
  61374. }
  61375. Component* AlertWindow::removeCustomComponent (const int index)
  61376. {
  61377. Component* const c = getCustomComponent (index);
  61378. if (c != 0)
  61379. {
  61380. customComps.removeValue (c);
  61381. allComps.removeValue (c);
  61382. removeChildComponent (c);
  61383. updateLayout (false);
  61384. }
  61385. return c;
  61386. }
  61387. void AlertWindow::paint (Graphics& g)
  61388. {
  61389. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61390. g.setColour (findColour (textColourId));
  61391. g.setFont (getLookAndFeel().getAlertWindowFont());
  61392. int i;
  61393. for (i = textBoxes.size(); --i >= 0;)
  61394. {
  61395. const TextEditor* const te = textBoxes.getUnchecked(i);
  61396. g.drawFittedText (textboxNames[i],
  61397. te->getX(), te->getY() - 14,
  61398. te->getWidth(), 14,
  61399. Justification::centredLeft, 1);
  61400. }
  61401. for (i = comboBoxNames.size(); --i >= 0;)
  61402. {
  61403. const ComboBox* const cb = comboBoxes.getUnchecked(i);
  61404. g.drawFittedText (comboBoxNames[i],
  61405. cb->getX(), cb->getY() - 14,
  61406. cb->getWidth(), 14,
  61407. Justification::centredLeft, 1);
  61408. }
  61409. for (i = customComps.size(); --i >= 0;)
  61410. {
  61411. const Component* const c = customComps.getUnchecked(i);
  61412. g.drawFittedText (c->getName(),
  61413. c->getX(), c->getY() - 14,
  61414. c->getWidth(), 14,
  61415. Justification::centredLeft, 1);
  61416. }
  61417. }
  61418. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61419. {
  61420. const int titleH = 24;
  61421. const int iconWidth = 80;
  61422. const int wid = jmax (font.getStringWidth (text),
  61423. font.getStringWidth (getName()));
  61424. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61425. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61426. const int edgeGap = 10;
  61427. const int labelHeight = 18;
  61428. int iconSpace;
  61429. if (alertIconType == NoIcon)
  61430. {
  61431. textLayout.layout (w, Justification::horizontallyCentred, true);
  61432. iconSpace = 0;
  61433. }
  61434. else
  61435. {
  61436. textLayout.layout (w, Justification::left, true);
  61437. iconSpace = iconWidth;
  61438. }
  61439. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61440. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61441. const int textLayoutH = textLayout.getHeight();
  61442. const int textBottom = 16 + titleH + textLayoutH;
  61443. int h = textBottom;
  61444. int buttonW = 40;
  61445. int i;
  61446. for (i = 0; i < buttons.size(); ++i)
  61447. buttonW += 16 + buttons.getUnchecked(i)->getWidth();
  61448. w = jmax (buttonW, w);
  61449. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61450. if (buttons.size() > 0)
  61451. h += 20 + buttons.getUnchecked(0)->getHeight();
  61452. for (i = customComps.size(); --i >= 0;)
  61453. {
  61454. Component* c = customComps.getUnchecked(i);
  61455. w = jmax (w, (c->getWidth() * 100) / 80);
  61456. h += 10 + c->getHeight();
  61457. if (c->getName().isNotEmpty())
  61458. h += labelHeight;
  61459. }
  61460. for (i = textBlocks.size(); --i >= 0;)
  61461. {
  61462. const AlertTextComp* const ac = static_cast <const AlertTextComp*> (textBlocks.getUnchecked(i));
  61463. w = jmax (w, ac->getPreferredWidth());
  61464. }
  61465. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61466. for (i = textBlocks.size(); --i >= 0;)
  61467. {
  61468. AlertTextComp* const ac = static_cast <AlertTextComp*> (textBlocks.getUnchecked(i));
  61469. ac->updateLayout ((int) (w * 0.8f));
  61470. h += ac->getHeight() + 10;
  61471. }
  61472. h = jmin (getParentHeight() - 50, h);
  61473. if (onlyIncreaseSize)
  61474. {
  61475. w = jmax (w, getWidth());
  61476. h = jmax (h, getHeight());
  61477. }
  61478. if (! isVisible())
  61479. {
  61480. centreAroundComponent (associatedComponent, w, h);
  61481. }
  61482. else
  61483. {
  61484. const int cx = getX() + getWidth() / 2;
  61485. const int cy = getY() + getHeight() / 2;
  61486. setBounds (cx - w / 2,
  61487. cy - h / 2,
  61488. w, h);
  61489. }
  61490. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61491. const int spacer = 16;
  61492. int totalWidth = -spacer;
  61493. for (i = buttons.size(); --i >= 0;)
  61494. totalWidth += buttons.getUnchecked(i)->getWidth() + spacer;
  61495. int x = (w - totalWidth) / 2;
  61496. int y = (int) (getHeight() * 0.95f);
  61497. for (i = 0; i < buttons.size(); ++i)
  61498. {
  61499. TextButton* const c = buttons.getUnchecked(i);
  61500. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61501. c->setTopLeftPosition (x, ny);
  61502. if (ny < y)
  61503. y = ny;
  61504. x += c->getWidth() + spacer;
  61505. c->toFront (false);
  61506. }
  61507. y = textBottom;
  61508. for (i = 0; i < allComps.size(); ++i)
  61509. {
  61510. Component* const c = allComps.getUnchecked(i);
  61511. h = 22;
  61512. const int comboIndex = comboBoxes.indexOf (dynamic_cast <ComboBox*> (c));
  61513. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61514. y += labelHeight;
  61515. const int tbIndex = textBoxes.indexOf (dynamic_cast <TextEditor*> (c));
  61516. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61517. y += labelHeight;
  61518. if (customComps.contains (c))
  61519. {
  61520. if (c->getName().isNotEmpty())
  61521. y += labelHeight;
  61522. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61523. h = c->getHeight();
  61524. }
  61525. else if (textBlocks.contains (c))
  61526. {
  61527. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61528. h = c->getHeight();
  61529. }
  61530. else
  61531. {
  61532. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61533. }
  61534. y += h + 10;
  61535. }
  61536. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61537. }
  61538. bool AlertWindow::containsAnyExtraComponents() const
  61539. {
  61540. return allComps.size() > 0;
  61541. }
  61542. void AlertWindow::mouseDown (const MouseEvent& e)
  61543. {
  61544. dragger.startDraggingComponent (this, e);
  61545. }
  61546. void AlertWindow::mouseDrag (const MouseEvent& e)
  61547. {
  61548. dragger.dragComponent (this, e, &constrainer);
  61549. }
  61550. bool AlertWindow::keyPressed (const KeyPress& key)
  61551. {
  61552. for (int i = buttons.size(); --i >= 0;)
  61553. {
  61554. TextButton* const b = buttons.getUnchecked(i);
  61555. if (b->isRegisteredForShortcut (key))
  61556. {
  61557. b->triggerClick();
  61558. return true;
  61559. }
  61560. }
  61561. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61562. {
  61563. exitModalState (0);
  61564. return true;
  61565. }
  61566. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61567. {
  61568. buttons.getUnchecked(0)->triggerClick();
  61569. return true;
  61570. }
  61571. return false;
  61572. }
  61573. void AlertWindow::lookAndFeelChanged()
  61574. {
  61575. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  61576. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  61577. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  61578. }
  61579. int AlertWindow::getDesktopWindowStyleFlags() const
  61580. {
  61581. return getLookAndFeel().getAlertBoxWindowFlags();
  61582. }
  61583. class AlertWindowInfo
  61584. {
  61585. public:
  61586. AlertWindowInfo (const String& title_, const String& message_, Component* component,
  61587. AlertWindow::AlertIconType iconType_, int numButtons_)
  61588. : title (title_), message (message_), iconType (iconType_),
  61589. numButtons (numButtons_), returnValue (0), associatedComponent (component)
  61590. {
  61591. }
  61592. String title, message, button1, button2, button3;
  61593. AlertWindow::AlertIconType iconType;
  61594. int numButtons, returnValue;
  61595. WeakReference<Component> associatedComponent;
  61596. int showModal() const
  61597. {
  61598. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  61599. return returnValue;
  61600. }
  61601. private:
  61602. void show()
  61603. {
  61604. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  61605. : LookAndFeel::getDefaultLookAndFeel();
  61606. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  61607. iconType, numButtons, associatedComponent));
  61608. jassert (alertBox != 0); // you have to return one of these!
  61609. returnValue = alertBox->runModalLoop();
  61610. }
  61611. static void* showCallback (void* userData)
  61612. {
  61613. static_cast <AlertWindowInfo*> (userData)->show();
  61614. return 0;
  61615. }
  61616. };
  61617. void AlertWindow::showMessageBox (AlertIconType iconType,
  61618. const String& title,
  61619. const String& message,
  61620. const String& buttonText,
  61621. Component* associatedComponent)
  61622. {
  61623. AlertWindowInfo info (title, message, associatedComponent, iconType, 1);
  61624. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  61625. info.showModal();
  61626. }
  61627. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  61628. const String& title,
  61629. const String& message,
  61630. const String& button1Text,
  61631. const String& button2Text,
  61632. Component* associatedComponent)
  61633. {
  61634. AlertWindowInfo info (title, message, associatedComponent, iconType, 2);
  61635. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  61636. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  61637. return info.showModal() != 0;
  61638. }
  61639. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  61640. const String& title,
  61641. const String& message,
  61642. const String& button1Text,
  61643. const String& button2Text,
  61644. const String& button3Text,
  61645. Component* associatedComponent)
  61646. {
  61647. AlertWindowInfo info (title, message, associatedComponent, iconType, 3);
  61648. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  61649. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  61650. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  61651. return info.showModal();
  61652. }
  61653. END_JUCE_NAMESPACE
  61654. /*** End of inlined file: juce_AlertWindow.cpp ***/
  61655. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  61656. BEGIN_JUCE_NAMESPACE
  61657. CallOutBox::CallOutBox (Component& contentComponent,
  61658. Component& componentToPointTo,
  61659. Component* const parentComponent)
  61660. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  61661. {
  61662. addAndMakeVisible (&content);
  61663. if (parentComponent != 0)
  61664. {
  61665. parentComponent->addChildComponent (this);
  61666. updatePosition (parentComponent->getLocalArea (&componentToPointTo, componentToPointTo.getLocalBounds()),
  61667. parentComponent->getLocalBounds());
  61668. setVisible (true);
  61669. }
  61670. else
  61671. {
  61672. if (! JUCEApplication::isStandaloneApp())
  61673. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61674. updatePosition (componentToPointTo.getScreenBounds(),
  61675. componentToPointTo.getParentMonitorArea());
  61676. addToDesktop (ComponentPeer::windowIsTemporary);
  61677. }
  61678. }
  61679. CallOutBox::~CallOutBox()
  61680. {
  61681. }
  61682. void CallOutBox::setArrowSize (const float newSize)
  61683. {
  61684. arrowSize = newSize;
  61685. borderSpace = jmax (20, (int) arrowSize);
  61686. refreshPath();
  61687. }
  61688. void CallOutBox::paint (Graphics& g)
  61689. {
  61690. if (background.isNull())
  61691. {
  61692. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  61693. Graphics g2 (background);
  61694. getLookAndFeel().drawCallOutBoxBackground (*this, g2, outline);
  61695. }
  61696. g.setColour (Colours::black);
  61697. g.drawImageAt (background, 0, 0);
  61698. }
  61699. void CallOutBox::resized()
  61700. {
  61701. content.setTopLeftPosition (borderSpace, borderSpace);
  61702. refreshPath();
  61703. }
  61704. void CallOutBox::moved()
  61705. {
  61706. refreshPath();
  61707. }
  61708. void CallOutBox::childBoundsChanged (Component*)
  61709. {
  61710. updatePosition (targetArea, availableArea);
  61711. }
  61712. bool CallOutBox::hitTest (int x, int y)
  61713. {
  61714. return outline.contains ((float) x, (float) y);
  61715. }
  61716. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  61717. void CallOutBox::inputAttemptWhenModal()
  61718. {
  61719. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  61720. if (targetArea.contains (mousePos))
  61721. {
  61722. // if you click on the area that originally popped-up the callout, you expect it
  61723. // to get rid of the box, but deleting the box here allows the click to pass through and
  61724. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  61725. postCommandMessage (callOutBoxDismissCommandId);
  61726. }
  61727. else
  61728. {
  61729. exitModalState (0);
  61730. setVisible (false);
  61731. }
  61732. }
  61733. void CallOutBox::handleCommandMessage (int commandId)
  61734. {
  61735. Component::handleCommandMessage (commandId);
  61736. if (commandId == callOutBoxDismissCommandId)
  61737. {
  61738. exitModalState (0);
  61739. setVisible (false);
  61740. }
  61741. }
  61742. bool CallOutBox::keyPressed (const KeyPress& key)
  61743. {
  61744. if (key.isKeyCode (KeyPress::escapeKey))
  61745. {
  61746. inputAttemptWhenModal();
  61747. return true;
  61748. }
  61749. return false;
  61750. }
  61751. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  61752. {
  61753. targetArea = newAreaToPointTo;
  61754. availableArea = newAreaToFitIn;
  61755. Rectangle<int> bounds (0, 0,
  61756. content.getWidth() + borderSpace * 2,
  61757. content.getHeight() + borderSpace * 2);
  61758. const int hw = bounds.getWidth() / 2;
  61759. const int hh = bounds.getHeight() / 2;
  61760. const float hwReduced = (float) (hw - borderSpace * 3);
  61761. const float hhReduced = (float) (hh - borderSpace * 3);
  61762. const float arrowIndent = borderSpace - arrowSize;
  61763. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  61764. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  61765. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  61766. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  61767. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  61768. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  61769. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  61770. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  61771. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  61772. float nearest = 1.0e9f;
  61773. for (int i = 0; i < 4; ++i)
  61774. {
  61775. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  61776. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  61777. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  61778. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  61779. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  61780. distanceFromCentre *= 2.0f;
  61781. if (distanceFromCentre < nearest)
  61782. {
  61783. nearest = distanceFromCentre;
  61784. targetPoint = targets[i];
  61785. bounds.setPosition ((int) (centre.getX() - hw),
  61786. (int) (centre.getY() - hh));
  61787. }
  61788. }
  61789. setBounds (bounds);
  61790. }
  61791. void CallOutBox::refreshPath()
  61792. {
  61793. repaint();
  61794. background = Image::null;
  61795. outline.clear();
  61796. const float gap = 4.5f;
  61797. const float cornerSize = 9.0f;
  61798. const float cornerSize2 = 2.0f * cornerSize;
  61799. const float arrowBaseWidth = arrowSize * 0.7f;
  61800. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  61801. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  61802. outline.startNewSubPath (left + cornerSize, top);
  61803. if (targetY <= top)
  61804. {
  61805. outline.lineTo (targetX - arrowBaseWidth, top);
  61806. outline.lineTo (targetX, targetY);
  61807. outline.lineTo (targetX + arrowBaseWidth, top);
  61808. }
  61809. outline.lineTo (right - cornerSize, top);
  61810. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  61811. if (targetX >= right)
  61812. {
  61813. outline.lineTo (right, targetY - arrowBaseWidth);
  61814. outline.lineTo (targetX, targetY);
  61815. outline.lineTo (right, targetY + arrowBaseWidth);
  61816. }
  61817. outline.lineTo (right, bottom - cornerSize);
  61818. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  61819. if (targetY >= bottom)
  61820. {
  61821. outline.lineTo (targetX + arrowBaseWidth, bottom);
  61822. outline.lineTo (targetX, targetY);
  61823. outline.lineTo (targetX - arrowBaseWidth, bottom);
  61824. }
  61825. outline.lineTo (left + cornerSize, bottom);
  61826. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  61827. if (targetX <= left)
  61828. {
  61829. outline.lineTo (left, targetY + arrowBaseWidth);
  61830. outline.lineTo (targetX, targetY);
  61831. outline.lineTo (left, targetY - arrowBaseWidth);
  61832. }
  61833. outline.lineTo (left, top + cornerSize);
  61834. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  61835. outline.closeSubPath();
  61836. }
  61837. END_JUCE_NAMESPACE
  61838. /*** End of inlined file: juce_CallOutBox.cpp ***/
  61839. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  61840. BEGIN_JUCE_NAMESPACE
  61841. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  61842. static Array <ComponentPeer*> heavyweightPeers;
  61843. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  61844. : component (component_),
  61845. styleFlags (styleFlags_),
  61846. lastPaintTime (0),
  61847. constrainer (0),
  61848. lastDragAndDropCompUnderMouse (0),
  61849. fakeMouseMessageSent (false),
  61850. isWindowMinimised (false)
  61851. {
  61852. heavyweightPeers.add (this);
  61853. }
  61854. ComponentPeer::~ComponentPeer()
  61855. {
  61856. heavyweightPeers.removeValue (this);
  61857. Desktop::getInstance().triggerFocusCallback();
  61858. }
  61859. int ComponentPeer::getNumPeers() throw()
  61860. {
  61861. return heavyweightPeers.size();
  61862. }
  61863. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  61864. {
  61865. return heavyweightPeers [index];
  61866. }
  61867. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  61868. {
  61869. for (int i = heavyweightPeers.size(); --i >= 0;)
  61870. {
  61871. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  61872. if (peer->getComponent() == component)
  61873. return peer;
  61874. }
  61875. return 0;
  61876. }
  61877. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  61878. {
  61879. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  61880. }
  61881. void ComponentPeer::updateCurrentModifiers() throw()
  61882. {
  61883. ModifierKeys::updateCurrentModifiers();
  61884. }
  61885. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  61886. {
  61887. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61888. jassert (mouse != 0); // not enough sources!
  61889. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  61890. }
  61891. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  61892. {
  61893. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61894. jassert (mouse != 0); // not enough sources!
  61895. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  61896. }
  61897. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  61898. {
  61899. Graphics g (&contextToPaintTo);
  61900. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61901. g.saveState();
  61902. #endif
  61903. JUCE_TRY
  61904. {
  61905. component->paintEntireComponent (g, true);
  61906. }
  61907. JUCE_CATCH_EXCEPTION
  61908. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61909. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  61910. // clearly when things are being repainted.
  61911. g.restoreState();
  61912. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  61913. (uint8) Random::getSystemRandom().nextInt (255),
  61914. (uint8) Random::getSystemRandom().nextInt (255),
  61915. (uint8) 0x50));
  61916. #endif
  61917. /** If this fails, it's probably be because your CPU floating-point precision mode has
  61918. been set to low.. This setting is sometimes changed by things like Direct3D, and can
  61919. mess up a lot of the calculations that the library needs to do.
  61920. */
  61921. jassert (roundToInt (10.1f) == 10);
  61922. }
  61923. bool ComponentPeer::handleKeyPress (const int keyCode,
  61924. const juce_wchar textCharacter)
  61925. {
  61926. updateCurrentModifiers();
  61927. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61928. ? Component::getCurrentlyFocusedComponent()
  61929. : component;
  61930. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61931. {
  61932. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61933. if (currentModalComp != 0)
  61934. target = currentModalComp;
  61935. }
  61936. const KeyPress keyInfo (keyCode,
  61937. ModifierKeys::getCurrentModifiers().getRawFlags()
  61938. & ModifierKeys::allKeyboardModifiers,
  61939. textCharacter);
  61940. bool keyWasUsed = false;
  61941. while (target != 0)
  61942. {
  61943. const WeakReference<Component> deletionChecker (target);
  61944. const Array <KeyListener*>* const keyListeners = target->keyListeners;
  61945. if (keyListeners != 0)
  61946. {
  61947. for (int i = keyListeners->size(); --i >= 0;)
  61948. {
  61949. keyWasUsed = keyListeners->getUnchecked(i)->keyPressed (keyInfo, target);
  61950. if (keyWasUsed || deletionChecker == 0)
  61951. return keyWasUsed;
  61952. i = jmin (i, keyListeners->size());
  61953. }
  61954. }
  61955. keyWasUsed = target->keyPressed (keyInfo);
  61956. if (keyWasUsed || deletionChecker == 0)
  61957. break;
  61958. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  61959. {
  61960. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  61961. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  61962. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  61963. break;
  61964. }
  61965. target = target->getParentComponent();
  61966. }
  61967. return keyWasUsed;
  61968. }
  61969. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  61970. {
  61971. updateCurrentModifiers();
  61972. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61973. ? Component::getCurrentlyFocusedComponent()
  61974. : component;
  61975. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61976. {
  61977. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61978. if (currentModalComp != 0)
  61979. target = currentModalComp;
  61980. }
  61981. bool keyWasUsed = false;
  61982. while (target != 0)
  61983. {
  61984. const WeakReference<Component> deletionChecker (target);
  61985. keyWasUsed = target->keyStateChanged (isKeyDown);
  61986. if (keyWasUsed || deletionChecker == 0)
  61987. break;
  61988. const Array <KeyListener*>* const keyListeners = target->keyListeners;
  61989. if (keyListeners != 0)
  61990. {
  61991. for (int i = keyListeners->size(); --i >= 0;)
  61992. {
  61993. keyWasUsed = keyListeners->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  61994. if (keyWasUsed || deletionChecker == 0)
  61995. return keyWasUsed;
  61996. i = jmin (i, keyListeners->size());
  61997. }
  61998. }
  61999. target = target->getParentComponent();
  62000. }
  62001. return keyWasUsed;
  62002. }
  62003. void ComponentPeer::handleModifierKeysChange()
  62004. {
  62005. updateCurrentModifiers();
  62006. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62007. if (target == 0)
  62008. target = Component::getCurrentlyFocusedComponent();
  62009. if (target == 0)
  62010. target = component;
  62011. if (target != 0)
  62012. target->internalModifierKeysChanged();
  62013. }
  62014. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62015. {
  62016. Component* const c = Component::getCurrentlyFocusedComponent();
  62017. if (component->isParentOf (c))
  62018. {
  62019. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62020. if (ti != 0 && ti->isTextInputActive())
  62021. return ti;
  62022. }
  62023. return 0;
  62024. }
  62025. void ComponentPeer::handleBroughtToFront()
  62026. {
  62027. updateCurrentModifiers();
  62028. if (component != 0)
  62029. component->internalBroughtToFront();
  62030. }
  62031. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62032. {
  62033. constrainer = newConstrainer;
  62034. }
  62035. void ComponentPeer::handleMovedOrResized()
  62036. {
  62037. updateCurrentModifiers();
  62038. const bool nowMinimised = isMinimised();
  62039. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62040. {
  62041. const WeakReference<Component> deletionChecker (component);
  62042. const Rectangle<int> newBounds (getBounds());
  62043. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62044. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62045. if (wasMoved || wasResized)
  62046. {
  62047. component->bounds = newBounds;
  62048. if (wasResized)
  62049. component->repaint();
  62050. component->sendMovedResizedMessages (wasMoved, wasResized);
  62051. if (deletionChecker == 0)
  62052. return;
  62053. }
  62054. }
  62055. if (isWindowMinimised != nowMinimised)
  62056. {
  62057. isWindowMinimised = nowMinimised;
  62058. component->minimisationStateChanged (nowMinimised);
  62059. component->sendVisibilityChangeMessage();
  62060. }
  62061. if (! isFullScreen())
  62062. lastNonFullscreenBounds = component->getBounds();
  62063. }
  62064. void ComponentPeer::handleFocusGain()
  62065. {
  62066. updateCurrentModifiers();
  62067. if (component->isParentOf (lastFocusedComponent))
  62068. {
  62069. Component::currentlyFocusedComponent = lastFocusedComponent;
  62070. Desktop::getInstance().triggerFocusCallback();
  62071. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62072. }
  62073. else
  62074. {
  62075. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62076. component->grabKeyboardFocus();
  62077. else
  62078. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  62079. }
  62080. }
  62081. void ComponentPeer::handleFocusLoss()
  62082. {
  62083. updateCurrentModifiers();
  62084. if (component->hasKeyboardFocus (true))
  62085. {
  62086. lastFocusedComponent = Component::currentlyFocusedComponent;
  62087. if (lastFocusedComponent != 0)
  62088. {
  62089. Component::currentlyFocusedComponent = 0;
  62090. Desktop::getInstance().triggerFocusCallback();
  62091. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62092. }
  62093. }
  62094. }
  62095. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62096. {
  62097. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62098. ? static_cast <Component*> (lastFocusedComponent)
  62099. : component;
  62100. }
  62101. void ComponentPeer::handleScreenSizeChange()
  62102. {
  62103. updateCurrentModifiers();
  62104. component->parentSizeChanged();
  62105. handleMovedOrResized();
  62106. }
  62107. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62108. {
  62109. lastNonFullscreenBounds = newBounds;
  62110. }
  62111. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62112. {
  62113. return lastNonFullscreenBounds;
  62114. }
  62115. const Rectangle<int> ComponentPeer::localToGlobal (const Rectangle<int>& relativePosition)
  62116. {
  62117. return relativePosition.withPosition (localToGlobal (relativePosition.getPosition()));
  62118. }
  62119. const Rectangle<int> ComponentPeer::globalToLocal (const Rectangle<int>& screenPosition)
  62120. {
  62121. return screenPosition.withPosition (globalToLocal (screenPosition.getPosition()));
  62122. }
  62123. namespace ComponentPeerHelpers
  62124. {
  62125. FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62126. const StringArray& files,
  62127. FileDragAndDropTarget* const lastOne)
  62128. {
  62129. while (c != 0)
  62130. {
  62131. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62132. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62133. return t;
  62134. c = c->getParentComponent();
  62135. }
  62136. return 0;
  62137. }
  62138. }
  62139. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62140. {
  62141. updateCurrentModifiers();
  62142. FileDragAndDropTarget* lastTarget
  62143. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62144. FileDragAndDropTarget* newTarget = 0;
  62145. Component* const compUnderMouse = component->getComponentAt (position);
  62146. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62147. {
  62148. lastDragAndDropCompUnderMouse = compUnderMouse;
  62149. newTarget = ComponentPeerHelpers::findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62150. if (newTarget != lastTarget)
  62151. {
  62152. if (lastTarget != 0)
  62153. lastTarget->fileDragExit (files);
  62154. dragAndDropTargetComponent = 0;
  62155. if (newTarget != 0)
  62156. {
  62157. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62158. const Point<int> pos (dragAndDropTargetComponent->getLocalPoint (component, position));
  62159. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62160. }
  62161. }
  62162. }
  62163. else
  62164. {
  62165. newTarget = lastTarget;
  62166. }
  62167. if (newTarget != 0)
  62168. {
  62169. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  62170. const Point<int> pos (targetComp->getLocalPoint (component, position));
  62171. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  62172. }
  62173. }
  62174. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62175. {
  62176. handleFileDragMove (files, Point<int> (-1, -1));
  62177. jassert (dragAndDropTargetComponent == 0);
  62178. lastDragAndDropCompUnderMouse = 0;
  62179. }
  62180. // We'll use an async message to deliver the drop, because if the target decides
  62181. // to run a modal loop, it can gum-up the operating system..
  62182. class AsyncFileDropMessage : public CallbackMessage
  62183. {
  62184. public:
  62185. AsyncFileDropMessage (Component* target_, FileDragAndDropTarget* dropTarget_,
  62186. const Point<int>& position_, const StringArray& files_)
  62187. : target (target_), dropTarget (dropTarget_), position (position_), files (files_)
  62188. {
  62189. }
  62190. void messageCallback()
  62191. {
  62192. if (target != 0)
  62193. dropTarget->filesDropped (files, position.getX(), position.getY());
  62194. }
  62195. private:
  62196. WeakReference<Component> target;
  62197. FileDragAndDropTarget* const dropTarget;
  62198. const Point<int> position;
  62199. const StringArray files;
  62200. JUCE_DECLARE_NON_COPYABLE (AsyncFileDropMessage);
  62201. };
  62202. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62203. {
  62204. handleFileDragMove (files, position);
  62205. if (dragAndDropTargetComponent != 0)
  62206. {
  62207. FileDragAndDropTarget* const target
  62208. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62209. dragAndDropTargetComponent = 0;
  62210. lastDragAndDropCompUnderMouse = 0;
  62211. if (target != 0)
  62212. {
  62213. Component* const targetComp = dynamic_cast <Component*> (target);
  62214. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62215. {
  62216. targetComp->internalModalInputAttempt();
  62217. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62218. return;
  62219. }
  62220. (new AsyncFileDropMessage (targetComp, target, targetComp->getLocalPoint (component, position), files))->post();
  62221. }
  62222. }
  62223. }
  62224. void ComponentPeer::handleUserClosingWindow()
  62225. {
  62226. updateCurrentModifiers();
  62227. component->userTriedToCloseWindow();
  62228. }
  62229. void ComponentPeer::clearMaskedRegion()
  62230. {
  62231. maskedRegion.clear();
  62232. }
  62233. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62234. {
  62235. maskedRegion.add (x, y, w, h);
  62236. }
  62237. const StringArray ComponentPeer::getAvailableRenderingEngines()
  62238. {
  62239. StringArray s;
  62240. s.add ("Software Renderer");
  62241. return s;
  62242. }
  62243. int ComponentPeer::getCurrentRenderingEngine() throw()
  62244. {
  62245. return 0;
  62246. }
  62247. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  62248. {
  62249. }
  62250. END_JUCE_NAMESPACE
  62251. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62252. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62253. BEGIN_JUCE_NAMESPACE
  62254. DialogWindow::DialogWindow (const String& name,
  62255. const Colour& backgroundColour_,
  62256. const bool escapeKeyTriggersCloseButton_,
  62257. const bool addToDesktop_)
  62258. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62259. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62260. {
  62261. }
  62262. DialogWindow::~DialogWindow()
  62263. {
  62264. }
  62265. void DialogWindow::resized()
  62266. {
  62267. DocumentWindow::resized();
  62268. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62269. if (escapeKeyTriggersCloseButton
  62270. && getCloseButton() != 0
  62271. && ! getCloseButton()->isRegisteredForShortcut (esc))
  62272. {
  62273. getCloseButton()->addShortcut (esc);
  62274. }
  62275. }
  62276. // (Sadly, this can't be made a local class inside the showModalDialog function, because the
  62277. // VC compiler complains about the undefined copy constructor)
  62278. class TempDialogWindow : public DialogWindow
  62279. {
  62280. public:
  62281. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  62282. : DialogWindow (title, colour, escapeCloses, true)
  62283. {
  62284. if (! JUCEApplication::isStandaloneApp())
  62285. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62286. }
  62287. void closeButtonPressed()
  62288. {
  62289. setVisible (false);
  62290. }
  62291. private:
  62292. JUCE_DECLARE_NON_COPYABLE (TempDialogWindow);
  62293. };
  62294. int DialogWindow::showModalDialog (const String& dialogTitle,
  62295. Component* contentComponent,
  62296. Component* componentToCentreAround,
  62297. const Colour& colour,
  62298. const bool escapeKeyTriggersCloseButton,
  62299. const bool shouldBeResizable,
  62300. const bool useBottomRightCornerResizer)
  62301. {
  62302. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  62303. dw.setContentComponent (contentComponent, true, true);
  62304. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  62305. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62306. const int result = dw.runModalLoop();
  62307. dw.setContentComponent (0, false);
  62308. return result;
  62309. }
  62310. END_JUCE_NAMESPACE
  62311. /*** End of inlined file: juce_DialogWindow.cpp ***/
  62312. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  62313. BEGIN_JUCE_NAMESPACE
  62314. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  62315. {
  62316. public:
  62317. ButtonListenerProxy (DocumentWindow& owner_)
  62318. : owner (owner_)
  62319. {
  62320. }
  62321. void buttonClicked (Button* button)
  62322. {
  62323. if (button == owner.getMinimiseButton())
  62324. owner.minimiseButtonPressed();
  62325. else if (button == owner.getMaximiseButton())
  62326. owner.maximiseButtonPressed();
  62327. else if (button == owner.getCloseButton())
  62328. owner.closeButtonPressed();
  62329. }
  62330. private:
  62331. DocumentWindow& owner;
  62332. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonListenerProxy);
  62333. };
  62334. DocumentWindow::DocumentWindow (const String& title,
  62335. const Colour& backgroundColour,
  62336. const int requiredButtons_,
  62337. const bool addToDesktop_)
  62338. : ResizableWindow (title, backgroundColour, addToDesktop_),
  62339. titleBarHeight (26),
  62340. menuBarHeight (24),
  62341. requiredButtons (requiredButtons_),
  62342. #if JUCE_MAC
  62343. positionTitleBarButtonsOnLeft (true),
  62344. #else
  62345. positionTitleBarButtonsOnLeft (false),
  62346. #endif
  62347. drawTitleTextCentred (true),
  62348. menuBarModel (0)
  62349. {
  62350. setResizeLimits (128, 128, 32768, 32768);
  62351. lookAndFeelChanged();
  62352. }
  62353. DocumentWindow::~DocumentWindow()
  62354. {
  62355. // Don't delete or remove the resizer components yourself! They're managed by the
  62356. // DocumentWindow, and you should leave them alone! You may have deleted them
  62357. // accidentally by careless use of deleteAllChildren()..?
  62358. jassert (menuBar == 0 || getIndexOfChildComponent (menuBar) >= 0);
  62359. jassert (titleBarButtons[0] == 0 || getIndexOfChildComponent (titleBarButtons[0]) >= 0);
  62360. jassert (titleBarButtons[1] == 0 || getIndexOfChildComponent (titleBarButtons[1]) >= 0);
  62361. jassert (titleBarButtons[2] == 0 || getIndexOfChildComponent (titleBarButtons[2]) >= 0);
  62362. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62363. titleBarButtons[i] = 0;
  62364. menuBar = 0;
  62365. }
  62366. void DocumentWindow::repaintTitleBar()
  62367. {
  62368. repaint (getTitleBarArea());
  62369. }
  62370. void DocumentWindow::setName (const String& newName)
  62371. {
  62372. if (newName != getName())
  62373. {
  62374. Component::setName (newName);
  62375. repaintTitleBar();
  62376. }
  62377. }
  62378. void DocumentWindow::setIcon (const Image& imageToUse)
  62379. {
  62380. titleBarIcon = imageToUse;
  62381. repaintTitleBar();
  62382. }
  62383. void DocumentWindow::setTitleBarHeight (const int newHeight)
  62384. {
  62385. titleBarHeight = newHeight;
  62386. resized();
  62387. repaintTitleBar();
  62388. }
  62389. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  62390. const bool positionTitleBarButtonsOnLeft_)
  62391. {
  62392. requiredButtons = requiredButtons_;
  62393. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62394. lookAndFeelChanged();
  62395. }
  62396. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62397. {
  62398. drawTitleTextCentred = textShouldBeCentred;
  62399. repaintTitleBar();
  62400. }
  62401. void DocumentWindow::setMenuBar (MenuBarModel* newMenuBarModel, const int newMenuBarHeight)
  62402. {
  62403. if (menuBarModel != newMenuBarModel)
  62404. {
  62405. menuBar = 0;
  62406. menuBarModel = newMenuBarModel;
  62407. menuBarHeight = newMenuBarHeight > 0 ? newMenuBarHeight
  62408. : getLookAndFeel().getDefaultMenuBarHeight();
  62409. if (menuBarModel != 0)
  62410. setMenuBarComponent (new MenuBarComponent (menuBarModel));
  62411. resized();
  62412. }
  62413. }
  62414. Component* DocumentWindow::getMenuBarComponent() const throw()
  62415. {
  62416. return menuBar;
  62417. }
  62418. void DocumentWindow::setMenuBarComponent (Component* newMenuBarComponent)
  62419. {
  62420. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62421. Component::addAndMakeVisible (menuBar = newMenuBarComponent);
  62422. if (menuBar != 0)
  62423. menuBar->setEnabled (isActiveWindow());
  62424. resized();
  62425. }
  62426. void DocumentWindow::closeButtonPressed()
  62427. {
  62428. /* If you've got a close button, you have to override this method to get
  62429. rid of your window!
  62430. If the window is just a pop-up, you should override this method and make
  62431. it delete the window in whatever way is appropriate for your app. E.g. you
  62432. might just want to call "delete this".
  62433. If your app is centred around this window such that the whole app should quit when
  62434. the window is closed, then you will probably want to use this method as an opportunity
  62435. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62436. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62437. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62438. or closing it via the taskbar icon on Windows).
  62439. */
  62440. jassertfalse;
  62441. }
  62442. void DocumentWindow::minimiseButtonPressed()
  62443. {
  62444. setMinimised (true);
  62445. }
  62446. void DocumentWindow::maximiseButtonPressed()
  62447. {
  62448. setFullScreen (! isFullScreen());
  62449. }
  62450. void DocumentWindow::paint (Graphics& g)
  62451. {
  62452. ResizableWindow::paint (g);
  62453. if (resizableBorder == 0)
  62454. {
  62455. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62456. const BorderSize<int> border (getBorderThickness());
  62457. g.fillRect (0, 0, getWidth(), border.getTop());
  62458. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62459. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62460. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62461. }
  62462. const Rectangle<int> titleBarArea (getTitleBarArea());
  62463. g.reduceClipRegion (titleBarArea);
  62464. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62465. int titleSpaceX1 = 6;
  62466. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62467. for (int i = 0; i < 3; ++i)
  62468. {
  62469. if (titleBarButtons[i] != 0)
  62470. {
  62471. if (positionTitleBarButtonsOnLeft)
  62472. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62473. else
  62474. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62475. }
  62476. }
  62477. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62478. titleBarArea.getWidth(),
  62479. titleBarArea.getHeight(),
  62480. titleSpaceX1,
  62481. jmax (1, titleSpaceX2 - titleSpaceX1),
  62482. titleBarIcon.isValid() ? &titleBarIcon : 0,
  62483. ! drawTitleTextCentred);
  62484. }
  62485. void DocumentWindow::resized()
  62486. {
  62487. ResizableWindow::resized();
  62488. if (titleBarButtons[1] != 0)
  62489. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62490. const Rectangle<int> titleBarArea (getTitleBarArea());
  62491. getLookAndFeel()
  62492. .positionDocumentWindowButtons (*this,
  62493. titleBarArea.getX(), titleBarArea.getY(),
  62494. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62495. titleBarButtons[0],
  62496. titleBarButtons[1],
  62497. titleBarButtons[2],
  62498. positionTitleBarButtonsOnLeft);
  62499. if (menuBar != 0)
  62500. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62501. titleBarArea.getWidth(), menuBarHeight);
  62502. }
  62503. const BorderSize<int> DocumentWindow::getBorderThickness()
  62504. {
  62505. return BorderSize<int> ((isFullScreen() || isUsingNativeTitleBar())
  62506. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62507. }
  62508. const BorderSize<int> DocumentWindow::getContentComponentBorder()
  62509. {
  62510. BorderSize<int> border (getBorderThickness());
  62511. border.setTop (border.getTop()
  62512. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62513. + (menuBar != 0 ? menuBarHeight : 0));
  62514. return border;
  62515. }
  62516. int DocumentWindow::getTitleBarHeight() const
  62517. {
  62518. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62519. }
  62520. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62521. {
  62522. const BorderSize<int> border (getBorderThickness());
  62523. return Rectangle<int> (border.getLeft(), border.getTop(),
  62524. getWidth() - border.getLeftAndRight(),
  62525. getTitleBarHeight());
  62526. }
  62527. Button* DocumentWindow::getCloseButton() const throw() { return titleBarButtons[2]; }
  62528. Button* DocumentWindow::getMinimiseButton() const throw() { return titleBarButtons[0]; }
  62529. Button* DocumentWindow::getMaximiseButton() const throw() { return titleBarButtons[1]; }
  62530. int DocumentWindow::getDesktopWindowStyleFlags() const
  62531. {
  62532. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62533. if ((requiredButtons & minimiseButton) != 0)
  62534. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62535. if ((requiredButtons & maximiseButton) != 0)
  62536. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62537. if ((requiredButtons & closeButton) != 0)
  62538. styleFlags |= ComponentPeer::windowHasCloseButton;
  62539. return styleFlags;
  62540. }
  62541. void DocumentWindow::lookAndFeelChanged()
  62542. {
  62543. int i;
  62544. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62545. titleBarButtons[i] = 0;
  62546. if (! isUsingNativeTitleBar())
  62547. {
  62548. LookAndFeel& lf = getLookAndFeel();
  62549. if ((requiredButtons & minimiseButton) != 0)
  62550. titleBarButtons[0] = lf.createDocumentWindowButton (minimiseButton);
  62551. if ((requiredButtons & maximiseButton) != 0)
  62552. titleBarButtons[1] = lf.createDocumentWindowButton (maximiseButton);
  62553. if ((requiredButtons & closeButton) != 0)
  62554. titleBarButtons[2] = lf.createDocumentWindowButton (closeButton);
  62555. for (i = 0; i < 3; ++i)
  62556. {
  62557. if (titleBarButtons[i] != 0)
  62558. {
  62559. if (buttonListener == 0)
  62560. buttonListener = new ButtonListenerProxy (*this);
  62561. titleBarButtons[i]->addListener (buttonListener);
  62562. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62563. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62564. Component::addAndMakeVisible (titleBarButtons[i]);
  62565. }
  62566. }
  62567. if (getCloseButton() != 0)
  62568. {
  62569. #if JUCE_MAC
  62570. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62571. #else
  62572. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  62573. #endif
  62574. }
  62575. }
  62576. activeWindowStatusChanged();
  62577. ResizableWindow::lookAndFeelChanged();
  62578. }
  62579. void DocumentWindow::parentHierarchyChanged()
  62580. {
  62581. lookAndFeelChanged();
  62582. }
  62583. void DocumentWindow::activeWindowStatusChanged()
  62584. {
  62585. ResizableWindow::activeWindowStatusChanged();
  62586. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62587. if (titleBarButtons[i] != 0)
  62588. titleBarButtons[i]->setEnabled (isActiveWindow());
  62589. if (menuBar != 0)
  62590. menuBar->setEnabled (isActiveWindow());
  62591. }
  62592. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  62593. {
  62594. if (getTitleBarArea().contains (e.x, e.y)
  62595. && getMaximiseButton() != 0)
  62596. {
  62597. getMaximiseButton()->triggerClick();
  62598. }
  62599. }
  62600. void DocumentWindow::userTriedToCloseWindow()
  62601. {
  62602. closeButtonPressed();
  62603. }
  62604. END_JUCE_NAMESPACE
  62605. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  62606. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  62607. BEGIN_JUCE_NAMESPACE
  62608. ResizableWindow::ResizableWindow (const String& name,
  62609. const bool addToDesktop_)
  62610. : TopLevelWindow (name, addToDesktop_),
  62611. resizeToFitContent (false),
  62612. fullscreen (false),
  62613. lastNonFullScreenPos (50, 50, 256, 256),
  62614. constrainer (0)
  62615. #if JUCE_DEBUG
  62616. , hasBeenResized (false)
  62617. #endif
  62618. {
  62619. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62620. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  62621. if (addToDesktop_)
  62622. Component::addToDesktop (getDesktopWindowStyleFlags());
  62623. }
  62624. ResizableWindow::ResizableWindow (const String& name,
  62625. const Colour& backgroundColour_,
  62626. const bool addToDesktop_)
  62627. : TopLevelWindow (name, addToDesktop_),
  62628. resizeToFitContent (false),
  62629. fullscreen (false),
  62630. lastNonFullScreenPos (50, 50, 256, 256),
  62631. constrainer (0)
  62632. #if JUCE_DEBUG
  62633. , hasBeenResized (false)
  62634. #endif
  62635. {
  62636. setBackgroundColour (backgroundColour_);
  62637. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62638. if (addToDesktop_)
  62639. Component::addToDesktop (getDesktopWindowStyleFlags());
  62640. }
  62641. ResizableWindow::~ResizableWindow()
  62642. {
  62643. // Don't delete or remove the resizer components yourself! They're managed by the
  62644. // ResizableWindow, and you should leave them alone! You may have deleted them
  62645. // accidentally by careless use of deleteAllChildren()..?
  62646. jassert (resizableCorner == 0 || getIndexOfChildComponent (resizableCorner) >= 0);
  62647. jassert (resizableBorder == 0 || getIndexOfChildComponent (resizableBorder) >= 0);
  62648. resizableCorner = 0;
  62649. resizableBorder = 0;
  62650. contentComponent.deleteAndZero();
  62651. // have you been adding your own components directly to this window..? tut tut tut.
  62652. // Read the instructions for using a ResizableWindow!
  62653. jassert (getNumChildComponents() == 0);
  62654. }
  62655. int ResizableWindow::getDesktopWindowStyleFlags() const
  62656. {
  62657. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  62658. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  62659. styleFlags |= ComponentPeer::windowIsResizable;
  62660. return styleFlags;
  62661. }
  62662. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  62663. const bool deleteOldOne,
  62664. const bool resizeToFit)
  62665. {
  62666. resizeToFitContent = resizeToFit;
  62667. if (newContentComponent != static_cast <Component*> (contentComponent))
  62668. {
  62669. if (deleteOldOne)
  62670. contentComponent.deleteAndZero(); // (avoid using a scoped pointer for this, so that it survives
  62671. // external deletion of the content comp)
  62672. else
  62673. removeChildComponent (contentComponent);
  62674. contentComponent = newContentComponent;
  62675. Component::addAndMakeVisible (contentComponent);
  62676. }
  62677. if (resizeToFit)
  62678. childBoundsChanged (contentComponent);
  62679. resized(); // must always be called to position the new content comp
  62680. }
  62681. void ResizableWindow::setContentComponentSize (int width, int height)
  62682. {
  62683. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  62684. const BorderSize<int> border (getContentComponentBorder());
  62685. setSize (width + border.getLeftAndRight(),
  62686. height + border.getTopAndBottom());
  62687. }
  62688. const BorderSize<int> ResizableWindow::getBorderThickness()
  62689. {
  62690. return BorderSize<int> (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  62691. }
  62692. const BorderSize<int> ResizableWindow::getContentComponentBorder()
  62693. {
  62694. return getBorderThickness();
  62695. }
  62696. void ResizableWindow::moved()
  62697. {
  62698. updateLastPos();
  62699. }
  62700. void ResizableWindow::visibilityChanged()
  62701. {
  62702. TopLevelWindow::visibilityChanged();
  62703. updateLastPos();
  62704. }
  62705. void ResizableWindow::resized()
  62706. {
  62707. if (resizableBorder != 0)
  62708. {
  62709. #if JUCE_WINDOWS || JUCE_LINUX
  62710. // hide the resizable border if the OS already provides one..
  62711. resizableBorder->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  62712. #else
  62713. resizableBorder->setVisible (! isFullScreen());
  62714. #endif
  62715. resizableBorder->setBorderThickness (getBorderThickness());
  62716. resizableBorder->setSize (getWidth(), getHeight());
  62717. resizableBorder->toBack();
  62718. }
  62719. if (resizableCorner != 0)
  62720. {
  62721. #if JUCE_MAC
  62722. // hide the resizable border if the OS already provides one..
  62723. resizableCorner->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  62724. #else
  62725. resizableCorner->setVisible (! isFullScreen());
  62726. #endif
  62727. const int resizerSize = 18;
  62728. resizableCorner->setBounds (getWidth() - resizerSize,
  62729. getHeight() - resizerSize,
  62730. resizerSize, resizerSize);
  62731. }
  62732. if (contentComponent != 0)
  62733. contentComponent->setBoundsInset (getContentComponentBorder());
  62734. updateLastPos();
  62735. #if JUCE_DEBUG
  62736. hasBeenResized = true;
  62737. #endif
  62738. }
  62739. void ResizableWindow::childBoundsChanged (Component* child)
  62740. {
  62741. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  62742. {
  62743. // not going to look very good if this component has a zero size..
  62744. jassert (child->getWidth() > 0);
  62745. jassert (child->getHeight() > 0);
  62746. const BorderSize<int> borders (getContentComponentBorder());
  62747. setSize (child->getWidth() + borders.getLeftAndRight(),
  62748. child->getHeight() + borders.getTopAndBottom());
  62749. }
  62750. }
  62751. void ResizableWindow::activeWindowStatusChanged()
  62752. {
  62753. const BorderSize<int> border (getContentComponentBorder());
  62754. Rectangle<int> area (getLocalBounds());
  62755. repaint (area.removeFromTop (border.getTop()));
  62756. repaint (area.removeFromLeft (border.getLeft()));
  62757. repaint (area.removeFromRight (border.getRight()));
  62758. repaint (area.removeFromBottom (border.getBottom()));
  62759. }
  62760. void ResizableWindow::setResizable (const bool shouldBeResizable,
  62761. const bool useBottomRightCornerResizer)
  62762. {
  62763. if (shouldBeResizable)
  62764. {
  62765. if (useBottomRightCornerResizer)
  62766. {
  62767. resizableBorder = 0;
  62768. if (resizableCorner == 0)
  62769. {
  62770. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  62771. resizableCorner->setAlwaysOnTop (true);
  62772. }
  62773. }
  62774. else
  62775. {
  62776. resizableCorner = 0;
  62777. if (resizableBorder == 0)
  62778. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  62779. }
  62780. }
  62781. else
  62782. {
  62783. resizableCorner = 0;
  62784. resizableBorder = 0;
  62785. }
  62786. if (isUsingNativeTitleBar())
  62787. recreateDesktopWindow();
  62788. childBoundsChanged (contentComponent);
  62789. resized();
  62790. }
  62791. bool ResizableWindow::isResizable() const throw()
  62792. {
  62793. return resizableCorner != 0
  62794. || resizableBorder != 0;
  62795. }
  62796. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  62797. const int newMinimumHeight,
  62798. const int newMaximumWidth,
  62799. const int newMaximumHeight) throw()
  62800. {
  62801. // if you've set up a custom constrainer then these settings won't have any effect..
  62802. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  62803. if (constrainer == 0)
  62804. setConstrainer (&defaultConstrainer);
  62805. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  62806. newMaximumWidth, newMaximumHeight);
  62807. setBoundsConstrained (getBounds());
  62808. }
  62809. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  62810. {
  62811. if (constrainer != newConstrainer)
  62812. {
  62813. constrainer = newConstrainer;
  62814. const bool useBottomRightCornerResizer = resizableCorner != 0;
  62815. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  62816. resizableCorner = 0;
  62817. resizableBorder = 0;
  62818. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62819. ComponentPeer* const peer = getPeer();
  62820. if (peer != 0)
  62821. peer->setConstrainer (newConstrainer);
  62822. }
  62823. }
  62824. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  62825. {
  62826. if (constrainer != 0)
  62827. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  62828. else
  62829. setBounds (bounds);
  62830. }
  62831. void ResizableWindow::paint (Graphics& g)
  62832. {
  62833. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  62834. getBorderThickness(), *this);
  62835. if (! isFullScreen())
  62836. {
  62837. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  62838. getBorderThickness(), *this);
  62839. }
  62840. #if JUCE_DEBUG
  62841. /* If this fails, then you've probably written a subclass with a resized()
  62842. callback but forgotten to make it call its parent class's resized() method.
  62843. It's important when you override methods like resized(), moved(),
  62844. etc., that you make sure the base class methods also get called.
  62845. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  62846. because your content should all be inside the content component - and it's the
  62847. content component's resized() method that you should be using to do your
  62848. layout.
  62849. */
  62850. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  62851. #endif
  62852. }
  62853. void ResizableWindow::lookAndFeelChanged()
  62854. {
  62855. resized();
  62856. if (isOnDesktop())
  62857. {
  62858. Component::addToDesktop (getDesktopWindowStyleFlags());
  62859. ComponentPeer* const peer = getPeer();
  62860. if (peer != 0)
  62861. peer->setConstrainer (constrainer);
  62862. }
  62863. }
  62864. const Colour ResizableWindow::getBackgroundColour() const throw()
  62865. {
  62866. return findColour (backgroundColourId, false);
  62867. }
  62868. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  62869. {
  62870. Colour backgroundColour (newColour);
  62871. if (! Desktop::canUseSemiTransparentWindows())
  62872. backgroundColour = newColour.withAlpha (1.0f);
  62873. setColour (backgroundColourId, backgroundColour);
  62874. setOpaque (backgroundColour.isOpaque());
  62875. repaint();
  62876. }
  62877. bool ResizableWindow::isFullScreen() const
  62878. {
  62879. if (isOnDesktop())
  62880. {
  62881. ComponentPeer* const peer = getPeer();
  62882. return peer != 0 && peer->isFullScreen();
  62883. }
  62884. return fullscreen;
  62885. }
  62886. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  62887. {
  62888. if (shouldBeFullScreen != isFullScreen())
  62889. {
  62890. updateLastPos();
  62891. fullscreen = shouldBeFullScreen;
  62892. if (isOnDesktop())
  62893. {
  62894. ComponentPeer* const peer = getPeer();
  62895. if (peer != 0)
  62896. {
  62897. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  62898. const Rectangle<int> lastPos (lastNonFullScreenPos);
  62899. peer->setFullScreen (shouldBeFullScreen);
  62900. if ((! shouldBeFullScreen) && ! lastPos.isEmpty())
  62901. setBounds (lastPos);
  62902. }
  62903. else
  62904. {
  62905. jassertfalse;
  62906. }
  62907. }
  62908. else
  62909. {
  62910. if (shouldBeFullScreen)
  62911. setBounds (0, 0, getParentWidth(), getParentHeight());
  62912. else
  62913. setBounds (lastNonFullScreenPos);
  62914. }
  62915. resized();
  62916. }
  62917. }
  62918. bool ResizableWindow::isMinimised() const
  62919. {
  62920. ComponentPeer* const peer = getPeer();
  62921. return (peer != 0) && peer->isMinimised();
  62922. }
  62923. void ResizableWindow::setMinimised (const bool shouldMinimise)
  62924. {
  62925. if (shouldMinimise != isMinimised())
  62926. {
  62927. ComponentPeer* const peer = getPeer();
  62928. if (peer != 0)
  62929. {
  62930. updateLastPos();
  62931. peer->setMinimised (shouldMinimise);
  62932. }
  62933. else
  62934. {
  62935. jassertfalse;
  62936. }
  62937. }
  62938. }
  62939. void ResizableWindow::updateLastPos()
  62940. {
  62941. if (isShowing() && ! (isFullScreen() || isMinimised()))
  62942. {
  62943. lastNonFullScreenPos = getBounds();
  62944. }
  62945. }
  62946. void ResizableWindow::parentSizeChanged()
  62947. {
  62948. if (isFullScreen() && getParentComponent() != 0)
  62949. {
  62950. setBounds (0, 0, getParentWidth(), getParentHeight());
  62951. }
  62952. }
  62953. const String ResizableWindow::getWindowStateAsString()
  62954. {
  62955. updateLastPos();
  62956. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  62957. }
  62958. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  62959. {
  62960. StringArray tokens;
  62961. tokens.addTokens (s, false);
  62962. tokens.removeEmptyStrings();
  62963. tokens.trim();
  62964. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  62965. const int firstCoord = fs ? 1 : 0;
  62966. if (tokens.size() != firstCoord + 4)
  62967. return false;
  62968. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  62969. tokens[firstCoord + 1].getIntValue(),
  62970. tokens[firstCoord + 2].getIntValue(),
  62971. tokens[firstCoord + 3].getIntValue());
  62972. if (newPos.isEmpty())
  62973. return false;
  62974. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  62975. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  62976. if (peer != 0)
  62977. peer->getFrameSize().addTo (newPos);
  62978. if (! screen.contains (newPos))
  62979. {
  62980. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  62981. jmin (newPos.getHeight(), screen.getHeight()));
  62982. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  62983. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  62984. }
  62985. if (peer != 0)
  62986. {
  62987. peer->getFrameSize().subtractFrom (newPos);
  62988. peer->setNonFullScreenBounds (newPos);
  62989. }
  62990. lastNonFullScreenPos = newPos;
  62991. setFullScreen (fs);
  62992. if (! fs)
  62993. setBoundsConstrained (newPos);
  62994. return true;
  62995. }
  62996. void ResizableWindow::mouseDown (const MouseEvent& e)
  62997. {
  62998. if (! isFullScreen())
  62999. dragger.startDraggingComponent (this, e);
  63000. }
  63001. void ResizableWindow::mouseDrag (const MouseEvent& e)
  63002. {
  63003. if (! isFullScreen())
  63004. dragger.dragComponent (this, e, constrainer);
  63005. }
  63006. #if JUCE_DEBUG
  63007. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  63008. {
  63009. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63010. manages its child components automatically, and if you add your own it'll cause
  63011. trouble. Instead, use setContentComponent() to give it a component which
  63012. will be automatically resized and kept in the right place - then you can add
  63013. subcomponents to the content comp. See the notes for the ResizableWindow class
  63014. for more info.
  63015. If you really know what you're doing and want to avoid this assertion, just call
  63016. Component::addChildComponent directly.
  63017. */
  63018. jassertfalse;
  63019. Component::addChildComponent (child, zOrder);
  63020. }
  63021. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63022. {
  63023. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63024. manages its child components automatically, and if you add your own it'll cause
  63025. trouble. Instead, use setContentComponent() to give it a component which
  63026. will be automatically resized and kept in the right place - then you can add
  63027. subcomponents to the content comp. See the notes for the ResizableWindow class
  63028. for more info.
  63029. If you really know what you're doing and want to avoid this assertion, just call
  63030. Component::addAndMakeVisible directly.
  63031. */
  63032. jassertfalse;
  63033. Component::addAndMakeVisible (child, zOrder);
  63034. }
  63035. #endif
  63036. END_JUCE_NAMESPACE
  63037. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63038. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63039. BEGIN_JUCE_NAMESPACE
  63040. SplashScreen::SplashScreen()
  63041. {
  63042. setOpaque (true);
  63043. }
  63044. SplashScreen::~SplashScreen()
  63045. {
  63046. }
  63047. void SplashScreen::show (const String& title,
  63048. const Image& backgroundImage_,
  63049. const int minimumTimeToDisplayFor,
  63050. const bool useDropShadow,
  63051. const bool removeOnMouseClick)
  63052. {
  63053. backgroundImage = backgroundImage_;
  63054. jassert (backgroundImage_.isValid());
  63055. if (backgroundImage_.isValid())
  63056. {
  63057. setOpaque (! backgroundImage_.hasAlphaChannel());
  63058. show (title,
  63059. backgroundImage_.getWidth(),
  63060. backgroundImage_.getHeight(),
  63061. minimumTimeToDisplayFor,
  63062. useDropShadow,
  63063. removeOnMouseClick);
  63064. }
  63065. }
  63066. void SplashScreen::show (const String& title,
  63067. const int width,
  63068. const int height,
  63069. const int minimumTimeToDisplayFor,
  63070. const bool useDropShadow,
  63071. const bool removeOnMouseClick)
  63072. {
  63073. setName (title);
  63074. setAlwaysOnTop (true);
  63075. setVisible (true);
  63076. centreWithSize (width, height);
  63077. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63078. toFront (false);
  63079. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63080. repaint();
  63081. originalClickCounter = removeOnMouseClick
  63082. ? Desktop::getMouseButtonClickCounter()
  63083. : std::numeric_limits<int>::max();
  63084. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63085. startTimer (50);
  63086. }
  63087. void SplashScreen::paint (Graphics& g)
  63088. {
  63089. g.setOpacity (1.0f);
  63090. g.drawImage (backgroundImage,
  63091. 0, 0, getWidth(), getHeight(),
  63092. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63093. }
  63094. void SplashScreen::timerCallback()
  63095. {
  63096. if (Time::getCurrentTime() > earliestTimeToDelete
  63097. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63098. {
  63099. delete this;
  63100. }
  63101. }
  63102. END_JUCE_NAMESPACE
  63103. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63104. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63105. BEGIN_JUCE_NAMESPACE
  63106. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63107. const bool hasProgressBar,
  63108. const bool hasCancelButton,
  63109. const int timeOutMsWhenCancelling_,
  63110. const String& cancelButtonText)
  63111. : Thread ("Juce Progress Window"),
  63112. progress (0.0),
  63113. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63114. {
  63115. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63116. .createAlertWindow (title, String::empty, cancelButtonText,
  63117. String::empty, String::empty,
  63118. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63119. if (hasProgressBar)
  63120. alertWindow->addProgressBarComponent (progress);
  63121. }
  63122. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63123. {
  63124. stopThread (timeOutMsWhenCancelling);
  63125. }
  63126. bool ThreadWithProgressWindow::runThread (const int priority)
  63127. {
  63128. startThread (priority);
  63129. startTimer (100);
  63130. {
  63131. const ScopedLock sl (messageLock);
  63132. alertWindow->setMessage (message);
  63133. }
  63134. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63135. stopThread (timeOutMsWhenCancelling);
  63136. alertWindow->setVisible (false);
  63137. return finishedNaturally;
  63138. }
  63139. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63140. {
  63141. progress = newProgress;
  63142. }
  63143. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63144. {
  63145. const ScopedLock sl (messageLock);
  63146. message = newStatusMessage;
  63147. }
  63148. void ThreadWithProgressWindow::timerCallback()
  63149. {
  63150. if (! isThreadRunning())
  63151. {
  63152. // thread has finished normally..
  63153. alertWindow->exitModalState (1);
  63154. alertWindow->setVisible (false);
  63155. }
  63156. else
  63157. {
  63158. const ScopedLock sl (messageLock);
  63159. alertWindow->setMessage (message);
  63160. }
  63161. }
  63162. END_JUCE_NAMESPACE
  63163. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63164. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63165. BEGIN_JUCE_NAMESPACE
  63166. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63167. const int millisecondsBeforeTipAppears_)
  63168. : Component ("tooltip"),
  63169. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63170. mouseClicks (0),
  63171. lastHideTime (0),
  63172. lastComponentUnderMouse (0),
  63173. changedCompsSinceShown (true)
  63174. {
  63175. if (Desktop::getInstance().getMainMouseSource().canHover())
  63176. startTimer (123);
  63177. setAlwaysOnTop (true);
  63178. setOpaque (true);
  63179. if (parentComponent != 0)
  63180. parentComponent->addChildComponent (this);
  63181. }
  63182. TooltipWindow::~TooltipWindow()
  63183. {
  63184. hide();
  63185. }
  63186. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63187. {
  63188. millisecondsBeforeTipAppears = newTimeMs;
  63189. }
  63190. void TooltipWindow::paint (Graphics& g)
  63191. {
  63192. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63193. }
  63194. void TooltipWindow::mouseEnter (const MouseEvent&)
  63195. {
  63196. hide();
  63197. }
  63198. void TooltipWindow::showFor (const String& tip)
  63199. {
  63200. jassert (tip.isNotEmpty());
  63201. if (tipShowing != tip)
  63202. repaint();
  63203. tipShowing = tip;
  63204. Point<int> mousePos (Desktop::getMousePosition());
  63205. if (getParentComponent() != 0)
  63206. mousePos = getParentComponent()->getLocalPoint (0, mousePos);
  63207. int x, y, w, h;
  63208. getLookAndFeel().getTooltipSize (tip, w, h);
  63209. if (mousePos.getX() > getParentWidth() / 2)
  63210. x = mousePos.getX() - (w + 12);
  63211. else
  63212. x = mousePos.getX() + 24;
  63213. if (mousePos.getY() > getParentHeight() / 2)
  63214. y = mousePos.getY() - (h + 6);
  63215. else
  63216. y = mousePos.getY() + 6;
  63217. setBounds (x, y, w, h);
  63218. setVisible (true);
  63219. if (getParentComponent() == 0)
  63220. {
  63221. addToDesktop (ComponentPeer::windowHasDropShadow
  63222. | ComponentPeer::windowIsTemporary
  63223. | ComponentPeer::windowIgnoresKeyPresses);
  63224. }
  63225. toFront (false);
  63226. }
  63227. const String TooltipWindow::getTipFor (Component* const c)
  63228. {
  63229. if (c != 0
  63230. && Process::isForegroundProcess()
  63231. && ! Component::isMouseButtonDownAnywhere())
  63232. {
  63233. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63234. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63235. return ttc->getTooltip();
  63236. }
  63237. return String::empty;
  63238. }
  63239. void TooltipWindow::hide()
  63240. {
  63241. tipShowing = String::empty;
  63242. removeFromDesktop();
  63243. setVisible (false);
  63244. }
  63245. void TooltipWindow::timerCallback()
  63246. {
  63247. const unsigned int now = Time::getApproximateMillisecondCounter();
  63248. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63249. const String newTip (getTipFor (newComp));
  63250. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63251. lastComponentUnderMouse = newComp;
  63252. lastTipUnderMouse = newTip;
  63253. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63254. const bool mouseWasClicked = clickCount > mouseClicks;
  63255. mouseClicks = clickCount;
  63256. const Point<int> mousePos (Desktop::getMousePosition());
  63257. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63258. lastMousePos = mousePos;
  63259. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63260. lastCompChangeTime = now;
  63261. if (isVisible() || now < lastHideTime + 500)
  63262. {
  63263. // if a tip is currently visible (or has just disappeared), update to a new one
  63264. // immediately if needed..
  63265. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63266. {
  63267. if (isVisible())
  63268. {
  63269. lastHideTime = now;
  63270. hide();
  63271. }
  63272. }
  63273. else if (tipChanged)
  63274. {
  63275. showFor (newTip);
  63276. }
  63277. }
  63278. else
  63279. {
  63280. // if there isn't currently a tip, but one is needed, only let it
  63281. // appear after a timeout..
  63282. if (newTip.isNotEmpty()
  63283. && newTip != tipShowing
  63284. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  63285. {
  63286. showFor (newTip);
  63287. }
  63288. }
  63289. }
  63290. END_JUCE_NAMESPACE
  63291. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  63292. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  63293. BEGIN_JUCE_NAMESPACE
  63294. /** Keeps track of the active top level window.
  63295. */
  63296. class TopLevelWindowManager : public Timer,
  63297. public DeletedAtShutdown
  63298. {
  63299. public:
  63300. TopLevelWindowManager()
  63301. : currentActive (0)
  63302. {
  63303. }
  63304. ~TopLevelWindowManager()
  63305. {
  63306. clearSingletonInstance();
  63307. }
  63308. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  63309. void timerCallback()
  63310. {
  63311. startTimer (jmin (1731, getTimerInterval() * 2));
  63312. TopLevelWindow* active = 0;
  63313. if (Process::isForegroundProcess())
  63314. {
  63315. active = currentActive;
  63316. Component* const c = Component::getCurrentlyFocusedComponent();
  63317. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  63318. if (tlw == 0 && c != 0)
  63319. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  63320. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  63321. if (tlw != 0)
  63322. active = tlw;
  63323. }
  63324. if (active != currentActive)
  63325. {
  63326. currentActive = active;
  63327. for (int i = windows.size(); --i >= 0;)
  63328. {
  63329. TopLevelWindow* const tlw = windows.getUnchecked (i);
  63330. tlw->setWindowActive (isWindowActive (tlw));
  63331. i = jmin (i, windows.size() - 1);
  63332. }
  63333. Desktop::getInstance().triggerFocusCallback();
  63334. }
  63335. }
  63336. bool addWindow (TopLevelWindow* const w)
  63337. {
  63338. windows.add (w);
  63339. startTimer (10);
  63340. return isWindowActive (w);
  63341. }
  63342. void removeWindow (TopLevelWindow* const w)
  63343. {
  63344. startTimer (10);
  63345. if (currentActive == w)
  63346. currentActive = 0;
  63347. windows.removeValue (w);
  63348. if (windows.size() == 0)
  63349. deleteInstance();
  63350. }
  63351. Array <TopLevelWindow*> windows;
  63352. private:
  63353. TopLevelWindow* currentActive;
  63354. bool isWindowActive (TopLevelWindow* const tlw) const
  63355. {
  63356. return (tlw == currentActive
  63357. || tlw->isParentOf (currentActive)
  63358. || tlw->hasKeyboardFocus (true))
  63359. && tlw->isShowing();
  63360. }
  63361. JUCE_DECLARE_NON_COPYABLE (TopLevelWindowManager);
  63362. };
  63363. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  63364. void juce_CheckCurrentlyFocusedTopLevelWindow()
  63365. {
  63366. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  63367. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  63368. }
  63369. TopLevelWindow::TopLevelWindow (const String& name,
  63370. const bool addToDesktop_)
  63371. : Component (name),
  63372. useDropShadow (true),
  63373. useNativeTitleBar (false),
  63374. windowIsActive_ (false)
  63375. {
  63376. setOpaque (true);
  63377. if (addToDesktop_)
  63378. Component::addToDesktop (getDesktopWindowStyleFlags());
  63379. else
  63380. setDropShadowEnabled (true);
  63381. setWantsKeyboardFocus (true);
  63382. setBroughtToFrontOnMouseClick (true);
  63383. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  63384. }
  63385. TopLevelWindow::~TopLevelWindow()
  63386. {
  63387. shadower = 0;
  63388. TopLevelWindowManager::getInstance()->removeWindow (this);
  63389. }
  63390. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  63391. {
  63392. if (hasKeyboardFocus (true))
  63393. TopLevelWindowManager::getInstance()->timerCallback();
  63394. else
  63395. TopLevelWindowManager::getInstance()->startTimer (10);
  63396. }
  63397. void TopLevelWindow::setWindowActive (const bool isNowActive)
  63398. {
  63399. if (windowIsActive_ != isNowActive)
  63400. {
  63401. windowIsActive_ = isNowActive;
  63402. activeWindowStatusChanged();
  63403. }
  63404. }
  63405. void TopLevelWindow::activeWindowStatusChanged()
  63406. {
  63407. }
  63408. void TopLevelWindow::visibilityChanged()
  63409. {
  63410. if (isShowing()
  63411. && (getPeer()->getStyleFlags() & (ComponentPeer::windowIsTemporary
  63412. | ComponentPeer::windowIgnoresKeyPresses)) == 0)
  63413. {
  63414. toFront (true);
  63415. }
  63416. }
  63417. void TopLevelWindow::parentHierarchyChanged()
  63418. {
  63419. setDropShadowEnabled (useDropShadow);
  63420. }
  63421. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63422. {
  63423. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63424. if (useDropShadow)
  63425. styleFlags |= ComponentPeer::windowHasDropShadow;
  63426. if (useNativeTitleBar)
  63427. styleFlags |= ComponentPeer::windowHasTitleBar;
  63428. return styleFlags;
  63429. }
  63430. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63431. {
  63432. useDropShadow = useShadow;
  63433. if (isOnDesktop())
  63434. {
  63435. shadower = 0;
  63436. Component::addToDesktop (getDesktopWindowStyleFlags());
  63437. }
  63438. else
  63439. {
  63440. if (useShadow && isOpaque())
  63441. {
  63442. if (shadower == 0)
  63443. {
  63444. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63445. if (shadower != 0)
  63446. shadower->setOwner (this);
  63447. }
  63448. }
  63449. else
  63450. {
  63451. shadower = 0;
  63452. }
  63453. }
  63454. }
  63455. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63456. {
  63457. if (useNativeTitleBar != useNativeTitleBar_)
  63458. {
  63459. useNativeTitleBar = useNativeTitleBar_;
  63460. recreateDesktopWindow();
  63461. sendLookAndFeelChange();
  63462. }
  63463. }
  63464. void TopLevelWindow::recreateDesktopWindow()
  63465. {
  63466. if (isOnDesktop())
  63467. {
  63468. Component::addToDesktop (getDesktopWindowStyleFlags());
  63469. toFront (true);
  63470. }
  63471. }
  63472. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63473. {
  63474. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63475. because this class needs to make sure its layout corresponds with settings like whether
  63476. it's got a native title bar or not.
  63477. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63478. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63479. method, then add or remove whatever flags are necessary from this value before returning it.
  63480. */
  63481. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63482. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63483. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63484. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63485. sendLookAndFeelChange();
  63486. }
  63487. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63488. {
  63489. if (c == 0)
  63490. c = TopLevelWindow::getActiveTopLevelWindow();
  63491. if (c == 0)
  63492. {
  63493. centreWithSize (width, height);
  63494. }
  63495. else
  63496. {
  63497. Point<int> targetCentre (c->localPointToGlobal (c->getLocalBounds().getCentre()));
  63498. Rectangle<int> parentArea (c->getParentMonitorArea());
  63499. if (getParentComponent() != 0)
  63500. {
  63501. targetCentre = getParentComponent()->getLocalPoint (0, targetCentre);
  63502. parentArea = getParentComponent()->getLocalBounds();
  63503. }
  63504. parentArea.reduce (12, 12);
  63505. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), targetCentre.getX() - width / 2),
  63506. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), targetCentre.getY() - height / 2),
  63507. width, height);
  63508. }
  63509. }
  63510. int TopLevelWindow::getNumTopLevelWindows() throw()
  63511. {
  63512. return TopLevelWindowManager::getInstance()->windows.size();
  63513. }
  63514. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63515. {
  63516. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63517. }
  63518. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63519. {
  63520. TopLevelWindow* best = 0;
  63521. int bestNumTWLParents = -1;
  63522. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63523. {
  63524. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63525. if (tlw->isActiveWindow())
  63526. {
  63527. int numTWLParents = 0;
  63528. const Component* c = tlw->getParentComponent();
  63529. while (c != 0)
  63530. {
  63531. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63532. ++numTWLParents;
  63533. c = c->getParentComponent();
  63534. }
  63535. if (bestNumTWLParents < numTWLParents)
  63536. {
  63537. best = tlw;
  63538. bestNumTWLParents = numTWLParents;
  63539. }
  63540. }
  63541. }
  63542. return best;
  63543. }
  63544. END_JUCE_NAMESPACE
  63545. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  63546. /*** Start of inlined file: juce_MarkerList.cpp ***/
  63547. BEGIN_JUCE_NAMESPACE
  63548. MarkerList::MarkerList()
  63549. {
  63550. }
  63551. MarkerList::MarkerList (const MarkerList& other)
  63552. {
  63553. operator= (other);
  63554. }
  63555. MarkerList& MarkerList::operator= (const MarkerList& other)
  63556. {
  63557. if (other != *this)
  63558. {
  63559. markers.clear();
  63560. markers.addCopiesOf (other.markers);
  63561. markersHaveChanged();
  63562. }
  63563. return *this;
  63564. }
  63565. MarkerList::~MarkerList()
  63566. {
  63567. listeners.call (&MarkerList::Listener::markerListBeingDeleted, this);
  63568. }
  63569. bool MarkerList::operator== (const MarkerList& other) const throw()
  63570. {
  63571. if (other.markers.size() != markers.size())
  63572. return false;
  63573. for (int i = markers.size(); --i >= 0;)
  63574. {
  63575. const Marker* const m1 = markers.getUnchecked(i);
  63576. jassert (m1 != 0);
  63577. const Marker* const m2 = other.getMarker (m1->name);
  63578. if (m2 == 0 || *m1 != *m2)
  63579. return false;
  63580. }
  63581. return true;
  63582. }
  63583. bool MarkerList::operator!= (const MarkerList& other) const throw()
  63584. {
  63585. return ! operator== (other);
  63586. }
  63587. int MarkerList::getNumMarkers() const throw()
  63588. {
  63589. return markers.size();
  63590. }
  63591. const MarkerList::Marker* MarkerList::getMarker (const int index) const throw()
  63592. {
  63593. return markers [index];
  63594. }
  63595. const MarkerList::Marker* MarkerList::getMarker (const String& name) const throw()
  63596. {
  63597. for (int i = 0; i < markers.size(); ++i)
  63598. {
  63599. const Marker* const m = markers.getUnchecked(i);
  63600. if (m->name == name)
  63601. return m;
  63602. }
  63603. return 0;
  63604. }
  63605. void MarkerList::setMarker (const String& name, const RelativeCoordinate& position)
  63606. {
  63607. Marker* const m = const_cast <Marker*> (getMarker (name));
  63608. if (m != 0)
  63609. {
  63610. if (m->position != position)
  63611. {
  63612. m->position = position;
  63613. markersHaveChanged();
  63614. }
  63615. return;
  63616. }
  63617. markers.add (new Marker (name, position));
  63618. markersHaveChanged();
  63619. }
  63620. void MarkerList::removeMarker (const int index)
  63621. {
  63622. if (isPositiveAndBelow (index, markers.size()))
  63623. {
  63624. markers.remove (index);
  63625. markersHaveChanged();
  63626. }
  63627. }
  63628. void MarkerList::removeMarker (const String& name)
  63629. {
  63630. for (int i = 0; i < markers.size(); ++i)
  63631. {
  63632. const Marker* const m = markers.getUnchecked(i);
  63633. if (m->name == name)
  63634. {
  63635. markers.remove (i);
  63636. markersHaveChanged();
  63637. }
  63638. }
  63639. }
  63640. void MarkerList::markersHaveChanged()
  63641. {
  63642. listeners.call (&MarkerList::Listener::markersChanged, this);
  63643. }
  63644. void MarkerList::Listener::markerListBeingDeleted (MarkerList*)
  63645. {
  63646. }
  63647. void MarkerList::addListener (Listener* listener)
  63648. {
  63649. listeners.add (listener);
  63650. }
  63651. void MarkerList::removeListener (Listener* listener)
  63652. {
  63653. listeners.remove (listener);
  63654. }
  63655. MarkerList::Marker::Marker (const Marker& other)
  63656. : name (other.name), position (other.position)
  63657. {
  63658. }
  63659. MarkerList::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  63660. : name (name_), position (position_)
  63661. {
  63662. }
  63663. bool MarkerList::Marker::operator== (const Marker& other) const throw()
  63664. {
  63665. return name == other.name && position == other.position;
  63666. }
  63667. bool MarkerList::Marker::operator!= (const Marker& other) const throw()
  63668. {
  63669. return ! operator== (other);
  63670. }
  63671. const Identifier MarkerList::ValueTreeWrapper::markerTag ("Marker");
  63672. const Identifier MarkerList::ValueTreeWrapper::nameProperty ("name");
  63673. const Identifier MarkerList::ValueTreeWrapper::posProperty ("position");
  63674. MarkerList::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  63675. : state (state_)
  63676. {
  63677. }
  63678. int MarkerList::ValueTreeWrapper::getNumMarkers() const
  63679. {
  63680. return state.getNumChildren();
  63681. }
  63682. const ValueTree MarkerList::ValueTreeWrapper::getMarkerState (int index) const
  63683. {
  63684. return state.getChild (index);
  63685. }
  63686. const ValueTree MarkerList::ValueTreeWrapper::getMarkerState (const String& name) const
  63687. {
  63688. return state.getChildWithProperty (nameProperty, name);
  63689. }
  63690. bool MarkerList::ValueTreeWrapper::containsMarker (const ValueTree& marker) const
  63691. {
  63692. return marker.isAChildOf (state);
  63693. }
  63694. const MarkerList::Marker MarkerList::ValueTreeWrapper::getMarker (const ValueTree& marker) const
  63695. {
  63696. jassert (containsMarker (marker));
  63697. return MarkerList::Marker (marker [nameProperty], RelativeCoordinate (marker [posProperty].toString()));
  63698. }
  63699. void MarkerList::ValueTreeWrapper::setMarker (const MarkerList::Marker& m, UndoManager* undoManager)
  63700. {
  63701. ValueTree marker (state.getChildWithProperty (nameProperty, m.name));
  63702. if (marker.isValid())
  63703. {
  63704. marker.setProperty (posProperty, m.position.toString(), undoManager);
  63705. }
  63706. else
  63707. {
  63708. marker = ValueTree (markerTag);
  63709. marker.setProperty (nameProperty, m.name, 0);
  63710. marker.setProperty (posProperty, m.position.toString(), 0);
  63711. state.addChild (marker, -1, undoManager);
  63712. }
  63713. }
  63714. void MarkerList::ValueTreeWrapper::removeMarker (const ValueTree& marker, UndoManager* undoManager)
  63715. {
  63716. state.removeChild (marker, undoManager);
  63717. }
  63718. double MarkerList::getMarkerPosition (const Marker& marker, Component* parentComponent) const
  63719. {
  63720. if (parentComponent != 0)
  63721. {
  63722. RelativeCoordinatePositionerBase::ComponentScope scope (*parentComponent);
  63723. return marker.position.resolve (&scope);
  63724. }
  63725. else
  63726. {
  63727. return marker.position.resolve (0);
  63728. }
  63729. }
  63730. void MarkerList::ValueTreeWrapper::applyTo (MarkerList& markerList)
  63731. {
  63732. const int numMarkers = getNumMarkers();
  63733. StringArray updatedMarkers;
  63734. int i;
  63735. for (i = 0; i < numMarkers; ++i)
  63736. {
  63737. const ValueTree marker (state.getChild (i));
  63738. const String name (marker [nameProperty].toString());
  63739. markerList.setMarker (name, RelativeCoordinate (marker [posProperty].toString()));
  63740. updatedMarkers.add (name);
  63741. }
  63742. for (i = markerList.getNumMarkers(); --i >= 0;)
  63743. if (! updatedMarkers.contains (markerList.getMarker (i)->name))
  63744. markerList.removeMarker (i);
  63745. }
  63746. void MarkerList::ValueTreeWrapper::readFrom (const MarkerList& markerList, UndoManager* undoManager)
  63747. {
  63748. state.removeAllChildren (undoManager);
  63749. for (int i = 0; i < markerList.getNumMarkers(); ++i)
  63750. setMarker (*markerList.getMarker(i), undoManager);
  63751. }
  63752. END_JUCE_NAMESPACE
  63753. /*** End of inlined file: juce_MarkerList.cpp ***/
  63754. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  63755. BEGIN_JUCE_NAMESPACE
  63756. const String RelativeCoordinate::Strings::parent ("parent");
  63757. const String RelativeCoordinate::Strings::left ("left");
  63758. const String RelativeCoordinate::Strings::right ("right");
  63759. const String RelativeCoordinate::Strings::top ("top");
  63760. const String RelativeCoordinate::Strings::bottom ("bottom");
  63761. const String RelativeCoordinate::Strings::x ("x");
  63762. const String RelativeCoordinate::Strings::y ("y");
  63763. const String RelativeCoordinate::Strings::width ("width");
  63764. const String RelativeCoordinate::Strings::height ("height");
  63765. RelativeCoordinate::StandardStrings::Type RelativeCoordinate::StandardStrings::getTypeOf (const String& s) throw()
  63766. {
  63767. if (s == Strings::left) return left;
  63768. if (s == Strings::right) return right;
  63769. if (s == Strings::top) return top;
  63770. if (s == Strings::bottom) return bottom;
  63771. if (s == Strings::x) return x;
  63772. if (s == Strings::y) return y;
  63773. if (s == Strings::width) return width;
  63774. if (s == Strings::height) return height;
  63775. if (s == Strings::parent) return parent;
  63776. return unknown;
  63777. }
  63778. RelativeCoordinate::RelativeCoordinate()
  63779. {
  63780. }
  63781. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  63782. : term (term_)
  63783. {
  63784. }
  63785. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  63786. : term (other.term)
  63787. {
  63788. }
  63789. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  63790. {
  63791. term = other.term;
  63792. return *this;
  63793. }
  63794. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  63795. : term (absoluteDistanceFromOrigin)
  63796. {
  63797. }
  63798. RelativeCoordinate::RelativeCoordinate (const String& s)
  63799. {
  63800. try
  63801. {
  63802. term = Expression (s);
  63803. }
  63804. catch (...)
  63805. {}
  63806. }
  63807. RelativeCoordinate::~RelativeCoordinate()
  63808. {
  63809. }
  63810. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  63811. {
  63812. return term.toString() == other.term.toString();
  63813. }
  63814. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  63815. {
  63816. return ! operator== (other);
  63817. }
  63818. double RelativeCoordinate::resolve (const Expression::Scope* scope) const
  63819. {
  63820. try
  63821. {
  63822. if (scope != 0)
  63823. return term.evaluate (*scope);
  63824. else
  63825. return term.evaluate();
  63826. }
  63827. catch (...)
  63828. {}
  63829. return 0.0;
  63830. }
  63831. bool RelativeCoordinate::isRecursive (const Expression::Scope* scope) const
  63832. {
  63833. try
  63834. {
  63835. if (scope != 0)
  63836. term.evaluate (*scope);
  63837. else
  63838. term.evaluate();
  63839. }
  63840. catch (...)
  63841. {
  63842. return true;
  63843. }
  63844. return false;
  63845. }
  63846. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::Scope* scope)
  63847. {
  63848. try
  63849. {
  63850. if (scope != 0)
  63851. {
  63852. term = term.adjustedToGiveNewResult (newPos, *scope);
  63853. }
  63854. else
  63855. {
  63856. Expression::Scope defaultScope;
  63857. term = term.adjustedToGiveNewResult (newPos, defaultScope);
  63858. }
  63859. }
  63860. catch (...)
  63861. {}
  63862. }
  63863. bool RelativeCoordinate::isDynamic() const
  63864. {
  63865. return term.usesAnySymbols();
  63866. }
  63867. const String RelativeCoordinate::toString() const
  63868. {
  63869. return term.toString();
  63870. }
  63871. END_JUCE_NAMESPACE
  63872. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  63873. /*** Start of inlined file: juce_RelativePoint.cpp ***/
  63874. BEGIN_JUCE_NAMESPACE
  63875. namespace RelativePointHelpers
  63876. {
  63877. inline void skipComma (String::CharPointerType& s)
  63878. {
  63879. s = s.findEndOfWhitespace();
  63880. if (*s == ',')
  63881. ++s;
  63882. }
  63883. }
  63884. RelativePoint::RelativePoint()
  63885. {
  63886. }
  63887. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  63888. : x (absolutePoint.getX()), y (absolutePoint.getY())
  63889. {
  63890. }
  63891. RelativePoint::RelativePoint (const float x_, const float y_)
  63892. : x (x_), y (y_)
  63893. {
  63894. }
  63895. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  63896. : x (x_), y (y_)
  63897. {
  63898. }
  63899. RelativePoint::RelativePoint (const String& s)
  63900. {
  63901. String::CharPointerType text (s.getCharPointer());
  63902. x = RelativeCoordinate (Expression::parse (text));
  63903. RelativePointHelpers::skipComma (text);
  63904. y = RelativeCoordinate (Expression::parse (text));
  63905. }
  63906. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  63907. {
  63908. return x == other.x && y == other.y;
  63909. }
  63910. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  63911. {
  63912. return ! operator== (other);
  63913. }
  63914. const Point<float> RelativePoint::resolve (const Expression::Scope* scope) const
  63915. {
  63916. return Point<float> ((float) x.resolve (scope),
  63917. (float) y.resolve (scope));
  63918. }
  63919. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::Scope* scope)
  63920. {
  63921. x.moveToAbsolute (newPos.getX(), scope);
  63922. y.moveToAbsolute (newPos.getY(), scope);
  63923. }
  63924. const String RelativePoint::toString() const
  63925. {
  63926. return x.toString() + ", " + y.toString();
  63927. }
  63928. bool RelativePoint::isDynamic() const
  63929. {
  63930. return x.isDynamic() || y.isDynamic();
  63931. }
  63932. END_JUCE_NAMESPACE
  63933. /*** End of inlined file: juce_RelativePoint.cpp ***/
  63934. /*** Start of inlined file: juce_RelativeRectangle.cpp ***/
  63935. BEGIN_JUCE_NAMESPACE
  63936. namespace RelativeRectangleHelpers
  63937. {
  63938. inline void skipComma (String::CharPointerType& s)
  63939. {
  63940. s = s.findEndOfWhitespace();
  63941. if (*s == ',')
  63942. ++s;
  63943. }
  63944. bool dependsOnSymbolsOtherThanThis (const Expression& e)
  63945. {
  63946. if (e.getType() == Expression::operatorType && e.getSymbolOrFunction() == ".")
  63947. return true;
  63948. if (e.getType() == Expression::symbolType)
  63949. {
  63950. switch (RelativeCoordinate::StandardStrings::getTypeOf (e.getSymbolOrFunction()))
  63951. {
  63952. case RelativeCoordinate::StandardStrings::x:
  63953. case RelativeCoordinate::StandardStrings::y:
  63954. case RelativeCoordinate::StandardStrings::left:
  63955. case RelativeCoordinate::StandardStrings::right:
  63956. case RelativeCoordinate::StandardStrings::top:
  63957. case RelativeCoordinate::StandardStrings::bottom: return false;
  63958. default: break;
  63959. }
  63960. return true;
  63961. }
  63962. else
  63963. {
  63964. for (int i = e.getNumInputs(); --i >= 0;)
  63965. if (dependsOnSymbolsOtherThanThis (e.getInput(i)))
  63966. return true;
  63967. }
  63968. return false;
  63969. }
  63970. }
  63971. RelativeRectangle::RelativeRectangle()
  63972. {
  63973. }
  63974. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  63975. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  63976. : left (left_), right (right_), top (top_), bottom (bottom_)
  63977. {
  63978. }
  63979. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect)
  63980. : left (rect.getX()),
  63981. right (Expression::symbol (RelativeCoordinate::Strings::left) + Expression ((double) rect.getWidth())),
  63982. top (rect.getY()),
  63983. bottom (Expression::symbol (RelativeCoordinate::Strings::top) + Expression ((double) rect.getHeight()))
  63984. {
  63985. }
  63986. RelativeRectangle::RelativeRectangle (const String& s)
  63987. {
  63988. String::CharPointerType text (s.getCharPointer());
  63989. left = RelativeCoordinate (Expression::parse (text));
  63990. RelativeRectangleHelpers::skipComma (text);
  63991. top = RelativeCoordinate (Expression::parse (text));
  63992. RelativeRectangleHelpers::skipComma (text);
  63993. right = RelativeCoordinate (Expression::parse (text));
  63994. RelativeRectangleHelpers::skipComma (text);
  63995. bottom = RelativeCoordinate (Expression::parse (text));
  63996. }
  63997. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  63998. {
  63999. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  64000. }
  64001. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  64002. {
  64003. return ! operator== (other);
  64004. }
  64005. // An expression context that can evaluate expressions using "this"
  64006. class RelativeRectangleLocalScope : public Expression::Scope
  64007. {
  64008. public:
  64009. RelativeRectangleLocalScope (const RelativeRectangle& rect_) : rect (rect_) {}
  64010. const Expression getSymbolValue (const String& symbol) const
  64011. {
  64012. switch (RelativeCoordinate::StandardStrings::getTypeOf (symbol))
  64013. {
  64014. case RelativeCoordinate::StandardStrings::x:
  64015. case RelativeCoordinate::StandardStrings::left: return rect.left.getExpression();
  64016. case RelativeCoordinate::StandardStrings::y:
  64017. case RelativeCoordinate::StandardStrings::top: return rect.top.getExpression();
  64018. case RelativeCoordinate::StandardStrings::right: return rect.right.getExpression();
  64019. case RelativeCoordinate::StandardStrings::bottom: return rect.bottom.getExpression();
  64020. default: break;
  64021. }
  64022. return Expression::Scope::getSymbolValue (symbol);
  64023. }
  64024. private:
  64025. const RelativeRectangle& rect;
  64026. JUCE_DECLARE_NON_COPYABLE (RelativeRectangleLocalScope);
  64027. };
  64028. const Rectangle<float> RelativeRectangle::resolve (const Expression::Scope* scope) const
  64029. {
  64030. if (scope == 0)
  64031. {
  64032. RelativeRectangleLocalScope scope (*this);
  64033. return resolve (&scope);
  64034. }
  64035. else
  64036. {
  64037. const double l = left.resolve (scope);
  64038. const double r = right.resolve (scope);
  64039. const double t = top.resolve (scope);
  64040. const double b = bottom.resolve (scope);
  64041. return Rectangle<float> ((float) l, (float) t, (float) jmax (0.0, r - l), (float) jmax (0.0, b - t));
  64042. }
  64043. }
  64044. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::Scope* scope)
  64045. {
  64046. left.moveToAbsolute (newPos.getX(), scope);
  64047. right.moveToAbsolute (newPos.getRight(), scope);
  64048. top.moveToAbsolute (newPos.getY(), scope);
  64049. bottom.moveToAbsolute (newPos.getBottom(), scope);
  64050. }
  64051. bool RelativeRectangle::isDynamic() const
  64052. {
  64053. using namespace RelativeRectangleHelpers;
  64054. return dependsOnSymbolsOtherThanThis (left.getExpression())
  64055. || dependsOnSymbolsOtherThanThis (right.getExpression())
  64056. || dependsOnSymbolsOtherThanThis (top.getExpression())
  64057. || dependsOnSymbolsOtherThanThis (bottom.getExpression());
  64058. }
  64059. const String RelativeRectangle::toString() const
  64060. {
  64061. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64062. }
  64063. void RelativeRectangle::renameSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Expression::Scope& scope)
  64064. {
  64065. left = left.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  64066. right = right.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  64067. top = top.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  64068. bottom = bottom.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  64069. }
  64070. class RelativeRectangleComponentPositioner : public RelativeCoordinatePositionerBase
  64071. {
  64072. public:
  64073. RelativeRectangleComponentPositioner (Component& component_, const RelativeRectangle& rectangle_)
  64074. : RelativeCoordinatePositionerBase (component_),
  64075. rectangle (rectangle_)
  64076. {
  64077. }
  64078. bool registerCoordinates()
  64079. {
  64080. bool ok = addCoordinate (rectangle.left);
  64081. ok = addCoordinate (rectangle.right) && ok;
  64082. ok = addCoordinate (rectangle.top) && ok;
  64083. ok = addCoordinate (rectangle.bottom) && ok;
  64084. return ok;
  64085. }
  64086. bool isUsingRectangle (const RelativeRectangle& other) const throw()
  64087. {
  64088. return rectangle == other;
  64089. }
  64090. void applyToComponentBounds()
  64091. {
  64092. for (int i = 4; --i >= 0;)
  64093. {
  64094. ComponentScope scope (getComponent());
  64095. const Rectangle<int> newBounds (rectangle.resolve (&scope).getSmallestIntegerContainer());
  64096. if (newBounds == getComponent().getBounds())
  64097. return;
  64098. getComponent().setBounds (newBounds);
  64099. }
  64100. jassertfalse; // must be a recursive reference!
  64101. }
  64102. private:
  64103. const RelativeRectangle rectangle;
  64104. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativeRectangleComponentPositioner);
  64105. };
  64106. void RelativeRectangle::applyToComponent (Component& component) const
  64107. {
  64108. if (isDynamic())
  64109. {
  64110. RelativeRectangleComponentPositioner* current = dynamic_cast <RelativeRectangleComponentPositioner*> (component.getPositioner());
  64111. if (current == 0 || ! current->isUsingRectangle (*this))
  64112. {
  64113. RelativeRectangleComponentPositioner* p = new RelativeRectangleComponentPositioner (component, *this);
  64114. component.setPositioner (p);
  64115. p->apply();
  64116. }
  64117. }
  64118. else
  64119. {
  64120. component.setPositioner (0);
  64121. component.setBounds (resolve (0).getSmallestIntegerContainer());
  64122. }
  64123. }
  64124. END_JUCE_NAMESPACE
  64125. /*** End of inlined file: juce_RelativeRectangle.cpp ***/
  64126. /*** Start of inlined file: juce_RelativePointPath.cpp ***/
  64127. BEGIN_JUCE_NAMESPACE
  64128. RelativePointPath::RelativePointPath()
  64129. : usesNonZeroWinding (true),
  64130. containsDynamicPoints (false)
  64131. {
  64132. }
  64133. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64134. : usesNonZeroWinding (true),
  64135. containsDynamicPoints (false)
  64136. {
  64137. for (int i = 0; i < other.elements.size(); ++i)
  64138. elements.add (other.elements.getUnchecked(i)->clone());
  64139. }
  64140. RelativePointPath::RelativePointPath (const Path& path)
  64141. : usesNonZeroWinding (path.isUsingNonZeroWinding()),
  64142. containsDynamicPoints (false)
  64143. {
  64144. for (Path::Iterator i (path); i.next();)
  64145. {
  64146. switch (i.elementType)
  64147. {
  64148. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64149. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64150. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64151. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64152. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64153. default: jassertfalse; break;
  64154. }
  64155. }
  64156. }
  64157. RelativePointPath::~RelativePointPath()
  64158. {
  64159. }
  64160. bool RelativePointPath::operator== (const RelativePointPath& other) const throw()
  64161. {
  64162. if (elements.size() != other.elements.size()
  64163. || usesNonZeroWinding != other.usesNonZeroWinding
  64164. || containsDynamicPoints != other.containsDynamicPoints)
  64165. return false;
  64166. for (int i = 0; i < elements.size(); ++i)
  64167. {
  64168. ElementBase* const e1 = elements.getUnchecked(i);
  64169. ElementBase* const e2 = other.elements.getUnchecked(i);
  64170. if (e1->type != e2->type)
  64171. return false;
  64172. int numPoints1, numPoints2;
  64173. const RelativePoint* const points1 = e1->getControlPoints (numPoints1);
  64174. const RelativePoint* const points2 = e2->getControlPoints (numPoints2);
  64175. jassert (numPoints1 == numPoints2);
  64176. for (int j = numPoints1; --j >= 0;)
  64177. if (points1[j] != points2[j])
  64178. return false;
  64179. }
  64180. return true;
  64181. }
  64182. bool RelativePointPath::operator!= (const RelativePointPath& other) const throw()
  64183. {
  64184. return ! operator== (other);
  64185. }
  64186. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64187. {
  64188. elements.swapWithArray (other.elements);
  64189. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64190. swapVariables (containsDynamicPoints, other.containsDynamicPoints);
  64191. }
  64192. void RelativePointPath::createPath (Path& path, Expression::Scope* scope) const
  64193. {
  64194. for (int i = 0; i < elements.size(); ++i)
  64195. elements.getUnchecked(i)->addToPath (path, scope);
  64196. }
  64197. bool RelativePointPath::containsAnyDynamicPoints() const
  64198. {
  64199. return containsDynamicPoints;
  64200. }
  64201. void RelativePointPath::addElement (ElementBase* newElement)
  64202. {
  64203. if (newElement != 0)
  64204. {
  64205. elements.add (newElement);
  64206. containsDynamicPoints = containsDynamicPoints || newElement->isDynamic();
  64207. }
  64208. }
  64209. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64210. {
  64211. }
  64212. bool RelativePointPath::ElementBase::isDynamic()
  64213. {
  64214. int numPoints;
  64215. const RelativePoint* const points = getControlPoints (numPoints);
  64216. for (int i = numPoints; --i >= 0;)
  64217. if (points[i].isDynamic())
  64218. return true;
  64219. return false;
  64220. }
  64221. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64222. : ElementBase (startSubPathElement), startPos (pos)
  64223. {
  64224. }
  64225. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64226. {
  64227. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64228. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64229. return v;
  64230. }
  64231. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::Scope* scope) const
  64232. {
  64233. path.startNewSubPath (startPos.resolve (scope));
  64234. }
  64235. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64236. {
  64237. numPoints = 1;
  64238. return &startPos;
  64239. }
  64240. RelativePointPath::ElementBase* RelativePointPath::StartSubPath::clone() const
  64241. {
  64242. return new StartSubPath (startPos);
  64243. }
  64244. RelativePointPath::CloseSubPath::CloseSubPath()
  64245. : ElementBase (closeSubPathElement)
  64246. {
  64247. }
  64248. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64249. {
  64250. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64251. }
  64252. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::Scope*) const
  64253. {
  64254. path.closeSubPath();
  64255. }
  64256. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64257. {
  64258. numPoints = 0;
  64259. return 0;
  64260. }
  64261. RelativePointPath::ElementBase* RelativePointPath::CloseSubPath::clone() const
  64262. {
  64263. return new CloseSubPath();
  64264. }
  64265. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64266. : ElementBase (lineToElement), endPoint (endPoint_)
  64267. {
  64268. }
  64269. const ValueTree RelativePointPath::LineTo::createTree() const
  64270. {
  64271. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64272. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64273. return v;
  64274. }
  64275. void RelativePointPath::LineTo::addToPath (Path& path, Expression::Scope* scope) const
  64276. {
  64277. path.lineTo (endPoint.resolve (scope));
  64278. }
  64279. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64280. {
  64281. numPoints = 1;
  64282. return &endPoint;
  64283. }
  64284. RelativePointPath::ElementBase* RelativePointPath::LineTo::clone() const
  64285. {
  64286. return new LineTo (endPoint);
  64287. }
  64288. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64289. : ElementBase (quadraticToElement)
  64290. {
  64291. controlPoints[0] = controlPoint;
  64292. controlPoints[1] = endPoint;
  64293. }
  64294. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64295. {
  64296. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64297. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64298. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64299. return v;
  64300. }
  64301. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::Scope* scope) const
  64302. {
  64303. path.quadraticTo (controlPoints[0].resolve (scope),
  64304. controlPoints[1].resolve (scope));
  64305. }
  64306. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64307. {
  64308. numPoints = 2;
  64309. return controlPoints;
  64310. }
  64311. RelativePointPath::ElementBase* RelativePointPath::QuadraticTo::clone() const
  64312. {
  64313. return new QuadraticTo (controlPoints[0], controlPoints[1]);
  64314. }
  64315. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64316. : ElementBase (cubicToElement)
  64317. {
  64318. controlPoints[0] = controlPoint1;
  64319. controlPoints[1] = controlPoint2;
  64320. controlPoints[2] = endPoint;
  64321. }
  64322. const ValueTree RelativePointPath::CubicTo::createTree() const
  64323. {
  64324. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64325. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64326. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64327. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64328. return v;
  64329. }
  64330. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::Scope* scope) const
  64331. {
  64332. path.cubicTo (controlPoints[0].resolve (scope),
  64333. controlPoints[1].resolve (scope),
  64334. controlPoints[2].resolve (scope));
  64335. }
  64336. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64337. {
  64338. numPoints = 3;
  64339. return controlPoints;
  64340. }
  64341. RelativePointPath::ElementBase* RelativePointPath::CubicTo::clone() const
  64342. {
  64343. return new CubicTo (controlPoints[0], controlPoints[1], controlPoints[2]);
  64344. }
  64345. END_JUCE_NAMESPACE
  64346. /*** End of inlined file: juce_RelativePointPath.cpp ***/
  64347. /*** Start of inlined file: juce_RelativeParallelogram.cpp ***/
  64348. BEGIN_JUCE_NAMESPACE
  64349. RelativeParallelogram::RelativeParallelogram()
  64350. {
  64351. }
  64352. RelativeParallelogram::RelativeParallelogram (const Rectangle<float>& r)
  64353. : topLeft (r.getTopLeft()), topRight (r.getTopRight()), bottomLeft (r.getBottomLeft())
  64354. {
  64355. }
  64356. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64357. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64358. {
  64359. }
  64360. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64361. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64362. {
  64363. }
  64364. RelativeParallelogram::~RelativeParallelogram()
  64365. {
  64366. }
  64367. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::Scope* const scope) const
  64368. {
  64369. points[0] = topLeft.resolve (scope);
  64370. points[1] = topRight.resolve (scope);
  64371. points[2] = bottomLeft.resolve (scope);
  64372. }
  64373. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::Scope* const scope) const
  64374. {
  64375. resolveThreePoints (points, scope);
  64376. points[3] = points[1] + (points[2] - points[0]);
  64377. }
  64378. const Rectangle<float> RelativeParallelogram::getBounds (Expression::Scope* const scope) const
  64379. {
  64380. Point<float> points[4];
  64381. resolveFourCorners (points, scope);
  64382. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64383. }
  64384. void RelativeParallelogram::getPath (Path& path, Expression::Scope* const scope) const
  64385. {
  64386. Point<float> points[4];
  64387. resolveFourCorners (points, scope);
  64388. path.startNewSubPath (points[0]);
  64389. path.lineTo (points[1]);
  64390. path.lineTo (points[3]);
  64391. path.lineTo (points[2]);
  64392. path.closeSubPath();
  64393. }
  64394. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::Scope* const scope)
  64395. {
  64396. Point<float> corners[3];
  64397. resolveThreePoints (corners, scope);
  64398. const Line<float> top (corners[0], corners[1]);
  64399. const Line<float> left (corners[0], corners[2]);
  64400. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64401. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64402. topRight.moveToAbsolute (newTopRight, scope);
  64403. bottomLeft.moveToAbsolute (newBottomLeft, scope);
  64404. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64405. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64406. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64407. }
  64408. bool RelativeParallelogram::isDynamic() const
  64409. {
  64410. return topLeft.isDynamic() || topRight.isDynamic() || bottomLeft.isDynamic();
  64411. }
  64412. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64413. {
  64414. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64415. }
  64416. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64417. {
  64418. return ! operator== (other);
  64419. }
  64420. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64421. {
  64422. const Point<float> tr (corners[1] - corners[0]);
  64423. const Point<float> bl (corners[2] - corners[0]);
  64424. target -= corners[0];
  64425. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64426. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64427. }
  64428. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64429. {
  64430. return corners[0]
  64431. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64432. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64433. }
  64434. const Rectangle<float> RelativeParallelogram::getBoundingBox (const Point<float>* const p) throw()
  64435. {
  64436. const Point<float> points[] = { p[0], p[1], p[2], p[1] + (p[2] - p[0]) };
  64437. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64438. }
  64439. END_JUCE_NAMESPACE
  64440. /*** End of inlined file: juce_RelativeParallelogram.cpp ***/
  64441. /*** Start of inlined file: juce_RelativeCoordinatePositioner.cpp ***/
  64442. BEGIN_JUCE_NAMESPACE
  64443. RelativeCoordinatePositionerBase::ComponentScope::ComponentScope (Component& component_)
  64444. : component (component_)
  64445. {
  64446. }
  64447. const Expression RelativeCoordinatePositionerBase::ComponentScope::getSymbolValue (const String& symbol) const
  64448. {
  64449. switch (RelativeCoordinate::StandardStrings::getTypeOf (symbol))
  64450. {
  64451. case RelativeCoordinate::StandardStrings::x:
  64452. case RelativeCoordinate::StandardStrings::left: return Expression ((double) component.getX());
  64453. case RelativeCoordinate::StandardStrings::y:
  64454. case RelativeCoordinate::StandardStrings::top: return Expression ((double) component.getY());
  64455. case RelativeCoordinate::StandardStrings::width: return Expression ((double) component.getWidth());
  64456. case RelativeCoordinate::StandardStrings::height: return Expression ((double) component.getHeight());
  64457. case RelativeCoordinate::StandardStrings::right: return Expression ((double) component.getRight());
  64458. case RelativeCoordinate::StandardStrings::bottom: return Expression ((double) component.getBottom());
  64459. default: break;
  64460. }
  64461. MarkerList* list;
  64462. const MarkerList::Marker* const marker = findMarker (symbol, list);
  64463. if (marker != 0)
  64464. return marker->position.getExpression();
  64465. return Expression::Scope::getSymbolValue (symbol);
  64466. }
  64467. void RelativeCoordinatePositionerBase::ComponentScope::visitRelativeScope (const String& scopeName, Visitor& visitor) const
  64468. {
  64469. Component* targetComp = 0;
  64470. if (scopeName == RelativeCoordinate::Strings::parent)
  64471. targetComp = component.getParentComponent();
  64472. else
  64473. targetComp = findSiblingComponent (scopeName);
  64474. if (targetComp != 0)
  64475. visitor.visit (ComponentScope (*targetComp));
  64476. else
  64477. Expression::Scope::visitRelativeScope (scopeName, visitor);
  64478. }
  64479. const String RelativeCoordinatePositionerBase::ComponentScope::getScopeUID() const
  64480. {
  64481. return String::toHexString ((int) (pointer_sized_int) (void*) &component);
  64482. }
  64483. Component* RelativeCoordinatePositionerBase::ComponentScope::findSiblingComponent (const String& componentID) const
  64484. {
  64485. Component* const parent = component.getParentComponent();
  64486. if (parent != 0)
  64487. {
  64488. for (int i = parent->getNumChildComponents(); --i >= 0;)
  64489. {
  64490. Component* const c = parent->getChildComponent(i);
  64491. if (c->getComponentID() == componentID)
  64492. return c;
  64493. }
  64494. }
  64495. return 0;
  64496. }
  64497. const MarkerList::Marker* RelativeCoordinatePositionerBase::ComponentScope::findMarker (const String& name, MarkerList*& list) const
  64498. {
  64499. const MarkerList::Marker* marker = 0;
  64500. Component* const parent = component.getParentComponent();
  64501. if (parent != 0)
  64502. {
  64503. list = parent->getMarkers (true);
  64504. if (list != 0)
  64505. marker = list->getMarker (name);
  64506. if (marker == 0)
  64507. {
  64508. list = parent->getMarkers (false);
  64509. if (list != 0)
  64510. marker = list->getMarker (name);
  64511. }
  64512. }
  64513. return marker;
  64514. }
  64515. class RelativeCoordinatePositionerBase::DependencyFinderScope : public ComponentScope
  64516. {
  64517. public:
  64518. DependencyFinderScope (Component& component_, RelativeCoordinatePositionerBase& positioner_, bool& ok_)
  64519. : ComponentScope (component_), positioner (positioner_), ok (ok_)
  64520. {
  64521. }
  64522. const Expression getSymbolValue (const String& symbol) const
  64523. {
  64524. if (symbol == RelativeCoordinate::Strings::left || symbol == RelativeCoordinate::Strings::x
  64525. || symbol == RelativeCoordinate::Strings::width || symbol == RelativeCoordinate::Strings::right
  64526. || symbol == RelativeCoordinate::Strings::top || symbol == RelativeCoordinate::Strings::y
  64527. || symbol == RelativeCoordinate::Strings::height || symbol == RelativeCoordinate::Strings::bottom)
  64528. {
  64529. positioner.registerComponentListener (component);
  64530. }
  64531. else
  64532. {
  64533. MarkerList* list;
  64534. const MarkerList::Marker* const marker = findMarker (symbol, list);
  64535. if (marker != 0)
  64536. {
  64537. positioner.registerMarkerListListener (list);
  64538. }
  64539. else
  64540. {
  64541. // The marker we want doesn't exist, so watch all lists in case they change and the marker appears later..
  64542. positioner.registerMarkerListListener (component.getMarkers (true));
  64543. positioner.registerMarkerListListener (component.getMarkers (false));
  64544. ok = false;
  64545. }
  64546. }
  64547. return ComponentScope::getSymbolValue (symbol);
  64548. }
  64549. void visitRelativeScope (const String& scopeName, Visitor& visitor) const
  64550. {
  64551. Component* targetComp = 0;
  64552. if (scopeName == RelativeCoordinate::Strings::parent)
  64553. targetComp = component.getParentComponent();
  64554. else
  64555. targetComp = findSiblingComponent (scopeName);
  64556. if (targetComp != 0)
  64557. {
  64558. visitor.visit (DependencyFinderScope (*targetComp, positioner, ok));
  64559. }
  64560. else
  64561. {
  64562. // The named component doesn't exist, so we'll watch the parent for changes in case it appears later..
  64563. Component* const parent = component.getParentComponent();
  64564. if (parent != 0)
  64565. positioner.registerComponentListener (*parent);
  64566. positioner.registerComponentListener (component);
  64567. ok = false;
  64568. }
  64569. }
  64570. private:
  64571. RelativeCoordinatePositionerBase& positioner;
  64572. bool& ok;
  64573. JUCE_DECLARE_NON_COPYABLE (DependencyFinderScope);
  64574. };
  64575. RelativeCoordinatePositionerBase::RelativeCoordinatePositionerBase (Component& component_)
  64576. : Component::Positioner (component_), registeredOk (false)
  64577. {
  64578. }
  64579. RelativeCoordinatePositionerBase::~RelativeCoordinatePositionerBase()
  64580. {
  64581. unregisterListeners();
  64582. }
  64583. void RelativeCoordinatePositionerBase::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  64584. {
  64585. apply();
  64586. }
  64587. void RelativeCoordinatePositionerBase::componentParentHierarchyChanged (Component&)
  64588. {
  64589. apply();
  64590. }
  64591. void RelativeCoordinatePositionerBase::componentChildrenChanged (Component& changed)
  64592. {
  64593. if (getComponent().getParentComponent() == &changed && ! registeredOk)
  64594. apply();
  64595. }
  64596. void RelativeCoordinatePositionerBase::componentBeingDeleted (Component& component)
  64597. {
  64598. jassert (sourceComponents.contains (&component));
  64599. sourceComponents.removeValue (&component);
  64600. registeredOk = false;
  64601. }
  64602. void RelativeCoordinatePositionerBase::markersChanged (MarkerList*)
  64603. {
  64604. apply();
  64605. }
  64606. void RelativeCoordinatePositionerBase::markerListBeingDeleted (MarkerList* markerList)
  64607. {
  64608. jassert (sourceMarkerLists.contains (markerList));
  64609. sourceMarkerLists.removeValue (markerList);
  64610. }
  64611. void RelativeCoordinatePositionerBase::apply()
  64612. {
  64613. if (! registeredOk)
  64614. {
  64615. unregisterListeners();
  64616. registeredOk = registerCoordinates();
  64617. }
  64618. applyToComponentBounds();
  64619. }
  64620. bool RelativeCoordinatePositionerBase::addCoordinate (const RelativeCoordinate& coord)
  64621. {
  64622. bool ok = true;
  64623. DependencyFinderScope finderScope (getComponent(), *this, ok);
  64624. coord.getExpression().evaluate (finderScope);
  64625. return ok;
  64626. }
  64627. bool RelativeCoordinatePositionerBase::addPoint (const RelativePoint& point)
  64628. {
  64629. const bool ok = addCoordinate (point.x);
  64630. return addCoordinate (point.y) && ok;
  64631. }
  64632. void RelativeCoordinatePositionerBase::registerComponentListener (Component& comp)
  64633. {
  64634. if (! sourceComponents.contains (&comp))
  64635. {
  64636. comp.addComponentListener (this);
  64637. sourceComponents.add (&comp);
  64638. }
  64639. }
  64640. void RelativeCoordinatePositionerBase::registerMarkerListListener (MarkerList* const list)
  64641. {
  64642. if (list != 0 && ! sourceMarkerLists.contains (list))
  64643. {
  64644. list->addListener (this);
  64645. sourceMarkerLists.add (list);
  64646. }
  64647. }
  64648. void RelativeCoordinatePositionerBase::unregisterListeners()
  64649. {
  64650. int i;
  64651. for (i = sourceComponents.size(); --i >= 0;)
  64652. sourceComponents.getUnchecked(i)->removeComponentListener (this);
  64653. for (i = sourceMarkerLists.size(); --i >= 0;)
  64654. sourceMarkerLists.getUnchecked(i)->removeListener (this);
  64655. sourceComponents.clear();
  64656. sourceMarkerLists.clear();
  64657. }
  64658. END_JUCE_NAMESPACE
  64659. /*** End of inlined file: juce_RelativeCoordinatePositioner.cpp ***/
  64660. #endif
  64661. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64662. /*** Start of inlined file: juce_Colour.cpp ***/
  64663. BEGIN_JUCE_NAMESPACE
  64664. namespace ColourHelpers
  64665. {
  64666. uint8 floatAlphaToInt (const float alpha) throw()
  64667. {
  64668. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64669. }
  64670. void convertHSBtoRGB (float h, float s, float v,
  64671. uint8& r, uint8& g, uint8& b) throw()
  64672. {
  64673. v = jlimit (0.0f, 1.0f, v);
  64674. v *= 255.0f;
  64675. const uint8 intV = (uint8) roundToInt (v);
  64676. if (s <= 0)
  64677. {
  64678. r = intV;
  64679. g = intV;
  64680. b = intV;
  64681. }
  64682. else
  64683. {
  64684. s = jmin (1.0f, s);
  64685. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64686. const float f = h - std::floor (h);
  64687. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64688. if (h < 1.0f)
  64689. {
  64690. r = intV;
  64691. g = (uint8) roundToInt (v * (1.0f - (s * (1.0f - f))));
  64692. b = x;
  64693. }
  64694. else if (h < 2.0f)
  64695. {
  64696. r = (uint8) roundToInt (v * (1.0f - s * f));
  64697. g = intV;
  64698. b = x;
  64699. }
  64700. else if (h < 3.0f)
  64701. {
  64702. r = x;
  64703. g = intV;
  64704. b = (uint8) roundToInt (v * (1.0f - (s * (1.0f - f))));
  64705. }
  64706. else if (h < 4.0f)
  64707. {
  64708. r = x;
  64709. g = (uint8) roundToInt (v * (1.0f - s * f));
  64710. b = intV;
  64711. }
  64712. else if (h < 5.0f)
  64713. {
  64714. r = (uint8) roundToInt (v * (1.0f - (s * (1.0f - f))));
  64715. g = x;
  64716. b = intV;
  64717. }
  64718. else
  64719. {
  64720. r = intV;
  64721. g = x;
  64722. b = (uint8) roundToInt (v * (1.0f - s * f));
  64723. }
  64724. }
  64725. }
  64726. }
  64727. Colour::Colour() throw()
  64728. : argb (0)
  64729. {
  64730. }
  64731. Colour::Colour (const Colour& other) throw()
  64732. : argb (other.argb)
  64733. {
  64734. }
  64735. Colour& Colour::operator= (const Colour& other) throw()
  64736. {
  64737. argb = other.argb;
  64738. return *this;
  64739. }
  64740. bool Colour::operator== (const Colour& other) const throw()
  64741. {
  64742. return argb.getARGB() == other.argb.getARGB();
  64743. }
  64744. bool Colour::operator!= (const Colour& other) const throw()
  64745. {
  64746. return argb.getARGB() != other.argb.getARGB();
  64747. }
  64748. Colour::Colour (const uint32 argb_) throw()
  64749. : argb (argb_)
  64750. {
  64751. }
  64752. Colour::Colour (const uint8 red,
  64753. const uint8 green,
  64754. const uint8 blue) throw()
  64755. {
  64756. argb.setARGB (0xff, red, green, blue);
  64757. }
  64758. const Colour Colour::fromRGB (const uint8 red,
  64759. const uint8 green,
  64760. const uint8 blue) throw()
  64761. {
  64762. return Colour (red, green, blue);
  64763. }
  64764. Colour::Colour (const uint8 red,
  64765. const uint8 green,
  64766. const uint8 blue,
  64767. const uint8 alpha) throw()
  64768. {
  64769. argb.setARGB (alpha, red, green, blue);
  64770. }
  64771. const Colour Colour::fromRGBA (const uint8 red,
  64772. const uint8 green,
  64773. const uint8 blue,
  64774. const uint8 alpha) throw()
  64775. {
  64776. return Colour (red, green, blue, alpha);
  64777. }
  64778. Colour::Colour (const uint8 red,
  64779. const uint8 green,
  64780. const uint8 blue,
  64781. const float alpha) throw()
  64782. {
  64783. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  64784. }
  64785. const Colour Colour::fromRGBAFloat (const uint8 red,
  64786. const uint8 green,
  64787. const uint8 blue,
  64788. const float alpha) throw()
  64789. {
  64790. return Colour (red, green, blue, alpha);
  64791. }
  64792. Colour::Colour (const float hue,
  64793. const float saturation,
  64794. const float brightness,
  64795. const float alpha) throw()
  64796. {
  64797. uint8 r, g, b;
  64798. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64799. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  64800. }
  64801. const Colour Colour::fromHSV (const float hue,
  64802. const float saturation,
  64803. const float brightness,
  64804. const float alpha) throw()
  64805. {
  64806. return Colour (hue, saturation, brightness, alpha);
  64807. }
  64808. Colour::Colour (const float hue,
  64809. const float saturation,
  64810. const float brightness,
  64811. const uint8 alpha) throw()
  64812. {
  64813. uint8 r, g, b;
  64814. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64815. argb.setARGB (alpha, r, g, b);
  64816. }
  64817. Colour::~Colour() throw()
  64818. {
  64819. }
  64820. const PixelARGB Colour::getPixelARGB() const throw()
  64821. {
  64822. PixelARGB p (argb);
  64823. p.premultiply();
  64824. return p;
  64825. }
  64826. uint32 Colour::getARGB() const throw()
  64827. {
  64828. return argb.getARGB();
  64829. }
  64830. bool Colour::isTransparent() const throw()
  64831. {
  64832. return getAlpha() == 0;
  64833. }
  64834. bool Colour::isOpaque() const throw()
  64835. {
  64836. return getAlpha() == 0xff;
  64837. }
  64838. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  64839. {
  64840. PixelARGB newCol (argb);
  64841. newCol.setAlpha (newAlpha);
  64842. return Colour (newCol.getARGB());
  64843. }
  64844. const Colour Colour::withAlpha (const float newAlpha) const throw()
  64845. {
  64846. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  64847. PixelARGB newCol (argb);
  64848. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  64849. return Colour (newCol.getARGB());
  64850. }
  64851. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  64852. {
  64853. jassert (alphaMultiplier >= 0);
  64854. PixelARGB newCol (argb);
  64855. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  64856. return Colour (newCol.getARGB());
  64857. }
  64858. const Colour Colour::overlaidWith (const Colour& src) const throw()
  64859. {
  64860. const int destAlpha = getAlpha();
  64861. if (destAlpha > 0)
  64862. {
  64863. const int invA = 0xff - (int) src.getAlpha();
  64864. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  64865. if (resA > 0)
  64866. {
  64867. const int da = (invA * destAlpha) / resA;
  64868. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  64869. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  64870. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  64871. (uint8) resA);
  64872. }
  64873. return *this;
  64874. }
  64875. else
  64876. {
  64877. return src;
  64878. }
  64879. }
  64880. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  64881. {
  64882. if (proportionOfOther <= 0)
  64883. return *this;
  64884. if (proportionOfOther >= 1.0f)
  64885. return other;
  64886. PixelARGB c1 (getPixelARGB());
  64887. const PixelARGB c2 (other.getPixelARGB());
  64888. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  64889. c1.unpremultiply();
  64890. return Colour (c1.getARGB());
  64891. }
  64892. float Colour::getFloatRed() const throw()
  64893. {
  64894. return getRed() / 255.0f;
  64895. }
  64896. float Colour::getFloatGreen() const throw()
  64897. {
  64898. return getGreen() / 255.0f;
  64899. }
  64900. float Colour::getFloatBlue() const throw()
  64901. {
  64902. return getBlue() / 255.0f;
  64903. }
  64904. float Colour::getFloatAlpha() const throw()
  64905. {
  64906. return getAlpha() / 255.0f;
  64907. }
  64908. void Colour::getHSB (float& h, float& s, float& v) const throw()
  64909. {
  64910. const int r = getRed();
  64911. const int g = getGreen();
  64912. const int b = getBlue();
  64913. const int hi = jmax (r, g, b);
  64914. const int lo = jmin (r, g, b);
  64915. if (hi != 0)
  64916. {
  64917. s = (hi - lo) / (float) hi;
  64918. if (s != 0)
  64919. {
  64920. const float invDiff = 1.0f / (hi - lo);
  64921. const float red = (hi - r) * invDiff;
  64922. const float green = (hi - g) * invDiff;
  64923. const float blue = (hi - b) * invDiff;
  64924. if (r == hi)
  64925. h = blue - green;
  64926. else if (g == hi)
  64927. h = 2.0f + red - blue;
  64928. else
  64929. h = 4.0f + green - red;
  64930. h *= 1.0f / 6.0f;
  64931. if (h < 0)
  64932. ++h;
  64933. }
  64934. else
  64935. {
  64936. h = 0;
  64937. }
  64938. }
  64939. else
  64940. {
  64941. s = 0;
  64942. h = 0;
  64943. }
  64944. v = hi / 255.0f;
  64945. }
  64946. float Colour::getHue() const throw()
  64947. {
  64948. float h, s, b;
  64949. getHSB (h, s, b);
  64950. return h;
  64951. }
  64952. const Colour Colour::withHue (const float hue) const throw()
  64953. {
  64954. float h, s, b;
  64955. getHSB (h, s, b);
  64956. return Colour (hue, s, b, getAlpha());
  64957. }
  64958. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  64959. {
  64960. float h, s, b;
  64961. getHSB (h, s, b);
  64962. return Colour (h + amountToRotate, s, b, getAlpha());
  64963. }
  64964. float Colour::getSaturation() const throw()
  64965. {
  64966. float h, s, b;
  64967. getHSB (h, s, b);
  64968. return s;
  64969. }
  64970. const Colour Colour::withSaturation (const float saturation) const throw()
  64971. {
  64972. float h, s, b;
  64973. getHSB (h, s, b);
  64974. return Colour (h, saturation, b, getAlpha());
  64975. }
  64976. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  64977. {
  64978. float h, s, b;
  64979. getHSB (h, s, b);
  64980. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  64981. }
  64982. float Colour::getBrightness() const throw()
  64983. {
  64984. float h, s, b;
  64985. getHSB (h, s, b);
  64986. return b;
  64987. }
  64988. const Colour Colour::withBrightness (const float brightness) const throw()
  64989. {
  64990. float h, s, b;
  64991. getHSB (h, s, b);
  64992. return Colour (h, s, brightness, getAlpha());
  64993. }
  64994. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  64995. {
  64996. float h, s, b;
  64997. getHSB (h, s, b);
  64998. b *= amount;
  64999. if (b > 1.0f)
  65000. b = 1.0f;
  65001. return Colour (h, s, b, getAlpha());
  65002. }
  65003. const Colour Colour::brighter (float amount) const throw()
  65004. {
  65005. amount = 1.0f / (1.0f + amount);
  65006. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  65007. (uint8) (255 - (amount * (255 - getGreen()))),
  65008. (uint8) (255 - (amount * (255 - getBlue()))),
  65009. getAlpha());
  65010. }
  65011. const Colour Colour::darker (float amount) const throw()
  65012. {
  65013. amount = 1.0f / (1.0f + amount);
  65014. return Colour ((uint8) (amount * getRed()),
  65015. (uint8) (amount * getGreen()),
  65016. (uint8) (amount * getBlue()),
  65017. getAlpha());
  65018. }
  65019. const Colour Colour::greyLevel (const float brightness) throw()
  65020. {
  65021. const uint8 level
  65022. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  65023. return Colour (level, level, level);
  65024. }
  65025. const Colour Colour::contrasting (const float amount) const throw()
  65026. {
  65027. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  65028. ? Colours::black
  65029. : Colours::white).withAlpha (amount));
  65030. }
  65031. const Colour Colour::contrasting (const Colour& colour1,
  65032. const Colour& colour2) throw()
  65033. {
  65034. const float b1 = colour1.getBrightness();
  65035. const float b2 = colour2.getBrightness();
  65036. float best = 0.0f;
  65037. float bestDist = 0.0f;
  65038. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  65039. {
  65040. const float d1 = std::abs (i - b1);
  65041. const float d2 = std::abs (i - b2);
  65042. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  65043. if (dist > bestDist)
  65044. {
  65045. best = i;
  65046. bestDist = dist;
  65047. }
  65048. }
  65049. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  65050. .withBrightness (best);
  65051. }
  65052. const String Colour::toString() const
  65053. {
  65054. return String::toHexString ((int) argb.getARGB());
  65055. }
  65056. const Colour Colour::fromString (const String& encodedColourString)
  65057. {
  65058. return Colour ((uint32) encodedColourString.getHexValue32());
  65059. }
  65060. const String Colour::toDisplayString (const bool includeAlphaValue) const
  65061. {
  65062. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  65063. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  65064. .toUpperCase();
  65065. }
  65066. END_JUCE_NAMESPACE
  65067. /*** End of inlined file: juce_Colour.cpp ***/
  65068. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  65069. BEGIN_JUCE_NAMESPACE
  65070. ColourGradient::ColourGradient() throw()
  65071. {
  65072. #if JUCE_DEBUG
  65073. point1.setX (987654.0f);
  65074. #endif
  65075. }
  65076. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  65077. const Colour& colour2, const float x2_, const float y2_,
  65078. const bool isRadial_)
  65079. : point1 (x1_, y1_),
  65080. point2 (x2_, y2_),
  65081. isRadial (isRadial_)
  65082. {
  65083. colours.add (ColourPoint (0.0, colour1));
  65084. colours.add (ColourPoint (1.0, colour2));
  65085. }
  65086. ColourGradient::~ColourGradient()
  65087. {
  65088. }
  65089. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  65090. {
  65091. return point1 == other.point1 && point2 == other.point2
  65092. && isRadial == other.isRadial
  65093. && colours == other.colours;
  65094. }
  65095. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  65096. {
  65097. return ! operator== (other);
  65098. }
  65099. void ColourGradient::clearColours()
  65100. {
  65101. colours.clear();
  65102. }
  65103. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  65104. {
  65105. // must be within the two end-points
  65106. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  65107. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  65108. int i;
  65109. for (i = 0; i < colours.size(); ++i)
  65110. if (colours.getReference(i).position > pos)
  65111. break;
  65112. colours.insert (i, ColourPoint (pos, colour));
  65113. return i;
  65114. }
  65115. void ColourGradient::removeColour (int index)
  65116. {
  65117. jassert (index > 0 && index < colours.size() - 1);
  65118. colours.remove (index);
  65119. }
  65120. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  65121. {
  65122. for (int i = 0; i < colours.size(); ++i)
  65123. {
  65124. Colour& c = colours.getReference(i).colour;
  65125. c = c.withMultipliedAlpha (multiplier);
  65126. }
  65127. }
  65128. int ColourGradient::getNumColours() const throw()
  65129. {
  65130. return colours.size();
  65131. }
  65132. double ColourGradient::getColourPosition (const int index) const throw()
  65133. {
  65134. if (isPositiveAndBelow (index, colours.size()))
  65135. return colours.getReference (index).position;
  65136. return 0;
  65137. }
  65138. const Colour ColourGradient::getColour (const int index) const throw()
  65139. {
  65140. if (isPositiveAndBelow (index, colours.size()))
  65141. return colours.getReference (index).colour;
  65142. return Colour();
  65143. }
  65144. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  65145. {
  65146. if (isPositiveAndBelow (index, colours.size()))
  65147. colours.getReference (index).colour = newColour;
  65148. }
  65149. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  65150. {
  65151. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65152. if (position <= 0 || colours.size() <= 1)
  65153. return colours.getReference(0).colour;
  65154. int i = colours.size() - 1;
  65155. while (position < colours.getReference(i).position)
  65156. --i;
  65157. const ColourPoint& p1 = colours.getReference (i);
  65158. if (i >= colours.size() - 1)
  65159. return p1.colour;
  65160. const ColourPoint& p2 = colours.getReference (i + 1);
  65161. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  65162. }
  65163. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  65164. {
  65165. #if JUCE_DEBUG
  65166. // trying to use the object without setting its co-ordinates? Have a careful read of
  65167. // the comments for the constructors.
  65168. jassert (point1.getX() != 987654.0f);
  65169. #endif
  65170. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65171. 3 * (int) point1.transformedBy (transform)
  65172. .getDistanceFrom (point2.transformedBy (transform)));
  65173. lookupTable.malloc (numEntries);
  65174. if (colours.size() >= 2)
  65175. {
  65176. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65177. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65178. int index = 0;
  65179. for (int j = 1; j < colours.size(); ++j)
  65180. {
  65181. const ColourPoint& p = colours.getReference (j);
  65182. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65183. const PixelARGB pix2 (p.colour.getPixelARGB());
  65184. for (int i = 0; i < numToDo; ++i)
  65185. {
  65186. jassert (index >= 0 && index < numEntries);
  65187. lookupTable[index] = pix1;
  65188. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65189. ++index;
  65190. }
  65191. pix1 = pix2;
  65192. }
  65193. while (index < numEntries)
  65194. lookupTable [index++] = pix1;
  65195. }
  65196. else
  65197. {
  65198. jassertfalse; // no colours specified!
  65199. }
  65200. return numEntries;
  65201. }
  65202. bool ColourGradient::isOpaque() const throw()
  65203. {
  65204. for (int i = 0; i < colours.size(); ++i)
  65205. if (! colours.getReference(i).colour.isOpaque())
  65206. return false;
  65207. return true;
  65208. }
  65209. bool ColourGradient::isInvisible() const throw()
  65210. {
  65211. for (int i = 0; i < colours.size(); ++i)
  65212. if (! colours.getReference(i).colour.isTransparent())
  65213. return false;
  65214. return true;
  65215. }
  65216. END_JUCE_NAMESPACE
  65217. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65218. /*** Start of inlined file: juce_Colours.cpp ***/
  65219. BEGIN_JUCE_NAMESPACE
  65220. const Colour Colours::transparentBlack (0);
  65221. const Colour Colours::transparentWhite (0x00ffffff);
  65222. const Colour Colours::aliceblue (0xfff0f8ff);
  65223. const Colour Colours::antiquewhite (0xfffaebd7);
  65224. const Colour Colours::aqua (0xff00ffff);
  65225. const Colour Colours::aquamarine (0xff7fffd4);
  65226. const Colour Colours::azure (0xfff0ffff);
  65227. const Colour Colours::beige (0xfff5f5dc);
  65228. const Colour Colours::bisque (0xffffe4c4);
  65229. const Colour Colours::black (0xff000000);
  65230. const Colour Colours::blanchedalmond (0xffffebcd);
  65231. const Colour Colours::blue (0xff0000ff);
  65232. const Colour Colours::blueviolet (0xff8a2be2);
  65233. const Colour Colours::brown (0xffa52a2a);
  65234. const Colour Colours::burlywood (0xffdeb887);
  65235. const Colour Colours::cadetblue (0xff5f9ea0);
  65236. const Colour Colours::chartreuse (0xff7fff00);
  65237. const Colour Colours::chocolate (0xffd2691e);
  65238. const Colour Colours::coral (0xffff7f50);
  65239. const Colour Colours::cornflowerblue (0xff6495ed);
  65240. const Colour Colours::cornsilk (0xfffff8dc);
  65241. const Colour Colours::crimson (0xffdc143c);
  65242. const Colour Colours::cyan (0xff00ffff);
  65243. const Colour Colours::darkblue (0xff00008b);
  65244. const Colour Colours::darkcyan (0xff008b8b);
  65245. const Colour Colours::darkgoldenrod (0xffb8860b);
  65246. const Colour Colours::darkgrey (0xff555555);
  65247. const Colour Colours::darkgreen (0xff006400);
  65248. const Colour Colours::darkkhaki (0xffbdb76b);
  65249. const Colour Colours::darkmagenta (0xff8b008b);
  65250. const Colour Colours::darkolivegreen (0xff556b2f);
  65251. const Colour Colours::darkorange (0xffff8c00);
  65252. const Colour Colours::darkorchid (0xff9932cc);
  65253. const Colour Colours::darkred (0xff8b0000);
  65254. const Colour Colours::darksalmon (0xffe9967a);
  65255. const Colour Colours::darkseagreen (0xff8fbc8f);
  65256. const Colour Colours::darkslateblue (0xff483d8b);
  65257. const Colour Colours::darkslategrey (0xff2f4f4f);
  65258. const Colour Colours::darkturquoise (0xff00ced1);
  65259. const Colour Colours::darkviolet (0xff9400d3);
  65260. const Colour Colours::deeppink (0xffff1493);
  65261. const Colour Colours::deepskyblue (0xff00bfff);
  65262. const Colour Colours::dimgrey (0xff696969);
  65263. const Colour Colours::dodgerblue (0xff1e90ff);
  65264. const Colour Colours::firebrick (0xffb22222);
  65265. const Colour Colours::floralwhite (0xfffffaf0);
  65266. const Colour Colours::forestgreen (0xff228b22);
  65267. const Colour Colours::fuchsia (0xffff00ff);
  65268. const Colour Colours::gainsboro (0xffdcdcdc);
  65269. const Colour Colours::gold (0xffffd700);
  65270. const Colour Colours::goldenrod (0xffdaa520);
  65271. const Colour Colours::grey (0xff808080);
  65272. const Colour Colours::green (0xff008000);
  65273. const Colour Colours::greenyellow (0xffadff2f);
  65274. const Colour Colours::honeydew (0xfff0fff0);
  65275. const Colour Colours::hotpink (0xffff69b4);
  65276. const Colour Colours::indianred (0xffcd5c5c);
  65277. const Colour Colours::indigo (0xff4b0082);
  65278. const Colour Colours::ivory (0xfffffff0);
  65279. const Colour Colours::khaki (0xfff0e68c);
  65280. const Colour Colours::lavender (0xffe6e6fa);
  65281. const Colour Colours::lavenderblush (0xfffff0f5);
  65282. const Colour Colours::lemonchiffon (0xfffffacd);
  65283. const Colour Colours::lightblue (0xffadd8e6);
  65284. const Colour Colours::lightcoral (0xfff08080);
  65285. const Colour Colours::lightcyan (0xffe0ffff);
  65286. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65287. const Colour Colours::lightgreen (0xff90ee90);
  65288. const Colour Colours::lightgrey (0xffd3d3d3);
  65289. const Colour Colours::lightpink (0xffffb6c1);
  65290. const Colour Colours::lightsalmon (0xffffa07a);
  65291. const Colour Colours::lightseagreen (0xff20b2aa);
  65292. const Colour Colours::lightskyblue (0xff87cefa);
  65293. const Colour Colours::lightslategrey (0xff778899);
  65294. const Colour Colours::lightsteelblue (0xffb0c4de);
  65295. const Colour Colours::lightyellow (0xffffffe0);
  65296. const Colour Colours::lime (0xff00ff00);
  65297. const Colour Colours::limegreen (0xff32cd32);
  65298. const Colour Colours::linen (0xfffaf0e6);
  65299. const Colour Colours::magenta (0xffff00ff);
  65300. const Colour Colours::maroon (0xff800000);
  65301. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65302. const Colour Colours::mediumblue (0xff0000cd);
  65303. const Colour Colours::mediumorchid (0xffba55d3);
  65304. const Colour Colours::mediumpurple (0xff9370db);
  65305. const Colour Colours::mediumseagreen (0xff3cb371);
  65306. const Colour Colours::mediumslateblue (0xff7b68ee);
  65307. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65308. const Colour Colours::mediumturquoise (0xff48d1cc);
  65309. const Colour Colours::mediumvioletred (0xffc71585);
  65310. const Colour Colours::midnightblue (0xff191970);
  65311. const Colour Colours::mintcream (0xfff5fffa);
  65312. const Colour Colours::mistyrose (0xffffe4e1);
  65313. const Colour Colours::navajowhite (0xffffdead);
  65314. const Colour Colours::navy (0xff000080);
  65315. const Colour Colours::oldlace (0xfffdf5e6);
  65316. const Colour Colours::olive (0xff808000);
  65317. const Colour Colours::olivedrab (0xff6b8e23);
  65318. const Colour Colours::orange (0xffffa500);
  65319. const Colour Colours::orangered (0xffff4500);
  65320. const Colour Colours::orchid (0xffda70d6);
  65321. const Colour Colours::palegoldenrod (0xffeee8aa);
  65322. const Colour Colours::palegreen (0xff98fb98);
  65323. const Colour Colours::paleturquoise (0xffafeeee);
  65324. const Colour Colours::palevioletred (0xffdb7093);
  65325. const Colour Colours::papayawhip (0xffffefd5);
  65326. const Colour Colours::peachpuff (0xffffdab9);
  65327. const Colour Colours::peru (0xffcd853f);
  65328. const Colour Colours::pink (0xffffc0cb);
  65329. const Colour Colours::plum (0xffdda0dd);
  65330. const Colour Colours::powderblue (0xffb0e0e6);
  65331. const Colour Colours::purple (0xff800080);
  65332. const Colour Colours::red (0xffff0000);
  65333. const Colour Colours::rosybrown (0xffbc8f8f);
  65334. const Colour Colours::royalblue (0xff4169e1);
  65335. const Colour Colours::saddlebrown (0xff8b4513);
  65336. const Colour Colours::salmon (0xfffa8072);
  65337. const Colour Colours::sandybrown (0xfff4a460);
  65338. const Colour Colours::seagreen (0xff2e8b57);
  65339. const Colour Colours::seashell (0xfffff5ee);
  65340. const Colour Colours::sienna (0xffa0522d);
  65341. const Colour Colours::silver (0xffc0c0c0);
  65342. const Colour Colours::skyblue (0xff87ceeb);
  65343. const Colour Colours::slateblue (0xff6a5acd);
  65344. const Colour Colours::slategrey (0xff708090);
  65345. const Colour Colours::snow (0xfffffafa);
  65346. const Colour Colours::springgreen (0xff00ff7f);
  65347. const Colour Colours::steelblue (0xff4682b4);
  65348. const Colour Colours::tan (0xffd2b48c);
  65349. const Colour Colours::teal (0xff008080);
  65350. const Colour Colours::thistle (0xffd8bfd8);
  65351. const Colour Colours::tomato (0xffff6347);
  65352. const Colour Colours::turquoise (0xff40e0d0);
  65353. const Colour Colours::violet (0xffee82ee);
  65354. const Colour Colours::wheat (0xfff5deb3);
  65355. const Colour Colours::white (0xffffffff);
  65356. const Colour Colours::whitesmoke (0xfff5f5f5);
  65357. const Colour Colours::yellow (0xffffff00);
  65358. const Colour Colours::yellowgreen (0xff9acd32);
  65359. const Colour Colours::findColourForName (const String& colourName,
  65360. const Colour& defaultColour)
  65361. {
  65362. static const int presets[] =
  65363. {
  65364. // (first value is the string's hashcode, second is ARGB)
  65365. 0x05978fff, 0xff000000, /* black */
  65366. 0x06bdcc29, 0xffffffff, /* white */
  65367. 0x002e305a, 0xff0000ff, /* blue */
  65368. 0x00308adf, 0xff808080, /* grey */
  65369. 0x05e0cf03, 0xff008000, /* green */
  65370. 0x0001b891, 0xffff0000, /* red */
  65371. 0xd43c6474, 0xffffff00, /* yellow */
  65372. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65373. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65374. 0x002dcebc, 0xff00ffff, /* aqua */
  65375. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65376. 0x0590228f, 0xfff0ffff, /* azure */
  65377. 0x05947fe4, 0xfff5f5dc, /* beige */
  65378. 0xad388e35, 0xffffe4c4, /* bisque */
  65379. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65380. 0x39129959, 0xff8a2be2, /* blueviolet */
  65381. 0x059a8136, 0xffa52a2a, /* brown */
  65382. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65383. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65384. 0x6b748956, 0xff7fff00, /* chartreuse */
  65385. 0x2903623c, 0xffd2691e, /* chocolate */
  65386. 0x05a74431, 0xffff7f50, /* coral */
  65387. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65388. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65389. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65390. 0x002ed323, 0xff00ffff, /* cyan */
  65391. 0x67cc74d0, 0xff00008b, /* darkblue */
  65392. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65393. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65394. 0x67cecf55, 0xff555555, /* darkgrey */
  65395. 0x920b194d, 0xff006400, /* darkgreen */
  65396. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65397. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65398. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65399. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65400. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65401. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65402. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65403. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65404. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65405. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65406. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65407. 0xc8769375, 0xff9400d3, /* darkviolet */
  65408. 0x25832862, 0xffff1493, /* deeppink */
  65409. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65410. 0x634c8b67, 0xff696969, /* dimgrey */
  65411. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65412. 0xef19e3cb, 0xffb22222, /* firebrick */
  65413. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65414. 0xd086fd06, 0xff228b22, /* forestgreen */
  65415. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65416. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65417. 0x00308060, 0xffffd700, /* gold */
  65418. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65419. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65420. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65421. 0x41892743, 0xffff69b4, /* hotpink */
  65422. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65423. 0xb969fed2, 0xff4b0082, /* indigo */
  65424. 0x05fef6a9, 0xfffffff0, /* ivory */
  65425. 0x06149302, 0xfff0e68c, /* khaki */
  65426. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65427. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65428. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65429. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65430. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65431. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65432. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65433. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65434. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65435. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65436. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65437. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65438. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65439. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65440. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65441. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65442. 0x0032afd5, 0xff00ff00, /* lime */
  65443. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65444. 0x06234efa, 0xfffaf0e6, /* linen */
  65445. 0x316858a9, 0xffff00ff, /* magenta */
  65446. 0xbf8ca470, 0xff800000, /* maroon */
  65447. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65448. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65449. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65450. 0x07556b71, 0xff9370db, /* mediumpurple */
  65451. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65452. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65453. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65454. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65455. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65456. 0x168eb32a, 0xff191970, /* midnightblue */
  65457. 0x4306b960, 0xfff5fffa, /* mintcream */
  65458. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65459. 0xe97218a6, 0xffffdead, /* navajowhite */
  65460. 0x00337bb6, 0xff000080, /* navy */
  65461. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65462. 0x064ee1db, 0xff808000, /* olive */
  65463. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65464. 0xc3de262e, 0xffffa500, /* orange */
  65465. 0x58bebba3, 0xffff4500, /* orangered */
  65466. 0xc3def8a3, 0xffda70d6, /* orchid */
  65467. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65468. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65469. 0x74022737, 0xffafeeee, /* paleturquoise */
  65470. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65471. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65472. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65473. 0x003472f8, 0xffcd853f, /* peru */
  65474. 0x00348176, 0xffffc0cb, /* pink */
  65475. 0x00348d94, 0xffdda0dd, /* plum */
  65476. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65477. 0xc5c507bc, 0xff800080, /* purple */
  65478. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65479. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65480. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65481. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65482. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65483. 0x34636c14, 0xff2e8b57, /* seagreen */
  65484. 0x3507fb41, 0xfffff5ee, /* seashell */
  65485. 0xca348772, 0xffa0522d, /* sienna */
  65486. 0xca37d30d, 0xffc0c0c0, /* silver */
  65487. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65488. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65489. 0x44ab37f8, 0xff708090, /* slategrey */
  65490. 0x0035f183, 0xfffffafa, /* snow */
  65491. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65492. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65493. 0x0001bfa1, 0xffd2b48c, /* tan */
  65494. 0x0036425c, 0xff008080, /* teal */
  65495. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65496. 0xcc41600a, 0xffff6347, /* tomato */
  65497. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65498. 0xcf57947f, 0xffee82ee, /* violet */
  65499. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65500. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65501. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65502. };
  65503. const int hash = colourName.trim().toLowerCase().hashCode();
  65504. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65505. if (presets [i] == hash)
  65506. return Colour (presets [i + 1]);
  65507. return defaultColour;
  65508. }
  65509. END_JUCE_NAMESPACE
  65510. /*** End of inlined file: juce_Colours.cpp ***/
  65511. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65512. BEGIN_JUCE_NAMESPACE
  65513. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65514. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65515. const Path& path, const AffineTransform& transform)
  65516. : bounds (bounds_),
  65517. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65518. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65519. needToCheckEmptinesss (true)
  65520. {
  65521. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65522. int* t = table;
  65523. for (int i = bounds.getHeight(); --i >= 0;)
  65524. {
  65525. *t = 0;
  65526. t += lineStrideElements;
  65527. }
  65528. const int topLimit = bounds.getY() << 8;
  65529. const int heightLimit = bounds.getHeight() << 8;
  65530. const int leftLimit = bounds.getX() << 8;
  65531. const int rightLimit = bounds.getRight() << 8;
  65532. PathFlatteningIterator iter (path, transform);
  65533. while (iter.next())
  65534. {
  65535. int y1 = roundToInt (iter.y1 * 256.0f);
  65536. int y2 = roundToInt (iter.y2 * 256.0f);
  65537. if (y1 != y2)
  65538. {
  65539. y1 -= topLimit;
  65540. y2 -= topLimit;
  65541. const int startY = y1;
  65542. int direction = -1;
  65543. if (y1 > y2)
  65544. {
  65545. swapVariables (y1, y2);
  65546. direction = 1;
  65547. }
  65548. if (y1 < 0)
  65549. y1 = 0;
  65550. if (y2 > heightLimit)
  65551. y2 = heightLimit;
  65552. if (y1 < y2)
  65553. {
  65554. const double startX = 256.0f * iter.x1;
  65555. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65556. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65557. do
  65558. {
  65559. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65560. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65561. if (x < leftLimit)
  65562. x = leftLimit;
  65563. else if (x >= rightLimit)
  65564. x = rightLimit - 1;
  65565. addEdgePoint (x, y1 >> 8, direction * step);
  65566. y1 += step;
  65567. }
  65568. while (y1 < y2);
  65569. }
  65570. }
  65571. }
  65572. sanitiseLevels (path.isUsingNonZeroWinding());
  65573. }
  65574. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65575. : bounds (rectangleToAdd),
  65576. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65577. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65578. needToCheckEmptinesss (true)
  65579. {
  65580. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65581. table[0] = 0;
  65582. const int x1 = rectangleToAdd.getX() << 8;
  65583. const int x2 = rectangleToAdd.getRight() << 8;
  65584. int* t = table;
  65585. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65586. {
  65587. t[0] = 2;
  65588. t[1] = x1;
  65589. t[2] = 255;
  65590. t[3] = x2;
  65591. t[4] = 0;
  65592. t += lineStrideElements;
  65593. }
  65594. }
  65595. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65596. : bounds (rectanglesToAdd.getBounds()),
  65597. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65598. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65599. needToCheckEmptinesss (true)
  65600. {
  65601. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65602. int* t = table;
  65603. for (int i = bounds.getHeight(); --i >= 0;)
  65604. {
  65605. *t = 0;
  65606. t += lineStrideElements;
  65607. }
  65608. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65609. {
  65610. const Rectangle<int>* const r = iter.getRectangle();
  65611. const int x1 = r->getX() << 8;
  65612. const int x2 = r->getRight() << 8;
  65613. int y = r->getY() - bounds.getY();
  65614. for (int j = r->getHeight(); --j >= 0;)
  65615. {
  65616. addEdgePoint (x1, y, 255);
  65617. addEdgePoint (x2, y, -255);
  65618. ++y;
  65619. }
  65620. }
  65621. sanitiseLevels (true);
  65622. }
  65623. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65624. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65625. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65626. 2 + (int) rectangleToAdd.getWidth(),
  65627. 2 + (int) rectangleToAdd.getHeight())),
  65628. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65629. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65630. needToCheckEmptinesss (true)
  65631. {
  65632. jassert (! rectangleToAdd.isEmpty());
  65633. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65634. table[0] = 0;
  65635. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65636. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65637. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65638. jassert (y1 < 256);
  65639. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65640. if (x2 <= x1 || y2 <= y1)
  65641. {
  65642. bounds.setHeight (0);
  65643. return;
  65644. }
  65645. int lineY = 0;
  65646. int* t = table;
  65647. if ((y1 >> 8) == (y2 >> 8))
  65648. {
  65649. t[0] = 2;
  65650. t[1] = x1;
  65651. t[2] = y2 - y1;
  65652. t[3] = x2;
  65653. t[4] = 0;
  65654. ++lineY;
  65655. t += lineStrideElements;
  65656. }
  65657. else
  65658. {
  65659. t[0] = 2;
  65660. t[1] = x1;
  65661. t[2] = 255 - (y1 & 255);
  65662. t[3] = x2;
  65663. t[4] = 0;
  65664. ++lineY;
  65665. t += lineStrideElements;
  65666. while (lineY < (y2 >> 8))
  65667. {
  65668. t[0] = 2;
  65669. t[1] = x1;
  65670. t[2] = 255;
  65671. t[3] = x2;
  65672. t[4] = 0;
  65673. ++lineY;
  65674. t += lineStrideElements;
  65675. }
  65676. jassert (lineY < bounds.getHeight());
  65677. t[0] = 2;
  65678. t[1] = x1;
  65679. t[2] = y2 & 255;
  65680. t[3] = x2;
  65681. t[4] = 0;
  65682. ++lineY;
  65683. t += lineStrideElements;
  65684. }
  65685. while (lineY < bounds.getHeight())
  65686. {
  65687. t[0] = 0;
  65688. t += lineStrideElements;
  65689. ++lineY;
  65690. }
  65691. }
  65692. EdgeTable::EdgeTable (const EdgeTable& other)
  65693. {
  65694. operator= (other);
  65695. }
  65696. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65697. {
  65698. bounds = other.bounds;
  65699. maxEdgesPerLine = other.maxEdgesPerLine;
  65700. lineStrideElements = other.lineStrideElements;
  65701. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65702. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65703. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65704. return *this;
  65705. }
  65706. EdgeTable::~EdgeTable()
  65707. {
  65708. }
  65709. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  65710. {
  65711. while (--numLines >= 0)
  65712. {
  65713. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  65714. src += srcLineStride;
  65715. dest += destLineStride;
  65716. }
  65717. }
  65718. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  65719. {
  65720. // Convert the table from relative windings to absolute levels..
  65721. int* lineStart = table;
  65722. for (int i = bounds.getHeight(); --i >= 0;)
  65723. {
  65724. int* line = lineStart;
  65725. lineStart += lineStrideElements;
  65726. int num = *line;
  65727. if (num == 0)
  65728. continue;
  65729. int level = 0;
  65730. if (useNonZeroWinding)
  65731. {
  65732. while (--num > 0)
  65733. {
  65734. line += 2;
  65735. level += *line;
  65736. int corrected = abs (level);
  65737. if (corrected >> 8)
  65738. corrected = 255;
  65739. *line = corrected;
  65740. }
  65741. }
  65742. else
  65743. {
  65744. while (--num > 0)
  65745. {
  65746. line += 2;
  65747. level += *line;
  65748. int corrected = abs (level);
  65749. if (corrected >> 8)
  65750. {
  65751. corrected &= 511;
  65752. if (corrected >> 8)
  65753. corrected = 511 - corrected;
  65754. }
  65755. *line = corrected;
  65756. }
  65757. }
  65758. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  65759. }
  65760. }
  65761. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine)
  65762. {
  65763. if (newNumEdgesPerLine != maxEdgesPerLine)
  65764. {
  65765. maxEdgesPerLine = newNumEdgesPerLine;
  65766. jassert (bounds.getHeight() > 0);
  65767. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  65768. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  65769. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  65770. table.swapWith (newTable);
  65771. lineStrideElements = newLineStrideElements;
  65772. }
  65773. }
  65774. void EdgeTable::optimiseTable()
  65775. {
  65776. int maxLineElements = 0;
  65777. for (int i = bounds.getHeight(); --i >= 0;)
  65778. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  65779. remapTableForNumEdges (maxLineElements);
  65780. }
  65781. void EdgeTable::addEdgePoint (const int x, const int y, const int winding)
  65782. {
  65783. jassert (y >= 0 && y < bounds.getHeight());
  65784. int* line = table + lineStrideElements * y;
  65785. const int numPoints = line[0];
  65786. int n = numPoints << 1;
  65787. if (n > 0)
  65788. {
  65789. while (n > 0)
  65790. {
  65791. const int cx = line [n - 1];
  65792. if (cx <= x)
  65793. {
  65794. if (cx == x)
  65795. {
  65796. line [n] += winding;
  65797. return;
  65798. }
  65799. break;
  65800. }
  65801. n -= 2;
  65802. }
  65803. if (numPoints >= maxEdgesPerLine)
  65804. {
  65805. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65806. jassert (numPoints < maxEdgesPerLine);
  65807. line = table + lineStrideElements * y;
  65808. }
  65809. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  65810. }
  65811. line [n + 1] = x;
  65812. line [n + 2] = winding;
  65813. line[0]++;
  65814. }
  65815. void EdgeTable::translate (float dx, const int dy) throw()
  65816. {
  65817. bounds.translate ((int) std::floor (dx), dy);
  65818. int* lineStart = table;
  65819. const int intDx = (int) (dx * 256.0f);
  65820. for (int i = bounds.getHeight(); --i >= 0;)
  65821. {
  65822. int* line = lineStart;
  65823. lineStart += lineStrideElements;
  65824. int num = *line++;
  65825. while (--num >= 0)
  65826. {
  65827. *line += intDx;
  65828. line += 2;
  65829. }
  65830. }
  65831. }
  65832. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine)
  65833. {
  65834. jassert (y >= 0 && y < bounds.getHeight());
  65835. int* dest = table + lineStrideElements * y;
  65836. if (dest[0] == 0)
  65837. return;
  65838. int otherNumPoints = *otherLine;
  65839. if (otherNumPoints == 0)
  65840. {
  65841. *dest = 0;
  65842. return;
  65843. }
  65844. const int right = bounds.getRight() << 8;
  65845. // optimise for the common case where our line lies entirely within a
  65846. // single pair of points, as happens when clipping to a simple rect.
  65847. if (otherNumPoints == 2 && otherLine[2] >= 255)
  65848. {
  65849. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  65850. return;
  65851. }
  65852. ++otherLine;
  65853. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  65854. int* temp = static_cast<int*> (alloca (lineSizeBytes));
  65855. memcpy (temp, dest, lineSizeBytes);
  65856. const int* src1 = temp;
  65857. int srcNum1 = *src1++;
  65858. int x1 = *src1++;
  65859. const int* src2 = otherLine;
  65860. int srcNum2 = otherNumPoints;
  65861. int x2 = *src2++;
  65862. int destIndex = 0, destTotal = 0;
  65863. int level1 = 0, level2 = 0;
  65864. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  65865. while (srcNum1 > 0 && srcNum2 > 0)
  65866. {
  65867. int nextX;
  65868. if (x1 < x2)
  65869. {
  65870. nextX = x1;
  65871. level1 = *src1++;
  65872. x1 = *src1++;
  65873. --srcNum1;
  65874. }
  65875. else if (x1 == x2)
  65876. {
  65877. nextX = x1;
  65878. level1 = *src1++;
  65879. level2 = *src2++;
  65880. x1 = *src1++;
  65881. x2 = *src2++;
  65882. --srcNum1;
  65883. --srcNum2;
  65884. }
  65885. else
  65886. {
  65887. nextX = x2;
  65888. level2 = *src2++;
  65889. x2 = *src2++;
  65890. --srcNum2;
  65891. }
  65892. if (nextX > lastX)
  65893. {
  65894. if (nextX >= right)
  65895. break;
  65896. lastX = nextX;
  65897. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  65898. jassert (isPositiveAndBelow (nextLevel, (int) 256));
  65899. if (nextLevel != lastLevel)
  65900. {
  65901. if (destTotal >= maxEdgesPerLine)
  65902. {
  65903. dest[0] = destTotal;
  65904. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65905. dest = table + lineStrideElements * y;
  65906. }
  65907. ++destTotal;
  65908. lastLevel = nextLevel;
  65909. dest[++destIndex] = nextX;
  65910. dest[++destIndex] = nextLevel;
  65911. }
  65912. }
  65913. }
  65914. if (lastLevel > 0)
  65915. {
  65916. if (destTotal >= maxEdgesPerLine)
  65917. {
  65918. dest[0] = destTotal;
  65919. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65920. dest = table + lineStrideElements * y;
  65921. }
  65922. ++destTotal;
  65923. dest[++destIndex] = right;
  65924. dest[++destIndex] = 0;
  65925. }
  65926. dest[0] = destTotal;
  65927. #if JUCE_DEBUG
  65928. int last = std::numeric_limits<int>::min();
  65929. for (int i = 0; i < dest[0]; ++i)
  65930. {
  65931. jassert (dest[i * 2 + 1] > last);
  65932. last = dest[i * 2 + 1];
  65933. }
  65934. jassert (dest [dest[0] * 2] == 0);
  65935. #endif
  65936. }
  65937. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  65938. {
  65939. int* lastItem = dest + (dest[0] * 2 - 1);
  65940. if (x2 < lastItem[0])
  65941. {
  65942. if (x2 <= dest[1])
  65943. {
  65944. dest[0] = 0;
  65945. return;
  65946. }
  65947. while (x2 < lastItem[-2])
  65948. {
  65949. --(dest[0]);
  65950. lastItem -= 2;
  65951. }
  65952. lastItem[0] = x2;
  65953. lastItem[1] = 0;
  65954. }
  65955. if (x1 > dest[1])
  65956. {
  65957. while (lastItem[0] > x1)
  65958. lastItem -= 2;
  65959. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  65960. if (itemsRemoved > 0)
  65961. {
  65962. dest[0] -= itemsRemoved;
  65963. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  65964. }
  65965. dest[1] = x1;
  65966. }
  65967. }
  65968. void EdgeTable::clipToRectangle (const Rectangle<int>& r)
  65969. {
  65970. const Rectangle<int> clipped (r.getIntersection (bounds));
  65971. if (clipped.isEmpty())
  65972. {
  65973. needToCheckEmptinesss = false;
  65974. bounds.setHeight (0);
  65975. }
  65976. else
  65977. {
  65978. const int top = clipped.getY() - bounds.getY();
  65979. const int bottom = clipped.getBottom() - bounds.getY();
  65980. if (bottom < bounds.getHeight())
  65981. bounds.setHeight (bottom);
  65982. if (clipped.getRight() < bounds.getRight())
  65983. bounds.setRight (clipped.getRight());
  65984. for (int i = top; --i >= 0;)
  65985. table [lineStrideElements * i] = 0;
  65986. if (clipped.getX() > bounds.getX())
  65987. {
  65988. const int x1 = clipped.getX() << 8;
  65989. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  65990. int* line = table + lineStrideElements * top;
  65991. for (int i = bottom - top; --i >= 0;)
  65992. {
  65993. if (line[0] != 0)
  65994. clipEdgeTableLineToRange (line, x1, x2);
  65995. line += lineStrideElements;
  65996. }
  65997. }
  65998. needToCheckEmptinesss = true;
  65999. }
  66000. }
  66001. void EdgeTable::excludeRectangle (const Rectangle<int>& r)
  66002. {
  66003. const Rectangle<int> clipped (r.getIntersection (bounds));
  66004. if (! clipped.isEmpty())
  66005. {
  66006. const int top = clipped.getY() - bounds.getY();
  66007. const int bottom = clipped.getBottom() - bounds.getY();
  66008. //XXX optimise here by shortening the table if it fills top or bottom
  66009. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  66010. clipped.getX() << 8, 0,
  66011. clipped.getRight() << 8, 255,
  66012. std::numeric_limits<int>::max(), 0 };
  66013. for (int i = top; i < bottom; ++i)
  66014. intersectWithEdgeTableLine (i, rectLine);
  66015. needToCheckEmptinesss = true;
  66016. }
  66017. }
  66018. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  66019. {
  66020. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  66021. if (clipped.isEmpty())
  66022. {
  66023. needToCheckEmptinesss = false;
  66024. bounds.setHeight (0);
  66025. }
  66026. else
  66027. {
  66028. const int top = clipped.getY() - bounds.getY();
  66029. const int bottom = clipped.getBottom() - bounds.getY();
  66030. if (bottom < bounds.getHeight())
  66031. bounds.setHeight (bottom);
  66032. if (clipped.getRight() < bounds.getRight())
  66033. bounds.setRight (clipped.getRight());
  66034. int i = 0;
  66035. for (i = top; --i >= 0;)
  66036. table [lineStrideElements * i] = 0;
  66037. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  66038. for (i = top; i < bottom; ++i)
  66039. {
  66040. intersectWithEdgeTableLine (i, otherLine);
  66041. otherLine += other.lineStrideElements;
  66042. }
  66043. needToCheckEmptinesss = true;
  66044. }
  66045. }
  66046. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels)
  66047. {
  66048. y -= bounds.getY();
  66049. if (y < 0 || y >= bounds.getHeight())
  66050. return;
  66051. needToCheckEmptinesss = true;
  66052. if (numPixels <= 0)
  66053. {
  66054. table [lineStrideElements * y] = 0;
  66055. return;
  66056. }
  66057. int* tempLine = static_cast<int*> (alloca ((numPixels * 2 + 4) * sizeof (int)));
  66058. int destIndex = 0, lastLevel = 0;
  66059. while (--numPixels >= 0)
  66060. {
  66061. const int alpha = *mask;
  66062. mask += maskStride;
  66063. if (alpha != lastLevel)
  66064. {
  66065. tempLine[++destIndex] = (x << 8);
  66066. tempLine[++destIndex] = alpha;
  66067. lastLevel = alpha;
  66068. }
  66069. ++x;
  66070. }
  66071. if (lastLevel > 0)
  66072. {
  66073. tempLine[++destIndex] = (x << 8);
  66074. tempLine[++destIndex] = 0;
  66075. }
  66076. tempLine[0] = destIndex >> 1;
  66077. intersectWithEdgeTableLine (y, tempLine);
  66078. }
  66079. bool EdgeTable::isEmpty() throw()
  66080. {
  66081. if (needToCheckEmptinesss)
  66082. {
  66083. needToCheckEmptinesss = false;
  66084. int* t = table;
  66085. for (int i = bounds.getHeight(); --i >= 0;)
  66086. {
  66087. if (t[0] > 1)
  66088. return false;
  66089. t += lineStrideElements;
  66090. }
  66091. bounds.setHeight (0);
  66092. }
  66093. return bounds.getHeight() == 0;
  66094. }
  66095. END_JUCE_NAMESPACE
  66096. /*** End of inlined file: juce_EdgeTable.cpp ***/
  66097. /*** Start of inlined file: juce_FillType.cpp ***/
  66098. BEGIN_JUCE_NAMESPACE
  66099. FillType::FillType() throw()
  66100. : colour (0xff000000), image (0)
  66101. {
  66102. }
  66103. FillType::FillType (const Colour& colour_) throw()
  66104. : colour (colour_), image (0)
  66105. {
  66106. }
  66107. FillType::FillType (const ColourGradient& gradient_)
  66108. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  66109. {
  66110. }
  66111. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  66112. : colour (0xff000000), image (image_), transform (transform_)
  66113. {
  66114. }
  66115. FillType::FillType (const FillType& other)
  66116. : colour (other.colour),
  66117. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  66118. image (other.image), transform (other.transform)
  66119. {
  66120. }
  66121. FillType& FillType::operator= (const FillType& other)
  66122. {
  66123. if (this != &other)
  66124. {
  66125. colour = other.colour;
  66126. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  66127. image = other.image;
  66128. transform = other.transform;
  66129. }
  66130. return *this;
  66131. }
  66132. FillType::~FillType() throw()
  66133. {
  66134. }
  66135. bool FillType::operator== (const FillType& other) const
  66136. {
  66137. return colour == other.colour && image == other.image
  66138. && transform == other.transform
  66139. && (gradient == other.gradient
  66140. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  66141. }
  66142. bool FillType::operator!= (const FillType& other) const
  66143. {
  66144. return ! operator== (other);
  66145. }
  66146. void FillType::setColour (const Colour& newColour) throw()
  66147. {
  66148. gradient = 0;
  66149. image = Image::null;
  66150. colour = newColour;
  66151. }
  66152. void FillType::setGradient (const ColourGradient& newGradient)
  66153. {
  66154. if (gradient != 0)
  66155. {
  66156. *gradient = newGradient;
  66157. }
  66158. else
  66159. {
  66160. image = Image::null;
  66161. gradient = new ColourGradient (newGradient);
  66162. colour = Colours::black;
  66163. }
  66164. }
  66165. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  66166. {
  66167. gradient = 0;
  66168. image = image_;
  66169. transform = transform_;
  66170. colour = Colours::black;
  66171. }
  66172. void FillType::setOpacity (const float newOpacity) throw()
  66173. {
  66174. colour = colour.withAlpha (newOpacity);
  66175. }
  66176. bool FillType::isInvisible() const throw()
  66177. {
  66178. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66179. }
  66180. END_JUCE_NAMESPACE
  66181. /*** End of inlined file: juce_FillType.cpp ***/
  66182. /*** Start of inlined file: juce_Graphics.cpp ***/
  66183. BEGIN_JUCE_NAMESPACE
  66184. namespace
  66185. {
  66186. template <typename Type>
  66187. bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66188. {
  66189. const int maxVal = 0x3fffffff;
  66190. return (int) x >= -maxVal && (int) x <= maxVal
  66191. && (int) y >= -maxVal && (int) y <= maxVal
  66192. && (int) w >= -maxVal && (int) w <= maxVal
  66193. && (int) h >= -maxVal && (int) h <= maxVal;
  66194. }
  66195. }
  66196. LowLevelGraphicsContext::LowLevelGraphicsContext()
  66197. {
  66198. }
  66199. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  66200. {
  66201. }
  66202. Graphics::Graphics (const Image& imageToDrawOnto)
  66203. : context (imageToDrawOnto.createLowLevelContext()),
  66204. contextToDelete (context),
  66205. saveStatePending (false)
  66206. {
  66207. }
  66208. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66209. : context (internalContext),
  66210. saveStatePending (false)
  66211. {
  66212. }
  66213. Graphics::~Graphics()
  66214. {
  66215. }
  66216. void Graphics::resetToDefaultState()
  66217. {
  66218. saveStateIfPending();
  66219. context->setFill (FillType());
  66220. context->setFont (Font());
  66221. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66222. }
  66223. bool Graphics::isVectorDevice() const
  66224. {
  66225. return context->isVectorDevice();
  66226. }
  66227. bool Graphics::reduceClipRegion (const Rectangle<int>& area)
  66228. {
  66229. saveStateIfPending();
  66230. return context->clipToRectangle (area);
  66231. }
  66232. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66233. {
  66234. return reduceClipRegion (Rectangle<int> (x, y, w, h));
  66235. }
  66236. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66237. {
  66238. saveStateIfPending();
  66239. return context->clipToRectangleList (clipRegion);
  66240. }
  66241. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66242. {
  66243. saveStateIfPending();
  66244. context->clipToPath (path, transform);
  66245. return ! context->isClipEmpty();
  66246. }
  66247. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66248. {
  66249. saveStateIfPending();
  66250. context->clipToImageAlpha (image, transform);
  66251. return ! context->isClipEmpty();
  66252. }
  66253. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66254. {
  66255. saveStateIfPending();
  66256. context->excludeClipRectangle (rectangleToExclude);
  66257. }
  66258. bool Graphics::isClipEmpty() const
  66259. {
  66260. return context->isClipEmpty();
  66261. }
  66262. const Rectangle<int> Graphics::getClipBounds() const
  66263. {
  66264. return context->getClipBounds();
  66265. }
  66266. void Graphics::saveState()
  66267. {
  66268. saveStateIfPending();
  66269. saveStatePending = true;
  66270. }
  66271. void Graphics::restoreState()
  66272. {
  66273. if (saveStatePending)
  66274. saveStatePending = false;
  66275. else
  66276. context->restoreState();
  66277. }
  66278. void Graphics::saveStateIfPending()
  66279. {
  66280. if (saveStatePending)
  66281. {
  66282. saveStatePending = false;
  66283. context->saveState();
  66284. }
  66285. }
  66286. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66287. {
  66288. saveStateIfPending();
  66289. context->setOrigin (newOriginX, newOriginY);
  66290. }
  66291. void Graphics::addTransform (const AffineTransform& transform)
  66292. {
  66293. saveStateIfPending();
  66294. context->addTransform (transform);
  66295. }
  66296. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66297. {
  66298. return context->clipRegionIntersects (area);
  66299. }
  66300. void Graphics::beginTransparencyLayer (float layerOpacity)
  66301. {
  66302. saveStateIfPending();
  66303. context->beginTransparencyLayer (layerOpacity);
  66304. }
  66305. void Graphics::endTransparencyLayer()
  66306. {
  66307. context->endTransparencyLayer();
  66308. }
  66309. void Graphics::setColour (const Colour& newColour)
  66310. {
  66311. saveStateIfPending();
  66312. context->setFill (newColour);
  66313. }
  66314. void Graphics::setOpacity (const float newOpacity)
  66315. {
  66316. saveStateIfPending();
  66317. context->setOpacity (newOpacity);
  66318. }
  66319. void Graphics::setGradientFill (const ColourGradient& gradient)
  66320. {
  66321. setFillType (gradient);
  66322. }
  66323. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66324. {
  66325. saveStateIfPending();
  66326. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66327. context->setOpacity (opacity);
  66328. }
  66329. void Graphics::setFillType (const FillType& newFill)
  66330. {
  66331. saveStateIfPending();
  66332. context->setFill (newFill);
  66333. }
  66334. void Graphics::setFont (const Font& newFont)
  66335. {
  66336. saveStateIfPending();
  66337. context->setFont (newFont);
  66338. }
  66339. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66340. {
  66341. saveStateIfPending();
  66342. Font f (context->getFont());
  66343. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66344. context->setFont (f);
  66345. }
  66346. const Font Graphics::getCurrentFont() const
  66347. {
  66348. return context->getFont();
  66349. }
  66350. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66351. {
  66352. if (text.isNotEmpty()
  66353. && startX < context->getClipBounds().getRight())
  66354. {
  66355. GlyphArrangement arr;
  66356. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66357. arr.draw (*this);
  66358. }
  66359. }
  66360. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66361. {
  66362. if (text.isNotEmpty())
  66363. {
  66364. GlyphArrangement arr;
  66365. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66366. arr.draw (*this, transform);
  66367. }
  66368. }
  66369. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66370. {
  66371. if (text.isNotEmpty()
  66372. && startX < context->getClipBounds().getRight())
  66373. {
  66374. GlyphArrangement arr;
  66375. arr.addJustifiedText (context->getFont(), text,
  66376. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66377. Justification::left);
  66378. arr.draw (*this);
  66379. }
  66380. }
  66381. void Graphics::drawText (const String& text,
  66382. const int x, const int y, const int width, const int height,
  66383. const Justification& justificationType,
  66384. const bool useEllipsesIfTooBig) const
  66385. {
  66386. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66387. {
  66388. GlyphArrangement arr;
  66389. arr.addCurtailedLineOfText (context->getFont(), text,
  66390. 0.0f, 0.0f, (float) width,
  66391. useEllipsesIfTooBig);
  66392. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66393. (float) x, (float) y, (float) width, (float) height,
  66394. justificationType);
  66395. arr.draw (*this);
  66396. }
  66397. }
  66398. void Graphics::drawFittedText (const String& text,
  66399. const int x, const int y, const int width, const int height,
  66400. const Justification& justification,
  66401. const int maximumNumberOfLines,
  66402. const float minimumHorizontalScale) const
  66403. {
  66404. if (text.isNotEmpty()
  66405. && width > 0 && height > 0
  66406. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66407. {
  66408. GlyphArrangement arr;
  66409. arr.addFittedText (context->getFont(), text,
  66410. (float) x, (float) y, (float) width, (float) height,
  66411. justification,
  66412. maximumNumberOfLines,
  66413. minimumHorizontalScale);
  66414. arr.draw (*this);
  66415. }
  66416. }
  66417. void Graphics::fillRect (int x, int y, int width, int height) const
  66418. {
  66419. // passing in a silly number can cause maths problems in rendering!
  66420. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66421. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66422. }
  66423. void Graphics::fillRect (const Rectangle<int>& r) const
  66424. {
  66425. context->fillRect (r, false);
  66426. }
  66427. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66428. {
  66429. // passing in a silly number can cause maths problems in rendering!
  66430. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66431. Path p;
  66432. p.addRectangle (x, y, width, height);
  66433. fillPath (p);
  66434. }
  66435. void Graphics::setPixel (int x, int y) const
  66436. {
  66437. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66438. }
  66439. void Graphics::fillAll() const
  66440. {
  66441. fillRect (context->getClipBounds());
  66442. }
  66443. void Graphics::fillAll (const Colour& colourToUse) const
  66444. {
  66445. if (! colourToUse.isTransparent())
  66446. {
  66447. const Rectangle<int> clip (context->getClipBounds());
  66448. context->saveState();
  66449. context->setFill (colourToUse);
  66450. context->fillRect (clip, false);
  66451. context->restoreState();
  66452. }
  66453. }
  66454. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66455. {
  66456. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66457. context->fillPath (path, transform);
  66458. }
  66459. void Graphics::strokePath (const Path& path,
  66460. const PathStrokeType& strokeType,
  66461. const AffineTransform& transform) const
  66462. {
  66463. Path stroke;
  66464. strokeType.createStrokedPath (stroke, path, transform, context->getScaleFactor());
  66465. fillPath (stroke);
  66466. }
  66467. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66468. const int lineThickness) const
  66469. {
  66470. // passing in a silly number can cause maths problems in rendering!
  66471. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66472. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66473. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66474. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66475. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66476. }
  66477. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66478. {
  66479. // passing in a silly number can cause maths problems in rendering!
  66480. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66481. Path p;
  66482. p.addRectangle (x, y, width, lineThickness);
  66483. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66484. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66485. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66486. fillPath (p);
  66487. }
  66488. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66489. {
  66490. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66491. }
  66492. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66493. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66494. const bool useGradient, const bool sharpEdgeOnOutside) const
  66495. {
  66496. // passing in a silly number can cause maths problems in rendering!
  66497. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66498. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66499. {
  66500. context->saveState();
  66501. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66502. const float ramp = oldOpacity / bevelThickness;
  66503. for (int i = bevelThickness; --i >= 0;)
  66504. {
  66505. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66506. : oldOpacity;
  66507. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66508. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66509. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66510. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66511. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66512. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66513. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66514. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66515. }
  66516. context->restoreState();
  66517. }
  66518. }
  66519. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66520. {
  66521. // passing in a silly number can cause maths problems in rendering!
  66522. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66523. Path p;
  66524. p.addEllipse (x, y, width, height);
  66525. fillPath (p);
  66526. }
  66527. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66528. const float lineThickness) const
  66529. {
  66530. // passing in a silly number can cause maths problems in rendering!
  66531. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66532. Path p;
  66533. p.addEllipse (x, y, width, height);
  66534. strokePath (p, PathStrokeType (lineThickness));
  66535. }
  66536. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  66537. {
  66538. // passing in a silly number can cause maths problems in rendering!
  66539. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66540. Path p;
  66541. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66542. fillPath (p);
  66543. }
  66544. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66545. {
  66546. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66547. }
  66548. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66549. const float cornerSize, const float lineThickness) const
  66550. {
  66551. // passing in a silly number can cause maths problems in rendering!
  66552. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66553. Path p;
  66554. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66555. strokePath (p, PathStrokeType (lineThickness));
  66556. }
  66557. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66558. {
  66559. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66560. }
  66561. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66562. {
  66563. Path p;
  66564. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66565. fillPath (p);
  66566. }
  66567. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66568. const int checkWidth, const int checkHeight,
  66569. const Colour& colour1, const Colour& colour2) const
  66570. {
  66571. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66572. if (checkWidth > 0 && checkHeight > 0)
  66573. {
  66574. context->saveState();
  66575. if (colour1 == colour2)
  66576. {
  66577. context->setFill (colour1);
  66578. context->fillRect (area, false);
  66579. }
  66580. else
  66581. {
  66582. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66583. if (! clipped.isEmpty())
  66584. {
  66585. context->clipToRectangle (clipped);
  66586. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66587. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66588. const int startX = area.getX() + checkNumX * checkWidth;
  66589. const int startY = area.getY() + checkNumY * checkHeight;
  66590. const int right = clipped.getRight();
  66591. const int bottom = clipped.getBottom();
  66592. for (int i = 0; i < 2; ++i)
  66593. {
  66594. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66595. int cy = i;
  66596. for (int y = startY; y < bottom; y += checkHeight)
  66597. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66598. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66599. }
  66600. }
  66601. }
  66602. context->restoreState();
  66603. }
  66604. }
  66605. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66606. {
  66607. context->drawVerticalLine (x, top, bottom);
  66608. }
  66609. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  66610. {
  66611. context->drawHorizontalLine (y, left, right);
  66612. }
  66613. void Graphics::drawLine (const float x1, const float y1, const float x2, const float y2) const
  66614. {
  66615. context->drawLine (Line<float> (x1, y1, x2, y2));
  66616. }
  66617. void Graphics::drawLine (const Line<float>& line) const
  66618. {
  66619. context->drawLine (line);
  66620. }
  66621. void Graphics::drawLine (const float x1, const float y1, const float x2, const float y2, const float lineThickness) const
  66622. {
  66623. drawLine (Line<float> (x1, y1, x2, y2), lineThickness);
  66624. }
  66625. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  66626. {
  66627. Path p;
  66628. p.addLineSegment (line, lineThickness);
  66629. fillPath (p);
  66630. }
  66631. void Graphics::drawDashedLine (const Line<float>& line, const float* const dashLengths,
  66632. const int numDashLengths, const float lineThickness, int n) const
  66633. {
  66634. jassert (n >= 0 && n < numDashLengths); // your start index must be valid!
  66635. const Point<double> delta ((line.getEnd() - line.getStart()).toDouble());
  66636. const double totalLen = delta.getDistanceFromOrigin();
  66637. if (totalLen >= 0.1)
  66638. {
  66639. const double onePixAlpha = 1.0 / totalLen;
  66640. for (double alpha = 0.0; alpha < 1.0;)
  66641. {
  66642. jassert (dashLengths[n] > 0); // can't have zero-length dashes!
  66643. const double lastAlpha = alpha;
  66644. alpha = jmin (1.0, alpha + dashLengths [n] * onePixAlpha);
  66645. n = (n + 1) % numDashLengths;
  66646. if ((n & 1) != 0)
  66647. {
  66648. const Line<float> segment (line.getStart() + (delta * lastAlpha).toFloat(),
  66649. line.getStart() + (delta * alpha).toFloat());
  66650. if (lineThickness != 1.0f)
  66651. drawLine (segment, lineThickness);
  66652. else
  66653. context->drawLine (segment);
  66654. }
  66655. }
  66656. }
  66657. }
  66658. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  66659. {
  66660. saveStateIfPending();
  66661. context->setInterpolationQuality (newQuality);
  66662. }
  66663. void Graphics::drawImageAt (const Image& imageToDraw,
  66664. const int topLeftX, const int topLeftY,
  66665. const bool fillAlphaChannelWithCurrentBrush) const
  66666. {
  66667. const int imageW = imageToDraw.getWidth();
  66668. const int imageH = imageToDraw.getHeight();
  66669. drawImage (imageToDraw,
  66670. topLeftX, topLeftY, imageW, imageH,
  66671. 0, 0, imageW, imageH,
  66672. fillAlphaChannelWithCurrentBrush);
  66673. }
  66674. void Graphics::drawImageWithin (const Image& imageToDraw,
  66675. const int destX, const int destY,
  66676. const int destW, const int destH,
  66677. const RectanglePlacement& placementWithinTarget,
  66678. const bool fillAlphaChannelWithCurrentBrush) const
  66679. {
  66680. // passing in a silly number can cause maths problems in rendering!
  66681. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  66682. if (imageToDraw.isValid())
  66683. {
  66684. const int imageW = imageToDraw.getWidth();
  66685. const int imageH = imageToDraw.getHeight();
  66686. if (imageW > 0 && imageH > 0)
  66687. {
  66688. double newX = 0.0, newY = 0.0;
  66689. double newW = imageW;
  66690. double newH = imageH;
  66691. placementWithinTarget.applyTo (newX, newY, newW, newH,
  66692. destX, destY, destW, destH);
  66693. if (newW > 0 && newH > 0)
  66694. {
  66695. drawImage (imageToDraw,
  66696. roundToInt (newX), roundToInt (newY),
  66697. roundToInt (newW), roundToInt (newH),
  66698. 0, 0, imageW, imageH,
  66699. fillAlphaChannelWithCurrentBrush);
  66700. }
  66701. }
  66702. }
  66703. }
  66704. void Graphics::drawImage (const Image& imageToDraw,
  66705. int dx, int dy, int dw, int dh,
  66706. int sx, int sy, int sw, int sh,
  66707. const bool fillAlphaChannelWithCurrentBrush) const
  66708. {
  66709. // passing in a silly number can cause maths problems in rendering!
  66710. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  66711. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  66712. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  66713. {
  66714. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  66715. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  66716. .translated ((float) dx, (float) dy),
  66717. fillAlphaChannelWithCurrentBrush);
  66718. }
  66719. }
  66720. void Graphics::drawImageTransformed (const Image& imageToDraw,
  66721. const AffineTransform& transform,
  66722. const bool fillAlphaChannelWithCurrentBrush) const
  66723. {
  66724. if (imageToDraw.isValid() && ! context->isClipEmpty())
  66725. {
  66726. if (fillAlphaChannelWithCurrentBrush)
  66727. {
  66728. context->saveState();
  66729. context->clipToImageAlpha (imageToDraw, transform);
  66730. fillAll();
  66731. context->restoreState();
  66732. }
  66733. else
  66734. {
  66735. context->drawImage (imageToDraw, transform, false);
  66736. }
  66737. }
  66738. }
  66739. Graphics::ScopedSaveState::ScopedSaveState (Graphics& g)
  66740. : context (g)
  66741. {
  66742. context.saveState();
  66743. }
  66744. Graphics::ScopedSaveState::~ScopedSaveState()
  66745. {
  66746. context.restoreState();
  66747. }
  66748. END_JUCE_NAMESPACE
  66749. /*** End of inlined file: juce_Graphics.cpp ***/
  66750. /*** Start of inlined file: juce_Justification.cpp ***/
  66751. BEGIN_JUCE_NAMESPACE
  66752. Justification::Justification (const Justification& other) throw()
  66753. : flags (other.flags)
  66754. {
  66755. }
  66756. Justification& Justification::operator= (const Justification& other) throw()
  66757. {
  66758. flags = other.flags;
  66759. return *this;
  66760. }
  66761. int Justification::getOnlyVerticalFlags() const throw()
  66762. {
  66763. return flags & (top | bottom | verticallyCentred);
  66764. }
  66765. int Justification::getOnlyHorizontalFlags() const throw()
  66766. {
  66767. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  66768. }
  66769. END_JUCE_NAMESPACE
  66770. /*** End of inlined file: juce_Justification.cpp ***/
  66771. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66772. BEGIN_JUCE_NAMESPACE
  66773. // this will throw an assertion if you try to draw something that's not
  66774. // possible in postscript
  66775. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  66776. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  66777. #define notPossibleInPostscriptAssert jassertfalse
  66778. #else
  66779. #define notPossibleInPostscriptAssert
  66780. #endif
  66781. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  66782. const String& documentTitle,
  66783. const int totalWidth_,
  66784. const int totalHeight_)
  66785. : out (resultingPostScript),
  66786. totalWidth (totalWidth_),
  66787. totalHeight (totalHeight_),
  66788. needToClip (true)
  66789. {
  66790. stateStack.add (new SavedState());
  66791. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  66792. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  66793. out << "%!PS-Adobe-3.0 EPSF-3.0"
  66794. "\n%%BoundingBox: 0 0 600 824"
  66795. "\n%%Pages: 0"
  66796. "\n%%Creator: Raw Material Software JUCE"
  66797. "\n%%Title: " << documentTitle <<
  66798. "\n%%CreationDate: none"
  66799. "\n%%LanguageLevel: 2"
  66800. "\n%%EndComments"
  66801. "\n%%BeginProlog"
  66802. "\n%%BeginResource: JRes"
  66803. "\n/bd {bind def} bind def"
  66804. "\n/c {setrgbcolor} bd"
  66805. "\n/m {moveto} bd"
  66806. "\n/l {lineto} bd"
  66807. "\n/rl {rlineto} bd"
  66808. "\n/ct {curveto} bd"
  66809. "\n/cp {closepath} bd"
  66810. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  66811. "\n/doclip {initclip newpath} bd"
  66812. "\n/endclip {clip newpath} bd"
  66813. "\n%%EndResource"
  66814. "\n%%EndProlog"
  66815. "\n%%BeginSetup"
  66816. "\n%%EndSetup"
  66817. "\n%%Page: 1 1"
  66818. "\n%%BeginPageSetup"
  66819. "\n%%EndPageSetup\n\n"
  66820. << "40 800 translate\n"
  66821. << scale << ' ' << scale << " scale\n\n";
  66822. }
  66823. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  66824. {
  66825. }
  66826. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  66827. {
  66828. return true;
  66829. }
  66830. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  66831. {
  66832. if (x != 0 || y != 0)
  66833. {
  66834. stateStack.getLast()->xOffset += x;
  66835. stateStack.getLast()->yOffset += y;
  66836. needToClip = true;
  66837. }
  66838. }
  66839. void LowLevelGraphicsPostScriptRenderer::addTransform (const AffineTransform& /*transform*/)
  66840. {
  66841. //xxx
  66842. jassertfalse;
  66843. }
  66844. float LowLevelGraphicsPostScriptRenderer::getScaleFactor()
  66845. {
  66846. jassertfalse; //xxx
  66847. return 1.0f;
  66848. }
  66849. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  66850. {
  66851. needToClip = true;
  66852. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66853. }
  66854. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  66855. {
  66856. needToClip = true;
  66857. return stateStack.getLast()->clip.clipTo (clipRegion);
  66858. }
  66859. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  66860. {
  66861. needToClip = true;
  66862. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66863. }
  66864. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  66865. {
  66866. writeClip();
  66867. Path p (path);
  66868. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66869. writePath (p);
  66870. out << "clip\n";
  66871. }
  66872. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  66873. {
  66874. needToClip = true;
  66875. jassertfalse; // xxx
  66876. }
  66877. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  66878. {
  66879. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66880. }
  66881. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  66882. {
  66883. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  66884. -stateStack.getLast()->yOffset);
  66885. }
  66886. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  66887. {
  66888. return stateStack.getLast()->clip.isEmpty();
  66889. }
  66890. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  66891. : xOffset (0),
  66892. yOffset (0)
  66893. {
  66894. }
  66895. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  66896. {
  66897. }
  66898. void LowLevelGraphicsPostScriptRenderer::saveState()
  66899. {
  66900. stateStack.add (new SavedState (*stateStack.getLast()));
  66901. }
  66902. void LowLevelGraphicsPostScriptRenderer::restoreState()
  66903. {
  66904. jassert (stateStack.size() > 0);
  66905. if (stateStack.size() > 0)
  66906. stateStack.removeLast();
  66907. }
  66908. void LowLevelGraphicsPostScriptRenderer::beginTransparencyLayer (float)
  66909. {
  66910. }
  66911. void LowLevelGraphicsPostScriptRenderer::endTransparencyLayer()
  66912. {
  66913. }
  66914. void LowLevelGraphicsPostScriptRenderer::writeClip()
  66915. {
  66916. if (needToClip)
  66917. {
  66918. needToClip = false;
  66919. out << "doclip ";
  66920. int itemsOnLine = 0;
  66921. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  66922. {
  66923. if (++itemsOnLine == 6)
  66924. {
  66925. itemsOnLine = 0;
  66926. out << '\n';
  66927. }
  66928. const Rectangle<int>& r = *i.getRectangle();
  66929. out << r.getX() << ' ' << -r.getY() << ' '
  66930. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  66931. }
  66932. out << "endclip\n";
  66933. }
  66934. }
  66935. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  66936. {
  66937. Colour c (Colours::white.overlaidWith (colour));
  66938. if (lastColour != c)
  66939. {
  66940. lastColour = c;
  66941. out << String (c.getFloatRed(), 3) << ' '
  66942. << String (c.getFloatGreen(), 3) << ' '
  66943. << String (c.getFloatBlue(), 3) << " c\n";
  66944. }
  66945. }
  66946. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  66947. {
  66948. out << String (x, 2) << ' '
  66949. << String (-y, 2) << ' ';
  66950. }
  66951. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  66952. {
  66953. out << "newpath ";
  66954. float lastX = 0.0f;
  66955. float lastY = 0.0f;
  66956. int itemsOnLine = 0;
  66957. Path::Iterator i (path);
  66958. while (i.next())
  66959. {
  66960. if (++itemsOnLine == 4)
  66961. {
  66962. itemsOnLine = 0;
  66963. out << '\n';
  66964. }
  66965. switch (i.elementType)
  66966. {
  66967. case Path::Iterator::startNewSubPath:
  66968. writeXY (i.x1, i.y1);
  66969. lastX = i.x1;
  66970. lastY = i.y1;
  66971. out << "m ";
  66972. break;
  66973. case Path::Iterator::lineTo:
  66974. writeXY (i.x1, i.y1);
  66975. lastX = i.x1;
  66976. lastY = i.y1;
  66977. out << "l ";
  66978. break;
  66979. case Path::Iterator::quadraticTo:
  66980. {
  66981. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  66982. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  66983. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  66984. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  66985. writeXY (cp1x, cp1y);
  66986. writeXY (cp2x, cp2y);
  66987. writeXY (i.x2, i.y2);
  66988. out << "ct ";
  66989. lastX = i.x2;
  66990. lastY = i.y2;
  66991. }
  66992. break;
  66993. case Path::Iterator::cubicTo:
  66994. writeXY (i.x1, i.y1);
  66995. writeXY (i.x2, i.y2);
  66996. writeXY (i.x3, i.y3);
  66997. out << "ct ";
  66998. lastX = i.x3;
  66999. lastY = i.y3;
  67000. break;
  67001. case Path::Iterator::closePath:
  67002. out << "cp ";
  67003. break;
  67004. default:
  67005. jassertfalse;
  67006. break;
  67007. }
  67008. }
  67009. out << '\n';
  67010. }
  67011. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  67012. {
  67013. out << "[ "
  67014. << trans.mat00 << ' '
  67015. << trans.mat10 << ' '
  67016. << trans.mat01 << ' '
  67017. << trans.mat11 << ' '
  67018. << trans.mat02 << ' '
  67019. << trans.mat12 << " ] concat ";
  67020. }
  67021. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  67022. {
  67023. stateStack.getLast()->fillType = fillType;
  67024. }
  67025. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  67026. {
  67027. }
  67028. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  67029. {
  67030. }
  67031. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  67032. {
  67033. if (stateStack.getLast()->fillType.isColour())
  67034. {
  67035. writeClip();
  67036. writeColour (stateStack.getLast()->fillType.colour);
  67037. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67038. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  67039. }
  67040. else
  67041. {
  67042. Path p;
  67043. p.addRectangle (r);
  67044. fillPath (p, AffineTransform::identity);
  67045. }
  67046. }
  67047. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  67048. {
  67049. if (stateStack.getLast()->fillType.isColour())
  67050. {
  67051. writeClip();
  67052. Path p (path);
  67053. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  67054. (float) stateStack.getLast()->yOffset));
  67055. writePath (p);
  67056. writeColour (stateStack.getLast()->fillType.colour);
  67057. out << "fill\n";
  67058. }
  67059. else if (stateStack.getLast()->fillType.isGradient())
  67060. {
  67061. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  67062. // postscript can't do semi-transparent ones.
  67063. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  67064. writeClip();
  67065. out << "gsave ";
  67066. {
  67067. Path p (path);
  67068. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67069. writePath (p);
  67070. out << "clip\n";
  67071. }
  67072. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  67073. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  67074. // time-being, this just fills it with the average colour..
  67075. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  67076. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  67077. out << "grestore\n";
  67078. }
  67079. }
  67080. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  67081. const int sx, const int sy,
  67082. const int maxW, const int maxH) const
  67083. {
  67084. out << "{<\n";
  67085. const int w = jmin (maxW, im.getWidth());
  67086. const int h = jmin (maxH, im.getHeight());
  67087. int charsOnLine = 0;
  67088. const Image::BitmapData srcData (im, 0, 0, w, h);
  67089. Colour pixel;
  67090. for (int y = h; --y >= 0;)
  67091. {
  67092. for (int x = 0; x < w; ++x)
  67093. {
  67094. const uint8* pixelData = srcData.getPixelPointer (x, y);
  67095. if (x >= sx && y >= sy)
  67096. {
  67097. if (im.isARGB())
  67098. {
  67099. PixelARGB p (*(const PixelARGB*) pixelData);
  67100. p.unpremultiply();
  67101. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  67102. }
  67103. else if (im.isRGB())
  67104. {
  67105. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  67106. }
  67107. else
  67108. {
  67109. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  67110. }
  67111. }
  67112. else
  67113. {
  67114. pixel = Colours::transparentWhite;
  67115. }
  67116. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  67117. out << String::toHexString (pixelValues, 3, 0);
  67118. charsOnLine += 3;
  67119. if (charsOnLine > 100)
  67120. {
  67121. out << '\n';
  67122. charsOnLine = 0;
  67123. }
  67124. }
  67125. }
  67126. out << "\n>}\n";
  67127. }
  67128. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  67129. {
  67130. const int w = sourceImage.getWidth();
  67131. const int h = sourceImage.getHeight();
  67132. writeClip();
  67133. out << "gsave ";
  67134. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  67135. .scaled (1.0f, -1.0f));
  67136. RectangleList imageClip;
  67137. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  67138. out << "newpath ";
  67139. int itemsOnLine = 0;
  67140. for (RectangleList::Iterator i (imageClip); i.next();)
  67141. {
  67142. if (++itemsOnLine == 6)
  67143. {
  67144. out << '\n';
  67145. itemsOnLine = 0;
  67146. }
  67147. const Rectangle<int>& r = *i.getRectangle();
  67148. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67149. }
  67150. out << " clip newpath\n";
  67151. out << w << ' ' << h << " scale\n";
  67152. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67153. writeImage (sourceImage, 0, 0, w, h);
  67154. out << "false 3 colorimage grestore\n";
  67155. needToClip = true;
  67156. }
  67157. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67158. {
  67159. Path p;
  67160. p.addLineSegment (line, 1.0f);
  67161. fillPath (p, AffineTransform::identity);
  67162. }
  67163. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67164. {
  67165. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67166. }
  67167. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67168. {
  67169. drawLine (Line<float> (left, (float) y, right, (float) y));
  67170. }
  67171. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67172. {
  67173. stateStack.getLast()->font = newFont;
  67174. }
  67175. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67176. {
  67177. return stateStack.getLast()->font;
  67178. }
  67179. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67180. {
  67181. Path p;
  67182. Font& font = stateStack.getLast()->font;
  67183. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67184. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67185. }
  67186. END_JUCE_NAMESPACE
  67187. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67188. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67189. BEGIN_JUCE_NAMESPACE
  67190. #if JUCE_MSVC
  67191. #pragma warning (push)
  67192. #pragma warning (disable: 4127) // "expression is constant" warning
  67193. #if JUCE_DEBUG
  67194. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67195. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67196. #endif
  67197. #endif
  67198. namespace SoftwareRendererClasses
  67199. {
  67200. template <class PixelType, bool replaceExisting = false>
  67201. class SolidColourEdgeTableRenderer
  67202. {
  67203. public:
  67204. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67205. : data (data_),
  67206. sourceColour (colour)
  67207. {
  67208. if (sizeof (PixelType) == 3)
  67209. {
  67210. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67211. && sourceColour.getGreen() == sourceColour.getBlue();
  67212. filler[0].set (sourceColour);
  67213. filler[1].set (sourceColour);
  67214. filler[2].set (sourceColour);
  67215. filler[3].set (sourceColour);
  67216. }
  67217. }
  67218. forcedinline void setEdgeTableYPos (const int y) throw()
  67219. {
  67220. linePixels = (PixelType*) data.getLinePointer (y);
  67221. }
  67222. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67223. {
  67224. if (replaceExisting)
  67225. linePixels[x].set (sourceColour);
  67226. else
  67227. linePixels[x].blend (sourceColour, alphaLevel);
  67228. }
  67229. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67230. {
  67231. if (replaceExisting)
  67232. linePixels[x].set (sourceColour);
  67233. else
  67234. linePixels[x].blend (sourceColour);
  67235. }
  67236. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67237. {
  67238. PixelARGB p (sourceColour);
  67239. p.multiplyAlpha (alphaLevel);
  67240. PixelType* dest = linePixels + x;
  67241. if (replaceExisting || p.getAlpha() >= 0xff)
  67242. replaceLine (dest, p, width);
  67243. else
  67244. blendLine (dest, p, width);
  67245. }
  67246. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67247. {
  67248. PixelType* dest = linePixels + x;
  67249. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67250. replaceLine (dest, sourceColour, width);
  67251. else
  67252. blendLine (dest, sourceColour, width);
  67253. }
  67254. private:
  67255. const Image::BitmapData& data;
  67256. PixelType* linePixels;
  67257. PixelARGB sourceColour;
  67258. PixelRGB filler [4];
  67259. bool areRGBComponentsEqual;
  67260. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67261. {
  67262. do
  67263. {
  67264. dest->blend (colour);
  67265. ++dest;
  67266. } while (--width > 0);
  67267. }
  67268. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67269. {
  67270. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67271. {
  67272. memset (dest, colour.getRed(), width * 3);
  67273. }
  67274. else
  67275. {
  67276. if (width >> 5)
  67277. {
  67278. const int* const intFiller = reinterpret_cast<const int*> (filler);
  67279. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67280. {
  67281. dest->set (colour);
  67282. ++dest;
  67283. --width;
  67284. }
  67285. while (width > 4)
  67286. {
  67287. int* d = reinterpret_cast<int*> (dest);
  67288. *d++ = intFiller[0];
  67289. *d++ = intFiller[1];
  67290. *d++ = intFiller[2];
  67291. dest = reinterpret_cast<PixelRGB*> (d);
  67292. width -= 4;
  67293. }
  67294. }
  67295. while (--width >= 0)
  67296. {
  67297. dest->set (colour);
  67298. ++dest;
  67299. }
  67300. }
  67301. }
  67302. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67303. {
  67304. memset (dest, colour.getAlpha(), width);
  67305. }
  67306. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67307. {
  67308. do
  67309. {
  67310. dest->set (colour);
  67311. ++dest;
  67312. } while (--width > 0);
  67313. }
  67314. JUCE_DECLARE_NON_COPYABLE (SolidColourEdgeTableRenderer);
  67315. };
  67316. class LinearGradientPixelGenerator
  67317. {
  67318. public:
  67319. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67320. : lookupTable (lookupTable_), numEntries (numEntries_)
  67321. {
  67322. jassert (numEntries_ >= 0);
  67323. Point<float> p1 (gradient.point1);
  67324. Point<float> p2 (gradient.point2);
  67325. if (! transform.isIdentity())
  67326. {
  67327. const Line<float> l (p2, p1);
  67328. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67329. p1.applyTransform (transform);
  67330. p2.applyTransform (transform);
  67331. p3.applyTransform (transform);
  67332. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67333. }
  67334. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67335. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67336. if (vertical)
  67337. {
  67338. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67339. start = roundToInt (p1.getY() * scale);
  67340. }
  67341. else if (horizontal)
  67342. {
  67343. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67344. start = roundToInt (p1.getX() * scale);
  67345. }
  67346. else
  67347. {
  67348. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67349. yTerm = p1.getY() - p1.getX() / grad;
  67350. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67351. grad *= scale;
  67352. }
  67353. }
  67354. forcedinline void setY (const int y) throw()
  67355. {
  67356. if (vertical)
  67357. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67358. else if (! horizontal)
  67359. start = roundToInt ((y - yTerm) * grad);
  67360. }
  67361. inline const PixelARGB getPixel (const int x) const throw()
  67362. {
  67363. return vertical ? linePix
  67364. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67365. }
  67366. private:
  67367. const PixelARGB* const lookupTable;
  67368. const int numEntries;
  67369. PixelARGB linePix;
  67370. int start, scale;
  67371. double grad, yTerm;
  67372. bool vertical, horizontal;
  67373. enum { numScaleBits = 12 };
  67374. JUCE_DECLARE_NON_COPYABLE (LinearGradientPixelGenerator);
  67375. };
  67376. class RadialGradientPixelGenerator
  67377. {
  67378. public:
  67379. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67380. const PixelARGB* const lookupTable_, const int numEntries_)
  67381. : lookupTable (lookupTable_),
  67382. numEntries (numEntries_),
  67383. gx1 (gradient.point1.getX()),
  67384. gy1 (gradient.point1.getY())
  67385. {
  67386. jassert (numEntries_ >= 0);
  67387. const Point<float> diff (gradient.point1 - gradient.point2);
  67388. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67389. invScale = numEntries / std::sqrt (maxDist);
  67390. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67391. }
  67392. forcedinline void setY (const int y) throw()
  67393. {
  67394. dy = y - gy1;
  67395. dy *= dy;
  67396. }
  67397. inline const PixelARGB getPixel (const int px) const throw()
  67398. {
  67399. double x = px - gx1;
  67400. x *= x;
  67401. x += dy;
  67402. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67403. }
  67404. protected:
  67405. const PixelARGB* const lookupTable;
  67406. const int numEntries;
  67407. const double gx1, gy1;
  67408. double maxDist, invScale, dy;
  67409. JUCE_DECLARE_NON_COPYABLE (RadialGradientPixelGenerator);
  67410. };
  67411. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67412. {
  67413. public:
  67414. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67415. const PixelARGB* const lookupTable_, const int numEntries_)
  67416. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67417. inverseTransform (transform.inverted())
  67418. {
  67419. tM10 = inverseTransform.mat10;
  67420. tM00 = inverseTransform.mat00;
  67421. }
  67422. forcedinline void setY (const int y) throw()
  67423. {
  67424. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67425. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67426. }
  67427. inline const PixelARGB getPixel (const int px) const throw()
  67428. {
  67429. double x = px;
  67430. const double y = tM10 * x + lineYM11;
  67431. x = tM00 * x + lineYM01;
  67432. x *= x;
  67433. x += y * y;
  67434. if (x >= maxDist)
  67435. return lookupTable [numEntries];
  67436. else
  67437. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67438. }
  67439. private:
  67440. double tM10, tM00, lineYM01, lineYM11;
  67441. const AffineTransform inverseTransform;
  67442. JUCE_DECLARE_NON_COPYABLE (TransformedRadialGradientPixelGenerator);
  67443. };
  67444. template <class PixelType, class GradientType>
  67445. class GradientEdgeTableRenderer : public GradientType
  67446. {
  67447. public:
  67448. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67449. const PixelARGB* const lookupTable_, const int numEntries_)
  67450. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67451. destData (destData_)
  67452. {
  67453. }
  67454. forcedinline void setEdgeTableYPos (const int y) throw()
  67455. {
  67456. linePixels = (PixelType*) destData.getLinePointer (y);
  67457. GradientType::setY (y);
  67458. }
  67459. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67460. {
  67461. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67462. }
  67463. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67464. {
  67465. linePixels[x].blend (GradientType::getPixel (x));
  67466. }
  67467. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67468. {
  67469. PixelType* dest = linePixels + x;
  67470. if (alphaLevel < 0xff)
  67471. {
  67472. do
  67473. {
  67474. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67475. } while (--width > 0);
  67476. }
  67477. else
  67478. {
  67479. do
  67480. {
  67481. (dest++)->blend (GradientType::getPixel (x++));
  67482. } while (--width > 0);
  67483. }
  67484. }
  67485. void handleEdgeTableLineFull (int x, int width) const throw()
  67486. {
  67487. PixelType* dest = linePixels + x;
  67488. do
  67489. {
  67490. (dest++)->blend (GradientType::getPixel (x++));
  67491. } while (--width > 0);
  67492. }
  67493. private:
  67494. const Image::BitmapData& destData;
  67495. PixelType* linePixels;
  67496. JUCE_DECLARE_NON_COPYABLE (GradientEdgeTableRenderer);
  67497. };
  67498. namespace RenderingHelpers
  67499. {
  67500. forcedinline int safeModulo (int n, const int divisor) throw()
  67501. {
  67502. jassert (divisor > 0);
  67503. n %= divisor;
  67504. return (n < 0) ? (n + divisor) : n;
  67505. }
  67506. }
  67507. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67508. class ImageFillEdgeTableRenderer
  67509. {
  67510. public:
  67511. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67512. const Image::BitmapData& srcData_,
  67513. const int extraAlpha_,
  67514. const int x, const int y)
  67515. : destData (destData_),
  67516. srcData (srcData_),
  67517. extraAlpha (extraAlpha_ + 1),
  67518. xOffset (repeatPattern ? RenderingHelpers::safeModulo (x, srcData_.width) - srcData_.width : x),
  67519. yOffset (repeatPattern ? RenderingHelpers::safeModulo (y, srcData_.height) - srcData_.height : y)
  67520. {
  67521. }
  67522. forcedinline void setEdgeTableYPos (int y) throw()
  67523. {
  67524. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67525. y -= yOffset;
  67526. if (repeatPattern)
  67527. {
  67528. jassert (y >= 0);
  67529. y %= srcData.height;
  67530. }
  67531. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67532. }
  67533. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67534. {
  67535. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67536. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67537. }
  67538. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67539. {
  67540. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67541. }
  67542. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67543. {
  67544. DestPixelType* dest = linePixels + x;
  67545. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67546. x -= xOffset;
  67547. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67548. if (alphaLevel < 0xfe)
  67549. {
  67550. do
  67551. {
  67552. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67553. } while (--width > 0);
  67554. }
  67555. else
  67556. {
  67557. if (repeatPattern)
  67558. {
  67559. do
  67560. {
  67561. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67562. } while (--width > 0);
  67563. }
  67564. else
  67565. {
  67566. copyRow (dest, sourceLineStart + x, width);
  67567. }
  67568. }
  67569. }
  67570. void handleEdgeTableLineFull (int x, int width) const throw()
  67571. {
  67572. DestPixelType* dest = linePixels + x;
  67573. x -= xOffset;
  67574. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67575. if (extraAlpha < 0xfe)
  67576. {
  67577. do
  67578. {
  67579. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67580. } while (--width > 0);
  67581. }
  67582. else
  67583. {
  67584. if (repeatPattern)
  67585. {
  67586. do
  67587. {
  67588. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67589. } while (--width > 0);
  67590. }
  67591. else
  67592. {
  67593. copyRow (dest, sourceLineStart + x, width);
  67594. }
  67595. }
  67596. }
  67597. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67598. {
  67599. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67600. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67601. uint8* mask = (uint8*) (s + x - xOffset);
  67602. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67603. mask += PixelARGB::indexA;
  67604. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67605. }
  67606. private:
  67607. const Image::BitmapData& destData;
  67608. const Image::BitmapData& srcData;
  67609. const int extraAlpha, xOffset, yOffset;
  67610. DestPixelType* linePixels;
  67611. SrcPixelType* sourceLineStart;
  67612. template <class PixelType1, class PixelType2>
  67613. static forcedinline void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67614. {
  67615. do
  67616. {
  67617. dest++ ->blend (*src++);
  67618. } while (--width > 0);
  67619. }
  67620. static forcedinline void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67621. {
  67622. memcpy (dest, src, width * sizeof (PixelRGB));
  67623. }
  67624. JUCE_DECLARE_NON_COPYABLE (ImageFillEdgeTableRenderer);
  67625. };
  67626. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67627. class TransformedImageFillEdgeTableRenderer
  67628. {
  67629. public:
  67630. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67631. const Image::BitmapData& srcData_,
  67632. const AffineTransform& transform,
  67633. const int extraAlpha_,
  67634. const bool betterQuality_)
  67635. : interpolator (transform,
  67636. betterQuality_ ? 0.5f : 0.0f,
  67637. betterQuality_ ? -128 : 0),
  67638. destData (destData_),
  67639. srcData (srcData_),
  67640. extraAlpha (extraAlpha_ + 1),
  67641. betterQuality (betterQuality_),
  67642. maxX (srcData_.width - 1),
  67643. maxY (srcData_.height - 1),
  67644. scratchSize (2048)
  67645. {
  67646. scratchBuffer.malloc (scratchSize);
  67647. }
  67648. forcedinline void setEdgeTableYPos (const int newY) throw()
  67649. {
  67650. y = newY;
  67651. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67652. }
  67653. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) throw()
  67654. {
  67655. SrcPixelType p;
  67656. generate (&p, x, 1);
  67657. linePixels[x].blend (p, (alphaLevel * extraAlpha) >> 8);
  67658. }
  67659. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  67660. {
  67661. SrcPixelType p;
  67662. generate (&p, x, 1);
  67663. linePixels[x].blend (p, extraAlpha);
  67664. }
  67665. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  67666. {
  67667. if (width > scratchSize)
  67668. {
  67669. scratchSize = width;
  67670. scratchBuffer.malloc (scratchSize);
  67671. }
  67672. SrcPixelType* span = scratchBuffer;
  67673. generate (span, x, width);
  67674. DestPixelType* dest = linePixels + x;
  67675. alphaLevel *= extraAlpha;
  67676. alphaLevel >>= 8;
  67677. if (alphaLevel < 0xfe)
  67678. {
  67679. do
  67680. {
  67681. dest++ ->blend (*span++, alphaLevel);
  67682. } while (--width > 0);
  67683. }
  67684. else
  67685. {
  67686. do
  67687. {
  67688. dest++ ->blend (*span++);
  67689. } while (--width > 0);
  67690. }
  67691. }
  67692. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  67693. {
  67694. handleEdgeTableLine (x, width, 255);
  67695. }
  67696. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  67697. {
  67698. if (width > scratchSize)
  67699. {
  67700. scratchSize = width;
  67701. scratchBuffer.malloc (scratchSize);
  67702. }
  67703. y = y_;
  67704. generate (scratchBuffer.getData(), x, width);
  67705. et.clipLineToMask (x, y_,
  67706. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67707. sizeof (SrcPixelType), width);
  67708. }
  67709. private:
  67710. template <class PixelType>
  67711. void generate (PixelType* dest, const int x, int numPixels) throw()
  67712. {
  67713. this->interpolator.setStartOfLine ((float) x, (float) y, numPixels);
  67714. do
  67715. {
  67716. int hiResX, hiResY;
  67717. this->interpolator.next (hiResX, hiResY);
  67718. int loResX = hiResX >> 8;
  67719. int loResY = hiResY >> 8;
  67720. if (repeatPattern)
  67721. {
  67722. loResX = RenderingHelpers::safeModulo (loResX, srcData.width);
  67723. loResY = RenderingHelpers::safeModulo (loResY, srcData.height);
  67724. }
  67725. if (betterQuality)
  67726. {
  67727. if (isPositiveAndBelow (loResX, maxX))
  67728. {
  67729. if (isPositiveAndBelow (loResY, maxY))
  67730. {
  67731. // In the centre of the image..
  67732. render4PixelAverage (dest, this->srcData.getPixelPointer (loResX, loResY),
  67733. hiResX & 255, hiResY & 255);
  67734. ++dest;
  67735. continue;
  67736. }
  67737. else
  67738. {
  67739. // At a top or bottom edge..
  67740. if (! repeatPattern)
  67741. {
  67742. if (loResY < 0)
  67743. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, 0), hiResX & 255, hiResY & 255);
  67744. else
  67745. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, maxY), hiResX & 255, 255 - (hiResY & 255));
  67746. ++dest;
  67747. continue;
  67748. }
  67749. }
  67750. }
  67751. else
  67752. {
  67753. if (isPositiveAndBelow (loResY, maxY))
  67754. {
  67755. // At a left or right hand edge..
  67756. if (! repeatPattern)
  67757. {
  67758. if (loResX < 0)
  67759. render2PixelAverageY (dest, this->srcData.getPixelPointer (0, loResY), hiResY & 255, hiResX & 255);
  67760. else
  67761. render2PixelAverageY (dest, this->srcData.getPixelPointer (maxX, loResY), hiResY & 255, 255 - (hiResX & 255));
  67762. ++dest;
  67763. continue;
  67764. }
  67765. }
  67766. }
  67767. }
  67768. if (! repeatPattern)
  67769. {
  67770. if (loResX < 0) loResX = 0;
  67771. if (loResY < 0) loResY = 0;
  67772. if (loResX > maxX) loResX = maxX;
  67773. if (loResY > maxY) loResY = maxY;
  67774. }
  67775. dest->set (*(const PixelType*) this->srcData.getPixelPointer (loResX, loResY));
  67776. ++dest;
  67777. } while (--numPixels > 0);
  67778. }
  67779. void render4PixelAverage (PixelARGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67780. {
  67781. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67782. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  67783. c[0] += weight * src[0];
  67784. c[1] += weight * src[1];
  67785. c[2] += weight * src[2];
  67786. c[3] += weight * src[3];
  67787. weight = subPixelX * (256 - subPixelY);
  67788. c[0] += weight * src[4];
  67789. c[1] += weight * src[5];
  67790. c[2] += weight * src[6];
  67791. c[3] += weight * src[7];
  67792. src += this->srcData.lineStride;
  67793. weight = (256 - subPixelX) * subPixelY;
  67794. c[0] += weight * src[0];
  67795. c[1] += weight * src[1];
  67796. c[2] += weight * src[2];
  67797. c[3] += weight * src[3];
  67798. weight = subPixelX * subPixelY;
  67799. c[0] += weight * src[4];
  67800. c[1] += weight * src[5];
  67801. c[2] += weight * src[6];
  67802. c[3] += weight * src[7];
  67803. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67804. (uint8) (c[PixelARGB::indexR] >> 16),
  67805. (uint8) (c[PixelARGB::indexG] >> 16),
  67806. (uint8) (c[PixelARGB::indexB] >> 16));
  67807. }
  67808. void render2PixelAverageX (PixelARGB* const dest, const uint8* src, const int subPixelX, const int alpha) throw()
  67809. {
  67810. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67811. uint32 weight = (256 - subPixelX) * alpha;
  67812. c[0] += weight * src[0];
  67813. c[1] += weight * src[1];
  67814. c[2] += weight * src[2];
  67815. c[3] += weight * src[3];
  67816. weight = subPixelX * alpha;
  67817. c[0] += weight * src[4];
  67818. c[1] += weight * src[5];
  67819. c[2] += weight * src[6];
  67820. c[3] += weight * src[7];
  67821. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67822. (uint8) (c[PixelARGB::indexR] >> 16),
  67823. (uint8) (c[PixelARGB::indexG] >> 16),
  67824. (uint8) (c[PixelARGB::indexB] >> 16));
  67825. }
  67826. void render2PixelAverageY (PixelARGB* const dest, const uint8* src, const int subPixelY, const int alpha) throw()
  67827. {
  67828. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67829. uint32 weight = (256 - subPixelY) * alpha;
  67830. c[0] += weight * src[0];
  67831. c[1] += weight * src[1];
  67832. c[2] += weight * src[2];
  67833. c[3] += weight * src[3];
  67834. src += this->srcData.lineStride;
  67835. weight = subPixelY * alpha;
  67836. c[0] += weight * src[0];
  67837. c[1] += weight * src[1];
  67838. c[2] += weight * src[2];
  67839. c[3] += weight * src[3];
  67840. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67841. (uint8) (c[PixelARGB::indexR] >> 16),
  67842. (uint8) (c[PixelARGB::indexG] >> 16),
  67843. (uint8) (c[PixelARGB::indexB] >> 16));
  67844. }
  67845. void render4PixelAverage (PixelRGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67846. {
  67847. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  67848. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  67849. c[0] += weight * src[0];
  67850. c[1] += weight * src[1];
  67851. c[2] += weight * src[2];
  67852. weight = subPixelX * (256 - subPixelY);
  67853. c[0] += weight * src[3];
  67854. c[1] += weight * src[4];
  67855. c[2] += weight * src[5];
  67856. src += this->srcData.lineStride;
  67857. weight = (256 - subPixelX) * subPixelY;
  67858. c[0] += weight * src[0];
  67859. c[1] += weight * src[1];
  67860. c[2] += weight * src[2];
  67861. weight = subPixelX * subPixelY;
  67862. c[0] += weight * src[3];
  67863. c[1] += weight * src[4];
  67864. c[2] += weight * src[5];
  67865. dest->setARGB ((uint8) 255,
  67866. (uint8) (c[PixelRGB::indexR] >> 16),
  67867. (uint8) (c[PixelRGB::indexG] >> 16),
  67868. (uint8) (c[PixelRGB::indexB] >> 16));
  67869. }
  67870. void render2PixelAverageX (PixelRGB* const dest, const uint8* src, const int subPixelX, const int /*alpha*/) throw()
  67871. {
  67872. uint32 c[3] = { 128, 128, 128 };
  67873. uint32 weight = (256 - subPixelX);
  67874. c[0] += weight * src[0];
  67875. c[1] += weight * src[1];
  67876. c[2] += weight * src[2];
  67877. c[0] += subPixelX * src[3];
  67878. c[1] += subPixelX * src[4];
  67879. c[2] += subPixelX * src[5];
  67880. dest->setARGB ((uint8) 255,
  67881. (uint8) (c[PixelRGB::indexR] >> 8),
  67882. (uint8) (c[PixelRGB::indexG] >> 8),
  67883. (uint8) (c[PixelRGB::indexB] >> 8));
  67884. }
  67885. void render2PixelAverageY (PixelRGB* const dest, const uint8* src, const int subPixelY, const int /*alpha*/) throw()
  67886. {
  67887. uint32 c[3] = { 128, 128, 128 };
  67888. uint32 weight = (256 - subPixelY);
  67889. c[0] += weight * src[0];
  67890. c[1] += weight * src[1];
  67891. c[2] += weight * src[2];
  67892. src += this->srcData.lineStride;
  67893. c[0] += subPixelY * src[0];
  67894. c[1] += subPixelY * src[1];
  67895. c[2] += subPixelY * src[2];
  67896. dest->setARGB ((uint8) 255,
  67897. (uint8) (c[PixelRGB::indexR] >> 8),
  67898. (uint8) (c[PixelRGB::indexG] >> 8),
  67899. (uint8) (c[PixelRGB::indexB] >> 8));
  67900. }
  67901. void render4PixelAverage (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67902. {
  67903. uint32 c = 256 * 128;
  67904. c += src[0] * ((256 - subPixelX) * (256 - subPixelY));
  67905. c += src[1] * (subPixelX * (256 - subPixelY));
  67906. src += this->srcData.lineStride;
  67907. c += src[0] * ((256 - subPixelX) * subPixelY);
  67908. c += src[1] * (subPixelX * subPixelY);
  67909. *((uint8*) dest) = (uint8) (c >> 16);
  67910. }
  67911. void render2PixelAverageX (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int alpha) throw()
  67912. {
  67913. uint32 c = 256 * 128;
  67914. c += src[0] * (256 - subPixelX) * alpha;
  67915. c += src[1] * subPixelX * alpha;
  67916. *((uint8*) dest) = (uint8) (c >> 16);
  67917. }
  67918. void render2PixelAverageY (PixelAlpha* const dest, const uint8* src, const int subPixelY, const int alpha) throw()
  67919. {
  67920. uint32 c = 256 * 128;
  67921. c += src[0] * (256 - subPixelY) * alpha;
  67922. src += this->srcData.lineStride;
  67923. c += src[0] * subPixelY * alpha;
  67924. *((uint8*) dest) = (uint8) (c >> 16);
  67925. }
  67926. class TransformedImageSpanInterpolator
  67927. {
  67928. public:
  67929. TransformedImageSpanInterpolator (const AffineTransform& transform, const float pixelOffset_, const int pixelOffsetInt_) throw()
  67930. : inverseTransform (transform.inverted()),
  67931. pixelOffset (pixelOffset_), pixelOffsetInt (pixelOffsetInt_)
  67932. {}
  67933. void setStartOfLine (float x, float y, const int numPixels) throw()
  67934. {
  67935. jassert (numPixels > 0);
  67936. x += pixelOffset;
  67937. y += pixelOffset;
  67938. float x1 = x, y1 = y;
  67939. x += numPixels;
  67940. inverseTransform.transformPoints (x1, y1, x, y);
  67941. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels, pixelOffsetInt);
  67942. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels, pixelOffsetInt);
  67943. }
  67944. void next (int& x, int& y) throw()
  67945. {
  67946. x = xBresenham.n;
  67947. xBresenham.stepToNext();
  67948. y = yBresenham.n;
  67949. yBresenham.stepToNext();
  67950. }
  67951. private:
  67952. class BresenhamInterpolator
  67953. {
  67954. public:
  67955. BresenhamInterpolator() throw() {}
  67956. void set (const int n1, const int n2, const int numSteps_, const int pixelOffsetInt) throw()
  67957. {
  67958. numSteps = numSteps_;
  67959. step = (n2 - n1) / numSteps;
  67960. remainder = modulo = (n2 - n1) % numSteps;
  67961. n = n1 + pixelOffsetInt;
  67962. if (modulo <= 0)
  67963. {
  67964. modulo += numSteps;
  67965. remainder += numSteps;
  67966. --step;
  67967. }
  67968. modulo -= numSteps;
  67969. }
  67970. forcedinline void stepToNext() throw()
  67971. {
  67972. modulo += remainder;
  67973. n += step;
  67974. if (modulo > 0)
  67975. {
  67976. modulo -= numSteps;
  67977. ++n;
  67978. }
  67979. }
  67980. int n;
  67981. private:
  67982. int numSteps, step, modulo, remainder;
  67983. };
  67984. const AffineTransform inverseTransform;
  67985. BresenhamInterpolator xBresenham, yBresenham;
  67986. const float pixelOffset;
  67987. const int pixelOffsetInt;
  67988. JUCE_DECLARE_NON_COPYABLE (TransformedImageSpanInterpolator);
  67989. };
  67990. TransformedImageSpanInterpolator interpolator;
  67991. const Image::BitmapData& destData;
  67992. const Image::BitmapData& srcData;
  67993. const int extraAlpha;
  67994. const bool betterQuality;
  67995. const int maxX, maxY;
  67996. int y;
  67997. DestPixelType* linePixels;
  67998. HeapBlock <SrcPixelType> scratchBuffer;
  67999. int scratchSize;
  68000. JUCE_DECLARE_NON_COPYABLE (TransformedImageFillEdgeTableRenderer);
  68001. };
  68002. class ClipRegionBase : public ReferenceCountedObject
  68003. {
  68004. public:
  68005. ClipRegionBase() {}
  68006. virtual ~ClipRegionBase() {}
  68007. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  68008. virtual const Ptr clone() const = 0;
  68009. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  68010. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  68011. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  68012. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  68013. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  68014. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  68015. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  68016. virtual const Ptr translated (const Point<int>& delta) = 0;
  68017. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  68018. virtual const Rectangle<int> getClipBounds() const = 0;
  68019. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  68020. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  68021. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  68022. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  68023. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  68024. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  68025. protected:
  68026. template <class Iterator>
  68027. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  68028. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  68029. {
  68030. switch (destData.pixelFormat)
  68031. {
  68032. case Image::ARGB:
  68033. switch (srcData.pixelFormat)
  68034. {
  68035. case Image::ARGB:
  68036. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68037. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68038. break;
  68039. case Image::RGB:
  68040. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68041. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68042. break;
  68043. default:
  68044. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68045. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68046. break;
  68047. }
  68048. break;
  68049. case Image::RGB:
  68050. switch (srcData.pixelFormat)
  68051. {
  68052. case Image::ARGB:
  68053. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68054. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68055. break;
  68056. case Image::RGB:
  68057. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68058. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68059. break;
  68060. default:
  68061. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68062. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68063. break;
  68064. }
  68065. break;
  68066. default:
  68067. switch (srcData.pixelFormat)
  68068. {
  68069. case Image::ARGB:
  68070. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68071. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68072. break;
  68073. case Image::RGB:
  68074. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68075. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68076. break;
  68077. default:
  68078. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68079. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68080. break;
  68081. }
  68082. break;
  68083. }
  68084. }
  68085. template <class Iterator>
  68086. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  68087. {
  68088. switch (destData.pixelFormat)
  68089. {
  68090. case Image::ARGB:
  68091. switch (srcData.pixelFormat)
  68092. {
  68093. case Image::ARGB:
  68094. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68095. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68096. break;
  68097. case Image::RGB:
  68098. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68099. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68100. break;
  68101. default:
  68102. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68103. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68104. break;
  68105. }
  68106. break;
  68107. case Image::RGB:
  68108. switch (srcData.pixelFormat)
  68109. {
  68110. case Image::ARGB:
  68111. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68112. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68113. break;
  68114. case Image::RGB:
  68115. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68116. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68117. break;
  68118. default:
  68119. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68120. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68121. break;
  68122. }
  68123. break;
  68124. default:
  68125. switch (srcData.pixelFormat)
  68126. {
  68127. case Image::ARGB:
  68128. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68129. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68130. break;
  68131. case Image::RGB:
  68132. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68133. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68134. break;
  68135. default:
  68136. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68137. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68138. break;
  68139. }
  68140. break;
  68141. }
  68142. }
  68143. template <class Iterator, class DestPixelType>
  68144. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68145. {
  68146. jassert (destData.pixelStride == sizeof (DestPixelType));
  68147. if (replaceContents)
  68148. {
  68149. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68150. iter.iterate (r);
  68151. }
  68152. else
  68153. {
  68154. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68155. iter.iterate (r);
  68156. }
  68157. }
  68158. template <class Iterator, class DestPixelType>
  68159. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68160. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68161. {
  68162. jassert (destData.pixelStride == sizeof (DestPixelType));
  68163. if (g.isRadial)
  68164. {
  68165. if (isIdentity)
  68166. {
  68167. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68168. iter.iterate (renderer);
  68169. }
  68170. else
  68171. {
  68172. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68173. iter.iterate (renderer);
  68174. }
  68175. }
  68176. else
  68177. {
  68178. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68179. iter.iterate (renderer);
  68180. }
  68181. }
  68182. };
  68183. class ClipRegion_EdgeTable : public ClipRegionBase
  68184. {
  68185. public:
  68186. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68187. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68188. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68189. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68190. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68191. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68192. ~ClipRegion_EdgeTable() {}
  68193. const Ptr clone() const
  68194. {
  68195. return new ClipRegion_EdgeTable (*this);
  68196. }
  68197. const Ptr applyClipTo (const Ptr& target) const
  68198. {
  68199. return target->clipToEdgeTable (edgeTable);
  68200. }
  68201. const Ptr clipToRectangle (const Rectangle<int>& r)
  68202. {
  68203. edgeTable.clipToRectangle (r);
  68204. return edgeTable.isEmpty() ? 0 : this;
  68205. }
  68206. const Ptr clipToRectangleList (const RectangleList& r)
  68207. {
  68208. RectangleList inverse (edgeTable.getMaximumBounds());
  68209. if (inverse.subtract (r))
  68210. for (RectangleList::Iterator iter (inverse); iter.next();)
  68211. edgeTable.excludeRectangle (*iter.getRectangle());
  68212. return edgeTable.isEmpty() ? 0 : this;
  68213. }
  68214. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68215. {
  68216. edgeTable.excludeRectangle (r);
  68217. return edgeTable.isEmpty() ? 0 : this;
  68218. }
  68219. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68220. {
  68221. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68222. edgeTable.clipToEdgeTable (et);
  68223. return edgeTable.isEmpty() ? 0 : this;
  68224. }
  68225. const Ptr clipToEdgeTable (const EdgeTable& et)
  68226. {
  68227. edgeTable.clipToEdgeTable (et);
  68228. return edgeTable.isEmpty() ? 0 : this;
  68229. }
  68230. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68231. {
  68232. const Image::BitmapData srcData (image, false);
  68233. if (transform.isOnlyTranslation())
  68234. {
  68235. // If our translation doesn't involve any distortion, just use a simple blit..
  68236. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68237. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68238. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68239. {
  68240. const int imageX = ((tx + 128) >> 8);
  68241. const int imageY = ((ty + 128) >> 8);
  68242. if (image.getFormat() == Image::ARGB)
  68243. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68244. else
  68245. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68246. return edgeTable.isEmpty() ? 0 : this;
  68247. }
  68248. }
  68249. if (transform.isSingularity())
  68250. return 0;
  68251. {
  68252. Path p;
  68253. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68254. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68255. edgeTable.clipToEdgeTable (et2);
  68256. }
  68257. if (! edgeTable.isEmpty())
  68258. {
  68259. if (image.getFormat() == Image::ARGB)
  68260. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68261. else
  68262. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68263. }
  68264. return edgeTable.isEmpty() ? 0 : this;
  68265. }
  68266. const Ptr translated (const Point<int>& delta)
  68267. {
  68268. edgeTable.translate ((float) delta.getX(), delta.getY());
  68269. return edgeTable.isEmpty() ? 0 : this;
  68270. }
  68271. bool clipRegionIntersects (const Rectangle<int>& r) const
  68272. {
  68273. return edgeTable.getMaximumBounds().intersects (r);
  68274. }
  68275. const Rectangle<int> getClipBounds() const
  68276. {
  68277. return edgeTable.getMaximumBounds();
  68278. }
  68279. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68280. {
  68281. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68282. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68283. if (! clipped.isEmpty())
  68284. {
  68285. ClipRegion_EdgeTable et (clipped);
  68286. et.edgeTable.clipToEdgeTable (edgeTable);
  68287. et.fillAllWithColour (destData, colour, replaceContents);
  68288. }
  68289. }
  68290. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68291. {
  68292. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68293. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68294. if (! clipped.isEmpty())
  68295. {
  68296. ClipRegion_EdgeTable et (clipped);
  68297. et.edgeTable.clipToEdgeTable (edgeTable);
  68298. et.fillAllWithColour (destData, colour, false);
  68299. }
  68300. }
  68301. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68302. {
  68303. switch (destData.pixelFormat)
  68304. {
  68305. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68306. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68307. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68308. }
  68309. }
  68310. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68311. {
  68312. HeapBlock <PixelARGB> lookupTable;
  68313. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68314. jassert (numLookupEntries > 0);
  68315. switch (destData.pixelFormat)
  68316. {
  68317. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68318. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68319. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68320. }
  68321. }
  68322. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68323. {
  68324. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68325. }
  68326. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68327. {
  68328. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68329. }
  68330. EdgeTable edgeTable;
  68331. private:
  68332. template <class SrcPixelType>
  68333. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68334. {
  68335. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68336. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68337. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68338. edgeTable.getMaximumBounds().getWidth());
  68339. }
  68340. template <class SrcPixelType>
  68341. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68342. {
  68343. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68344. edgeTable.clipToRectangle (r);
  68345. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68346. for (int y = 0; y < r.getHeight(); ++y)
  68347. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68348. }
  68349. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68350. };
  68351. class ClipRegion_RectangleList : public ClipRegionBase
  68352. {
  68353. public:
  68354. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68355. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68356. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68357. ~ClipRegion_RectangleList() {}
  68358. const Ptr clone() const
  68359. {
  68360. return new ClipRegion_RectangleList (*this);
  68361. }
  68362. const Ptr applyClipTo (const Ptr& target) const
  68363. {
  68364. return target->clipToRectangleList (clip);
  68365. }
  68366. const Ptr clipToRectangle (const Rectangle<int>& r)
  68367. {
  68368. clip.clipTo (r);
  68369. return clip.isEmpty() ? 0 : this;
  68370. }
  68371. const Ptr clipToRectangleList (const RectangleList& r)
  68372. {
  68373. clip.clipTo (r);
  68374. return clip.isEmpty() ? 0 : this;
  68375. }
  68376. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68377. {
  68378. clip.subtract (r);
  68379. return clip.isEmpty() ? 0 : this;
  68380. }
  68381. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68382. {
  68383. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68384. }
  68385. const Ptr clipToEdgeTable (const EdgeTable& et)
  68386. {
  68387. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68388. }
  68389. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68390. {
  68391. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68392. }
  68393. const Ptr translated (const Point<int>& delta)
  68394. {
  68395. clip.offsetAll (delta.getX(), delta.getY());
  68396. return clip.isEmpty() ? 0 : this;
  68397. }
  68398. bool clipRegionIntersects (const Rectangle<int>& r) const
  68399. {
  68400. return clip.intersects (r);
  68401. }
  68402. const Rectangle<int> getClipBounds() const
  68403. {
  68404. return clip.getBounds();
  68405. }
  68406. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68407. {
  68408. SubRectangleIterator iter (clip, area);
  68409. switch (destData.pixelFormat)
  68410. {
  68411. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68412. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68413. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68414. }
  68415. }
  68416. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68417. {
  68418. SubRectangleIteratorFloat iter (clip, area);
  68419. switch (destData.pixelFormat)
  68420. {
  68421. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68422. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68423. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68424. }
  68425. }
  68426. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68427. {
  68428. switch (destData.pixelFormat)
  68429. {
  68430. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68431. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68432. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68433. }
  68434. }
  68435. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68436. {
  68437. HeapBlock <PixelARGB> lookupTable;
  68438. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68439. jassert (numLookupEntries > 0);
  68440. switch (destData.pixelFormat)
  68441. {
  68442. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68443. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68444. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68445. }
  68446. }
  68447. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68448. {
  68449. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68450. }
  68451. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68452. {
  68453. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68454. }
  68455. RectangleList clip;
  68456. template <class Renderer>
  68457. void iterate (Renderer& r) const throw()
  68458. {
  68459. RectangleList::Iterator iter (clip);
  68460. while (iter.next())
  68461. {
  68462. const Rectangle<int> rect (*iter.getRectangle());
  68463. const int x = rect.getX();
  68464. const int w = rect.getWidth();
  68465. jassert (w > 0);
  68466. const int bottom = rect.getBottom();
  68467. for (int y = rect.getY(); y < bottom; ++y)
  68468. {
  68469. r.setEdgeTableYPos (y);
  68470. r.handleEdgeTableLineFull (x, w);
  68471. }
  68472. }
  68473. }
  68474. private:
  68475. class SubRectangleIterator
  68476. {
  68477. public:
  68478. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68479. : clip (clip_), area (area_)
  68480. {
  68481. }
  68482. template <class Renderer>
  68483. void iterate (Renderer& r) const throw()
  68484. {
  68485. RectangleList::Iterator iter (clip);
  68486. while (iter.next())
  68487. {
  68488. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68489. if (! rect.isEmpty())
  68490. {
  68491. const int x = rect.getX();
  68492. const int w = rect.getWidth();
  68493. const int bottom = rect.getBottom();
  68494. for (int y = rect.getY(); y < bottom; ++y)
  68495. {
  68496. r.setEdgeTableYPos (y);
  68497. r.handleEdgeTableLineFull (x, w);
  68498. }
  68499. }
  68500. }
  68501. }
  68502. private:
  68503. const RectangleList& clip;
  68504. const Rectangle<int> area;
  68505. JUCE_DECLARE_NON_COPYABLE (SubRectangleIterator);
  68506. };
  68507. class SubRectangleIteratorFloat
  68508. {
  68509. public:
  68510. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68511. : clip (clip_), area (area_)
  68512. {
  68513. }
  68514. template <class Renderer>
  68515. void iterate (Renderer& r) const throw()
  68516. {
  68517. int left = roundToInt (area.getX() * 256.0f);
  68518. int top = roundToInt (area.getY() * 256.0f);
  68519. int right = roundToInt (area.getRight() * 256.0f);
  68520. int bottom = roundToInt (area.getBottom() * 256.0f);
  68521. int totalTop, totalLeft, totalBottom, totalRight;
  68522. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68523. if ((top >> 8) == (bottom >> 8))
  68524. {
  68525. topAlpha = bottom - top;
  68526. bottomAlpha = 0;
  68527. totalTop = top >> 8;
  68528. totalBottom = bottom = top = totalTop + 1;
  68529. }
  68530. else
  68531. {
  68532. if ((top & 255) == 0)
  68533. {
  68534. topAlpha = 0;
  68535. top = totalTop = (top >> 8);
  68536. }
  68537. else
  68538. {
  68539. topAlpha = 255 - (top & 255);
  68540. totalTop = (top >> 8);
  68541. top = totalTop + 1;
  68542. }
  68543. bottomAlpha = bottom & 255;
  68544. bottom >>= 8;
  68545. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68546. }
  68547. if ((left >> 8) == (right >> 8))
  68548. {
  68549. leftAlpha = right - left;
  68550. rightAlpha = 0;
  68551. totalLeft = (left >> 8);
  68552. totalRight = right = left = totalLeft + 1;
  68553. }
  68554. else
  68555. {
  68556. if ((left & 255) == 0)
  68557. {
  68558. leftAlpha = 0;
  68559. left = totalLeft = (left >> 8);
  68560. }
  68561. else
  68562. {
  68563. leftAlpha = 255 - (left & 255);
  68564. totalLeft = (left >> 8);
  68565. left = totalLeft + 1;
  68566. }
  68567. rightAlpha = right & 255;
  68568. right >>= 8;
  68569. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68570. }
  68571. RectangleList::Iterator iter (clip);
  68572. while (iter.next())
  68573. {
  68574. const int clipLeft = iter.getRectangle()->getX();
  68575. const int clipRight = iter.getRectangle()->getRight();
  68576. const int clipTop = iter.getRectangle()->getY();
  68577. const int clipBottom = iter.getRectangle()->getBottom();
  68578. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68579. {
  68580. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68581. {
  68582. if (topAlpha != 0 && totalTop >= clipTop)
  68583. {
  68584. r.setEdgeTableYPos (totalTop);
  68585. r.handleEdgeTablePixel (left, topAlpha);
  68586. }
  68587. const int endY = jmin (bottom, clipBottom);
  68588. for (int y = jmax (clipTop, top); y < endY; ++y)
  68589. {
  68590. r.setEdgeTableYPos (y);
  68591. r.handleEdgeTablePixelFull (left);
  68592. }
  68593. if (bottomAlpha != 0 && bottom < clipBottom)
  68594. {
  68595. r.setEdgeTableYPos (bottom);
  68596. r.handleEdgeTablePixel (left, bottomAlpha);
  68597. }
  68598. }
  68599. else
  68600. {
  68601. const int clippedLeft = jmax (left, clipLeft);
  68602. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68603. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68604. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68605. if (topAlpha != 0 && totalTop >= clipTop)
  68606. {
  68607. r.setEdgeTableYPos (totalTop);
  68608. if (doLeftAlpha)
  68609. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68610. if (clippedWidth > 0)
  68611. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68612. if (doRightAlpha)
  68613. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68614. }
  68615. const int endY = jmin (bottom, clipBottom);
  68616. for (int y = jmax (clipTop, top); y < endY; ++y)
  68617. {
  68618. r.setEdgeTableYPos (y);
  68619. if (doLeftAlpha)
  68620. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68621. if (clippedWidth > 0)
  68622. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68623. if (doRightAlpha)
  68624. r.handleEdgeTablePixel (right, rightAlpha);
  68625. }
  68626. if (bottomAlpha != 0 && bottom < clipBottom)
  68627. {
  68628. r.setEdgeTableYPos (bottom);
  68629. if (doLeftAlpha)
  68630. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68631. if (clippedWidth > 0)
  68632. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68633. if (doRightAlpha)
  68634. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68635. }
  68636. }
  68637. }
  68638. }
  68639. }
  68640. private:
  68641. const RectangleList& clip;
  68642. const Rectangle<float>& area;
  68643. JUCE_DECLARE_NON_COPYABLE (SubRectangleIteratorFloat);
  68644. };
  68645. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68646. };
  68647. }
  68648. class LowLevelGraphicsSoftwareRenderer::SavedState
  68649. {
  68650. public:
  68651. SavedState (const Image& image_, const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68652. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68653. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  68654. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  68655. {
  68656. }
  68657. SavedState (const Image& image_, const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68658. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68659. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  68660. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  68661. {
  68662. }
  68663. SavedState (const SavedState& other)
  68664. : image (other.image), clip (other.clip), complexTransform (other.complexTransform),
  68665. xOffset (other.xOffset), yOffset (other.yOffset), compositionAlpha (other.compositionAlpha),
  68666. isOnlyTranslated (other.isOnlyTranslated), font (other.font), fillType (other.fillType),
  68667. interpolationQuality (other.interpolationQuality)
  68668. {
  68669. }
  68670. void setOrigin (const int x, const int y) throw()
  68671. {
  68672. if (isOnlyTranslated)
  68673. {
  68674. xOffset += x;
  68675. yOffset += y;
  68676. }
  68677. else
  68678. {
  68679. complexTransform = getTransformWith (AffineTransform::translation ((float) x, (float) y));
  68680. }
  68681. }
  68682. void addTransform (const AffineTransform& t)
  68683. {
  68684. if ((! isOnlyTranslated)
  68685. || (! t.isOnlyTranslation())
  68686. || (int) (t.getTranslationX() * 256.0f) != 0
  68687. || (int) (t.getTranslationY() * 256.0f) != 0)
  68688. {
  68689. complexTransform = getTransformWith (t);
  68690. isOnlyTranslated = false;
  68691. }
  68692. else
  68693. {
  68694. xOffset += (int) t.getTranslationX();
  68695. yOffset += (int) t.getTranslationY();
  68696. }
  68697. }
  68698. float getScaleFactor() const
  68699. {
  68700. return isOnlyTranslated ? 1.0f : complexTransform.getScaleFactor();
  68701. }
  68702. bool clipToRectangle (const Rectangle<int>& r)
  68703. {
  68704. if (clip != 0)
  68705. {
  68706. if (isOnlyTranslated)
  68707. {
  68708. cloneClipIfMultiplyReferenced();
  68709. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68710. }
  68711. else
  68712. {
  68713. Path p;
  68714. p.addRectangle (r);
  68715. clipToPath (p, AffineTransform::identity);
  68716. }
  68717. }
  68718. return clip != 0;
  68719. }
  68720. bool clipToRectangleList (const RectangleList& r)
  68721. {
  68722. if (clip != 0)
  68723. {
  68724. if (isOnlyTranslated)
  68725. {
  68726. cloneClipIfMultiplyReferenced();
  68727. RectangleList offsetList (r);
  68728. offsetList.offsetAll (xOffset, yOffset);
  68729. clip = clip->clipToRectangleList (offsetList);
  68730. }
  68731. else
  68732. {
  68733. clipToPath (r.toPath(), AffineTransform::identity);
  68734. }
  68735. }
  68736. return clip != 0;
  68737. }
  68738. bool excludeClipRectangle (const Rectangle<int>& r)
  68739. {
  68740. if (clip != 0)
  68741. {
  68742. cloneClipIfMultiplyReferenced();
  68743. if (isOnlyTranslated)
  68744. {
  68745. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68746. }
  68747. else
  68748. {
  68749. Path p;
  68750. p.addRectangle (r.toFloat());
  68751. p.applyTransform (complexTransform);
  68752. p.addRectangle (clip->getClipBounds().toFloat());
  68753. p.setUsingNonZeroWinding (false);
  68754. clip = clip->clipToPath (p, AffineTransform::identity);
  68755. }
  68756. }
  68757. return clip != 0;
  68758. }
  68759. void clipToPath (const Path& p, const AffineTransform& transform)
  68760. {
  68761. if (clip != 0)
  68762. {
  68763. cloneClipIfMultiplyReferenced();
  68764. clip = clip->clipToPath (p, getTransformWith (transform));
  68765. }
  68766. }
  68767. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& t)
  68768. {
  68769. if (clip != 0)
  68770. {
  68771. if (sourceImage.hasAlphaChannel())
  68772. {
  68773. cloneClipIfMultiplyReferenced();
  68774. clip = clip->clipToImageAlpha (sourceImage, getTransformWith (t),
  68775. interpolationQuality != Graphics::lowResamplingQuality);
  68776. }
  68777. else
  68778. {
  68779. Path p;
  68780. p.addRectangle (sourceImage.getBounds());
  68781. clipToPath (p, t);
  68782. }
  68783. }
  68784. }
  68785. bool clipRegionIntersects (const Rectangle<int>& r) const
  68786. {
  68787. if (clip != 0)
  68788. {
  68789. if (isOnlyTranslated)
  68790. return clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68791. else
  68792. return getClipBounds().intersects (r);
  68793. }
  68794. return false;
  68795. }
  68796. const Rectangle<int> getUntransformedClipBounds() const
  68797. {
  68798. return clip != 0 ? clip->getClipBounds() : Rectangle<int>();
  68799. }
  68800. const Rectangle<int> getClipBounds() const
  68801. {
  68802. if (clip != 0)
  68803. {
  68804. if (isOnlyTranslated)
  68805. return clip->getClipBounds().translated (-xOffset, -yOffset);
  68806. else
  68807. return clip->getClipBounds().toFloat().transformed (complexTransform.inverted()).getSmallestIntegerContainer();
  68808. }
  68809. return Rectangle<int>();
  68810. }
  68811. SavedState* beginTransparencyLayer (float opacity)
  68812. {
  68813. const Rectangle<int> layerBounds (getUntransformedClipBounds());
  68814. SavedState* s = new SavedState (*this);
  68815. s->image = Image (Image::ARGB, layerBounds.getWidth(), layerBounds.getHeight(), true);
  68816. s->compositionAlpha = opacity;
  68817. if (s->isOnlyTranslated)
  68818. {
  68819. s->xOffset -= layerBounds.getX();
  68820. s->yOffset -= layerBounds.getY();
  68821. }
  68822. else
  68823. {
  68824. s->complexTransform = s->complexTransform.followedBy (AffineTransform::translation ((float) -layerBounds.getX(),
  68825. (float) -layerBounds.getY()));
  68826. }
  68827. s->cloneClipIfMultiplyReferenced();
  68828. s->clip = s->clip->translated (-layerBounds.getPosition());
  68829. return s;
  68830. }
  68831. void endTransparencyLayer (SavedState& layerState)
  68832. {
  68833. const Rectangle<int> layerBounds (getUntransformedClipBounds());
  68834. const ScopedPointer<LowLevelGraphicsContext> g (image.createLowLevelContext());
  68835. g->setOpacity (layerState.compositionAlpha);
  68836. g->drawImage (layerState.image, AffineTransform::translation ((float) layerBounds.getX(),
  68837. (float) layerBounds.getY()), false);
  68838. }
  68839. void fillRect (const Rectangle<int>& r, const bool replaceContents)
  68840. {
  68841. if (clip != 0)
  68842. {
  68843. if (isOnlyTranslated)
  68844. {
  68845. if (fillType.isColour())
  68846. {
  68847. Image::BitmapData destData (image, true);
  68848. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68849. }
  68850. else
  68851. {
  68852. const Rectangle<int> totalClip (clip->getClipBounds());
  68853. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68854. if (! clipped.isEmpty())
  68855. fillShape (new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68856. }
  68857. }
  68858. else
  68859. {
  68860. Path p;
  68861. p.addRectangle (r);
  68862. fillPath (p, AffineTransform::identity);
  68863. }
  68864. }
  68865. }
  68866. void fillRect (const Rectangle<float>& r)
  68867. {
  68868. if (clip != 0)
  68869. {
  68870. if (isOnlyTranslated)
  68871. {
  68872. if (fillType.isColour())
  68873. {
  68874. Image::BitmapData destData (image, true);
  68875. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68876. }
  68877. else
  68878. {
  68879. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  68880. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  68881. if (! clipped.isEmpty())
  68882. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  68883. }
  68884. }
  68885. else
  68886. {
  68887. Path p;
  68888. p.addRectangle (r);
  68889. fillPath (p, AffineTransform::identity);
  68890. }
  68891. }
  68892. }
  68893. void fillPath (const Path& path, const AffineTransform& transform)
  68894. {
  68895. if (clip != 0)
  68896. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, getTransformWith (transform)), false);
  68897. }
  68898. void fillEdgeTable (const EdgeTable& edgeTable, const float x, const int y)
  68899. {
  68900. jassert (isOnlyTranslated);
  68901. if (clip != 0)
  68902. {
  68903. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  68904. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  68905. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  68906. fillShape (shapeToFill, false);
  68907. }
  68908. }
  68909. void fillShape (SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  68910. {
  68911. jassert (clip != 0);
  68912. shapeToFill = clip->applyClipTo (shapeToFill);
  68913. if (shapeToFill != 0)
  68914. {
  68915. Image::BitmapData destData (image, true);
  68916. if (fillType.isGradient())
  68917. {
  68918. jassert (! replaceContents); // that option is just for solid colours
  68919. ColourGradient g2 (*(fillType.gradient));
  68920. g2.multiplyOpacity (fillType.getOpacity());
  68921. AffineTransform transform (getTransformWith (fillType.transform).translated (-0.5f, -0.5f));
  68922. const bool isIdentity = transform.isOnlyTranslation();
  68923. if (isIdentity)
  68924. {
  68925. // If our translation doesn't involve any distortion, we can speed it up..
  68926. g2.point1.applyTransform (transform);
  68927. g2.point2.applyTransform (transform);
  68928. transform = AffineTransform::identity;
  68929. }
  68930. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  68931. }
  68932. else if (fillType.isTiledImage())
  68933. {
  68934. renderImage (fillType.image, fillType.transform, shapeToFill);
  68935. }
  68936. else
  68937. {
  68938. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  68939. }
  68940. }
  68941. }
  68942. void renderImage (const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  68943. {
  68944. const AffineTransform transform (getTransformWith (t));
  68945. const Image::BitmapData destData (image, true);
  68946. const Image::BitmapData srcData (sourceImage, false);
  68947. const int alpha = fillType.colour.getAlpha();
  68948. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  68949. if (transform.isOnlyTranslation())
  68950. {
  68951. // If our translation doesn't involve any distortion, just use a simple blit..
  68952. int tx = (int) (transform.getTranslationX() * 256.0f);
  68953. int ty = (int) (transform.getTranslationY() * 256.0f);
  68954. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68955. {
  68956. tx = ((tx + 128) >> 8);
  68957. ty = ((ty + 128) >> 8);
  68958. if (tiledFillClipRegion != 0)
  68959. {
  68960. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  68961. }
  68962. else
  68963. {
  68964. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (image.getBounds())));
  68965. c = clip->applyClipTo (c);
  68966. if (c != 0)
  68967. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  68968. }
  68969. return;
  68970. }
  68971. }
  68972. if (transform.isSingularity())
  68973. return;
  68974. if (tiledFillClipRegion != 0)
  68975. {
  68976. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  68977. }
  68978. else
  68979. {
  68980. Path p;
  68981. p.addRectangle (sourceImage.getBounds());
  68982. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  68983. c = c->clipToPath (p, transform);
  68984. if (c != 0)
  68985. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  68986. }
  68987. }
  68988. Image image;
  68989. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  68990. private:
  68991. AffineTransform complexTransform;
  68992. int xOffset, yOffset;
  68993. float compositionAlpha;
  68994. public:
  68995. bool isOnlyTranslated;
  68996. Font font;
  68997. FillType fillType;
  68998. Graphics::ResamplingQuality interpolationQuality;
  68999. private:
  69000. void cloneClipIfMultiplyReferenced()
  69001. {
  69002. if (clip->getReferenceCount() > 1)
  69003. clip = clip->clone();
  69004. }
  69005. const AffineTransform getTransform() const
  69006. {
  69007. if (isOnlyTranslated)
  69008. return AffineTransform::translation ((float) xOffset, (float) yOffset);
  69009. return complexTransform;
  69010. }
  69011. const AffineTransform getTransformWith (const AffineTransform& userTransform) const
  69012. {
  69013. if (isOnlyTranslated)
  69014. return userTransform.translated ((float) xOffset, (float) yOffset);
  69015. return userTransform.followedBy (complexTransform);
  69016. }
  69017. SavedState& operator= (const SavedState&);
  69018. };
  69019. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  69020. : image (image_),
  69021. currentState (new SavedState (image_, image_.getBounds(), 0, 0))
  69022. {
  69023. }
  69024. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  69025. const RectangleList& initialClip)
  69026. : image (image_),
  69027. currentState (new SavedState (image_, initialClip, xOffset, yOffset))
  69028. {
  69029. }
  69030. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  69031. {
  69032. }
  69033. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  69034. {
  69035. return false;
  69036. }
  69037. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  69038. {
  69039. currentState->setOrigin (x, y);
  69040. }
  69041. void LowLevelGraphicsSoftwareRenderer::addTransform (const AffineTransform& transform)
  69042. {
  69043. currentState->addTransform (transform);
  69044. }
  69045. float LowLevelGraphicsSoftwareRenderer::getScaleFactor()
  69046. {
  69047. return currentState->getScaleFactor();
  69048. }
  69049. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  69050. {
  69051. return currentState->clipToRectangle (r);
  69052. }
  69053. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  69054. {
  69055. return currentState->clipToRectangleList (clipRegion);
  69056. }
  69057. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  69058. {
  69059. currentState->excludeClipRectangle (r);
  69060. }
  69061. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  69062. {
  69063. currentState->clipToPath (path, transform);
  69064. }
  69065. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  69066. {
  69067. currentState->clipToImageAlpha (sourceImage, transform);
  69068. }
  69069. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  69070. {
  69071. return currentState->clipRegionIntersects (r);
  69072. }
  69073. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  69074. {
  69075. return currentState->getClipBounds();
  69076. }
  69077. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  69078. {
  69079. return currentState->clip == 0;
  69080. }
  69081. void LowLevelGraphicsSoftwareRenderer::saveState()
  69082. {
  69083. stateStack.add (new SavedState (*currentState));
  69084. }
  69085. void LowLevelGraphicsSoftwareRenderer::restoreState()
  69086. {
  69087. SavedState* const top = stateStack.getLast();
  69088. if (top != 0)
  69089. {
  69090. currentState = top;
  69091. stateStack.removeLast (1, false);
  69092. }
  69093. else
  69094. {
  69095. jassertfalse; // trying to pop with an empty stack!
  69096. }
  69097. }
  69098. void LowLevelGraphicsSoftwareRenderer::beginTransparencyLayer (float opacity)
  69099. {
  69100. saveState();
  69101. currentState = currentState->beginTransparencyLayer (opacity);
  69102. }
  69103. void LowLevelGraphicsSoftwareRenderer::endTransparencyLayer()
  69104. {
  69105. const ScopedPointer<SavedState> layer (currentState);
  69106. restoreState();
  69107. currentState->endTransparencyLayer (*layer);
  69108. }
  69109. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  69110. {
  69111. currentState->fillType = fillType;
  69112. }
  69113. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  69114. {
  69115. currentState->fillType.setOpacity (newOpacity);
  69116. }
  69117. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  69118. {
  69119. currentState->interpolationQuality = quality;
  69120. }
  69121. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  69122. {
  69123. currentState->fillRect (r, replaceExistingContents);
  69124. }
  69125. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  69126. {
  69127. currentState->fillPath (path, transform);
  69128. }
  69129. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  69130. {
  69131. currentState->renderImage (sourceImage, transform, fillEntireClipAsTiles ? currentState->clip : 0);
  69132. }
  69133. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  69134. {
  69135. Path p;
  69136. p.addLineSegment (line, 1.0f);
  69137. fillPath (p, AffineTransform::identity);
  69138. }
  69139. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  69140. {
  69141. if (bottom > top)
  69142. currentState->fillRect (Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  69143. }
  69144. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  69145. {
  69146. if (right > left)
  69147. currentState->fillRect (Rectangle<float> (left, (float) y, right - left, 1.0f));
  69148. }
  69149. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69150. {
  69151. public:
  69152. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69153. void draw (SavedState& state, float x, const float y) const
  69154. {
  69155. if (snapToIntegerCoordinate)
  69156. x = std::floor (x + 0.5f);
  69157. if (edgeTable != 0)
  69158. state.fillEdgeTable (*edgeTable, x, roundToInt (y));
  69159. }
  69160. void generate (const Font& newFont, const int glyphNumber)
  69161. {
  69162. font = newFont;
  69163. snapToIntegerCoordinate = newFont.getTypeface()->isHinted();
  69164. glyph = glyphNumber;
  69165. edgeTable = 0;
  69166. Path glyphPath;
  69167. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  69168. if (! glyphPath.isEmpty())
  69169. {
  69170. const float fontHeight = font.getHeight();
  69171. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69172. #if JUCE_MAC || JUCE_IOS
  69173. .translated (0.0f, -0.5f)
  69174. #endif
  69175. );
  69176. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  69177. glyphPath, transform);
  69178. }
  69179. }
  69180. Font font;
  69181. int glyph, lastAccessCount;
  69182. bool snapToIntegerCoordinate;
  69183. private:
  69184. ScopedPointer <EdgeTable> edgeTable;
  69185. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedGlyph);
  69186. };
  69187. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69188. {
  69189. public:
  69190. GlyphCache()
  69191. : accessCounter (0), hits (0), misses (0)
  69192. {
  69193. addNewGlyphSlots (120);
  69194. }
  69195. ~GlyphCache()
  69196. {
  69197. clearSingletonInstance();
  69198. }
  69199. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69200. void drawGlyph (SavedState& state, const Font& font, const int glyphNumber, float x, float y)
  69201. {
  69202. ++accessCounter;
  69203. int oldestCounter = std::numeric_limits<int>::max();
  69204. CachedGlyph* oldest = 0;
  69205. for (int i = glyphs.size(); --i >= 0;)
  69206. {
  69207. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69208. if (glyph->glyph == glyphNumber && glyph->font == font)
  69209. {
  69210. ++hits;
  69211. glyph->lastAccessCount = accessCounter;
  69212. glyph->draw (state, x, y);
  69213. return;
  69214. }
  69215. if (glyph->lastAccessCount <= oldestCounter)
  69216. {
  69217. oldestCounter = glyph->lastAccessCount;
  69218. oldest = glyph;
  69219. }
  69220. }
  69221. if (hits + ++misses > (glyphs.size() << 4))
  69222. {
  69223. if (misses * 2 > hits)
  69224. addNewGlyphSlots (32);
  69225. hits = misses = 0;
  69226. oldest = glyphs.getLast();
  69227. }
  69228. jassert (oldest != 0);
  69229. oldest->lastAccessCount = accessCounter;
  69230. oldest->generate (font, glyphNumber);
  69231. oldest->draw (state, x, y);
  69232. }
  69233. private:
  69234. friend class OwnedArray <CachedGlyph>;
  69235. OwnedArray <CachedGlyph> glyphs;
  69236. int accessCounter, hits, misses;
  69237. void addNewGlyphSlots (int num)
  69238. {
  69239. while (--num >= 0)
  69240. glyphs.add (new CachedGlyph());
  69241. }
  69242. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphCache);
  69243. };
  69244. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69245. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69246. {
  69247. currentState->font = newFont;
  69248. }
  69249. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69250. {
  69251. return currentState->font;
  69252. }
  69253. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69254. {
  69255. Font& f = currentState->font;
  69256. if (transform.isOnlyTranslation() && currentState->isOnlyTranslated)
  69257. {
  69258. GlyphCache::getInstance()->drawGlyph (*currentState, f, glyphNumber,
  69259. transform.getTranslationX(),
  69260. transform.getTranslationY());
  69261. }
  69262. else
  69263. {
  69264. Path p;
  69265. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69266. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69267. }
  69268. }
  69269. #if JUCE_MSVC
  69270. #pragma warning (pop)
  69271. #if JUCE_DEBUG
  69272. #pragma optimize ("", on) // resets optimisations to the project defaults
  69273. #endif
  69274. #endif
  69275. END_JUCE_NAMESPACE
  69276. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69277. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69278. BEGIN_JUCE_NAMESPACE
  69279. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69280. : flags (other.flags)
  69281. {
  69282. }
  69283. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69284. {
  69285. flags = other.flags;
  69286. return *this;
  69287. }
  69288. void RectanglePlacement::applyTo (double& x, double& y, double& w, double& h,
  69289. const double dx, const double dy, const double dw, const double dh) const throw()
  69290. {
  69291. if (w == 0 || h == 0)
  69292. return;
  69293. if ((flags & stretchToFit) != 0)
  69294. {
  69295. x = dx;
  69296. y = dy;
  69297. w = dw;
  69298. h = dh;
  69299. }
  69300. else
  69301. {
  69302. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69303. : jmin (dw / w, dh / h);
  69304. if ((flags & onlyReduceInSize) != 0)
  69305. scale = jmin (scale, 1.0);
  69306. if ((flags & onlyIncreaseInSize) != 0)
  69307. scale = jmax (scale, 1.0);
  69308. w *= scale;
  69309. h *= scale;
  69310. if ((flags & xLeft) != 0)
  69311. x = dx;
  69312. else if ((flags & xRight) != 0)
  69313. x = dx + dw - w;
  69314. else
  69315. x = dx + (dw - w) * 0.5;
  69316. if ((flags & yTop) != 0)
  69317. y = dy;
  69318. else if ((flags & yBottom) != 0)
  69319. y = dy + dh - h;
  69320. else
  69321. y = dy + (dh - h) * 0.5;
  69322. }
  69323. }
  69324. const AffineTransform RectanglePlacement::getTransformToFit (const Rectangle<float>& source, const Rectangle<float>& destination) const throw()
  69325. {
  69326. if (source.isEmpty())
  69327. return AffineTransform::identity;
  69328. float newX = destination.getX();
  69329. float newY = destination.getY();
  69330. float scaleX = destination.getWidth() / source.getWidth();
  69331. float scaleY = destination.getHeight() / source.getHeight();
  69332. if ((flags & stretchToFit) == 0)
  69333. {
  69334. scaleX = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69335. : jmin (scaleX, scaleY);
  69336. if ((flags & onlyReduceInSize) != 0)
  69337. scaleX = jmin (scaleX, 1.0f);
  69338. if ((flags & onlyIncreaseInSize) != 0)
  69339. scaleX = jmax (scaleX, 1.0f);
  69340. scaleY = scaleX;
  69341. if ((flags & xRight) != 0)
  69342. newX += destination.getWidth() - source.getWidth() * scaleX; // right
  69343. else if ((flags & xLeft) == 0)
  69344. newX += (destination.getWidth() - source.getWidth() * scaleX) / 2.0f; // centre
  69345. if ((flags & yBottom) != 0)
  69346. newY += destination.getHeight() - source.getHeight() * scaleX; // bottom
  69347. else if ((flags & yTop) == 0)
  69348. newY += (destination.getHeight() - source.getHeight() * scaleX) / 2.0f; // centre
  69349. }
  69350. return AffineTransform::translation (-source.getX(), -source.getY())
  69351. .scaled (scaleX, scaleY)
  69352. .translated (newX, newY);
  69353. }
  69354. END_JUCE_NAMESPACE
  69355. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69356. /*** Start of inlined file: juce_Drawable.cpp ***/
  69357. BEGIN_JUCE_NAMESPACE
  69358. Drawable::Drawable()
  69359. {
  69360. setInterceptsMouseClicks (false, false);
  69361. setPaintingIsUnclipped (true);
  69362. }
  69363. Drawable::~Drawable()
  69364. {
  69365. }
  69366. void Drawable::draw (Graphics& g, float opacity, const AffineTransform& transform) const
  69367. {
  69368. const_cast <Drawable*> (this)->nonConstDraw (g, opacity, transform);
  69369. }
  69370. void Drawable::nonConstDraw (Graphics& g, float opacity, const AffineTransform& transform)
  69371. {
  69372. Graphics::ScopedSaveState ss (g);
  69373. const float oldOpacity = getAlpha();
  69374. setAlpha (opacity);
  69375. g.addTransform (AffineTransform::translation ((float) -originRelativeToComponent.getX(),
  69376. (float) -originRelativeToComponent.getY())
  69377. .followedBy (getTransform())
  69378. .followedBy (transform));
  69379. if (! g.isClipEmpty())
  69380. paintEntireComponent (g, false);
  69381. setAlpha (oldOpacity);
  69382. }
  69383. void Drawable::drawAt (Graphics& g, float x, float y, float opacity) const
  69384. {
  69385. draw (g, opacity, AffineTransform::translation (x, y));
  69386. }
  69387. void Drawable::drawWithin (Graphics& g, const Rectangle<float>& destArea, const RectanglePlacement& placement, float opacity) const
  69388. {
  69389. draw (g, opacity, placement.getTransformToFit (getDrawableBounds(), destArea));
  69390. }
  69391. DrawableComposite* Drawable::getParent() const
  69392. {
  69393. return dynamic_cast <DrawableComposite*> (getParentComponent());
  69394. }
  69395. void Drawable::transformContextToCorrectOrigin (Graphics& g)
  69396. {
  69397. g.setOrigin (originRelativeToComponent.getX(),
  69398. originRelativeToComponent.getY());
  69399. }
  69400. void Drawable::parentHierarchyChanged()
  69401. {
  69402. setBoundsToEnclose (getDrawableBounds());
  69403. }
  69404. void Drawable::setBoundsToEnclose (const Rectangle<float>& area)
  69405. {
  69406. Drawable* const parent = getParent();
  69407. Point<int> parentOrigin;
  69408. if (parent != 0)
  69409. parentOrigin = parent->originRelativeToComponent;
  69410. const Rectangle<int> newBounds (area.getSmallestIntegerContainer() + parentOrigin);
  69411. originRelativeToComponent = parentOrigin - newBounds.getPosition();
  69412. setBounds (newBounds);
  69413. }
  69414. void Drawable::setOriginWithOriginalSize (const Point<float>& originWithinParent)
  69415. {
  69416. setTransform (AffineTransform::translation (originWithinParent.getX(), originWithinParent.getY()));
  69417. }
  69418. void Drawable::setTransformToFit (const Rectangle<float>& area, const RectanglePlacement& placement)
  69419. {
  69420. if (! area.isEmpty())
  69421. setTransform (placement.getTransformToFit (getDrawableBounds(), area));
  69422. }
  69423. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69424. {
  69425. Drawable* result = 0;
  69426. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69427. if (image.isValid())
  69428. {
  69429. DrawableImage* const di = new DrawableImage();
  69430. di->setImage (image);
  69431. result = di;
  69432. }
  69433. else
  69434. {
  69435. const String asString (String::createStringFromData (data, (int) numBytes));
  69436. XmlDocument doc (asString);
  69437. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69438. if (outer != 0 && outer->hasTagName ("svg"))
  69439. {
  69440. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69441. if (svg != 0)
  69442. result = Drawable::createFromSVG (*svg);
  69443. }
  69444. }
  69445. return result;
  69446. }
  69447. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69448. {
  69449. MemoryOutputStream mo;
  69450. mo.writeFromInputStream (dataSource, -1);
  69451. return createFromImageData (mo.getData(), mo.getDataSize());
  69452. }
  69453. Drawable* Drawable::createFromImageFile (const File& file)
  69454. {
  69455. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69456. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69457. }
  69458. template <class DrawableClass>
  69459. class DrawableTypeHandler : public ComponentBuilder::TypeHandler
  69460. {
  69461. public:
  69462. DrawableTypeHandler()
  69463. : ComponentBuilder::TypeHandler (DrawableClass::valueTreeType)
  69464. {
  69465. }
  69466. Component* addNewComponentFromState (const ValueTree& state, Component* parent)
  69467. {
  69468. DrawableClass* const d = new DrawableClass();
  69469. if (parent != 0)
  69470. parent->addAndMakeVisible (d);
  69471. updateComponentFromState (d, state);
  69472. return d;
  69473. }
  69474. void updateComponentFromState (Component* component, const ValueTree& state)
  69475. {
  69476. DrawableClass* const d = dynamic_cast <DrawableClass*> (component);
  69477. jassert (d != 0);
  69478. d->refreshFromValueTree (state, *this->getBuilder());
  69479. }
  69480. };
  69481. void Drawable::registerDrawableTypeHandlers (ComponentBuilder& builder)
  69482. {
  69483. builder.registerTypeHandler (new DrawableTypeHandler <DrawablePath>());
  69484. builder.registerTypeHandler (new DrawableTypeHandler <DrawableComposite>());
  69485. builder.registerTypeHandler (new DrawableTypeHandler <DrawableRectangle>());
  69486. builder.registerTypeHandler (new DrawableTypeHandler <DrawableImage>());
  69487. builder.registerTypeHandler (new DrawableTypeHandler <DrawableText>());
  69488. }
  69489. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ComponentBuilder::ImageProvider* imageProvider)
  69490. {
  69491. ComponentBuilder builder (tree);
  69492. builder.setImageProvider (imageProvider);
  69493. registerDrawableTypeHandlers (builder);
  69494. ScopedPointer<Component> comp (builder.createComponent());
  69495. Drawable* const d = dynamic_cast<Drawable*> (static_cast <Component*> (comp));
  69496. if (d != 0)
  69497. comp.release();
  69498. return d;
  69499. }
  69500. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69501. : state (state_)
  69502. {
  69503. }
  69504. const String Drawable::ValueTreeWrapperBase::getID() const
  69505. {
  69506. return state [ComponentBuilder::idProperty];
  69507. }
  69508. void Drawable::ValueTreeWrapperBase::setID (const String& newID)
  69509. {
  69510. if (newID.isEmpty())
  69511. state.removeProperty (ComponentBuilder::idProperty, 0);
  69512. else
  69513. state.setProperty (ComponentBuilder::idProperty, newID, 0);
  69514. }
  69515. END_JUCE_NAMESPACE
  69516. /*** End of inlined file: juce_Drawable.cpp ***/
  69517. /*** Start of inlined file: juce_DrawableShape.cpp ***/
  69518. BEGIN_JUCE_NAMESPACE
  69519. DrawableShape::DrawableShape()
  69520. : strokeType (0.0f),
  69521. mainFill (Colours::black),
  69522. strokeFill (Colours::black)
  69523. {
  69524. }
  69525. DrawableShape::DrawableShape (const DrawableShape& other)
  69526. : strokeType (other.strokeType),
  69527. mainFill (other.mainFill),
  69528. strokeFill (other.strokeFill)
  69529. {
  69530. }
  69531. DrawableShape::~DrawableShape()
  69532. {
  69533. }
  69534. class DrawableShape::RelativePositioner : public RelativeCoordinatePositionerBase
  69535. {
  69536. public:
  69537. RelativePositioner (DrawableShape& component_, const DrawableShape::RelativeFillType& fill_, bool isMainFill_)
  69538. : RelativeCoordinatePositionerBase (component_),
  69539. owner (component_),
  69540. fill (fill_),
  69541. isMainFill (isMainFill_)
  69542. {
  69543. }
  69544. bool registerCoordinates()
  69545. {
  69546. bool ok = addPoint (fill.gradientPoint1);
  69547. ok = addPoint (fill.gradientPoint2) && ok;
  69548. return addPoint (fill.gradientPoint3) && ok;
  69549. }
  69550. void applyToComponentBounds()
  69551. {
  69552. ComponentScope scope (owner);
  69553. if (isMainFill ? owner.mainFill.recalculateCoords (&scope)
  69554. : owner.strokeFill.recalculateCoords (&scope))
  69555. owner.repaint();
  69556. }
  69557. private:
  69558. DrawableShape& owner;
  69559. const DrawableShape::RelativeFillType fill;
  69560. const bool isMainFill;
  69561. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativePositioner);
  69562. };
  69563. void DrawableShape::setFill (const FillType& newFill)
  69564. {
  69565. setFill (RelativeFillType (newFill));
  69566. }
  69567. void DrawableShape::setStrokeFill (const FillType& newFill)
  69568. {
  69569. setStrokeFill (RelativeFillType (newFill));
  69570. }
  69571. void DrawableShape::setFillInternal (RelativeFillType& fill, const RelativeFillType& newFill,
  69572. ScopedPointer<RelativeCoordinatePositionerBase>& positioner)
  69573. {
  69574. if (fill != newFill)
  69575. {
  69576. fill = newFill;
  69577. positioner = 0;
  69578. if (fill.isDynamic())
  69579. {
  69580. positioner = new RelativePositioner (*this, fill, true);
  69581. positioner->apply();
  69582. }
  69583. else
  69584. {
  69585. fill.recalculateCoords (0);
  69586. }
  69587. repaint();
  69588. }
  69589. }
  69590. void DrawableShape::setFill (const RelativeFillType& newFill)
  69591. {
  69592. setFillInternal (mainFill, newFill, mainFillPositioner);
  69593. }
  69594. void DrawableShape::setStrokeFill (const RelativeFillType& newFill)
  69595. {
  69596. setFillInternal (strokeFill, newFill, strokeFillPositioner);
  69597. }
  69598. void DrawableShape::setStrokeType (const PathStrokeType& newStrokeType)
  69599. {
  69600. if (strokeType != newStrokeType)
  69601. {
  69602. strokeType = newStrokeType;
  69603. strokeChanged();
  69604. }
  69605. }
  69606. void DrawableShape::setStrokeThickness (const float newThickness)
  69607. {
  69608. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  69609. }
  69610. bool DrawableShape::isStrokeVisible() const throw()
  69611. {
  69612. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.fill.isInvisible();
  69613. }
  69614. void DrawableShape::refreshFillTypes (const FillAndStrokeState& newState, ComponentBuilder::ImageProvider* imageProvider)
  69615. {
  69616. setFill (newState.getFill (FillAndStrokeState::fill, imageProvider));
  69617. setStrokeFill (newState.getFill (FillAndStrokeState::stroke, imageProvider));
  69618. }
  69619. void DrawableShape::writeTo (FillAndStrokeState& state, ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager) const
  69620. {
  69621. state.setFill (FillAndStrokeState::fill, mainFill, imageProvider, undoManager);
  69622. state.setFill (FillAndStrokeState::stroke, strokeFill, imageProvider, undoManager);
  69623. state.setStrokeType (strokeType, undoManager);
  69624. }
  69625. void DrawableShape::paint (Graphics& g)
  69626. {
  69627. transformContextToCorrectOrigin (g);
  69628. g.setFillType (mainFill.fill);
  69629. g.fillPath (path);
  69630. if (isStrokeVisible())
  69631. {
  69632. g.setFillType (strokeFill.fill);
  69633. g.fillPath (strokePath);
  69634. }
  69635. }
  69636. void DrawableShape::pathChanged()
  69637. {
  69638. strokeChanged();
  69639. }
  69640. void DrawableShape::strokeChanged()
  69641. {
  69642. strokePath.clear();
  69643. strokeType.createStrokedPath (strokePath, path, AffineTransform::identity, 4.0f);
  69644. setBoundsToEnclose (getDrawableBounds());
  69645. repaint();
  69646. }
  69647. const Rectangle<float> DrawableShape::getDrawableBounds() const
  69648. {
  69649. if (isStrokeVisible())
  69650. return strokePath.getBounds();
  69651. else
  69652. return path.getBounds();
  69653. }
  69654. bool DrawableShape::hitTest (int x, int y)
  69655. {
  69656. bool allowsClicksOnThisComponent, allowsClicksOnChildComponents;
  69657. getInterceptsMouseClicks (allowsClicksOnThisComponent, allowsClicksOnChildComponents);
  69658. if (! allowsClicksOnThisComponent)
  69659. return false;
  69660. const float globalX = (float) (x - originRelativeToComponent.getX());
  69661. const float globalY = (float) (y - originRelativeToComponent.getY());
  69662. return path.contains (globalX, globalY)
  69663. || (isStrokeVisible() && strokePath.contains (globalX, globalY));
  69664. }
  69665. DrawableShape::RelativeFillType::RelativeFillType()
  69666. {
  69667. }
  69668. DrawableShape::RelativeFillType::RelativeFillType (const FillType& fill_)
  69669. : fill (fill_)
  69670. {
  69671. if (fill.isGradient())
  69672. {
  69673. const ColourGradient& g = *fill.gradient;
  69674. gradientPoint1 = g.point1.transformedBy (fill.transform);
  69675. gradientPoint2 = g.point2.transformedBy (fill.transform);
  69676. gradientPoint3 = Point<float> (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69677. g.point1.getY() + g.point1.getX() - g.point2.getX())
  69678. .transformedBy (fill.transform);
  69679. fill.transform = AffineTransform::identity;
  69680. }
  69681. }
  69682. DrawableShape::RelativeFillType::RelativeFillType (const RelativeFillType& other)
  69683. : fill (other.fill),
  69684. gradientPoint1 (other.gradientPoint1),
  69685. gradientPoint2 (other.gradientPoint2),
  69686. gradientPoint3 (other.gradientPoint3)
  69687. {
  69688. }
  69689. DrawableShape::RelativeFillType& DrawableShape::RelativeFillType::operator= (const RelativeFillType& other)
  69690. {
  69691. fill = other.fill;
  69692. gradientPoint1 = other.gradientPoint1;
  69693. gradientPoint2 = other.gradientPoint2;
  69694. gradientPoint3 = other.gradientPoint3;
  69695. return *this;
  69696. }
  69697. bool DrawableShape::RelativeFillType::operator== (const RelativeFillType& other) const
  69698. {
  69699. return fill == other.fill
  69700. && ((! fill.isGradient())
  69701. || (gradientPoint1 == other.gradientPoint1
  69702. && gradientPoint2 == other.gradientPoint2
  69703. && gradientPoint3 == other.gradientPoint3));
  69704. }
  69705. bool DrawableShape::RelativeFillType::operator!= (const RelativeFillType& other) const
  69706. {
  69707. return ! operator== (other);
  69708. }
  69709. bool DrawableShape::RelativeFillType::recalculateCoords (Expression::Scope* scope)
  69710. {
  69711. if (fill.isGradient())
  69712. {
  69713. const Point<float> g1 (gradientPoint1.resolve (scope));
  69714. const Point<float> g2 (gradientPoint2.resolve (scope));
  69715. AffineTransform t;
  69716. ColourGradient& g = *fill.gradient;
  69717. if (g.isRadial)
  69718. {
  69719. const Point<float> g3 (gradientPoint3.resolve (scope));
  69720. const Point<float> g3Source (g1.getX() + g2.getY() - g1.getY(),
  69721. g1.getY() + g1.getX() - g2.getX());
  69722. t = AffineTransform::fromTargetPoints (g1.getX(), g1.getY(), g1.getX(), g1.getY(),
  69723. g2.getX(), g2.getY(), g2.getX(), g2.getY(),
  69724. g3Source.getX(), g3Source.getY(), g3.getX(), g3.getY());
  69725. }
  69726. if (g.point1 != g1 || g.point2 != g2 || fill.transform != t)
  69727. {
  69728. g.point1 = g1;
  69729. g.point2 = g2;
  69730. fill.transform = t;
  69731. return true;
  69732. }
  69733. }
  69734. return false;
  69735. }
  69736. bool DrawableShape::RelativeFillType::isDynamic() const
  69737. {
  69738. return gradientPoint1.isDynamic() || gradientPoint2.isDynamic() || gradientPoint3.isDynamic();
  69739. }
  69740. void DrawableShape::RelativeFillType::writeTo (ValueTree& v, ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager) const
  69741. {
  69742. if (fill.isColour())
  69743. {
  69744. v.setProperty (FillAndStrokeState::type, "solid", undoManager);
  69745. v.setProperty (FillAndStrokeState::colour, String::toHexString ((int) fill.colour.getARGB()), undoManager);
  69746. }
  69747. else if (fill.isGradient())
  69748. {
  69749. v.setProperty (FillAndStrokeState::type, "gradient", undoManager);
  69750. v.setProperty (FillAndStrokeState::gradientPoint1, gradientPoint1.toString(), undoManager);
  69751. v.setProperty (FillAndStrokeState::gradientPoint2, gradientPoint2.toString(), undoManager);
  69752. v.setProperty (FillAndStrokeState::gradientPoint3, gradientPoint3.toString(), undoManager);
  69753. const ColourGradient& cg = *fill.gradient;
  69754. v.setProperty (FillAndStrokeState::radial, cg.isRadial, undoManager);
  69755. String s;
  69756. for (int i = 0; i < cg.getNumColours(); ++i)
  69757. s << ' ' << cg.getColourPosition (i)
  69758. << ' ' << String::toHexString ((int) cg.getColour(i).getARGB());
  69759. v.setProperty (FillAndStrokeState::colours, s.trimStart(), undoManager);
  69760. }
  69761. else if (fill.isTiledImage())
  69762. {
  69763. v.setProperty (FillAndStrokeState::type, "image", undoManager);
  69764. if (imageProvider != 0)
  69765. v.setProperty (FillAndStrokeState::imageId, imageProvider->getIdentifierForImage (fill.image), undoManager);
  69766. if (fill.getOpacity() < 1.0f)
  69767. v.setProperty (FillAndStrokeState::imageOpacity, fill.getOpacity(), undoManager);
  69768. else
  69769. v.removeProperty (FillAndStrokeState::imageOpacity, undoManager);
  69770. }
  69771. else
  69772. {
  69773. jassertfalse;
  69774. }
  69775. }
  69776. bool DrawableShape::RelativeFillType::readFrom (const ValueTree& v, ComponentBuilder::ImageProvider* imageProvider)
  69777. {
  69778. const String newType (v [FillAndStrokeState::type].toString());
  69779. if (newType == "solid")
  69780. {
  69781. const String colourString (v [FillAndStrokeState::colour].toString());
  69782. fill.setColour (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  69783. : (uint32) colourString.getHexValue32()));
  69784. return true;
  69785. }
  69786. else if (newType == "gradient")
  69787. {
  69788. ColourGradient g;
  69789. g.isRadial = v [FillAndStrokeState::radial];
  69790. StringArray colourSteps;
  69791. colourSteps.addTokens (v [FillAndStrokeState::colours].toString(), false);
  69792. for (int i = 0; i < colourSteps.size() / 2; ++i)
  69793. g.addColour (colourSteps[i * 2].getDoubleValue(),
  69794. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  69795. fill.setGradient (g);
  69796. gradientPoint1 = RelativePoint (v [FillAndStrokeState::gradientPoint1]);
  69797. gradientPoint2 = RelativePoint (v [FillAndStrokeState::gradientPoint2]);
  69798. gradientPoint3 = RelativePoint (v [FillAndStrokeState::gradientPoint3]);
  69799. return true;
  69800. }
  69801. else if (newType == "image")
  69802. {
  69803. Image im;
  69804. if (imageProvider != 0)
  69805. im = imageProvider->getImageForIdentifier (v [FillAndStrokeState::imageId]);
  69806. fill.setTiledImage (im, AffineTransform::identity);
  69807. fill.setOpacity ((float) v.getProperty (FillAndStrokeState::imageOpacity, 1.0f));
  69808. return true;
  69809. }
  69810. jassertfalse;
  69811. return false;
  69812. }
  69813. const Identifier DrawableShape::FillAndStrokeState::type ("type");
  69814. const Identifier DrawableShape::FillAndStrokeState::colour ("colour");
  69815. const Identifier DrawableShape::FillAndStrokeState::colours ("colours");
  69816. const Identifier DrawableShape::FillAndStrokeState::fill ("Fill");
  69817. const Identifier DrawableShape::FillAndStrokeState::stroke ("Stroke");
  69818. const Identifier DrawableShape::FillAndStrokeState::path ("Path");
  69819. const Identifier DrawableShape::FillAndStrokeState::jointStyle ("jointStyle");
  69820. const Identifier DrawableShape::FillAndStrokeState::capStyle ("capStyle");
  69821. const Identifier DrawableShape::FillAndStrokeState::strokeWidth ("strokeWidth");
  69822. const Identifier DrawableShape::FillAndStrokeState::gradientPoint1 ("point1");
  69823. const Identifier DrawableShape::FillAndStrokeState::gradientPoint2 ("point2");
  69824. const Identifier DrawableShape::FillAndStrokeState::gradientPoint3 ("point3");
  69825. const Identifier DrawableShape::FillAndStrokeState::radial ("radial");
  69826. const Identifier DrawableShape::FillAndStrokeState::imageId ("imageId");
  69827. const Identifier DrawableShape::FillAndStrokeState::imageOpacity ("imageOpacity");
  69828. DrawableShape::FillAndStrokeState::FillAndStrokeState (const ValueTree& state_)
  69829. : Drawable::ValueTreeWrapperBase (state_)
  69830. {
  69831. }
  69832. const DrawableShape::RelativeFillType DrawableShape::FillAndStrokeState::getFill (const Identifier& fillOrStrokeType, ComponentBuilder::ImageProvider* imageProvider) const
  69833. {
  69834. DrawableShape::RelativeFillType f;
  69835. f.readFrom (state.getChildWithName (fillOrStrokeType), imageProvider);
  69836. return f;
  69837. }
  69838. ValueTree DrawableShape::FillAndStrokeState::getFillState (const Identifier& fillOrStrokeType)
  69839. {
  69840. ValueTree v (state.getChildWithName (fillOrStrokeType));
  69841. if (v.isValid())
  69842. return v;
  69843. setFill (fillOrStrokeType, FillType (Colours::black), 0, 0);
  69844. return getFillState (fillOrStrokeType);
  69845. }
  69846. void DrawableShape::FillAndStrokeState::setFill (const Identifier& fillOrStrokeType, const RelativeFillType& newFill,
  69847. ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager)
  69848. {
  69849. ValueTree v (state.getOrCreateChildWithName (fillOrStrokeType, undoManager));
  69850. newFill.writeTo (v, imageProvider, undoManager);
  69851. }
  69852. const PathStrokeType DrawableShape::FillAndStrokeState::getStrokeType() const
  69853. {
  69854. const String jointStyleString (state [jointStyle].toString());
  69855. const String capStyleString (state [capStyle].toString());
  69856. return PathStrokeType (state [strokeWidth],
  69857. jointStyleString == "curved" ? PathStrokeType::curved
  69858. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  69859. : PathStrokeType::mitered),
  69860. capStyleString == "square" ? PathStrokeType::square
  69861. : (capStyleString == "round" ? PathStrokeType::rounded
  69862. : PathStrokeType::butt));
  69863. }
  69864. void DrawableShape::FillAndStrokeState::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  69865. {
  69866. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  69867. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  69868. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  69869. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  69870. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  69871. }
  69872. END_JUCE_NAMESPACE
  69873. /*** End of inlined file: juce_DrawableShape.cpp ***/
  69874. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69875. BEGIN_JUCE_NAMESPACE
  69876. DrawableComposite::DrawableComposite()
  69877. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f)),
  69878. updateBoundsReentrant (false)
  69879. {
  69880. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69881. RelativeCoordinate (100.0),
  69882. RelativeCoordinate (0.0),
  69883. RelativeCoordinate (100.0)));
  69884. }
  69885. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  69886. : bounds (other.bounds),
  69887. markersX (other.markersX),
  69888. markersY (other.markersY),
  69889. updateBoundsReentrant (false)
  69890. {
  69891. for (int i = 0; i < other.getNumChildComponents(); ++i)
  69892. {
  69893. const Drawable* const d = dynamic_cast <const Drawable*> (other.getChildComponent(i));
  69894. if (d != 0)
  69895. addAndMakeVisible (d->createCopy());
  69896. }
  69897. }
  69898. DrawableComposite::~DrawableComposite()
  69899. {
  69900. deleteAllChildren();
  69901. }
  69902. Drawable* DrawableComposite::createCopy() const
  69903. {
  69904. return new DrawableComposite (*this);
  69905. }
  69906. const Rectangle<float> DrawableComposite::getDrawableBounds() const
  69907. {
  69908. Rectangle<float> r;
  69909. for (int i = getNumChildComponents(); --i >= 0;)
  69910. {
  69911. const Drawable* const d = dynamic_cast <const Drawable*> (getChildComponent(i));
  69912. if (d != 0)
  69913. r = r.getUnion (d->isTransformed() ? d->getDrawableBounds().transformed (d->getTransform())
  69914. : d->getDrawableBounds());
  69915. }
  69916. return r;
  69917. }
  69918. MarkerList* DrawableComposite::getMarkers (bool xAxis)
  69919. {
  69920. return xAxis ? &markersX : &markersY;
  69921. }
  69922. const RelativeRectangle DrawableComposite::getContentArea() const
  69923. {
  69924. jassert (markersX.getNumMarkers() >= 2 && markersX.getMarker (0)->name == contentLeftMarkerName && markersX.getMarker (1)->name == contentRightMarkerName);
  69925. jassert (markersY.getNumMarkers() >= 2 && markersY.getMarker (0)->name == contentTopMarkerName && markersY.getMarker (1)->name == contentBottomMarkerName);
  69926. return RelativeRectangle (markersX.getMarker(0)->position, markersX.getMarker(1)->position,
  69927. markersY.getMarker(0)->position, markersY.getMarker(1)->position);
  69928. }
  69929. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  69930. {
  69931. markersX.setMarker (contentLeftMarkerName, newArea.left);
  69932. markersX.setMarker (contentRightMarkerName, newArea.right);
  69933. markersY.setMarker (contentTopMarkerName, newArea.top);
  69934. markersY.setMarker (contentBottomMarkerName, newArea.bottom);
  69935. }
  69936. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBounds)
  69937. {
  69938. if (bounds != newBounds)
  69939. {
  69940. bounds = newBounds;
  69941. if (bounds.isDynamic())
  69942. {
  69943. Drawable::Positioner<DrawableComposite>* const p = new Drawable::Positioner<DrawableComposite> (*this);
  69944. setPositioner (p);
  69945. p->apply();
  69946. }
  69947. else
  69948. {
  69949. setPositioner (0);
  69950. recalculateCoordinates (0);
  69951. }
  69952. }
  69953. }
  69954. void DrawableComposite::resetBoundingBoxToContentArea()
  69955. {
  69956. const RelativeRectangle content (getContentArea());
  69957. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69958. RelativePoint (content.right, content.top),
  69959. RelativePoint (content.left, content.bottom)));
  69960. }
  69961. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  69962. {
  69963. const Rectangle<float> activeArea (getDrawableBounds());
  69964. setContentArea (RelativeRectangle (RelativeCoordinate (activeArea.getX()),
  69965. RelativeCoordinate (activeArea.getRight()),
  69966. RelativeCoordinate (activeArea.getY()),
  69967. RelativeCoordinate (activeArea.getBottom())));
  69968. resetBoundingBoxToContentArea();
  69969. }
  69970. bool DrawableComposite::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  69971. {
  69972. bool ok = positioner.addPoint (bounds.topLeft);
  69973. ok = positioner.addPoint (bounds.topRight) && ok;
  69974. return positioner.addPoint (bounds.bottomLeft) && ok;
  69975. }
  69976. void DrawableComposite::recalculateCoordinates (Expression::Scope* scope)
  69977. {
  69978. Point<float> resolved[3];
  69979. bounds.resolveThreePoints (resolved, scope);
  69980. const Rectangle<float> content (getContentArea().resolve (scope));
  69981. AffineTransform t (AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  69982. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  69983. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY()));
  69984. if (t.isSingularity())
  69985. t = AffineTransform::identity;
  69986. setTransform (t);
  69987. }
  69988. void DrawableComposite::parentHierarchyChanged()
  69989. {
  69990. DrawableComposite* parent = getParent();
  69991. if (parent != 0)
  69992. originRelativeToComponent = parent->originRelativeToComponent - getPosition();
  69993. }
  69994. void DrawableComposite::childBoundsChanged (Component*)
  69995. {
  69996. updateBoundsToFitChildren();
  69997. }
  69998. void DrawableComposite::childrenChanged()
  69999. {
  70000. updateBoundsToFitChildren();
  70001. }
  70002. void DrawableComposite::updateBoundsToFitChildren()
  70003. {
  70004. if (! updateBoundsReentrant)
  70005. {
  70006. const ScopedValueSetter<bool> setter (updateBoundsReentrant, true, false);
  70007. Rectangle<int> childArea;
  70008. for (int i = getNumChildComponents(); --i >= 0;)
  70009. childArea = childArea.getUnion (getChildComponent(i)->getBoundsInParent());
  70010. const Point<int> delta (childArea.getPosition());
  70011. childArea += getPosition();
  70012. if (childArea != getBounds())
  70013. {
  70014. if (! delta.isOrigin())
  70015. {
  70016. originRelativeToComponent -= delta;
  70017. for (int i = getNumChildComponents(); --i >= 0;)
  70018. {
  70019. Component* const c = getChildComponent(i);
  70020. if (c != 0)
  70021. c->setBounds (c->getBounds() - delta);
  70022. }
  70023. }
  70024. setBounds (childArea);
  70025. }
  70026. }
  70027. }
  70028. const char* const DrawableComposite::contentLeftMarkerName = "left";
  70029. const char* const DrawableComposite::contentRightMarkerName = "right";
  70030. const char* const DrawableComposite::contentTopMarkerName = "top";
  70031. const char* const DrawableComposite::contentBottomMarkerName = "bottom";
  70032. const Identifier DrawableComposite::valueTreeType ("Group");
  70033. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  70034. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  70035. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70036. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  70037. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  70038. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  70039. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70040. : ValueTreeWrapperBase (state_)
  70041. {
  70042. jassert (state.hasType (valueTreeType));
  70043. }
  70044. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  70045. {
  70046. return state.getChildWithName (childGroupTag);
  70047. }
  70048. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  70049. {
  70050. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  70051. }
  70052. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  70053. {
  70054. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70055. state.getProperty (topRight, "100, 0"),
  70056. state.getProperty (bottomLeft, "0, 100"));
  70057. }
  70058. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70059. {
  70060. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70061. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70062. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70063. }
  70064. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  70065. {
  70066. const RelativeRectangle content (getContentArea());
  70067. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  70068. RelativePoint (content.right, content.top),
  70069. RelativePoint (content.left, content.bottom)), undoManager);
  70070. }
  70071. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  70072. {
  70073. MarkerList::ValueTreeWrapper markersX (getMarkerList (true));
  70074. MarkerList::ValueTreeWrapper markersY (getMarkerList (false));
  70075. return RelativeRectangle (markersX.getMarker (markersX.getMarkerState (0)).position,
  70076. markersX.getMarker (markersX.getMarkerState (1)).position,
  70077. markersY.getMarker (markersY.getMarkerState (0)).position,
  70078. markersY.getMarker (markersY.getMarkerState (1)).position);
  70079. }
  70080. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  70081. {
  70082. MarkerList::ValueTreeWrapper markersX (getMarkerListCreating (true, 0));
  70083. MarkerList::ValueTreeWrapper markersY (getMarkerListCreating (false, 0));
  70084. markersX.setMarker (MarkerList::Marker (contentLeftMarkerName, newArea.left), undoManager);
  70085. markersX.setMarker (MarkerList::Marker (contentRightMarkerName, newArea.right), undoManager);
  70086. markersY.setMarker (MarkerList::Marker (contentTopMarkerName, newArea.top), undoManager);
  70087. markersY.setMarker (MarkerList::Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  70088. }
  70089. MarkerList::ValueTreeWrapper DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  70090. {
  70091. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  70092. }
  70093. MarkerList::ValueTreeWrapper DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  70094. {
  70095. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  70096. }
  70097. void DrawableComposite::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70098. {
  70099. const ValueTreeWrapper wrapper (tree);
  70100. setComponentID (wrapper.getID());
  70101. wrapper.getMarkerList (true).applyTo (markersX);
  70102. wrapper.getMarkerList (false).applyTo (markersY);
  70103. setBoundingBox (wrapper.getBoundingBox());
  70104. builder.updateChildComponents (*this, wrapper.getChildList());
  70105. }
  70106. const ValueTree DrawableComposite::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70107. {
  70108. ValueTree tree (valueTreeType);
  70109. ValueTreeWrapper v (tree);
  70110. v.setID (getComponentID());
  70111. v.setBoundingBox (bounds, 0);
  70112. ValueTree childList (v.getChildListCreating (0));
  70113. for (int i = 0; i < getNumChildComponents(); ++i)
  70114. {
  70115. const Drawable* const d = dynamic_cast <const Drawable*> (getChildComponent(i));
  70116. jassert (d != 0); // You can't save a mix of Drawables and normal components!
  70117. childList.addChild (d->createValueTree (imageProvider), -1, 0);
  70118. }
  70119. v.getMarkerListCreating (true, 0).readFrom (markersX, 0);
  70120. v.getMarkerListCreating (false, 0).readFrom (markersY, 0);
  70121. return tree;
  70122. }
  70123. END_JUCE_NAMESPACE
  70124. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70125. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70126. BEGIN_JUCE_NAMESPACE
  70127. DrawableImage::DrawableImage()
  70128. : image (0),
  70129. opacity (1.0f),
  70130. overlayColour (0x00000000)
  70131. {
  70132. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70133. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70134. }
  70135. DrawableImage::DrawableImage (const DrawableImage& other)
  70136. : image (other.image),
  70137. opacity (other.opacity),
  70138. overlayColour (other.overlayColour),
  70139. bounds (other.bounds)
  70140. {
  70141. }
  70142. DrawableImage::~DrawableImage()
  70143. {
  70144. }
  70145. void DrawableImage::setImage (const Image& imageToUse)
  70146. {
  70147. image = imageToUse;
  70148. setBounds (imageToUse.getBounds());
  70149. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70150. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70151. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70152. recalculateCoordinates (0);
  70153. repaint();
  70154. }
  70155. void DrawableImage::setOpacity (const float newOpacity)
  70156. {
  70157. opacity = newOpacity;
  70158. }
  70159. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70160. {
  70161. overlayColour = newOverlayColour;
  70162. }
  70163. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70164. {
  70165. if (bounds != newBounds)
  70166. {
  70167. bounds = newBounds;
  70168. if (bounds.isDynamic())
  70169. {
  70170. Drawable::Positioner<DrawableImage>* const p = new Drawable::Positioner<DrawableImage> (*this);
  70171. setPositioner (p);
  70172. p->apply();
  70173. }
  70174. else
  70175. {
  70176. setPositioner (0);
  70177. recalculateCoordinates (0);
  70178. }
  70179. }
  70180. }
  70181. bool DrawableImage::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70182. {
  70183. bool ok = positioner.addPoint (bounds.topLeft);
  70184. ok = positioner.addPoint (bounds.topRight) && ok;
  70185. return positioner.addPoint (bounds.bottomLeft) && ok;
  70186. }
  70187. void DrawableImage::recalculateCoordinates (Expression::Scope* scope)
  70188. {
  70189. if (image.isValid())
  70190. {
  70191. Point<float> resolved[3];
  70192. bounds.resolveThreePoints (resolved, scope);
  70193. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70194. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70195. AffineTransform t (AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70196. tr.getX(), tr.getY(),
  70197. bl.getX(), bl.getY()));
  70198. if (t.isSingularity())
  70199. t = AffineTransform::identity;
  70200. setTransform (t);
  70201. }
  70202. }
  70203. void DrawableImage::paint (Graphics& g)
  70204. {
  70205. if (image.isValid())
  70206. {
  70207. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70208. {
  70209. g.setOpacity (opacity);
  70210. g.drawImageAt (image, 0, 0, false);
  70211. }
  70212. if (! overlayColour.isTransparent())
  70213. {
  70214. g.setColour (overlayColour.withMultipliedAlpha (opacity));
  70215. g.drawImageAt (image, 0, 0, true);
  70216. }
  70217. }
  70218. }
  70219. const Rectangle<float> DrawableImage::getDrawableBounds() const
  70220. {
  70221. return image.getBounds().toFloat();
  70222. }
  70223. bool DrawableImage::hitTest (int x, int y) const
  70224. {
  70225. return (! image.isNull())
  70226. && image.getPixelAt (x, y).getAlpha() >= 127;
  70227. }
  70228. Drawable* DrawableImage::createCopy() const
  70229. {
  70230. return new DrawableImage (*this);
  70231. }
  70232. const Identifier DrawableImage::valueTreeType ("Image");
  70233. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70234. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70235. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70236. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70237. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70238. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70239. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70240. : ValueTreeWrapperBase (state_)
  70241. {
  70242. jassert (state.hasType (valueTreeType));
  70243. }
  70244. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70245. {
  70246. return state [image];
  70247. }
  70248. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70249. {
  70250. return state.getPropertyAsValue (image, undoManager);
  70251. }
  70252. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70253. {
  70254. state.setProperty (image, newIdentifier, undoManager);
  70255. }
  70256. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70257. {
  70258. return (float) state.getProperty (opacity, 1.0);
  70259. }
  70260. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70261. {
  70262. if (! state.hasProperty (opacity))
  70263. state.setProperty (opacity, 1.0, undoManager);
  70264. return state.getPropertyAsValue (opacity, undoManager);
  70265. }
  70266. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70267. {
  70268. state.setProperty (opacity, newOpacity, undoManager);
  70269. }
  70270. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70271. {
  70272. return Colour (state [overlay].toString().getHexValue32());
  70273. }
  70274. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70275. {
  70276. if (newColour.isTransparent())
  70277. state.removeProperty (overlay, undoManager);
  70278. else
  70279. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70280. }
  70281. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70282. {
  70283. return state.getPropertyAsValue (overlay, undoManager);
  70284. }
  70285. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70286. {
  70287. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70288. state.getProperty (topRight, "100, 0"),
  70289. state.getProperty (bottomLeft, "0, 100"));
  70290. }
  70291. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70292. {
  70293. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70294. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70295. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70296. }
  70297. void DrawableImage::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70298. {
  70299. const ValueTreeWrapper controller (tree);
  70300. setComponentID (controller.getID());
  70301. const float newOpacity = controller.getOpacity();
  70302. const Colour newOverlayColour (controller.getOverlayColour());
  70303. Image newImage;
  70304. const var imageIdentifier (controller.getImageIdentifier());
  70305. jassert (builder.getImageProvider() != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70306. if (builder.getImageProvider() != 0)
  70307. newImage = builder.getImageProvider()->getImageForIdentifier (imageIdentifier);
  70308. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70309. if (bounds != newBounds || newOpacity != opacity
  70310. || overlayColour != newOverlayColour || image != newImage)
  70311. {
  70312. repaint();
  70313. opacity = newOpacity;
  70314. overlayColour = newOverlayColour;
  70315. if (image != newImage)
  70316. setImage (newImage);
  70317. setBoundingBox (newBounds);
  70318. }
  70319. }
  70320. const ValueTree DrawableImage::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70321. {
  70322. ValueTree tree (valueTreeType);
  70323. ValueTreeWrapper v (tree);
  70324. v.setID (getComponentID());
  70325. v.setOpacity (opacity, 0);
  70326. v.setOverlayColour (overlayColour, 0);
  70327. v.setBoundingBox (bounds, 0);
  70328. if (image.isValid())
  70329. {
  70330. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70331. if (imageProvider != 0)
  70332. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70333. }
  70334. return tree;
  70335. }
  70336. END_JUCE_NAMESPACE
  70337. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70338. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70339. BEGIN_JUCE_NAMESPACE
  70340. DrawablePath::DrawablePath()
  70341. {
  70342. }
  70343. DrawablePath::DrawablePath (const DrawablePath& other)
  70344. : DrawableShape (other)
  70345. {
  70346. if (other.relativePath != 0)
  70347. setPath (*other.relativePath);
  70348. else
  70349. setPath (other.path);
  70350. }
  70351. DrawablePath::~DrawablePath()
  70352. {
  70353. }
  70354. Drawable* DrawablePath::createCopy() const
  70355. {
  70356. return new DrawablePath (*this);
  70357. }
  70358. void DrawablePath::setPath (const Path& newPath)
  70359. {
  70360. path = newPath;
  70361. pathChanged();
  70362. }
  70363. const Path& DrawablePath::getPath() const
  70364. {
  70365. return path;
  70366. }
  70367. const Path& DrawablePath::getStrokePath() const
  70368. {
  70369. return strokePath;
  70370. }
  70371. void DrawablePath::applyRelativePath (const RelativePointPath& newRelativePath, Expression::Scope* scope)
  70372. {
  70373. Path newPath;
  70374. newRelativePath.createPath (newPath, scope);
  70375. if (path != newPath)
  70376. {
  70377. path.swapWithPath (newPath);
  70378. pathChanged();
  70379. }
  70380. }
  70381. class DrawablePath::RelativePositioner : public RelativeCoordinatePositionerBase
  70382. {
  70383. public:
  70384. RelativePositioner (DrawablePath& component_)
  70385. : RelativeCoordinatePositionerBase (component_),
  70386. owner (component_)
  70387. {
  70388. }
  70389. bool registerCoordinates()
  70390. {
  70391. bool ok = true;
  70392. jassert (owner.relativePath != 0);
  70393. const RelativePointPath& path = *owner.relativePath;
  70394. for (int i = 0; i < path.elements.size(); ++i)
  70395. {
  70396. RelativePointPath::ElementBase* const e = path.elements.getUnchecked(i);
  70397. int numPoints;
  70398. RelativePoint* const points = e->getControlPoints (numPoints);
  70399. for (int j = numPoints; --j >= 0;)
  70400. ok = addPoint (points[j]) && ok;
  70401. }
  70402. return ok;
  70403. }
  70404. void applyToComponentBounds()
  70405. {
  70406. jassert (owner.relativePath != 0);
  70407. ComponentScope scope (getComponent());
  70408. owner.applyRelativePath (*owner.relativePath, &scope);
  70409. }
  70410. private:
  70411. DrawablePath& owner;
  70412. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativePositioner);
  70413. };
  70414. void DrawablePath::setPath (const RelativePointPath& newRelativePath)
  70415. {
  70416. if (newRelativePath.containsAnyDynamicPoints())
  70417. {
  70418. if (relativePath == 0 || newRelativePath != *relativePath)
  70419. {
  70420. relativePath = new RelativePointPath (newRelativePath);
  70421. RelativePositioner* const p = new RelativePositioner (*this);
  70422. setPositioner (p);
  70423. p->apply();
  70424. }
  70425. }
  70426. else
  70427. {
  70428. relativePath = 0;
  70429. applyRelativePath (newRelativePath, 0);
  70430. }
  70431. }
  70432. const Identifier DrawablePath::valueTreeType ("Path");
  70433. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70434. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70435. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70436. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70437. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70438. : FillAndStrokeState (state_)
  70439. {
  70440. jassert (state.hasType (valueTreeType));
  70441. }
  70442. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70443. {
  70444. return state.getOrCreateChildWithName (path, 0);
  70445. }
  70446. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70447. {
  70448. return state [nonZeroWinding];
  70449. }
  70450. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70451. {
  70452. state.setProperty (nonZeroWinding, b, undoManager);
  70453. }
  70454. void DrawablePath::ValueTreeWrapper::readFrom (const RelativePointPath& relativePath, UndoManager* undoManager)
  70455. {
  70456. setUsesNonZeroWinding (relativePath.usesNonZeroWinding, undoManager);
  70457. ValueTree pathTree (getPathState());
  70458. pathTree.removeAllChildren (undoManager);
  70459. for (int i = 0; i < relativePath.elements.size(); ++i)
  70460. pathTree.addChild (relativePath.elements.getUnchecked(i)->createTree(), -1, undoManager);
  70461. }
  70462. void DrawablePath::ValueTreeWrapper::writeTo (RelativePointPath& relativePath) const
  70463. {
  70464. relativePath.usesNonZeroWinding = usesNonZeroWinding();
  70465. RelativePoint points[3];
  70466. const ValueTree pathTree (state.getChildWithName (path));
  70467. const int num = pathTree.getNumChildren();
  70468. for (int i = 0; i < num; ++i)
  70469. {
  70470. const Element e (pathTree.getChild(i));
  70471. const int numCps = e.getNumControlPoints();
  70472. for (int j = 0; j < numCps; ++j)
  70473. points[j] = e.getControlPoint (j);
  70474. const Identifier type (e.getType());
  70475. RelativePointPath::ElementBase* newElement = 0;
  70476. if (type == Element::startSubPathElement) newElement = new RelativePointPath::StartSubPath (points[0]);
  70477. else if (type == Element::closeSubPathElement) newElement = new RelativePointPath::CloseSubPath();
  70478. else if (type == Element::lineToElement) newElement = new RelativePointPath::LineTo (points[0]);
  70479. else if (type == Element::quadraticToElement) newElement = new RelativePointPath::QuadraticTo (points[0], points[1]);
  70480. else if (type == Element::cubicToElement) newElement = new RelativePointPath::CubicTo (points[0], points[1], points[2]);
  70481. else jassertfalse;
  70482. relativePath.addElement (newElement);
  70483. }
  70484. }
  70485. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70486. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70487. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70488. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70489. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70490. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70491. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70492. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70493. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70494. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70495. : state (state_)
  70496. {
  70497. }
  70498. DrawablePath::ValueTreeWrapper::Element::~Element()
  70499. {
  70500. }
  70501. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70502. {
  70503. return ValueTreeWrapper (state.getParent().getParent());
  70504. }
  70505. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70506. {
  70507. return Element (state.getSibling (-1));
  70508. }
  70509. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70510. {
  70511. const Identifier i (state.getType());
  70512. if (i == startSubPathElement || i == lineToElement) return 1;
  70513. if (i == quadraticToElement) return 2;
  70514. if (i == cubicToElement) return 3;
  70515. return 0;
  70516. }
  70517. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70518. {
  70519. jassert (index >= 0 && index < getNumControlPoints());
  70520. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70521. }
  70522. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70523. {
  70524. jassert (index >= 0 && index < getNumControlPoints());
  70525. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70526. }
  70527. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70528. {
  70529. jassert (index >= 0 && index < getNumControlPoints());
  70530. state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70531. }
  70532. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70533. {
  70534. const Identifier i (state.getType());
  70535. if (i == startSubPathElement)
  70536. return getControlPoint (0);
  70537. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70538. return getPreviousElement().getEndPoint();
  70539. }
  70540. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70541. {
  70542. const Identifier i (state.getType());
  70543. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70544. if (i == quadraticToElement) return getControlPoint (1);
  70545. if (i == cubicToElement) return getControlPoint (2);
  70546. jassert (i == closeSubPathElement);
  70547. return RelativePoint();
  70548. }
  70549. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::Scope* scope) const
  70550. {
  70551. const Identifier i (state.getType());
  70552. if (i == lineToElement || i == closeSubPathElement)
  70553. return getEndPoint().resolve (scope).getDistanceFrom (getStartPoint().resolve (scope));
  70554. if (i == cubicToElement)
  70555. {
  70556. Path p;
  70557. p.startNewSubPath (getStartPoint().resolve (scope));
  70558. p.cubicTo (getControlPoint (0).resolve (scope), getControlPoint (1).resolve (scope), getControlPoint (2).resolve (scope));
  70559. return p.getLength();
  70560. }
  70561. if (i == quadraticToElement)
  70562. {
  70563. Path p;
  70564. p.startNewSubPath (getStartPoint().resolve (scope));
  70565. p.quadraticTo (getControlPoint (0).resolve (scope), getControlPoint (1).resolve (scope));
  70566. return p.getLength();
  70567. }
  70568. jassert (i == startSubPathElement);
  70569. return 0;
  70570. }
  70571. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70572. {
  70573. return state [mode].toString();
  70574. }
  70575. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70576. {
  70577. if (state.hasType (cubicToElement))
  70578. state.setProperty (mode, newMode, undoManager);
  70579. }
  70580. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70581. {
  70582. const Identifier i (state.getType());
  70583. if (i == quadraticToElement || i == cubicToElement)
  70584. {
  70585. ValueTree newState (lineToElement);
  70586. Element e (newState);
  70587. e.setControlPoint (0, getEndPoint(), undoManager);
  70588. state = newState;
  70589. }
  70590. }
  70591. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::Scope* scope, UndoManager* undoManager)
  70592. {
  70593. const Identifier i (state.getType());
  70594. if (i == lineToElement || i == quadraticToElement)
  70595. {
  70596. ValueTree newState (cubicToElement);
  70597. Element e (newState);
  70598. const RelativePoint start (getStartPoint());
  70599. const RelativePoint end (getEndPoint());
  70600. const Point<float> startResolved (start.resolve (scope));
  70601. const Point<float> endResolved (end.resolve (scope));
  70602. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70603. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70604. e.setControlPoint (2, end, undoManager);
  70605. state = newState;
  70606. }
  70607. }
  70608. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70609. {
  70610. const Identifier i (state.getType());
  70611. if (i != startSubPathElement)
  70612. {
  70613. ValueTree newState (startSubPathElement);
  70614. Element e (newState);
  70615. e.setControlPoint (0, getEndPoint(), undoManager);
  70616. state = newState;
  70617. }
  70618. }
  70619. namespace DrawablePathHelpers
  70620. {
  70621. const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70622. {
  70623. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70624. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70625. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70626. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70627. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70628. return newCp1 + (newCp2 - newCp1) * proportion;
  70629. }
  70630. const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70631. {
  70632. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70633. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70634. return mid1 + (mid2 - mid1) * proportion;
  70635. }
  70636. }
  70637. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::Scope* scope) const
  70638. {
  70639. using namespace DrawablePathHelpers;
  70640. const Identifier type (state.getType());
  70641. float bestProp = 0;
  70642. if (type == cubicToElement)
  70643. {
  70644. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70645. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope), rp4.resolve (scope) };
  70646. float bestDistance = std::numeric_limits<float>::max();
  70647. for (int i = 110; --i >= 0;)
  70648. {
  70649. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70650. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70651. const float distance = centre.getDistanceFrom (targetPoint);
  70652. if (distance < bestDistance)
  70653. {
  70654. bestProp = prop;
  70655. bestDistance = distance;
  70656. }
  70657. }
  70658. }
  70659. else if (type == quadraticToElement)
  70660. {
  70661. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70662. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope) };
  70663. float bestDistance = std::numeric_limits<float>::max();
  70664. for (int i = 110; --i >= 0;)
  70665. {
  70666. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70667. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70668. const float distance = centre.getDistanceFrom (targetPoint);
  70669. if (distance < bestDistance)
  70670. {
  70671. bestProp = prop;
  70672. bestDistance = distance;
  70673. }
  70674. }
  70675. }
  70676. else if (type == lineToElement)
  70677. {
  70678. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70679. const Line<float> line (rp1.resolve (scope), rp2.resolve (scope));
  70680. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70681. }
  70682. return bestProp;
  70683. }
  70684. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::Scope* scope, UndoManager* undoManager)
  70685. {
  70686. ValueTree newTree;
  70687. const Identifier type (state.getType());
  70688. if (type == cubicToElement)
  70689. {
  70690. float bestProp = findProportionAlongLine (targetPoint, scope);
  70691. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70692. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope), rp4.resolve (scope) };
  70693. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70694. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70695. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70696. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70697. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70698. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70699. setControlPoint (0, mid1, undoManager);
  70700. setControlPoint (1, newCp1, undoManager);
  70701. setControlPoint (2, newCentre, undoManager);
  70702. setModeOfEndPoint (roundedMode, undoManager);
  70703. Element newElement (newTree = ValueTree (cubicToElement));
  70704. newElement.setControlPoint (0, newCp2, 0);
  70705. newElement.setControlPoint (1, mid3, 0);
  70706. newElement.setControlPoint (2, rp4, 0);
  70707. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70708. }
  70709. else if (type == quadraticToElement)
  70710. {
  70711. float bestProp = findProportionAlongLine (targetPoint, scope);
  70712. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70713. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope) };
  70714. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70715. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70716. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70717. setControlPoint (0, mid1, undoManager);
  70718. setControlPoint (1, newCentre, undoManager);
  70719. setModeOfEndPoint (roundedMode, undoManager);
  70720. Element newElement (newTree = ValueTree (quadraticToElement));
  70721. newElement.setControlPoint (0, mid2, 0);
  70722. newElement.setControlPoint (1, rp3, 0);
  70723. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70724. }
  70725. else if (type == lineToElement)
  70726. {
  70727. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70728. const Line<float> line (rp1.resolve (scope), rp2.resolve (scope));
  70729. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70730. setControlPoint (0, newPoint, undoManager);
  70731. Element newElement (newTree = ValueTree (lineToElement));
  70732. newElement.setControlPoint (0, rp2, 0);
  70733. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70734. }
  70735. else if (type == closeSubPathElement)
  70736. {
  70737. }
  70738. return newTree;
  70739. }
  70740. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70741. {
  70742. state.getParent().removeChild (state, undoManager);
  70743. }
  70744. void DrawablePath::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70745. {
  70746. ValueTreeWrapper v (tree);
  70747. setComponentID (v.getID());
  70748. refreshFillTypes (v, builder.getImageProvider());
  70749. setStrokeType (v.getStrokeType());
  70750. RelativePointPath newRelativePath;
  70751. v.writeTo (newRelativePath);
  70752. setPath (newRelativePath);
  70753. }
  70754. const ValueTree DrawablePath::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70755. {
  70756. ValueTree tree (valueTreeType);
  70757. ValueTreeWrapper v (tree);
  70758. v.setID (getComponentID());
  70759. writeTo (v, imageProvider, 0);
  70760. if (relativePath != 0)
  70761. v.readFrom (*relativePath, 0);
  70762. else
  70763. v.readFrom (RelativePointPath (path), 0);
  70764. return tree;
  70765. }
  70766. END_JUCE_NAMESPACE
  70767. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70768. /*** Start of inlined file: juce_DrawableRectangle.cpp ***/
  70769. BEGIN_JUCE_NAMESPACE
  70770. DrawableRectangle::DrawableRectangle()
  70771. {
  70772. }
  70773. DrawableRectangle::DrawableRectangle (const DrawableRectangle& other)
  70774. : DrawableShape (other),
  70775. bounds (other.bounds),
  70776. cornerSize (other.cornerSize)
  70777. {
  70778. }
  70779. DrawableRectangle::~DrawableRectangle()
  70780. {
  70781. }
  70782. Drawable* DrawableRectangle::createCopy() const
  70783. {
  70784. return new DrawableRectangle (*this);
  70785. }
  70786. void DrawableRectangle::setRectangle (const RelativeParallelogram& newBounds)
  70787. {
  70788. if (bounds != newBounds)
  70789. {
  70790. bounds = newBounds;
  70791. rebuildPath();
  70792. }
  70793. }
  70794. void DrawableRectangle::setCornerSize (const RelativePoint& newSize)
  70795. {
  70796. if (cornerSize != newSize)
  70797. {
  70798. cornerSize = newSize;
  70799. rebuildPath();
  70800. }
  70801. }
  70802. void DrawableRectangle::rebuildPath()
  70803. {
  70804. if (bounds.isDynamic() || cornerSize.isDynamic())
  70805. {
  70806. Drawable::Positioner<DrawableRectangle>* const p = new Drawable::Positioner<DrawableRectangle> (*this);
  70807. setPositioner (p);
  70808. p->apply();
  70809. }
  70810. else
  70811. {
  70812. setPositioner (0);
  70813. recalculateCoordinates (0);
  70814. }
  70815. }
  70816. bool DrawableRectangle::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70817. {
  70818. bool ok = positioner.addPoint (bounds.topLeft);
  70819. ok = positioner.addPoint (bounds.topRight) && ok;
  70820. ok = positioner.addPoint (bounds.bottomLeft) && ok;
  70821. return positioner.addPoint (cornerSize) && ok;
  70822. }
  70823. void DrawableRectangle::recalculateCoordinates (Expression::Scope* scope)
  70824. {
  70825. Point<float> points[3];
  70826. bounds.resolveThreePoints (points, scope);
  70827. const float cornerSizeX = (float) cornerSize.x.resolve (scope);
  70828. const float cornerSizeY = (float) cornerSize.y.resolve (scope);
  70829. const float w = Line<float> (points[0], points[1]).getLength();
  70830. const float h = Line<float> (points[0], points[2]).getLength();
  70831. Path newPath;
  70832. if (cornerSizeX > 0 && cornerSizeY > 0)
  70833. newPath.addRoundedRectangle (0, 0, w, h, cornerSizeX, cornerSizeY);
  70834. else
  70835. newPath.addRectangle (0, 0, w, h);
  70836. newPath.applyTransform (AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70837. w, 0, points[1].getX(), points[1].getY(),
  70838. 0, h, points[2].getX(), points[2].getY()));
  70839. if (path != newPath)
  70840. {
  70841. path.swapWithPath (newPath);
  70842. pathChanged();
  70843. }
  70844. }
  70845. const Identifier DrawableRectangle::valueTreeType ("Rectangle");
  70846. const Identifier DrawableRectangle::ValueTreeWrapper::topLeft ("topLeft");
  70847. const Identifier DrawableRectangle::ValueTreeWrapper::topRight ("topRight");
  70848. const Identifier DrawableRectangle::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70849. const Identifier DrawableRectangle::ValueTreeWrapper::cornerSize ("cornerSize");
  70850. DrawableRectangle::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70851. : FillAndStrokeState (state_)
  70852. {
  70853. jassert (state.hasType (valueTreeType));
  70854. }
  70855. const RelativeParallelogram DrawableRectangle::ValueTreeWrapper::getRectangle() const
  70856. {
  70857. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70858. state.getProperty (topRight, "100, 0"),
  70859. state.getProperty (bottomLeft, "0, 100"));
  70860. }
  70861. void DrawableRectangle::ValueTreeWrapper::setRectangle (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70862. {
  70863. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70864. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70865. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70866. }
  70867. void DrawableRectangle::ValueTreeWrapper::setCornerSize (const RelativePoint& newSize, UndoManager* undoManager)
  70868. {
  70869. state.setProperty (cornerSize, newSize.toString(), undoManager);
  70870. }
  70871. const RelativePoint DrawableRectangle::ValueTreeWrapper::getCornerSize() const
  70872. {
  70873. return RelativePoint (state [cornerSize]);
  70874. }
  70875. Value DrawableRectangle::ValueTreeWrapper::getCornerSizeValue (UndoManager* undoManager) const
  70876. {
  70877. return state.getPropertyAsValue (cornerSize, undoManager);
  70878. }
  70879. void DrawableRectangle::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70880. {
  70881. ValueTreeWrapper v (tree);
  70882. setComponentID (v.getID());
  70883. refreshFillTypes (v, builder.getImageProvider());
  70884. setStrokeType (v.getStrokeType());
  70885. setRectangle (v.getRectangle());
  70886. setCornerSize (v.getCornerSize());
  70887. }
  70888. const ValueTree DrawableRectangle::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70889. {
  70890. ValueTree tree (valueTreeType);
  70891. ValueTreeWrapper v (tree);
  70892. v.setID (getComponentID());
  70893. writeTo (v, imageProvider, 0);
  70894. v.setRectangle (bounds, 0);
  70895. v.setCornerSize (cornerSize, 0);
  70896. return tree;
  70897. }
  70898. END_JUCE_NAMESPACE
  70899. /*** End of inlined file: juce_DrawableRectangle.cpp ***/
  70900. /*** Start of inlined file: juce_DrawableText.cpp ***/
  70901. BEGIN_JUCE_NAMESPACE
  70902. DrawableText::DrawableText()
  70903. : colour (Colours::black),
  70904. justification (Justification::centredLeft)
  70905. {
  70906. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  70907. RelativePoint (50.0f, 0.0f),
  70908. RelativePoint (0.0f, 20.0f)));
  70909. setFont (Font (15.0f), true);
  70910. }
  70911. DrawableText::DrawableText (const DrawableText& other)
  70912. : bounds (other.bounds),
  70913. fontSizeControlPoint (other.fontSizeControlPoint),
  70914. font (other.font),
  70915. text (other.text),
  70916. colour (other.colour),
  70917. justification (other.justification)
  70918. {
  70919. }
  70920. DrawableText::~DrawableText()
  70921. {
  70922. }
  70923. void DrawableText::setText (const String& newText)
  70924. {
  70925. if (text != newText)
  70926. {
  70927. text = newText;
  70928. refreshBounds();
  70929. }
  70930. }
  70931. void DrawableText::setColour (const Colour& newColour)
  70932. {
  70933. if (colour != newColour)
  70934. {
  70935. colour = newColour;
  70936. repaint();
  70937. }
  70938. }
  70939. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  70940. {
  70941. if (font != newFont)
  70942. {
  70943. font = newFont;
  70944. if (applySizeAndScale)
  70945. {
  70946. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (resolvedPoints,
  70947. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  70948. }
  70949. refreshBounds();
  70950. }
  70951. }
  70952. void DrawableText::setJustification (const Justification& newJustification)
  70953. {
  70954. justification = newJustification;
  70955. repaint();
  70956. }
  70957. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  70958. {
  70959. if (bounds != newBounds)
  70960. {
  70961. bounds = newBounds;
  70962. refreshBounds();
  70963. }
  70964. }
  70965. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  70966. {
  70967. if (fontSizeControlPoint != newPoint)
  70968. {
  70969. fontSizeControlPoint = newPoint;
  70970. refreshBounds();
  70971. }
  70972. }
  70973. void DrawableText::refreshBounds()
  70974. {
  70975. if (bounds.isDynamic() || fontSizeControlPoint.isDynamic())
  70976. {
  70977. Drawable::Positioner<DrawableText>* const p = new Drawable::Positioner<DrawableText> (*this);
  70978. setPositioner (p);
  70979. p->apply();
  70980. }
  70981. else
  70982. {
  70983. setPositioner (0);
  70984. recalculateCoordinates (0);
  70985. }
  70986. }
  70987. bool DrawableText::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70988. {
  70989. bool ok = positioner.addPoint (bounds.topLeft);
  70990. ok = positioner.addPoint (bounds.topRight) && ok;
  70991. ok = positioner.addPoint (bounds.bottomLeft) && ok;
  70992. return positioner.addPoint (fontSizeControlPoint) && ok;
  70993. }
  70994. void DrawableText::recalculateCoordinates (Expression::Scope* scope)
  70995. {
  70996. bounds.resolveThreePoints (resolvedPoints, scope);
  70997. const float w = Line<float> (resolvedPoints[0], resolvedPoints[1]).getLength();
  70998. const float h = Line<float> (resolvedPoints[0], resolvedPoints[2]).getLength();
  70999. const Point<float> fontCoords (RelativeParallelogram::getInternalCoordForPoint (resolvedPoints, fontSizeControlPoint.resolve (scope)));
  71000. const float fontHeight = jlimit (0.01f, jmax (0.01f, h), fontCoords.getY());
  71001. const float fontWidth = jlimit (0.01f, jmax (0.01f, w), fontCoords.getX());
  71002. scaledFont = font;
  71003. scaledFont.setHeight (fontHeight);
  71004. scaledFont.setHorizontalScale (fontWidth / fontHeight);
  71005. setBoundsToEnclose (getDrawableBounds());
  71006. repaint();
  71007. }
  71008. const AffineTransform DrawableText::getArrangementAndTransform (GlyphArrangement& glyphs) const
  71009. {
  71010. const float w = Line<float> (resolvedPoints[0], resolvedPoints[1]).getLength();
  71011. const float h = Line<float> (resolvedPoints[0], resolvedPoints[2]).getLength();
  71012. glyphs.addFittedText (scaledFont, text, 0, 0, w, h, justification, 0x100000);
  71013. return AffineTransform::fromTargetPoints (0, 0, resolvedPoints[0].getX(), resolvedPoints[0].getY(),
  71014. w, 0, resolvedPoints[1].getX(), resolvedPoints[1].getY(),
  71015. 0, h, resolvedPoints[2].getX(), resolvedPoints[2].getY());
  71016. }
  71017. void DrawableText::paint (Graphics& g)
  71018. {
  71019. transformContextToCorrectOrigin (g);
  71020. g.setColour (colour);
  71021. GlyphArrangement ga;
  71022. const AffineTransform transform (getArrangementAndTransform (ga));
  71023. ga.draw (g, transform);
  71024. }
  71025. const Rectangle<float> DrawableText::getDrawableBounds() const
  71026. {
  71027. return RelativeParallelogram::getBoundingBox (resolvedPoints);
  71028. }
  71029. Drawable* DrawableText::createCopy() const
  71030. {
  71031. return new DrawableText (*this);
  71032. }
  71033. const Identifier DrawableText::valueTreeType ("Text");
  71034. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  71035. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  71036. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  71037. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  71038. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  71039. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  71040. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  71041. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  71042. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  71043. : ValueTreeWrapperBase (state_)
  71044. {
  71045. jassert (state.hasType (valueTreeType));
  71046. }
  71047. const String DrawableText::ValueTreeWrapper::getText() const
  71048. {
  71049. return state [text].toString();
  71050. }
  71051. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  71052. {
  71053. state.setProperty (text, newText, undoManager);
  71054. }
  71055. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  71056. {
  71057. return state.getPropertyAsValue (text, undoManager);
  71058. }
  71059. const Colour DrawableText::ValueTreeWrapper::getColour() const
  71060. {
  71061. return Colour::fromString (state [colour].toString());
  71062. }
  71063. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  71064. {
  71065. state.setProperty (colour, newColour.toString(), undoManager);
  71066. }
  71067. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  71068. {
  71069. return Justification ((int) state [justification]);
  71070. }
  71071. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  71072. {
  71073. state.setProperty (justification, newJustification.getFlags(), undoManager);
  71074. }
  71075. const Font DrawableText::ValueTreeWrapper::getFont() const
  71076. {
  71077. return Font::fromString (state [font]);
  71078. }
  71079. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  71080. {
  71081. state.setProperty (font, newFont.toString(), undoManager);
  71082. }
  71083. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  71084. {
  71085. return state.getPropertyAsValue (font, undoManager);
  71086. }
  71087. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  71088. {
  71089. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  71090. }
  71091. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71092. {
  71093. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71094. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71095. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71096. }
  71097. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  71098. {
  71099. return state [fontSizeAnchor].toString();
  71100. }
  71101. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  71102. {
  71103. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  71104. }
  71105. void DrawableText::refreshFromValueTree (const ValueTree& tree, ComponentBuilder&)
  71106. {
  71107. ValueTreeWrapper v (tree);
  71108. setComponentID (v.getID());
  71109. const RelativeParallelogram newBounds (v.getBoundingBox());
  71110. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  71111. const Colour newColour (v.getColour());
  71112. const Justification newJustification (v.getJustification());
  71113. const String newText (v.getText());
  71114. const Font newFont (v.getFont());
  71115. if (text != newText || font != newFont || justification != newJustification
  71116. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  71117. {
  71118. setBoundingBox (newBounds);
  71119. setFontSizeControlPoint (newFontPoint);
  71120. setColour (newColour);
  71121. setFont (newFont, false);
  71122. setJustification (newJustification);
  71123. setText (newText);
  71124. }
  71125. }
  71126. const ValueTree DrawableText::createValueTree (ComponentBuilder::ImageProvider*) const
  71127. {
  71128. ValueTree tree (valueTreeType);
  71129. ValueTreeWrapper v (tree);
  71130. v.setID (getComponentID());
  71131. v.setText (text, 0);
  71132. v.setFont (font, 0);
  71133. v.setJustification (justification, 0);
  71134. v.setColour (colour, 0);
  71135. v.setBoundingBox (bounds, 0);
  71136. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  71137. return tree;
  71138. }
  71139. END_JUCE_NAMESPACE
  71140. /*** End of inlined file: juce_DrawableText.cpp ***/
  71141. /*** Start of inlined file: juce_SVGParser.cpp ***/
  71142. BEGIN_JUCE_NAMESPACE
  71143. class SVGState
  71144. {
  71145. public:
  71146. SVGState (const XmlElement* const topLevel)
  71147. : topLevelXml (topLevel),
  71148. elementX (0), elementY (0),
  71149. width (512), height (512),
  71150. viewBoxW (0), viewBoxH (0)
  71151. {
  71152. }
  71153. Drawable* parseSVGElement (const XmlElement& xml)
  71154. {
  71155. if (! xml.hasTagName ("svg"))
  71156. return 0;
  71157. DrawableComposite* const drawable = new DrawableComposite();
  71158. drawable->setName (xml.getStringAttribute ("id"));
  71159. SVGState newState (*this);
  71160. if (xml.hasAttribute ("transform"))
  71161. newState.addTransform (xml);
  71162. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  71163. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  71164. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71165. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71166. if (xml.hasAttribute ("viewBox"))
  71167. {
  71168. const String viewBoxAtt (xml.getStringAttribute ("viewBox"));
  71169. String::CharPointerType viewParams (viewBoxAtt.getCharPointer());
  71170. float vx, vy, vw, vh;
  71171. if (parseCoords (viewParams, vx, vy, true)
  71172. && parseCoords (viewParams, vw, vh, true)
  71173. && vw > 0
  71174. && vh > 0)
  71175. {
  71176. newState.viewBoxW = vw;
  71177. newState.viewBoxH = vh;
  71178. int placementFlags = 0;
  71179. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71180. if (aspect.containsIgnoreCase ("none"))
  71181. {
  71182. placementFlags = RectanglePlacement::stretchToFit;
  71183. }
  71184. else
  71185. {
  71186. if (aspect.containsIgnoreCase ("slice"))
  71187. placementFlags |= RectanglePlacement::fillDestination;
  71188. if (aspect.containsIgnoreCase ("xMin"))
  71189. placementFlags |= RectanglePlacement::xLeft;
  71190. else if (aspect.containsIgnoreCase ("xMax"))
  71191. placementFlags |= RectanglePlacement::xRight;
  71192. else
  71193. placementFlags |= RectanglePlacement::xMid;
  71194. if (aspect.containsIgnoreCase ("yMin"))
  71195. placementFlags |= RectanglePlacement::yTop;
  71196. else if (aspect.containsIgnoreCase ("yMax"))
  71197. placementFlags |= RectanglePlacement::yBottom;
  71198. else
  71199. placementFlags |= RectanglePlacement::yMid;
  71200. }
  71201. const RectanglePlacement placement (placementFlags);
  71202. newState.transform
  71203. = placement.getTransformToFit (Rectangle<float> (vx, vy, vw, vh),
  71204. Rectangle<float> (0.0f, 0.0f, newState.width, newState.height))
  71205. .followedBy (newState.transform);
  71206. }
  71207. }
  71208. else
  71209. {
  71210. if (viewBoxW == 0)
  71211. newState.viewBoxW = newState.width;
  71212. if (viewBoxH == 0)
  71213. newState.viewBoxH = newState.height;
  71214. }
  71215. newState.parseSubElements (xml, drawable);
  71216. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71217. return drawable;
  71218. }
  71219. private:
  71220. const XmlElement* const topLevelXml;
  71221. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71222. AffineTransform transform;
  71223. String cssStyleText;
  71224. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71225. {
  71226. forEachXmlChildElement (xml, e)
  71227. {
  71228. Drawable* d = 0;
  71229. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71230. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71231. else if (e->hasTagName ("path")) d = parsePath (*e);
  71232. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71233. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71234. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71235. else if (e->hasTagName ("line")) d = parseLine (*e);
  71236. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71237. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71238. else if (e->hasTagName ("text")) d = parseText (*e);
  71239. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71240. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71241. parentDrawable->addAndMakeVisible (d);
  71242. }
  71243. }
  71244. DrawableComposite* parseSwitch (const XmlElement& xml)
  71245. {
  71246. const XmlElement* const group = xml.getChildByName ("g");
  71247. if (group != 0)
  71248. return parseGroupElement (*group);
  71249. return 0;
  71250. }
  71251. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71252. {
  71253. DrawableComposite* const drawable = new DrawableComposite();
  71254. drawable->setName (xml.getStringAttribute ("id"));
  71255. if (xml.hasAttribute ("transform"))
  71256. {
  71257. SVGState newState (*this);
  71258. newState.addTransform (xml);
  71259. newState.parseSubElements (xml, drawable);
  71260. }
  71261. else
  71262. {
  71263. parseSubElements (xml, drawable);
  71264. }
  71265. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71266. return drawable;
  71267. }
  71268. Drawable* parsePath (const XmlElement& xml) const
  71269. {
  71270. const String dAttribute (xml.getStringAttribute ("d").trimStart());
  71271. String::CharPointerType d (dAttribute.getCharPointer());
  71272. Path path;
  71273. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71274. path.setUsingNonZeroWinding (false);
  71275. float lastX = 0, lastY = 0;
  71276. float lastX2 = 0, lastY2 = 0;
  71277. juce_wchar lastCommandChar = 0;
  71278. bool isRelative = true;
  71279. bool carryOn = true;
  71280. const CharPointer_ASCII validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71281. while (! d.isEmpty())
  71282. {
  71283. float x, y, x2, y2, x3, y3;
  71284. if (validCommandChars.indexOf (*d) >= 0)
  71285. {
  71286. lastCommandChar = d.getAndAdvance();
  71287. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71288. }
  71289. switch (lastCommandChar)
  71290. {
  71291. case 'M':
  71292. case 'm':
  71293. case 'L':
  71294. case 'l':
  71295. if (parseCoords (d, x, y, false))
  71296. {
  71297. if (isRelative)
  71298. {
  71299. x += lastX;
  71300. y += lastY;
  71301. }
  71302. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71303. {
  71304. path.startNewSubPath (x, y);
  71305. lastCommandChar = 'l';
  71306. }
  71307. else
  71308. path.lineTo (x, y);
  71309. lastX2 = lastX;
  71310. lastY2 = lastY;
  71311. lastX = x;
  71312. lastY = y;
  71313. }
  71314. else
  71315. {
  71316. ++d;
  71317. }
  71318. break;
  71319. case 'H':
  71320. case 'h':
  71321. if (parseCoord (d, x, false, true))
  71322. {
  71323. if (isRelative)
  71324. x += lastX;
  71325. path.lineTo (x, lastY);
  71326. lastX2 = lastX;
  71327. lastX = x;
  71328. }
  71329. else
  71330. {
  71331. ++d;
  71332. }
  71333. break;
  71334. case 'V':
  71335. case 'v':
  71336. if (parseCoord (d, y, false, false))
  71337. {
  71338. if (isRelative)
  71339. y += lastY;
  71340. path.lineTo (lastX, y);
  71341. lastY2 = lastY;
  71342. lastY = y;
  71343. }
  71344. else
  71345. {
  71346. ++d;
  71347. }
  71348. break;
  71349. case 'C':
  71350. case 'c':
  71351. if (parseCoords (d, x, y, false)
  71352. && parseCoords (d, x2, y2, false)
  71353. && parseCoords (d, x3, y3, false))
  71354. {
  71355. if (isRelative)
  71356. {
  71357. x += lastX;
  71358. y += lastY;
  71359. x2 += lastX;
  71360. y2 += lastY;
  71361. x3 += lastX;
  71362. y3 += lastY;
  71363. }
  71364. path.cubicTo (x, y, x2, y2, x3, y3);
  71365. lastX2 = x2;
  71366. lastY2 = y2;
  71367. lastX = x3;
  71368. lastY = y3;
  71369. }
  71370. else
  71371. {
  71372. ++d;
  71373. }
  71374. break;
  71375. case 'S':
  71376. case 's':
  71377. if (parseCoords (d, x, y, false)
  71378. && parseCoords (d, x3, y3, false))
  71379. {
  71380. if (isRelative)
  71381. {
  71382. x += lastX;
  71383. y += lastY;
  71384. x3 += lastX;
  71385. y3 += lastY;
  71386. }
  71387. x2 = lastX + (lastX - lastX2);
  71388. y2 = lastY + (lastY - lastY2);
  71389. path.cubicTo (x2, y2, x, y, x3, y3);
  71390. lastX2 = x;
  71391. lastY2 = y;
  71392. lastX = x3;
  71393. lastY = y3;
  71394. }
  71395. else
  71396. {
  71397. ++d;
  71398. }
  71399. break;
  71400. case 'Q':
  71401. case 'q':
  71402. if (parseCoords (d, x, y, false)
  71403. && parseCoords (d, x2, y2, false))
  71404. {
  71405. if (isRelative)
  71406. {
  71407. x += lastX;
  71408. y += lastY;
  71409. x2 += lastX;
  71410. y2 += lastY;
  71411. }
  71412. path.quadraticTo (x, y, x2, y2);
  71413. lastX2 = x;
  71414. lastY2 = y;
  71415. lastX = x2;
  71416. lastY = y2;
  71417. }
  71418. else
  71419. {
  71420. ++d;
  71421. }
  71422. break;
  71423. case 'T':
  71424. case 't':
  71425. if (parseCoords (d, x, y, false))
  71426. {
  71427. if (isRelative)
  71428. {
  71429. x += lastX;
  71430. y += lastY;
  71431. }
  71432. x2 = lastX + (lastX - lastX2);
  71433. y2 = lastY + (lastY - lastY2);
  71434. path.quadraticTo (x2, y2, x, y);
  71435. lastX2 = x2;
  71436. lastY2 = y2;
  71437. lastX = x;
  71438. lastY = y;
  71439. }
  71440. else
  71441. {
  71442. ++d;
  71443. }
  71444. break;
  71445. case 'A':
  71446. case 'a':
  71447. if (parseCoords (d, x, y, false))
  71448. {
  71449. String num;
  71450. if (parseNextNumber (d, num, false))
  71451. {
  71452. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71453. if (parseNextNumber (d, num, false))
  71454. {
  71455. const bool largeArc = num.getIntValue() != 0;
  71456. if (parseNextNumber (d, num, false))
  71457. {
  71458. const bool sweep = num.getIntValue() != 0;
  71459. if (parseCoords (d, x2, y2, false))
  71460. {
  71461. if (isRelative)
  71462. {
  71463. x2 += lastX;
  71464. y2 += lastY;
  71465. }
  71466. if (lastX != x2 || lastY != y2)
  71467. {
  71468. double centreX, centreY, startAngle, deltaAngle;
  71469. double rx = x, ry = y;
  71470. endpointToCentreParameters (lastX, lastY, x2, y2,
  71471. angle, largeArc, sweep,
  71472. rx, ry, centreX, centreY,
  71473. startAngle, deltaAngle);
  71474. path.addCentredArc ((float) centreX, (float) centreY,
  71475. (float) rx, (float) ry,
  71476. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71477. false);
  71478. path.lineTo (x2, y2);
  71479. }
  71480. lastX2 = lastX;
  71481. lastY2 = lastY;
  71482. lastX = x2;
  71483. lastY = y2;
  71484. }
  71485. }
  71486. }
  71487. }
  71488. }
  71489. else
  71490. {
  71491. ++d;
  71492. }
  71493. break;
  71494. case 'Z':
  71495. case 'z':
  71496. path.closeSubPath();
  71497. d = d.findEndOfWhitespace();
  71498. break;
  71499. default:
  71500. carryOn = false;
  71501. break;
  71502. }
  71503. if (! carryOn)
  71504. break;
  71505. }
  71506. return parseShape (xml, path);
  71507. }
  71508. Drawable* parseRect (const XmlElement& xml) const
  71509. {
  71510. Path rect;
  71511. const bool hasRX = xml.hasAttribute ("rx");
  71512. const bool hasRY = xml.hasAttribute ("ry");
  71513. if (hasRX || hasRY)
  71514. {
  71515. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71516. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71517. if (! hasRX)
  71518. rx = ry;
  71519. else if (! hasRY)
  71520. ry = rx;
  71521. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71522. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71523. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71524. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71525. rx, ry);
  71526. }
  71527. else
  71528. {
  71529. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71530. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71531. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71532. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  71533. }
  71534. return parseShape (xml, rect);
  71535. }
  71536. Drawable* parseCircle (const XmlElement& xml) const
  71537. {
  71538. Path circle;
  71539. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71540. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71541. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  71542. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  71543. return parseShape (xml, circle);
  71544. }
  71545. Drawable* parseEllipse (const XmlElement& xml) const
  71546. {
  71547. Path ellipse;
  71548. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71549. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71550. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71551. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71552. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  71553. return parseShape (xml, ellipse);
  71554. }
  71555. Drawable* parseLine (const XmlElement& xml) const
  71556. {
  71557. Path line;
  71558. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  71559. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  71560. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  71561. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  71562. line.startNewSubPath (x1, y1);
  71563. line.lineTo (x2, y2);
  71564. return parseShape (xml, line);
  71565. }
  71566. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  71567. {
  71568. const String pointsAtt (xml.getStringAttribute ("points"));
  71569. String::CharPointerType points (pointsAtt.getCharPointer());
  71570. Path path;
  71571. float x, y;
  71572. if (parseCoords (points, x, y, true))
  71573. {
  71574. float firstX = x;
  71575. float firstY = y;
  71576. float lastX = 0, lastY = 0;
  71577. path.startNewSubPath (x, y);
  71578. while (parseCoords (points, x, y, true))
  71579. {
  71580. lastX = x;
  71581. lastY = y;
  71582. path.lineTo (x, y);
  71583. }
  71584. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  71585. path.closeSubPath();
  71586. }
  71587. return parseShape (xml, path);
  71588. }
  71589. Drawable* parseShape (const XmlElement& xml, Path& path,
  71590. const bool shouldParseTransform = true) const
  71591. {
  71592. if (shouldParseTransform && xml.hasAttribute ("transform"))
  71593. {
  71594. SVGState newState (*this);
  71595. newState.addTransform (xml);
  71596. return newState.parseShape (xml, path, false);
  71597. }
  71598. DrawablePath* dp = new DrawablePath();
  71599. dp->setName (xml.getStringAttribute ("id"));
  71600. dp->setFill (Colours::transparentBlack);
  71601. path.applyTransform (transform);
  71602. dp->setPath (path);
  71603. Path::Iterator iter (path);
  71604. bool containsClosedSubPath = false;
  71605. while (iter.next())
  71606. {
  71607. if (iter.elementType == Path::Iterator::closePath)
  71608. {
  71609. containsClosedSubPath = true;
  71610. break;
  71611. }
  71612. }
  71613. dp->setFill (getPathFillType (path,
  71614. getStyleAttribute (&xml, "fill"),
  71615. getStyleAttribute (&xml, "fill-opacity"),
  71616. getStyleAttribute (&xml, "opacity"),
  71617. containsClosedSubPath ? Colours::black
  71618. : Colours::transparentBlack));
  71619. const String strokeType (getStyleAttribute (&xml, "stroke"));
  71620. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  71621. {
  71622. dp->setStrokeFill (getPathFillType (path, strokeType,
  71623. getStyleAttribute (&xml, "stroke-opacity"),
  71624. getStyleAttribute (&xml, "opacity"),
  71625. Colours::transparentBlack));
  71626. dp->setStrokeType (getStrokeFor (&xml));
  71627. }
  71628. return dp;
  71629. }
  71630. const XmlElement* findLinkedElement (const XmlElement* e) const
  71631. {
  71632. const String id (e->getStringAttribute ("xlink:href"));
  71633. if (! id.startsWithChar ('#'))
  71634. return 0;
  71635. return findElementForId (topLevelXml, id.substring (1));
  71636. }
  71637. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  71638. {
  71639. if (fillXml == 0)
  71640. return;
  71641. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71642. {
  71643. int index = 0;
  71644. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71645. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71646. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71647. double offset = e->getDoubleAttribute ("offset");
  71648. if (e->getStringAttribute ("offset").containsChar ('%'))
  71649. offset *= 0.01;
  71650. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71651. }
  71652. }
  71653. const FillType getPathFillType (const Path& path,
  71654. const String& fill,
  71655. const String& fillOpacity,
  71656. const String& overallOpacity,
  71657. const Colour& defaultColour) const
  71658. {
  71659. float opacity = 1.0f;
  71660. if (overallOpacity.isNotEmpty())
  71661. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71662. if (fillOpacity.isNotEmpty())
  71663. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71664. if (fill.startsWithIgnoreCase ("url"))
  71665. {
  71666. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71667. .upToLastOccurrenceOf (")", false, false).trim());
  71668. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71669. if (fillXml != 0
  71670. && (fillXml->hasTagName ("linearGradient")
  71671. || fillXml->hasTagName ("radialGradient")))
  71672. {
  71673. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71674. ColourGradient gradient;
  71675. addGradientStopsIn (gradient, inheritedFrom);
  71676. addGradientStopsIn (gradient, fillXml);
  71677. if (gradient.getNumColours() > 0)
  71678. {
  71679. gradient.addColour (0.0, gradient.getColour (0));
  71680. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71681. }
  71682. else
  71683. {
  71684. gradient.addColour (0.0, Colours::black);
  71685. gradient.addColour (1.0, Colours::black);
  71686. }
  71687. if (overallOpacity.isNotEmpty())
  71688. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71689. jassert (gradient.getNumColours() > 0);
  71690. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71691. float gradientWidth = viewBoxW;
  71692. float gradientHeight = viewBoxH;
  71693. float dx = 0.0f;
  71694. float dy = 0.0f;
  71695. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71696. if (! userSpace)
  71697. {
  71698. const Rectangle<float> bounds (path.getBounds());
  71699. dx = bounds.getX();
  71700. dy = bounds.getY();
  71701. gradientWidth = bounds.getWidth();
  71702. gradientHeight = bounds.getHeight();
  71703. }
  71704. if (gradient.isRadial)
  71705. {
  71706. if (userSpace)
  71707. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71708. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71709. else
  71710. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  71711. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  71712. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71713. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71714. //xxx (the fx, fy focal point isn't handled properly here..)
  71715. }
  71716. else
  71717. {
  71718. if (userSpace)
  71719. {
  71720. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71721. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71722. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71723. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71724. }
  71725. else
  71726. {
  71727. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  71728. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  71729. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  71730. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  71731. }
  71732. if (gradient.point1 == gradient.point2)
  71733. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71734. }
  71735. FillType type (gradient);
  71736. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71737. .followedBy (transform);
  71738. return type;
  71739. }
  71740. }
  71741. if (fill.equalsIgnoreCase ("none"))
  71742. return Colours::transparentBlack;
  71743. int i = 0;
  71744. const Colour colour (parseColour (fill, i, defaultColour));
  71745. return colour.withMultipliedAlpha (opacity);
  71746. }
  71747. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71748. {
  71749. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71750. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71751. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71752. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71753. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71754. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71755. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71756. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71757. if (join.equalsIgnoreCase ("round"))
  71758. joinStyle = PathStrokeType::curved;
  71759. else if (join.equalsIgnoreCase ("bevel"))
  71760. joinStyle = PathStrokeType::beveled;
  71761. if (cap.equalsIgnoreCase ("round"))
  71762. capStyle = PathStrokeType::rounded;
  71763. else if (cap.equalsIgnoreCase ("square"))
  71764. capStyle = PathStrokeType::square;
  71765. float ox = 0.0f, oy = 0.0f;
  71766. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71767. transform.transformPoints (ox, oy, x, y);
  71768. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypot (x - ox, y - oy) : 1.0f,
  71769. joinStyle, capStyle);
  71770. }
  71771. Drawable* parseText (const XmlElement& xml)
  71772. {
  71773. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71774. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71775. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71776. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71777. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71778. //xxx not done text yet!
  71779. forEachXmlChildElement (xml, e)
  71780. {
  71781. if (e->isTextElement())
  71782. {
  71783. const String text (e->getText());
  71784. Path path;
  71785. Drawable* s = parseShape (*e, path);
  71786. delete s; // xxx not finished!
  71787. }
  71788. else if (e->hasTagName ("tspan"))
  71789. {
  71790. Drawable* s = parseText (*e);
  71791. delete s; // xxx not finished!
  71792. }
  71793. }
  71794. return 0;
  71795. }
  71796. void addTransform (const XmlElement& xml)
  71797. {
  71798. transform = parseTransform (xml.getStringAttribute ("transform"))
  71799. .followedBy (transform);
  71800. }
  71801. bool parseCoord (String::CharPointerType& s, float& value, const bool allowUnits, const bool isX) const
  71802. {
  71803. String number;
  71804. if (! parseNextNumber (s, number, allowUnits))
  71805. {
  71806. value = 0;
  71807. return false;
  71808. }
  71809. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71810. return true;
  71811. }
  71812. bool parseCoords (String::CharPointerType& s, float& x, float& y, const bool allowUnits) const
  71813. {
  71814. return parseCoord (s, x, allowUnits, true)
  71815. && parseCoord (s, y, allowUnits, false);
  71816. }
  71817. float getCoordLength (const String& s, const float sizeForProportions) const
  71818. {
  71819. float n = s.getFloatValue();
  71820. const int len = s.length();
  71821. if (len > 2)
  71822. {
  71823. const float dpi = 96.0f;
  71824. const juce_wchar n1 = s [len - 2];
  71825. const juce_wchar n2 = s [len - 1];
  71826. if (n1 == 'i' && n2 == 'n')
  71827. n *= dpi;
  71828. else if (n1 == 'm' && n2 == 'm')
  71829. n *= dpi / 25.4f;
  71830. else if (n1 == 'c' && n2 == 'm')
  71831. n *= dpi / 2.54f;
  71832. else if (n1 == 'p' && n2 == 'c')
  71833. n *= 15.0f;
  71834. else if (n2 == '%')
  71835. n *= 0.01f * sizeForProportions;
  71836. }
  71837. return n;
  71838. }
  71839. void getCoordList (Array <float>& coords, const String& list,
  71840. const bool allowUnits, const bool isX) const
  71841. {
  71842. String::CharPointerType text (list.getCharPointer());
  71843. float value;
  71844. while (parseCoord (text, value, allowUnits, isX))
  71845. coords.add (value);
  71846. }
  71847. void parseCSSStyle (const XmlElement& xml)
  71848. {
  71849. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  71850. }
  71851. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  71852. const String& defaultValue = String::empty) const
  71853. {
  71854. if (xml->hasAttribute (attributeName))
  71855. return xml->getStringAttribute (attributeName, defaultValue);
  71856. const String styleAtt (xml->getStringAttribute ("style"));
  71857. if (styleAtt.isNotEmpty())
  71858. {
  71859. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  71860. if (value.isNotEmpty())
  71861. return value;
  71862. }
  71863. else if (xml->hasAttribute ("class"))
  71864. {
  71865. const String className ("." + xml->getStringAttribute ("class"));
  71866. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  71867. if (index < 0)
  71868. index = cssStyleText.indexOfIgnoreCase (className + "{");
  71869. if (index >= 0)
  71870. {
  71871. const int openBracket = cssStyleText.indexOfChar (index, '{');
  71872. if (openBracket > index)
  71873. {
  71874. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  71875. if (closeBracket > openBracket)
  71876. {
  71877. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  71878. if (value.isNotEmpty())
  71879. return value;
  71880. }
  71881. }
  71882. }
  71883. }
  71884. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71885. if (xml != 0)
  71886. return getStyleAttribute (xml, attributeName, defaultValue);
  71887. return defaultValue;
  71888. }
  71889. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  71890. {
  71891. if (xml->hasAttribute (attributeName))
  71892. return xml->getStringAttribute (attributeName);
  71893. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71894. if (xml != 0)
  71895. return getInheritedAttribute (xml, attributeName);
  71896. return String::empty;
  71897. }
  71898. static bool isIdentifierChar (const juce_wchar c)
  71899. {
  71900. return CharacterFunctions::isLetter (c) || c == '-';
  71901. }
  71902. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  71903. {
  71904. int i = 0;
  71905. for (;;)
  71906. {
  71907. i = list.indexOf (i, attributeName);
  71908. if (i < 0)
  71909. break;
  71910. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  71911. && ! isIdentifierChar (list [i + attributeName.length()]))
  71912. {
  71913. i = list.indexOfChar (i, ':');
  71914. if (i < 0)
  71915. break;
  71916. int end = list.indexOfChar (i, ';');
  71917. if (end < 0)
  71918. end = 0x7ffff;
  71919. return list.substring (i + 1, end).trim();
  71920. }
  71921. ++i;
  71922. }
  71923. return defaultValue;
  71924. }
  71925. static bool parseNextNumber (String::CharPointerType& s, String& value, const bool allowUnits)
  71926. {
  71927. while (s.isWhitespace() || *s == ',')
  71928. ++s;
  71929. String::CharPointerType start (s);
  71930. int numChars = 0;
  71931. if (s.isDigit() || *s == '.' || *s == '-')
  71932. {
  71933. ++numChars;
  71934. ++s;
  71935. }
  71936. while (s.isDigit() || *s == '.')
  71937. {
  71938. ++numChars;
  71939. ++s;
  71940. }
  71941. if ((*s == 'e' || *s == 'E')
  71942. && ((s + 1).isDigit() || s[1] == '-' || s[1] == '+'))
  71943. {
  71944. s += 2;
  71945. numChars += 2;
  71946. while (s.isDigit())
  71947. {
  71948. ++numChars;
  71949. ++s;
  71950. }
  71951. }
  71952. if (allowUnits)
  71953. {
  71954. while (s.isLetter())
  71955. {
  71956. ++numChars;
  71957. ++s;
  71958. }
  71959. }
  71960. if (numChars == 0)
  71961. return false;
  71962. value = String (start, numChars);
  71963. while (s.isWhitespace() || *s == ',')
  71964. ++s;
  71965. return true;
  71966. }
  71967. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  71968. {
  71969. if (s [index] == '#')
  71970. {
  71971. uint32 hex [6];
  71972. zeromem (hex, sizeof (hex));
  71973. int numChars = 0;
  71974. for (int i = 6; --i >= 0;)
  71975. {
  71976. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  71977. if (hexValue >= 0)
  71978. hex [numChars++] = hexValue;
  71979. else
  71980. break;
  71981. }
  71982. if (numChars <= 3)
  71983. return Colour ((uint8) (hex [0] * 0x11),
  71984. (uint8) (hex [1] * 0x11),
  71985. (uint8) (hex [2] * 0x11));
  71986. else
  71987. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  71988. (uint8) ((hex [2] << 4) + hex [3]),
  71989. (uint8) ((hex [4] << 4) + hex [5]));
  71990. }
  71991. else if (s [index] == 'r'
  71992. && s [index + 1] == 'g'
  71993. && s [index + 2] == 'b')
  71994. {
  71995. const int openBracket = s.indexOfChar (index, '(');
  71996. const int closeBracket = s.indexOfChar (openBracket, ')');
  71997. if (openBracket >= 3 && closeBracket > openBracket)
  71998. {
  71999. index = closeBracket;
  72000. StringArray tokens;
  72001. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  72002. tokens.trim();
  72003. tokens.removeEmptyStrings();
  72004. if (tokens[0].containsChar ('%'))
  72005. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  72006. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  72007. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  72008. else
  72009. return Colour ((uint8) tokens[0].getIntValue(),
  72010. (uint8) tokens[1].getIntValue(),
  72011. (uint8) tokens[2].getIntValue());
  72012. }
  72013. }
  72014. return Colours::findColourForName (s, defaultColour);
  72015. }
  72016. static const AffineTransform parseTransform (String t)
  72017. {
  72018. AffineTransform result;
  72019. while (t.isNotEmpty())
  72020. {
  72021. StringArray tokens;
  72022. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  72023. .upToFirstOccurrenceOf (")", false, false),
  72024. ", ", String::empty);
  72025. tokens.removeEmptyStrings (true);
  72026. float numbers [6];
  72027. for (int i = 0; i < 6; ++i)
  72028. numbers[i] = tokens[i].getFloatValue();
  72029. AffineTransform trans;
  72030. if (t.startsWithIgnoreCase ("matrix"))
  72031. {
  72032. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  72033. numbers[1], numbers[3], numbers[5]);
  72034. }
  72035. else if (t.startsWithIgnoreCase ("translate"))
  72036. {
  72037. jassert (tokens.size() == 2);
  72038. trans = AffineTransform::translation (numbers[0], numbers[1]);
  72039. }
  72040. else if (t.startsWithIgnoreCase ("scale"))
  72041. {
  72042. if (tokens.size() == 1)
  72043. trans = AffineTransform::scale (numbers[0], numbers[0]);
  72044. else
  72045. trans = AffineTransform::scale (numbers[0], numbers[1]);
  72046. }
  72047. else if (t.startsWithIgnoreCase ("rotate"))
  72048. {
  72049. if (tokens.size() != 3)
  72050. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  72051. else
  72052. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  72053. numbers[1], numbers[2]);
  72054. }
  72055. else if (t.startsWithIgnoreCase ("skewX"))
  72056. {
  72057. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  72058. 0.0f, 1.0f, 0.0f);
  72059. }
  72060. else if (t.startsWithIgnoreCase ("skewY"))
  72061. {
  72062. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  72063. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  72064. }
  72065. result = trans.followedBy (result);
  72066. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  72067. }
  72068. return result;
  72069. }
  72070. static void endpointToCentreParameters (const double x1, const double y1,
  72071. const double x2, const double y2,
  72072. const double angle,
  72073. const bool largeArc, const bool sweep,
  72074. double& rx, double& ry,
  72075. double& centreX, double& centreY,
  72076. double& startAngle, double& deltaAngle)
  72077. {
  72078. const double midX = (x1 - x2) * 0.5;
  72079. const double midY = (y1 - y2) * 0.5;
  72080. const double cosAngle = cos (angle);
  72081. const double sinAngle = sin (angle);
  72082. const double xp = cosAngle * midX + sinAngle * midY;
  72083. const double yp = cosAngle * midY - sinAngle * midX;
  72084. const double xp2 = xp * xp;
  72085. const double yp2 = yp * yp;
  72086. double rx2 = rx * rx;
  72087. double ry2 = ry * ry;
  72088. const double s = (xp2 / rx2) + (yp2 / ry2);
  72089. double c;
  72090. if (s <= 1.0)
  72091. {
  72092. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  72093. / (( rx2 * yp2) + (ry2 * xp2))));
  72094. if (largeArc == sweep)
  72095. c = -c;
  72096. }
  72097. else
  72098. {
  72099. const double s2 = std::sqrt (s);
  72100. rx *= s2;
  72101. ry *= s2;
  72102. rx2 = rx * rx;
  72103. ry2 = ry * ry;
  72104. c = 0;
  72105. }
  72106. const double cpx = ((rx * yp) / ry) * c;
  72107. const double cpy = ((-ry * xp) / rx) * c;
  72108. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  72109. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  72110. const double ux = (xp - cpx) / rx;
  72111. const double uy = (yp - cpy) / ry;
  72112. const double vx = (-xp - cpx) / rx;
  72113. const double vy = (-yp - cpy) / ry;
  72114. const double length = juce_hypot (ux, uy);
  72115. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  72116. if (uy < 0)
  72117. startAngle = -startAngle;
  72118. startAngle += double_Pi * 0.5;
  72119. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  72120. / (length * juce_hypot (vx, vy))));
  72121. if ((ux * vy) - (uy * vx) < 0)
  72122. deltaAngle = -deltaAngle;
  72123. if (sweep)
  72124. {
  72125. if (deltaAngle < 0)
  72126. deltaAngle += double_Pi * 2.0;
  72127. }
  72128. else
  72129. {
  72130. if (deltaAngle > 0)
  72131. deltaAngle -= double_Pi * 2.0;
  72132. }
  72133. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  72134. }
  72135. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  72136. {
  72137. forEachXmlChildElement (*parent, e)
  72138. {
  72139. if (e->compareAttribute ("id", id))
  72140. return e;
  72141. const XmlElement* const found = findElementForId (e, id);
  72142. if (found != 0)
  72143. return found;
  72144. }
  72145. return 0;
  72146. }
  72147. SVGState& operator= (const SVGState&);
  72148. };
  72149. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  72150. {
  72151. SVGState state (&svgDocument);
  72152. return state.parseSVGElement (svgDocument);
  72153. }
  72154. END_JUCE_NAMESPACE
  72155. /*** End of inlined file: juce_SVGParser.cpp ***/
  72156. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  72157. BEGIN_JUCE_NAMESPACE
  72158. #if JUCE_MSVC && JUCE_DEBUG
  72159. #pragma optimize ("t", on)
  72160. #endif
  72161. DropShadowEffect::DropShadowEffect()
  72162. : offsetX (0),
  72163. offsetY (0),
  72164. radius (4),
  72165. opacity (0.6f)
  72166. {
  72167. }
  72168. DropShadowEffect::~DropShadowEffect()
  72169. {
  72170. }
  72171. void DropShadowEffect::setShadowProperties (const float newRadius,
  72172. const float newOpacity,
  72173. const int newShadowOffsetX,
  72174. const int newShadowOffsetY)
  72175. {
  72176. radius = jmax (1.1f, newRadius);
  72177. offsetX = newShadowOffsetX;
  72178. offsetY = newShadowOffsetY;
  72179. opacity = newOpacity;
  72180. }
  72181. void DropShadowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72182. {
  72183. const int w = image.getWidth();
  72184. const int h = image.getHeight();
  72185. Image shadowImage (Image::SingleChannel, w, h, false);
  72186. const Image::BitmapData srcData (image, false);
  72187. const Image::BitmapData destData (shadowImage, true);
  72188. const int filter = roundToInt (63.0f / radius);
  72189. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72190. for (int x = w; --x >= 0;)
  72191. {
  72192. int shadowAlpha = 0;
  72193. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72194. uint8* shadowPix = destData.data + x;
  72195. for (int y = h; --y >= 0;)
  72196. {
  72197. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72198. *shadowPix = (uint8) shadowAlpha;
  72199. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  72200. shadowPix += destData.lineStride;
  72201. }
  72202. }
  72203. for (int y = h; --y >= 0;)
  72204. {
  72205. int shadowAlpha = 0;
  72206. uint8* shadowPix = destData.getLinePointer (y);
  72207. for (int x = w; --x >= 0;)
  72208. {
  72209. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72210. *shadowPix++ = (uint8) shadowAlpha;
  72211. }
  72212. }
  72213. g.setColour (Colours::black.withAlpha (opacity * alpha));
  72214. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72215. g.setOpacity (alpha);
  72216. g.drawImageAt (image, 0, 0);
  72217. }
  72218. #if JUCE_MSVC && JUCE_DEBUG
  72219. #pragma optimize ("", on) // resets optimisations to the project defaults
  72220. #endif
  72221. END_JUCE_NAMESPACE
  72222. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72223. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72224. BEGIN_JUCE_NAMESPACE
  72225. GlowEffect::GlowEffect()
  72226. : radius (2.0f),
  72227. colour (Colours::white)
  72228. {
  72229. }
  72230. GlowEffect::~GlowEffect()
  72231. {
  72232. }
  72233. void GlowEffect::setGlowProperties (const float newRadius,
  72234. const Colour& newColour)
  72235. {
  72236. radius = newRadius;
  72237. colour = newColour;
  72238. }
  72239. void GlowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72240. {
  72241. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72242. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72243. blurKernel.createGaussianBlur (radius);
  72244. blurKernel.rescaleAllValues (radius);
  72245. blurKernel.applyToImage (temp, image, image.getBounds());
  72246. g.setColour (colour.withMultipliedAlpha (alpha));
  72247. g.drawImageAt (temp, 0, 0, true);
  72248. g.setOpacity (alpha);
  72249. g.drawImageAt (image, 0, 0, false);
  72250. }
  72251. END_JUCE_NAMESPACE
  72252. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72253. /*** Start of inlined file: juce_Font.cpp ***/
  72254. BEGIN_JUCE_NAMESPACE
  72255. namespace FontValues
  72256. {
  72257. float limitFontHeight (const float height) throw()
  72258. {
  72259. return jlimit (0.1f, 10000.0f, height);
  72260. }
  72261. const float defaultFontHeight = 14.0f;
  72262. String fallbackFont;
  72263. }
  72264. class TypefaceCache : public DeletedAtShutdown
  72265. {
  72266. public:
  72267. TypefaceCache()
  72268. : counter (0)
  72269. {
  72270. setSize (10);
  72271. }
  72272. ~TypefaceCache()
  72273. {
  72274. clearSingletonInstance();
  72275. }
  72276. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72277. void setSize (const int numToCache)
  72278. {
  72279. faces.clear();
  72280. faces.insertMultiple (-1, CachedFace(), numToCache);
  72281. }
  72282. const Typeface::Ptr findTypefaceFor (const Font& font)
  72283. {
  72284. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72285. const String faceName (font.getTypefaceName());
  72286. int i;
  72287. for (i = faces.size(); --i >= 0;)
  72288. {
  72289. CachedFace& face = faces.getReference(i);
  72290. if (face.flags == flags
  72291. && face.typefaceName == faceName
  72292. && face.typeface->isSuitableForFont (font))
  72293. {
  72294. face.lastUsageCount = ++counter;
  72295. return face.typeface;
  72296. }
  72297. }
  72298. int replaceIndex = 0;
  72299. int bestLastUsageCount = std::numeric_limits<int>::max();
  72300. for (i = faces.size(); --i >= 0;)
  72301. {
  72302. const int lu = faces.getReference(i).lastUsageCount;
  72303. if (bestLastUsageCount > lu)
  72304. {
  72305. bestLastUsageCount = lu;
  72306. replaceIndex = i;
  72307. }
  72308. }
  72309. CachedFace& face = faces.getReference (replaceIndex);
  72310. face.typefaceName = faceName;
  72311. face.flags = flags;
  72312. face.lastUsageCount = ++counter;
  72313. face.typeface = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72314. jassert (face.typeface != 0); // the look and feel must return a typeface!
  72315. if (defaultFace == 0 && font == Font())
  72316. defaultFace = face.typeface;
  72317. return face.typeface;
  72318. }
  72319. const Typeface::Ptr getDefaultTypeface() const throw()
  72320. {
  72321. return defaultFace;
  72322. }
  72323. private:
  72324. struct CachedFace
  72325. {
  72326. CachedFace() throw()
  72327. : lastUsageCount (0), flags (-1)
  72328. {
  72329. }
  72330. // Although it seems a bit wacky to store the name here, it's because it may be a
  72331. // placeholder rather than a real one, e.g. "<Sans-Serif>" vs the actual typeface name.
  72332. // Since the typeface itself doesn't know that it may have this alias, the name under
  72333. // which it was fetched needs to be stored separately.
  72334. String typefaceName;
  72335. int lastUsageCount, flags;
  72336. Typeface::Ptr typeface;
  72337. };
  72338. Array <CachedFace> faces;
  72339. Typeface::Ptr defaultFace;
  72340. int counter;
  72341. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypefaceCache);
  72342. };
  72343. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72344. void Typeface::setTypefaceCacheSize (int numFontsToCache)
  72345. {
  72346. TypefaceCache::getInstance()->setSize (numFontsToCache);
  72347. }
  72348. Font::SharedFontInternal::SharedFontInternal (const float height_, const int styleFlags_) throw()
  72349. : typefaceName (Font::getDefaultSansSerifFontName()),
  72350. height (height_),
  72351. horizontalScale (1.0f),
  72352. kerning (0),
  72353. ascent (0),
  72354. styleFlags (styleFlags_),
  72355. typeface (TypefaceCache::getInstance()->getDefaultTypeface())
  72356. {
  72357. }
  72358. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const int styleFlags_) throw()
  72359. : typefaceName (typefaceName_),
  72360. height (height_),
  72361. horizontalScale (1.0f),
  72362. kerning (0),
  72363. ascent (0),
  72364. styleFlags (styleFlags_),
  72365. typeface (0)
  72366. {
  72367. }
  72368. Font::SharedFontInternal::SharedFontInternal (const Typeface::Ptr& typeface_) throw()
  72369. : typefaceName (typeface_->getName()),
  72370. height (FontValues::defaultFontHeight),
  72371. horizontalScale (1.0f),
  72372. kerning (0),
  72373. ascent (0),
  72374. styleFlags (Font::plain),
  72375. typeface (typeface_)
  72376. {
  72377. }
  72378. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72379. : typefaceName (other.typefaceName),
  72380. height (other.height),
  72381. horizontalScale (other.horizontalScale),
  72382. kerning (other.kerning),
  72383. ascent (other.ascent),
  72384. styleFlags (other.styleFlags),
  72385. typeface (other.typeface)
  72386. {
  72387. }
  72388. bool Font::SharedFontInternal::operator== (const SharedFontInternal& other) const throw()
  72389. {
  72390. return height == other.height
  72391. && styleFlags == other.styleFlags
  72392. && horizontalScale == other.horizontalScale
  72393. && kerning == other.kerning
  72394. && typefaceName == other.typefaceName;
  72395. }
  72396. Font::Font()
  72397. : font (new SharedFontInternal (FontValues::defaultFontHeight, Font::plain))
  72398. {
  72399. }
  72400. Font::Font (const float fontHeight, const int styleFlags_)
  72401. : font (new SharedFontInternal (FontValues::limitFontHeight (fontHeight), styleFlags_))
  72402. {
  72403. }
  72404. Font::Font (const String& typefaceName_, const float fontHeight, const int styleFlags_)
  72405. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight), styleFlags_))
  72406. {
  72407. }
  72408. Font::Font (const Typeface::Ptr& typeface)
  72409. : font (new SharedFontInternal (typeface))
  72410. {
  72411. }
  72412. Font::Font (const Font& other) throw()
  72413. : font (other.font)
  72414. {
  72415. }
  72416. Font& Font::operator= (const Font& other) throw()
  72417. {
  72418. font = other.font;
  72419. return *this;
  72420. }
  72421. Font::~Font() throw()
  72422. {
  72423. }
  72424. bool Font::operator== (const Font& other) const throw()
  72425. {
  72426. return font == other.font
  72427. || *font == *other.font;
  72428. }
  72429. bool Font::operator!= (const Font& other) const throw()
  72430. {
  72431. return ! operator== (other);
  72432. }
  72433. void Font::dupeInternalIfShared()
  72434. {
  72435. if (font->getReferenceCount() > 1)
  72436. font = new SharedFontInternal (*font);
  72437. }
  72438. const String Font::getDefaultSansSerifFontName()
  72439. {
  72440. static const String name ("<Sans-Serif>");
  72441. return name;
  72442. }
  72443. const String Font::getDefaultSerifFontName()
  72444. {
  72445. static const String name ("<Serif>");
  72446. return name;
  72447. }
  72448. const String Font::getDefaultMonospacedFontName()
  72449. {
  72450. static const String name ("<Monospaced>");
  72451. return name;
  72452. }
  72453. void Font::setTypefaceName (const String& faceName)
  72454. {
  72455. if (faceName != font->typefaceName)
  72456. {
  72457. dupeInternalIfShared();
  72458. font->typefaceName = faceName;
  72459. font->typeface = 0;
  72460. font->ascent = 0;
  72461. }
  72462. }
  72463. const String Font::getFallbackFontName()
  72464. {
  72465. return FontValues::fallbackFont;
  72466. }
  72467. void Font::setFallbackFontName (const String& name)
  72468. {
  72469. FontValues::fallbackFont = name;
  72470. }
  72471. void Font::setHeight (float newHeight)
  72472. {
  72473. newHeight = FontValues::limitFontHeight (newHeight);
  72474. if (font->height != newHeight)
  72475. {
  72476. dupeInternalIfShared();
  72477. font->height = newHeight;
  72478. }
  72479. }
  72480. void Font::setHeightWithoutChangingWidth (float newHeight)
  72481. {
  72482. newHeight = FontValues::limitFontHeight (newHeight);
  72483. if (font->height != newHeight)
  72484. {
  72485. dupeInternalIfShared();
  72486. font->horizontalScale *= (font->height / newHeight);
  72487. font->height = newHeight;
  72488. }
  72489. }
  72490. void Font::setStyleFlags (const int newFlags)
  72491. {
  72492. if (font->styleFlags != newFlags)
  72493. {
  72494. dupeInternalIfShared();
  72495. font->styleFlags = newFlags;
  72496. font->typeface = 0;
  72497. font->ascent = 0;
  72498. }
  72499. }
  72500. void Font::setSizeAndStyle (float newHeight,
  72501. const int newStyleFlags,
  72502. const float newHorizontalScale,
  72503. const float newKerningAmount)
  72504. {
  72505. newHeight = FontValues::limitFontHeight (newHeight);
  72506. if (font->height != newHeight
  72507. || font->horizontalScale != newHorizontalScale
  72508. || font->kerning != newKerningAmount)
  72509. {
  72510. dupeInternalIfShared();
  72511. font->height = newHeight;
  72512. font->horizontalScale = newHorizontalScale;
  72513. font->kerning = newKerningAmount;
  72514. }
  72515. setStyleFlags (newStyleFlags);
  72516. }
  72517. void Font::setHorizontalScale (const float scaleFactor)
  72518. {
  72519. dupeInternalIfShared();
  72520. font->horizontalScale = scaleFactor;
  72521. }
  72522. void Font::setExtraKerningFactor (const float extraKerning)
  72523. {
  72524. dupeInternalIfShared();
  72525. font->kerning = extraKerning;
  72526. }
  72527. void Font::setBold (const bool shouldBeBold)
  72528. {
  72529. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  72530. : (font->styleFlags & ~bold));
  72531. }
  72532. const Font Font::boldened() const
  72533. {
  72534. Font f (*this);
  72535. f.setBold (true);
  72536. return f;
  72537. }
  72538. bool Font::isBold() const throw()
  72539. {
  72540. return (font->styleFlags & bold) != 0;
  72541. }
  72542. void Font::setItalic (const bool shouldBeItalic)
  72543. {
  72544. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  72545. : (font->styleFlags & ~italic));
  72546. }
  72547. const Font Font::italicised() const
  72548. {
  72549. Font f (*this);
  72550. f.setItalic (true);
  72551. return f;
  72552. }
  72553. bool Font::isItalic() const throw()
  72554. {
  72555. return (font->styleFlags & italic) != 0;
  72556. }
  72557. void Font::setUnderline (const bool shouldBeUnderlined)
  72558. {
  72559. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  72560. : (font->styleFlags & ~underlined));
  72561. }
  72562. bool Font::isUnderlined() const throw()
  72563. {
  72564. return (font->styleFlags & underlined) != 0;
  72565. }
  72566. float Font::getAscent() const
  72567. {
  72568. if (font->ascent == 0)
  72569. font->ascent = getTypeface()->getAscent();
  72570. return font->height * font->ascent;
  72571. }
  72572. float Font::getDescent() const
  72573. {
  72574. return font->height - getAscent();
  72575. }
  72576. int Font::getStringWidth (const String& text) const
  72577. {
  72578. return roundToInt (getStringWidthFloat (text));
  72579. }
  72580. float Font::getStringWidthFloat (const String& text) const
  72581. {
  72582. float w = getTypeface()->getStringWidth (text);
  72583. if (font->kerning != 0)
  72584. w += font->kerning * text.length();
  72585. return w * font->height * font->horizontalScale;
  72586. }
  72587. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const
  72588. {
  72589. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  72590. const float scale = font->height * font->horizontalScale;
  72591. const int num = xOffsets.size();
  72592. if (num > 0)
  72593. {
  72594. float* const x = &(xOffsets.getReference(0));
  72595. if (font->kerning != 0)
  72596. {
  72597. for (int i = 0; i < num; ++i)
  72598. x[i] = (x[i] + i * font->kerning) * scale;
  72599. }
  72600. else
  72601. {
  72602. for (int i = 0; i < num; ++i)
  72603. x[i] *= scale;
  72604. }
  72605. }
  72606. }
  72607. void Font::findFonts (Array<Font>& destArray)
  72608. {
  72609. const StringArray names (findAllTypefaceNames());
  72610. for (int i = 0; i < names.size(); ++i)
  72611. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  72612. }
  72613. const String Font::toString() const
  72614. {
  72615. String s (getTypefaceName());
  72616. if (s == getDefaultSansSerifFontName())
  72617. s = String::empty;
  72618. else
  72619. s += "; ";
  72620. s += String (getHeight(), 1);
  72621. if (isBold())
  72622. s += " bold";
  72623. if (isItalic())
  72624. s += " italic";
  72625. return s;
  72626. }
  72627. const Font Font::fromString (const String& fontDescription)
  72628. {
  72629. String name;
  72630. const int separator = fontDescription.indexOfChar (';');
  72631. if (separator > 0)
  72632. name = fontDescription.substring (0, separator).trim();
  72633. if (name.isEmpty())
  72634. name = getDefaultSansSerifFontName();
  72635. String sizeAndStyle (fontDescription.substring (separator + 1));
  72636. float height = sizeAndStyle.getFloatValue();
  72637. if (height <= 0)
  72638. height = 10.0f;
  72639. int flags = Font::plain;
  72640. if (sizeAndStyle.containsIgnoreCase ("bold"))
  72641. flags |= Font::bold;
  72642. if (sizeAndStyle.containsIgnoreCase ("italic"))
  72643. flags |= Font::italic;
  72644. return Font (name, height, flags);
  72645. }
  72646. Typeface* Font::getTypeface() const
  72647. {
  72648. if (font->typeface == 0)
  72649. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  72650. return font->typeface;
  72651. }
  72652. END_JUCE_NAMESPACE
  72653. /*** End of inlined file: juce_Font.cpp ***/
  72654. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  72655. BEGIN_JUCE_NAMESPACE
  72656. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  72657. const juce_wchar character_, const int glyph_)
  72658. : x (x_),
  72659. y (y_),
  72660. w (w_),
  72661. font (font_),
  72662. character (character_),
  72663. glyph (glyph_)
  72664. {
  72665. }
  72666. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  72667. : x (other.x),
  72668. y (other.y),
  72669. w (other.w),
  72670. font (other.font),
  72671. character (other.character),
  72672. glyph (other.glyph)
  72673. {
  72674. }
  72675. void PositionedGlyph::draw (const Graphics& g) const
  72676. {
  72677. if (! isWhitespace())
  72678. {
  72679. g.getInternalContext()->setFont (font);
  72680. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  72681. }
  72682. }
  72683. void PositionedGlyph::draw (const Graphics& g,
  72684. const AffineTransform& transform) const
  72685. {
  72686. if (! isWhitespace())
  72687. {
  72688. g.getInternalContext()->setFont (font);
  72689. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72690. .followedBy (transform));
  72691. }
  72692. }
  72693. void PositionedGlyph::createPath (Path& path) const
  72694. {
  72695. if (! isWhitespace())
  72696. {
  72697. Typeface* const t = font.getTypeface();
  72698. if (t != 0)
  72699. {
  72700. Path p;
  72701. t->getOutlineForGlyph (glyph, p);
  72702. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72703. .translated (x, y));
  72704. }
  72705. }
  72706. }
  72707. bool PositionedGlyph::hitTest (float px, float py) const
  72708. {
  72709. if (getBounds().contains (px, py) && ! isWhitespace())
  72710. {
  72711. Typeface* const t = font.getTypeface();
  72712. if (t != 0)
  72713. {
  72714. Path p;
  72715. t->getOutlineForGlyph (glyph, p);
  72716. AffineTransform::translation (-x, -y)
  72717. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72718. .transformPoint (px, py);
  72719. return p.contains (px, py);
  72720. }
  72721. }
  72722. return false;
  72723. }
  72724. void PositionedGlyph::moveBy (const float deltaX,
  72725. const float deltaY)
  72726. {
  72727. x += deltaX;
  72728. y += deltaY;
  72729. }
  72730. GlyphArrangement::GlyphArrangement()
  72731. {
  72732. glyphs.ensureStorageAllocated (128);
  72733. }
  72734. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72735. {
  72736. addGlyphArrangement (other);
  72737. }
  72738. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72739. {
  72740. if (this != &other)
  72741. {
  72742. clear();
  72743. addGlyphArrangement (other);
  72744. }
  72745. return *this;
  72746. }
  72747. GlyphArrangement::~GlyphArrangement()
  72748. {
  72749. }
  72750. void GlyphArrangement::clear()
  72751. {
  72752. glyphs.clear();
  72753. }
  72754. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72755. {
  72756. jassert (isPositiveAndBelow (index, glyphs.size()));
  72757. return *glyphs [index];
  72758. }
  72759. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72760. {
  72761. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72762. glyphs.addCopiesOf (other.glyphs);
  72763. }
  72764. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72765. {
  72766. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72767. }
  72768. void GlyphArrangement::addLineOfText (const Font& font,
  72769. const String& text,
  72770. const float xOffset,
  72771. const float yOffset)
  72772. {
  72773. addCurtailedLineOfText (font, text,
  72774. xOffset, yOffset,
  72775. 1.0e10f, false);
  72776. }
  72777. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72778. const String& text,
  72779. float xOffset,
  72780. const float yOffset,
  72781. const float maxWidthPixels,
  72782. const bool useEllipsis)
  72783. {
  72784. if (text.isNotEmpty())
  72785. {
  72786. Array <int> newGlyphs;
  72787. Array <float> xOffsets;
  72788. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72789. const int textLen = newGlyphs.size();
  72790. String::CharPointerType t (text.getCharPointer());
  72791. for (int i = 0; i < textLen; ++i)
  72792. {
  72793. const float thisX = xOffsets.getUnchecked (i);
  72794. const float nextX = xOffsets.getUnchecked (i + 1);
  72795. if (nextX > maxWidthPixels + 1.0f)
  72796. {
  72797. // curtail the string if it's too wide..
  72798. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72799. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72800. break;
  72801. }
  72802. else
  72803. {
  72804. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72805. font, t.getAndAdvance(), newGlyphs.getUnchecked(i)));
  72806. }
  72807. }
  72808. }
  72809. }
  72810. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72811. const int startIndex, int endIndex)
  72812. {
  72813. int numDeleted = 0;
  72814. if (glyphs.size() > 0)
  72815. {
  72816. Array<int> dotGlyphs;
  72817. Array<float> dotXs;
  72818. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72819. const float dx = dotXs[1];
  72820. float xOffset = 0.0f, yOffset = 0.0f;
  72821. while (endIndex > startIndex)
  72822. {
  72823. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72824. xOffset = pg->x;
  72825. yOffset = pg->y;
  72826. glyphs.remove (endIndex);
  72827. ++numDeleted;
  72828. if (xOffset + dx * 3 <= maxXPos)
  72829. break;
  72830. }
  72831. for (int i = 3; --i >= 0;)
  72832. {
  72833. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72834. font, '.', dotGlyphs.getFirst()));
  72835. --numDeleted;
  72836. xOffset += dx;
  72837. if (xOffset > maxXPos)
  72838. break;
  72839. }
  72840. }
  72841. return numDeleted;
  72842. }
  72843. void GlyphArrangement::addJustifiedText (const Font& font,
  72844. const String& text,
  72845. float x, float y,
  72846. const float maxLineWidth,
  72847. const Justification& horizontalLayout)
  72848. {
  72849. int lineStartIndex = glyphs.size();
  72850. addLineOfText (font, text, x, y);
  72851. const float originalY = y;
  72852. while (lineStartIndex < glyphs.size())
  72853. {
  72854. int i = lineStartIndex;
  72855. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72856. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72857. ++i;
  72858. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72859. int lastWordBreakIndex = -1;
  72860. while (i < glyphs.size())
  72861. {
  72862. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72863. const juce_wchar c = pg->getCharacter();
  72864. if (c == '\r' || c == '\n')
  72865. {
  72866. ++i;
  72867. if (c == '\r' && i < glyphs.size()
  72868. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  72869. ++i;
  72870. break;
  72871. }
  72872. else if (pg->isWhitespace())
  72873. {
  72874. lastWordBreakIndex = i + 1;
  72875. }
  72876. else if (pg->getRight() - 0.0001f >= lineMaxX)
  72877. {
  72878. if (lastWordBreakIndex >= 0)
  72879. i = lastWordBreakIndex;
  72880. break;
  72881. }
  72882. ++i;
  72883. }
  72884. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  72885. float currentLineEndX = currentLineStartX;
  72886. for (int j = i; --j >= lineStartIndex;)
  72887. {
  72888. if (! glyphs.getUnchecked (j)->isWhitespace())
  72889. {
  72890. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  72891. break;
  72892. }
  72893. }
  72894. float deltaX = 0.0f;
  72895. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  72896. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  72897. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  72898. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  72899. else if (horizontalLayout.testFlags (Justification::right))
  72900. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  72901. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  72902. x + deltaX - currentLineStartX, y - originalY);
  72903. lineStartIndex = i;
  72904. y += font.getHeight();
  72905. }
  72906. }
  72907. void GlyphArrangement::addFittedText (const Font& f,
  72908. const String& text,
  72909. const float x, const float y,
  72910. const float width, const float height,
  72911. const Justification& layout,
  72912. int maximumLines,
  72913. const float minimumHorizontalScale)
  72914. {
  72915. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  72916. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  72917. if (text.containsAnyOf ("\r\n"))
  72918. {
  72919. GlyphArrangement ga;
  72920. ga.addJustifiedText (f, text, x, y, width, layout);
  72921. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  72922. float dy = y - bb.getY();
  72923. if (layout.testFlags (Justification::verticallyCentred))
  72924. dy += (height - bb.getHeight()) * 0.5f;
  72925. else if (layout.testFlags (Justification::bottom))
  72926. dy += height - bb.getHeight();
  72927. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  72928. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  72929. for (int i = 0; i < ga.glyphs.size(); ++i)
  72930. glyphs.add (ga.glyphs.getUnchecked (i));
  72931. ga.glyphs.clear (false);
  72932. return;
  72933. }
  72934. int startIndex = glyphs.size();
  72935. addLineOfText (f, text.trim(), x, y);
  72936. if (glyphs.size() > startIndex)
  72937. {
  72938. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72939. - glyphs.getUnchecked (startIndex)->getLeft();
  72940. if (lineWidth <= 0)
  72941. return;
  72942. if (lineWidth * minimumHorizontalScale < width)
  72943. {
  72944. if (lineWidth > width)
  72945. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  72946. width / lineWidth);
  72947. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  72948. x, y, width, height, layout);
  72949. }
  72950. else if (maximumLines <= 1)
  72951. {
  72952. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  72953. x, y, width, height, f, layout, minimumHorizontalScale);
  72954. }
  72955. else
  72956. {
  72957. Font font (f);
  72958. String txt (text.trim());
  72959. const int length = txt.length();
  72960. const int originalStartIndex = startIndex;
  72961. int numLines = 1;
  72962. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  72963. maximumLines = 1;
  72964. maximumLines = jmin (maximumLines, length);
  72965. while (numLines < maximumLines)
  72966. {
  72967. ++numLines;
  72968. const float newFontHeight = height / (float) numLines;
  72969. if (newFontHeight < font.getHeight())
  72970. {
  72971. font.setHeight (jmax (8.0f, newFontHeight));
  72972. removeRangeOfGlyphs (startIndex, -1);
  72973. addLineOfText (font, txt, x, y);
  72974. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72975. - glyphs.getUnchecked (startIndex)->getLeft();
  72976. }
  72977. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  72978. break;
  72979. }
  72980. if (numLines < 1)
  72981. numLines = 1;
  72982. float lineY = y;
  72983. float widthPerLine = lineWidth / numLines;
  72984. int lastLineStartIndex = 0;
  72985. for (int line = 0; line < numLines; ++line)
  72986. {
  72987. int i = startIndex;
  72988. lastLineStartIndex = i;
  72989. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  72990. if (line == numLines - 1)
  72991. {
  72992. widthPerLine = width;
  72993. i = glyphs.size();
  72994. }
  72995. else
  72996. {
  72997. while (i < glyphs.size())
  72998. {
  72999. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  73000. if (lineWidth > widthPerLine)
  73001. {
  73002. // got to a point where the line's too long, so skip forward to find a
  73003. // good place to break it..
  73004. const int searchStartIndex = i;
  73005. while (i < glyphs.size())
  73006. {
  73007. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  73008. {
  73009. if (glyphs.getUnchecked (i)->isWhitespace()
  73010. || glyphs.getUnchecked (i)->getCharacter() == '-')
  73011. {
  73012. ++i;
  73013. break;
  73014. }
  73015. }
  73016. else
  73017. {
  73018. // can't find a suitable break, so try looking backwards..
  73019. i = searchStartIndex;
  73020. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  73021. {
  73022. if (glyphs.getUnchecked (i - back)->isWhitespace()
  73023. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  73024. {
  73025. i -= back - 1;
  73026. break;
  73027. }
  73028. }
  73029. break;
  73030. }
  73031. ++i;
  73032. }
  73033. break;
  73034. }
  73035. ++i;
  73036. }
  73037. int wsStart = i;
  73038. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  73039. --wsStart;
  73040. int wsEnd = i;
  73041. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  73042. ++wsEnd;
  73043. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  73044. i = jmax (wsStart, startIndex + 1);
  73045. }
  73046. i -= fitLineIntoSpace (startIndex, i - startIndex,
  73047. x, lineY, width, font.getHeight(), font,
  73048. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  73049. minimumHorizontalScale);
  73050. startIndex = i;
  73051. lineY += font.getHeight();
  73052. if (startIndex >= glyphs.size())
  73053. break;
  73054. }
  73055. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  73056. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  73057. }
  73058. }
  73059. }
  73060. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  73061. const float dx, const float dy)
  73062. {
  73063. jassert (startIndex >= 0);
  73064. if (dx != 0.0f || dy != 0.0f)
  73065. {
  73066. if (num < 0 || startIndex + num > glyphs.size())
  73067. num = glyphs.size() - startIndex;
  73068. while (--num >= 0)
  73069. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  73070. }
  73071. }
  73072. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  73073. const Justification& justification, float minimumHorizontalScale)
  73074. {
  73075. int numDeleted = 0;
  73076. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  73077. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  73078. if (lineWidth > w)
  73079. {
  73080. if (minimumHorizontalScale < 1.0f)
  73081. {
  73082. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  73083. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  73084. }
  73085. if (lineWidth > w)
  73086. {
  73087. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  73088. numGlyphs -= numDeleted;
  73089. }
  73090. }
  73091. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  73092. return numDeleted;
  73093. }
  73094. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  73095. const float horizontalScaleFactor)
  73096. {
  73097. jassert (startIndex >= 0);
  73098. if (num < 0 || startIndex + num > glyphs.size())
  73099. num = glyphs.size() - startIndex;
  73100. if (num > 0)
  73101. {
  73102. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  73103. while (--num >= 0)
  73104. {
  73105. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73106. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  73107. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  73108. pg->w *= horizontalScaleFactor;
  73109. }
  73110. }
  73111. }
  73112. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  73113. {
  73114. jassert (startIndex >= 0);
  73115. if (num < 0 || startIndex + num > glyphs.size())
  73116. num = glyphs.size() - startIndex;
  73117. Rectangle<float> result;
  73118. while (--num >= 0)
  73119. {
  73120. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73121. if (includeWhitespace || ! pg->isWhitespace())
  73122. result = result.getUnion (pg->getBounds());
  73123. }
  73124. return result;
  73125. }
  73126. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  73127. const float x, const float y, const float width, const float height,
  73128. const Justification& justification)
  73129. {
  73130. jassert (num >= 0 && startIndex >= 0);
  73131. if (glyphs.size() > 0 && num > 0)
  73132. {
  73133. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  73134. | Justification::horizontallyCentred)));
  73135. float deltaX = 0.0f;
  73136. if (justification.testFlags (Justification::horizontallyJustified))
  73137. deltaX = x - bb.getX();
  73138. else if (justification.testFlags (Justification::horizontallyCentred))
  73139. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  73140. else if (justification.testFlags (Justification::right))
  73141. deltaX = (x + width) - bb.getRight();
  73142. else
  73143. deltaX = x - bb.getX();
  73144. float deltaY = 0.0f;
  73145. if (justification.testFlags (Justification::top))
  73146. deltaY = y - bb.getY();
  73147. else if (justification.testFlags (Justification::bottom))
  73148. deltaY = (y + height) - bb.getBottom();
  73149. else
  73150. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  73151. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  73152. if (justification.testFlags (Justification::horizontallyJustified))
  73153. {
  73154. int lineStart = 0;
  73155. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  73156. int i;
  73157. for (i = 0; i < num; ++i)
  73158. {
  73159. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  73160. if (glyphY != baseY)
  73161. {
  73162. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73163. lineStart = i;
  73164. baseY = glyphY;
  73165. }
  73166. }
  73167. if (i > lineStart)
  73168. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73169. }
  73170. }
  73171. }
  73172. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  73173. {
  73174. if (start + num < glyphs.size()
  73175. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  73176. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  73177. {
  73178. int numSpaces = 0;
  73179. int spacesAtEnd = 0;
  73180. for (int i = 0; i < num; ++i)
  73181. {
  73182. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73183. {
  73184. ++spacesAtEnd;
  73185. ++numSpaces;
  73186. }
  73187. else
  73188. {
  73189. spacesAtEnd = 0;
  73190. }
  73191. }
  73192. numSpaces -= spacesAtEnd;
  73193. if (numSpaces > 0)
  73194. {
  73195. const float startX = glyphs.getUnchecked (start)->getLeft();
  73196. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  73197. const float extraPaddingBetweenWords
  73198. = (targetWidth - (endX - startX)) / (float) numSpaces;
  73199. float deltaX = 0.0f;
  73200. for (int i = 0; i < num; ++i)
  73201. {
  73202. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  73203. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73204. deltaX += extraPaddingBetweenWords;
  73205. }
  73206. }
  73207. }
  73208. }
  73209. void GlyphArrangement::draw (const Graphics& g) const
  73210. {
  73211. for (int i = 0; i < glyphs.size(); ++i)
  73212. {
  73213. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73214. if (pg->font.isUnderlined())
  73215. {
  73216. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73217. float nextX = pg->x + pg->w;
  73218. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73219. nextX = glyphs.getUnchecked (i + 1)->x;
  73220. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73221. nextX - pg->x, lineThickness);
  73222. }
  73223. pg->draw (g);
  73224. }
  73225. }
  73226. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  73227. {
  73228. for (int i = 0; i < glyphs.size(); ++i)
  73229. {
  73230. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73231. if (pg->font.isUnderlined())
  73232. {
  73233. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73234. float nextX = pg->x + pg->w;
  73235. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73236. nextX = glyphs.getUnchecked (i + 1)->x;
  73237. Path p;
  73238. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73239. nextX, pg->y + lineThickness * 2.0f),
  73240. lineThickness);
  73241. g.fillPath (p, transform);
  73242. }
  73243. pg->draw (g, transform);
  73244. }
  73245. }
  73246. void GlyphArrangement::createPath (Path& path) const
  73247. {
  73248. for (int i = 0; i < glyphs.size(); ++i)
  73249. glyphs.getUnchecked (i)->createPath (path);
  73250. }
  73251. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73252. {
  73253. for (int i = 0; i < glyphs.size(); ++i)
  73254. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73255. return i;
  73256. return -1;
  73257. }
  73258. END_JUCE_NAMESPACE
  73259. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73260. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73261. BEGIN_JUCE_NAMESPACE
  73262. class TextLayout::Token
  73263. {
  73264. public:
  73265. Token (const String& t,
  73266. const Font& f,
  73267. const bool isWhitespace_)
  73268. : text (t),
  73269. font (f),
  73270. x(0),
  73271. y(0),
  73272. isWhitespace (isWhitespace_)
  73273. {
  73274. w = font.getStringWidth (t);
  73275. h = roundToInt (f.getHeight());
  73276. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73277. }
  73278. Token (const Token& other)
  73279. : text (other.text),
  73280. font (other.font),
  73281. x (other.x),
  73282. y (other.y),
  73283. w (other.w),
  73284. h (other.h),
  73285. line (other.line),
  73286. lineHeight (other.lineHeight),
  73287. isWhitespace (other.isWhitespace),
  73288. isNewLine (other.isNewLine)
  73289. {
  73290. }
  73291. void draw (Graphics& g,
  73292. const int xOffset,
  73293. const int yOffset)
  73294. {
  73295. if (! isWhitespace)
  73296. {
  73297. g.setFont (font);
  73298. g.drawSingleLineText (text.trimEnd(),
  73299. xOffset + x,
  73300. yOffset + y + (lineHeight - h)
  73301. + roundToInt (font.getAscent()));
  73302. }
  73303. }
  73304. String text;
  73305. Font font;
  73306. int x, y, w, h;
  73307. int line, lineHeight;
  73308. bool isWhitespace, isNewLine;
  73309. private:
  73310. JUCE_LEAK_DETECTOR (Token);
  73311. };
  73312. TextLayout::TextLayout()
  73313. : totalLines (0)
  73314. {
  73315. tokens.ensureStorageAllocated (64);
  73316. }
  73317. TextLayout::TextLayout (const String& text, const Font& font)
  73318. : totalLines (0)
  73319. {
  73320. tokens.ensureStorageAllocated (64);
  73321. appendText (text, font);
  73322. }
  73323. TextLayout::TextLayout (const TextLayout& other)
  73324. : totalLines (0)
  73325. {
  73326. *this = other;
  73327. }
  73328. TextLayout& TextLayout::operator= (const TextLayout& other)
  73329. {
  73330. if (this != &other)
  73331. {
  73332. clear();
  73333. totalLines = other.totalLines;
  73334. tokens.addCopiesOf (other.tokens);
  73335. }
  73336. return *this;
  73337. }
  73338. TextLayout::~TextLayout()
  73339. {
  73340. clear();
  73341. }
  73342. void TextLayout::clear()
  73343. {
  73344. tokens.clear();
  73345. totalLines = 0;
  73346. }
  73347. bool TextLayout::isEmpty() const
  73348. {
  73349. return tokens.size() == 0;
  73350. }
  73351. void TextLayout::appendText (const String& text, const Font& font)
  73352. {
  73353. String::CharPointerType t (text.getCharPointer());
  73354. String currentString;
  73355. int lastCharType = 0;
  73356. for (;;)
  73357. {
  73358. const juce_wchar c = t.getAndAdvance();
  73359. if (c == 0)
  73360. break;
  73361. int charType;
  73362. if (c == '\r' || c == '\n')
  73363. {
  73364. charType = 0;
  73365. }
  73366. else if (CharacterFunctions::isWhitespace (c))
  73367. {
  73368. charType = 2;
  73369. }
  73370. else
  73371. {
  73372. charType = 1;
  73373. }
  73374. if (charType == 0 || charType != lastCharType)
  73375. {
  73376. if (currentString.isNotEmpty())
  73377. {
  73378. tokens.add (new Token (currentString, font,
  73379. lastCharType == 2 || lastCharType == 0));
  73380. }
  73381. currentString = String::charToString (c);
  73382. if (c == '\r' && *t == '\n')
  73383. currentString += t.getAndAdvance();
  73384. }
  73385. else
  73386. {
  73387. currentString += c;
  73388. }
  73389. lastCharType = charType;
  73390. }
  73391. if (currentString.isNotEmpty())
  73392. tokens.add (new Token (currentString, font, lastCharType == 2));
  73393. }
  73394. void TextLayout::setText (const String& text, const Font& font)
  73395. {
  73396. clear();
  73397. appendText (text, font);
  73398. }
  73399. void TextLayout::layout (int maxWidth,
  73400. const Justification& justification,
  73401. const bool attemptToBalanceLineLengths)
  73402. {
  73403. if (attemptToBalanceLineLengths)
  73404. {
  73405. const int originalW = maxWidth;
  73406. int bestWidth = maxWidth;
  73407. float bestLineProportion = 0.0f;
  73408. while (maxWidth > originalW / 2)
  73409. {
  73410. layout (maxWidth, justification, false);
  73411. if (getNumLines() <= 1)
  73412. return;
  73413. const int lastLineW = getLineWidth (getNumLines() - 1);
  73414. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73415. const float prop = lastLineW / (float) lastButOneLineW;
  73416. if (prop > 0.9f)
  73417. return;
  73418. if (prop > bestLineProportion)
  73419. {
  73420. bestLineProportion = prop;
  73421. bestWidth = maxWidth;
  73422. }
  73423. maxWidth -= 10;
  73424. }
  73425. layout (bestWidth, justification, false);
  73426. }
  73427. else
  73428. {
  73429. int x = 0;
  73430. int y = 0;
  73431. int h = 0;
  73432. totalLines = 0;
  73433. int i;
  73434. for (i = 0; i < tokens.size(); ++i)
  73435. {
  73436. Token* const t = tokens.getUnchecked(i);
  73437. t->x = x;
  73438. t->y = y;
  73439. t->line = totalLines;
  73440. x += t->w;
  73441. h = jmax (h, t->h);
  73442. const Token* nextTok = tokens [i + 1];
  73443. if (nextTok == 0)
  73444. break;
  73445. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73446. {
  73447. // finished a line, so go back and update the heights of the things on it
  73448. for (int j = i; j >= 0; --j)
  73449. {
  73450. Token* const tok = tokens.getUnchecked(j);
  73451. if (tok->line == totalLines)
  73452. tok->lineHeight = h;
  73453. else
  73454. break;
  73455. }
  73456. x = 0;
  73457. y += h;
  73458. h = 0;
  73459. ++totalLines;
  73460. }
  73461. }
  73462. // finished a line, so go back and update the heights of the things on it
  73463. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73464. {
  73465. Token* const t = tokens.getUnchecked(j);
  73466. if (t->line == totalLines)
  73467. t->lineHeight = h;
  73468. else
  73469. break;
  73470. }
  73471. ++totalLines;
  73472. if (! justification.testFlags (Justification::left))
  73473. {
  73474. int totalW = getWidth();
  73475. for (i = totalLines; --i >= 0;)
  73476. {
  73477. const int lineW = getLineWidth (i);
  73478. int dx = 0;
  73479. if (justification.testFlags (Justification::horizontallyCentred))
  73480. dx = (totalW - lineW) / 2;
  73481. else if (justification.testFlags (Justification::right))
  73482. dx = totalW - lineW;
  73483. for (int j = tokens.size(); --j >= 0;)
  73484. {
  73485. Token* const t = tokens.getUnchecked(j);
  73486. if (t->line == i)
  73487. t->x += dx;
  73488. }
  73489. }
  73490. }
  73491. }
  73492. }
  73493. int TextLayout::getLineWidth (const int lineNumber) const
  73494. {
  73495. int maxW = 0;
  73496. for (int i = tokens.size(); --i >= 0;)
  73497. {
  73498. const Token* const t = tokens.getUnchecked(i);
  73499. if (t->line == lineNumber && ! t->isWhitespace)
  73500. maxW = jmax (maxW, t->x + t->w);
  73501. }
  73502. return maxW;
  73503. }
  73504. int TextLayout::getWidth() const
  73505. {
  73506. int maxW = 0;
  73507. for (int i = tokens.size(); --i >= 0;)
  73508. {
  73509. const Token* const t = tokens.getUnchecked(i);
  73510. if (! t->isWhitespace)
  73511. maxW = jmax (maxW, t->x + t->w);
  73512. }
  73513. return maxW;
  73514. }
  73515. int TextLayout::getHeight() const
  73516. {
  73517. int maxH = 0;
  73518. for (int i = tokens.size(); --i >= 0;)
  73519. {
  73520. const Token* const t = tokens.getUnchecked(i);
  73521. if (! t->isWhitespace)
  73522. maxH = jmax (maxH, t->y + t->h);
  73523. }
  73524. return maxH;
  73525. }
  73526. void TextLayout::draw (Graphics& g,
  73527. const int xOffset,
  73528. const int yOffset) const
  73529. {
  73530. for (int i = tokens.size(); --i >= 0;)
  73531. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  73532. }
  73533. void TextLayout::drawWithin (Graphics& g,
  73534. int x, int y, int w, int h,
  73535. const Justification& justification) const
  73536. {
  73537. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  73538. x, y, w, h);
  73539. draw (g, x, y);
  73540. }
  73541. END_JUCE_NAMESPACE
  73542. /*** End of inlined file: juce_TextLayout.cpp ***/
  73543. /*** Start of inlined file: juce_Typeface.cpp ***/
  73544. BEGIN_JUCE_NAMESPACE
  73545. Typeface::Typeface (const String& name_) throw()
  73546. : name (name_), isFallbackFont (false)
  73547. {
  73548. }
  73549. Typeface::~Typeface()
  73550. {
  73551. }
  73552. const Typeface::Ptr Typeface::getFallbackTypeface()
  73553. {
  73554. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73555. Typeface* t = fallbackFont.getTypeface();
  73556. t->isFallbackFont = true;
  73557. return t;
  73558. }
  73559. class CustomTypeface::GlyphInfo
  73560. {
  73561. public:
  73562. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  73563. : character (character_), path (path_), width (width_)
  73564. {
  73565. }
  73566. struct KerningPair
  73567. {
  73568. juce_wchar character2;
  73569. float kerningAmount;
  73570. };
  73571. void addKerningPair (const juce_wchar subsequentCharacter,
  73572. const float extraKerningAmount) throw()
  73573. {
  73574. KerningPair kp;
  73575. kp.character2 = subsequentCharacter;
  73576. kp.kerningAmount = extraKerningAmount;
  73577. kerningPairs.add (kp);
  73578. }
  73579. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  73580. {
  73581. if (subsequentCharacter != 0)
  73582. {
  73583. for (int i = kerningPairs.size(); --i >= 0;)
  73584. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  73585. return width + kerningPairs.getReference(i).kerningAmount;
  73586. }
  73587. return width;
  73588. }
  73589. const juce_wchar character;
  73590. const Path path;
  73591. float width;
  73592. Array <KerningPair> kerningPairs;
  73593. private:
  73594. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphInfo);
  73595. };
  73596. CustomTypeface::CustomTypeface()
  73597. : Typeface (String::empty)
  73598. {
  73599. clear();
  73600. }
  73601. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  73602. : Typeface (String::empty)
  73603. {
  73604. clear();
  73605. GZIPDecompressorInputStream gzin (serialisedTypefaceStream);
  73606. BufferedInputStream in (gzin, 32768);
  73607. name = in.readString();
  73608. isBold = in.readBool();
  73609. isItalic = in.readBool();
  73610. ascent = in.readFloat();
  73611. defaultCharacter = (juce_wchar) in.readShort();
  73612. int i, numChars = in.readInt();
  73613. for (i = 0; i < numChars; ++i)
  73614. {
  73615. const juce_wchar c = (juce_wchar) in.readShort();
  73616. const float width = in.readFloat();
  73617. Path p;
  73618. p.loadPathFromStream (in);
  73619. addGlyph (c, p, width);
  73620. }
  73621. const int numKerningPairs = in.readInt();
  73622. for (i = 0; i < numKerningPairs; ++i)
  73623. {
  73624. const juce_wchar char1 = (juce_wchar) in.readShort();
  73625. const juce_wchar char2 = (juce_wchar) in.readShort();
  73626. addKerningPair (char1, char2, in.readFloat());
  73627. }
  73628. }
  73629. CustomTypeface::~CustomTypeface()
  73630. {
  73631. }
  73632. void CustomTypeface::clear()
  73633. {
  73634. defaultCharacter = 0;
  73635. ascent = 1.0f;
  73636. isBold = isItalic = false;
  73637. zeromem (lookupTable, sizeof (lookupTable));
  73638. glyphs.clear();
  73639. }
  73640. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  73641. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  73642. {
  73643. name = name_;
  73644. defaultCharacter = defaultCharacter_;
  73645. ascent = ascent_;
  73646. isBold = isBold_;
  73647. isItalic = isItalic_;
  73648. }
  73649. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  73650. {
  73651. // Check that you're not trying to add the same character twice..
  73652. jassert (findGlyph (character, false) == 0);
  73653. if (isPositiveAndBelow ((int) character, (int) numElementsInArray (lookupTable)))
  73654. lookupTable [character] = (short) glyphs.size();
  73655. glyphs.add (new GlyphInfo (character, path, width));
  73656. }
  73657. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  73658. {
  73659. if (extraAmount != 0)
  73660. {
  73661. GlyphInfo* const g = findGlyph (char1, true);
  73662. jassert (g != 0); // can only add kerning pairs for characters that exist!
  73663. if (g != 0)
  73664. g->addKerningPair (char2, extraAmount);
  73665. }
  73666. }
  73667. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  73668. {
  73669. if (isPositiveAndBelow ((int) character, (int) numElementsInArray (lookupTable)) && lookupTable [character] > 0)
  73670. return glyphs [(int) lookupTable [(int) character]];
  73671. for (int i = 0; i < glyphs.size(); ++i)
  73672. {
  73673. GlyphInfo* const g = glyphs.getUnchecked(i);
  73674. if (g->character == character)
  73675. return g;
  73676. }
  73677. if (loadIfNeeded && loadGlyphIfPossible (character))
  73678. return findGlyph (character, false);
  73679. return 0;
  73680. }
  73681. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  73682. {
  73683. GlyphInfo* glyph = findGlyph (character, true);
  73684. if (glyph == 0)
  73685. {
  73686. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  73687. glyph = findGlyph (L' ', true);
  73688. if (glyph == 0)
  73689. {
  73690. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73691. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73692. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73693. {
  73694. Path path;
  73695. fallbackTypeface->getOutlineForGlyph (character, path);
  73696. addGlyph (character, path, fallbackTypeface->getStringWidth (String::charToString (character)));
  73697. }
  73698. if (glyph == 0)
  73699. glyph = findGlyph (defaultCharacter, true);
  73700. }
  73701. }
  73702. return glyph;
  73703. }
  73704. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73705. {
  73706. return false;
  73707. }
  73708. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73709. {
  73710. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73711. for (int i = 0; i < numCharacters; ++i)
  73712. {
  73713. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73714. Array <int> glyphIndexes;
  73715. Array <float> offsets;
  73716. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73717. const int glyphIndex = glyphIndexes.getFirst();
  73718. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73719. {
  73720. const float glyphWidth = offsets[1];
  73721. Path p;
  73722. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73723. addGlyph (c, p, glyphWidth);
  73724. for (int j = glyphs.size() - 1; --j >= 0;)
  73725. {
  73726. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73727. glyphIndexes.clearQuick();
  73728. offsets.clearQuick();
  73729. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73730. if (offsets.size() > 1)
  73731. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73732. }
  73733. }
  73734. }
  73735. }
  73736. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73737. {
  73738. GZIPCompressorOutputStream out (&outputStream);
  73739. out.writeString (name);
  73740. out.writeBool (isBold);
  73741. out.writeBool (isItalic);
  73742. out.writeFloat (ascent);
  73743. out.writeShort ((short) (unsigned short) defaultCharacter);
  73744. out.writeInt (glyphs.size());
  73745. int i, numKerningPairs = 0;
  73746. for (i = 0; i < glyphs.size(); ++i)
  73747. {
  73748. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73749. out.writeShort ((short) (unsigned short) g->character);
  73750. out.writeFloat (g->width);
  73751. g->path.writePathToStream (out);
  73752. numKerningPairs += g->kerningPairs.size();
  73753. }
  73754. out.writeInt (numKerningPairs);
  73755. for (i = 0; i < glyphs.size(); ++i)
  73756. {
  73757. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73758. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73759. {
  73760. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73761. out.writeShort ((short) (unsigned short) g->character);
  73762. out.writeShort ((short) (unsigned short) p.character2);
  73763. out.writeFloat (p.kerningAmount);
  73764. }
  73765. }
  73766. return true;
  73767. }
  73768. float CustomTypeface::getAscent() const
  73769. {
  73770. return ascent;
  73771. }
  73772. float CustomTypeface::getDescent() const
  73773. {
  73774. return 1.0f - ascent;
  73775. }
  73776. float CustomTypeface::getStringWidth (const String& text)
  73777. {
  73778. float x = 0;
  73779. String::CharPointerType t (text.getCharPointer());
  73780. while (! t.isEmpty())
  73781. {
  73782. const GlyphInfo* const glyph = findGlyphSubstituting (t.getAndAdvance());
  73783. if (glyph == 0 && ! isFallbackFont)
  73784. {
  73785. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73786. if (fallbackTypeface != 0)
  73787. x += fallbackTypeface->getStringWidth (String::charToString (*t));
  73788. }
  73789. if (glyph != 0)
  73790. x += glyph->getHorizontalSpacing (*t);
  73791. }
  73792. return x;
  73793. }
  73794. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73795. {
  73796. xOffsets.add (0);
  73797. float x = 0;
  73798. String::CharPointerType t (text.getCharPointer());
  73799. while (! t.isEmpty())
  73800. {
  73801. const juce_wchar c = t.getAndAdvance();
  73802. const GlyphInfo* const glyph = findGlyph (c, true);
  73803. if (glyph == 0 && ! isFallbackFont)
  73804. {
  73805. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73806. if (fallbackTypeface != 0)
  73807. {
  73808. Array <int> subGlyphs;
  73809. Array <float> subOffsets;
  73810. fallbackTypeface->getGlyphPositions (String::charToString (c), subGlyphs, subOffsets);
  73811. if (subGlyphs.size() > 0)
  73812. {
  73813. resultGlyphs.add (subGlyphs.getFirst());
  73814. x += subOffsets[1];
  73815. xOffsets.add (x);
  73816. }
  73817. }
  73818. }
  73819. if (glyph != 0)
  73820. {
  73821. x += glyph->getHorizontalSpacing (*t);
  73822. resultGlyphs.add ((int) glyph->character);
  73823. xOffsets.add (x);
  73824. }
  73825. }
  73826. }
  73827. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73828. {
  73829. const GlyphInfo* const glyph = findGlyph ((juce_wchar) glyphNumber, true);
  73830. if (glyph == 0 && ! isFallbackFont)
  73831. {
  73832. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73833. if (fallbackTypeface != 0)
  73834. fallbackTypeface->getOutlineForGlyph (glyphNumber, path);
  73835. }
  73836. if (glyph != 0)
  73837. {
  73838. path = glyph->path;
  73839. return true;
  73840. }
  73841. return false;
  73842. }
  73843. END_JUCE_NAMESPACE
  73844. /*** End of inlined file: juce_Typeface.cpp ***/
  73845. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73846. BEGIN_JUCE_NAMESPACE
  73847. AffineTransform::AffineTransform() throw()
  73848. : mat00 (1.0f), mat01 (0), mat02 (0),
  73849. mat10 (0), mat11 (1.0f), mat12 (0)
  73850. {
  73851. }
  73852. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73853. : mat00 (other.mat00), mat01 (other.mat01), mat02 (other.mat02),
  73854. mat10 (other.mat10), mat11 (other.mat11), mat12 (other.mat12)
  73855. {
  73856. }
  73857. AffineTransform::AffineTransform (const float mat00_, const float mat01_, const float mat02_,
  73858. const float mat10_, const float mat11_, const float mat12_) throw()
  73859. : mat00 (mat00_), mat01 (mat01_), mat02 (mat02_),
  73860. mat10 (mat10_), mat11 (mat11_), mat12 (mat12_)
  73861. {
  73862. }
  73863. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73864. {
  73865. mat00 = other.mat00;
  73866. mat01 = other.mat01;
  73867. mat02 = other.mat02;
  73868. mat10 = other.mat10;
  73869. mat11 = other.mat11;
  73870. mat12 = other.mat12;
  73871. return *this;
  73872. }
  73873. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73874. {
  73875. return mat00 == other.mat00
  73876. && mat01 == other.mat01
  73877. && mat02 == other.mat02
  73878. && mat10 == other.mat10
  73879. && mat11 == other.mat11
  73880. && mat12 == other.mat12;
  73881. }
  73882. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  73883. {
  73884. return ! operator== (other);
  73885. }
  73886. bool AffineTransform::isIdentity() const throw()
  73887. {
  73888. return (mat01 == 0)
  73889. && (mat02 == 0)
  73890. && (mat10 == 0)
  73891. && (mat12 == 0)
  73892. && (mat00 == 1.0f)
  73893. && (mat11 == 1.0f);
  73894. }
  73895. const AffineTransform AffineTransform::identity;
  73896. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  73897. {
  73898. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  73899. other.mat00 * mat01 + other.mat01 * mat11,
  73900. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  73901. other.mat10 * mat00 + other.mat11 * mat10,
  73902. other.mat10 * mat01 + other.mat11 * mat11,
  73903. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  73904. }
  73905. const AffineTransform AffineTransform::translated (const float dx, const float dy) const throw()
  73906. {
  73907. return AffineTransform (mat00, mat01, mat02 + dx,
  73908. mat10, mat11, mat12 + dy);
  73909. }
  73910. const AffineTransform AffineTransform::translation (const float dx, const float dy) throw()
  73911. {
  73912. return AffineTransform (1.0f, 0, dx,
  73913. 0, 1.0f, dy);
  73914. }
  73915. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  73916. {
  73917. const float cosRad = std::cos (rad);
  73918. const float sinRad = std::sin (rad);
  73919. return AffineTransform (cosRad * mat00 + -sinRad * mat10,
  73920. cosRad * mat01 + -sinRad * mat11,
  73921. cosRad * mat02 + -sinRad * mat12,
  73922. sinRad * mat00 + cosRad * mat10,
  73923. sinRad * mat01 + cosRad * mat11,
  73924. sinRad * mat02 + cosRad * mat12);
  73925. }
  73926. const AffineTransform AffineTransform::rotation (const float rad) throw()
  73927. {
  73928. const float cosRad = std::cos (rad);
  73929. const float sinRad = std::sin (rad);
  73930. return AffineTransform (cosRad, -sinRad, 0,
  73931. sinRad, cosRad, 0);
  73932. }
  73933. const AffineTransform AffineTransform::rotation (const float rad, const float pivotX, const float pivotY) throw()
  73934. {
  73935. const float cosRad = std::cos (rad);
  73936. const float sinRad = std::sin (rad);
  73937. return AffineTransform (cosRad, -sinRad, -cosRad * pivotX + sinRad * pivotY + pivotX,
  73938. sinRad, cosRad, -sinRad * pivotX + -cosRad * pivotY + pivotY);
  73939. }
  73940. const AffineTransform AffineTransform::rotated (const float angle, const float pivotX, const float pivotY) const throw()
  73941. {
  73942. return followedBy (rotation (angle, pivotX, pivotY));
  73943. }
  73944. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY) const throw()
  73945. {
  73946. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  73947. factorY * mat10, factorY * mat11, factorY * mat12);
  73948. }
  73949. const AffineTransform AffineTransform::scale (const float factorX, const float factorY) throw()
  73950. {
  73951. return AffineTransform (factorX, 0, 0,
  73952. 0, factorY, 0);
  73953. }
  73954. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY,
  73955. const float pivotX, const float pivotY) const throw()
  73956. {
  73957. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02 + pivotX * (1.0f - factorX),
  73958. factorY * mat10, factorY * mat11, factorY * mat12 + pivotY * (1.0f - factorY));
  73959. }
  73960. const AffineTransform AffineTransform::scale (const float factorX, const float factorY,
  73961. const float pivotX, const float pivotY) throw()
  73962. {
  73963. return AffineTransform (factorX, 0, pivotX * (1.0f - factorX),
  73964. 0, factorY, pivotY * (1.0f - factorY));
  73965. }
  73966. const AffineTransform AffineTransform::shear (float shearX, float shearY) throw()
  73967. {
  73968. return AffineTransform (1.0f, shearX, 0,
  73969. shearY, 1.0f, 0);
  73970. }
  73971. const AffineTransform AffineTransform::sheared (const float shearX, const float shearY) const throw()
  73972. {
  73973. return AffineTransform (mat00 + shearX * mat10,
  73974. mat01 + shearX * mat11,
  73975. mat02 + shearX * mat12,
  73976. shearY * mat00 + mat10,
  73977. shearY * mat01 + mat11,
  73978. shearY * mat02 + mat12);
  73979. }
  73980. const AffineTransform AffineTransform::inverted() const throw()
  73981. {
  73982. double determinant = (mat00 * mat11 - mat10 * mat01);
  73983. if (determinant != 0.0)
  73984. {
  73985. determinant = 1.0 / determinant;
  73986. const float dst00 = (float) (mat11 * determinant);
  73987. const float dst10 = (float) (-mat10 * determinant);
  73988. const float dst01 = (float) (-mat01 * determinant);
  73989. const float dst11 = (float) (mat00 * determinant);
  73990. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  73991. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  73992. }
  73993. else
  73994. {
  73995. // singularity..
  73996. return *this;
  73997. }
  73998. }
  73999. bool AffineTransform::isSingularity() const throw()
  74000. {
  74001. return (mat00 * mat11 - mat10 * mat01) == 0;
  74002. }
  74003. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  74004. const float x10, const float y10,
  74005. const float x01, const float y01) throw()
  74006. {
  74007. return AffineTransform (x10 - x00, x01 - x00, x00,
  74008. y10 - y00, y01 - y00, y00);
  74009. }
  74010. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  74011. const float sx2, const float sy2, const float tx2, const float ty2,
  74012. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  74013. {
  74014. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  74015. .inverted()
  74016. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  74017. }
  74018. bool AffineTransform::isOnlyTranslation() const throw()
  74019. {
  74020. return (mat01 == 0)
  74021. && (mat10 == 0)
  74022. && (mat00 == 1.0f)
  74023. && (mat11 == 1.0f);
  74024. }
  74025. float AffineTransform::getScaleFactor() const throw()
  74026. {
  74027. return juce_hypot (mat00 + mat01, mat10 + mat11);
  74028. }
  74029. END_JUCE_NAMESPACE
  74030. /*** End of inlined file: juce_AffineTransform.cpp ***/
  74031. /*** Start of inlined file: juce_Path.cpp ***/
  74032. BEGIN_JUCE_NAMESPACE
  74033. // tests that some co-ords aren't NaNs
  74034. #define CHECK_COORDS_ARE_VALID(x, y) \
  74035. jassert (x == x && y == y);
  74036. namespace PathHelpers
  74037. {
  74038. const float ellipseAngularIncrement = 0.05f;
  74039. const String nextToken (String::CharPointerType& t)
  74040. {
  74041. t = t.findEndOfWhitespace();
  74042. String::CharPointerType start (t);
  74043. int numChars = 0;
  74044. while (! (t.isEmpty() || t.isWhitespace()))
  74045. {
  74046. ++t;
  74047. ++numChars;
  74048. }
  74049. return String (start, numChars);
  74050. }
  74051. inline double lengthOf (float x1, float y1, float x2, float y2) throw()
  74052. {
  74053. return juce_hypot ((double) (x1 - x2), (double) (y1 - y2));
  74054. }
  74055. }
  74056. const float Path::lineMarker = 100001.0f;
  74057. const float Path::moveMarker = 100002.0f;
  74058. const float Path::quadMarker = 100003.0f;
  74059. const float Path::cubicMarker = 100004.0f;
  74060. const float Path::closeSubPathMarker = 100005.0f;
  74061. Path::Path()
  74062. : numElements (0),
  74063. pathXMin (0),
  74064. pathXMax (0),
  74065. pathYMin (0),
  74066. pathYMax (0),
  74067. useNonZeroWinding (true)
  74068. {
  74069. }
  74070. Path::~Path()
  74071. {
  74072. }
  74073. Path::Path (const Path& other)
  74074. : numElements (other.numElements),
  74075. pathXMin (other.pathXMin),
  74076. pathXMax (other.pathXMax),
  74077. pathYMin (other.pathYMin),
  74078. pathYMax (other.pathYMax),
  74079. useNonZeroWinding (other.useNonZeroWinding)
  74080. {
  74081. if (numElements > 0)
  74082. {
  74083. data.setAllocatedSize ((int) numElements);
  74084. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74085. }
  74086. }
  74087. Path& Path::operator= (const Path& other)
  74088. {
  74089. if (this != &other)
  74090. {
  74091. data.ensureAllocatedSize ((int) other.numElements);
  74092. numElements = other.numElements;
  74093. pathXMin = other.pathXMin;
  74094. pathXMax = other.pathXMax;
  74095. pathYMin = other.pathYMin;
  74096. pathYMax = other.pathYMax;
  74097. useNonZeroWinding = other.useNonZeroWinding;
  74098. if (numElements > 0)
  74099. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74100. }
  74101. return *this;
  74102. }
  74103. bool Path::operator== (const Path& other) const throw()
  74104. {
  74105. return ! operator!= (other);
  74106. }
  74107. bool Path::operator!= (const Path& other) const throw()
  74108. {
  74109. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  74110. return true;
  74111. for (size_t i = 0; i < numElements; ++i)
  74112. if (data.elements[i] != other.data.elements[i])
  74113. return true;
  74114. return false;
  74115. }
  74116. void Path::clear() throw()
  74117. {
  74118. numElements = 0;
  74119. pathXMin = 0;
  74120. pathYMin = 0;
  74121. pathYMax = 0;
  74122. pathXMax = 0;
  74123. }
  74124. void Path::swapWithPath (Path& other) throw()
  74125. {
  74126. data.swapWith (other.data);
  74127. swapVariables <size_t> (numElements, other.numElements);
  74128. swapVariables <float> (pathXMin, other.pathXMin);
  74129. swapVariables <float> (pathXMax, other.pathXMax);
  74130. swapVariables <float> (pathYMin, other.pathYMin);
  74131. swapVariables <float> (pathYMax, other.pathYMax);
  74132. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  74133. }
  74134. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  74135. {
  74136. useNonZeroWinding = isNonZero;
  74137. }
  74138. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  74139. const bool preserveProportions) throw()
  74140. {
  74141. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  74142. }
  74143. bool Path::isEmpty() const throw()
  74144. {
  74145. size_t i = 0;
  74146. while (i < numElements)
  74147. {
  74148. const float type = data.elements [i++];
  74149. if (type == moveMarker)
  74150. {
  74151. i += 2;
  74152. }
  74153. else if (type == lineMarker
  74154. || type == quadMarker
  74155. || type == cubicMarker)
  74156. {
  74157. return false;
  74158. }
  74159. }
  74160. return true;
  74161. }
  74162. const Rectangle<float> Path::getBounds() const throw()
  74163. {
  74164. return Rectangle<float> (pathXMin, pathYMin,
  74165. pathXMax - pathXMin,
  74166. pathYMax - pathYMin);
  74167. }
  74168. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74169. {
  74170. return getBounds().transformed (transform);
  74171. }
  74172. void Path::startNewSubPath (const float x, const float y)
  74173. {
  74174. CHECK_COORDS_ARE_VALID (x, y);
  74175. if (numElements == 0)
  74176. {
  74177. pathXMin = pathXMax = x;
  74178. pathYMin = pathYMax = y;
  74179. }
  74180. else
  74181. {
  74182. pathXMin = jmin (pathXMin, x);
  74183. pathXMax = jmax (pathXMax, x);
  74184. pathYMin = jmin (pathYMin, y);
  74185. pathYMax = jmax (pathYMax, y);
  74186. }
  74187. data.ensureAllocatedSize ((int) numElements + 3);
  74188. data.elements [numElements++] = moveMarker;
  74189. data.elements [numElements++] = x;
  74190. data.elements [numElements++] = y;
  74191. }
  74192. void Path::startNewSubPath (const Point<float>& start)
  74193. {
  74194. startNewSubPath (start.getX(), start.getY());
  74195. }
  74196. void Path::lineTo (const float x, const float y)
  74197. {
  74198. CHECK_COORDS_ARE_VALID (x, y);
  74199. if (numElements == 0)
  74200. startNewSubPath (0, 0);
  74201. data.ensureAllocatedSize ((int) numElements + 3);
  74202. data.elements [numElements++] = lineMarker;
  74203. data.elements [numElements++] = x;
  74204. data.elements [numElements++] = y;
  74205. pathXMin = jmin (pathXMin, x);
  74206. pathXMax = jmax (pathXMax, x);
  74207. pathYMin = jmin (pathYMin, y);
  74208. pathYMax = jmax (pathYMax, y);
  74209. }
  74210. void Path::lineTo (const Point<float>& end)
  74211. {
  74212. lineTo (end.getX(), end.getY());
  74213. }
  74214. void Path::quadraticTo (const float x1, const float y1,
  74215. const float x2, const float y2)
  74216. {
  74217. CHECK_COORDS_ARE_VALID (x1, y1);
  74218. CHECK_COORDS_ARE_VALID (x2, y2);
  74219. if (numElements == 0)
  74220. startNewSubPath (0, 0);
  74221. data.ensureAllocatedSize ((int) numElements + 5);
  74222. data.elements [numElements++] = quadMarker;
  74223. data.elements [numElements++] = x1;
  74224. data.elements [numElements++] = y1;
  74225. data.elements [numElements++] = x2;
  74226. data.elements [numElements++] = y2;
  74227. pathXMin = jmin (pathXMin, x1, x2);
  74228. pathXMax = jmax (pathXMax, x1, x2);
  74229. pathYMin = jmin (pathYMin, y1, y2);
  74230. pathYMax = jmax (pathYMax, y1, y2);
  74231. }
  74232. void Path::quadraticTo (const Point<float>& controlPoint,
  74233. const Point<float>& endPoint)
  74234. {
  74235. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74236. endPoint.getX(), endPoint.getY());
  74237. }
  74238. void Path::cubicTo (const float x1, const float y1,
  74239. const float x2, const float y2,
  74240. const float x3, const float y3)
  74241. {
  74242. CHECK_COORDS_ARE_VALID (x1, y1);
  74243. CHECK_COORDS_ARE_VALID (x2, y2);
  74244. CHECK_COORDS_ARE_VALID (x3, y3);
  74245. if (numElements == 0)
  74246. startNewSubPath (0, 0);
  74247. data.ensureAllocatedSize ((int) numElements + 7);
  74248. data.elements [numElements++] = cubicMarker;
  74249. data.elements [numElements++] = x1;
  74250. data.elements [numElements++] = y1;
  74251. data.elements [numElements++] = x2;
  74252. data.elements [numElements++] = y2;
  74253. data.elements [numElements++] = x3;
  74254. data.elements [numElements++] = y3;
  74255. pathXMin = jmin (pathXMin, x1, x2, x3);
  74256. pathXMax = jmax (pathXMax, x1, x2, x3);
  74257. pathYMin = jmin (pathYMin, y1, y2, y3);
  74258. pathYMax = jmax (pathYMax, y1, y2, y3);
  74259. }
  74260. void Path::cubicTo (const Point<float>& controlPoint1,
  74261. const Point<float>& controlPoint2,
  74262. const Point<float>& endPoint)
  74263. {
  74264. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74265. controlPoint2.getX(), controlPoint2.getY(),
  74266. endPoint.getX(), endPoint.getY());
  74267. }
  74268. void Path::closeSubPath()
  74269. {
  74270. if (numElements > 0
  74271. && data.elements [numElements - 1] != closeSubPathMarker)
  74272. {
  74273. data.ensureAllocatedSize ((int) numElements + 1);
  74274. data.elements [numElements++] = closeSubPathMarker;
  74275. }
  74276. }
  74277. const Point<float> Path::getCurrentPosition() const
  74278. {
  74279. int i = (int) numElements - 1;
  74280. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74281. {
  74282. while (i >= 0)
  74283. {
  74284. if (data.elements[i] == moveMarker)
  74285. {
  74286. i += 2;
  74287. break;
  74288. }
  74289. --i;
  74290. }
  74291. }
  74292. if (i > 0)
  74293. return Point<float> (data.elements [i - 1], data.elements [i]);
  74294. return Point<float>();
  74295. }
  74296. void Path::addRectangle (const float x, const float y,
  74297. const float w, const float h)
  74298. {
  74299. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74300. if (w < 0)
  74301. swapVariables (x1, x2);
  74302. if (h < 0)
  74303. swapVariables (y1, y2);
  74304. data.ensureAllocatedSize ((int) numElements + 13);
  74305. if (numElements == 0)
  74306. {
  74307. pathXMin = x1;
  74308. pathXMax = x2;
  74309. pathYMin = y1;
  74310. pathYMax = y2;
  74311. }
  74312. else
  74313. {
  74314. pathXMin = jmin (pathXMin, x1);
  74315. pathXMax = jmax (pathXMax, x2);
  74316. pathYMin = jmin (pathYMin, y1);
  74317. pathYMax = jmax (pathYMax, y2);
  74318. }
  74319. data.elements [numElements++] = moveMarker;
  74320. data.elements [numElements++] = x1;
  74321. data.elements [numElements++] = y2;
  74322. data.elements [numElements++] = lineMarker;
  74323. data.elements [numElements++] = x1;
  74324. data.elements [numElements++] = y1;
  74325. data.elements [numElements++] = lineMarker;
  74326. data.elements [numElements++] = x2;
  74327. data.elements [numElements++] = y1;
  74328. data.elements [numElements++] = lineMarker;
  74329. data.elements [numElements++] = x2;
  74330. data.elements [numElements++] = y2;
  74331. data.elements [numElements++] = closeSubPathMarker;
  74332. }
  74333. void Path::addRoundedRectangle (const float x, const float y,
  74334. const float w, const float h,
  74335. float csx,
  74336. float csy)
  74337. {
  74338. csx = jmin (csx, w * 0.5f);
  74339. csy = jmin (csy, h * 0.5f);
  74340. const float cs45x = csx * 0.45f;
  74341. const float cs45y = csy * 0.45f;
  74342. const float x2 = x + w;
  74343. const float y2 = y + h;
  74344. startNewSubPath (x + csx, y);
  74345. lineTo (x2 - csx, y);
  74346. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74347. lineTo (x2, y2 - csy);
  74348. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74349. lineTo (x + csx, y2);
  74350. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74351. lineTo (x, y + csy);
  74352. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74353. closeSubPath();
  74354. }
  74355. void Path::addRoundedRectangle (const float x, const float y,
  74356. const float w, const float h,
  74357. float cs)
  74358. {
  74359. addRoundedRectangle (x, y, w, h, cs, cs);
  74360. }
  74361. void Path::addTriangle (const float x1, const float y1,
  74362. const float x2, const float y2,
  74363. const float x3, const float y3)
  74364. {
  74365. startNewSubPath (x1, y1);
  74366. lineTo (x2, y2);
  74367. lineTo (x3, y3);
  74368. closeSubPath();
  74369. }
  74370. void Path::addQuadrilateral (const float x1, const float y1,
  74371. const float x2, const float y2,
  74372. const float x3, const float y3,
  74373. const float x4, const float y4)
  74374. {
  74375. startNewSubPath (x1, y1);
  74376. lineTo (x2, y2);
  74377. lineTo (x3, y3);
  74378. lineTo (x4, y4);
  74379. closeSubPath();
  74380. }
  74381. void Path::addEllipse (const float x, const float y,
  74382. const float w, const float h)
  74383. {
  74384. const float hw = w * 0.5f;
  74385. const float hw55 = hw * 0.55f;
  74386. const float hh = h * 0.5f;
  74387. const float hh55 = hh * 0.55f;
  74388. const float cx = x + hw;
  74389. const float cy = y + hh;
  74390. startNewSubPath (cx, cy - hh);
  74391. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh55, cx + hw, cy);
  74392. cubicTo (cx + hw, cy + hh55, cx + hw55, cy + hh, cx, cy + hh);
  74393. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh55, cx - hw, cy);
  74394. cubicTo (cx - hw, cy - hh55, cx - hw55, cy - hh, cx, cy - hh);
  74395. closeSubPath();
  74396. }
  74397. void Path::addArc (const float x, const float y,
  74398. const float w, const float h,
  74399. const float fromRadians,
  74400. const float toRadians,
  74401. const bool startAsNewSubPath)
  74402. {
  74403. const float radiusX = w / 2.0f;
  74404. const float radiusY = h / 2.0f;
  74405. addCentredArc (x + radiusX,
  74406. y + radiusY,
  74407. radiusX, radiusY,
  74408. 0.0f,
  74409. fromRadians, toRadians,
  74410. startAsNewSubPath);
  74411. }
  74412. void Path::addCentredArc (const float centreX, const float centreY,
  74413. const float radiusX, const float radiusY,
  74414. const float rotationOfEllipse,
  74415. const float fromRadians,
  74416. const float toRadians,
  74417. const bool startAsNewSubPath)
  74418. {
  74419. if (radiusX > 0.0f && radiusY > 0.0f)
  74420. {
  74421. const Point<float> centre (centreX, centreY);
  74422. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74423. float angle = fromRadians;
  74424. if (startAsNewSubPath)
  74425. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74426. if (fromRadians < toRadians)
  74427. {
  74428. if (startAsNewSubPath)
  74429. angle += PathHelpers::ellipseAngularIncrement;
  74430. while (angle < toRadians)
  74431. {
  74432. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74433. angle += PathHelpers::ellipseAngularIncrement;
  74434. }
  74435. }
  74436. else
  74437. {
  74438. if (startAsNewSubPath)
  74439. angle -= PathHelpers::ellipseAngularIncrement;
  74440. while (angle > toRadians)
  74441. {
  74442. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74443. angle -= PathHelpers::ellipseAngularIncrement;
  74444. }
  74445. }
  74446. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74447. }
  74448. }
  74449. void Path::addPieSegment (const float x, const float y,
  74450. const float width, const float height,
  74451. const float fromRadians,
  74452. const float toRadians,
  74453. const float innerCircleProportionalSize)
  74454. {
  74455. float radiusX = width * 0.5f;
  74456. float radiusY = height * 0.5f;
  74457. const Point<float> centre (x + radiusX, y + radiusY);
  74458. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74459. addArc (x, y, width, height, fromRadians, toRadians);
  74460. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74461. {
  74462. closeSubPath();
  74463. if (innerCircleProportionalSize > 0)
  74464. {
  74465. radiusX *= innerCircleProportionalSize;
  74466. radiusY *= innerCircleProportionalSize;
  74467. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74468. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74469. }
  74470. }
  74471. else
  74472. {
  74473. if (innerCircleProportionalSize > 0)
  74474. {
  74475. radiusX *= innerCircleProportionalSize;
  74476. radiusY *= innerCircleProportionalSize;
  74477. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74478. }
  74479. else
  74480. {
  74481. lineTo (centre);
  74482. }
  74483. }
  74484. closeSubPath();
  74485. }
  74486. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74487. {
  74488. const Line<float> reversed (line.reversed());
  74489. lineThickness *= 0.5f;
  74490. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74491. lineTo (line.getPointAlongLine (0, -lineThickness));
  74492. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74493. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74494. closeSubPath();
  74495. }
  74496. void Path::addArrow (const Line<float>& line, float lineThickness,
  74497. float arrowheadWidth, float arrowheadLength)
  74498. {
  74499. const Line<float> reversed (line.reversed());
  74500. lineThickness *= 0.5f;
  74501. arrowheadWidth *= 0.5f;
  74502. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74503. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74504. lineTo (line.getPointAlongLine (0, -lineThickness));
  74505. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74506. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74507. lineTo (line.getEnd());
  74508. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74509. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74510. closeSubPath();
  74511. }
  74512. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74513. const float radius, const float startAngle)
  74514. {
  74515. jassert (numberOfSides > 1); // this would be silly.
  74516. if (numberOfSides > 1)
  74517. {
  74518. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74519. for (int i = 0; i < numberOfSides; ++i)
  74520. {
  74521. const float angle = startAngle + i * angleBetweenPoints;
  74522. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74523. if (i == 0)
  74524. startNewSubPath (p);
  74525. else
  74526. lineTo (p);
  74527. }
  74528. closeSubPath();
  74529. }
  74530. }
  74531. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  74532. const float innerRadius, const float outerRadius, const float startAngle)
  74533. {
  74534. jassert (numberOfPoints > 1); // this would be silly.
  74535. if (numberOfPoints > 1)
  74536. {
  74537. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  74538. for (int i = 0; i < numberOfPoints; ++i)
  74539. {
  74540. const float angle = startAngle + i * angleBetweenPoints;
  74541. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  74542. if (i == 0)
  74543. startNewSubPath (p);
  74544. else
  74545. lineTo (p);
  74546. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  74547. }
  74548. closeSubPath();
  74549. }
  74550. }
  74551. void Path::addBubble (float x, float y,
  74552. float w, float h,
  74553. float cs,
  74554. float tipX,
  74555. float tipY,
  74556. int whichSide,
  74557. float arrowPos,
  74558. float arrowWidth)
  74559. {
  74560. if (w > 1.0f && h > 1.0f)
  74561. {
  74562. cs = jmin (cs, w * 0.5f, h * 0.5f);
  74563. const float cs2 = 2.0f * cs;
  74564. startNewSubPath (x + cs, y);
  74565. if (whichSide == 0)
  74566. {
  74567. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74568. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74569. lineTo (arrowX1, y);
  74570. lineTo (tipX, tipY);
  74571. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  74572. }
  74573. lineTo (x + w - cs, y);
  74574. if (cs > 0.0f)
  74575. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  74576. if (whichSide == 3)
  74577. {
  74578. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74579. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74580. lineTo (x + w, arrowY1);
  74581. lineTo (tipX, tipY);
  74582. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  74583. }
  74584. lineTo (x + w, y + h - cs);
  74585. if (cs > 0.0f)
  74586. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  74587. if (whichSide == 2)
  74588. {
  74589. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74590. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74591. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  74592. lineTo (tipX, tipY);
  74593. lineTo (arrowX1, y + h);
  74594. }
  74595. lineTo (x + cs, y + h);
  74596. if (cs > 0.0f)
  74597. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  74598. if (whichSide == 1)
  74599. {
  74600. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74601. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74602. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  74603. lineTo (tipX, tipY);
  74604. lineTo (x, arrowY1);
  74605. }
  74606. lineTo (x, y + cs);
  74607. if (cs > 0.0f)
  74608. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  74609. closeSubPath();
  74610. }
  74611. }
  74612. void Path::addPath (const Path& other)
  74613. {
  74614. size_t i = 0;
  74615. while (i < other.numElements)
  74616. {
  74617. const float type = other.data.elements [i++];
  74618. if (type == moveMarker)
  74619. {
  74620. startNewSubPath (other.data.elements [i],
  74621. other.data.elements [i + 1]);
  74622. i += 2;
  74623. }
  74624. else if (type == lineMarker)
  74625. {
  74626. lineTo (other.data.elements [i],
  74627. other.data.elements [i + 1]);
  74628. i += 2;
  74629. }
  74630. else if (type == quadMarker)
  74631. {
  74632. quadraticTo (other.data.elements [i],
  74633. other.data.elements [i + 1],
  74634. other.data.elements [i + 2],
  74635. other.data.elements [i + 3]);
  74636. i += 4;
  74637. }
  74638. else if (type == cubicMarker)
  74639. {
  74640. cubicTo (other.data.elements [i],
  74641. other.data.elements [i + 1],
  74642. other.data.elements [i + 2],
  74643. other.data.elements [i + 3],
  74644. other.data.elements [i + 4],
  74645. other.data.elements [i + 5]);
  74646. i += 6;
  74647. }
  74648. else if (type == closeSubPathMarker)
  74649. {
  74650. closeSubPath();
  74651. }
  74652. else
  74653. {
  74654. // something's gone wrong with the element list!
  74655. jassertfalse;
  74656. }
  74657. }
  74658. }
  74659. void Path::addPath (const Path& other,
  74660. const AffineTransform& transformToApply)
  74661. {
  74662. size_t i = 0;
  74663. while (i < other.numElements)
  74664. {
  74665. const float type = other.data.elements [i++];
  74666. if (type == closeSubPathMarker)
  74667. {
  74668. closeSubPath();
  74669. }
  74670. else
  74671. {
  74672. float x = other.data.elements [i++];
  74673. float y = other.data.elements [i++];
  74674. transformToApply.transformPoint (x, y);
  74675. if (type == moveMarker)
  74676. {
  74677. startNewSubPath (x, y);
  74678. }
  74679. else if (type == lineMarker)
  74680. {
  74681. lineTo (x, y);
  74682. }
  74683. else if (type == quadMarker)
  74684. {
  74685. float x2 = other.data.elements [i++];
  74686. float y2 = other.data.elements [i++];
  74687. transformToApply.transformPoint (x2, y2);
  74688. quadraticTo (x, y, x2, y2);
  74689. }
  74690. else if (type == cubicMarker)
  74691. {
  74692. float x2 = other.data.elements [i++];
  74693. float y2 = other.data.elements [i++];
  74694. float x3 = other.data.elements [i++];
  74695. float y3 = other.data.elements [i++];
  74696. transformToApply.transformPoints (x2, y2, x3, y3);
  74697. cubicTo (x, y, x2, y2, x3, y3);
  74698. }
  74699. else
  74700. {
  74701. // something's gone wrong with the element list!
  74702. jassertfalse;
  74703. }
  74704. }
  74705. }
  74706. }
  74707. void Path::applyTransform (const AffineTransform& transform) throw()
  74708. {
  74709. size_t i = 0;
  74710. pathYMin = pathXMin = 0;
  74711. pathYMax = pathXMax = 0;
  74712. bool setMaxMin = false;
  74713. while (i < numElements)
  74714. {
  74715. const float type = data.elements [i++];
  74716. if (type == moveMarker)
  74717. {
  74718. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74719. if (setMaxMin)
  74720. {
  74721. pathXMin = jmin (pathXMin, data.elements [i]);
  74722. pathXMax = jmax (pathXMax, data.elements [i]);
  74723. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74724. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74725. }
  74726. else
  74727. {
  74728. pathXMin = pathXMax = data.elements [i];
  74729. pathYMin = pathYMax = data.elements [i + 1];
  74730. setMaxMin = true;
  74731. }
  74732. i += 2;
  74733. }
  74734. else if (type == lineMarker)
  74735. {
  74736. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74737. pathXMin = jmin (pathXMin, data.elements [i]);
  74738. pathXMax = jmax (pathXMax, data.elements [i]);
  74739. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74740. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74741. i += 2;
  74742. }
  74743. else if (type == quadMarker)
  74744. {
  74745. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74746. data.elements [i + 2], data.elements [i + 3]);
  74747. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74748. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74749. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74750. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74751. i += 4;
  74752. }
  74753. else if (type == cubicMarker)
  74754. {
  74755. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74756. data.elements [i + 2], data.elements [i + 3],
  74757. data.elements [i + 4], data.elements [i + 5]);
  74758. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74759. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74760. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74761. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74762. i += 6;
  74763. }
  74764. }
  74765. }
  74766. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74767. const float w, const float h,
  74768. const bool preserveProportions,
  74769. const Justification& justification) const
  74770. {
  74771. Rectangle<float> bounds (getBounds());
  74772. if (preserveProportions)
  74773. {
  74774. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74775. return AffineTransform::identity;
  74776. float newW, newH;
  74777. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74778. if (srcRatio > h / w)
  74779. {
  74780. newW = h / srcRatio;
  74781. newH = h;
  74782. }
  74783. else
  74784. {
  74785. newW = w;
  74786. newH = w * srcRatio;
  74787. }
  74788. float newXCentre = x;
  74789. float newYCentre = y;
  74790. if (justification.testFlags (Justification::left))
  74791. newXCentre += newW * 0.5f;
  74792. else if (justification.testFlags (Justification::right))
  74793. newXCentre += w - newW * 0.5f;
  74794. else
  74795. newXCentre += w * 0.5f;
  74796. if (justification.testFlags (Justification::top))
  74797. newYCentre += newH * 0.5f;
  74798. else if (justification.testFlags (Justification::bottom))
  74799. newYCentre += h - newH * 0.5f;
  74800. else
  74801. newYCentre += h * 0.5f;
  74802. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  74803. bounds.getHeight() * -0.5f - bounds.getY())
  74804. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  74805. .translated (newXCentre, newYCentre);
  74806. }
  74807. else
  74808. {
  74809. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  74810. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  74811. .translated (x, y);
  74812. }
  74813. }
  74814. bool Path::contains (const float x, const float y, const float tolerance) const
  74815. {
  74816. if (x <= pathXMin || x >= pathXMax
  74817. || y <= pathYMin || y >= pathYMax)
  74818. return false;
  74819. PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
  74820. int positiveCrossings = 0;
  74821. int negativeCrossings = 0;
  74822. while (i.next())
  74823. {
  74824. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  74825. {
  74826. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  74827. if (intersectX <= x)
  74828. {
  74829. if (i.y1 < i.y2)
  74830. ++positiveCrossings;
  74831. else
  74832. ++negativeCrossings;
  74833. }
  74834. }
  74835. }
  74836. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  74837. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  74838. }
  74839. bool Path::contains (const Point<float>& point, const float tolerance) const
  74840. {
  74841. return contains (point.getX(), point.getY(), tolerance);
  74842. }
  74843. bool Path::intersectsLine (const Line<float>& line, const float tolerance)
  74844. {
  74845. PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
  74846. Point<float> intersection;
  74847. while (i.next())
  74848. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74849. return true;
  74850. return false;
  74851. }
  74852. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  74853. {
  74854. Line<float> result (line);
  74855. const bool startInside = contains (line.getStart());
  74856. const bool endInside = contains (line.getEnd());
  74857. if (startInside == endInside)
  74858. {
  74859. if (keepSectionOutsidePath == startInside)
  74860. result = Line<float>();
  74861. }
  74862. else
  74863. {
  74864. PathFlatteningIterator i (*this, AffineTransform::identity);
  74865. Point<float> intersection;
  74866. while (i.next())
  74867. {
  74868. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74869. {
  74870. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  74871. result.setStart (intersection);
  74872. else
  74873. result.setEnd (intersection);
  74874. }
  74875. }
  74876. }
  74877. return result;
  74878. }
  74879. float Path::getLength (const AffineTransform& transform) const
  74880. {
  74881. float length = 0;
  74882. PathFlatteningIterator i (*this, transform);
  74883. while (i.next())
  74884. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  74885. return length;
  74886. }
  74887. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  74888. {
  74889. PathFlatteningIterator i (*this, transform);
  74890. while (i.next())
  74891. {
  74892. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74893. const float lineLength = line.getLength();
  74894. if (distanceFromStart <= lineLength)
  74895. return line.getPointAlongLine (distanceFromStart);
  74896. distanceFromStart -= lineLength;
  74897. }
  74898. return Point<float> (i.x2, i.y2);
  74899. }
  74900. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  74901. const AffineTransform& transform) const
  74902. {
  74903. PathFlatteningIterator i (*this, transform);
  74904. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  74905. float length = 0;
  74906. Point<float> pointOnLine;
  74907. while (i.next())
  74908. {
  74909. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74910. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  74911. if (distance < bestDistance)
  74912. {
  74913. bestDistance = distance;
  74914. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  74915. pointOnPath = pointOnLine;
  74916. }
  74917. length += line.getLength();
  74918. }
  74919. return bestPosition;
  74920. }
  74921. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  74922. {
  74923. if (cornerRadius <= 0.01f)
  74924. return *this;
  74925. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  74926. size_t n = 0;
  74927. bool lastWasLine = false, firstWasLine = false;
  74928. Path p;
  74929. while (n < numElements)
  74930. {
  74931. const float type = data.elements [n++];
  74932. if (type == moveMarker)
  74933. {
  74934. indexOfPathStart = p.numElements;
  74935. indexOfPathStartThis = n - 1;
  74936. const float x = data.elements [n++];
  74937. const float y = data.elements [n++];
  74938. p.startNewSubPath (x, y);
  74939. lastWasLine = false;
  74940. firstWasLine = (data.elements [n] == lineMarker);
  74941. }
  74942. else if (type == lineMarker || type == closeSubPathMarker)
  74943. {
  74944. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  74945. if (type == lineMarker)
  74946. {
  74947. endX = data.elements [n++];
  74948. endY = data.elements [n++];
  74949. if (n > 8)
  74950. {
  74951. startX = data.elements [n - 8];
  74952. startY = data.elements [n - 7];
  74953. joinX = data.elements [n - 5];
  74954. joinY = data.elements [n - 4];
  74955. }
  74956. }
  74957. else
  74958. {
  74959. endX = data.elements [indexOfPathStartThis + 1];
  74960. endY = data.elements [indexOfPathStartThis + 2];
  74961. if (n > 6)
  74962. {
  74963. startX = data.elements [n - 6];
  74964. startY = data.elements [n - 5];
  74965. joinX = data.elements [n - 3];
  74966. joinY = data.elements [n - 2];
  74967. }
  74968. }
  74969. if (lastWasLine)
  74970. {
  74971. const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
  74972. if (len1 > 0)
  74973. {
  74974. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74975. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74976. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74977. }
  74978. const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
  74979. if (len2 > 0)
  74980. {
  74981. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74982. p.quadraticTo (joinX, joinY,
  74983. (float) (joinX + (endX - joinX) * propNeeded),
  74984. (float) (joinY + (endY - joinY) * propNeeded));
  74985. }
  74986. p.lineTo (endX, endY);
  74987. }
  74988. else if (type == lineMarker)
  74989. {
  74990. p.lineTo (endX, endY);
  74991. lastWasLine = true;
  74992. }
  74993. if (type == closeSubPathMarker)
  74994. {
  74995. if (firstWasLine)
  74996. {
  74997. startX = data.elements [n - 3];
  74998. startY = data.elements [n - 2];
  74999. joinX = endX;
  75000. joinY = endY;
  75001. endX = data.elements [indexOfPathStartThis + 4];
  75002. endY = data.elements [indexOfPathStartThis + 5];
  75003. const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
  75004. if (len1 > 0)
  75005. {
  75006. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75007. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75008. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75009. }
  75010. const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
  75011. if (len2 > 0)
  75012. {
  75013. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75014. endX = (float) (joinX + (endX - joinX) * propNeeded);
  75015. endY = (float) (joinY + (endY - joinY) * propNeeded);
  75016. p.quadraticTo (joinX, joinY, endX, endY);
  75017. p.data.elements [indexOfPathStart + 1] = endX;
  75018. p.data.elements [indexOfPathStart + 2] = endY;
  75019. }
  75020. }
  75021. p.closeSubPath();
  75022. }
  75023. }
  75024. else if (type == quadMarker)
  75025. {
  75026. lastWasLine = false;
  75027. const float x1 = data.elements [n++];
  75028. const float y1 = data.elements [n++];
  75029. const float x2 = data.elements [n++];
  75030. const float y2 = data.elements [n++];
  75031. p.quadraticTo (x1, y1, x2, y2);
  75032. }
  75033. else if (type == cubicMarker)
  75034. {
  75035. lastWasLine = false;
  75036. const float x1 = data.elements [n++];
  75037. const float y1 = data.elements [n++];
  75038. const float x2 = data.elements [n++];
  75039. const float y2 = data.elements [n++];
  75040. const float x3 = data.elements [n++];
  75041. const float y3 = data.elements [n++];
  75042. p.cubicTo (x1, y1, x2, y2, x3, y3);
  75043. }
  75044. }
  75045. return p;
  75046. }
  75047. void Path::loadPathFromStream (InputStream& source)
  75048. {
  75049. while (! source.isExhausted())
  75050. {
  75051. switch (source.readByte())
  75052. {
  75053. case 'm':
  75054. {
  75055. const float x = source.readFloat();
  75056. const float y = source.readFloat();
  75057. startNewSubPath (x, y);
  75058. break;
  75059. }
  75060. case 'l':
  75061. {
  75062. const float x = source.readFloat();
  75063. const float y = source.readFloat();
  75064. lineTo (x, y);
  75065. break;
  75066. }
  75067. case 'q':
  75068. {
  75069. const float x1 = source.readFloat();
  75070. const float y1 = source.readFloat();
  75071. const float x2 = source.readFloat();
  75072. const float y2 = source.readFloat();
  75073. quadraticTo (x1, y1, x2, y2);
  75074. break;
  75075. }
  75076. case 'b':
  75077. {
  75078. const float x1 = source.readFloat();
  75079. const float y1 = source.readFloat();
  75080. const float x2 = source.readFloat();
  75081. const float y2 = source.readFloat();
  75082. const float x3 = source.readFloat();
  75083. const float y3 = source.readFloat();
  75084. cubicTo (x1, y1, x2, y2, x3, y3);
  75085. break;
  75086. }
  75087. case 'c':
  75088. closeSubPath();
  75089. break;
  75090. case 'n':
  75091. useNonZeroWinding = true;
  75092. break;
  75093. case 'z':
  75094. useNonZeroWinding = false;
  75095. break;
  75096. case 'e':
  75097. return; // end of path marker
  75098. default:
  75099. jassertfalse; // illegal char in the stream
  75100. break;
  75101. }
  75102. }
  75103. }
  75104. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  75105. {
  75106. MemoryInputStream in (pathData, numberOfBytes, false);
  75107. loadPathFromStream (in);
  75108. }
  75109. void Path::writePathToStream (OutputStream& dest) const
  75110. {
  75111. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  75112. size_t i = 0;
  75113. while (i < numElements)
  75114. {
  75115. const float type = data.elements [i++];
  75116. if (type == moveMarker)
  75117. {
  75118. dest.writeByte ('m');
  75119. dest.writeFloat (data.elements [i++]);
  75120. dest.writeFloat (data.elements [i++]);
  75121. }
  75122. else if (type == lineMarker)
  75123. {
  75124. dest.writeByte ('l');
  75125. dest.writeFloat (data.elements [i++]);
  75126. dest.writeFloat (data.elements [i++]);
  75127. }
  75128. else if (type == quadMarker)
  75129. {
  75130. dest.writeByte ('q');
  75131. dest.writeFloat (data.elements [i++]);
  75132. dest.writeFloat (data.elements [i++]);
  75133. dest.writeFloat (data.elements [i++]);
  75134. dest.writeFloat (data.elements [i++]);
  75135. }
  75136. else if (type == cubicMarker)
  75137. {
  75138. dest.writeByte ('b');
  75139. dest.writeFloat (data.elements [i++]);
  75140. dest.writeFloat (data.elements [i++]);
  75141. dest.writeFloat (data.elements [i++]);
  75142. dest.writeFloat (data.elements [i++]);
  75143. dest.writeFloat (data.elements [i++]);
  75144. dest.writeFloat (data.elements [i++]);
  75145. }
  75146. else if (type == closeSubPathMarker)
  75147. {
  75148. dest.writeByte ('c');
  75149. }
  75150. }
  75151. dest.writeByte ('e'); // marks the end-of-path
  75152. }
  75153. const String Path::toString() const
  75154. {
  75155. MemoryOutputStream s (2048);
  75156. if (! useNonZeroWinding)
  75157. s << 'a';
  75158. size_t i = 0;
  75159. float lastMarker = 0.0f;
  75160. while (i < numElements)
  75161. {
  75162. const float marker = data.elements [i++];
  75163. char markerChar = 0;
  75164. int numCoords = 0;
  75165. if (marker == moveMarker)
  75166. {
  75167. markerChar = 'm';
  75168. numCoords = 2;
  75169. }
  75170. else if (marker == lineMarker)
  75171. {
  75172. markerChar = 'l';
  75173. numCoords = 2;
  75174. }
  75175. else if (marker == quadMarker)
  75176. {
  75177. markerChar = 'q';
  75178. numCoords = 4;
  75179. }
  75180. else if (marker == cubicMarker)
  75181. {
  75182. markerChar = 'c';
  75183. numCoords = 6;
  75184. }
  75185. else
  75186. {
  75187. jassert (marker == closeSubPathMarker);
  75188. markerChar = 'z';
  75189. }
  75190. if (marker != lastMarker)
  75191. {
  75192. if (s.getDataSize() != 0)
  75193. s << ' ';
  75194. s << markerChar;
  75195. lastMarker = marker;
  75196. }
  75197. while (--numCoords >= 0 && i < numElements)
  75198. {
  75199. String coord (data.elements [i++], 3);
  75200. while (coord.endsWithChar ('0') && coord != "0")
  75201. coord = coord.dropLastCharacters (1);
  75202. if (coord.endsWithChar ('.'))
  75203. coord = coord.dropLastCharacters (1);
  75204. if (s.getDataSize() != 0)
  75205. s << ' ';
  75206. s << coord;
  75207. }
  75208. }
  75209. return s.toUTF8();
  75210. }
  75211. void Path::restoreFromString (const String& stringVersion)
  75212. {
  75213. clear();
  75214. setUsingNonZeroWinding (true);
  75215. String::CharPointerType t (stringVersion.getCharPointer());
  75216. juce_wchar marker = 'm';
  75217. int numValues = 2;
  75218. float values [6];
  75219. for (;;)
  75220. {
  75221. const String token (PathHelpers::nextToken (t));
  75222. const juce_wchar firstChar = token[0];
  75223. int startNum = 0;
  75224. if (firstChar == 0)
  75225. break;
  75226. if (firstChar == 'm' || firstChar == 'l')
  75227. {
  75228. marker = firstChar;
  75229. numValues = 2;
  75230. }
  75231. else if (firstChar == 'q')
  75232. {
  75233. marker = firstChar;
  75234. numValues = 4;
  75235. }
  75236. else if (firstChar == 'c')
  75237. {
  75238. marker = firstChar;
  75239. numValues = 6;
  75240. }
  75241. else if (firstChar == 'z')
  75242. {
  75243. marker = firstChar;
  75244. numValues = 0;
  75245. }
  75246. else if (firstChar == 'a')
  75247. {
  75248. setUsingNonZeroWinding (false);
  75249. continue;
  75250. }
  75251. else
  75252. {
  75253. ++startNum;
  75254. values [0] = token.getFloatValue();
  75255. }
  75256. for (int i = startNum; i < numValues; ++i)
  75257. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75258. switch (marker)
  75259. {
  75260. case 'm': startNewSubPath (values[0], values[1]); break;
  75261. case 'l': lineTo (values[0], values[1]); break;
  75262. case 'q': quadraticTo (values[0], values[1], values[2], values[3]); break;
  75263. case 'c': cubicTo (values[0], values[1], values[2], values[3], values[4], values[5]); break;
  75264. case 'z': closeSubPath(); break;
  75265. default: jassertfalse; break; // illegal string format?
  75266. }
  75267. }
  75268. }
  75269. Path::Iterator::Iterator (const Path& path_)
  75270. : path (path_),
  75271. index (0)
  75272. {
  75273. }
  75274. Path::Iterator::~Iterator()
  75275. {
  75276. }
  75277. bool Path::Iterator::next()
  75278. {
  75279. const float* const elements = path.data.elements;
  75280. if (index < path.numElements)
  75281. {
  75282. const float type = elements [index++];
  75283. if (type == moveMarker)
  75284. {
  75285. elementType = startNewSubPath;
  75286. x1 = elements [index++];
  75287. y1 = elements [index++];
  75288. }
  75289. else if (type == lineMarker)
  75290. {
  75291. elementType = lineTo;
  75292. x1 = elements [index++];
  75293. y1 = elements [index++];
  75294. }
  75295. else if (type == quadMarker)
  75296. {
  75297. elementType = quadraticTo;
  75298. x1 = elements [index++];
  75299. y1 = elements [index++];
  75300. x2 = elements [index++];
  75301. y2 = elements [index++];
  75302. }
  75303. else if (type == cubicMarker)
  75304. {
  75305. elementType = cubicTo;
  75306. x1 = elements [index++];
  75307. y1 = elements [index++];
  75308. x2 = elements [index++];
  75309. y2 = elements [index++];
  75310. x3 = elements [index++];
  75311. y3 = elements [index++];
  75312. }
  75313. else if (type == closeSubPathMarker)
  75314. {
  75315. elementType = closePath;
  75316. }
  75317. return true;
  75318. }
  75319. return false;
  75320. }
  75321. END_JUCE_NAMESPACE
  75322. /*** End of inlined file: juce_Path.cpp ***/
  75323. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75324. BEGIN_JUCE_NAMESPACE
  75325. #if JUCE_MSVC && JUCE_DEBUG
  75326. #pragma optimize ("t", on)
  75327. #endif
  75328. const float PathFlatteningIterator::defaultTolerance = 0.6f;
  75329. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75330. const AffineTransform& transform_,
  75331. const float tolerance)
  75332. : x2 (0),
  75333. y2 (0),
  75334. closesSubPath (false),
  75335. subPathIndex (-1),
  75336. path (path_),
  75337. transform (transform_),
  75338. points (path_.data.elements),
  75339. toleranceSquared (tolerance * tolerance),
  75340. subPathCloseX (0),
  75341. subPathCloseY (0),
  75342. isIdentityTransform (transform_.isIdentity()),
  75343. stackBase (32),
  75344. index (0),
  75345. stackSize (32)
  75346. {
  75347. stackPos = stackBase;
  75348. }
  75349. PathFlatteningIterator::~PathFlatteningIterator()
  75350. {
  75351. }
  75352. bool PathFlatteningIterator::next()
  75353. {
  75354. x1 = x2;
  75355. y1 = y2;
  75356. float x3 = 0;
  75357. float y3 = 0;
  75358. float x4 = 0;
  75359. float y4 = 0;
  75360. float type;
  75361. for (;;)
  75362. {
  75363. if (stackPos == stackBase)
  75364. {
  75365. if (index >= path.numElements)
  75366. {
  75367. return false;
  75368. }
  75369. else
  75370. {
  75371. type = points [index++];
  75372. if (type != Path::closeSubPathMarker)
  75373. {
  75374. x2 = points [index++];
  75375. y2 = points [index++];
  75376. if (type == Path::quadMarker)
  75377. {
  75378. x3 = points [index++];
  75379. y3 = points [index++];
  75380. if (! isIdentityTransform)
  75381. transform.transformPoints (x2, y2, x3, y3);
  75382. }
  75383. else if (type == Path::cubicMarker)
  75384. {
  75385. x3 = points [index++];
  75386. y3 = points [index++];
  75387. x4 = points [index++];
  75388. y4 = points [index++];
  75389. if (! isIdentityTransform)
  75390. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75391. }
  75392. else
  75393. {
  75394. if (! isIdentityTransform)
  75395. transform.transformPoint (x2, y2);
  75396. }
  75397. }
  75398. }
  75399. }
  75400. else
  75401. {
  75402. type = *--stackPos;
  75403. if (type != Path::closeSubPathMarker)
  75404. {
  75405. x2 = *--stackPos;
  75406. y2 = *--stackPos;
  75407. if (type == Path::quadMarker)
  75408. {
  75409. x3 = *--stackPos;
  75410. y3 = *--stackPos;
  75411. }
  75412. else if (type == Path::cubicMarker)
  75413. {
  75414. x3 = *--stackPos;
  75415. y3 = *--stackPos;
  75416. x4 = *--stackPos;
  75417. y4 = *--stackPos;
  75418. }
  75419. }
  75420. }
  75421. if (type == Path::lineMarker)
  75422. {
  75423. ++subPathIndex;
  75424. closesSubPath = (stackPos == stackBase)
  75425. && (index < path.numElements)
  75426. && (points [index] == Path::closeSubPathMarker)
  75427. && x2 == subPathCloseX
  75428. && y2 == subPathCloseY;
  75429. return true;
  75430. }
  75431. else if (type == Path::quadMarker)
  75432. {
  75433. const size_t offset = (size_t) (stackPos - stackBase);
  75434. if (offset >= stackSize - 10)
  75435. {
  75436. stackSize <<= 1;
  75437. stackBase.realloc (stackSize);
  75438. stackPos = stackBase + offset;
  75439. }
  75440. const float m1x = (x1 + x2) * 0.5f;
  75441. const float m1y = (y1 + y2) * 0.5f;
  75442. const float m2x = (x2 + x3) * 0.5f;
  75443. const float m2y = (y2 + y3) * 0.5f;
  75444. const float m3x = (m1x + m2x) * 0.5f;
  75445. const float m3y = (m1y + m2y) * 0.5f;
  75446. const float errorX = m3x - x2;
  75447. const float errorY = m3y - y2;
  75448. if (errorX * errorX + errorY * errorY > toleranceSquared)
  75449. {
  75450. *stackPos++ = y3;
  75451. *stackPos++ = x3;
  75452. *stackPos++ = m2y;
  75453. *stackPos++ = m2x;
  75454. *stackPos++ = Path::quadMarker;
  75455. *stackPos++ = m3y;
  75456. *stackPos++ = m3x;
  75457. *stackPos++ = m1y;
  75458. *stackPos++ = m1x;
  75459. *stackPos++ = Path::quadMarker;
  75460. }
  75461. else
  75462. {
  75463. *stackPos++ = y3;
  75464. *stackPos++ = x3;
  75465. *stackPos++ = Path::lineMarker;
  75466. *stackPos++ = m3y;
  75467. *stackPos++ = m3x;
  75468. *stackPos++ = Path::lineMarker;
  75469. }
  75470. jassert (stackPos < stackBase + stackSize);
  75471. }
  75472. else if (type == Path::cubicMarker)
  75473. {
  75474. const size_t offset = (size_t) (stackPos - stackBase);
  75475. if (offset >= stackSize - 16)
  75476. {
  75477. stackSize <<= 1;
  75478. stackBase.realloc (stackSize);
  75479. stackPos = stackBase + offset;
  75480. }
  75481. const float m1x = (x1 + x2) * 0.5f;
  75482. const float m1y = (y1 + y2) * 0.5f;
  75483. const float m2x = (x3 + x2) * 0.5f;
  75484. const float m2y = (y3 + y2) * 0.5f;
  75485. const float m3x = (x3 + x4) * 0.5f;
  75486. const float m3y = (y3 + y4) * 0.5f;
  75487. const float m4x = (m1x + m2x) * 0.5f;
  75488. const float m4y = (m1y + m2y) * 0.5f;
  75489. const float m5x = (m3x + m2x) * 0.5f;
  75490. const float m5y = (m3y + m2y) * 0.5f;
  75491. const float error1X = m4x - x2;
  75492. const float error1Y = m4y - y2;
  75493. const float error2X = m5x - x3;
  75494. const float error2Y = m5y - y3;
  75495. if (error1X * error1X + error1Y * error1Y > toleranceSquared
  75496. || error2X * error2X + error2Y * error2Y > toleranceSquared)
  75497. {
  75498. *stackPos++ = y4;
  75499. *stackPos++ = x4;
  75500. *stackPos++ = m3y;
  75501. *stackPos++ = m3x;
  75502. *stackPos++ = m5y;
  75503. *stackPos++ = m5x;
  75504. *stackPos++ = Path::cubicMarker;
  75505. *stackPos++ = (m4y + m5y) * 0.5f;
  75506. *stackPos++ = (m4x + m5x) * 0.5f;
  75507. *stackPos++ = m4y;
  75508. *stackPos++ = m4x;
  75509. *stackPos++ = m1y;
  75510. *stackPos++ = m1x;
  75511. *stackPos++ = Path::cubicMarker;
  75512. }
  75513. else
  75514. {
  75515. *stackPos++ = y4;
  75516. *stackPos++ = x4;
  75517. *stackPos++ = Path::lineMarker;
  75518. *stackPos++ = m5y;
  75519. *stackPos++ = m5x;
  75520. *stackPos++ = Path::lineMarker;
  75521. *stackPos++ = m4y;
  75522. *stackPos++ = m4x;
  75523. *stackPos++ = Path::lineMarker;
  75524. }
  75525. }
  75526. else if (type == Path::closeSubPathMarker)
  75527. {
  75528. if (x2 != subPathCloseX || y2 != subPathCloseY)
  75529. {
  75530. x1 = x2;
  75531. y1 = y2;
  75532. x2 = subPathCloseX;
  75533. y2 = subPathCloseY;
  75534. closesSubPath = true;
  75535. return true;
  75536. }
  75537. }
  75538. else
  75539. {
  75540. jassert (type == Path::moveMarker);
  75541. subPathIndex = -1;
  75542. subPathCloseX = x1 = x2;
  75543. subPathCloseY = y1 = y2;
  75544. }
  75545. }
  75546. }
  75547. #if JUCE_MSVC && JUCE_DEBUG
  75548. #pragma optimize ("", on) // resets optimisations to the project defaults
  75549. #endif
  75550. END_JUCE_NAMESPACE
  75551. /*** End of inlined file: juce_PathIterator.cpp ***/
  75552. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  75553. BEGIN_JUCE_NAMESPACE
  75554. PathStrokeType::PathStrokeType (const float strokeThickness,
  75555. const JointStyle jointStyle_,
  75556. const EndCapStyle endStyle_) throw()
  75557. : thickness (strokeThickness),
  75558. jointStyle (jointStyle_),
  75559. endStyle (endStyle_)
  75560. {
  75561. }
  75562. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  75563. : thickness (other.thickness),
  75564. jointStyle (other.jointStyle),
  75565. endStyle (other.endStyle)
  75566. {
  75567. }
  75568. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  75569. {
  75570. thickness = other.thickness;
  75571. jointStyle = other.jointStyle;
  75572. endStyle = other.endStyle;
  75573. return *this;
  75574. }
  75575. PathStrokeType::~PathStrokeType() throw()
  75576. {
  75577. }
  75578. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  75579. {
  75580. return thickness == other.thickness
  75581. && jointStyle == other.jointStyle
  75582. && endStyle == other.endStyle;
  75583. }
  75584. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  75585. {
  75586. return ! operator== (other);
  75587. }
  75588. namespace PathStrokeHelpers
  75589. {
  75590. bool lineIntersection (const float x1, const float y1,
  75591. const float x2, const float y2,
  75592. const float x3, const float y3,
  75593. const float x4, const float y4,
  75594. float& intersectionX,
  75595. float& intersectionY,
  75596. float& distanceBeyondLine1EndSquared) throw()
  75597. {
  75598. if (x2 != x3 || y2 != y3)
  75599. {
  75600. const float dx1 = x2 - x1;
  75601. const float dy1 = y2 - y1;
  75602. const float dx2 = x4 - x3;
  75603. const float dy2 = y4 - y3;
  75604. const float divisor = dx1 * dy2 - dx2 * dy1;
  75605. if (divisor == 0)
  75606. {
  75607. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75608. {
  75609. if (dy1 == 0 && dy2 != 0)
  75610. {
  75611. const float along = (y1 - y3) / dy2;
  75612. intersectionX = x3 + along * dx2;
  75613. intersectionY = y1;
  75614. distanceBeyondLine1EndSquared = intersectionX - x2;
  75615. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75616. if ((x2 > x1) == (intersectionX < x2))
  75617. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75618. return along >= 0 && along <= 1.0f;
  75619. }
  75620. else if (dy2 == 0 && dy1 != 0)
  75621. {
  75622. const float along = (y3 - y1) / dy1;
  75623. intersectionX = x1 + along * dx1;
  75624. intersectionY = y3;
  75625. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75626. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75627. if (along < 1.0f)
  75628. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75629. return along >= 0 && along <= 1.0f;
  75630. }
  75631. else if (dx1 == 0 && dx2 != 0)
  75632. {
  75633. const float along = (x1 - x3) / dx2;
  75634. intersectionX = x1;
  75635. intersectionY = y3 + along * dy2;
  75636. distanceBeyondLine1EndSquared = intersectionY - y2;
  75637. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75638. if ((y2 > y1) == (intersectionY < y2))
  75639. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75640. return along >= 0 && along <= 1.0f;
  75641. }
  75642. else if (dx2 == 0 && dx1 != 0)
  75643. {
  75644. const float along = (x3 - x1) / dx1;
  75645. intersectionX = x3;
  75646. intersectionY = y1 + along * dy1;
  75647. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75648. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75649. if (along < 1.0f)
  75650. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75651. return along >= 0 && along <= 1.0f;
  75652. }
  75653. }
  75654. intersectionX = 0.5f * (x2 + x3);
  75655. intersectionY = 0.5f * (y2 + y3);
  75656. distanceBeyondLine1EndSquared = 0.0f;
  75657. return false;
  75658. }
  75659. else
  75660. {
  75661. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75662. intersectionX = x1 + along1 * dx1;
  75663. intersectionY = y1 + along1 * dy1;
  75664. if (along1 >= 0 && along1 <= 1.0f)
  75665. {
  75666. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75667. if (along2 >= 0 && along2 <= divisor)
  75668. {
  75669. distanceBeyondLine1EndSquared = 0.0f;
  75670. return true;
  75671. }
  75672. }
  75673. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75674. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75675. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75676. if (along1 < 1.0f)
  75677. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75678. return false;
  75679. }
  75680. }
  75681. intersectionX = x2;
  75682. intersectionY = y2;
  75683. distanceBeyondLine1EndSquared = 0.0f;
  75684. return true;
  75685. }
  75686. void addEdgeAndJoint (Path& destPath,
  75687. const PathStrokeType::JointStyle style,
  75688. const float maxMiterExtensionSquared, const float width,
  75689. const float x1, const float y1,
  75690. const float x2, const float y2,
  75691. const float x3, const float y3,
  75692. const float x4, const float y4,
  75693. const float midX, const float midY)
  75694. {
  75695. if (style == PathStrokeType::beveled
  75696. || (x3 == x4 && y3 == y4)
  75697. || (x1 == x2 && y1 == y2))
  75698. {
  75699. destPath.lineTo (x2, y2);
  75700. destPath.lineTo (x3, y3);
  75701. }
  75702. else
  75703. {
  75704. float jx, jy, distanceBeyondLine1EndSquared;
  75705. // if they intersect, use this point..
  75706. if (lineIntersection (x1, y1, x2, y2,
  75707. x3, y3, x4, y4,
  75708. jx, jy, distanceBeyondLine1EndSquared))
  75709. {
  75710. destPath.lineTo (jx, jy);
  75711. }
  75712. else
  75713. {
  75714. if (style == PathStrokeType::mitered)
  75715. {
  75716. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75717. && distanceBeyondLine1EndSquared > 0.0f)
  75718. {
  75719. destPath.lineTo (jx, jy);
  75720. }
  75721. else
  75722. {
  75723. // the end sticks out too far, so just use a blunt joint
  75724. destPath.lineTo (x2, y2);
  75725. destPath.lineTo (x3, y3);
  75726. }
  75727. }
  75728. else
  75729. {
  75730. // curved joints
  75731. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75732. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75733. const float angleIncrement = 0.1f;
  75734. destPath.lineTo (x2, y2);
  75735. if (std::abs (angle1 - angle2) > angleIncrement)
  75736. {
  75737. if (angle2 > angle1 + float_Pi
  75738. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75739. {
  75740. if (angle2 > angle1)
  75741. angle2 -= float_Pi * 2.0f;
  75742. jassert (angle1 <= angle2 + float_Pi);
  75743. angle1 -= angleIncrement;
  75744. while (angle1 > angle2)
  75745. {
  75746. destPath.lineTo (midX + width * std::sin (angle1),
  75747. midY + width * std::cos (angle1));
  75748. angle1 -= angleIncrement;
  75749. }
  75750. }
  75751. else
  75752. {
  75753. if (angle1 > angle2)
  75754. angle1 -= float_Pi * 2.0f;
  75755. jassert (angle1 >= angle2 - float_Pi);
  75756. angle1 += angleIncrement;
  75757. while (angle1 < angle2)
  75758. {
  75759. destPath.lineTo (midX + width * std::sin (angle1),
  75760. midY + width * std::cos (angle1));
  75761. angle1 += angleIncrement;
  75762. }
  75763. }
  75764. }
  75765. destPath.lineTo (x3, y3);
  75766. }
  75767. }
  75768. }
  75769. }
  75770. void addLineEnd (Path& destPath,
  75771. const PathStrokeType::EndCapStyle style,
  75772. const float x1, const float y1,
  75773. const float x2, const float y2,
  75774. const float width)
  75775. {
  75776. if (style == PathStrokeType::butt)
  75777. {
  75778. destPath.lineTo (x2, y2);
  75779. }
  75780. else
  75781. {
  75782. float offx1, offy1, offx2, offy2;
  75783. float dx = x2 - x1;
  75784. float dy = y2 - y1;
  75785. const float len = juce_hypot (dx, dy);
  75786. if (len == 0)
  75787. {
  75788. offx1 = offx2 = x1;
  75789. offy1 = offy2 = y1;
  75790. }
  75791. else
  75792. {
  75793. const float offset = width / len;
  75794. dx *= offset;
  75795. dy *= offset;
  75796. offx1 = x1 + dy;
  75797. offy1 = y1 - dx;
  75798. offx2 = x2 + dy;
  75799. offy2 = y2 - dx;
  75800. }
  75801. if (style == PathStrokeType::square)
  75802. {
  75803. // sqaure ends
  75804. destPath.lineTo (offx1, offy1);
  75805. destPath.lineTo (offx2, offy2);
  75806. destPath.lineTo (x2, y2);
  75807. }
  75808. else
  75809. {
  75810. // rounded ends
  75811. const float midx = (offx1 + offx2) * 0.5f;
  75812. const float midy = (offy1 + offy2) * 0.5f;
  75813. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  75814. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  75815. midx, midy);
  75816. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  75817. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  75818. x2, y2);
  75819. }
  75820. }
  75821. }
  75822. struct Arrowhead
  75823. {
  75824. float startWidth, startLength;
  75825. float endWidth, endLength;
  75826. };
  75827. void addArrowhead (Path& destPath,
  75828. const float x1, const float y1,
  75829. const float x2, const float y2,
  75830. const float tipX, const float tipY,
  75831. const float width,
  75832. const float arrowheadWidth)
  75833. {
  75834. Line<float> line (x1, y1, x2, y2);
  75835. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  75836. destPath.lineTo (tipX, tipY);
  75837. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  75838. destPath.lineTo (x2, y2);
  75839. }
  75840. struct LineSection
  75841. {
  75842. float x1, y1, x2, y2; // original line
  75843. float lx1, ly1, lx2, ly2; // the left-hand stroke
  75844. float rx1, ry1, rx2, ry2; // the right-hand stroke
  75845. };
  75846. void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  75847. {
  75848. while (amountAtEnd > 0 && subPath.size() > 0)
  75849. {
  75850. LineSection& l = subPath.getReference (subPath.size() - 1);
  75851. float dx = l.rx2 - l.rx1;
  75852. float dy = l.ry2 - l.ry1;
  75853. const float len = juce_hypot (dx, dy);
  75854. if (len <= amountAtEnd && subPath.size() > 1)
  75855. {
  75856. LineSection& prev = subPath.getReference (subPath.size() - 2);
  75857. prev.x2 = l.x2;
  75858. prev.y2 = l.y2;
  75859. subPath.removeLast();
  75860. amountAtEnd -= len;
  75861. }
  75862. else
  75863. {
  75864. const float prop = jmin (0.9999f, amountAtEnd / len);
  75865. dx *= prop;
  75866. dy *= prop;
  75867. l.rx1 += dx;
  75868. l.ry1 += dy;
  75869. l.lx2 += dx;
  75870. l.ly2 += dy;
  75871. break;
  75872. }
  75873. }
  75874. while (amountAtStart > 0 && subPath.size() > 0)
  75875. {
  75876. LineSection& l = subPath.getReference (0);
  75877. float dx = l.rx2 - l.rx1;
  75878. float dy = l.ry2 - l.ry1;
  75879. const float len = juce_hypot (dx, dy);
  75880. if (len <= amountAtStart && subPath.size() > 1)
  75881. {
  75882. LineSection& next = subPath.getReference (1);
  75883. next.x1 = l.x1;
  75884. next.y1 = l.y1;
  75885. subPath.remove (0);
  75886. amountAtStart -= len;
  75887. }
  75888. else
  75889. {
  75890. const float prop = jmin (0.9999f, amountAtStart / len);
  75891. dx *= prop;
  75892. dy *= prop;
  75893. l.rx2 -= dx;
  75894. l.ry2 -= dy;
  75895. l.lx1 -= dx;
  75896. l.ly1 -= dy;
  75897. break;
  75898. }
  75899. }
  75900. }
  75901. void addSubPath (Path& destPath, Array<LineSection>& subPath,
  75902. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  75903. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  75904. const Arrowhead* const arrowhead)
  75905. {
  75906. jassert (subPath.size() > 0);
  75907. if (arrowhead != 0)
  75908. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  75909. const LineSection& firstLine = subPath.getReference (0);
  75910. float lastX1 = firstLine.lx1;
  75911. float lastY1 = firstLine.ly1;
  75912. float lastX2 = firstLine.lx2;
  75913. float lastY2 = firstLine.ly2;
  75914. if (isClosed)
  75915. {
  75916. destPath.startNewSubPath (lastX1, lastY1);
  75917. }
  75918. else
  75919. {
  75920. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  75921. if (arrowhead != 0)
  75922. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  75923. width, arrowhead->startWidth);
  75924. else
  75925. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  75926. }
  75927. int i;
  75928. for (i = 1; i < subPath.size(); ++i)
  75929. {
  75930. const LineSection& l = subPath.getReference (i);
  75931. addEdgeAndJoint (destPath, jointStyle,
  75932. maxMiterExtensionSquared, width,
  75933. lastX1, lastY1, lastX2, lastY2,
  75934. l.lx1, l.ly1, l.lx2, l.ly2,
  75935. l.x1, l.y1);
  75936. lastX1 = l.lx1;
  75937. lastY1 = l.ly1;
  75938. lastX2 = l.lx2;
  75939. lastY2 = l.ly2;
  75940. }
  75941. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  75942. if (isClosed)
  75943. {
  75944. const LineSection& l = subPath.getReference (0);
  75945. addEdgeAndJoint (destPath, jointStyle,
  75946. maxMiterExtensionSquared, width,
  75947. lastX1, lastY1, lastX2, lastY2,
  75948. l.lx1, l.ly1, l.lx2, l.ly2,
  75949. l.x1, l.y1);
  75950. destPath.closeSubPath();
  75951. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  75952. }
  75953. else
  75954. {
  75955. destPath.lineTo (lastX2, lastY2);
  75956. if (arrowhead != 0)
  75957. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  75958. width, arrowhead->endWidth);
  75959. else
  75960. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  75961. }
  75962. lastX1 = lastLine.rx1;
  75963. lastY1 = lastLine.ry1;
  75964. lastX2 = lastLine.rx2;
  75965. lastY2 = lastLine.ry2;
  75966. for (i = subPath.size() - 1; --i >= 0;)
  75967. {
  75968. const LineSection& l = subPath.getReference (i);
  75969. addEdgeAndJoint (destPath, jointStyle,
  75970. maxMiterExtensionSquared, width,
  75971. lastX1, lastY1, lastX2, lastY2,
  75972. l.rx1, l.ry1, l.rx2, l.ry2,
  75973. l.x2, l.y2);
  75974. lastX1 = l.rx1;
  75975. lastY1 = l.ry1;
  75976. lastX2 = l.rx2;
  75977. lastY2 = l.ry2;
  75978. }
  75979. if (isClosed)
  75980. {
  75981. addEdgeAndJoint (destPath, jointStyle,
  75982. maxMiterExtensionSquared, width,
  75983. lastX1, lastY1, lastX2, lastY2,
  75984. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  75985. lastLine.x2, lastLine.y2);
  75986. }
  75987. else
  75988. {
  75989. // do the last line
  75990. destPath.lineTo (lastX2, lastY2);
  75991. }
  75992. destPath.closeSubPath();
  75993. }
  75994. void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  75995. const PathStrokeType::EndCapStyle endStyle,
  75996. Path& destPath, const Path& source,
  75997. const AffineTransform& transform,
  75998. const float extraAccuracy, const Arrowhead* const arrowhead)
  75999. {
  76000. jassert (extraAccuracy > 0);
  76001. if (thickness <= 0)
  76002. {
  76003. destPath.clear();
  76004. return;
  76005. }
  76006. const Path* sourcePath = &source;
  76007. Path temp;
  76008. if (sourcePath == &destPath)
  76009. {
  76010. destPath.swapWithPath (temp);
  76011. sourcePath = &temp;
  76012. }
  76013. else
  76014. {
  76015. destPath.clear();
  76016. }
  76017. destPath.setUsingNonZeroWinding (true);
  76018. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  76019. const float width = 0.5f * thickness;
  76020. // Iterate the path, creating a list of the
  76021. // left/right-hand lines along either side of it...
  76022. PathFlatteningIterator it (*sourcePath, transform, PathFlatteningIterator::defaultTolerance / extraAccuracy);
  76023. Array <LineSection> subPath;
  76024. subPath.ensureStorageAllocated (512);
  76025. LineSection l;
  76026. l.x1 = 0;
  76027. l.y1 = 0;
  76028. const float minSegmentLength = 0.0001f;
  76029. while (it.next())
  76030. {
  76031. if (it.subPathIndex == 0)
  76032. {
  76033. if (subPath.size() > 0)
  76034. {
  76035. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76036. subPath.clearQuick();
  76037. }
  76038. l.x1 = it.x1;
  76039. l.y1 = it.y1;
  76040. }
  76041. l.x2 = it.x2;
  76042. l.y2 = it.y2;
  76043. float dx = l.x2 - l.x1;
  76044. float dy = l.y2 - l.y1;
  76045. const float hypotSquared = dx*dx + dy*dy;
  76046. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  76047. {
  76048. const float len = std::sqrt (hypotSquared);
  76049. if (len == 0)
  76050. {
  76051. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  76052. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  76053. }
  76054. else
  76055. {
  76056. const float offset = width / len;
  76057. dx *= offset;
  76058. dy *= offset;
  76059. l.rx2 = l.x1 - dy;
  76060. l.ry2 = l.y1 + dx;
  76061. l.lx1 = l.x1 + dy;
  76062. l.ly1 = l.y1 - dx;
  76063. l.lx2 = l.x2 + dy;
  76064. l.ly2 = l.y2 - dx;
  76065. l.rx1 = l.x2 - dy;
  76066. l.ry1 = l.y2 + dx;
  76067. }
  76068. subPath.add (l);
  76069. if (it.closesSubPath)
  76070. {
  76071. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76072. subPath.clearQuick();
  76073. }
  76074. else
  76075. {
  76076. l.x1 = it.x2;
  76077. l.y1 = it.y2;
  76078. }
  76079. }
  76080. }
  76081. if (subPath.size() > 0)
  76082. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76083. }
  76084. }
  76085. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  76086. const AffineTransform& transform, const float extraAccuracy) const
  76087. {
  76088. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  76089. transform, extraAccuracy, 0);
  76090. }
  76091. void PathStrokeType::createDashedStroke (Path& destPath,
  76092. const Path& sourcePath,
  76093. const float* dashLengths,
  76094. int numDashLengths,
  76095. const AffineTransform& transform,
  76096. const float extraAccuracy) const
  76097. {
  76098. jassert (extraAccuracy > 0);
  76099. if (thickness <= 0)
  76100. return;
  76101. // this should really be an even number..
  76102. jassert ((numDashLengths & 1) == 0);
  76103. Path newDestPath;
  76104. PathFlatteningIterator it (sourcePath, transform, PathFlatteningIterator::defaultTolerance / extraAccuracy);
  76105. bool first = true;
  76106. int dashNum = 0;
  76107. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  76108. float dx = 0.0f, dy = 0.0f;
  76109. for (;;)
  76110. {
  76111. const bool isSolid = ((dashNum & 1) == 0);
  76112. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  76113. jassert (dashLen > 0); // must be a positive increment!
  76114. if (dashLen <= 0)
  76115. break;
  76116. pos += dashLen;
  76117. while (pos > lineEndPos)
  76118. {
  76119. if (! it.next())
  76120. {
  76121. if (isSolid && ! first)
  76122. newDestPath.lineTo (it.x2, it.y2);
  76123. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76124. return;
  76125. }
  76126. if (isSolid && ! first)
  76127. newDestPath.lineTo (it.x1, it.y1);
  76128. else
  76129. newDestPath.startNewSubPath (it.x1, it.y1);
  76130. dx = it.x2 - it.x1;
  76131. dy = it.y2 - it.y1;
  76132. lineLen = juce_hypot (dx, dy);
  76133. lineEndPos += lineLen;
  76134. first = it.closesSubPath;
  76135. }
  76136. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76137. if (isSolid)
  76138. newDestPath.lineTo (it.x1 + dx * alpha,
  76139. it.y1 + dy * alpha);
  76140. else
  76141. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76142. it.y1 + dy * alpha);
  76143. }
  76144. }
  76145. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76146. const Path& sourcePath,
  76147. const float arrowheadStartWidth, const float arrowheadStartLength,
  76148. const float arrowheadEndWidth, const float arrowheadEndLength,
  76149. const AffineTransform& transform,
  76150. const float extraAccuracy) const
  76151. {
  76152. PathStrokeHelpers::Arrowhead head;
  76153. head.startWidth = arrowheadStartWidth;
  76154. head.startLength = arrowheadStartLength;
  76155. head.endWidth = arrowheadEndWidth;
  76156. head.endLength = arrowheadEndLength;
  76157. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76158. destPath, sourcePath, transform, extraAccuracy, &head);
  76159. }
  76160. END_JUCE_NAMESPACE
  76161. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76162. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76163. BEGIN_JUCE_NAMESPACE
  76164. RectangleList::RectangleList() throw()
  76165. {
  76166. }
  76167. RectangleList::RectangleList (const Rectangle<int>& rect)
  76168. {
  76169. if (! rect.isEmpty())
  76170. rects.add (rect);
  76171. }
  76172. RectangleList::RectangleList (const RectangleList& other)
  76173. : rects (other.rects)
  76174. {
  76175. }
  76176. RectangleList& RectangleList::operator= (const RectangleList& other)
  76177. {
  76178. rects = other.rects;
  76179. return *this;
  76180. }
  76181. RectangleList::~RectangleList()
  76182. {
  76183. }
  76184. void RectangleList::clear()
  76185. {
  76186. rects.clearQuick();
  76187. }
  76188. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76189. {
  76190. if (isPositiveAndBelow (index, rects.size()))
  76191. return rects.getReference (index);
  76192. return Rectangle<int>();
  76193. }
  76194. bool RectangleList::isEmpty() const throw()
  76195. {
  76196. return rects.size() == 0;
  76197. }
  76198. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76199. : current (0),
  76200. owner (list),
  76201. index (list.rects.size())
  76202. {
  76203. }
  76204. RectangleList::Iterator::~Iterator()
  76205. {
  76206. }
  76207. bool RectangleList::Iterator::next() throw()
  76208. {
  76209. if (--index >= 0)
  76210. {
  76211. current = & (owner.rects.getReference (index));
  76212. return true;
  76213. }
  76214. return false;
  76215. }
  76216. void RectangleList::add (const Rectangle<int>& rect)
  76217. {
  76218. if (! rect.isEmpty())
  76219. {
  76220. if (rects.size() == 0)
  76221. {
  76222. rects.add (rect);
  76223. }
  76224. else
  76225. {
  76226. bool anyOverlaps = false;
  76227. int i;
  76228. for (i = rects.size(); --i >= 0;)
  76229. {
  76230. Rectangle<int>& ourRect = rects.getReference (i);
  76231. if (rect.intersects (ourRect))
  76232. {
  76233. if (rect.contains (ourRect))
  76234. rects.remove (i);
  76235. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76236. anyOverlaps = true;
  76237. }
  76238. }
  76239. if (anyOverlaps && rects.size() > 0)
  76240. {
  76241. RectangleList r (rect);
  76242. for (i = rects.size(); --i >= 0;)
  76243. {
  76244. const Rectangle<int>& ourRect = rects.getReference (i);
  76245. if (rect.intersects (ourRect))
  76246. {
  76247. r.subtract (ourRect);
  76248. if (r.rects.size() == 0)
  76249. return;
  76250. }
  76251. }
  76252. for (i = r.getNumRectangles(); --i >= 0;)
  76253. rects.add (r.rects.getReference (i));
  76254. }
  76255. else
  76256. {
  76257. rects.add (rect);
  76258. }
  76259. }
  76260. }
  76261. }
  76262. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76263. {
  76264. if (! rect.isEmpty())
  76265. rects.add (rect);
  76266. }
  76267. void RectangleList::add (const int x, const int y, const int w, const int h)
  76268. {
  76269. if (rects.size() == 0)
  76270. {
  76271. if (w > 0 && h > 0)
  76272. rects.add (Rectangle<int> (x, y, w, h));
  76273. }
  76274. else
  76275. {
  76276. add (Rectangle<int> (x, y, w, h));
  76277. }
  76278. }
  76279. void RectangleList::add (const RectangleList& other)
  76280. {
  76281. for (int i = 0; i < other.rects.size(); ++i)
  76282. add (other.rects.getReference (i));
  76283. }
  76284. void RectangleList::subtract (const Rectangle<int>& rect)
  76285. {
  76286. const int originalNumRects = rects.size();
  76287. if (originalNumRects > 0)
  76288. {
  76289. const int x1 = rect.x;
  76290. const int y1 = rect.y;
  76291. const int x2 = x1 + rect.w;
  76292. const int y2 = y1 + rect.h;
  76293. for (int i = getNumRectangles(); --i >= 0;)
  76294. {
  76295. Rectangle<int>& r = rects.getReference (i);
  76296. const int rx1 = r.x;
  76297. const int ry1 = r.y;
  76298. const int rx2 = rx1 + r.w;
  76299. const int ry2 = ry1 + r.h;
  76300. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76301. {
  76302. if (x1 > rx1 && x1 < rx2)
  76303. {
  76304. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76305. {
  76306. r.w = x1 - rx1;
  76307. }
  76308. else
  76309. {
  76310. r.x = x1;
  76311. r.w = rx2 - x1;
  76312. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76313. i += 2;
  76314. }
  76315. }
  76316. else if (x2 > rx1 && x2 < rx2)
  76317. {
  76318. r.x = x2;
  76319. r.w = rx2 - x2;
  76320. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76321. {
  76322. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76323. i += 2;
  76324. }
  76325. }
  76326. else if (y1 > ry1 && y1 < ry2)
  76327. {
  76328. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76329. {
  76330. r.h = y1 - ry1;
  76331. }
  76332. else
  76333. {
  76334. r.y = y1;
  76335. r.h = ry2 - y1;
  76336. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76337. i += 2;
  76338. }
  76339. }
  76340. else if (y2 > ry1 && y2 < ry2)
  76341. {
  76342. r.y = y2;
  76343. r.h = ry2 - y2;
  76344. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76345. {
  76346. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76347. i += 2;
  76348. }
  76349. }
  76350. else
  76351. {
  76352. rects.remove (i);
  76353. }
  76354. }
  76355. }
  76356. }
  76357. }
  76358. bool RectangleList::subtract (const RectangleList& otherList)
  76359. {
  76360. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76361. subtract (otherList.rects.getReference (i));
  76362. return rects.size() > 0;
  76363. }
  76364. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76365. {
  76366. bool notEmpty = false;
  76367. if (rect.isEmpty())
  76368. {
  76369. clear();
  76370. }
  76371. else
  76372. {
  76373. for (int i = rects.size(); --i >= 0;)
  76374. {
  76375. Rectangle<int>& r = rects.getReference (i);
  76376. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76377. rects.remove (i);
  76378. else
  76379. notEmpty = true;
  76380. }
  76381. }
  76382. return notEmpty;
  76383. }
  76384. bool RectangleList::clipTo (const RectangleList& other)
  76385. {
  76386. if (rects.size() == 0)
  76387. return false;
  76388. RectangleList result;
  76389. for (int j = 0; j < rects.size(); ++j)
  76390. {
  76391. const Rectangle<int>& rect = rects.getReference (j);
  76392. for (int i = other.rects.size(); --i >= 0;)
  76393. {
  76394. Rectangle<int> r (other.rects.getReference (i));
  76395. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76396. result.rects.add (r);
  76397. }
  76398. }
  76399. swapWith (result);
  76400. return ! isEmpty();
  76401. }
  76402. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76403. {
  76404. destRegion.clear();
  76405. if (! rect.isEmpty())
  76406. {
  76407. for (int i = rects.size(); --i >= 0;)
  76408. {
  76409. Rectangle<int> r (rects.getReference (i));
  76410. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76411. destRegion.rects.add (r);
  76412. }
  76413. }
  76414. return destRegion.rects.size() > 0;
  76415. }
  76416. void RectangleList::swapWith (RectangleList& otherList) throw()
  76417. {
  76418. rects.swapWithArray (otherList.rects);
  76419. }
  76420. void RectangleList::consolidate()
  76421. {
  76422. int i;
  76423. for (i = 0; i < getNumRectangles() - 1; ++i)
  76424. {
  76425. Rectangle<int>& r = rects.getReference (i);
  76426. const int rx1 = r.x;
  76427. const int ry1 = r.y;
  76428. const int rx2 = rx1 + r.w;
  76429. const int ry2 = ry1 + r.h;
  76430. for (int j = rects.size(); --j > i;)
  76431. {
  76432. Rectangle<int>& r2 = rects.getReference (j);
  76433. const int jrx1 = r2.x;
  76434. const int jry1 = r2.y;
  76435. const int jrx2 = jrx1 + r2.w;
  76436. const int jry2 = jry1 + r2.h;
  76437. // if the vertical edges of any blocks are touching and their horizontals don't
  76438. // line up, split them horizontally..
  76439. if (jrx1 == rx2 || jrx2 == rx1)
  76440. {
  76441. if (jry1 > ry1 && jry1 < ry2)
  76442. {
  76443. r.h = jry1 - ry1;
  76444. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76445. i = -1;
  76446. break;
  76447. }
  76448. if (jry2 > ry1 && jry2 < ry2)
  76449. {
  76450. r.h = jry2 - ry1;
  76451. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76452. i = -1;
  76453. break;
  76454. }
  76455. else if (ry1 > jry1 && ry1 < jry2)
  76456. {
  76457. r2.h = ry1 - jry1;
  76458. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76459. i = -1;
  76460. break;
  76461. }
  76462. else if (ry2 > jry1 && ry2 < jry2)
  76463. {
  76464. r2.h = ry2 - jry1;
  76465. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76466. i = -1;
  76467. break;
  76468. }
  76469. }
  76470. }
  76471. }
  76472. for (i = 0; i < rects.size() - 1; ++i)
  76473. {
  76474. Rectangle<int>& r = rects.getReference (i);
  76475. for (int j = rects.size(); --j > i;)
  76476. {
  76477. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76478. {
  76479. rects.remove (j);
  76480. i = -1;
  76481. break;
  76482. }
  76483. }
  76484. }
  76485. }
  76486. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76487. {
  76488. for (int i = getNumRectangles(); --i >= 0;)
  76489. if (rects.getReference (i).contains (x, y))
  76490. return true;
  76491. return false;
  76492. }
  76493. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  76494. {
  76495. if (rects.size() > 1)
  76496. {
  76497. RectangleList r (rectangleToCheck);
  76498. for (int i = rects.size(); --i >= 0;)
  76499. {
  76500. r.subtract (rects.getReference (i));
  76501. if (r.rects.size() == 0)
  76502. return true;
  76503. }
  76504. }
  76505. else if (rects.size() > 0)
  76506. {
  76507. return rects.getReference (0).contains (rectangleToCheck);
  76508. }
  76509. return false;
  76510. }
  76511. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  76512. {
  76513. for (int i = rects.size(); --i >= 0;)
  76514. if (rects.getReference (i).intersects (rectangleToCheck))
  76515. return true;
  76516. return false;
  76517. }
  76518. bool RectangleList::intersects (const RectangleList& other) const throw()
  76519. {
  76520. for (int i = rects.size(); --i >= 0;)
  76521. if (other.intersectsRectangle (rects.getReference (i)))
  76522. return true;
  76523. return false;
  76524. }
  76525. const Rectangle<int> RectangleList::getBounds() const throw()
  76526. {
  76527. if (rects.size() <= 1)
  76528. {
  76529. if (rects.size() == 0)
  76530. return Rectangle<int>();
  76531. else
  76532. return rects.getReference (0);
  76533. }
  76534. else
  76535. {
  76536. const Rectangle<int>& r = rects.getReference (0);
  76537. int minX = r.x;
  76538. int minY = r.y;
  76539. int maxX = minX + r.w;
  76540. int maxY = minY + r.h;
  76541. for (int i = rects.size(); --i > 0;)
  76542. {
  76543. const Rectangle<int>& r2 = rects.getReference (i);
  76544. minX = jmin (minX, r2.x);
  76545. minY = jmin (minY, r2.y);
  76546. maxX = jmax (maxX, r2.getRight());
  76547. maxY = jmax (maxY, r2.getBottom());
  76548. }
  76549. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  76550. }
  76551. }
  76552. void RectangleList::offsetAll (const int dx, const int dy) throw()
  76553. {
  76554. for (int i = rects.size(); --i >= 0;)
  76555. {
  76556. Rectangle<int>& r = rects.getReference (i);
  76557. r.x += dx;
  76558. r.y += dy;
  76559. }
  76560. }
  76561. const Path RectangleList::toPath() const
  76562. {
  76563. Path p;
  76564. for (int i = rects.size(); --i >= 0;)
  76565. {
  76566. const Rectangle<int>& r = rects.getReference (i);
  76567. p.addRectangle ((float) r.x,
  76568. (float) r.y,
  76569. (float) r.w,
  76570. (float) r.h);
  76571. }
  76572. return p;
  76573. }
  76574. END_JUCE_NAMESPACE
  76575. /*** End of inlined file: juce_RectangleList.cpp ***/
  76576. /*** Start of inlined file: juce_Image.cpp ***/
  76577. BEGIN_JUCE_NAMESPACE
  76578. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  76579. : format (format_), width (width_), height (height_)
  76580. {
  76581. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  76582. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  76583. }
  76584. Image::SharedImage::~SharedImage()
  76585. {
  76586. }
  76587. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  76588. {
  76589. return imageData + lineStride * y + pixelStride * x;
  76590. }
  76591. class SoftwareSharedImage : public Image::SharedImage
  76592. {
  76593. public:
  76594. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  76595. : Image::SharedImage (format_, width_, height_)
  76596. {
  76597. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  76598. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  76599. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  76600. imageData = imageDataAllocated;
  76601. }
  76602. Image::ImageType getType() const
  76603. {
  76604. return Image::SoftwareImage;
  76605. }
  76606. LowLevelGraphicsContext* createLowLevelContext()
  76607. {
  76608. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  76609. }
  76610. Image::SharedImage* clone()
  76611. {
  76612. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  76613. memcpy (s->imageData, imageData, lineStride * height);
  76614. return s;
  76615. }
  76616. private:
  76617. HeapBlock<uint8> imageDataAllocated;
  76618. JUCE_LEAK_DETECTOR (SoftwareSharedImage);
  76619. };
  76620. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  76621. {
  76622. return new SoftwareSharedImage (format, width, height, clearImage);
  76623. }
  76624. class SubsectionSharedImage : public Image::SharedImage
  76625. {
  76626. public:
  76627. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  76628. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  76629. image (image_), area (area_)
  76630. {
  76631. pixelStride = image_->getPixelStride();
  76632. lineStride = image_->getLineStride();
  76633. imageData = image_->getPixelData (area_.getX(), area_.getY());
  76634. }
  76635. Image::ImageType getType() const
  76636. {
  76637. return Image::SoftwareImage;
  76638. }
  76639. LowLevelGraphicsContext* createLowLevelContext()
  76640. {
  76641. LowLevelGraphicsContext* g = image->createLowLevelContext();
  76642. g->clipToRectangle (area);
  76643. g->setOrigin (area.getX(), area.getY());
  76644. return g;
  76645. }
  76646. Image::SharedImage* clone()
  76647. {
  76648. return new SubsectionSharedImage (image->clone(), area);
  76649. }
  76650. private:
  76651. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  76652. const Rectangle<int> area;
  76653. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubsectionSharedImage);
  76654. };
  76655. const Image Image::getClippedImage (const Rectangle<int>& area) const
  76656. {
  76657. if (area.contains (getBounds()))
  76658. return *this;
  76659. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  76660. if (validArea.isEmpty())
  76661. return Image::null;
  76662. return Image (new SubsectionSharedImage (image, validArea));
  76663. }
  76664. Image::Image()
  76665. {
  76666. }
  76667. Image::Image (SharedImage* const instance)
  76668. : image (instance)
  76669. {
  76670. }
  76671. Image::Image (const PixelFormat format,
  76672. const int width, const int height,
  76673. const bool clearImage, const ImageType type)
  76674. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  76675. : new SoftwareSharedImage (format, width, height, clearImage))
  76676. {
  76677. }
  76678. Image::Image (const Image& other)
  76679. : image (other.image)
  76680. {
  76681. }
  76682. Image& Image::operator= (const Image& other)
  76683. {
  76684. image = other.image;
  76685. return *this;
  76686. }
  76687. Image::~Image()
  76688. {
  76689. }
  76690. const Image Image::null;
  76691. LowLevelGraphicsContext* Image::createLowLevelContext() const
  76692. {
  76693. return image == 0 ? 0 : image->createLowLevelContext();
  76694. }
  76695. void Image::duplicateIfShared()
  76696. {
  76697. if (image != 0 && image->getReferenceCount() > 1)
  76698. image = image->clone();
  76699. }
  76700. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  76701. {
  76702. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  76703. return *this;
  76704. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  76705. Graphics g (newImage);
  76706. g.setImageResamplingQuality (quality);
  76707. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  76708. return newImage;
  76709. }
  76710. const Image Image::convertedToFormat (PixelFormat newFormat) const
  76711. {
  76712. if (image == 0 || newFormat == image->format)
  76713. return *this;
  76714. const int w = image->width, h = image->height;
  76715. Image newImage (newFormat, w, h, false, image->getType());
  76716. if (newFormat == SingleChannel)
  76717. {
  76718. if (! hasAlphaChannel())
  76719. {
  76720. newImage.clear (getBounds(), Colours::black);
  76721. }
  76722. else
  76723. {
  76724. const BitmapData destData (newImage, 0, 0, w, h, true);
  76725. const BitmapData srcData (*this, 0, 0, w, h);
  76726. for (int y = 0; y < h; ++y)
  76727. {
  76728. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  76729. uint8* dst = destData.getLinePointer (y);
  76730. for (int x = w; --x >= 0;)
  76731. {
  76732. *dst++ = src->getAlpha();
  76733. ++src;
  76734. }
  76735. }
  76736. }
  76737. }
  76738. else
  76739. {
  76740. if (hasAlphaChannel())
  76741. newImage.clear (getBounds());
  76742. Graphics g (newImage);
  76743. g.drawImageAt (*this, 0, 0);
  76744. }
  76745. return newImage;
  76746. }
  76747. NamedValueSet* Image::getProperties() const
  76748. {
  76749. return image == 0 ? 0 : &(image->userData);
  76750. }
  76751. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  76752. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76753. pixelFormat (image.getFormat()),
  76754. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76755. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76756. width (w),
  76757. height (h)
  76758. {
  76759. jassert (data != 0);
  76760. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76761. }
  76762. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  76763. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76764. pixelFormat (image.getFormat()),
  76765. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76766. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76767. width (w),
  76768. height (h)
  76769. {
  76770. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76771. }
  76772. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  76773. : data (image.image == 0 ? 0 : image.image->imageData),
  76774. pixelFormat (image.getFormat()),
  76775. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76776. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76777. width (image.getWidth()),
  76778. height (image.getHeight())
  76779. {
  76780. }
  76781. Image::BitmapData::~BitmapData()
  76782. {
  76783. }
  76784. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  76785. {
  76786. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  76787. const uint8* const pixel = getPixelPointer (x, y);
  76788. switch (pixelFormat)
  76789. {
  76790. case Image::ARGB:
  76791. {
  76792. PixelARGB p (*(const PixelARGB*) pixel);
  76793. p.unpremultiply();
  76794. return Colour (p.getARGB());
  76795. }
  76796. case Image::RGB:
  76797. return Colour (((const PixelRGB*) pixel)->getARGB());
  76798. case Image::SingleChannel:
  76799. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  76800. default:
  76801. jassertfalse;
  76802. break;
  76803. }
  76804. return Colour();
  76805. }
  76806. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  76807. {
  76808. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  76809. uint8* const pixel = getPixelPointer (x, y);
  76810. const PixelARGB col (colour.getPixelARGB());
  76811. switch (pixelFormat)
  76812. {
  76813. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  76814. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  76815. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  76816. default: jassertfalse; break;
  76817. }
  76818. }
  76819. void Image::setPixelData (int x, int y, int w, int h,
  76820. const uint8* const sourcePixelData, const int sourceLineStride)
  76821. {
  76822. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  76823. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  76824. {
  76825. const BitmapData dest (*this, x, y, w, h, true);
  76826. for (int i = 0; i < h; ++i)
  76827. {
  76828. memcpy (dest.getLinePointer(i),
  76829. sourcePixelData + sourceLineStride * i,
  76830. w * dest.pixelStride);
  76831. }
  76832. }
  76833. }
  76834. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  76835. {
  76836. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  76837. if (! clipped.isEmpty())
  76838. {
  76839. const PixelARGB col (colourToClearTo.getPixelARGB());
  76840. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  76841. uint8* dest = destData.data;
  76842. int dh = clipped.getHeight();
  76843. while (--dh >= 0)
  76844. {
  76845. uint8* line = dest;
  76846. dest += destData.lineStride;
  76847. if (isARGB())
  76848. {
  76849. for (int x = clipped.getWidth(); --x >= 0;)
  76850. {
  76851. ((PixelARGB*) line)->set (col);
  76852. line += destData.pixelStride;
  76853. }
  76854. }
  76855. else if (isRGB())
  76856. {
  76857. for (int x = clipped.getWidth(); --x >= 0;)
  76858. {
  76859. ((PixelRGB*) line)->set (col);
  76860. line += destData.pixelStride;
  76861. }
  76862. }
  76863. else
  76864. {
  76865. for (int x = clipped.getWidth(); --x >= 0;)
  76866. {
  76867. *line = col.getAlpha();
  76868. line += destData.pixelStride;
  76869. }
  76870. }
  76871. }
  76872. }
  76873. }
  76874. const Colour Image::getPixelAt (const int x, const int y) const
  76875. {
  76876. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  76877. {
  76878. const BitmapData srcData (*this, x, y, 1, 1);
  76879. return srcData.getPixelColour (0, 0);
  76880. }
  76881. return Colour();
  76882. }
  76883. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  76884. {
  76885. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  76886. {
  76887. const BitmapData destData (*this, x, y, 1, 1, true);
  76888. destData.setPixelColour (0, 0, colour);
  76889. }
  76890. }
  76891. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  76892. {
  76893. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight())
  76894. && hasAlphaChannel())
  76895. {
  76896. const BitmapData destData (*this, x, y, 1, 1, true);
  76897. if (isARGB())
  76898. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  76899. else
  76900. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  76901. }
  76902. }
  76903. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  76904. {
  76905. if (hasAlphaChannel())
  76906. {
  76907. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76908. if (isARGB())
  76909. {
  76910. for (int y = 0; y < destData.height; ++y)
  76911. {
  76912. uint8* p = destData.getLinePointer (y);
  76913. for (int x = 0; x < destData.width; ++x)
  76914. {
  76915. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  76916. p += destData.pixelStride;
  76917. }
  76918. }
  76919. }
  76920. else
  76921. {
  76922. for (int y = 0; y < destData.height; ++y)
  76923. {
  76924. uint8* p = destData.getLinePointer (y);
  76925. for (int x = 0; x < destData.width; ++x)
  76926. {
  76927. *p = (uint8) (*p * amountToMultiplyBy);
  76928. p += destData.pixelStride;
  76929. }
  76930. }
  76931. }
  76932. }
  76933. else
  76934. {
  76935. jassertfalse; // can't do this without an alpha-channel!
  76936. }
  76937. }
  76938. void Image::desaturate()
  76939. {
  76940. if (isARGB() || isRGB())
  76941. {
  76942. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76943. if (isARGB())
  76944. {
  76945. for (int y = 0; y < destData.height; ++y)
  76946. {
  76947. uint8* p = destData.getLinePointer (y);
  76948. for (int x = 0; x < destData.width; ++x)
  76949. {
  76950. ((PixelARGB*) p)->desaturate();
  76951. p += destData.pixelStride;
  76952. }
  76953. }
  76954. }
  76955. else
  76956. {
  76957. for (int y = 0; y < destData.height; ++y)
  76958. {
  76959. uint8* p = destData.getLinePointer (y);
  76960. for (int x = 0; x < destData.width; ++x)
  76961. {
  76962. ((PixelRGB*) p)->desaturate();
  76963. p += destData.pixelStride;
  76964. }
  76965. }
  76966. }
  76967. }
  76968. }
  76969. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  76970. {
  76971. if (hasAlphaChannel())
  76972. {
  76973. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  76974. SparseSet<int> pixelsOnRow;
  76975. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  76976. for (int y = 0; y < srcData.height; ++y)
  76977. {
  76978. pixelsOnRow.clear();
  76979. const uint8* lineData = srcData.getLinePointer (y);
  76980. if (isARGB())
  76981. {
  76982. for (int x = 0; x < srcData.width; ++x)
  76983. {
  76984. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  76985. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76986. lineData += srcData.pixelStride;
  76987. }
  76988. }
  76989. else
  76990. {
  76991. for (int x = 0; x < srcData.width; ++x)
  76992. {
  76993. if (*lineData >= threshold)
  76994. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76995. lineData += srcData.pixelStride;
  76996. }
  76997. }
  76998. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  76999. {
  77000. const Range<int> range (pixelsOnRow.getRange (i));
  77001. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  77002. }
  77003. result.consolidate();
  77004. }
  77005. }
  77006. else
  77007. {
  77008. result.add (0, 0, getWidth(), getHeight());
  77009. }
  77010. }
  77011. void Image::moveImageSection (int dx, int dy,
  77012. int sx, int sy,
  77013. int w, int h)
  77014. {
  77015. if (dx < 0)
  77016. {
  77017. w += dx;
  77018. sx -= dx;
  77019. dx = 0;
  77020. }
  77021. if (dy < 0)
  77022. {
  77023. h += dy;
  77024. sy -= dy;
  77025. dy = 0;
  77026. }
  77027. if (sx < 0)
  77028. {
  77029. w += sx;
  77030. dx -= sx;
  77031. sx = 0;
  77032. }
  77033. if (sy < 0)
  77034. {
  77035. h += sy;
  77036. dy -= sy;
  77037. sy = 0;
  77038. }
  77039. const int minX = jmin (dx, sx);
  77040. const int minY = jmin (dy, sy);
  77041. w = jmin (w, getWidth() - jmax (sx, dx));
  77042. h = jmin (h, getHeight() - jmax (sy, dy));
  77043. if (w > 0 && h > 0)
  77044. {
  77045. const int maxX = jmax (dx, sx) + w;
  77046. const int maxY = jmax (dy, sy) + h;
  77047. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  77048. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77049. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77050. const int lineSize = destData.pixelStride * w;
  77051. if (dy > sy)
  77052. {
  77053. while (--h >= 0)
  77054. {
  77055. const int offset = h * destData.lineStride;
  77056. memmove (dst + offset, src + offset, lineSize);
  77057. }
  77058. }
  77059. else if (dst != src)
  77060. {
  77061. while (--h >= 0)
  77062. {
  77063. memmove (dst, src, lineSize);
  77064. dst += destData.lineStride;
  77065. src += destData.lineStride;
  77066. }
  77067. }
  77068. }
  77069. }
  77070. END_JUCE_NAMESPACE
  77071. /*** End of inlined file: juce_Image.cpp ***/
  77072. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77073. BEGIN_JUCE_NAMESPACE
  77074. class ImageCache::Pimpl : public Timer,
  77075. public DeletedAtShutdown
  77076. {
  77077. public:
  77078. Pimpl()
  77079. : cacheTimeout (5000)
  77080. {
  77081. }
  77082. ~Pimpl()
  77083. {
  77084. clearSingletonInstance();
  77085. }
  77086. const Image getFromHashCode (const int64 hashCode)
  77087. {
  77088. const ScopedLock sl (lock);
  77089. for (int i = images.size(); --i >= 0;)
  77090. {
  77091. Item* const item = images.getUnchecked(i);
  77092. if (item->hashCode == hashCode)
  77093. return item->image;
  77094. }
  77095. return Image::null;
  77096. }
  77097. void addImageToCache (const Image& image, const int64 hashCode)
  77098. {
  77099. if (image.isValid())
  77100. {
  77101. if (! isTimerRunning())
  77102. startTimer (2000);
  77103. Item* const item = new Item();
  77104. item->hashCode = hashCode;
  77105. item->image = image;
  77106. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77107. const ScopedLock sl (lock);
  77108. images.add (item);
  77109. }
  77110. }
  77111. void timerCallback()
  77112. {
  77113. const uint32 now = Time::getApproximateMillisecondCounter();
  77114. const ScopedLock sl (lock);
  77115. for (int i = images.size(); --i >= 0;)
  77116. {
  77117. Item* const item = images.getUnchecked(i);
  77118. if (item->image.getReferenceCount() <= 1)
  77119. {
  77120. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77121. images.remove (i);
  77122. }
  77123. else
  77124. {
  77125. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77126. }
  77127. }
  77128. if (images.size() == 0)
  77129. stopTimer();
  77130. }
  77131. struct Item
  77132. {
  77133. Image image;
  77134. int64 hashCode;
  77135. uint32 lastUseTime;
  77136. };
  77137. int cacheTimeout;
  77138. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77139. private:
  77140. OwnedArray<Item> images;
  77141. CriticalSection lock;
  77142. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  77143. };
  77144. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77145. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77146. {
  77147. if (Pimpl::getInstanceWithoutCreating() != 0)
  77148. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77149. return Image::null;
  77150. }
  77151. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77152. {
  77153. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77154. }
  77155. const Image ImageCache::getFromFile (const File& file)
  77156. {
  77157. const int64 hashCode = file.hashCode64();
  77158. Image image (getFromHashCode (hashCode));
  77159. if (image.isNull())
  77160. {
  77161. image = ImageFileFormat::loadFrom (file);
  77162. addImageToCache (image, hashCode);
  77163. }
  77164. return image;
  77165. }
  77166. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77167. {
  77168. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77169. Image image (getFromHashCode (hashCode));
  77170. if (image.isNull())
  77171. {
  77172. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77173. addImageToCache (image, hashCode);
  77174. }
  77175. return image;
  77176. }
  77177. void ImageCache::setCacheTimeout (const int millisecs)
  77178. {
  77179. Pimpl::getInstance()->cacheTimeout = millisecs;
  77180. }
  77181. END_JUCE_NAMESPACE
  77182. /*** End of inlined file: juce_ImageCache.cpp ***/
  77183. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77184. BEGIN_JUCE_NAMESPACE
  77185. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77186. : values (size_ * size_),
  77187. size (size_)
  77188. {
  77189. clear();
  77190. }
  77191. ImageConvolutionKernel::~ImageConvolutionKernel()
  77192. {
  77193. }
  77194. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77195. {
  77196. if (isPositiveAndBelow (x, size) && isPositiveAndBelow (y, size))
  77197. return values [x + y * size];
  77198. jassertfalse;
  77199. return 0;
  77200. }
  77201. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77202. {
  77203. if (isPositiveAndBelow (x, size) && isPositiveAndBelow (y, size))
  77204. {
  77205. values [x + y * size] = value;
  77206. }
  77207. else
  77208. {
  77209. jassertfalse;
  77210. }
  77211. }
  77212. void ImageConvolutionKernel::clear()
  77213. {
  77214. for (int i = size * size; --i >= 0;)
  77215. values[i] = 0;
  77216. }
  77217. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77218. {
  77219. double currentTotal = 0.0;
  77220. for (int i = size * size; --i >= 0;)
  77221. currentTotal += values[i];
  77222. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77223. }
  77224. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77225. {
  77226. for (int i = size * size; --i >= 0;)
  77227. values[i] *= multiplier;
  77228. }
  77229. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77230. {
  77231. const double radiusFactor = -1.0 / (radius * radius * 2);
  77232. const int centre = size >> 1;
  77233. for (int y = size; --y >= 0;)
  77234. {
  77235. for (int x = size; --x >= 0;)
  77236. {
  77237. const int cx = x - centre;
  77238. const int cy = y - centre;
  77239. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77240. }
  77241. }
  77242. setOverallSum (1.0f);
  77243. }
  77244. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77245. const Image& sourceImage,
  77246. const Rectangle<int>& destinationArea) const
  77247. {
  77248. if (sourceImage == destImage)
  77249. {
  77250. destImage.duplicateIfShared();
  77251. }
  77252. else
  77253. {
  77254. if (sourceImage.getWidth() != destImage.getWidth()
  77255. || sourceImage.getHeight() != destImage.getHeight()
  77256. || sourceImage.getFormat() != destImage.getFormat())
  77257. {
  77258. jassertfalse;
  77259. return;
  77260. }
  77261. }
  77262. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77263. if (area.isEmpty())
  77264. return;
  77265. const int right = area.getRight();
  77266. const int bottom = area.getBottom();
  77267. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  77268. uint8* line = destData.data;
  77269. const Image::BitmapData srcData (sourceImage, false);
  77270. if (destData.pixelStride == 4)
  77271. {
  77272. for (int y = area.getY(); y < bottom; ++y)
  77273. {
  77274. uint8* dest = line;
  77275. line += destData.lineStride;
  77276. for (int x = area.getX(); x < right; ++x)
  77277. {
  77278. float c1 = 0;
  77279. float c2 = 0;
  77280. float c3 = 0;
  77281. float c4 = 0;
  77282. for (int yy = 0; yy < size; ++yy)
  77283. {
  77284. const int sy = y + yy - (size >> 1);
  77285. if (sy >= srcData.height)
  77286. break;
  77287. if (sy >= 0)
  77288. {
  77289. int sx = x - (size >> 1);
  77290. const uint8* src = srcData.getPixelPointer (sx, sy);
  77291. for (int xx = 0; xx < size; ++xx)
  77292. {
  77293. if (sx >= srcData.width)
  77294. break;
  77295. if (sx >= 0)
  77296. {
  77297. const float kernelMult = values [xx + yy * size];
  77298. c1 += kernelMult * *src++;
  77299. c2 += kernelMult * *src++;
  77300. c3 += kernelMult * *src++;
  77301. c4 += kernelMult * *src++;
  77302. }
  77303. else
  77304. {
  77305. src += 4;
  77306. }
  77307. ++sx;
  77308. }
  77309. }
  77310. }
  77311. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77312. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77313. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77314. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77315. }
  77316. }
  77317. }
  77318. else if (destData.pixelStride == 3)
  77319. {
  77320. for (int y = area.getY(); y < bottom; ++y)
  77321. {
  77322. uint8* dest = line;
  77323. line += destData.lineStride;
  77324. for (int x = area.getX(); x < right; ++x)
  77325. {
  77326. float c1 = 0;
  77327. float c2 = 0;
  77328. float c3 = 0;
  77329. for (int yy = 0; yy < size; ++yy)
  77330. {
  77331. const int sy = y + yy - (size >> 1);
  77332. if (sy >= srcData.height)
  77333. break;
  77334. if (sy >= 0)
  77335. {
  77336. int sx = x - (size >> 1);
  77337. const uint8* src = srcData.getPixelPointer (sx, sy);
  77338. for (int xx = 0; xx < size; ++xx)
  77339. {
  77340. if (sx >= srcData.width)
  77341. break;
  77342. if (sx >= 0)
  77343. {
  77344. const float kernelMult = values [xx + yy * size];
  77345. c1 += kernelMult * *src++;
  77346. c2 += kernelMult * *src++;
  77347. c3 += kernelMult * *src++;
  77348. }
  77349. else
  77350. {
  77351. src += 3;
  77352. }
  77353. ++sx;
  77354. }
  77355. }
  77356. }
  77357. *dest++ = (uint8) roundToInt (c1);
  77358. *dest++ = (uint8) roundToInt (c2);
  77359. *dest++ = (uint8) roundToInt (c3);
  77360. }
  77361. }
  77362. }
  77363. }
  77364. END_JUCE_NAMESPACE
  77365. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77366. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77367. BEGIN_JUCE_NAMESPACE
  77368. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77369. {
  77370. static PNGImageFormat png;
  77371. static JPEGImageFormat jpg;
  77372. static GIFImageFormat gif;
  77373. ImageFileFormat* formats[4];
  77374. int numFormats = 0;
  77375. formats [numFormats++] = &png;
  77376. formats [numFormats++] = &jpg;
  77377. formats [numFormats++] = &gif;
  77378. const int64 streamPos = input.getPosition();
  77379. for (int i = 0; i < numFormats; ++i)
  77380. {
  77381. const bool found = formats[i]->canUnderstand (input);
  77382. input.setPosition (streamPos);
  77383. if (found)
  77384. return formats[i];
  77385. }
  77386. return 0;
  77387. }
  77388. const Image ImageFileFormat::loadFrom (InputStream& input)
  77389. {
  77390. ImageFileFormat* const format = findImageFormatForStream (input);
  77391. if (format != 0)
  77392. return format->decodeImage (input);
  77393. return Image::null;
  77394. }
  77395. const Image ImageFileFormat::loadFrom (const File& file)
  77396. {
  77397. InputStream* const in = file.createInputStream();
  77398. if (in != 0)
  77399. {
  77400. BufferedInputStream b (in, 8192, true);
  77401. return loadFrom (b);
  77402. }
  77403. return Image::null;
  77404. }
  77405. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77406. {
  77407. if (rawData != 0 && numBytes > 4)
  77408. {
  77409. MemoryInputStream stream (rawData, numBytes, false);
  77410. return loadFrom (stream);
  77411. }
  77412. return Image::null;
  77413. }
  77414. END_JUCE_NAMESPACE
  77415. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77416. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77417. BEGIN_JUCE_NAMESPACE
  77418. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77419. const Image juce_loadWithCoreImage (InputStream& input);
  77420. #else
  77421. class GIFLoader
  77422. {
  77423. public:
  77424. GIFLoader (InputStream& in)
  77425. : input (in),
  77426. dataBlockIsZero (false),
  77427. fresh (false),
  77428. finished (false)
  77429. {
  77430. currentBit = lastBit = lastByteIndex = 0;
  77431. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77432. firstcode = oldcode = 0;
  77433. clearCode = end_code = 0;
  77434. int imageWidth, imageHeight;
  77435. int transparent = -1;
  77436. if (! getSizeFromHeader (imageWidth, imageHeight))
  77437. return;
  77438. if ((imageWidth <= 0) || (imageHeight <= 0))
  77439. return;
  77440. unsigned char buf [16];
  77441. if (in.read (buf, 3) != 3)
  77442. return;
  77443. int numColours = 2 << (buf[0] & 7);
  77444. if ((buf[0] & 0x80) != 0)
  77445. readPalette (numColours);
  77446. for (;;)
  77447. {
  77448. if (input.read (buf, 1) != 1 || buf[0] == ';')
  77449. break;
  77450. if (buf[0] == '!')
  77451. {
  77452. if (input.read (buf, 1) != 1)
  77453. break;
  77454. if (processExtension (buf[0], transparent) < 0)
  77455. break;
  77456. continue;
  77457. }
  77458. if (buf[0] != ',')
  77459. continue;
  77460. if (input.read (buf, 9) != 9)
  77461. break;
  77462. imageWidth = makeWord (buf[4], buf[5]);
  77463. imageHeight = makeWord (buf[6], buf[7]);
  77464. numColours = 2 << (buf[8] & 7);
  77465. if ((buf[8] & 0x80) != 0)
  77466. if (! readPalette (numColours))
  77467. break;
  77468. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77469. imageWidth, imageHeight, (transparent >= 0));
  77470. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  77471. readImage ((buf[8] & 0x40) != 0, transparent);
  77472. break;
  77473. }
  77474. }
  77475. ~GIFLoader() {}
  77476. Image image;
  77477. private:
  77478. InputStream& input;
  77479. uint8 buffer [300];
  77480. uint8 palette [256][4];
  77481. bool dataBlockIsZero, fresh, finished;
  77482. int currentBit, lastBit, lastByteIndex;
  77483. int codeSize, setCodeSize;
  77484. int maxCode, maxCodeSize;
  77485. int firstcode, oldcode;
  77486. int clearCode, end_code;
  77487. enum { maxGifCode = 1 << 12 };
  77488. int table [2] [maxGifCode];
  77489. int stack [2 * maxGifCode];
  77490. int *sp;
  77491. bool getSizeFromHeader (int& w, int& h)
  77492. {
  77493. char b[8];
  77494. if (input.read (b, 6) == 6)
  77495. {
  77496. if ((strncmp ("GIF87a", b, 6) == 0)
  77497. || (strncmp ("GIF89a", b, 6) == 0))
  77498. {
  77499. if (input.read (b, 4) == 4)
  77500. {
  77501. w = makeWord (b[0], b[1]);
  77502. h = makeWord (b[2], b[3]);
  77503. return true;
  77504. }
  77505. }
  77506. }
  77507. return false;
  77508. }
  77509. bool readPalette (const int numCols)
  77510. {
  77511. unsigned char rgb[4];
  77512. for (int i = 0; i < numCols; ++i)
  77513. {
  77514. input.read (rgb, 3);
  77515. palette [i][0] = rgb[0];
  77516. palette [i][1] = rgb[1];
  77517. palette [i][2] = rgb[2];
  77518. palette [i][3] = 0xff;
  77519. }
  77520. return true;
  77521. }
  77522. int readDataBlock (unsigned char* dest)
  77523. {
  77524. unsigned char n;
  77525. if (input.read (&n, 1) == 1)
  77526. {
  77527. dataBlockIsZero = (n == 0);
  77528. if (dataBlockIsZero || (input.read (dest, n) == n))
  77529. return n;
  77530. }
  77531. return -1;
  77532. }
  77533. int processExtension (const int type, int& transparent)
  77534. {
  77535. unsigned char b [300];
  77536. int n = 0;
  77537. if (type == 0xf9)
  77538. {
  77539. n = readDataBlock (b);
  77540. if (n < 0)
  77541. return 1;
  77542. if ((b[0] & 0x1) != 0)
  77543. transparent = b[3];
  77544. }
  77545. do
  77546. {
  77547. n = readDataBlock (b);
  77548. }
  77549. while (n > 0);
  77550. return n;
  77551. }
  77552. int readLZWByte (const bool initialise, const int inputCodeSize)
  77553. {
  77554. int code, incode, i;
  77555. if (initialise)
  77556. {
  77557. setCodeSize = inputCodeSize;
  77558. codeSize = setCodeSize + 1;
  77559. clearCode = 1 << setCodeSize;
  77560. end_code = clearCode + 1;
  77561. maxCodeSize = 2 * clearCode;
  77562. maxCode = clearCode + 2;
  77563. getCode (0, true);
  77564. fresh = true;
  77565. for (i = 0; i < clearCode; ++i)
  77566. {
  77567. table[0][i] = 0;
  77568. table[1][i] = i;
  77569. }
  77570. for (; i < maxGifCode; ++i)
  77571. {
  77572. table[0][i] = 0;
  77573. table[1][i] = 0;
  77574. }
  77575. sp = stack;
  77576. return 0;
  77577. }
  77578. else if (fresh)
  77579. {
  77580. fresh = false;
  77581. do
  77582. {
  77583. firstcode = oldcode
  77584. = getCode (codeSize, false);
  77585. }
  77586. while (firstcode == clearCode);
  77587. return firstcode;
  77588. }
  77589. if (sp > stack)
  77590. return *--sp;
  77591. while ((code = getCode (codeSize, false)) >= 0)
  77592. {
  77593. if (code == clearCode)
  77594. {
  77595. for (i = 0; i < clearCode; ++i)
  77596. {
  77597. table[0][i] = 0;
  77598. table[1][i] = i;
  77599. }
  77600. for (; i < maxGifCode; ++i)
  77601. {
  77602. table[0][i] = 0;
  77603. table[1][i] = 0;
  77604. }
  77605. codeSize = setCodeSize + 1;
  77606. maxCodeSize = 2 * clearCode;
  77607. maxCode = clearCode + 2;
  77608. sp = stack;
  77609. firstcode = oldcode = getCode (codeSize, false);
  77610. return firstcode;
  77611. }
  77612. else if (code == end_code)
  77613. {
  77614. if (dataBlockIsZero)
  77615. return -2;
  77616. unsigned char buf [260];
  77617. int n;
  77618. while ((n = readDataBlock (buf)) > 0)
  77619. {}
  77620. if (n != 0)
  77621. return -2;
  77622. }
  77623. incode = code;
  77624. if (code >= maxCode)
  77625. {
  77626. *sp++ = firstcode;
  77627. code = oldcode;
  77628. }
  77629. while (code >= clearCode)
  77630. {
  77631. *sp++ = table[1][code];
  77632. if (code == table[0][code])
  77633. return -2;
  77634. code = table[0][code];
  77635. }
  77636. *sp++ = firstcode = table[1][code];
  77637. if ((code = maxCode) < maxGifCode)
  77638. {
  77639. table[0][code] = oldcode;
  77640. table[1][code] = firstcode;
  77641. ++maxCode;
  77642. if ((maxCode >= maxCodeSize)
  77643. && (maxCodeSize < maxGifCode))
  77644. {
  77645. maxCodeSize <<= 1;
  77646. ++codeSize;
  77647. }
  77648. }
  77649. oldcode = incode;
  77650. if (sp > stack)
  77651. return *--sp;
  77652. }
  77653. return code;
  77654. }
  77655. int getCode (const int codeSize_, const bool initialise)
  77656. {
  77657. if (initialise)
  77658. {
  77659. currentBit = 0;
  77660. lastBit = 0;
  77661. finished = false;
  77662. return 0;
  77663. }
  77664. if ((currentBit + codeSize_) >= lastBit)
  77665. {
  77666. if (finished)
  77667. return -1;
  77668. buffer[0] = buffer [lastByteIndex - 2];
  77669. buffer[1] = buffer [lastByteIndex - 1];
  77670. const int n = readDataBlock (&buffer[2]);
  77671. if (n == 0)
  77672. finished = true;
  77673. lastByteIndex = 2 + n;
  77674. currentBit = (currentBit - lastBit) + 16;
  77675. lastBit = (2 + n) * 8 ;
  77676. }
  77677. int result = 0;
  77678. int i = currentBit;
  77679. for (int j = 0; j < codeSize_; ++j)
  77680. {
  77681. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  77682. ++i;
  77683. }
  77684. currentBit += codeSize_;
  77685. return result;
  77686. }
  77687. bool readImage (const int interlace, const int transparent)
  77688. {
  77689. unsigned char c;
  77690. if (input.read (&c, 1) != 1
  77691. || readLZWByte (true, c) < 0)
  77692. return false;
  77693. if (transparent >= 0)
  77694. {
  77695. palette [transparent][0] = 0;
  77696. palette [transparent][1] = 0;
  77697. palette [transparent][2] = 0;
  77698. palette [transparent][3] = 0;
  77699. }
  77700. int index;
  77701. int xpos = 0, ypos = 0, pass = 0;
  77702. const Image::BitmapData destData (image, true);
  77703. uint8* p = destData.data;
  77704. const bool hasAlpha = image.hasAlphaChannel();
  77705. while ((index = readLZWByte (false, c)) >= 0)
  77706. {
  77707. const uint8* const paletteEntry = palette [index];
  77708. if (hasAlpha)
  77709. {
  77710. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  77711. paletteEntry[0],
  77712. paletteEntry[1],
  77713. paletteEntry[2]);
  77714. ((PixelARGB*) p)->premultiply();
  77715. }
  77716. else
  77717. {
  77718. ((PixelRGB*) p)->setARGB (0,
  77719. paletteEntry[0],
  77720. paletteEntry[1],
  77721. paletteEntry[2]);
  77722. }
  77723. p += destData.pixelStride;
  77724. ++xpos;
  77725. if (xpos == destData.width)
  77726. {
  77727. xpos = 0;
  77728. if (interlace)
  77729. {
  77730. switch (pass)
  77731. {
  77732. case 0:
  77733. case 1: ypos += 8; break;
  77734. case 2: ypos += 4; break;
  77735. case 3: ypos += 2; break;
  77736. }
  77737. while (ypos >= destData.height)
  77738. {
  77739. ++pass;
  77740. switch (pass)
  77741. {
  77742. case 1: ypos = 4; break;
  77743. case 2: ypos = 2; break;
  77744. case 3: ypos = 1; break;
  77745. default: return true;
  77746. }
  77747. }
  77748. }
  77749. else
  77750. {
  77751. ++ypos;
  77752. }
  77753. p = destData.getPixelPointer (xpos, ypos);
  77754. }
  77755. if (ypos >= destData.height)
  77756. break;
  77757. }
  77758. return true;
  77759. }
  77760. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  77761. JUCE_DECLARE_NON_COPYABLE (GIFLoader);
  77762. };
  77763. #endif
  77764. GIFImageFormat::GIFImageFormat() {}
  77765. GIFImageFormat::~GIFImageFormat() {}
  77766. const String GIFImageFormat::getFormatName() { return "GIF"; }
  77767. bool GIFImageFormat::canUnderstand (InputStream& in)
  77768. {
  77769. char header [4];
  77770. return (in.read (header, sizeof (header)) == sizeof (header))
  77771. && header[0] == 'G'
  77772. && header[1] == 'I'
  77773. && header[2] == 'F';
  77774. }
  77775. const Image GIFImageFormat::decodeImage (InputStream& in)
  77776. {
  77777. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77778. return juce_loadWithCoreImage (in);
  77779. #else
  77780. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  77781. return loader->image;
  77782. #endif
  77783. }
  77784. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  77785. {
  77786. jassertfalse; // writing isn't implemented for GIFs!
  77787. return false;
  77788. }
  77789. END_JUCE_NAMESPACE
  77790. /*** End of inlined file: juce_GIFLoader.cpp ***/
  77791. #endif
  77792. //==============================================================================
  77793. // some files include lots of library code, so leave them to the end to avoid cluttering
  77794. // up the build for the clean files.
  77795. #if JUCE_BUILD_CORE
  77796. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  77797. namespace zlibNamespace
  77798. {
  77799. #if JUCE_INCLUDE_ZLIB_CODE
  77800. #undef OS_CODE
  77801. #undef fdopen
  77802. /*** Start of inlined file: zlib.h ***/
  77803. #ifndef ZLIB_H
  77804. #define ZLIB_H
  77805. /*** Start of inlined file: zconf.h ***/
  77806. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  77807. #ifndef ZCONF_H
  77808. #define ZCONF_H
  77809. // *** Just a few hacks here to make it compile nicely with Juce..
  77810. #define Z_PREFIX 1
  77811. #undef __MACTYPES__
  77812. #ifdef _MSC_VER
  77813. #pragma warning (disable : 4131 4127 4244 4267)
  77814. #endif
  77815. /*
  77816. * If you *really* need a unique prefix for all types and library functions,
  77817. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  77818. */
  77819. #ifdef Z_PREFIX
  77820. # define deflateInit_ z_deflateInit_
  77821. # define deflate z_deflate
  77822. # define deflateEnd z_deflateEnd
  77823. # define inflateInit_ z_inflateInit_
  77824. # define inflate z_inflate
  77825. # define inflateEnd z_inflateEnd
  77826. # define inflatePrime z_inflatePrime
  77827. # define inflateGetHeader z_inflateGetHeader
  77828. # define adler32_combine z_adler32_combine
  77829. # define crc32_combine z_crc32_combine
  77830. # define deflateInit2_ z_deflateInit2_
  77831. # define deflateSetDictionary z_deflateSetDictionary
  77832. # define deflateCopy z_deflateCopy
  77833. # define deflateReset z_deflateReset
  77834. # define deflateParams z_deflateParams
  77835. # define deflateBound z_deflateBound
  77836. # define deflatePrime z_deflatePrime
  77837. # define inflateInit2_ z_inflateInit2_
  77838. # define inflateSetDictionary z_inflateSetDictionary
  77839. # define inflateSync z_inflateSync
  77840. # define inflateSyncPoint z_inflateSyncPoint
  77841. # define inflateCopy z_inflateCopy
  77842. # define inflateReset z_inflateReset
  77843. # define inflateBack z_inflateBack
  77844. # define inflateBackEnd z_inflateBackEnd
  77845. # define compress z_compress
  77846. # define compress2 z_compress2
  77847. # define compressBound z_compressBound
  77848. # define uncompress z_uncompress
  77849. # define adler32 z_adler32
  77850. # define crc32 z_crc32
  77851. # define get_crc_table z_get_crc_table
  77852. # define zError z_zError
  77853. # define alloc_func z_alloc_func
  77854. # define free_func z_free_func
  77855. # define in_func z_in_func
  77856. # define out_func z_out_func
  77857. # define Byte z_Byte
  77858. # define uInt z_uInt
  77859. # define uLong z_uLong
  77860. # define Bytef z_Bytef
  77861. # define charf z_charf
  77862. # define intf z_intf
  77863. # define uIntf z_uIntf
  77864. # define uLongf z_uLongf
  77865. # define voidpf z_voidpf
  77866. # define voidp z_voidp
  77867. #endif
  77868. #if defined(__MSDOS__) && !defined(MSDOS)
  77869. # define MSDOS
  77870. #endif
  77871. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  77872. # define OS2
  77873. #endif
  77874. #if defined(_WINDOWS) && !defined(WINDOWS)
  77875. # define WINDOWS
  77876. #endif
  77877. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  77878. # ifndef WIN32
  77879. # define WIN32
  77880. # endif
  77881. #endif
  77882. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  77883. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  77884. # ifndef SYS16BIT
  77885. # define SYS16BIT
  77886. # endif
  77887. # endif
  77888. #endif
  77889. /*
  77890. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  77891. * than 64k bytes at a time (needed on systems with 16-bit int).
  77892. */
  77893. #ifdef SYS16BIT
  77894. # define MAXSEG_64K
  77895. #endif
  77896. #ifdef MSDOS
  77897. # define UNALIGNED_OK
  77898. #endif
  77899. #ifdef __STDC_VERSION__
  77900. # ifndef STDC
  77901. # define STDC
  77902. # endif
  77903. # if __STDC_VERSION__ >= 199901L
  77904. # ifndef STDC99
  77905. # define STDC99
  77906. # endif
  77907. # endif
  77908. #endif
  77909. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  77910. # define STDC
  77911. #endif
  77912. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  77913. # define STDC
  77914. #endif
  77915. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  77916. # define STDC
  77917. #endif
  77918. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  77919. # define STDC
  77920. #endif
  77921. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  77922. # define STDC
  77923. #endif
  77924. #ifndef STDC
  77925. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  77926. # define const /* note: need a more gentle solution here */
  77927. # endif
  77928. #endif
  77929. /* Some Mac compilers merge all .h files incorrectly: */
  77930. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  77931. # define NO_DUMMY_DECL
  77932. #endif
  77933. /* Maximum value for memLevel in deflateInit2 */
  77934. #ifndef MAX_MEM_LEVEL
  77935. # ifdef MAXSEG_64K
  77936. # define MAX_MEM_LEVEL 8
  77937. # else
  77938. # define MAX_MEM_LEVEL 9
  77939. # endif
  77940. #endif
  77941. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  77942. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  77943. * created by gzip. (Files created by minigzip can still be extracted by
  77944. * gzip.)
  77945. */
  77946. #ifndef MAX_WBITS
  77947. # define MAX_WBITS 15 /* 32K LZ77 window */
  77948. #endif
  77949. /* The memory requirements for deflate are (in bytes):
  77950. (1 << (windowBits+2)) + (1 << (memLevel+9))
  77951. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  77952. plus a few kilobytes for small objects. For example, if you want to reduce
  77953. the default memory requirements from 256K to 128K, compile with
  77954. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  77955. Of course this will generally degrade compression (there's no free lunch).
  77956. The memory requirements for inflate are (in bytes) 1 << windowBits
  77957. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  77958. for small objects.
  77959. */
  77960. /* Type declarations */
  77961. #ifndef OF /* function prototypes */
  77962. # ifdef STDC
  77963. # define OF(args) args
  77964. # else
  77965. # define OF(args) ()
  77966. # endif
  77967. #endif
  77968. /* The following definitions for FAR are needed only for MSDOS mixed
  77969. * model programming (small or medium model with some far allocations).
  77970. * This was tested only with MSC; for other MSDOS compilers you may have
  77971. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  77972. * just define FAR to be empty.
  77973. */
  77974. #ifdef SYS16BIT
  77975. # if defined(M_I86SM) || defined(M_I86MM)
  77976. /* MSC small or medium model */
  77977. # define SMALL_MEDIUM
  77978. # ifdef _MSC_VER
  77979. # define FAR _far
  77980. # else
  77981. # define FAR far
  77982. # endif
  77983. # endif
  77984. # if (defined(__SMALL__) || defined(__MEDIUM__))
  77985. /* Turbo C small or medium model */
  77986. # define SMALL_MEDIUM
  77987. # ifdef __BORLANDC__
  77988. # define FAR _far
  77989. # else
  77990. # define FAR far
  77991. # endif
  77992. # endif
  77993. #endif
  77994. #if defined(WINDOWS) || defined(WIN32)
  77995. /* If building or using zlib as a DLL, define ZLIB_DLL.
  77996. * This is not mandatory, but it offers a little performance increase.
  77997. */
  77998. # ifdef ZLIB_DLL
  77999. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  78000. # ifdef ZLIB_INTERNAL
  78001. # define ZEXTERN extern __declspec(dllexport)
  78002. # else
  78003. # define ZEXTERN extern __declspec(dllimport)
  78004. # endif
  78005. # endif
  78006. # endif /* ZLIB_DLL */
  78007. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  78008. * define ZLIB_WINAPI.
  78009. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  78010. */
  78011. # ifdef ZLIB_WINAPI
  78012. # ifdef FAR
  78013. # undef FAR
  78014. # endif
  78015. # include <windows.h>
  78016. /* No need for _export, use ZLIB.DEF instead. */
  78017. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  78018. # define ZEXPORT WINAPI
  78019. # ifdef WIN32
  78020. # define ZEXPORTVA WINAPIV
  78021. # else
  78022. # define ZEXPORTVA FAR CDECL
  78023. # endif
  78024. # endif
  78025. #endif
  78026. #if defined (__BEOS__)
  78027. # ifdef ZLIB_DLL
  78028. # ifdef ZLIB_INTERNAL
  78029. # define ZEXPORT __declspec(dllexport)
  78030. # define ZEXPORTVA __declspec(dllexport)
  78031. # else
  78032. # define ZEXPORT __declspec(dllimport)
  78033. # define ZEXPORTVA __declspec(dllimport)
  78034. # endif
  78035. # endif
  78036. #endif
  78037. #ifndef ZEXTERN
  78038. # define ZEXTERN extern
  78039. #endif
  78040. #ifndef ZEXPORT
  78041. # define ZEXPORT
  78042. #endif
  78043. #ifndef ZEXPORTVA
  78044. # define ZEXPORTVA
  78045. #endif
  78046. #ifndef FAR
  78047. # define FAR
  78048. #endif
  78049. #if !defined(__MACTYPES__)
  78050. typedef unsigned char Byte; /* 8 bits */
  78051. #endif
  78052. typedef unsigned int uInt; /* 16 bits or more */
  78053. typedef unsigned long uLong; /* 32 bits or more */
  78054. #ifdef SMALL_MEDIUM
  78055. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78056. # define Bytef Byte FAR
  78057. #else
  78058. typedef Byte FAR Bytef;
  78059. #endif
  78060. typedef char FAR charf;
  78061. typedef int FAR intf;
  78062. typedef uInt FAR uIntf;
  78063. typedef uLong FAR uLongf;
  78064. #ifdef STDC
  78065. typedef void const *voidpc;
  78066. typedef void FAR *voidpf;
  78067. typedef void *voidp;
  78068. #else
  78069. typedef Byte const *voidpc;
  78070. typedef Byte FAR *voidpf;
  78071. typedef Byte *voidp;
  78072. #endif
  78073. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78074. # include <sys/types.h> /* for off_t */
  78075. # include <unistd.h> /* for SEEK_* and off_t */
  78076. # ifdef VMS
  78077. # include <unixio.h> /* for off_t */
  78078. # endif
  78079. # define z_off_t off_t
  78080. #endif
  78081. #ifndef SEEK_SET
  78082. # define SEEK_SET 0 /* Seek from beginning of file. */
  78083. # define SEEK_CUR 1 /* Seek from current position. */
  78084. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78085. #endif
  78086. #ifndef z_off_t
  78087. # define z_off_t long
  78088. #endif
  78089. #if defined(__OS400__)
  78090. # define NO_vsnprintf
  78091. #endif
  78092. #if defined(__MVS__)
  78093. # define NO_vsnprintf
  78094. # ifdef FAR
  78095. # undef FAR
  78096. # endif
  78097. #endif
  78098. /* MVS linker does not support external names larger than 8 bytes */
  78099. #if defined(__MVS__)
  78100. # pragma map(deflateInit_,"DEIN")
  78101. # pragma map(deflateInit2_,"DEIN2")
  78102. # pragma map(deflateEnd,"DEEND")
  78103. # pragma map(deflateBound,"DEBND")
  78104. # pragma map(inflateInit_,"ININ")
  78105. # pragma map(inflateInit2_,"ININ2")
  78106. # pragma map(inflateEnd,"INEND")
  78107. # pragma map(inflateSync,"INSY")
  78108. # pragma map(inflateSetDictionary,"INSEDI")
  78109. # pragma map(compressBound,"CMBND")
  78110. # pragma map(inflate_table,"INTABL")
  78111. # pragma map(inflate_fast,"INFA")
  78112. # pragma map(inflate_copyright,"INCOPY")
  78113. #endif
  78114. #endif /* ZCONF_H */
  78115. /*** End of inlined file: zconf.h ***/
  78116. #ifdef __cplusplus
  78117. //extern "C" {
  78118. #endif
  78119. #define ZLIB_VERSION "1.2.3"
  78120. #define ZLIB_VERNUM 0x1230
  78121. /*
  78122. The 'zlib' compression library provides in-memory compression and
  78123. decompression functions, including integrity checks of the uncompressed
  78124. data. This version of the library supports only one compression method
  78125. (deflation) but other algorithms will be added later and will have the same
  78126. stream interface.
  78127. Compression can be done in a single step if the buffers are large
  78128. enough (for example if an input file is mmap'ed), or can be done by
  78129. repeated calls of the compression function. In the latter case, the
  78130. application must provide more input and/or consume the output
  78131. (providing more output space) before each call.
  78132. The compressed data format used by default by the in-memory functions is
  78133. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78134. around a deflate stream, which is itself documented in RFC 1951.
  78135. The library also supports reading and writing files in gzip (.gz) format
  78136. with an interface similar to that of stdio using the functions that start
  78137. with "gz". The gzip format is different from the zlib format. gzip is a
  78138. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78139. This library can optionally read and write gzip streams in memory as well.
  78140. The zlib format was designed to be compact and fast for use in memory
  78141. and on communications channels. The gzip format was designed for single-
  78142. file compression on file systems, has a larger header than zlib to maintain
  78143. directory information, and uses a different, slower check method than zlib.
  78144. The library does not install any signal handler. The decoder checks
  78145. the consistency of the compressed data, so the library should never
  78146. crash even in case of corrupted input.
  78147. */
  78148. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78149. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78150. struct internal_state;
  78151. typedef struct z_stream_s {
  78152. Bytef *next_in; /* next input byte */
  78153. uInt avail_in; /* number of bytes available at next_in */
  78154. uLong total_in; /* total nb of input bytes read so far */
  78155. Bytef *next_out; /* next output byte should be put there */
  78156. uInt avail_out; /* remaining free space at next_out */
  78157. uLong total_out; /* total nb of bytes output so far */
  78158. char *msg; /* last error message, NULL if no error */
  78159. struct internal_state FAR *state; /* not visible by applications */
  78160. alloc_func zalloc; /* used to allocate the internal state */
  78161. free_func zfree; /* used to free the internal state */
  78162. voidpf opaque; /* private data object passed to zalloc and zfree */
  78163. int data_type; /* best guess about the data type: binary or text */
  78164. uLong adler; /* adler32 value of the uncompressed data */
  78165. uLong reserved; /* reserved for future use */
  78166. } z_stream;
  78167. typedef z_stream FAR *z_streamp;
  78168. /*
  78169. gzip header information passed to and from zlib routines. See RFC 1952
  78170. for more details on the meanings of these fields.
  78171. */
  78172. typedef struct gz_header_s {
  78173. int text; /* true if compressed data believed to be text */
  78174. uLong time; /* modification time */
  78175. int xflags; /* extra flags (not used when writing a gzip file) */
  78176. int os; /* operating system */
  78177. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78178. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78179. uInt extra_max; /* space at extra (only when reading header) */
  78180. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78181. uInt name_max; /* space at name (only when reading header) */
  78182. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78183. uInt comm_max; /* space at comment (only when reading header) */
  78184. int hcrc; /* true if there was or will be a header crc */
  78185. int done; /* true when done reading gzip header (not used
  78186. when writing a gzip file) */
  78187. } gz_header;
  78188. typedef gz_header FAR *gz_headerp;
  78189. /*
  78190. The application must update next_in and avail_in when avail_in has
  78191. dropped to zero. It must update next_out and avail_out when avail_out
  78192. has dropped to zero. The application must initialize zalloc, zfree and
  78193. opaque before calling the init function. All other fields are set by the
  78194. compression library and must not be updated by the application.
  78195. The opaque value provided by the application will be passed as the first
  78196. parameter for calls of zalloc and zfree. This can be useful for custom
  78197. memory management. The compression library attaches no meaning to the
  78198. opaque value.
  78199. zalloc must return Z_NULL if there is not enough memory for the object.
  78200. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78201. thread safe.
  78202. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78203. exactly 65536 bytes, but will not be required to allocate more than this
  78204. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78205. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78206. have their offset normalized to zero. The default allocation function
  78207. provided by this library ensures this (see zutil.c). To reduce memory
  78208. requirements and avoid any allocation of 64K objects, at the expense of
  78209. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78210. The fields total_in and total_out can be used for statistics or
  78211. progress reports. After compression, total_in holds the total size of
  78212. the uncompressed data and may be saved for use in the decompressor
  78213. (particularly if the decompressor wants to decompress everything in
  78214. a single step).
  78215. */
  78216. /* constants */
  78217. #define Z_NO_FLUSH 0
  78218. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78219. #define Z_SYNC_FLUSH 2
  78220. #define Z_FULL_FLUSH 3
  78221. #define Z_FINISH 4
  78222. #define Z_BLOCK 5
  78223. /* Allowed flush values; see deflate() and inflate() below for details */
  78224. #define Z_OK 0
  78225. #define Z_STREAM_END 1
  78226. #define Z_NEED_DICT 2
  78227. #define Z_ERRNO (-1)
  78228. #define Z_STREAM_ERROR (-2)
  78229. #define Z_DATA_ERROR (-3)
  78230. #define Z_MEM_ERROR (-4)
  78231. #define Z_BUF_ERROR (-5)
  78232. #define Z_VERSION_ERROR (-6)
  78233. /* Return codes for the compression/decompression functions. Negative
  78234. * values are errors, positive values are used for special but normal events.
  78235. */
  78236. #define Z_NO_COMPRESSION 0
  78237. #define Z_BEST_SPEED 1
  78238. #define Z_BEST_COMPRESSION 9
  78239. #define Z_DEFAULT_COMPRESSION (-1)
  78240. /* compression levels */
  78241. #define Z_FILTERED 1
  78242. #define Z_HUFFMAN_ONLY 2
  78243. #define Z_RLE 3
  78244. #define Z_FIXED 4
  78245. #define Z_DEFAULT_STRATEGY 0
  78246. /* compression strategy; see deflateInit2() below for details */
  78247. #define Z_BINARY 0
  78248. #define Z_TEXT 1
  78249. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78250. #define Z_UNKNOWN 2
  78251. /* Possible values of the data_type field (though see inflate()) */
  78252. #define Z_DEFLATED 8
  78253. /* The deflate compression method (the only one supported in this version) */
  78254. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78255. #define zlib_version zlibVersion()
  78256. /* for compatibility with versions < 1.0.2 */
  78257. /* basic functions */
  78258. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78259. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78260. If the first character differs, the library code actually used is
  78261. not compatible with the zlib.h header file used by the application.
  78262. This check is automatically made by deflateInit and inflateInit.
  78263. */
  78264. /*
  78265. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78266. Initializes the internal stream state for compression. The fields
  78267. zalloc, zfree and opaque must be initialized before by the caller.
  78268. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78269. use default allocation functions.
  78270. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78271. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78272. all (the input data is simply copied a block at a time).
  78273. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78274. compression (currently equivalent to level 6).
  78275. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78276. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78277. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78278. with the version assumed by the caller (ZLIB_VERSION).
  78279. msg is set to null if there is no error message. deflateInit does not
  78280. perform any compression: this will be done by deflate().
  78281. */
  78282. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78283. /*
  78284. deflate compresses as much data as possible, and stops when the input
  78285. buffer becomes empty or the output buffer becomes full. It may introduce some
  78286. output latency (reading input without producing any output) except when
  78287. forced to flush.
  78288. The detailed semantics are as follows. deflate performs one or both of the
  78289. following actions:
  78290. - Compress more input starting at next_in and update next_in and avail_in
  78291. accordingly. If not all input can be processed (because there is not
  78292. enough room in the output buffer), next_in and avail_in are updated and
  78293. processing will resume at this point for the next call of deflate().
  78294. - Provide more output starting at next_out and update next_out and avail_out
  78295. accordingly. This action is forced if the parameter flush is non zero.
  78296. Forcing flush frequently degrades the compression ratio, so this parameter
  78297. should be set only when necessary (in interactive applications).
  78298. Some output may be provided even if flush is not set.
  78299. Before the call of deflate(), the application should ensure that at least
  78300. one of the actions is possible, by providing more input and/or consuming
  78301. more output, and updating avail_in or avail_out accordingly; avail_out
  78302. should never be zero before the call. The application can consume the
  78303. compressed output when it wants, for example when the output buffer is full
  78304. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78305. and with zero avail_out, it must be called again after making room in the
  78306. output buffer because there might be more output pending.
  78307. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78308. decide how much data to accumualte before producing output, in order to
  78309. maximize compression.
  78310. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78311. flushed to the output buffer and the output is aligned on a byte boundary, so
  78312. that the decompressor can get all input data available so far. (In particular
  78313. avail_in is zero after the call if enough output space has been provided
  78314. before the call.) Flushing may degrade compression for some compression
  78315. algorithms and so it should be used only when necessary.
  78316. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78317. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78318. restart from this point if previous compressed data has been damaged or if
  78319. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78320. compression.
  78321. If deflate returns with avail_out == 0, this function must be called again
  78322. with the same value of the flush parameter and more output space (updated
  78323. avail_out), until the flush is complete (deflate returns with non-zero
  78324. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78325. avail_out is greater than six to avoid repeated flush markers due to
  78326. avail_out == 0 on return.
  78327. If the parameter flush is set to Z_FINISH, pending input is processed,
  78328. pending output is flushed and deflate returns with Z_STREAM_END if there
  78329. was enough output space; if deflate returns with Z_OK, this function must be
  78330. called again with Z_FINISH and more output space (updated avail_out) but no
  78331. more input data, until it returns with Z_STREAM_END or an error. After
  78332. deflate has returned Z_STREAM_END, the only possible operations on the
  78333. stream are deflateReset or deflateEnd.
  78334. Z_FINISH can be used immediately after deflateInit if all the compression
  78335. is to be done in a single step. In this case, avail_out must be at least
  78336. the value returned by deflateBound (see below). If deflate does not return
  78337. Z_STREAM_END, then it must be called again as described above.
  78338. deflate() sets strm->adler to the adler32 checksum of all input read
  78339. so far (that is, total_in bytes).
  78340. deflate() may update strm->data_type if it can make a good guess about
  78341. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78342. binary. This field is only for information purposes and does not affect
  78343. the compression algorithm in any manner.
  78344. deflate() returns Z_OK if some progress has been made (more input
  78345. processed or more output produced), Z_STREAM_END if all input has been
  78346. consumed and all output has been produced (only when flush is set to
  78347. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78348. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78349. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78350. fatal, and deflate() can be called again with more input and more output
  78351. space to continue compressing.
  78352. */
  78353. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78354. /*
  78355. All dynamically allocated data structures for this stream are freed.
  78356. This function discards any unprocessed input and does not flush any
  78357. pending output.
  78358. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78359. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78360. prematurely (some input or output was discarded). In the error case,
  78361. msg may be set but then points to a static string (which must not be
  78362. deallocated).
  78363. */
  78364. /*
  78365. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78366. Initializes the internal stream state for decompression. The fields
  78367. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78368. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78369. value depends on the compression method), inflateInit determines the
  78370. compression method from the zlib header and allocates all data structures
  78371. accordingly; otherwise the allocation will be deferred to the first call of
  78372. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78373. use default allocation functions.
  78374. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78375. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78376. version assumed by the caller. msg is set to null if there is no error
  78377. message. inflateInit does not perform any decompression apart from reading
  78378. the zlib header if present: this will be done by inflate(). (So next_in and
  78379. avail_in may be modified, but next_out and avail_out are unchanged.)
  78380. */
  78381. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78382. /*
  78383. inflate decompresses as much data as possible, and stops when the input
  78384. buffer becomes empty or the output buffer becomes full. It may introduce
  78385. some output latency (reading input without producing any output) except when
  78386. forced to flush.
  78387. The detailed semantics are as follows. inflate performs one or both of the
  78388. following actions:
  78389. - Decompress more input starting at next_in and update next_in and avail_in
  78390. accordingly. If not all input can be processed (because there is not
  78391. enough room in the output buffer), next_in is updated and processing
  78392. will resume at this point for the next call of inflate().
  78393. - Provide more output starting at next_out and update next_out and avail_out
  78394. accordingly. inflate() provides as much output as possible, until there
  78395. is no more input data or no more space in the output buffer (see below
  78396. about the flush parameter).
  78397. Before the call of inflate(), the application should ensure that at least
  78398. one of the actions is possible, by providing more input and/or consuming
  78399. more output, and updating the next_* and avail_* values accordingly.
  78400. The application can consume the uncompressed output when it wants, for
  78401. example when the output buffer is full (avail_out == 0), or after each
  78402. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78403. must be called again after making room in the output buffer because there
  78404. might be more output pending.
  78405. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78406. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78407. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78408. if and when it gets to the next deflate block boundary. When decoding the
  78409. zlib or gzip format, this will cause inflate() to return immediately after
  78410. the header and before the first block. When doing a raw inflate, inflate()
  78411. will go ahead and process the first block, and will return when it gets to
  78412. the end of that block, or when it runs out of data.
  78413. The Z_BLOCK option assists in appending to or combining deflate streams.
  78414. Also to assist in this, on return inflate() will set strm->data_type to the
  78415. number of unused bits in the last byte taken from strm->next_in, plus 64
  78416. if inflate() is currently decoding the last block in the deflate stream,
  78417. plus 128 if inflate() returned immediately after decoding an end-of-block
  78418. code or decoding the complete header up to just before the first byte of the
  78419. deflate stream. The end-of-block will not be indicated until all of the
  78420. uncompressed data from that block has been written to strm->next_out. The
  78421. number of unused bits may in general be greater than seven, except when
  78422. bit 7 of data_type is set, in which case the number of unused bits will be
  78423. less than eight.
  78424. inflate() should normally be called until it returns Z_STREAM_END or an
  78425. error. However if all decompression is to be performed in a single step
  78426. (a single call of inflate), the parameter flush should be set to
  78427. Z_FINISH. In this case all pending input is processed and all pending
  78428. output is flushed; avail_out must be large enough to hold all the
  78429. uncompressed data. (The size of the uncompressed data may have been saved
  78430. by the compressor for this purpose.) The next operation on this stream must
  78431. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78432. is never required, but can be used to inform inflate that a faster approach
  78433. may be used for the single inflate() call.
  78434. In this implementation, inflate() always flushes as much output as
  78435. possible to the output buffer, and always uses the faster approach on the
  78436. first call. So the only effect of the flush parameter in this implementation
  78437. is on the return value of inflate(), as noted below, or when it returns early
  78438. because Z_BLOCK is used.
  78439. If a preset dictionary is needed after this call (see inflateSetDictionary
  78440. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78441. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78442. strm->adler to the adler32 checksum of all output produced so far (that is,
  78443. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78444. below. At the end of the stream, inflate() checks that its computed adler32
  78445. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78446. only if the checksum is correct.
  78447. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78448. deflate data. The header type is detected automatically. Any information
  78449. contained in the gzip header is not retained, so applications that need that
  78450. information should instead use raw inflate, see inflateInit2() below, or
  78451. inflateBack() and perform their own processing of the gzip header and
  78452. trailer.
  78453. inflate() returns Z_OK if some progress has been made (more input processed
  78454. or more output produced), Z_STREAM_END if the end of the compressed data has
  78455. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78456. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78457. corrupted (input stream not conforming to the zlib format or incorrect check
  78458. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78459. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78460. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78461. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78462. inflate() can be called again with more input and more output space to
  78463. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78464. call inflateSync() to look for a good compression block if a partial recovery
  78465. of the data is desired.
  78466. */
  78467. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78468. /*
  78469. All dynamically allocated data structures for this stream are freed.
  78470. This function discards any unprocessed input and does not flush any
  78471. pending output.
  78472. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78473. was inconsistent. In the error case, msg may be set but then points to a
  78474. static string (which must not be deallocated).
  78475. */
  78476. /* Advanced functions */
  78477. /*
  78478. The following functions are needed only in some special applications.
  78479. */
  78480. /*
  78481. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78482. int level,
  78483. int method,
  78484. int windowBits,
  78485. int memLevel,
  78486. int strategy));
  78487. This is another version of deflateInit with more compression options. The
  78488. fields next_in, zalloc, zfree and opaque must be initialized before by
  78489. the caller.
  78490. The method parameter is the compression method. It must be Z_DEFLATED in
  78491. this version of the library.
  78492. The windowBits parameter is the base two logarithm of the window size
  78493. (the size of the history buffer). It should be in the range 8..15 for this
  78494. version of the library. Larger values of this parameter result in better
  78495. compression at the expense of memory usage. The default value is 15 if
  78496. deflateInit is used instead.
  78497. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  78498. determines the window size. deflate() will then generate raw deflate data
  78499. with no zlib header or trailer, and will not compute an adler32 check value.
  78500. windowBits can also be greater than 15 for optional gzip encoding. Add
  78501. 16 to windowBits to write a simple gzip header and trailer around the
  78502. compressed data instead of a zlib wrapper. The gzip header will have no
  78503. file name, no extra data, no comment, no modification time (set to zero),
  78504. no header crc, and the operating system will be set to 255 (unknown). If a
  78505. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  78506. The memLevel parameter specifies how much memory should be allocated
  78507. for the internal compression state. memLevel=1 uses minimum memory but
  78508. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  78509. for optimal speed. The default value is 8. See zconf.h for total memory
  78510. usage as a function of windowBits and memLevel.
  78511. The strategy parameter is used to tune the compression algorithm. Use the
  78512. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  78513. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  78514. string match), or Z_RLE to limit match distances to one (run-length
  78515. encoding). Filtered data consists mostly of small values with a somewhat
  78516. random distribution. In this case, the compression algorithm is tuned to
  78517. compress them better. The effect of Z_FILTERED is to force more Huffman
  78518. coding and less string matching; it is somewhat intermediate between
  78519. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  78520. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  78521. parameter only affects the compression ratio but not the correctness of the
  78522. compressed output even if it is not set appropriately. Z_FIXED prevents the
  78523. use of dynamic Huffman codes, allowing for a simpler decoder for special
  78524. applications.
  78525. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78526. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  78527. method). msg is set to null if there is no error message. deflateInit2 does
  78528. not perform any compression: this will be done by deflate().
  78529. */
  78530. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  78531. const Bytef *dictionary,
  78532. uInt dictLength));
  78533. /*
  78534. Initializes the compression dictionary from the given byte sequence
  78535. without producing any compressed output. This function must be called
  78536. immediately after deflateInit, deflateInit2 or deflateReset, before any
  78537. call of deflate. The compressor and decompressor must use exactly the same
  78538. dictionary (see inflateSetDictionary).
  78539. The dictionary should consist of strings (byte sequences) that are likely
  78540. to be encountered later in the data to be compressed, with the most commonly
  78541. used strings preferably put towards the end of the dictionary. Using a
  78542. dictionary is most useful when the data to be compressed is short and can be
  78543. predicted with good accuracy; the data can then be compressed better than
  78544. with the default empty dictionary.
  78545. Depending on the size of the compression data structures selected by
  78546. deflateInit or deflateInit2, a part of the dictionary may in effect be
  78547. discarded, for example if the dictionary is larger than the window size in
  78548. deflate or deflate2. Thus the strings most likely to be useful should be
  78549. put at the end of the dictionary, not at the front. In addition, the
  78550. current implementation of deflate will use at most the window size minus
  78551. 262 bytes of the provided dictionary.
  78552. Upon return of this function, strm->adler is set to the adler32 value
  78553. of the dictionary; the decompressor may later use this value to determine
  78554. which dictionary has been used by the compressor. (The adler32 value
  78555. applies to the whole dictionary even if only a subset of the dictionary is
  78556. actually used by the compressor.) If a raw deflate was requested, then the
  78557. adler32 value is not computed and strm->adler is not set.
  78558. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  78559. parameter is invalid (such as NULL dictionary) or the stream state is
  78560. inconsistent (for example if deflate has already been called for this stream
  78561. or if the compression method is bsort). deflateSetDictionary does not
  78562. perform any compression: this will be done by deflate().
  78563. */
  78564. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  78565. z_streamp source));
  78566. /*
  78567. Sets the destination stream as a complete copy of the source stream.
  78568. This function can be useful when several compression strategies will be
  78569. tried, for example when there are several ways of pre-processing the input
  78570. data with a filter. The streams that will be discarded should then be freed
  78571. by calling deflateEnd. Note that deflateCopy duplicates the internal
  78572. compression state which can be quite large, so this strategy is slow and
  78573. can consume lots of memory.
  78574. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78575. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78576. (such as zalloc being NULL). msg is left unchanged in both source and
  78577. destination.
  78578. */
  78579. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  78580. /*
  78581. This function is equivalent to deflateEnd followed by deflateInit,
  78582. but does not free and reallocate all the internal compression state.
  78583. The stream will keep the same compression level and any other attributes
  78584. that may have been set by deflateInit2.
  78585. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78586. stream state was inconsistent (such as zalloc or state being NULL).
  78587. */
  78588. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  78589. int level,
  78590. int strategy));
  78591. /*
  78592. Dynamically update the compression level and compression strategy. The
  78593. interpretation of level and strategy is as in deflateInit2. This can be
  78594. used to switch between compression and straight copy of the input data, or
  78595. to switch to a different kind of input data requiring a different
  78596. strategy. If the compression level is changed, the input available so far
  78597. is compressed with the old level (and may be flushed); the new level will
  78598. take effect only at the next call of deflate().
  78599. Before the call of deflateParams, the stream state must be set as for
  78600. a call of deflate(), since the currently available input may have to
  78601. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  78602. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  78603. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  78604. if strm->avail_out was zero.
  78605. */
  78606. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  78607. int good_length,
  78608. int max_lazy,
  78609. int nice_length,
  78610. int max_chain));
  78611. /*
  78612. Fine tune deflate's internal compression parameters. This should only be
  78613. used by someone who understands the algorithm used by zlib's deflate for
  78614. searching for the best matching string, and even then only by the most
  78615. fanatic optimizer trying to squeeze out the last compressed bit for their
  78616. specific input data. Read the deflate.c source code for the meaning of the
  78617. max_lazy, good_length, nice_length, and max_chain parameters.
  78618. deflateTune() can be called after deflateInit() or deflateInit2(), and
  78619. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  78620. */
  78621. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  78622. uLong sourceLen));
  78623. /*
  78624. deflateBound() returns an upper bound on the compressed size after
  78625. deflation of sourceLen bytes. It must be called after deflateInit()
  78626. or deflateInit2(). This would be used to allocate an output buffer
  78627. for deflation in a single pass, and so would be called before deflate().
  78628. */
  78629. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  78630. int bits,
  78631. int value));
  78632. /*
  78633. deflatePrime() inserts bits in the deflate output stream. The intent
  78634. is that this function is used to start off the deflate output with the
  78635. bits leftover from a previous deflate stream when appending to it. As such,
  78636. this function can only be used for raw deflate, and must be used before the
  78637. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  78638. less than or equal to 16, and that many of the least significant bits of
  78639. value will be inserted in the output.
  78640. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78641. stream state was inconsistent.
  78642. */
  78643. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  78644. gz_headerp head));
  78645. /*
  78646. deflateSetHeader() provides gzip header information for when a gzip
  78647. stream is requested by deflateInit2(). deflateSetHeader() may be called
  78648. after deflateInit2() or deflateReset() and before the first call of
  78649. deflate(). The text, time, os, extra field, name, and comment information
  78650. in the provided gz_header structure are written to the gzip header (xflag is
  78651. ignored -- the extra flags are set according to the compression level). The
  78652. caller must assure that, if not Z_NULL, name and comment are terminated with
  78653. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  78654. available there. If hcrc is true, a gzip header crc is included. Note that
  78655. the current versions of the command-line version of gzip (up through version
  78656. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  78657. gzip file" and give up.
  78658. If deflateSetHeader is not used, the default gzip header has text false,
  78659. the time set to zero, and os set to 255, with no extra, name, or comment
  78660. fields. The gzip header is returned to the default state by deflateReset().
  78661. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78662. stream state was inconsistent.
  78663. */
  78664. /*
  78665. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  78666. int windowBits));
  78667. This is another version of inflateInit with an extra parameter. The
  78668. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  78669. before by the caller.
  78670. The windowBits parameter is the base two logarithm of the maximum window
  78671. size (the size of the history buffer). It should be in the range 8..15 for
  78672. this version of the library. The default value is 15 if inflateInit is used
  78673. instead. windowBits must be greater than or equal to the windowBits value
  78674. provided to deflateInit2() while compressing, or it must be equal to 15 if
  78675. deflateInit2() was not used. If a compressed stream with a larger window
  78676. size is given as input, inflate() will return with the error code
  78677. Z_DATA_ERROR instead of trying to allocate a larger window.
  78678. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  78679. determines the window size. inflate() will then process raw deflate data,
  78680. not looking for a zlib or gzip header, not generating a check value, and not
  78681. looking for any check values for comparison at the end of the stream. This
  78682. is for use with other formats that use the deflate compressed data format
  78683. such as zip. Those formats provide their own check values. If a custom
  78684. format is developed using the raw deflate format for compressed data, it is
  78685. recommended that a check value such as an adler32 or a crc32 be applied to
  78686. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  78687. most applications, the zlib format should be used as is. Note that comments
  78688. above on the use in deflateInit2() applies to the magnitude of windowBits.
  78689. windowBits can also be greater than 15 for optional gzip decoding. Add
  78690. 32 to windowBits to enable zlib and gzip decoding with automatic header
  78691. detection, or add 16 to decode only the gzip format (the zlib format will
  78692. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  78693. a crc32 instead of an adler32.
  78694. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78695. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  78696. is set to null if there is no error message. inflateInit2 does not perform
  78697. any decompression apart from reading the zlib header if present: this will
  78698. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  78699. and avail_out are unchanged.)
  78700. */
  78701. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  78702. const Bytef *dictionary,
  78703. uInt dictLength));
  78704. /*
  78705. Initializes the decompression dictionary from the given uncompressed byte
  78706. sequence. This function must be called immediately after a call of inflate,
  78707. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  78708. can be determined from the adler32 value returned by that call of inflate.
  78709. The compressor and decompressor must use exactly the same dictionary (see
  78710. deflateSetDictionary). For raw inflate, this function can be called
  78711. immediately after inflateInit2() or inflateReset() and before any call of
  78712. inflate() to set the dictionary. The application must insure that the
  78713. dictionary that was used for compression is provided.
  78714. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  78715. parameter is invalid (such as NULL dictionary) or the stream state is
  78716. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  78717. expected one (incorrect adler32 value). inflateSetDictionary does not
  78718. perform any decompression: this will be done by subsequent calls of
  78719. inflate().
  78720. */
  78721. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  78722. /*
  78723. Skips invalid compressed data until a full flush point (see above the
  78724. description of deflate with Z_FULL_FLUSH) can be found, or until all
  78725. available input is skipped. No output is provided.
  78726. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  78727. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  78728. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  78729. case, the application may save the current current value of total_in which
  78730. indicates where valid compressed data was found. In the error case, the
  78731. application may repeatedly call inflateSync, providing more input each time,
  78732. until success or end of the input data.
  78733. */
  78734. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  78735. z_streamp source));
  78736. /*
  78737. Sets the destination stream as a complete copy of the source stream.
  78738. This function can be useful when randomly accessing a large stream. The
  78739. first pass through the stream can periodically record the inflate state,
  78740. allowing restarting inflate at those points when randomly accessing the
  78741. stream.
  78742. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78743. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78744. (such as zalloc being NULL). msg is left unchanged in both source and
  78745. destination.
  78746. */
  78747. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  78748. /*
  78749. This function is equivalent to inflateEnd followed by inflateInit,
  78750. but does not free and reallocate all the internal decompression state.
  78751. The stream will keep attributes that may have been set by inflateInit2.
  78752. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78753. stream state was inconsistent (such as zalloc or state being NULL).
  78754. */
  78755. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  78756. int bits,
  78757. int value));
  78758. /*
  78759. This function inserts bits in the inflate input stream. The intent is
  78760. that this function is used to start inflating at a bit position in the
  78761. middle of a byte. The provided bits will be used before any bytes are used
  78762. from next_in. This function should only be used with raw inflate, and
  78763. should be used before the first inflate() call after inflateInit2() or
  78764. inflateReset(). bits must be less than or equal to 16, and that many of the
  78765. least significant bits of value will be inserted in the input.
  78766. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78767. stream state was inconsistent.
  78768. */
  78769. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  78770. gz_headerp head));
  78771. /*
  78772. inflateGetHeader() requests that gzip header information be stored in the
  78773. provided gz_header structure. inflateGetHeader() may be called after
  78774. inflateInit2() or inflateReset(), and before the first call of inflate().
  78775. As inflate() processes the gzip stream, head->done is zero until the header
  78776. is completed, at which time head->done is set to one. If a zlib stream is
  78777. being decoded, then head->done is set to -1 to indicate that there will be
  78778. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  78779. force inflate() to return immediately after header processing is complete
  78780. and before any actual data is decompressed.
  78781. The text, time, xflags, and os fields are filled in with the gzip header
  78782. contents. hcrc is set to true if there is a header CRC. (The header CRC
  78783. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  78784. contains the maximum number of bytes to write to extra. Once done is true,
  78785. extra_len contains the actual extra field length, and extra contains the
  78786. extra field, or that field truncated if extra_max is less than extra_len.
  78787. If name is not Z_NULL, then up to name_max characters are written there,
  78788. terminated with a zero unless the length is greater than name_max. If
  78789. comment is not Z_NULL, then up to comm_max characters are written there,
  78790. terminated with a zero unless the length is greater than comm_max. When
  78791. any of extra, name, or comment are not Z_NULL and the respective field is
  78792. not present in the header, then that field is set to Z_NULL to signal its
  78793. absence. This allows the use of deflateSetHeader() with the returned
  78794. structure to duplicate the header. However if those fields are set to
  78795. allocated memory, then the application will need to save those pointers
  78796. elsewhere so that they can be eventually freed.
  78797. If inflateGetHeader is not used, then the header information is simply
  78798. discarded. The header is always checked for validity, including the header
  78799. CRC if present. inflateReset() will reset the process to discard the header
  78800. information. The application would need to call inflateGetHeader() again to
  78801. retrieve the header from the next gzip stream.
  78802. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78803. stream state was inconsistent.
  78804. */
  78805. /*
  78806. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  78807. unsigned char FAR *window));
  78808. Initialize the internal stream state for decompression using inflateBack()
  78809. calls. The fields zalloc, zfree and opaque in strm must be initialized
  78810. before the call. If zalloc and zfree are Z_NULL, then the default library-
  78811. derived memory allocation routines are used. windowBits is the base two
  78812. logarithm of the window size, in the range 8..15. window is a caller
  78813. supplied buffer of that size. Except for special applications where it is
  78814. assured that deflate was used with small window sizes, windowBits must be 15
  78815. and a 32K byte window must be supplied to be able to decompress general
  78816. deflate streams.
  78817. See inflateBack() for the usage of these routines.
  78818. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  78819. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  78820. be allocated, or Z_VERSION_ERROR if the version of the library does not
  78821. match the version of the header file.
  78822. */
  78823. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  78824. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  78825. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  78826. in_func in, void FAR *in_desc,
  78827. out_func out, void FAR *out_desc));
  78828. /*
  78829. inflateBack() does a raw inflate with a single call using a call-back
  78830. interface for input and output. This is more efficient than inflate() for
  78831. file i/o applications in that it avoids copying between the output and the
  78832. sliding window by simply making the window itself the output buffer. This
  78833. function trusts the application to not change the output buffer passed by
  78834. the output function, at least until inflateBack() returns.
  78835. inflateBackInit() must be called first to allocate the internal state
  78836. and to initialize the state with the user-provided window buffer.
  78837. inflateBack() may then be used multiple times to inflate a complete, raw
  78838. deflate stream with each call. inflateBackEnd() is then called to free
  78839. the allocated state.
  78840. A raw deflate stream is one with no zlib or gzip header or trailer.
  78841. This routine would normally be used in a utility that reads zip or gzip
  78842. files and writes out uncompressed files. The utility would decode the
  78843. header and process the trailer on its own, hence this routine expects
  78844. only the raw deflate stream to decompress. This is different from the
  78845. normal behavior of inflate(), which expects either a zlib or gzip header and
  78846. trailer around the deflate stream.
  78847. inflateBack() uses two subroutines supplied by the caller that are then
  78848. called by inflateBack() for input and output. inflateBack() calls those
  78849. routines until it reads a complete deflate stream and writes out all of the
  78850. uncompressed data, or until it encounters an error. The function's
  78851. parameters and return types are defined above in the in_func and out_func
  78852. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  78853. number of bytes of provided input, and a pointer to that input in buf. If
  78854. there is no input available, in() must return zero--buf is ignored in that
  78855. case--and inflateBack() will return a buffer error. inflateBack() will call
  78856. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  78857. should return zero on success, or non-zero on failure. If out() returns
  78858. non-zero, inflateBack() will return with an error. Neither in() nor out()
  78859. are permitted to change the contents of the window provided to
  78860. inflateBackInit(), which is also the buffer that out() uses to write from.
  78861. The length written by out() will be at most the window size. Any non-zero
  78862. amount of input may be provided by in().
  78863. For convenience, inflateBack() can be provided input on the first call by
  78864. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  78865. in() will be called. Therefore strm->next_in must be initialized before
  78866. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  78867. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  78868. must also be initialized, and then if strm->avail_in is not zero, input will
  78869. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  78870. The in_desc and out_desc parameters of inflateBack() is passed as the
  78871. first parameter of in() and out() respectively when they are called. These
  78872. descriptors can be optionally used to pass any information that the caller-
  78873. supplied in() and out() functions need to do their job.
  78874. On return, inflateBack() will set strm->next_in and strm->avail_in to
  78875. pass back any unused input that was provided by the last in() call. The
  78876. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  78877. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  78878. error in the deflate stream (in which case strm->msg is set to indicate the
  78879. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  78880. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  78881. distinguished using strm->next_in which will be Z_NULL only if in() returned
  78882. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  78883. out() returning non-zero. (in() will always be called before out(), so
  78884. strm->next_in is assured to be defined if out() returns non-zero.) Note
  78885. that inflateBack() cannot return Z_OK.
  78886. */
  78887. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  78888. /*
  78889. All memory allocated by inflateBackInit() is freed.
  78890. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  78891. state was inconsistent.
  78892. */
  78893. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  78894. /* Return flags indicating compile-time options.
  78895. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  78896. 1.0: size of uInt
  78897. 3.2: size of uLong
  78898. 5.4: size of voidpf (pointer)
  78899. 7.6: size of z_off_t
  78900. Compiler, assembler, and debug options:
  78901. 8: DEBUG
  78902. 9: ASMV or ASMINF -- use ASM code
  78903. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  78904. 11: 0 (reserved)
  78905. One-time table building (smaller code, but not thread-safe if true):
  78906. 12: BUILDFIXED -- build static block decoding tables when needed
  78907. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  78908. 14,15: 0 (reserved)
  78909. Library content (indicates missing functionality):
  78910. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  78911. deflate code when not needed)
  78912. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  78913. and decode gzip streams (to avoid linking crc code)
  78914. 18-19: 0 (reserved)
  78915. Operation variations (changes in library functionality):
  78916. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  78917. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  78918. 22,23: 0 (reserved)
  78919. The sprintf variant used by gzprintf (zero is best):
  78920. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  78921. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  78922. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  78923. Remainder:
  78924. 27-31: 0 (reserved)
  78925. */
  78926. /* utility functions */
  78927. /*
  78928. The following utility functions are implemented on top of the
  78929. basic stream-oriented functions. To simplify the interface, some
  78930. default options are assumed (compression level and memory usage,
  78931. standard memory allocation functions). The source code of these
  78932. utility functions can easily be modified if you need special options.
  78933. */
  78934. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  78935. const Bytef *source, uLong sourceLen));
  78936. /*
  78937. Compresses the source buffer into the destination buffer. sourceLen is
  78938. the byte length of the source buffer. Upon entry, destLen is the total
  78939. size of the destination buffer, which must be at least the value returned
  78940. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78941. compressed buffer.
  78942. This function can be used to compress a whole file at once if the
  78943. input file is mmap'ed.
  78944. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  78945. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78946. buffer.
  78947. */
  78948. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  78949. const Bytef *source, uLong sourceLen,
  78950. int level));
  78951. /*
  78952. Compresses the source buffer into the destination buffer. The level
  78953. parameter has the same meaning as in deflateInit. sourceLen is the byte
  78954. length of the source buffer. Upon entry, destLen is the total size of the
  78955. destination buffer, which must be at least the value returned by
  78956. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78957. compressed buffer.
  78958. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78959. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  78960. Z_STREAM_ERROR if the level parameter is invalid.
  78961. */
  78962. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  78963. /*
  78964. compressBound() returns an upper bound on the compressed size after
  78965. compress() or compress2() on sourceLen bytes. It would be used before
  78966. a compress() or compress2() call to allocate the destination buffer.
  78967. */
  78968. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  78969. const Bytef *source, uLong sourceLen));
  78970. /*
  78971. Decompresses the source buffer into the destination buffer. sourceLen is
  78972. the byte length of the source buffer. Upon entry, destLen is the total
  78973. size of the destination buffer, which must be large enough to hold the
  78974. entire uncompressed data. (The size of the uncompressed data must have
  78975. been saved previously by the compressor and transmitted to the decompressor
  78976. by some mechanism outside the scope of this compression library.)
  78977. Upon exit, destLen is the actual size of the compressed buffer.
  78978. This function can be used to decompress a whole file at once if the
  78979. input file is mmap'ed.
  78980. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  78981. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78982. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  78983. */
  78984. typedef voidp gzFile;
  78985. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  78986. /*
  78987. Opens a gzip (.gz) file for reading or writing. The mode parameter
  78988. is as in fopen ("rb" or "wb") but can also include a compression level
  78989. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  78990. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  78991. as in "wb1R". (See the description of deflateInit2 for more information
  78992. about the strategy parameter.)
  78993. gzopen can be used to read a file which is not in gzip format; in this
  78994. case gzread will directly read from the file without decompression.
  78995. gzopen returns NULL if the file could not be opened or if there was
  78996. insufficient memory to allocate the (de)compression state; errno
  78997. can be checked to distinguish the two cases (if errno is zero, the
  78998. zlib error is Z_MEM_ERROR). */
  78999. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  79000. /*
  79001. gzdopen() associates a gzFile with the file descriptor fd. File
  79002. descriptors are obtained from calls like open, dup, creat, pipe or
  79003. fileno (in the file has been previously opened with fopen).
  79004. The mode parameter is as in gzopen.
  79005. The next call of gzclose on the returned gzFile will also close the
  79006. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  79007. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  79008. gzdopen returns NULL if there was insufficient memory to allocate
  79009. the (de)compression state.
  79010. */
  79011. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  79012. /*
  79013. Dynamically update the compression level or strategy. See the description
  79014. of deflateInit2 for the meaning of these parameters.
  79015. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  79016. opened for writing.
  79017. */
  79018. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79019. /*
  79020. Reads the given number of uncompressed bytes from the compressed file.
  79021. If the input file was not in gzip format, gzread copies the given number
  79022. of bytes into the buffer.
  79023. gzread returns the number of uncompressed bytes actually read (0 for
  79024. end of file, -1 for error). */
  79025. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79026. voidpc buf, unsigned len));
  79027. /*
  79028. Writes the given number of uncompressed bytes into the compressed file.
  79029. gzwrite returns the number of uncompressed bytes actually written
  79030. (0 in case of error).
  79031. */
  79032. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79033. /*
  79034. Converts, formats, and writes the args to the compressed file under
  79035. control of the format string, as in fprintf. gzprintf returns the number of
  79036. uncompressed bytes actually written (0 in case of error). The number of
  79037. uncompressed bytes written is limited to 4095. The caller should assure that
  79038. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79039. return an error (0) with nothing written. In this case, there may also be a
  79040. buffer overflow with unpredictable consequences, which is possible only if
  79041. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79042. because the secure snprintf() or vsnprintf() functions were not available.
  79043. */
  79044. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79045. /*
  79046. Writes the given null-terminated string to the compressed file, excluding
  79047. the terminating null character.
  79048. gzputs returns the number of characters written, or -1 in case of error.
  79049. */
  79050. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79051. /*
  79052. Reads bytes from the compressed file until len-1 characters are read, or
  79053. a newline character is read and transferred to buf, or an end-of-file
  79054. condition is encountered. The string is then terminated with a null
  79055. character.
  79056. gzgets returns buf, or Z_NULL in case of error.
  79057. */
  79058. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79059. /*
  79060. Writes c, converted to an unsigned char, into the compressed file.
  79061. gzputc returns the value that was written, or -1 in case of error.
  79062. */
  79063. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79064. /*
  79065. Reads one byte from the compressed file. gzgetc returns this byte
  79066. or -1 in case of end of file or error.
  79067. */
  79068. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79069. /*
  79070. Push one character back onto the stream to be read again later.
  79071. Only one character of push-back is allowed. gzungetc() returns the
  79072. character pushed, or -1 on failure. gzungetc() will fail if a
  79073. character has been pushed but not read yet, or if c is -1. The pushed
  79074. character will be discarded if the stream is repositioned with gzseek()
  79075. or gzrewind().
  79076. */
  79077. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79078. /*
  79079. Flushes all pending output into the compressed file. The parameter
  79080. flush is as in the deflate() function. The return value is the zlib
  79081. error number (see function gzerror below). gzflush returns Z_OK if
  79082. the flush parameter is Z_FINISH and all output could be flushed.
  79083. gzflush should be called only when strictly necessary because it can
  79084. degrade compression.
  79085. */
  79086. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79087. z_off_t offset, int whence));
  79088. /*
  79089. Sets the starting position for the next gzread or gzwrite on the
  79090. given compressed file. The offset represents a number of bytes in the
  79091. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79092. the value SEEK_END is not supported.
  79093. If the file is opened for reading, this function is emulated but can be
  79094. extremely slow. If the file is opened for writing, only forward seeks are
  79095. supported; gzseek then compresses a sequence of zeroes up to the new
  79096. starting position.
  79097. gzseek returns the resulting offset location as measured in bytes from
  79098. the beginning of the uncompressed stream, or -1 in case of error, in
  79099. particular if the file is opened for writing and the new starting position
  79100. would be before the current position.
  79101. */
  79102. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79103. /*
  79104. Rewinds the given file. This function is supported only for reading.
  79105. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79106. */
  79107. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79108. /*
  79109. Returns the starting position for the next gzread or gzwrite on the
  79110. given compressed file. This position represents a number of bytes in the
  79111. uncompressed data stream.
  79112. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79113. */
  79114. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79115. /*
  79116. Returns 1 when EOF has previously been detected reading the given
  79117. input stream, otherwise zero.
  79118. */
  79119. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79120. /*
  79121. Returns 1 if file is being read directly without decompression, otherwise
  79122. zero.
  79123. */
  79124. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79125. /*
  79126. Flushes all pending output if necessary, closes the compressed file
  79127. and deallocates all the (de)compression state. The return value is the zlib
  79128. error number (see function gzerror below).
  79129. */
  79130. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79131. /*
  79132. Returns the error message for the last error which occurred on the
  79133. given compressed file. errnum is set to zlib error number. If an
  79134. error occurred in the file system and not in the compression library,
  79135. errnum is set to Z_ERRNO and the application may consult errno
  79136. to get the exact error code.
  79137. */
  79138. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79139. /*
  79140. Clears the error and end-of-file flags for file. This is analogous to the
  79141. clearerr() function in stdio. This is useful for continuing to read a gzip
  79142. file that is being written concurrently.
  79143. */
  79144. /* checksum functions */
  79145. /*
  79146. These functions are not related to compression but are exported
  79147. anyway because they might be useful in applications using the
  79148. compression library.
  79149. */
  79150. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79151. /*
  79152. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79153. return the updated checksum. If buf is NULL, this function returns
  79154. the required initial value for the checksum.
  79155. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79156. much faster. Usage example:
  79157. uLong adler = adler32(0L, Z_NULL, 0);
  79158. while (read_buffer(buffer, length) != EOF) {
  79159. adler = adler32(adler, buffer, length);
  79160. }
  79161. if (adler != original_adler) error();
  79162. */
  79163. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79164. z_off_t len2));
  79165. /*
  79166. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79167. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79168. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79169. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79170. */
  79171. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79172. /*
  79173. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79174. updated CRC-32. If buf is NULL, this function returns the required initial
  79175. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79176. performed within this function so it shouldn't be done by the application.
  79177. Usage example:
  79178. uLong crc = crc32(0L, Z_NULL, 0);
  79179. while (read_buffer(buffer, length) != EOF) {
  79180. crc = crc32(crc, buffer, length);
  79181. }
  79182. if (crc != original_crc) error();
  79183. */
  79184. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79185. /*
  79186. Combine two CRC-32 check values into one. For two sequences of bytes,
  79187. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79188. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79189. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79190. len2.
  79191. */
  79192. /* various hacks, don't look :) */
  79193. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79194. * and the compiler's view of z_stream:
  79195. */
  79196. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79197. const char *version, int stream_size));
  79198. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79199. const char *version, int stream_size));
  79200. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79201. int windowBits, int memLevel,
  79202. int strategy, const char *version,
  79203. int stream_size));
  79204. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79205. const char *version, int stream_size));
  79206. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79207. unsigned char FAR *window,
  79208. const char *version,
  79209. int stream_size));
  79210. #define deflateInit(strm, level) \
  79211. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79212. #define inflateInit(strm) \
  79213. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79214. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79215. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79216. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79217. #define inflateInit2(strm, windowBits) \
  79218. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79219. #define inflateBackInit(strm, windowBits, window) \
  79220. inflateBackInit_((strm), (windowBits), (window), \
  79221. ZLIB_VERSION, sizeof(z_stream))
  79222. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79223. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79224. #endif
  79225. ZEXTERN const char * ZEXPORT zError OF((int));
  79226. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79227. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79228. #ifdef __cplusplus
  79229. //}
  79230. #endif
  79231. #endif /* ZLIB_H */
  79232. /*** End of inlined file: zlib.h ***/
  79233. #undef OS_CODE
  79234. #else
  79235. #include <zlib.h>
  79236. #endif
  79237. }
  79238. BEGIN_JUCE_NAMESPACE
  79239. class GZIPCompressorOutputStream::GZIPCompressorHelper
  79240. {
  79241. public:
  79242. GZIPCompressorHelper (const int compressionLevel, const int windowBits)
  79243. : data (0),
  79244. dataSize (0),
  79245. compLevel (compressionLevel),
  79246. strategy (0),
  79247. setParams (true),
  79248. streamIsValid (false),
  79249. finished (false),
  79250. shouldFinish (false)
  79251. {
  79252. using namespace zlibNamespace;
  79253. zerostruct (stream);
  79254. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79255. windowBits != 0 ? windowBits : MAX_WBITS,
  79256. 8, strategy) == Z_OK);
  79257. }
  79258. ~GZIPCompressorHelper()
  79259. {
  79260. using namespace zlibNamespace;
  79261. if (streamIsValid)
  79262. deflateEnd (&stream);
  79263. }
  79264. bool needsInput() const throw()
  79265. {
  79266. return dataSize <= 0;
  79267. }
  79268. void setInput (const uint8* const newData, const int size) throw()
  79269. {
  79270. data = newData;
  79271. dataSize = size;
  79272. }
  79273. int doNextBlock (uint8* const dest, const int destSize) throw()
  79274. {
  79275. using namespace zlibNamespace;
  79276. if (streamIsValid)
  79277. {
  79278. stream.next_in = const_cast <uint8*> (data);
  79279. stream.next_out = dest;
  79280. stream.avail_in = dataSize;
  79281. stream.avail_out = destSize;
  79282. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79283. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79284. setParams = false;
  79285. switch (result)
  79286. {
  79287. case Z_STREAM_END:
  79288. finished = true;
  79289. // Deliberate fall-through..
  79290. case Z_OK:
  79291. data += dataSize - stream.avail_in;
  79292. dataSize = stream.avail_in;
  79293. return destSize - stream.avail_out;
  79294. default:
  79295. break;
  79296. }
  79297. }
  79298. return 0;
  79299. }
  79300. enum { gzipCompBufferSize = 32768 };
  79301. private:
  79302. zlibNamespace::z_stream stream;
  79303. const uint8* data;
  79304. int dataSize, compLevel, strategy;
  79305. bool setParams, streamIsValid;
  79306. public:
  79307. bool finished, shouldFinish;
  79308. };
  79309. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79310. int compressionLevel,
  79311. const bool deleteDestStream,
  79312. const int windowBits)
  79313. : destStream (destStream_),
  79314. streamToDelete (deleteDestStream ? destStream_ : 0),
  79315. buffer ((size_t) GZIPCompressorHelper::gzipCompBufferSize)
  79316. {
  79317. if (compressionLevel < 1 || compressionLevel > 9)
  79318. compressionLevel = -1;
  79319. helper = new GZIPCompressorHelper (compressionLevel, windowBits);
  79320. }
  79321. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79322. {
  79323. flush();
  79324. }
  79325. void GZIPCompressorOutputStream::flush()
  79326. {
  79327. if (! helper->finished)
  79328. {
  79329. helper->shouldFinish = true;
  79330. while (! helper->finished)
  79331. doNextBlock();
  79332. }
  79333. destStream->flush();
  79334. }
  79335. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79336. {
  79337. if (! helper->finished)
  79338. {
  79339. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79340. while (! helper->needsInput())
  79341. {
  79342. if (! doNextBlock())
  79343. return false;
  79344. }
  79345. }
  79346. return true;
  79347. }
  79348. bool GZIPCompressorOutputStream::doNextBlock()
  79349. {
  79350. const int len = helper->doNextBlock (buffer, (int) GZIPCompressorHelper::gzipCompBufferSize);
  79351. return len <= 0 || destStream->write (buffer, len);
  79352. }
  79353. int64 GZIPCompressorOutputStream::getPosition()
  79354. {
  79355. return destStream->getPosition();
  79356. }
  79357. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79358. {
  79359. jassertfalse; // can't do it!
  79360. return false;
  79361. }
  79362. END_JUCE_NAMESPACE
  79363. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79364. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79365. #if JUCE_MSVC
  79366. #pragma warning (push)
  79367. #pragma warning (disable: 4309 4305)
  79368. #endif
  79369. namespace zlibNamespace
  79370. {
  79371. #if JUCE_INCLUDE_ZLIB_CODE
  79372. #undef OS_CODE
  79373. #undef fdopen
  79374. #define ZLIB_INTERNAL
  79375. #define NO_DUMMY_DECL
  79376. /*** Start of inlined file: adler32.c ***/
  79377. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79378. #define ZLIB_INTERNAL
  79379. #define BASE 65521UL /* largest prime smaller than 65536 */
  79380. #define NMAX 5552
  79381. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79382. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79383. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79384. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79385. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79386. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79387. /* use NO_DIVIDE if your processor does not do division in hardware */
  79388. #ifdef NO_DIVIDE
  79389. # define MOD(a) \
  79390. do { \
  79391. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79392. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79393. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79394. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79395. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79396. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79397. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79398. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79399. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79400. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79401. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79402. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79403. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79404. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79405. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79406. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79407. if (a >= BASE) a -= BASE; \
  79408. } while (0)
  79409. # define MOD4(a) \
  79410. do { \
  79411. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79412. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79413. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79414. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79415. if (a >= BASE) a -= BASE; \
  79416. } while (0)
  79417. #else
  79418. # define MOD(a) a %= BASE
  79419. # define MOD4(a) a %= BASE
  79420. #endif
  79421. /* ========================================================================= */
  79422. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79423. {
  79424. unsigned long sum2;
  79425. unsigned n;
  79426. /* split Adler-32 into component sums */
  79427. sum2 = (adler >> 16) & 0xffff;
  79428. adler &= 0xffff;
  79429. /* in case user likes doing a byte at a time, keep it fast */
  79430. if (len == 1) {
  79431. adler += buf[0];
  79432. if (adler >= BASE)
  79433. adler -= BASE;
  79434. sum2 += adler;
  79435. if (sum2 >= BASE)
  79436. sum2 -= BASE;
  79437. return adler | (sum2 << 16);
  79438. }
  79439. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79440. if (buf == Z_NULL)
  79441. return 1L;
  79442. /* in case short lengths are provided, keep it somewhat fast */
  79443. if (len < 16) {
  79444. while (len--) {
  79445. adler += *buf++;
  79446. sum2 += adler;
  79447. }
  79448. if (adler >= BASE)
  79449. adler -= BASE;
  79450. MOD4(sum2); /* only added so many BASE's */
  79451. return adler | (sum2 << 16);
  79452. }
  79453. /* do length NMAX blocks -- requires just one modulo operation */
  79454. while (len >= NMAX) {
  79455. len -= NMAX;
  79456. n = NMAX / 16; /* NMAX is divisible by 16 */
  79457. do {
  79458. DO16(buf); /* 16 sums unrolled */
  79459. buf += 16;
  79460. } while (--n);
  79461. MOD(adler);
  79462. MOD(sum2);
  79463. }
  79464. /* do remaining bytes (less than NMAX, still just one modulo) */
  79465. if (len) { /* avoid modulos if none remaining */
  79466. while (len >= 16) {
  79467. len -= 16;
  79468. DO16(buf);
  79469. buf += 16;
  79470. }
  79471. while (len--) {
  79472. adler += *buf++;
  79473. sum2 += adler;
  79474. }
  79475. MOD(adler);
  79476. MOD(sum2);
  79477. }
  79478. /* return recombined sums */
  79479. return adler | (sum2 << 16);
  79480. }
  79481. /* ========================================================================= */
  79482. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79483. {
  79484. unsigned long sum1;
  79485. unsigned long sum2;
  79486. unsigned rem;
  79487. /* the derivation of this formula is left as an exercise for the reader */
  79488. rem = (unsigned)(len2 % BASE);
  79489. sum1 = adler1 & 0xffff;
  79490. sum2 = rem * sum1;
  79491. MOD(sum2);
  79492. sum1 += (adler2 & 0xffff) + BASE - 1;
  79493. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79494. if (sum1 > BASE) sum1 -= BASE;
  79495. if (sum1 > BASE) sum1 -= BASE;
  79496. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  79497. if (sum2 > BASE) sum2 -= BASE;
  79498. return sum1 | (sum2 << 16);
  79499. }
  79500. /*** End of inlined file: adler32.c ***/
  79501. /*** Start of inlined file: compress.c ***/
  79502. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79503. #define ZLIB_INTERNAL
  79504. /* ===========================================================================
  79505. Compresses the source buffer into the destination buffer. The level
  79506. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79507. length of the source buffer. Upon entry, destLen is the total size of the
  79508. destination buffer, which must be at least 0.1% larger than sourceLen plus
  79509. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  79510. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79511. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79512. Z_STREAM_ERROR if the level parameter is invalid.
  79513. */
  79514. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  79515. uLong sourceLen, int level)
  79516. {
  79517. z_stream stream;
  79518. int err;
  79519. stream.next_in = (Bytef*)source;
  79520. stream.avail_in = (uInt)sourceLen;
  79521. #ifdef MAXSEG_64K
  79522. /* Check for source > 64K on 16-bit machine: */
  79523. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79524. #endif
  79525. stream.next_out = dest;
  79526. stream.avail_out = (uInt)*destLen;
  79527. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79528. stream.zalloc = (alloc_func)0;
  79529. stream.zfree = (free_func)0;
  79530. stream.opaque = (voidpf)0;
  79531. err = deflateInit(&stream, level);
  79532. if (err != Z_OK) return err;
  79533. err = deflate(&stream, Z_FINISH);
  79534. if (err != Z_STREAM_END) {
  79535. deflateEnd(&stream);
  79536. return err == Z_OK ? Z_BUF_ERROR : err;
  79537. }
  79538. *destLen = stream.total_out;
  79539. err = deflateEnd(&stream);
  79540. return err;
  79541. }
  79542. /* ===========================================================================
  79543. */
  79544. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  79545. {
  79546. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  79547. }
  79548. /* ===========================================================================
  79549. If the default memLevel or windowBits for deflateInit() is changed, then
  79550. this function needs to be updated.
  79551. */
  79552. uLong ZEXPORT compressBound (uLong sourceLen)
  79553. {
  79554. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  79555. }
  79556. /*** End of inlined file: compress.c ***/
  79557. #undef DO1
  79558. #undef DO8
  79559. /*** Start of inlined file: crc32.c ***/
  79560. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79561. /*
  79562. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  79563. protection on the static variables used to control the first-use generation
  79564. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  79565. first call get_crc_table() to initialize the tables before allowing more than
  79566. one thread to use crc32().
  79567. */
  79568. #ifdef MAKECRCH
  79569. # include <stdio.h>
  79570. # ifndef DYNAMIC_CRC_TABLE
  79571. # define DYNAMIC_CRC_TABLE
  79572. # endif /* !DYNAMIC_CRC_TABLE */
  79573. #endif /* MAKECRCH */
  79574. /*** Start of inlined file: zutil.h ***/
  79575. /* WARNING: this file should *not* be used by applications. It is
  79576. part of the implementation of the compression library and is
  79577. subject to change. Applications should only use zlib.h.
  79578. */
  79579. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79580. #ifndef ZUTIL_H
  79581. #define ZUTIL_H
  79582. #define ZLIB_INTERNAL
  79583. #ifdef STDC
  79584. # ifndef _WIN32_WCE
  79585. # include <stddef.h>
  79586. # endif
  79587. # include <string.h>
  79588. # include <stdlib.h>
  79589. #endif
  79590. #ifdef NO_ERRNO_H
  79591. # ifdef _WIN32_WCE
  79592. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79593. * errno. We define it as a global variable to simplify porting.
  79594. * Its value is always 0 and should not be used. We rename it to
  79595. * avoid conflict with other libraries that use the same workaround.
  79596. */
  79597. # define errno z_errno
  79598. # endif
  79599. extern int errno;
  79600. #else
  79601. # ifndef _WIN32_WCE
  79602. # include <errno.h>
  79603. # endif
  79604. #endif
  79605. #ifndef local
  79606. # define local static
  79607. #endif
  79608. /* compile with -Dlocal if your debugger can't find static symbols */
  79609. typedef unsigned char uch;
  79610. typedef uch FAR uchf;
  79611. typedef unsigned short ush;
  79612. typedef ush FAR ushf;
  79613. typedef unsigned long ulg;
  79614. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  79615. /* (size given to avoid silly warnings with Visual C++) */
  79616. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  79617. #define ERR_RETURN(strm,err) \
  79618. return (strm->msg = (char*)ERR_MSG(err), (err))
  79619. /* To be used only when the state is known to be valid */
  79620. /* common constants */
  79621. #ifndef DEF_WBITS
  79622. # define DEF_WBITS MAX_WBITS
  79623. #endif
  79624. /* default windowBits for decompression. MAX_WBITS is for compression only */
  79625. #if MAX_MEM_LEVEL >= 8
  79626. # define DEF_MEM_LEVEL 8
  79627. #else
  79628. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  79629. #endif
  79630. /* default memLevel */
  79631. #define STORED_BLOCK 0
  79632. #define STATIC_TREES 1
  79633. #define DYN_TREES 2
  79634. /* The three kinds of block type */
  79635. #define MIN_MATCH 3
  79636. #define MAX_MATCH 258
  79637. /* The minimum and maximum match lengths */
  79638. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  79639. /* target dependencies */
  79640. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  79641. # define OS_CODE 0x00
  79642. # if defined(__TURBOC__) || defined(__BORLANDC__)
  79643. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  79644. /* Allow compilation with ANSI keywords only enabled */
  79645. void _Cdecl farfree( void *block );
  79646. void *_Cdecl farmalloc( unsigned long nbytes );
  79647. # else
  79648. # include <alloc.h>
  79649. # endif
  79650. # else /* MSC or DJGPP */
  79651. # include <malloc.h>
  79652. # endif
  79653. #endif
  79654. #ifdef AMIGA
  79655. # define OS_CODE 0x01
  79656. #endif
  79657. #if defined(VAXC) || defined(VMS)
  79658. # define OS_CODE 0x02
  79659. # define F_OPEN(name, mode) \
  79660. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  79661. #endif
  79662. #if defined(ATARI) || defined(atarist)
  79663. # define OS_CODE 0x05
  79664. #endif
  79665. #ifdef OS2
  79666. # define OS_CODE 0x06
  79667. # ifdef M_I86
  79668. #include <malloc.h>
  79669. # endif
  79670. #endif
  79671. #if defined(MACOS) || TARGET_OS_MAC
  79672. # define OS_CODE 0x07
  79673. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  79674. # include <unix.h> /* for fdopen */
  79675. # else
  79676. # ifndef fdopen
  79677. # define fdopen(fd,mode) NULL /* No fdopen() */
  79678. # endif
  79679. # endif
  79680. #endif
  79681. #ifdef TOPS20
  79682. # define OS_CODE 0x0a
  79683. #endif
  79684. #ifdef WIN32
  79685. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  79686. # define OS_CODE 0x0b
  79687. # endif
  79688. #endif
  79689. #ifdef __50SERIES /* Prime/PRIMOS */
  79690. # define OS_CODE 0x0f
  79691. #endif
  79692. #if defined(_BEOS_) || defined(RISCOS)
  79693. # define fdopen(fd,mode) NULL /* No fdopen() */
  79694. #endif
  79695. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  79696. # if defined(_WIN32_WCE)
  79697. # define fdopen(fd,mode) NULL /* No fdopen() */
  79698. # ifndef _PTRDIFF_T_DEFINED
  79699. typedef int ptrdiff_t;
  79700. # define _PTRDIFF_T_DEFINED
  79701. # endif
  79702. # else
  79703. # define fdopen(fd,type) _fdopen(fd,type)
  79704. # endif
  79705. #endif
  79706. /* common defaults */
  79707. #ifndef OS_CODE
  79708. # define OS_CODE 0x03 /* assume Unix */
  79709. #endif
  79710. #ifndef F_OPEN
  79711. # define F_OPEN(name, mode) fopen((name), (mode))
  79712. #endif
  79713. /* functions */
  79714. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  79715. # ifndef HAVE_VSNPRINTF
  79716. # define HAVE_VSNPRINTF
  79717. # endif
  79718. #endif
  79719. #if defined(__CYGWIN__)
  79720. # ifndef HAVE_VSNPRINTF
  79721. # define HAVE_VSNPRINTF
  79722. # endif
  79723. #endif
  79724. #ifndef HAVE_VSNPRINTF
  79725. # ifdef MSDOS
  79726. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  79727. but for now we just assume it doesn't. */
  79728. # define NO_vsnprintf
  79729. # endif
  79730. # ifdef __TURBOC__
  79731. # define NO_vsnprintf
  79732. # endif
  79733. # ifdef WIN32
  79734. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  79735. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  79736. # define vsnprintf _vsnprintf
  79737. # endif
  79738. # endif
  79739. # ifdef __SASC
  79740. # define NO_vsnprintf
  79741. # endif
  79742. #endif
  79743. #ifdef VMS
  79744. # define NO_vsnprintf
  79745. #endif
  79746. #if defined(pyr)
  79747. # define NO_MEMCPY
  79748. #endif
  79749. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  79750. /* Use our own functions for small and medium model with MSC <= 5.0.
  79751. * You may have to use the same strategy for Borland C (untested).
  79752. * The __SC__ check is for Symantec.
  79753. */
  79754. # define NO_MEMCPY
  79755. #endif
  79756. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  79757. # define HAVE_MEMCPY
  79758. #endif
  79759. #ifdef HAVE_MEMCPY
  79760. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  79761. # define zmemcpy _fmemcpy
  79762. # define zmemcmp _fmemcmp
  79763. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  79764. # else
  79765. # define zmemcpy memcpy
  79766. # define zmemcmp memcmp
  79767. # define zmemzero(dest, len) memset(dest, 0, len)
  79768. # endif
  79769. #else
  79770. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  79771. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  79772. extern void zmemzero OF((Bytef* dest, uInt len));
  79773. #endif
  79774. /* Diagnostic functions */
  79775. #ifdef DEBUG
  79776. # include <stdio.h>
  79777. extern int z_verbose;
  79778. extern void z_error OF((const char *m));
  79779. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  79780. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  79781. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  79782. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  79783. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  79784. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  79785. #else
  79786. # define Assert(cond,msg)
  79787. # define Trace(x)
  79788. # define Tracev(x)
  79789. # define Tracevv(x)
  79790. # define Tracec(c,x)
  79791. # define Tracecv(c,x)
  79792. #endif
  79793. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  79794. void zcfree OF((voidpf opaque, voidpf ptr));
  79795. #define ZALLOC(strm, items, size) \
  79796. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  79797. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  79798. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  79799. #endif /* ZUTIL_H */
  79800. /*** End of inlined file: zutil.h ***/
  79801. /* for STDC and FAR definitions */
  79802. #define local static
  79803. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  79804. #ifndef NOBYFOUR
  79805. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  79806. # include <limits.h>
  79807. # define BYFOUR
  79808. # if (UINT_MAX == 0xffffffffUL)
  79809. typedef unsigned int u4;
  79810. # else
  79811. # if (ULONG_MAX == 0xffffffffUL)
  79812. typedef unsigned long u4;
  79813. # else
  79814. # if (USHRT_MAX == 0xffffffffUL)
  79815. typedef unsigned short u4;
  79816. # else
  79817. # undef BYFOUR /* can't find a four-byte integer type! */
  79818. # endif
  79819. # endif
  79820. # endif
  79821. # endif /* STDC */
  79822. #endif /* !NOBYFOUR */
  79823. /* Definitions for doing the crc four data bytes at a time. */
  79824. #ifdef BYFOUR
  79825. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  79826. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  79827. local unsigned long crc32_little OF((unsigned long,
  79828. const unsigned char FAR *, unsigned));
  79829. local unsigned long crc32_big OF((unsigned long,
  79830. const unsigned char FAR *, unsigned));
  79831. # define TBLS 8
  79832. #else
  79833. # define TBLS 1
  79834. #endif /* BYFOUR */
  79835. /* Local functions for crc concatenation */
  79836. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  79837. unsigned long vec));
  79838. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  79839. #ifdef DYNAMIC_CRC_TABLE
  79840. local volatile int crc_table_empty = 1;
  79841. local unsigned long FAR crc_table[TBLS][256];
  79842. local void make_crc_table OF((void));
  79843. #ifdef MAKECRCH
  79844. local void write_table OF((FILE *, const unsigned long FAR *));
  79845. #endif /* MAKECRCH */
  79846. /*
  79847. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  79848. 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.
  79849. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  79850. with the lowest powers in the most significant bit. Then adding polynomials
  79851. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  79852. one. If we call the above polynomial p, and represent a byte as the
  79853. polynomial q, also with the lowest power in the most significant bit (so the
  79854. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  79855. where a mod b means the remainder after dividing a by b.
  79856. This calculation is done using the shift-register method of multiplying and
  79857. taking the remainder. The register is initialized to zero, and for each
  79858. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  79859. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  79860. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  79861. out is a one). We start with the highest power (least significant bit) of
  79862. q and repeat for all eight bits of q.
  79863. The first table is simply the CRC of all possible eight bit values. This is
  79864. all the information needed to generate CRCs on data a byte at a time for all
  79865. combinations of CRC register values and incoming bytes. The remaining tables
  79866. allow for word-at-a-time CRC calculation for both big-endian and little-
  79867. endian machines, where a word is four bytes.
  79868. */
  79869. local void make_crc_table()
  79870. {
  79871. unsigned long c;
  79872. int n, k;
  79873. unsigned long poly; /* polynomial exclusive-or pattern */
  79874. /* terms of polynomial defining this crc (except x^32): */
  79875. static volatile int first = 1; /* flag to limit concurrent making */
  79876. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  79877. /* See if another task is already doing this (not thread-safe, but better
  79878. than nothing -- significantly reduces duration of vulnerability in
  79879. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  79880. if (first) {
  79881. first = 0;
  79882. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  79883. poly = 0UL;
  79884. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  79885. poly |= 1UL << (31 - p[n]);
  79886. /* generate a crc for every 8-bit value */
  79887. for (n = 0; n < 256; n++) {
  79888. c = (unsigned long)n;
  79889. for (k = 0; k < 8; k++)
  79890. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  79891. crc_table[0][n] = c;
  79892. }
  79893. #ifdef BYFOUR
  79894. /* generate crc for each value followed by one, two, and three zeros,
  79895. and then the byte reversal of those as well as the first table */
  79896. for (n = 0; n < 256; n++) {
  79897. c = crc_table[0][n];
  79898. crc_table[4][n] = REV(c);
  79899. for (k = 1; k < 4; k++) {
  79900. c = crc_table[0][c & 0xff] ^ (c >> 8);
  79901. crc_table[k][n] = c;
  79902. crc_table[k + 4][n] = REV(c);
  79903. }
  79904. }
  79905. #endif /* BYFOUR */
  79906. crc_table_empty = 0;
  79907. }
  79908. else { /* not first */
  79909. /* wait for the other guy to finish (not efficient, but rare) */
  79910. while (crc_table_empty)
  79911. ;
  79912. }
  79913. #ifdef MAKECRCH
  79914. /* write out CRC tables to crc32.h */
  79915. {
  79916. FILE *out;
  79917. out = fopen("crc32.h", "w");
  79918. if (out == NULL) return;
  79919. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  79920. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  79921. fprintf(out, "local const unsigned long FAR ");
  79922. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  79923. write_table(out, crc_table[0]);
  79924. # ifdef BYFOUR
  79925. fprintf(out, "#ifdef BYFOUR\n");
  79926. for (k = 1; k < 8; k++) {
  79927. fprintf(out, " },\n {\n");
  79928. write_table(out, crc_table[k]);
  79929. }
  79930. fprintf(out, "#endif\n");
  79931. # endif /* BYFOUR */
  79932. fprintf(out, " }\n};\n");
  79933. fclose(out);
  79934. }
  79935. #endif /* MAKECRCH */
  79936. }
  79937. #ifdef MAKECRCH
  79938. local void write_table(out, table)
  79939. FILE *out;
  79940. const unsigned long FAR *table;
  79941. {
  79942. int n;
  79943. for (n = 0; n < 256; n++)
  79944. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  79945. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  79946. }
  79947. #endif /* MAKECRCH */
  79948. #else /* !DYNAMIC_CRC_TABLE */
  79949. /* ========================================================================
  79950. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  79951. */
  79952. /*** Start of inlined file: crc32.h ***/
  79953. local const unsigned long FAR crc_table[TBLS][256] =
  79954. {
  79955. {
  79956. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  79957. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  79958. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  79959. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  79960. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  79961. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  79962. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  79963. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  79964. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  79965. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  79966. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  79967. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  79968. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  79969. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  79970. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  79971. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  79972. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  79973. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  79974. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  79975. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  79976. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  79977. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  79978. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  79979. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  79980. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  79981. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  79982. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  79983. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  79984. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  79985. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  79986. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  79987. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  79988. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  79989. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  79990. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  79991. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  79992. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  79993. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  79994. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  79995. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  79996. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  79997. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  79998. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  79999. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  80000. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  80001. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  80002. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  80003. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  80004. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  80005. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  80006. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  80007. 0x2d02ef8dUL
  80008. #ifdef BYFOUR
  80009. },
  80010. {
  80011. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  80012. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  80013. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  80014. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  80015. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  80016. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  80017. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  80018. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80019. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80020. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80021. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80022. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80023. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80024. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80025. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80026. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80027. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80028. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80029. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80030. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80031. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80032. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80033. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80034. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80035. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80036. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80037. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80038. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80039. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80040. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80041. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80042. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80043. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80044. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80045. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80046. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80047. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80048. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80049. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80050. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80051. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80052. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80053. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80054. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80055. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80056. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80057. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80058. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80059. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80060. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80061. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80062. 0x9324fd72UL
  80063. },
  80064. {
  80065. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80066. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80067. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80068. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80069. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80070. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80071. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80072. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80073. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80074. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80075. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80076. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80077. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80078. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80079. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80080. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80081. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80082. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80083. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80084. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80085. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80086. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80087. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80088. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80089. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80090. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80091. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80092. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80093. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80094. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80095. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80096. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80097. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80098. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80099. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80100. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80101. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80102. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80103. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80104. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80105. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80106. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80107. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80108. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80109. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80110. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80111. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80112. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80113. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80114. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80115. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80116. 0xbe9834edUL
  80117. },
  80118. {
  80119. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80120. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80121. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80122. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80123. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80124. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80125. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80126. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80127. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80128. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80129. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80130. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80131. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80132. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80133. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80134. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80135. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80136. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80137. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80138. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80139. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80140. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80141. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80142. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80143. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80144. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80145. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80146. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80147. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80148. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80149. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80150. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80151. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80152. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80153. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80154. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80155. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80156. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80157. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80158. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80159. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80160. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80161. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80162. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80163. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80164. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80165. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80166. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80167. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80168. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80169. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80170. 0xde0506f1UL
  80171. },
  80172. {
  80173. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80174. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80175. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80176. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80177. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80178. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80179. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80180. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80181. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80182. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80183. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80184. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80185. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80186. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80187. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80188. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80189. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80190. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80191. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80192. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80193. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80194. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80195. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80196. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80197. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80198. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80199. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80200. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80201. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80202. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80203. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80204. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80205. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80206. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80207. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80208. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80209. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80210. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80211. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80212. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80213. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80214. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80215. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80216. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80217. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80218. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80219. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80220. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80221. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80222. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80223. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80224. 0x8def022dUL
  80225. },
  80226. {
  80227. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80228. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80229. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80230. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80231. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80232. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80233. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80234. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80235. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80236. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80237. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80238. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80239. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80240. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80241. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80242. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80243. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80244. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80245. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80246. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80247. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80248. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80249. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80250. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80251. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80252. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80253. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80254. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80255. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80256. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80257. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80258. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80259. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80260. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80261. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80262. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80263. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80264. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80265. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80266. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80267. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80268. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80269. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80270. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80271. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80272. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80273. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80274. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80275. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80276. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80277. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80278. 0x72fd2493UL
  80279. },
  80280. {
  80281. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80282. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80283. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80284. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80285. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80286. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80287. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80288. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80289. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80290. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80291. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80292. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80293. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80294. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80295. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80296. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80297. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80298. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80299. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80300. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80301. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80302. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80303. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80304. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80305. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80306. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80307. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80308. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80309. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80310. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80311. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80312. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80313. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80314. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80315. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80316. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80317. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80318. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80319. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80320. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80321. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80322. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80323. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80324. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80325. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80326. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80327. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80328. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80329. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80330. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80331. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80332. 0xed3498beUL
  80333. },
  80334. {
  80335. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80336. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80337. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80338. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80339. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80340. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80341. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80342. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80343. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80344. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80345. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80346. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80347. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80348. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80349. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80350. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80351. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80352. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80353. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80354. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80355. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80356. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80357. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80358. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80359. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80360. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80361. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80362. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80363. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80364. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80365. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80366. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80367. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80368. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80369. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80370. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80371. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80372. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80373. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80374. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80375. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80376. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80377. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80378. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80379. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80380. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80381. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80382. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80383. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80384. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80385. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80386. 0xf10605deUL
  80387. #endif
  80388. }
  80389. };
  80390. /*** End of inlined file: crc32.h ***/
  80391. #endif /* DYNAMIC_CRC_TABLE */
  80392. /* =========================================================================
  80393. * This function can be used by asm versions of crc32()
  80394. */
  80395. const unsigned long FAR * ZEXPORT get_crc_table()
  80396. {
  80397. #ifdef DYNAMIC_CRC_TABLE
  80398. if (crc_table_empty)
  80399. make_crc_table();
  80400. #endif /* DYNAMIC_CRC_TABLE */
  80401. return (const unsigned long FAR *)crc_table;
  80402. }
  80403. /* ========================================================================= */
  80404. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80405. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80406. /* ========================================================================= */
  80407. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80408. {
  80409. if (buf == Z_NULL) return 0UL;
  80410. #ifdef DYNAMIC_CRC_TABLE
  80411. if (crc_table_empty)
  80412. make_crc_table();
  80413. #endif /* DYNAMIC_CRC_TABLE */
  80414. #ifdef BYFOUR
  80415. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80416. u4 endian;
  80417. endian = 1;
  80418. if (*((unsigned char *)(&endian)))
  80419. return crc32_little(crc, buf, len);
  80420. else
  80421. return crc32_big(crc, buf, len);
  80422. }
  80423. #endif /* BYFOUR */
  80424. crc = crc ^ 0xffffffffUL;
  80425. while (len >= 8) {
  80426. DO8;
  80427. len -= 8;
  80428. }
  80429. if (len) do {
  80430. DO1;
  80431. } while (--len);
  80432. return crc ^ 0xffffffffUL;
  80433. }
  80434. #ifdef BYFOUR
  80435. /* ========================================================================= */
  80436. #define DOLIT4 c ^= *buf4++; \
  80437. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80438. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80439. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80440. /* ========================================================================= */
  80441. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80442. {
  80443. register u4 c;
  80444. register const u4 FAR *buf4;
  80445. c = (u4)crc;
  80446. c = ~c;
  80447. while (len && ((ptrdiff_t)buf & 3)) {
  80448. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80449. len--;
  80450. }
  80451. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80452. while (len >= 32) {
  80453. DOLIT32;
  80454. len -= 32;
  80455. }
  80456. while (len >= 4) {
  80457. DOLIT4;
  80458. len -= 4;
  80459. }
  80460. buf = (const unsigned char FAR *)buf4;
  80461. if (len) do {
  80462. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80463. } while (--len);
  80464. c = ~c;
  80465. return (unsigned long)c;
  80466. }
  80467. /* ========================================================================= */
  80468. #define DOBIG4 c ^= *++buf4; \
  80469. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80470. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80471. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80472. /* ========================================================================= */
  80473. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80474. {
  80475. register u4 c;
  80476. register const u4 FAR *buf4;
  80477. c = REV((u4)crc);
  80478. c = ~c;
  80479. while (len && ((ptrdiff_t)buf & 3)) {
  80480. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80481. len--;
  80482. }
  80483. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80484. buf4--;
  80485. while (len >= 32) {
  80486. DOBIG32;
  80487. len -= 32;
  80488. }
  80489. while (len >= 4) {
  80490. DOBIG4;
  80491. len -= 4;
  80492. }
  80493. buf4++;
  80494. buf = (const unsigned char FAR *)buf4;
  80495. if (len) do {
  80496. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80497. } while (--len);
  80498. c = ~c;
  80499. return (unsigned long)(REV(c));
  80500. }
  80501. #endif /* BYFOUR */
  80502. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  80503. /* ========================================================================= */
  80504. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  80505. {
  80506. unsigned long sum;
  80507. sum = 0;
  80508. while (vec) {
  80509. if (vec & 1)
  80510. sum ^= *mat;
  80511. vec >>= 1;
  80512. mat++;
  80513. }
  80514. return sum;
  80515. }
  80516. /* ========================================================================= */
  80517. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  80518. {
  80519. int n;
  80520. for (n = 0; n < GF2_DIM; n++)
  80521. square[n] = gf2_matrix_times(mat, mat[n]);
  80522. }
  80523. /* ========================================================================= */
  80524. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  80525. {
  80526. int n;
  80527. unsigned long row;
  80528. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  80529. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  80530. /* degenerate case */
  80531. if (len2 == 0)
  80532. return crc1;
  80533. /* put operator for one zero bit in odd */
  80534. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  80535. row = 1;
  80536. for (n = 1; n < GF2_DIM; n++) {
  80537. odd[n] = row;
  80538. row <<= 1;
  80539. }
  80540. /* put operator for two zero bits in even */
  80541. gf2_matrix_square(even, odd);
  80542. /* put operator for four zero bits in odd */
  80543. gf2_matrix_square(odd, even);
  80544. /* apply len2 zeros to crc1 (first square will put the operator for one
  80545. zero byte, eight zero bits, in even) */
  80546. do {
  80547. /* apply zeros operator for this bit of len2 */
  80548. gf2_matrix_square(even, odd);
  80549. if (len2 & 1)
  80550. crc1 = gf2_matrix_times(even, crc1);
  80551. len2 >>= 1;
  80552. /* if no more bits set, then done */
  80553. if (len2 == 0)
  80554. break;
  80555. /* another iteration of the loop with odd and even swapped */
  80556. gf2_matrix_square(odd, even);
  80557. if (len2 & 1)
  80558. crc1 = gf2_matrix_times(odd, crc1);
  80559. len2 >>= 1;
  80560. /* if no more bits set, then done */
  80561. } while (len2 != 0);
  80562. /* return combined crc */
  80563. crc1 ^= crc2;
  80564. return crc1;
  80565. }
  80566. /*** End of inlined file: crc32.c ***/
  80567. /*** Start of inlined file: deflate.c ***/
  80568. /*
  80569. * ALGORITHM
  80570. *
  80571. * The "deflation" process depends on being able to identify portions
  80572. * of the input text which are identical to earlier input (within a
  80573. * sliding window trailing behind the input currently being processed).
  80574. *
  80575. * The most straightforward technique turns out to be the fastest for
  80576. * most input files: try all possible matches and select the longest.
  80577. * The key feature of this algorithm is that insertions into the string
  80578. * dictionary are very simple and thus fast, and deletions are avoided
  80579. * completely. Insertions are performed at each input character, whereas
  80580. * string matches are performed only when the previous match ends. So it
  80581. * is preferable to spend more time in matches to allow very fast string
  80582. * insertions and avoid deletions. The matching algorithm for small
  80583. * strings is inspired from that of Rabin & Karp. A brute force approach
  80584. * is used to find longer strings when a small match has been found.
  80585. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  80586. * (by Leonid Broukhis).
  80587. * A previous version of this file used a more sophisticated algorithm
  80588. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  80589. * time, but has a larger average cost, uses more memory and is patented.
  80590. * However the F&G algorithm may be faster for some highly redundant
  80591. * files if the parameter max_chain_length (described below) is too large.
  80592. *
  80593. * ACKNOWLEDGEMENTS
  80594. *
  80595. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  80596. * I found it in 'freeze' written by Leonid Broukhis.
  80597. * Thanks to many people for bug reports and testing.
  80598. *
  80599. * REFERENCES
  80600. *
  80601. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  80602. * Available in http://www.ietf.org/rfc/rfc1951.txt
  80603. *
  80604. * A description of the Rabin and Karp algorithm is given in the book
  80605. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  80606. *
  80607. * Fiala,E.R., and Greene,D.H.
  80608. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  80609. *
  80610. */
  80611. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80612. /*** Start of inlined file: deflate.h ***/
  80613. /* WARNING: this file should *not* be used by applications. It is
  80614. part of the implementation of the compression library and is
  80615. subject to change. Applications should only use zlib.h.
  80616. */
  80617. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80618. #ifndef DEFLATE_H
  80619. #define DEFLATE_H
  80620. /* define NO_GZIP when compiling if you want to disable gzip header and
  80621. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  80622. the crc code when it is not needed. For shared libraries, gzip encoding
  80623. should be left enabled. */
  80624. #ifndef NO_GZIP
  80625. # define GZIP
  80626. #endif
  80627. #define NO_DUMMY_DECL
  80628. /* ===========================================================================
  80629. * Internal compression state.
  80630. */
  80631. #define LENGTH_CODES 29
  80632. /* number of length codes, not counting the special END_BLOCK code */
  80633. #define LITERALS 256
  80634. /* number of literal bytes 0..255 */
  80635. #define L_CODES (LITERALS+1+LENGTH_CODES)
  80636. /* number of Literal or Length codes, including the END_BLOCK code */
  80637. #define D_CODES 30
  80638. /* number of distance codes */
  80639. #define BL_CODES 19
  80640. /* number of codes used to transfer the bit lengths */
  80641. #define HEAP_SIZE (2*L_CODES+1)
  80642. /* maximum heap size */
  80643. #define MAX_BITS 15
  80644. /* All codes must not exceed MAX_BITS bits */
  80645. #define INIT_STATE 42
  80646. #define EXTRA_STATE 69
  80647. #define NAME_STATE 73
  80648. #define COMMENT_STATE 91
  80649. #define HCRC_STATE 103
  80650. #define BUSY_STATE 113
  80651. #define FINISH_STATE 666
  80652. /* Stream status */
  80653. /* Data structure describing a single value and its code string. */
  80654. typedef struct ct_data_s {
  80655. union {
  80656. ush freq; /* frequency count */
  80657. ush code; /* bit string */
  80658. } fc;
  80659. union {
  80660. ush dad; /* father node in Huffman tree */
  80661. ush len; /* length of bit string */
  80662. } dl;
  80663. } FAR ct_data;
  80664. #define Freq fc.freq
  80665. #define Code fc.code
  80666. #define Dad dl.dad
  80667. #define Len dl.len
  80668. typedef struct static_tree_desc_s static_tree_desc;
  80669. typedef struct tree_desc_s {
  80670. ct_data *dyn_tree; /* the dynamic tree */
  80671. int max_code; /* largest code with non zero frequency */
  80672. static_tree_desc *stat_desc; /* the corresponding static tree */
  80673. } FAR tree_desc;
  80674. typedef ush Pos;
  80675. typedef Pos FAR Posf;
  80676. typedef unsigned IPos;
  80677. /* A Pos is an index in the character window. We use short instead of int to
  80678. * save space in the various tables. IPos is used only for parameter passing.
  80679. */
  80680. typedef struct internal_state {
  80681. z_streamp strm; /* pointer back to this zlib stream */
  80682. int status; /* as the name implies */
  80683. Bytef *pending_buf; /* output still pending */
  80684. ulg pending_buf_size; /* size of pending_buf */
  80685. Bytef *pending_out; /* next pending byte to output to the stream */
  80686. uInt pending; /* nb of bytes in the pending buffer */
  80687. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  80688. gz_headerp gzhead; /* gzip header information to write */
  80689. uInt gzindex; /* where in extra, name, or comment */
  80690. Byte method; /* STORED (for zip only) or DEFLATED */
  80691. int last_flush; /* value of flush param for previous deflate call */
  80692. /* used by deflate.c: */
  80693. uInt w_size; /* LZ77 window size (32K by default) */
  80694. uInt w_bits; /* log2(w_size) (8..16) */
  80695. uInt w_mask; /* w_size - 1 */
  80696. Bytef *window;
  80697. /* Sliding window. Input bytes are read into the second half of the window,
  80698. * and move to the first half later to keep a dictionary of at least wSize
  80699. * bytes. With this organization, matches are limited to a distance of
  80700. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  80701. * performed with a length multiple of the block size. Also, it limits
  80702. * the window size to 64K, which is quite useful on MSDOS.
  80703. * To do: use the user input buffer as sliding window.
  80704. */
  80705. ulg window_size;
  80706. /* Actual size of window: 2*wSize, except when the user input buffer
  80707. * is directly used as sliding window.
  80708. */
  80709. Posf *prev;
  80710. /* Link to older string with same hash index. To limit the size of this
  80711. * array to 64K, this link is maintained only for the last 32K strings.
  80712. * An index in this array is thus a window index modulo 32K.
  80713. */
  80714. Posf *head; /* Heads of the hash chains or NIL. */
  80715. uInt ins_h; /* hash index of string to be inserted */
  80716. uInt hash_size; /* number of elements in hash table */
  80717. uInt hash_bits; /* log2(hash_size) */
  80718. uInt hash_mask; /* hash_size-1 */
  80719. uInt hash_shift;
  80720. /* Number of bits by which ins_h must be shifted at each input
  80721. * step. It must be such that after MIN_MATCH steps, the oldest
  80722. * byte no longer takes part in the hash key, that is:
  80723. * hash_shift * MIN_MATCH >= hash_bits
  80724. */
  80725. long block_start;
  80726. /* Window position at the beginning of the current output block. Gets
  80727. * negative when the window is moved backwards.
  80728. */
  80729. uInt match_length; /* length of best match */
  80730. IPos prev_match; /* previous match */
  80731. int match_available; /* set if previous match exists */
  80732. uInt strstart; /* start of string to insert */
  80733. uInt match_start; /* start of matching string */
  80734. uInt lookahead; /* number of valid bytes ahead in window */
  80735. uInt prev_length;
  80736. /* Length of the best match at previous step. Matches not greater than this
  80737. * are discarded. This is used in the lazy match evaluation.
  80738. */
  80739. uInt max_chain_length;
  80740. /* To speed up deflation, hash chains are never searched beyond this
  80741. * length. A higher limit improves compression ratio but degrades the
  80742. * speed.
  80743. */
  80744. uInt max_lazy_match;
  80745. /* Attempt to find a better match only when the current match is strictly
  80746. * smaller than this value. This mechanism is used only for compression
  80747. * levels >= 4.
  80748. */
  80749. # define max_insert_length max_lazy_match
  80750. /* Insert new strings in the hash table only if the match length is not
  80751. * greater than this length. This saves time but degrades compression.
  80752. * max_insert_length is used only for compression levels <= 3.
  80753. */
  80754. int level; /* compression level (1..9) */
  80755. int strategy; /* favor or force Huffman coding*/
  80756. uInt good_match;
  80757. /* Use a faster search when the previous match is longer than this */
  80758. int nice_match; /* Stop searching when current match exceeds this */
  80759. /* used by trees.c: */
  80760. /* Didn't use ct_data typedef below to supress compiler warning */
  80761. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  80762. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  80763. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  80764. struct tree_desc_s l_desc; /* desc. for literal tree */
  80765. struct tree_desc_s d_desc; /* desc. for distance tree */
  80766. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  80767. ush bl_count[MAX_BITS+1];
  80768. /* number of codes at each bit length for an optimal tree */
  80769. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  80770. int heap_len; /* number of elements in the heap */
  80771. int heap_max; /* element of largest frequency */
  80772. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  80773. * The same heap array is used to build all trees.
  80774. */
  80775. uch depth[2*L_CODES+1];
  80776. /* Depth of each subtree used as tie breaker for trees of equal frequency
  80777. */
  80778. uchf *l_buf; /* buffer for literals or lengths */
  80779. uInt lit_bufsize;
  80780. /* Size of match buffer for literals/lengths. There are 4 reasons for
  80781. * limiting lit_bufsize to 64K:
  80782. * - frequencies can be kept in 16 bit counters
  80783. * - if compression is not successful for the first block, all input
  80784. * data is still in the window so we can still emit a stored block even
  80785. * when input comes from standard input. (This can also be done for
  80786. * all blocks if lit_bufsize is not greater than 32K.)
  80787. * - if compression is not successful for a file smaller than 64K, we can
  80788. * even emit a stored file instead of a stored block (saving 5 bytes).
  80789. * This is applicable only for zip (not gzip or zlib).
  80790. * - creating new Huffman trees less frequently may not provide fast
  80791. * adaptation to changes in the input data statistics. (Take for
  80792. * example a binary file with poorly compressible code followed by
  80793. * a highly compressible string table.) Smaller buffer sizes give
  80794. * fast adaptation but have of course the overhead of transmitting
  80795. * trees more frequently.
  80796. * - I can't count above 4
  80797. */
  80798. uInt last_lit; /* running index in l_buf */
  80799. ushf *d_buf;
  80800. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  80801. * the same number of elements. To use different lengths, an extra flag
  80802. * array would be necessary.
  80803. */
  80804. ulg opt_len; /* bit length of current block with optimal trees */
  80805. ulg static_len; /* bit length of current block with static trees */
  80806. uInt matches; /* number of string matches in current block */
  80807. int last_eob_len; /* bit length of EOB code for last block */
  80808. #ifdef DEBUG
  80809. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  80810. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  80811. #endif
  80812. ush bi_buf;
  80813. /* Output buffer. bits are inserted starting at the bottom (least
  80814. * significant bits).
  80815. */
  80816. int bi_valid;
  80817. /* Number of valid bits in bi_buf. All bits above the last valid bit
  80818. * are always zero.
  80819. */
  80820. } FAR deflate_state;
  80821. /* Output a byte on the stream.
  80822. * IN assertion: there is enough room in pending_buf.
  80823. */
  80824. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  80825. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80826. /* Minimum amount of lookahead, except at the end of the input file.
  80827. * See deflate.c for comments about the MIN_MATCH+1.
  80828. */
  80829. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  80830. /* In order to simplify the code, particularly on 16 bit machines, match
  80831. * distances are limited to MAX_DIST instead of WSIZE.
  80832. */
  80833. /* in trees.c */
  80834. void _tr_init OF((deflate_state *s));
  80835. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  80836. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80837. int eof));
  80838. void _tr_align OF((deflate_state *s));
  80839. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80840. int eof));
  80841. #define d_code(dist) \
  80842. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  80843. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  80844. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  80845. * used.
  80846. */
  80847. #ifndef DEBUG
  80848. /* Inline versions of _tr_tally for speed: */
  80849. #if defined(GEN_TREES_H) || !defined(STDC)
  80850. extern uch _length_code[];
  80851. extern uch _dist_code[];
  80852. #else
  80853. extern const uch _length_code[];
  80854. extern const uch _dist_code[];
  80855. #endif
  80856. # define _tr_tally_lit(s, c, flush) \
  80857. { uch cc = (c); \
  80858. s->d_buf[s->last_lit] = 0; \
  80859. s->l_buf[s->last_lit++] = cc; \
  80860. s->dyn_ltree[cc].Freq++; \
  80861. flush = (s->last_lit == s->lit_bufsize-1); \
  80862. }
  80863. # define _tr_tally_dist(s, distance, length, flush) \
  80864. { uch len = (length); \
  80865. ush dist = (distance); \
  80866. s->d_buf[s->last_lit] = dist; \
  80867. s->l_buf[s->last_lit++] = len; \
  80868. dist--; \
  80869. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  80870. s->dyn_dtree[d_code(dist)].Freq++; \
  80871. flush = (s->last_lit == s->lit_bufsize-1); \
  80872. }
  80873. #else
  80874. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  80875. # define _tr_tally_dist(s, distance, length, flush) \
  80876. flush = _tr_tally(s, distance, length)
  80877. #endif
  80878. #endif /* DEFLATE_H */
  80879. /*** End of inlined file: deflate.h ***/
  80880. const char deflate_copyright[] =
  80881. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  80882. /*
  80883. If you use the zlib library in a product, an acknowledgment is welcome
  80884. in the documentation of your product. If for some reason you cannot
  80885. include such an acknowledgment, I would appreciate that you keep this
  80886. copyright string in the executable of your product.
  80887. */
  80888. /* ===========================================================================
  80889. * Function prototypes.
  80890. */
  80891. typedef enum {
  80892. need_more, /* block not completed, need more input or more output */
  80893. block_done, /* block flush performed */
  80894. finish_started, /* finish started, need only more output at next deflate */
  80895. finish_done /* finish done, accept no more input or output */
  80896. } block_state;
  80897. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  80898. /* Compression function. Returns the block state after the call. */
  80899. local void fill_window OF((deflate_state *s));
  80900. local block_state deflate_stored OF((deflate_state *s, int flush));
  80901. local block_state deflate_fast OF((deflate_state *s, int flush));
  80902. #ifndef FASTEST
  80903. local block_state deflate_slow OF((deflate_state *s, int flush));
  80904. #endif
  80905. local void lm_init OF((deflate_state *s));
  80906. local void putShortMSB OF((deflate_state *s, uInt b));
  80907. local void flush_pending OF((z_streamp strm));
  80908. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  80909. #ifndef FASTEST
  80910. #ifdef ASMV
  80911. void match_init OF((void)); /* asm code initialization */
  80912. uInt longest_match OF((deflate_state *s, IPos cur_match));
  80913. #else
  80914. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  80915. #endif
  80916. #endif
  80917. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  80918. #ifdef DEBUG
  80919. local void check_match OF((deflate_state *s, IPos start, IPos match,
  80920. int length));
  80921. #endif
  80922. /* ===========================================================================
  80923. * Local data
  80924. */
  80925. #define NIL 0
  80926. /* Tail of hash chains */
  80927. #ifndef TOO_FAR
  80928. # define TOO_FAR 4096
  80929. #endif
  80930. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  80931. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80932. /* Minimum amount of lookahead, except at the end of the input file.
  80933. * See deflate.c for comments about the MIN_MATCH+1.
  80934. */
  80935. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  80936. * the desired pack level (0..9). The values given below have been tuned to
  80937. * exclude worst case performance for pathological files. Better values may be
  80938. * found for specific files.
  80939. */
  80940. typedef struct config_s {
  80941. ush good_length; /* reduce lazy search above this match length */
  80942. ush max_lazy; /* do not perform lazy search above this match length */
  80943. ush nice_length; /* quit search above this match length */
  80944. ush max_chain;
  80945. compress_func func;
  80946. } config;
  80947. #ifdef FASTEST
  80948. local const config configuration_table[2] = {
  80949. /* good lazy nice chain */
  80950. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80951. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  80952. #else
  80953. local const config configuration_table[10] = {
  80954. /* good lazy nice chain */
  80955. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80956. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  80957. /* 2 */ {4, 5, 16, 8, deflate_fast},
  80958. /* 3 */ {4, 6, 32, 32, deflate_fast},
  80959. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  80960. /* 5 */ {8, 16, 32, 32, deflate_slow},
  80961. /* 6 */ {8, 16, 128, 128, deflate_slow},
  80962. /* 7 */ {8, 32, 128, 256, deflate_slow},
  80963. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  80964. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  80965. #endif
  80966. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  80967. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  80968. * meaning.
  80969. */
  80970. #define EQUAL 0
  80971. /* result of memcmp for equal strings */
  80972. #ifndef NO_DUMMY_DECL
  80973. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  80974. #endif
  80975. /* ===========================================================================
  80976. * Update a hash value with the given input byte
  80977. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  80978. * input characters, so that a running hash key can be computed from the
  80979. * previous key instead of complete recalculation each time.
  80980. */
  80981. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  80982. /* ===========================================================================
  80983. * Insert string str in the dictionary and set match_head to the previous head
  80984. * of the hash chain (the most recent string with same hash key). Return
  80985. * the previous length of the hash chain.
  80986. * If this file is compiled with -DFASTEST, the compression level is forced
  80987. * to 1, and no hash chains are maintained.
  80988. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  80989. * input characters and the first MIN_MATCH bytes of str are valid
  80990. * (except for the last MIN_MATCH-1 bytes of the input file).
  80991. */
  80992. #ifdef FASTEST
  80993. #define INSERT_STRING(s, str, match_head) \
  80994. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80995. match_head = s->head[s->ins_h], \
  80996. s->head[s->ins_h] = (Pos)(str))
  80997. #else
  80998. #define INSERT_STRING(s, str, match_head) \
  80999. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81000. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  81001. s->head[s->ins_h] = (Pos)(str))
  81002. #endif
  81003. /* ===========================================================================
  81004. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  81005. * prev[] will be initialized on the fly.
  81006. */
  81007. #define CLEAR_HASH(s) \
  81008. s->head[s->hash_size-1] = NIL; \
  81009. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  81010. /* ========================================================================= */
  81011. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  81012. {
  81013. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  81014. Z_DEFAULT_STRATEGY, version, stream_size);
  81015. /* To do: ignore strm->next_in if we use it as window */
  81016. }
  81017. /* ========================================================================= */
  81018. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81019. {
  81020. deflate_state *s;
  81021. int wrap = 1;
  81022. static const char my_version[] = ZLIB_VERSION;
  81023. ushf *overlay;
  81024. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81025. * output size for (length,distance) codes is <= 24 bits.
  81026. */
  81027. if (version == Z_NULL || version[0] != my_version[0] ||
  81028. stream_size != sizeof(z_stream)) {
  81029. return Z_VERSION_ERROR;
  81030. }
  81031. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81032. strm->msg = Z_NULL;
  81033. if (strm->zalloc == (alloc_func)0) {
  81034. strm->zalloc = zcalloc;
  81035. strm->opaque = (voidpf)0;
  81036. }
  81037. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81038. #ifdef FASTEST
  81039. if (level != 0) level = 1;
  81040. #else
  81041. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81042. #endif
  81043. if (windowBits < 0) { /* suppress zlib wrapper */
  81044. wrap = 0;
  81045. windowBits = -windowBits;
  81046. }
  81047. #ifdef GZIP
  81048. else if (windowBits > 15) {
  81049. wrap = 2; /* write gzip wrapper instead */
  81050. windowBits -= 16;
  81051. }
  81052. #endif
  81053. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81054. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81055. strategy < 0 || strategy > Z_FIXED) {
  81056. return Z_STREAM_ERROR;
  81057. }
  81058. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81059. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81060. if (s == Z_NULL) return Z_MEM_ERROR;
  81061. strm->state = (struct internal_state FAR *)s;
  81062. s->strm = strm;
  81063. s->wrap = wrap;
  81064. s->gzhead = Z_NULL;
  81065. s->w_bits = windowBits;
  81066. s->w_size = 1 << s->w_bits;
  81067. s->w_mask = s->w_size - 1;
  81068. s->hash_bits = memLevel + 7;
  81069. s->hash_size = 1 << s->hash_bits;
  81070. s->hash_mask = s->hash_size - 1;
  81071. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81072. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81073. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81074. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81075. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81076. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81077. s->pending_buf = (uchf *) overlay;
  81078. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81079. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81080. s->pending_buf == Z_NULL) {
  81081. s->status = FINISH_STATE;
  81082. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81083. deflateEnd (strm);
  81084. return Z_MEM_ERROR;
  81085. }
  81086. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81087. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81088. s->level = level;
  81089. s->strategy = strategy;
  81090. s->method = (Byte)method;
  81091. return deflateReset(strm);
  81092. }
  81093. /* ========================================================================= */
  81094. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81095. {
  81096. deflate_state *s;
  81097. uInt length = dictLength;
  81098. uInt n;
  81099. IPos hash_head = 0;
  81100. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81101. strm->state->wrap == 2 ||
  81102. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81103. return Z_STREAM_ERROR;
  81104. s = strm->state;
  81105. if (s->wrap)
  81106. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81107. if (length < MIN_MATCH) return Z_OK;
  81108. if (length > MAX_DIST(s)) {
  81109. length = MAX_DIST(s);
  81110. dictionary += dictLength - length; /* use the tail of the dictionary */
  81111. }
  81112. zmemcpy(s->window, dictionary, length);
  81113. s->strstart = length;
  81114. s->block_start = (long)length;
  81115. /* Insert all strings in the hash table (except for the last two bytes).
  81116. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81117. * call of fill_window.
  81118. */
  81119. s->ins_h = s->window[0];
  81120. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81121. for (n = 0; n <= length - MIN_MATCH; n++) {
  81122. INSERT_STRING(s, n, hash_head);
  81123. }
  81124. if (hash_head) hash_head = 0; /* to make compiler happy */
  81125. return Z_OK;
  81126. }
  81127. /* ========================================================================= */
  81128. int ZEXPORT deflateReset (z_streamp strm)
  81129. {
  81130. deflate_state *s;
  81131. if (strm == Z_NULL || strm->state == Z_NULL ||
  81132. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81133. return Z_STREAM_ERROR;
  81134. }
  81135. strm->total_in = strm->total_out = 0;
  81136. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81137. strm->data_type = Z_UNKNOWN;
  81138. s = (deflate_state *)strm->state;
  81139. s->pending = 0;
  81140. s->pending_out = s->pending_buf;
  81141. if (s->wrap < 0) {
  81142. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81143. }
  81144. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81145. strm->adler =
  81146. #ifdef GZIP
  81147. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81148. #endif
  81149. adler32(0L, Z_NULL, 0);
  81150. s->last_flush = Z_NO_FLUSH;
  81151. _tr_init(s);
  81152. lm_init(s);
  81153. return Z_OK;
  81154. }
  81155. /* ========================================================================= */
  81156. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81157. {
  81158. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81159. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81160. strm->state->gzhead = head;
  81161. return Z_OK;
  81162. }
  81163. /* ========================================================================= */
  81164. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81165. {
  81166. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81167. strm->state->bi_valid = bits;
  81168. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81169. return Z_OK;
  81170. }
  81171. /* ========================================================================= */
  81172. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81173. {
  81174. deflate_state *s;
  81175. compress_func func;
  81176. int err = Z_OK;
  81177. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81178. s = strm->state;
  81179. #ifdef FASTEST
  81180. if (level != 0) level = 1;
  81181. #else
  81182. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81183. #endif
  81184. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81185. return Z_STREAM_ERROR;
  81186. }
  81187. func = configuration_table[s->level].func;
  81188. if (func != configuration_table[level].func && strm->total_in != 0) {
  81189. /* Flush the last buffer: */
  81190. err = deflate(strm, Z_PARTIAL_FLUSH);
  81191. }
  81192. if (s->level != level) {
  81193. s->level = level;
  81194. s->max_lazy_match = configuration_table[level].max_lazy;
  81195. s->good_match = configuration_table[level].good_length;
  81196. s->nice_match = configuration_table[level].nice_length;
  81197. s->max_chain_length = configuration_table[level].max_chain;
  81198. }
  81199. s->strategy = strategy;
  81200. return err;
  81201. }
  81202. /* ========================================================================= */
  81203. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81204. {
  81205. deflate_state *s;
  81206. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81207. s = strm->state;
  81208. s->good_match = good_length;
  81209. s->max_lazy_match = max_lazy;
  81210. s->nice_match = nice_length;
  81211. s->max_chain_length = max_chain;
  81212. return Z_OK;
  81213. }
  81214. /* =========================================================================
  81215. * For the default windowBits of 15 and memLevel of 8, this function returns
  81216. * a close to exact, as well as small, upper bound on the compressed size.
  81217. * They are coded as constants here for a reason--if the #define's are
  81218. * changed, then this function needs to be changed as well. The return
  81219. * value for 15 and 8 only works for those exact settings.
  81220. *
  81221. * For any setting other than those defaults for windowBits and memLevel,
  81222. * the value returned is a conservative worst case for the maximum expansion
  81223. * resulting from using fixed blocks instead of stored blocks, which deflate
  81224. * can emit on compressed data for some combinations of the parameters.
  81225. *
  81226. * This function could be more sophisticated to provide closer upper bounds
  81227. * for every combination of windowBits and memLevel, as well as wrap.
  81228. * But even the conservative upper bound of about 14% expansion does not
  81229. * seem onerous for output buffer allocation.
  81230. */
  81231. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81232. {
  81233. deflate_state *s;
  81234. uLong destLen;
  81235. /* conservative upper bound */
  81236. destLen = sourceLen +
  81237. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81238. /* if can't get parameters, return conservative bound */
  81239. if (strm == Z_NULL || strm->state == Z_NULL)
  81240. return destLen;
  81241. /* if not default parameters, return conservative bound */
  81242. s = strm->state;
  81243. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81244. return destLen;
  81245. /* default settings: return tight bound for that case */
  81246. return compressBound(sourceLen);
  81247. }
  81248. /* =========================================================================
  81249. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81250. * IN assertion: the stream state is correct and there is enough room in
  81251. * pending_buf.
  81252. */
  81253. local void putShortMSB (deflate_state *s, uInt b)
  81254. {
  81255. put_byte(s, (Byte)(b >> 8));
  81256. put_byte(s, (Byte)(b & 0xff));
  81257. }
  81258. /* =========================================================================
  81259. * Flush as much pending output as possible. All deflate() output goes
  81260. * through this function so some applications may wish to modify it
  81261. * to avoid allocating a large strm->next_out buffer and copying into it.
  81262. * (See also read_buf()).
  81263. */
  81264. local void flush_pending (z_streamp strm)
  81265. {
  81266. unsigned len = strm->state->pending;
  81267. if (len > strm->avail_out) len = strm->avail_out;
  81268. if (len == 0) return;
  81269. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81270. strm->next_out += len;
  81271. strm->state->pending_out += len;
  81272. strm->total_out += len;
  81273. strm->avail_out -= len;
  81274. strm->state->pending -= len;
  81275. if (strm->state->pending == 0) {
  81276. strm->state->pending_out = strm->state->pending_buf;
  81277. }
  81278. }
  81279. /* ========================================================================= */
  81280. int ZEXPORT deflate (z_streamp strm, int flush)
  81281. {
  81282. int old_flush; /* value of flush param for previous deflate call */
  81283. deflate_state *s;
  81284. if (strm == Z_NULL || strm->state == Z_NULL ||
  81285. flush > Z_FINISH || flush < 0) {
  81286. return Z_STREAM_ERROR;
  81287. }
  81288. s = strm->state;
  81289. if (strm->next_out == Z_NULL ||
  81290. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81291. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81292. ERR_RETURN(strm, Z_STREAM_ERROR);
  81293. }
  81294. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81295. s->strm = strm; /* just in case */
  81296. old_flush = s->last_flush;
  81297. s->last_flush = flush;
  81298. /* Write the header */
  81299. if (s->status == INIT_STATE) {
  81300. #ifdef GZIP
  81301. if (s->wrap == 2) {
  81302. strm->adler = crc32(0L, Z_NULL, 0);
  81303. put_byte(s, 31);
  81304. put_byte(s, 139);
  81305. put_byte(s, 8);
  81306. if (s->gzhead == NULL) {
  81307. put_byte(s, 0);
  81308. put_byte(s, 0);
  81309. put_byte(s, 0);
  81310. put_byte(s, 0);
  81311. put_byte(s, 0);
  81312. put_byte(s, s->level == 9 ? 2 :
  81313. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81314. 4 : 0));
  81315. put_byte(s, OS_CODE);
  81316. s->status = BUSY_STATE;
  81317. }
  81318. else {
  81319. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81320. (s->gzhead->hcrc ? 2 : 0) +
  81321. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81322. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81323. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81324. );
  81325. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81326. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81327. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81328. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81329. put_byte(s, s->level == 9 ? 2 :
  81330. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81331. 4 : 0));
  81332. put_byte(s, s->gzhead->os & 0xff);
  81333. if (s->gzhead->extra != NULL) {
  81334. put_byte(s, s->gzhead->extra_len & 0xff);
  81335. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81336. }
  81337. if (s->gzhead->hcrc)
  81338. strm->adler = crc32(strm->adler, s->pending_buf,
  81339. s->pending);
  81340. s->gzindex = 0;
  81341. s->status = EXTRA_STATE;
  81342. }
  81343. }
  81344. else
  81345. #endif
  81346. {
  81347. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81348. uInt level_flags;
  81349. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81350. level_flags = 0;
  81351. else if (s->level < 6)
  81352. level_flags = 1;
  81353. else if (s->level == 6)
  81354. level_flags = 2;
  81355. else
  81356. level_flags = 3;
  81357. header |= (level_flags << 6);
  81358. if (s->strstart != 0) header |= PRESET_DICT;
  81359. header += 31 - (header % 31);
  81360. s->status = BUSY_STATE;
  81361. putShortMSB(s, header);
  81362. /* Save the adler32 of the preset dictionary: */
  81363. if (s->strstart != 0) {
  81364. putShortMSB(s, (uInt)(strm->adler >> 16));
  81365. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81366. }
  81367. strm->adler = adler32(0L, Z_NULL, 0);
  81368. }
  81369. }
  81370. #ifdef GZIP
  81371. if (s->status == EXTRA_STATE) {
  81372. if (s->gzhead->extra != NULL) {
  81373. uInt beg = s->pending; /* start of bytes to update crc */
  81374. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81375. if (s->pending == s->pending_buf_size) {
  81376. if (s->gzhead->hcrc && s->pending > beg)
  81377. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81378. s->pending - beg);
  81379. flush_pending(strm);
  81380. beg = s->pending;
  81381. if (s->pending == s->pending_buf_size)
  81382. break;
  81383. }
  81384. put_byte(s, s->gzhead->extra[s->gzindex]);
  81385. s->gzindex++;
  81386. }
  81387. if (s->gzhead->hcrc && s->pending > beg)
  81388. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81389. s->pending - beg);
  81390. if (s->gzindex == s->gzhead->extra_len) {
  81391. s->gzindex = 0;
  81392. s->status = NAME_STATE;
  81393. }
  81394. }
  81395. else
  81396. s->status = NAME_STATE;
  81397. }
  81398. if (s->status == NAME_STATE) {
  81399. if (s->gzhead->name != NULL) {
  81400. uInt beg = s->pending; /* start of bytes to update crc */
  81401. int val;
  81402. do {
  81403. if (s->pending == s->pending_buf_size) {
  81404. if (s->gzhead->hcrc && s->pending > beg)
  81405. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81406. s->pending - beg);
  81407. flush_pending(strm);
  81408. beg = s->pending;
  81409. if (s->pending == s->pending_buf_size) {
  81410. val = 1;
  81411. break;
  81412. }
  81413. }
  81414. val = s->gzhead->name[s->gzindex++];
  81415. put_byte(s, val);
  81416. } while (val != 0);
  81417. if (s->gzhead->hcrc && s->pending > beg)
  81418. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81419. s->pending - beg);
  81420. if (val == 0) {
  81421. s->gzindex = 0;
  81422. s->status = COMMENT_STATE;
  81423. }
  81424. }
  81425. else
  81426. s->status = COMMENT_STATE;
  81427. }
  81428. if (s->status == COMMENT_STATE) {
  81429. if (s->gzhead->comment != NULL) {
  81430. uInt beg = s->pending; /* start of bytes to update crc */
  81431. int val;
  81432. do {
  81433. if (s->pending == s->pending_buf_size) {
  81434. if (s->gzhead->hcrc && s->pending > beg)
  81435. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81436. s->pending - beg);
  81437. flush_pending(strm);
  81438. beg = s->pending;
  81439. if (s->pending == s->pending_buf_size) {
  81440. val = 1;
  81441. break;
  81442. }
  81443. }
  81444. val = s->gzhead->comment[s->gzindex++];
  81445. put_byte(s, val);
  81446. } while (val != 0);
  81447. if (s->gzhead->hcrc && s->pending > beg)
  81448. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81449. s->pending - beg);
  81450. if (val == 0)
  81451. s->status = HCRC_STATE;
  81452. }
  81453. else
  81454. s->status = HCRC_STATE;
  81455. }
  81456. if (s->status == HCRC_STATE) {
  81457. if (s->gzhead->hcrc) {
  81458. if (s->pending + 2 > s->pending_buf_size)
  81459. flush_pending(strm);
  81460. if (s->pending + 2 <= s->pending_buf_size) {
  81461. put_byte(s, (Byte)(strm->adler & 0xff));
  81462. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81463. strm->adler = crc32(0L, Z_NULL, 0);
  81464. s->status = BUSY_STATE;
  81465. }
  81466. }
  81467. else
  81468. s->status = BUSY_STATE;
  81469. }
  81470. #endif
  81471. /* Flush as much pending output as possible */
  81472. if (s->pending != 0) {
  81473. flush_pending(strm);
  81474. if (strm->avail_out == 0) {
  81475. /* Since avail_out is 0, deflate will be called again with
  81476. * more output space, but possibly with both pending and
  81477. * avail_in equal to zero. There won't be anything to do,
  81478. * but this is not an error situation so make sure we
  81479. * return OK instead of BUF_ERROR at next call of deflate:
  81480. */
  81481. s->last_flush = -1;
  81482. return Z_OK;
  81483. }
  81484. /* Make sure there is something to do and avoid duplicate consecutive
  81485. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81486. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81487. */
  81488. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81489. flush != Z_FINISH) {
  81490. ERR_RETURN(strm, Z_BUF_ERROR);
  81491. }
  81492. /* User must not provide more input after the first FINISH: */
  81493. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81494. ERR_RETURN(strm, Z_BUF_ERROR);
  81495. }
  81496. /* Start a new block or continue the current one.
  81497. */
  81498. if (strm->avail_in != 0 || s->lookahead != 0 ||
  81499. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  81500. block_state bstate;
  81501. bstate = (*(configuration_table[s->level].func))(s, flush);
  81502. if (bstate == finish_started || bstate == finish_done) {
  81503. s->status = FINISH_STATE;
  81504. }
  81505. if (bstate == need_more || bstate == finish_started) {
  81506. if (strm->avail_out == 0) {
  81507. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  81508. }
  81509. return Z_OK;
  81510. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  81511. * of deflate should use the same flush parameter to make sure
  81512. * that the flush is complete. So we don't have to output an
  81513. * empty block here, this will be done at next call. This also
  81514. * ensures that for a very small output buffer, we emit at most
  81515. * one empty block.
  81516. */
  81517. }
  81518. if (bstate == block_done) {
  81519. if (flush == Z_PARTIAL_FLUSH) {
  81520. _tr_align(s);
  81521. } else { /* FULL_FLUSH or SYNC_FLUSH */
  81522. _tr_stored_block(s, (char*)0, 0L, 0);
  81523. /* For a full flush, this empty block will be recognized
  81524. * as a special marker by inflate_sync().
  81525. */
  81526. if (flush == Z_FULL_FLUSH) {
  81527. CLEAR_HASH(s); /* forget history */
  81528. }
  81529. }
  81530. flush_pending(strm);
  81531. if (strm->avail_out == 0) {
  81532. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  81533. return Z_OK;
  81534. }
  81535. }
  81536. }
  81537. Assert(strm->avail_out > 0, "bug2");
  81538. if (flush != Z_FINISH) return Z_OK;
  81539. if (s->wrap <= 0) return Z_STREAM_END;
  81540. /* Write the trailer */
  81541. #ifdef GZIP
  81542. if (s->wrap == 2) {
  81543. put_byte(s, (Byte)(strm->adler & 0xff));
  81544. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81545. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  81546. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  81547. put_byte(s, (Byte)(strm->total_in & 0xff));
  81548. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  81549. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  81550. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  81551. }
  81552. else
  81553. #endif
  81554. {
  81555. putShortMSB(s, (uInt)(strm->adler >> 16));
  81556. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81557. }
  81558. flush_pending(strm);
  81559. /* If avail_out is zero, the application will call deflate again
  81560. * to flush the rest.
  81561. */
  81562. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  81563. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  81564. }
  81565. /* ========================================================================= */
  81566. int ZEXPORT deflateEnd (z_streamp strm)
  81567. {
  81568. int status;
  81569. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81570. status = strm->state->status;
  81571. if (status != INIT_STATE &&
  81572. status != EXTRA_STATE &&
  81573. status != NAME_STATE &&
  81574. status != COMMENT_STATE &&
  81575. status != HCRC_STATE &&
  81576. status != BUSY_STATE &&
  81577. status != FINISH_STATE) {
  81578. return Z_STREAM_ERROR;
  81579. }
  81580. /* Deallocate in reverse order of allocations: */
  81581. TRY_FREE(strm, strm->state->pending_buf);
  81582. TRY_FREE(strm, strm->state->head);
  81583. TRY_FREE(strm, strm->state->prev);
  81584. TRY_FREE(strm, strm->state->window);
  81585. ZFREE(strm, strm->state);
  81586. strm->state = Z_NULL;
  81587. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  81588. }
  81589. /* =========================================================================
  81590. * Copy the source state to the destination state.
  81591. * To simplify the source, this is not supported for 16-bit MSDOS (which
  81592. * doesn't have enough memory anyway to duplicate compression states).
  81593. */
  81594. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  81595. {
  81596. #ifdef MAXSEG_64K
  81597. return Z_STREAM_ERROR;
  81598. #else
  81599. deflate_state *ds;
  81600. deflate_state *ss;
  81601. ushf *overlay;
  81602. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  81603. return Z_STREAM_ERROR;
  81604. }
  81605. ss = source->state;
  81606. zmemcpy(dest, source, sizeof(z_stream));
  81607. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  81608. if (ds == Z_NULL) return Z_MEM_ERROR;
  81609. dest->state = (struct internal_state FAR *) ds;
  81610. zmemcpy(ds, ss, sizeof(deflate_state));
  81611. ds->strm = dest;
  81612. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  81613. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  81614. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  81615. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  81616. ds->pending_buf = (uchf *) overlay;
  81617. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  81618. ds->pending_buf == Z_NULL) {
  81619. deflateEnd (dest);
  81620. return Z_MEM_ERROR;
  81621. }
  81622. /* following zmemcpy do not work for 16-bit MSDOS */
  81623. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  81624. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  81625. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  81626. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  81627. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  81628. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  81629. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  81630. ds->l_desc.dyn_tree = ds->dyn_ltree;
  81631. ds->d_desc.dyn_tree = ds->dyn_dtree;
  81632. ds->bl_desc.dyn_tree = ds->bl_tree;
  81633. return Z_OK;
  81634. #endif /* MAXSEG_64K */
  81635. }
  81636. /* ===========================================================================
  81637. * Read a new buffer from the current input stream, update the adler32
  81638. * and total number of bytes read. All deflate() input goes through
  81639. * this function so some applications may wish to modify it to avoid
  81640. * allocating a large strm->next_in buffer and copying from it.
  81641. * (See also flush_pending()).
  81642. */
  81643. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  81644. {
  81645. unsigned len = strm->avail_in;
  81646. if (len > size) len = size;
  81647. if (len == 0) return 0;
  81648. strm->avail_in -= len;
  81649. if (strm->state->wrap == 1) {
  81650. strm->adler = adler32(strm->adler, strm->next_in, len);
  81651. }
  81652. #ifdef GZIP
  81653. else if (strm->state->wrap == 2) {
  81654. strm->adler = crc32(strm->adler, strm->next_in, len);
  81655. }
  81656. #endif
  81657. zmemcpy(buf, strm->next_in, len);
  81658. strm->next_in += len;
  81659. strm->total_in += len;
  81660. return (int)len;
  81661. }
  81662. /* ===========================================================================
  81663. * Initialize the "longest match" routines for a new zlib stream
  81664. */
  81665. local void lm_init (deflate_state *s)
  81666. {
  81667. s->window_size = (ulg)2L*s->w_size;
  81668. CLEAR_HASH(s);
  81669. /* Set the default configuration parameters:
  81670. */
  81671. s->max_lazy_match = configuration_table[s->level].max_lazy;
  81672. s->good_match = configuration_table[s->level].good_length;
  81673. s->nice_match = configuration_table[s->level].nice_length;
  81674. s->max_chain_length = configuration_table[s->level].max_chain;
  81675. s->strstart = 0;
  81676. s->block_start = 0L;
  81677. s->lookahead = 0;
  81678. s->match_length = s->prev_length = MIN_MATCH-1;
  81679. s->match_available = 0;
  81680. s->ins_h = 0;
  81681. #ifndef FASTEST
  81682. #ifdef ASMV
  81683. match_init(); /* initialize the asm code */
  81684. #endif
  81685. #endif
  81686. }
  81687. #ifndef FASTEST
  81688. /* ===========================================================================
  81689. * Set match_start to the longest match starting at the given string and
  81690. * return its length. Matches shorter or equal to prev_length are discarded,
  81691. * in which case the result is equal to prev_length and match_start is
  81692. * garbage.
  81693. * IN assertions: cur_match is the head of the hash chain for the current
  81694. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  81695. * OUT assertion: the match length is not greater than s->lookahead.
  81696. */
  81697. #ifndef ASMV
  81698. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  81699. * match.S. The code will be functionally equivalent.
  81700. */
  81701. local uInt longest_match(deflate_state *s, IPos cur_match)
  81702. {
  81703. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  81704. register Bytef *scan = s->window + s->strstart; /* current string */
  81705. register Bytef *match; /* matched string */
  81706. register int len; /* length of current match */
  81707. int best_len = s->prev_length; /* best match length so far */
  81708. int nice_match = s->nice_match; /* stop if match long enough */
  81709. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  81710. s->strstart - (IPos)MAX_DIST(s) : NIL;
  81711. /* Stop when cur_match becomes <= limit. To simplify the code,
  81712. * we prevent matches with the string of window index 0.
  81713. */
  81714. Posf *prev = s->prev;
  81715. uInt wmask = s->w_mask;
  81716. #ifdef UNALIGNED_OK
  81717. /* Compare two bytes at a time. Note: this is not always beneficial.
  81718. * Try with and without -DUNALIGNED_OK to check.
  81719. */
  81720. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  81721. register ush scan_start = *(ushf*)scan;
  81722. register ush scan_end = *(ushf*)(scan+best_len-1);
  81723. #else
  81724. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81725. register Byte scan_end1 = scan[best_len-1];
  81726. register Byte scan_end = scan[best_len];
  81727. #endif
  81728. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81729. * It is easy to get rid of this optimization if necessary.
  81730. */
  81731. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81732. /* Do not waste too much time if we already have a good match: */
  81733. if (s->prev_length >= s->good_match) {
  81734. chain_length >>= 2;
  81735. }
  81736. /* Do not look for matches beyond the end of the input. This is necessary
  81737. * to make deflate deterministic.
  81738. */
  81739. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  81740. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81741. do {
  81742. Assert(cur_match < s->strstart, "no future");
  81743. match = s->window + cur_match;
  81744. /* Skip to next match if the match length cannot increase
  81745. * or if the match length is less than 2. Note that the checks below
  81746. * for insufficient lookahead only occur occasionally for performance
  81747. * reasons. Therefore uninitialized memory will be accessed, and
  81748. * conditional jumps will be made that depend on those values.
  81749. * However the length of the match is limited to the lookahead, so
  81750. * the output of deflate is not affected by the uninitialized values.
  81751. */
  81752. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  81753. /* This code assumes sizeof(unsigned short) == 2. Do not use
  81754. * UNALIGNED_OK if your compiler uses a different size.
  81755. */
  81756. if (*(ushf*)(match+best_len-1) != scan_end ||
  81757. *(ushf*)match != scan_start) continue;
  81758. /* It is not necessary to compare scan[2] and match[2] since they are
  81759. * always equal when the other bytes match, given that the hash keys
  81760. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  81761. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  81762. * lookahead only every 4th comparison; the 128th check will be made
  81763. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  81764. * necessary to put more guard bytes at the end of the window, or
  81765. * to check more often for insufficient lookahead.
  81766. */
  81767. Assert(scan[2] == match[2], "scan[2]?");
  81768. scan++, match++;
  81769. do {
  81770. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81771. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81772. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81773. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81774. scan < strend);
  81775. /* The funny "do {}" generates better code on most compilers */
  81776. /* Here, scan <= window+strstart+257 */
  81777. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81778. if (*scan == *match) scan++;
  81779. len = (MAX_MATCH - 1) - (int)(strend-scan);
  81780. scan = strend - (MAX_MATCH-1);
  81781. #else /* UNALIGNED_OK */
  81782. if (match[best_len] != scan_end ||
  81783. match[best_len-1] != scan_end1 ||
  81784. *match != *scan ||
  81785. *++match != scan[1]) continue;
  81786. /* The check at best_len-1 can be removed because it will be made
  81787. * again later. (This heuristic is not always a win.)
  81788. * It is not necessary to compare scan[2] and match[2] since they
  81789. * are always equal when the other bytes match, given that
  81790. * the hash keys are equal and that HASH_BITS >= 8.
  81791. */
  81792. scan += 2, match++;
  81793. Assert(*scan == *match, "match[2]?");
  81794. /* We check for insufficient lookahead only every 8th comparison;
  81795. * the 256th check will be made at strstart+258.
  81796. */
  81797. do {
  81798. } while (*++scan == *++match && *++scan == *++match &&
  81799. *++scan == *++match && *++scan == *++match &&
  81800. *++scan == *++match && *++scan == *++match &&
  81801. *++scan == *++match && *++scan == *++match &&
  81802. scan < strend);
  81803. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81804. len = MAX_MATCH - (int)(strend - scan);
  81805. scan = strend - MAX_MATCH;
  81806. #endif /* UNALIGNED_OK */
  81807. if (len > best_len) {
  81808. s->match_start = cur_match;
  81809. best_len = len;
  81810. if (len >= nice_match) break;
  81811. #ifdef UNALIGNED_OK
  81812. scan_end = *(ushf*)(scan+best_len-1);
  81813. #else
  81814. scan_end1 = scan[best_len-1];
  81815. scan_end = scan[best_len];
  81816. #endif
  81817. }
  81818. } while ((cur_match = prev[cur_match & wmask]) > limit
  81819. && --chain_length != 0);
  81820. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  81821. return s->lookahead;
  81822. }
  81823. #endif /* ASMV */
  81824. #endif /* FASTEST */
  81825. /* ---------------------------------------------------------------------------
  81826. * Optimized version for level == 1 or strategy == Z_RLE only
  81827. */
  81828. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  81829. {
  81830. register Bytef *scan = s->window + s->strstart; /* current string */
  81831. register Bytef *match; /* matched string */
  81832. register int len; /* length of current match */
  81833. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81834. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81835. * It is easy to get rid of this optimization if necessary.
  81836. */
  81837. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81838. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81839. Assert(cur_match < s->strstart, "no future");
  81840. match = s->window + cur_match;
  81841. /* Return failure if the match length is less than 2:
  81842. */
  81843. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  81844. /* The check at best_len-1 can be removed because it will be made
  81845. * again later. (This heuristic is not always a win.)
  81846. * It is not necessary to compare scan[2] and match[2] since they
  81847. * are always equal when the other bytes match, given that
  81848. * the hash keys are equal and that HASH_BITS >= 8.
  81849. */
  81850. scan += 2, match += 2;
  81851. Assert(*scan == *match, "match[2]?");
  81852. /* We check for insufficient lookahead only every 8th comparison;
  81853. * the 256th check will be made at strstart+258.
  81854. */
  81855. do {
  81856. } while (*++scan == *++match && *++scan == *++match &&
  81857. *++scan == *++match && *++scan == *++match &&
  81858. *++scan == *++match && *++scan == *++match &&
  81859. *++scan == *++match && *++scan == *++match &&
  81860. scan < strend);
  81861. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81862. len = MAX_MATCH - (int)(strend - scan);
  81863. if (len < MIN_MATCH) return MIN_MATCH - 1;
  81864. s->match_start = cur_match;
  81865. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  81866. }
  81867. #ifdef DEBUG
  81868. /* ===========================================================================
  81869. * Check that the match at match_start is indeed a match.
  81870. */
  81871. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  81872. {
  81873. /* check that the match is indeed a match */
  81874. if (zmemcmp(s->window + match,
  81875. s->window + start, length) != EQUAL) {
  81876. fprintf(stderr, " start %u, match %u, length %d\n",
  81877. start, match, length);
  81878. do {
  81879. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  81880. } while (--length != 0);
  81881. z_error("invalid match");
  81882. }
  81883. if (z_verbose > 1) {
  81884. fprintf(stderr,"\\[%d,%d]", start-match, length);
  81885. do { putc(s->window[start++], stderr); } while (--length != 0);
  81886. }
  81887. }
  81888. #else
  81889. # define check_match(s, start, match, length)
  81890. #endif /* DEBUG */
  81891. /* ===========================================================================
  81892. * Fill the window when the lookahead becomes insufficient.
  81893. * Updates strstart and lookahead.
  81894. *
  81895. * IN assertion: lookahead < MIN_LOOKAHEAD
  81896. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  81897. * At least one byte has been read, or avail_in == 0; reads are
  81898. * performed for at least two bytes (required for the zip translate_eol
  81899. * option -- not supported here).
  81900. */
  81901. local void fill_window (deflate_state *s)
  81902. {
  81903. register unsigned n, m;
  81904. register Posf *p;
  81905. unsigned more; /* Amount of free space at the end of the window. */
  81906. uInt wsize = s->w_size;
  81907. do {
  81908. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  81909. /* Deal with !@#$% 64K limit: */
  81910. if (sizeof(int) <= 2) {
  81911. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  81912. more = wsize;
  81913. } else if (more == (unsigned)(-1)) {
  81914. /* Very unlikely, but possible on 16 bit machine if
  81915. * strstart == 0 && lookahead == 1 (input done a byte at time)
  81916. */
  81917. more--;
  81918. }
  81919. }
  81920. /* If the window is almost full and there is insufficient lookahead,
  81921. * move the upper half to the lower one to make room in the upper half.
  81922. */
  81923. if (s->strstart >= wsize+MAX_DIST(s)) {
  81924. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  81925. s->match_start -= wsize;
  81926. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  81927. s->block_start -= (long) wsize;
  81928. /* Slide the hash table (could be avoided with 32 bit values
  81929. at the expense of memory usage). We slide even when level == 0
  81930. to keep the hash table consistent if we switch back to level > 0
  81931. later. (Using level 0 permanently is not an optimal usage of
  81932. zlib, so we don't care about this pathological case.)
  81933. */
  81934. /* %%% avoid this when Z_RLE */
  81935. n = s->hash_size;
  81936. p = &s->head[n];
  81937. do {
  81938. m = *--p;
  81939. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81940. } while (--n);
  81941. n = wsize;
  81942. #ifndef FASTEST
  81943. p = &s->prev[n];
  81944. do {
  81945. m = *--p;
  81946. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81947. /* If n is not on any hash chain, prev[n] is garbage but
  81948. * its value will never be used.
  81949. */
  81950. } while (--n);
  81951. #endif
  81952. more += wsize;
  81953. }
  81954. if (s->strm->avail_in == 0) return;
  81955. /* If there was no sliding:
  81956. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  81957. * more == window_size - lookahead - strstart
  81958. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  81959. * => more >= window_size - 2*WSIZE + 2
  81960. * In the BIG_MEM or MMAP case (not yet supported),
  81961. * window_size == input_size + MIN_LOOKAHEAD &&
  81962. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  81963. * Otherwise, window_size == 2*WSIZE so more >= 2.
  81964. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  81965. */
  81966. Assert(more >= 2, "more < 2");
  81967. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  81968. s->lookahead += n;
  81969. /* Initialize the hash value now that we have some input: */
  81970. if (s->lookahead >= MIN_MATCH) {
  81971. s->ins_h = s->window[s->strstart];
  81972. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  81973. #if MIN_MATCH != 3
  81974. Call UPDATE_HASH() MIN_MATCH-3 more times
  81975. #endif
  81976. }
  81977. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  81978. * but this is not important since only literal bytes will be emitted.
  81979. */
  81980. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  81981. }
  81982. /* ===========================================================================
  81983. * Flush the current block, with given end-of-file flag.
  81984. * IN assertion: strstart is set to the end of the current match.
  81985. */
  81986. #define FLUSH_BLOCK_ONLY(s, eof) { \
  81987. _tr_flush_block(s, (s->block_start >= 0L ? \
  81988. (charf *)&s->window[(unsigned)s->block_start] : \
  81989. (charf *)Z_NULL), \
  81990. (ulg)((long)s->strstart - s->block_start), \
  81991. (eof)); \
  81992. s->block_start = s->strstart; \
  81993. flush_pending(s->strm); \
  81994. Tracev((stderr,"[FLUSH]")); \
  81995. }
  81996. /* Same but force premature exit if necessary. */
  81997. #define FLUSH_BLOCK(s, eof) { \
  81998. FLUSH_BLOCK_ONLY(s, eof); \
  81999. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  82000. }
  82001. /* ===========================================================================
  82002. * Copy without compression as much as possible from the input stream, return
  82003. * the current block state.
  82004. * This function does not insert new strings in the dictionary since
  82005. * uncompressible data is probably not useful. This function is used
  82006. * only for the level=0 compression option.
  82007. * NOTE: this function should be optimized to avoid extra copying from
  82008. * window to pending_buf.
  82009. */
  82010. local block_state deflate_stored(deflate_state *s, int flush)
  82011. {
  82012. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82013. * to pending_buf_size, and each stored block has a 5 byte header:
  82014. */
  82015. ulg max_block_size = 0xffff;
  82016. ulg max_start;
  82017. if (max_block_size > s->pending_buf_size - 5) {
  82018. max_block_size = s->pending_buf_size - 5;
  82019. }
  82020. /* Copy as much as possible from input to output: */
  82021. for (;;) {
  82022. /* Fill the window as much as possible: */
  82023. if (s->lookahead <= 1) {
  82024. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82025. s->block_start >= (long)s->w_size, "slide too late");
  82026. fill_window(s);
  82027. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82028. if (s->lookahead == 0) break; /* flush the current block */
  82029. }
  82030. Assert(s->block_start >= 0L, "block gone");
  82031. s->strstart += s->lookahead;
  82032. s->lookahead = 0;
  82033. /* Emit a stored block if pending_buf will be full: */
  82034. max_start = s->block_start + max_block_size;
  82035. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82036. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82037. s->lookahead = (uInt)(s->strstart - max_start);
  82038. s->strstart = (uInt)max_start;
  82039. FLUSH_BLOCK(s, 0);
  82040. }
  82041. /* Flush if we may have to slide, otherwise block_start may become
  82042. * negative and the data will be gone:
  82043. */
  82044. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82045. FLUSH_BLOCK(s, 0);
  82046. }
  82047. }
  82048. FLUSH_BLOCK(s, flush == Z_FINISH);
  82049. return flush == Z_FINISH ? finish_done : block_done;
  82050. }
  82051. /* ===========================================================================
  82052. * Compress as much as possible from the input stream, return the current
  82053. * block state.
  82054. * This function does not perform lazy evaluation of matches and inserts
  82055. * new strings in the dictionary only for unmatched strings or for short
  82056. * matches. It is used only for the fast compression options.
  82057. */
  82058. local block_state deflate_fast(deflate_state *s, int flush)
  82059. {
  82060. IPos hash_head = NIL; /* head of the hash chain */
  82061. int bflush; /* set if current block must be flushed */
  82062. for (;;) {
  82063. /* Make sure that we always have enough lookahead, except
  82064. * at the end of the input file. We need MAX_MATCH bytes
  82065. * for the next match, plus MIN_MATCH bytes to insert the
  82066. * string following the next match.
  82067. */
  82068. if (s->lookahead < MIN_LOOKAHEAD) {
  82069. fill_window(s);
  82070. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82071. return need_more;
  82072. }
  82073. if (s->lookahead == 0) break; /* flush the current block */
  82074. }
  82075. /* Insert the string window[strstart .. strstart+2] in the
  82076. * dictionary, and set hash_head to the head of the hash chain:
  82077. */
  82078. if (s->lookahead >= MIN_MATCH) {
  82079. INSERT_STRING(s, s->strstart, hash_head);
  82080. }
  82081. /* Find the longest match, discarding those <= prev_length.
  82082. * At this point we have always match_length < MIN_MATCH
  82083. */
  82084. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82085. /* To simplify the code, we prevent matches with the string
  82086. * of window index 0 (in particular we have to avoid a match
  82087. * of the string with itself at the start of the input file).
  82088. */
  82089. #ifdef FASTEST
  82090. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82091. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82092. s->match_length = longest_match_fast (s, hash_head);
  82093. }
  82094. #else
  82095. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82096. s->match_length = longest_match (s, hash_head);
  82097. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82098. s->match_length = longest_match_fast (s, hash_head);
  82099. }
  82100. #endif
  82101. /* longest_match() or longest_match_fast() sets match_start */
  82102. }
  82103. if (s->match_length >= MIN_MATCH) {
  82104. check_match(s, s->strstart, s->match_start, s->match_length);
  82105. _tr_tally_dist(s, s->strstart - s->match_start,
  82106. s->match_length - MIN_MATCH, bflush);
  82107. s->lookahead -= s->match_length;
  82108. /* Insert new strings in the hash table only if the match length
  82109. * is not too large. This saves time but degrades compression.
  82110. */
  82111. #ifndef FASTEST
  82112. if (s->match_length <= s->max_insert_length &&
  82113. s->lookahead >= MIN_MATCH) {
  82114. s->match_length--; /* string at strstart already in table */
  82115. do {
  82116. s->strstart++;
  82117. INSERT_STRING(s, s->strstart, hash_head);
  82118. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82119. * always MIN_MATCH bytes ahead.
  82120. */
  82121. } while (--s->match_length != 0);
  82122. s->strstart++;
  82123. } else
  82124. #endif
  82125. {
  82126. s->strstart += s->match_length;
  82127. s->match_length = 0;
  82128. s->ins_h = s->window[s->strstart];
  82129. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82130. #if MIN_MATCH != 3
  82131. Call UPDATE_HASH() MIN_MATCH-3 more times
  82132. #endif
  82133. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82134. * matter since it will be recomputed at next deflate call.
  82135. */
  82136. }
  82137. } else {
  82138. /* No match, output a literal byte */
  82139. Tracevv((stderr,"%c", s->window[s->strstart]));
  82140. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82141. s->lookahead--;
  82142. s->strstart++;
  82143. }
  82144. if (bflush) FLUSH_BLOCK(s, 0);
  82145. }
  82146. FLUSH_BLOCK(s, flush == Z_FINISH);
  82147. return flush == Z_FINISH ? finish_done : block_done;
  82148. }
  82149. #ifndef FASTEST
  82150. /* ===========================================================================
  82151. * Same as above, but achieves better compression. We use a lazy
  82152. * evaluation for matches: a match is finally adopted only if there is
  82153. * no better match at the next window position.
  82154. */
  82155. local block_state deflate_slow(deflate_state *s, int flush)
  82156. {
  82157. IPos hash_head = NIL; /* head of hash chain */
  82158. int bflush; /* set if current block must be flushed */
  82159. /* Process the input block. */
  82160. for (;;) {
  82161. /* Make sure that we always have enough lookahead, except
  82162. * at the end of the input file. We need MAX_MATCH bytes
  82163. * for the next match, plus MIN_MATCH bytes to insert the
  82164. * string following the next match.
  82165. */
  82166. if (s->lookahead < MIN_LOOKAHEAD) {
  82167. fill_window(s);
  82168. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82169. return need_more;
  82170. }
  82171. if (s->lookahead == 0) break; /* flush the current block */
  82172. }
  82173. /* Insert the string window[strstart .. strstart+2] in the
  82174. * dictionary, and set hash_head to the head of the hash chain:
  82175. */
  82176. if (s->lookahead >= MIN_MATCH) {
  82177. INSERT_STRING(s, s->strstart, hash_head);
  82178. }
  82179. /* Find the longest match, discarding those <= prev_length.
  82180. */
  82181. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82182. s->match_length = MIN_MATCH-1;
  82183. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82184. s->strstart - hash_head <= MAX_DIST(s)) {
  82185. /* To simplify the code, we prevent matches with the string
  82186. * of window index 0 (in particular we have to avoid a match
  82187. * of the string with itself at the start of the input file).
  82188. */
  82189. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82190. s->match_length = longest_match (s, hash_head);
  82191. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82192. s->match_length = longest_match_fast (s, hash_head);
  82193. }
  82194. /* longest_match() or longest_match_fast() sets match_start */
  82195. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82196. #if TOO_FAR <= 32767
  82197. || (s->match_length == MIN_MATCH &&
  82198. s->strstart - s->match_start > TOO_FAR)
  82199. #endif
  82200. )) {
  82201. /* If prev_match is also MIN_MATCH, match_start is garbage
  82202. * but we will ignore the current match anyway.
  82203. */
  82204. s->match_length = MIN_MATCH-1;
  82205. }
  82206. }
  82207. /* If there was a match at the previous step and the current
  82208. * match is not better, output the previous match:
  82209. */
  82210. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82211. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82212. /* Do not insert strings in hash table beyond this. */
  82213. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82214. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82215. s->prev_length - MIN_MATCH, bflush);
  82216. /* Insert in hash table all strings up to the end of the match.
  82217. * strstart-1 and strstart are already inserted. If there is not
  82218. * enough lookahead, the last two strings are not inserted in
  82219. * the hash table.
  82220. */
  82221. s->lookahead -= s->prev_length-1;
  82222. s->prev_length -= 2;
  82223. do {
  82224. if (++s->strstart <= max_insert) {
  82225. INSERT_STRING(s, s->strstart, hash_head);
  82226. }
  82227. } while (--s->prev_length != 0);
  82228. s->match_available = 0;
  82229. s->match_length = MIN_MATCH-1;
  82230. s->strstart++;
  82231. if (bflush) FLUSH_BLOCK(s, 0);
  82232. } else if (s->match_available) {
  82233. /* If there was no match at the previous position, output a
  82234. * single literal. If there was a match but the current match
  82235. * is longer, truncate the previous match to a single literal.
  82236. */
  82237. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82238. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82239. if (bflush) {
  82240. FLUSH_BLOCK_ONLY(s, 0);
  82241. }
  82242. s->strstart++;
  82243. s->lookahead--;
  82244. if (s->strm->avail_out == 0) return need_more;
  82245. } else {
  82246. /* There is no previous match to compare with, wait for
  82247. * the next step to decide.
  82248. */
  82249. s->match_available = 1;
  82250. s->strstart++;
  82251. s->lookahead--;
  82252. }
  82253. }
  82254. Assert (flush != Z_NO_FLUSH, "no flush?");
  82255. if (s->match_available) {
  82256. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82257. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82258. s->match_available = 0;
  82259. }
  82260. FLUSH_BLOCK(s, flush == Z_FINISH);
  82261. return flush == Z_FINISH ? finish_done : block_done;
  82262. }
  82263. #endif /* FASTEST */
  82264. #if 0
  82265. /* ===========================================================================
  82266. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82267. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82268. * deflate switches away from Z_RLE.)
  82269. */
  82270. local block_state deflate_rle(s, flush)
  82271. deflate_state *s;
  82272. int flush;
  82273. {
  82274. int bflush; /* set if current block must be flushed */
  82275. uInt run; /* length of run */
  82276. uInt max; /* maximum length of run */
  82277. uInt prev; /* byte at distance one to match */
  82278. Bytef *scan; /* scan for end of run */
  82279. for (;;) {
  82280. /* Make sure that we always have enough lookahead, except
  82281. * at the end of the input file. We need MAX_MATCH bytes
  82282. * for the longest encodable run.
  82283. */
  82284. if (s->lookahead < MAX_MATCH) {
  82285. fill_window(s);
  82286. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82287. return need_more;
  82288. }
  82289. if (s->lookahead == 0) break; /* flush the current block */
  82290. }
  82291. /* See how many times the previous byte repeats */
  82292. run = 0;
  82293. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82294. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82295. scan = s->window + s->strstart - 1;
  82296. prev = *scan++;
  82297. do {
  82298. if (*scan++ != prev)
  82299. break;
  82300. } while (++run < max);
  82301. }
  82302. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82303. if (run >= MIN_MATCH) {
  82304. check_match(s, s->strstart, s->strstart - 1, run);
  82305. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82306. s->lookahead -= run;
  82307. s->strstart += run;
  82308. } else {
  82309. /* No match, output a literal byte */
  82310. Tracevv((stderr,"%c", s->window[s->strstart]));
  82311. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82312. s->lookahead--;
  82313. s->strstart++;
  82314. }
  82315. if (bflush) FLUSH_BLOCK(s, 0);
  82316. }
  82317. FLUSH_BLOCK(s, flush == Z_FINISH);
  82318. return flush == Z_FINISH ? finish_done : block_done;
  82319. }
  82320. #endif
  82321. /*** End of inlined file: deflate.c ***/
  82322. /*** Start of inlined file: inffast.c ***/
  82323. /*** Start of inlined file: inftrees.h ***/
  82324. /* WARNING: this file should *not* be used by applications. It is
  82325. part of the implementation of the compression library and is
  82326. subject to change. Applications should only use zlib.h.
  82327. */
  82328. #ifndef _INFTREES_H_
  82329. #define _INFTREES_H_
  82330. /* Structure for decoding tables. Each entry provides either the
  82331. information needed to do the operation requested by the code that
  82332. indexed that table entry, or it provides a pointer to another
  82333. table that indexes more bits of the code. op indicates whether
  82334. the entry is a pointer to another table, a literal, a length or
  82335. distance, an end-of-block, or an invalid code. For a table
  82336. pointer, the low four bits of op is the number of index bits of
  82337. that table. For a length or distance, the low four bits of op
  82338. is the number of extra bits to get after the code. bits is
  82339. the number of bits in this code or part of the code to drop off
  82340. of the bit buffer. val is the actual byte to output in the case
  82341. of a literal, the base length or distance, or the offset from
  82342. the current table to the next table. Each entry is four bytes. */
  82343. typedef struct {
  82344. unsigned char op; /* operation, extra bits, table bits */
  82345. unsigned char bits; /* bits in this part of the code */
  82346. unsigned short val; /* offset in table or code value */
  82347. } code;
  82348. /* op values as set by inflate_table():
  82349. 00000000 - literal
  82350. 0000tttt - table link, tttt != 0 is the number of table index bits
  82351. 0001eeee - length or distance, eeee is the number of extra bits
  82352. 01100000 - end of block
  82353. 01000000 - invalid code
  82354. */
  82355. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82356. exhaustive search was 1444 code structures (852 for length/literals
  82357. and 592 for distances, the latter actually the result of an
  82358. exhaustive search). The true maximum is not known, but the value
  82359. below is more than safe. */
  82360. #define ENOUGH 2048
  82361. #define MAXD 592
  82362. /* Type of code to build for inftable() */
  82363. typedef enum {
  82364. CODES,
  82365. LENS,
  82366. DISTS
  82367. } codetype;
  82368. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82369. unsigned codes, code FAR * FAR *table,
  82370. unsigned FAR *bits, unsigned short FAR *work));
  82371. #endif
  82372. /*** End of inlined file: inftrees.h ***/
  82373. /*** Start of inlined file: inflate.h ***/
  82374. /* WARNING: this file should *not* be used by applications. It is
  82375. part of the implementation of the compression library and is
  82376. subject to change. Applications should only use zlib.h.
  82377. */
  82378. #ifndef _INFLATE_H_
  82379. #define _INFLATE_H_
  82380. /* define NO_GZIP when compiling if you want to disable gzip header and
  82381. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82382. the crc code when it is not needed. For shared libraries, gzip decoding
  82383. should be left enabled. */
  82384. #ifndef NO_GZIP
  82385. # define GUNZIP
  82386. #endif
  82387. /* Possible inflate modes between inflate() calls */
  82388. typedef enum {
  82389. HEAD, /* i: waiting for magic header */
  82390. FLAGS, /* i: waiting for method and flags (gzip) */
  82391. TIME, /* i: waiting for modification time (gzip) */
  82392. OS, /* i: waiting for extra flags and operating system (gzip) */
  82393. EXLEN, /* i: waiting for extra length (gzip) */
  82394. EXTRA, /* i: waiting for extra bytes (gzip) */
  82395. NAME, /* i: waiting for end of file name (gzip) */
  82396. COMMENT, /* i: waiting for end of comment (gzip) */
  82397. HCRC, /* i: waiting for header crc (gzip) */
  82398. DICTID, /* i: waiting for dictionary check value */
  82399. DICT, /* waiting for inflateSetDictionary() call */
  82400. TYPE, /* i: waiting for type bits, including last-flag bit */
  82401. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82402. STORED, /* i: waiting for stored size (length and complement) */
  82403. COPY, /* i/o: waiting for input or output to copy stored block */
  82404. TABLE, /* i: waiting for dynamic block table lengths */
  82405. LENLENS, /* i: waiting for code length code lengths */
  82406. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82407. LEN, /* i: waiting for length/lit code */
  82408. LENEXT, /* i: waiting for length extra bits */
  82409. DIST, /* i: waiting for distance code */
  82410. DISTEXT, /* i: waiting for distance extra bits */
  82411. MATCH, /* o: waiting for output space to copy string */
  82412. LIT, /* o: waiting for output space to write literal */
  82413. CHECK, /* i: waiting for 32-bit check value */
  82414. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82415. DONE, /* finished check, done -- remain here until reset */
  82416. BAD, /* got a data error -- remain here until reset */
  82417. MEM, /* got an inflate() memory error -- remain here until reset */
  82418. SYNC /* looking for synchronization bytes to restart inflate() */
  82419. } inflate_mode;
  82420. /*
  82421. State transitions between above modes -
  82422. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82423. Process header:
  82424. HEAD -> (gzip) or (zlib)
  82425. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82426. NAME -> COMMENT -> HCRC -> TYPE
  82427. (zlib) -> DICTID or TYPE
  82428. DICTID -> DICT -> TYPE
  82429. Read deflate blocks:
  82430. TYPE -> STORED or TABLE or LEN or CHECK
  82431. STORED -> COPY -> TYPE
  82432. TABLE -> LENLENS -> CODELENS -> LEN
  82433. Read deflate codes:
  82434. LEN -> LENEXT or LIT or TYPE
  82435. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82436. LIT -> LEN
  82437. Process trailer:
  82438. CHECK -> LENGTH -> DONE
  82439. */
  82440. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82441. struct inflate_state {
  82442. inflate_mode mode; /* current inflate mode */
  82443. int last; /* true if processing last block */
  82444. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82445. int havedict; /* true if dictionary provided */
  82446. int flags; /* gzip header method and flags (0 if zlib) */
  82447. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82448. unsigned long check; /* protected copy of check value */
  82449. unsigned long total; /* protected copy of output count */
  82450. gz_headerp head; /* where to save gzip header information */
  82451. /* sliding window */
  82452. unsigned wbits; /* log base 2 of requested window size */
  82453. unsigned wsize; /* window size or zero if not using window */
  82454. unsigned whave; /* valid bytes in the window */
  82455. unsigned write; /* window write index */
  82456. unsigned char FAR *window; /* allocated sliding window, if needed */
  82457. /* bit accumulator */
  82458. unsigned long hold; /* input bit accumulator */
  82459. unsigned bits; /* number of bits in "in" */
  82460. /* for string and stored block copying */
  82461. unsigned length; /* literal or length of data to copy */
  82462. unsigned offset; /* distance back to copy string from */
  82463. /* for table and code decoding */
  82464. unsigned extra; /* extra bits needed */
  82465. /* fixed and dynamic code tables */
  82466. code const FAR *lencode; /* starting table for length/literal codes */
  82467. code const FAR *distcode; /* starting table for distance codes */
  82468. unsigned lenbits; /* index bits for lencode */
  82469. unsigned distbits; /* index bits for distcode */
  82470. /* dynamic table building */
  82471. unsigned ncode; /* number of code length code lengths */
  82472. unsigned nlen; /* number of length code lengths */
  82473. unsigned ndist; /* number of distance code lengths */
  82474. unsigned have; /* number of code lengths in lens[] */
  82475. code FAR *next; /* next available space in codes[] */
  82476. unsigned short lens[320]; /* temporary storage for code lengths */
  82477. unsigned short work[288]; /* work area for code table building */
  82478. code codes[ENOUGH]; /* space for code tables */
  82479. };
  82480. #endif
  82481. /*** End of inlined file: inflate.h ***/
  82482. /*** Start of inlined file: inffast.h ***/
  82483. /* WARNING: this file should *not* be used by applications. It is
  82484. part of the implementation of the compression library and is
  82485. subject to change. Applications should only use zlib.h.
  82486. */
  82487. void inflate_fast OF((z_streamp strm, unsigned start));
  82488. /*** End of inlined file: inffast.h ***/
  82489. #ifndef ASMINF
  82490. /* Allow machine dependent optimization for post-increment or pre-increment.
  82491. Based on testing to date,
  82492. Pre-increment preferred for:
  82493. - PowerPC G3 (Adler)
  82494. - MIPS R5000 (Randers-Pehrson)
  82495. Post-increment preferred for:
  82496. - none
  82497. No measurable difference:
  82498. - Pentium III (Anderson)
  82499. - M68060 (Nikl)
  82500. */
  82501. #ifdef POSTINC
  82502. # define OFF 0
  82503. # define PUP(a) *(a)++
  82504. #else
  82505. # define OFF 1
  82506. # define PUP(a) *++(a)
  82507. #endif
  82508. /*
  82509. Decode literal, length, and distance codes and write out the resulting
  82510. literal and match bytes until either not enough input or output is
  82511. available, an end-of-block is encountered, or a data error is encountered.
  82512. When large enough input and output buffers are supplied to inflate(), for
  82513. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  82514. inflate execution time is spent in this routine.
  82515. Entry assumptions:
  82516. state->mode == LEN
  82517. strm->avail_in >= 6
  82518. strm->avail_out >= 258
  82519. start >= strm->avail_out
  82520. state->bits < 8
  82521. On return, state->mode is one of:
  82522. LEN -- ran out of enough output space or enough available input
  82523. TYPE -- reached end of block code, inflate() to interpret next block
  82524. BAD -- error in block data
  82525. Notes:
  82526. - The maximum input bits used by a length/distance pair is 15 bits for the
  82527. length code, 5 bits for the length extra, 15 bits for the distance code,
  82528. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  82529. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  82530. checking for available input while decoding.
  82531. - The maximum bytes that a single length/distance pair can output is 258
  82532. bytes, which is the maximum length that can be coded. inflate_fast()
  82533. requires strm->avail_out >= 258 for each loop to avoid checking for
  82534. output space.
  82535. */
  82536. void inflate_fast (z_streamp strm, unsigned start)
  82537. {
  82538. struct inflate_state FAR *state;
  82539. unsigned char FAR *in; /* local strm->next_in */
  82540. unsigned char FAR *last; /* while in < last, enough input available */
  82541. unsigned char FAR *out; /* local strm->next_out */
  82542. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  82543. unsigned char FAR *end; /* while out < end, enough space available */
  82544. #ifdef INFLATE_STRICT
  82545. unsigned dmax; /* maximum distance from zlib header */
  82546. #endif
  82547. unsigned wsize; /* window size or zero if not using window */
  82548. unsigned whave; /* valid bytes in the window */
  82549. unsigned write; /* window write index */
  82550. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  82551. unsigned long hold; /* local strm->hold */
  82552. unsigned bits; /* local strm->bits */
  82553. code const FAR *lcode; /* local strm->lencode */
  82554. code const FAR *dcode; /* local strm->distcode */
  82555. unsigned lmask; /* mask for first level of length codes */
  82556. unsigned dmask; /* mask for first level of distance codes */
  82557. code thisx; /* retrieved table entry */
  82558. unsigned op; /* code bits, operation, extra bits, or */
  82559. /* window position, window bytes to copy */
  82560. unsigned len; /* match length, unused bytes */
  82561. unsigned dist; /* match distance */
  82562. unsigned char FAR *from; /* where to copy match from */
  82563. /* copy state to local variables */
  82564. state = (struct inflate_state FAR *)strm->state;
  82565. in = strm->next_in - OFF;
  82566. last = in + (strm->avail_in - 5);
  82567. out = strm->next_out - OFF;
  82568. beg = out - (start - strm->avail_out);
  82569. end = out + (strm->avail_out - 257);
  82570. #ifdef INFLATE_STRICT
  82571. dmax = state->dmax;
  82572. #endif
  82573. wsize = state->wsize;
  82574. whave = state->whave;
  82575. write = state->write;
  82576. window = state->window;
  82577. hold = state->hold;
  82578. bits = state->bits;
  82579. lcode = state->lencode;
  82580. dcode = state->distcode;
  82581. lmask = (1U << state->lenbits) - 1;
  82582. dmask = (1U << state->distbits) - 1;
  82583. /* decode literals and length/distances until end-of-block or not enough
  82584. input data or output space */
  82585. do {
  82586. if (bits < 15) {
  82587. hold += (unsigned long)(PUP(in)) << bits;
  82588. bits += 8;
  82589. hold += (unsigned long)(PUP(in)) << bits;
  82590. bits += 8;
  82591. }
  82592. thisx = lcode[hold & lmask];
  82593. dolen:
  82594. op = (unsigned)(thisx.bits);
  82595. hold >>= op;
  82596. bits -= op;
  82597. op = (unsigned)(thisx.op);
  82598. if (op == 0) { /* literal */
  82599. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82600. "inflate: literal '%c'\n" :
  82601. "inflate: literal 0x%02x\n", thisx.val));
  82602. PUP(out) = (unsigned char)(thisx.val);
  82603. }
  82604. else if (op & 16) { /* length base */
  82605. len = (unsigned)(thisx.val);
  82606. op &= 15; /* number of extra bits */
  82607. if (op) {
  82608. if (bits < op) {
  82609. hold += (unsigned long)(PUP(in)) << bits;
  82610. bits += 8;
  82611. }
  82612. len += (unsigned)hold & ((1U << op) - 1);
  82613. hold >>= op;
  82614. bits -= op;
  82615. }
  82616. Tracevv((stderr, "inflate: length %u\n", len));
  82617. if (bits < 15) {
  82618. hold += (unsigned long)(PUP(in)) << bits;
  82619. bits += 8;
  82620. hold += (unsigned long)(PUP(in)) << bits;
  82621. bits += 8;
  82622. }
  82623. thisx = dcode[hold & dmask];
  82624. dodist:
  82625. op = (unsigned)(thisx.bits);
  82626. hold >>= op;
  82627. bits -= op;
  82628. op = (unsigned)(thisx.op);
  82629. if (op & 16) { /* distance base */
  82630. dist = (unsigned)(thisx.val);
  82631. op &= 15; /* number of extra bits */
  82632. if (bits < op) {
  82633. hold += (unsigned long)(PUP(in)) << bits;
  82634. bits += 8;
  82635. if (bits < op) {
  82636. hold += (unsigned long)(PUP(in)) << bits;
  82637. bits += 8;
  82638. }
  82639. }
  82640. dist += (unsigned)hold & ((1U << op) - 1);
  82641. #ifdef INFLATE_STRICT
  82642. if (dist > dmax) {
  82643. strm->msg = (char *)"invalid distance too far back";
  82644. state->mode = BAD;
  82645. break;
  82646. }
  82647. #endif
  82648. hold >>= op;
  82649. bits -= op;
  82650. Tracevv((stderr, "inflate: distance %u\n", dist));
  82651. op = (unsigned)(out - beg); /* max distance in output */
  82652. if (dist > op) { /* see if copy from window */
  82653. op = dist - op; /* distance back in window */
  82654. if (op > whave) {
  82655. strm->msg = (char *)"invalid distance too far back";
  82656. state->mode = BAD;
  82657. break;
  82658. }
  82659. from = window - OFF;
  82660. if (write == 0) { /* very common case */
  82661. from += wsize - op;
  82662. if (op < len) { /* some from window */
  82663. len -= op;
  82664. do {
  82665. PUP(out) = PUP(from);
  82666. } while (--op);
  82667. from = out - dist; /* rest from output */
  82668. }
  82669. }
  82670. else if (write < op) { /* wrap around window */
  82671. from += wsize + write - op;
  82672. op -= write;
  82673. if (op < len) { /* some from end of window */
  82674. len -= op;
  82675. do {
  82676. PUP(out) = PUP(from);
  82677. } while (--op);
  82678. from = window - OFF;
  82679. if (write < len) { /* some from start of window */
  82680. op = write;
  82681. len -= op;
  82682. do {
  82683. PUP(out) = PUP(from);
  82684. } while (--op);
  82685. from = out - dist; /* rest from output */
  82686. }
  82687. }
  82688. }
  82689. else { /* contiguous in window */
  82690. from += write - op;
  82691. if (op < len) { /* some from window */
  82692. len -= op;
  82693. do {
  82694. PUP(out) = PUP(from);
  82695. } while (--op);
  82696. from = out - dist; /* rest from output */
  82697. }
  82698. }
  82699. while (len > 2) {
  82700. PUP(out) = PUP(from);
  82701. PUP(out) = PUP(from);
  82702. PUP(out) = PUP(from);
  82703. len -= 3;
  82704. }
  82705. if (len) {
  82706. PUP(out) = PUP(from);
  82707. if (len > 1)
  82708. PUP(out) = PUP(from);
  82709. }
  82710. }
  82711. else {
  82712. from = out - dist; /* copy direct from output */
  82713. do { /* minimum length is three */
  82714. PUP(out) = PUP(from);
  82715. PUP(out) = PUP(from);
  82716. PUP(out) = PUP(from);
  82717. len -= 3;
  82718. } while (len > 2);
  82719. if (len) {
  82720. PUP(out) = PUP(from);
  82721. if (len > 1)
  82722. PUP(out) = PUP(from);
  82723. }
  82724. }
  82725. }
  82726. else if ((op & 64) == 0) { /* 2nd level distance code */
  82727. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  82728. goto dodist;
  82729. }
  82730. else {
  82731. strm->msg = (char *)"invalid distance code";
  82732. state->mode = BAD;
  82733. break;
  82734. }
  82735. }
  82736. else if ((op & 64) == 0) { /* 2nd level length code */
  82737. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  82738. goto dolen;
  82739. }
  82740. else if (op & 32) { /* end-of-block */
  82741. Tracevv((stderr, "inflate: end of block\n"));
  82742. state->mode = TYPE;
  82743. break;
  82744. }
  82745. else {
  82746. strm->msg = (char *)"invalid literal/length code";
  82747. state->mode = BAD;
  82748. break;
  82749. }
  82750. } while (in < last && out < end);
  82751. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  82752. len = bits >> 3;
  82753. in -= len;
  82754. bits -= len << 3;
  82755. hold &= (1U << bits) - 1;
  82756. /* update state and return */
  82757. strm->next_in = in + OFF;
  82758. strm->next_out = out + OFF;
  82759. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  82760. strm->avail_out = (unsigned)(out < end ?
  82761. 257 + (end - out) : 257 - (out - end));
  82762. state->hold = hold;
  82763. state->bits = bits;
  82764. return;
  82765. }
  82766. /*
  82767. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  82768. - Using bit fields for code structure
  82769. - Different op definition to avoid & for extra bits (do & for table bits)
  82770. - Three separate decoding do-loops for direct, window, and write == 0
  82771. - Special case for distance > 1 copies to do overlapped load and store copy
  82772. - Explicit branch predictions (based on measured branch probabilities)
  82773. - Deferring match copy and interspersed it with decoding subsequent codes
  82774. - Swapping literal/length else
  82775. - Swapping window/direct else
  82776. - Larger unrolled copy loops (three is about right)
  82777. - Moving len -= 3 statement into middle of loop
  82778. */
  82779. #endif /* !ASMINF */
  82780. /*** End of inlined file: inffast.c ***/
  82781. #undef PULLBYTE
  82782. #undef LOAD
  82783. #undef RESTORE
  82784. #undef INITBITS
  82785. #undef NEEDBITS
  82786. #undef DROPBITS
  82787. #undef BYTEBITS
  82788. /*** Start of inlined file: inflate.c ***/
  82789. /*
  82790. * Change history:
  82791. *
  82792. * 1.2.beta0 24 Nov 2002
  82793. * - First version -- complete rewrite of inflate to simplify code, avoid
  82794. * creation of window when not needed, minimize use of window when it is
  82795. * needed, make inffast.c even faster, implement gzip decoding, and to
  82796. * improve code readability and style over the previous zlib inflate code
  82797. *
  82798. * 1.2.beta1 25 Nov 2002
  82799. * - Use pointers for available input and output checking in inffast.c
  82800. * - Remove input and output counters in inffast.c
  82801. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  82802. * - Remove unnecessary second byte pull from length extra in inffast.c
  82803. * - Unroll direct copy to three copies per loop in inffast.c
  82804. *
  82805. * 1.2.beta2 4 Dec 2002
  82806. * - Change external routine names to reduce potential conflicts
  82807. * - Correct filename to inffixed.h for fixed tables in inflate.c
  82808. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  82809. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  82810. * to avoid negation problem on Alphas (64 bit) in inflate.c
  82811. *
  82812. * 1.2.beta3 22 Dec 2002
  82813. * - Add comments on state->bits assertion in inffast.c
  82814. * - Add comments on op field in inftrees.h
  82815. * - Fix bug in reuse of allocated window after inflateReset()
  82816. * - Remove bit fields--back to byte structure for speed
  82817. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  82818. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  82819. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  82820. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  82821. * - Use local copies of stream next and avail values, as well as local bit
  82822. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  82823. *
  82824. * 1.2.beta4 1 Jan 2003
  82825. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  82826. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  82827. * - Add comments in inffast.c to introduce the inflate_fast() routine
  82828. * - Rearrange window copies in inflate_fast() for speed and simplification
  82829. * - Unroll last copy for window match in inflate_fast()
  82830. * - Use local copies of window variables in inflate_fast() for speed
  82831. * - Pull out common write == 0 case for speed in inflate_fast()
  82832. * - Make op and len in inflate_fast() unsigned for consistency
  82833. * - Add FAR to lcode and dcode declarations in inflate_fast()
  82834. * - Simplified bad distance check in inflate_fast()
  82835. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  82836. * source file infback.c to provide a call-back interface to inflate for
  82837. * programs like gzip and unzip -- uses window as output buffer to avoid
  82838. * window copying
  82839. *
  82840. * 1.2.beta5 1 Jan 2003
  82841. * - Improved inflateBack() interface to allow the caller to provide initial
  82842. * input in strm.
  82843. * - Fixed stored blocks bug in inflateBack()
  82844. *
  82845. * 1.2.beta6 4 Jan 2003
  82846. * - Added comments in inffast.c on effectiveness of POSTINC
  82847. * - Typecasting all around to reduce compiler warnings
  82848. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  82849. * make compilers happy
  82850. * - Changed type of window in inflateBackInit() to unsigned char *
  82851. *
  82852. * 1.2.beta7 27 Jan 2003
  82853. * - Changed many types to unsigned or unsigned short to avoid warnings
  82854. * - Added inflateCopy() function
  82855. *
  82856. * 1.2.0 9 Mar 2003
  82857. * - Changed inflateBack() interface to provide separate opaque descriptors
  82858. * for the in() and out() functions
  82859. * - Changed inflateBack() argument and in_func typedef to swap the length
  82860. * and buffer address return values for the input function
  82861. * - Check next_in and next_out for Z_NULL on entry to inflate()
  82862. *
  82863. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  82864. */
  82865. /*** Start of inlined file: inffast.h ***/
  82866. /* WARNING: this file should *not* be used by applications. It is
  82867. part of the implementation of the compression library and is
  82868. subject to change. Applications should only use zlib.h.
  82869. */
  82870. void inflate_fast OF((z_streamp strm, unsigned start));
  82871. /*** End of inlined file: inffast.h ***/
  82872. #ifdef MAKEFIXED
  82873. # ifndef BUILDFIXED
  82874. # define BUILDFIXED
  82875. # endif
  82876. #endif
  82877. /* function prototypes */
  82878. local void fixedtables OF((struct inflate_state FAR *state));
  82879. local int updatewindow OF((z_streamp strm, unsigned out));
  82880. #ifdef BUILDFIXED
  82881. void makefixed OF((void));
  82882. #endif
  82883. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  82884. unsigned len));
  82885. int ZEXPORT inflateReset (z_streamp strm)
  82886. {
  82887. struct inflate_state FAR *state;
  82888. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82889. state = (struct inflate_state FAR *)strm->state;
  82890. strm->total_in = strm->total_out = state->total = 0;
  82891. strm->msg = Z_NULL;
  82892. strm->adler = 1; /* to support ill-conceived Java test suite */
  82893. state->mode = HEAD;
  82894. state->last = 0;
  82895. state->havedict = 0;
  82896. state->dmax = 32768U;
  82897. state->head = Z_NULL;
  82898. state->wsize = 0;
  82899. state->whave = 0;
  82900. state->write = 0;
  82901. state->hold = 0;
  82902. state->bits = 0;
  82903. state->lencode = state->distcode = state->next = state->codes;
  82904. Tracev((stderr, "inflate: reset\n"));
  82905. return Z_OK;
  82906. }
  82907. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  82908. {
  82909. struct inflate_state FAR *state;
  82910. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82911. state = (struct inflate_state FAR *)strm->state;
  82912. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  82913. value &= (1L << bits) - 1;
  82914. state->hold += value << state->bits;
  82915. state->bits += bits;
  82916. return Z_OK;
  82917. }
  82918. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  82919. {
  82920. struct inflate_state FAR *state;
  82921. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  82922. stream_size != (int)(sizeof(z_stream)))
  82923. return Z_VERSION_ERROR;
  82924. if (strm == Z_NULL) return Z_STREAM_ERROR;
  82925. strm->msg = Z_NULL; /* in case we return an error */
  82926. if (strm->zalloc == (alloc_func)0) {
  82927. strm->zalloc = zcalloc;
  82928. strm->opaque = (voidpf)0;
  82929. }
  82930. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  82931. state = (struct inflate_state FAR *)
  82932. ZALLOC(strm, 1, sizeof(struct inflate_state));
  82933. if (state == Z_NULL) return Z_MEM_ERROR;
  82934. Tracev((stderr, "inflate: allocated\n"));
  82935. strm->state = (struct internal_state FAR *)state;
  82936. if (windowBits < 0) {
  82937. state->wrap = 0;
  82938. windowBits = -windowBits;
  82939. }
  82940. else {
  82941. state->wrap = (windowBits >> 4) + 1;
  82942. #ifdef GUNZIP
  82943. if (windowBits < 48) windowBits &= 15;
  82944. #endif
  82945. }
  82946. if (windowBits < 8 || windowBits > 15) {
  82947. ZFREE(strm, state);
  82948. strm->state = Z_NULL;
  82949. return Z_STREAM_ERROR;
  82950. }
  82951. state->wbits = (unsigned)windowBits;
  82952. state->window = Z_NULL;
  82953. return inflateReset(strm);
  82954. }
  82955. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  82956. {
  82957. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  82958. }
  82959. /*
  82960. Return state with length and distance decoding tables and index sizes set to
  82961. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  82962. If BUILDFIXED is defined, then instead this routine builds the tables the
  82963. first time it's called, and returns those tables the first time and
  82964. thereafter. This reduces the size of the code by about 2K bytes, in
  82965. exchange for a little execution time. However, BUILDFIXED should not be
  82966. used for threaded applications, since the rewriting of the tables and virgin
  82967. may not be thread-safe.
  82968. */
  82969. local void fixedtables (struct inflate_state FAR *state)
  82970. {
  82971. #ifdef BUILDFIXED
  82972. static int virgin = 1;
  82973. static code *lenfix, *distfix;
  82974. static code fixed[544];
  82975. /* build fixed huffman tables if first call (may not be thread safe) */
  82976. if (virgin) {
  82977. unsigned sym, bits;
  82978. static code *next;
  82979. /* literal/length table */
  82980. sym = 0;
  82981. while (sym < 144) state->lens[sym++] = 8;
  82982. while (sym < 256) state->lens[sym++] = 9;
  82983. while (sym < 280) state->lens[sym++] = 7;
  82984. while (sym < 288) state->lens[sym++] = 8;
  82985. next = fixed;
  82986. lenfix = next;
  82987. bits = 9;
  82988. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  82989. /* distance table */
  82990. sym = 0;
  82991. while (sym < 32) state->lens[sym++] = 5;
  82992. distfix = next;
  82993. bits = 5;
  82994. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  82995. /* do this just once */
  82996. virgin = 0;
  82997. }
  82998. #else /* !BUILDFIXED */
  82999. /*** Start of inlined file: inffixed.h ***/
  83000. /* WARNING: this file should *not* be used by applications. It
  83001. is part of the implementation of the compression library and
  83002. is subject to change. Applications should only use zlib.h.
  83003. */
  83004. static const code lenfix[512] = {
  83005. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  83006. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  83007. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  83008. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  83009. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  83010. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  83011. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  83012. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  83013. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  83014. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  83015. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  83016. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  83017. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  83018. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83019. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83020. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83021. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83022. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83023. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83024. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83025. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83026. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83027. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83028. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83029. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83030. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83031. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83032. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83033. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83034. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83035. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83036. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83037. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83038. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83039. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83040. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83041. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83042. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83043. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83044. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83045. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83046. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83047. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83048. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83049. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83050. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83051. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83052. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83053. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83054. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83055. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83056. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83057. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83058. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83059. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83060. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83061. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83062. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83063. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83064. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83065. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83066. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83067. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83068. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83069. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83070. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83071. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83072. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83073. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83074. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83075. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83076. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83077. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83078. {0,9,255}
  83079. };
  83080. static const code distfix[32] = {
  83081. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83082. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83083. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83084. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83085. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83086. {22,5,193},{64,5,0}
  83087. };
  83088. /*** End of inlined file: inffixed.h ***/
  83089. #endif /* BUILDFIXED */
  83090. state->lencode = lenfix;
  83091. state->lenbits = 9;
  83092. state->distcode = distfix;
  83093. state->distbits = 5;
  83094. }
  83095. #ifdef MAKEFIXED
  83096. #include <stdio.h>
  83097. /*
  83098. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83099. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83100. those tables to stdout, which would be piped to inffixed.h. A small program
  83101. can simply call makefixed to do this:
  83102. void makefixed(void);
  83103. int main(void)
  83104. {
  83105. makefixed();
  83106. return 0;
  83107. }
  83108. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83109. a.out > inffixed.h
  83110. */
  83111. void makefixed()
  83112. {
  83113. unsigned low, size;
  83114. struct inflate_state state;
  83115. fixedtables(&state);
  83116. puts(" /* inffixed.h -- table for decoding fixed codes");
  83117. puts(" * Generated automatically by makefixed().");
  83118. puts(" */");
  83119. puts("");
  83120. puts(" /* WARNING: this file should *not* be used by applications.");
  83121. puts(" It is part of the implementation of this library and is");
  83122. puts(" subject to change. Applications should only use zlib.h.");
  83123. puts(" */");
  83124. puts("");
  83125. size = 1U << 9;
  83126. printf(" static const code lenfix[%u] = {", size);
  83127. low = 0;
  83128. for (;;) {
  83129. if ((low % 7) == 0) printf("\n ");
  83130. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83131. state.lencode[low].val);
  83132. if (++low == size) break;
  83133. putchar(',');
  83134. }
  83135. puts("\n };");
  83136. size = 1U << 5;
  83137. printf("\n static const code distfix[%u] = {", size);
  83138. low = 0;
  83139. for (;;) {
  83140. if ((low % 6) == 0) printf("\n ");
  83141. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83142. state.distcode[low].val);
  83143. if (++low == size) break;
  83144. putchar(',');
  83145. }
  83146. puts("\n };");
  83147. }
  83148. #endif /* MAKEFIXED */
  83149. /*
  83150. Update the window with the last wsize (normally 32K) bytes written before
  83151. returning. If window does not exist yet, create it. This is only called
  83152. when a window is already in use, or when output has been written during this
  83153. inflate call, but the end of the deflate stream has not been reached yet.
  83154. It is also called to create a window for dictionary data when a dictionary
  83155. is loaded.
  83156. Providing output buffers larger than 32K to inflate() should provide a speed
  83157. advantage, since only the last 32K of output is copied to the sliding window
  83158. upon return from inflate(), and since all distances after the first 32K of
  83159. output will fall in the output data, making match copies simpler and faster.
  83160. The advantage may be dependent on the size of the processor's data caches.
  83161. */
  83162. local int updatewindow (z_streamp strm, unsigned out)
  83163. {
  83164. struct inflate_state FAR *state;
  83165. unsigned copy, dist;
  83166. state = (struct inflate_state FAR *)strm->state;
  83167. /* if it hasn't been done already, allocate space for the window */
  83168. if (state->window == Z_NULL) {
  83169. state->window = (unsigned char FAR *)
  83170. ZALLOC(strm, 1U << state->wbits,
  83171. sizeof(unsigned char));
  83172. if (state->window == Z_NULL) return 1;
  83173. }
  83174. /* if window not in use yet, initialize */
  83175. if (state->wsize == 0) {
  83176. state->wsize = 1U << state->wbits;
  83177. state->write = 0;
  83178. state->whave = 0;
  83179. }
  83180. /* copy state->wsize or less output bytes into the circular window */
  83181. copy = out - strm->avail_out;
  83182. if (copy >= state->wsize) {
  83183. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83184. state->write = 0;
  83185. state->whave = state->wsize;
  83186. }
  83187. else {
  83188. dist = state->wsize - state->write;
  83189. if (dist > copy) dist = copy;
  83190. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83191. copy -= dist;
  83192. if (copy) {
  83193. zmemcpy(state->window, strm->next_out - copy, copy);
  83194. state->write = copy;
  83195. state->whave = state->wsize;
  83196. }
  83197. else {
  83198. state->write += dist;
  83199. if (state->write == state->wsize) state->write = 0;
  83200. if (state->whave < state->wsize) state->whave += dist;
  83201. }
  83202. }
  83203. return 0;
  83204. }
  83205. /* Macros for inflate(): */
  83206. /* check function to use adler32() for zlib or crc32() for gzip */
  83207. #ifdef GUNZIP
  83208. # define UPDATE(check, buf, len) \
  83209. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83210. #else
  83211. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83212. #endif
  83213. /* check macros for header crc */
  83214. #ifdef GUNZIP
  83215. # define CRC2(check, word) \
  83216. do { \
  83217. hbuf[0] = (unsigned char)(word); \
  83218. hbuf[1] = (unsigned char)((word) >> 8); \
  83219. check = crc32(check, hbuf, 2); \
  83220. } while (0)
  83221. # define CRC4(check, word) \
  83222. do { \
  83223. hbuf[0] = (unsigned char)(word); \
  83224. hbuf[1] = (unsigned char)((word) >> 8); \
  83225. hbuf[2] = (unsigned char)((word) >> 16); \
  83226. hbuf[3] = (unsigned char)((word) >> 24); \
  83227. check = crc32(check, hbuf, 4); \
  83228. } while (0)
  83229. #endif
  83230. /* Load registers with state in inflate() for speed */
  83231. #define LOAD() \
  83232. do { \
  83233. put = strm->next_out; \
  83234. left = strm->avail_out; \
  83235. next = strm->next_in; \
  83236. have = strm->avail_in; \
  83237. hold = state->hold; \
  83238. bits = state->bits; \
  83239. } while (0)
  83240. /* Restore state from registers in inflate() */
  83241. #define RESTORE() \
  83242. do { \
  83243. strm->next_out = put; \
  83244. strm->avail_out = left; \
  83245. strm->next_in = next; \
  83246. strm->avail_in = have; \
  83247. state->hold = hold; \
  83248. state->bits = bits; \
  83249. } while (0)
  83250. /* Clear the input bit accumulator */
  83251. #define INITBITS() \
  83252. do { \
  83253. hold = 0; \
  83254. bits = 0; \
  83255. } while (0)
  83256. /* Get a byte of input into the bit accumulator, or return from inflate()
  83257. if there is no input available. */
  83258. #define PULLBYTE() \
  83259. do { \
  83260. if (have == 0) goto inf_leave; \
  83261. have--; \
  83262. hold += (unsigned long)(*next++) << bits; \
  83263. bits += 8; \
  83264. } while (0)
  83265. /* Assure that there are at least n bits in the bit accumulator. If there is
  83266. not enough available input to do that, then return from inflate(). */
  83267. #define NEEDBITS(n) \
  83268. do { \
  83269. while (bits < (unsigned)(n)) \
  83270. PULLBYTE(); \
  83271. } while (0)
  83272. /* Return the low n bits of the bit accumulator (n < 16) */
  83273. #define BITS(n) \
  83274. ((unsigned)hold & ((1U << (n)) - 1))
  83275. /* Remove n bits from the bit accumulator */
  83276. #define DROPBITS(n) \
  83277. do { \
  83278. hold >>= (n); \
  83279. bits -= (unsigned)(n); \
  83280. } while (0)
  83281. /* Remove zero to seven bits as needed to go to a byte boundary */
  83282. #define BYTEBITS() \
  83283. do { \
  83284. hold >>= bits & 7; \
  83285. bits -= bits & 7; \
  83286. } while (0)
  83287. /* Reverse the bytes in a 32-bit value */
  83288. #define REVERSE(q) \
  83289. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83290. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83291. /*
  83292. inflate() uses a state machine to process as much input data and generate as
  83293. much output data as possible before returning. The state machine is
  83294. structured roughly as follows:
  83295. for (;;) switch (state) {
  83296. ...
  83297. case STATEn:
  83298. if (not enough input data or output space to make progress)
  83299. return;
  83300. ... make progress ...
  83301. state = STATEm;
  83302. break;
  83303. ...
  83304. }
  83305. so when inflate() is called again, the same case is attempted again, and
  83306. if the appropriate resources are provided, the machine proceeds to the
  83307. next state. The NEEDBITS() macro is usually the way the state evaluates
  83308. whether it can proceed or should return. NEEDBITS() does the return if
  83309. the requested bits are not available. The typical use of the BITS macros
  83310. is:
  83311. NEEDBITS(n);
  83312. ... do something with BITS(n) ...
  83313. DROPBITS(n);
  83314. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83315. input left to load n bits into the accumulator, or it continues. BITS(n)
  83316. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83317. the low n bits off the accumulator. INITBITS() clears the accumulator
  83318. and sets the number of available bits to zero. BYTEBITS() discards just
  83319. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83320. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83321. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83322. if there is no input available. The decoding of variable length codes uses
  83323. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83324. code, and no more.
  83325. Some states loop until they get enough input, making sure that enough
  83326. state information is maintained to continue the loop where it left off
  83327. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83328. would all have to actually be part of the saved state in case NEEDBITS()
  83329. returns:
  83330. case STATEw:
  83331. while (want < need) {
  83332. NEEDBITS(n);
  83333. keep[want++] = BITS(n);
  83334. DROPBITS(n);
  83335. }
  83336. state = STATEx;
  83337. case STATEx:
  83338. As shown above, if the next state is also the next case, then the break
  83339. is omitted.
  83340. A state may also return if there is not enough output space available to
  83341. complete that state. Those states are copying stored data, writing a
  83342. literal byte, and copying a matching string.
  83343. When returning, a "goto inf_leave" is used to update the total counters,
  83344. update the check value, and determine whether any progress has been made
  83345. during that inflate() call in order to return the proper return code.
  83346. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83347. When there is a window, goto inf_leave will update the window with the last
  83348. output written. If a goto inf_leave occurs in the middle of decompression
  83349. and there is no window currently, goto inf_leave will create one and copy
  83350. output to the window for the next call of inflate().
  83351. In this implementation, the flush parameter of inflate() only affects the
  83352. return code (per zlib.h). inflate() always writes as much as possible to
  83353. strm->next_out, given the space available and the provided input--the effect
  83354. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83355. the allocation of and copying into a sliding window until necessary, which
  83356. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83357. stream available. So the only thing the flush parameter actually does is:
  83358. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83359. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83360. */
  83361. int ZEXPORT inflate (z_streamp strm, int flush)
  83362. {
  83363. struct inflate_state FAR *state;
  83364. unsigned char FAR *next; /* next input */
  83365. unsigned char FAR *put; /* next output */
  83366. unsigned have, left; /* available input and output */
  83367. unsigned long hold; /* bit buffer */
  83368. unsigned bits; /* bits in bit buffer */
  83369. unsigned in, out; /* save starting available input and output */
  83370. unsigned copy; /* number of stored or match bytes to copy */
  83371. unsigned char FAR *from; /* where to copy match bytes from */
  83372. code thisx; /* current decoding table entry */
  83373. code last; /* parent table entry */
  83374. unsigned len; /* length to copy for repeats, bits to drop */
  83375. int ret; /* return code */
  83376. #ifdef GUNZIP
  83377. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83378. #endif
  83379. static const unsigned short order[19] = /* permutation of code lengths */
  83380. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83381. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83382. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83383. return Z_STREAM_ERROR;
  83384. state = (struct inflate_state FAR *)strm->state;
  83385. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83386. LOAD();
  83387. in = have;
  83388. out = left;
  83389. ret = Z_OK;
  83390. for (;;)
  83391. switch (state->mode) {
  83392. case HEAD:
  83393. if (state->wrap == 0) {
  83394. state->mode = TYPEDO;
  83395. break;
  83396. }
  83397. NEEDBITS(16);
  83398. #ifdef GUNZIP
  83399. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83400. state->check = crc32(0L, Z_NULL, 0);
  83401. CRC2(state->check, hold);
  83402. INITBITS();
  83403. state->mode = FLAGS;
  83404. break;
  83405. }
  83406. state->flags = 0; /* expect zlib header */
  83407. if (state->head != Z_NULL)
  83408. state->head->done = -1;
  83409. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83410. #else
  83411. if (
  83412. #endif
  83413. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83414. strm->msg = (char *)"incorrect header check";
  83415. state->mode = BAD;
  83416. break;
  83417. }
  83418. if (BITS(4) != Z_DEFLATED) {
  83419. strm->msg = (char *)"unknown compression method";
  83420. state->mode = BAD;
  83421. break;
  83422. }
  83423. DROPBITS(4);
  83424. len = BITS(4) + 8;
  83425. if (len > state->wbits) {
  83426. strm->msg = (char *)"invalid window size";
  83427. state->mode = BAD;
  83428. break;
  83429. }
  83430. state->dmax = 1U << len;
  83431. Tracev((stderr, "inflate: zlib header ok\n"));
  83432. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83433. state->mode = hold & 0x200 ? DICTID : TYPE;
  83434. INITBITS();
  83435. break;
  83436. #ifdef GUNZIP
  83437. case FLAGS:
  83438. NEEDBITS(16);
  83439. state->flags = (int)(hold);
  83440. if ((state->flags & 0xff) != Z_DEFLATED) {
  83441. strm->msg = (char *)"unknown compression method";
  83442. state->mode = BAD;
  83443. break;
  83444. }
  83445. if (state->flags & 0xe000) {
  83446. strm->msg = (char *)"unknown header flags set";
  83447. state->mode = BAD;
  83448. break;
  83449. }
  83450. if (state->head != Z_NULL)
  83451. state->head->text = (int)((hold >> 8) & 1);
  83452. if (state->flags & 0x0200) CRC2(state->check, hold);
  83453. INITBITS();
  83454. state->mode = TIME;
  83455. case TIME:
  83456. NEEDBITS(32);
  83457. if (state->head != Z_NULL)
  83458. state->head->time = hold;
  83459. if (state->flags & 0x0200) CRC4(state->check, hold);
  83460. INITBITS();
  83461. state->mode = OS;
  83462. case OS:
  83463. NEEDBITS(16);
  83464. if (state->head != Z_NULL) {
  83465. state->head->xflags = (int)(hold & 0xff);
  83466. state->head->os = (int)(hold >> 8);
  83467. }
  83468. if (state->flags & 0x0200) CRC2(state->check, hold);
  83469. INITBITS();
  83470. state->mode = EXLEN;
  83471. case EXLEN:
  83472. if (state->flags & 0x0400) {
  83473. NEEDBITS(16);
  83474. state->length = (unsigned)(hold);
  83475. if (state->head != Z_NULL)
  83476. state->head->extra_len = (unsigned)hold;
  83477. if (state->flags & 0x0200) CRC2(state->check, hold);
  83478. INITBITS();
  83479. }
  83480. else if (state->head != Z_NULL)
  83481. state->head->extra = Z_NULL;
  83482. state->mode = EXTRA;
  83483. case EXTRA:
  83484. if (state->flags & 0x0400) {
  83485. copy = state->length;
  83486. if (copy > have) copy = have;
  83487. if (copy) {
  83488. if (state->head != Z_NULL &&
  83489. state->head->extra != Z_NULL) {
  83490. len = state->head->extra_len - state->length;
  83491. zmemcpy(state->head->extra + len, next,
  83492. len + copy > state->head->extra_max ?
  83493. state->head->extra_max - len : copy);
  83494. }
  83495. if (state->flags & 0x0200)
  83496. state->check = crc32(state->check, next, copy);
  83497. have -= copy;
  83498. next += copy;
  83499. state->length -= copy;
  83500. }
  83501. if (state->length) goto inf_leave;
  83502. }
  83503. state->length = 0;
  83504. state->mode = NAME;
  83505. case NAME:
  83506. if (state->flags & 0x0800) {
  83507. if (have == 0) goto inf_leave;
  83508. copy = 0;
  83509. do {
  83510. len = (unsigned)(next[copy++]);
  83511. if (state->head != Z_NULL &&
  83512. state->head->name != Z_NULL &&
  83513. state->length < state->head->name_max)
  83514. state->head->name[state->length++] = len;
  83515. } while (len && copy < have);
  83516. if (state->flags & 0x0200)
  83517. state->check = crc32(state->check, next, copy);
  83518. have -= copy;
  83519. next += copy;
  83520. if (len) goto inf_leave;
  83521. }
  83522. else if (state->head != Z_NULL)
  83523. state->head->name = Z_NULL;
  83524. state->length = 0;
  83525. state->mode = COMMENT;
  83526. case COMMENT:
  83527. if (state->flags & 0x1000) {
  83528. if (have == 0) goto inf_leave;
  83529. copy = 0;
  83530. do {
  83531. len = (unsigned)(next[copy++]);
  83532. if (state->head != Z_NULL &&
  83533. state->head->comment != Z_NULL &&
  83534. state->length < state->head->comm_max)
  83535. state->head->comment[state->length++] = len;
  83536. } while (len && copy < have);
  83537. if (state->flags & 0x0200)
  83538. state->check = crc32(state->check, next, copy);
  83539. have -= copy;
  83540. next += copy;
  83541. if (len) goto inf_leave;
  83542. }
  83543. else if (state->head != Z_NULL)
  83544. state->head->comment = Z_NULL;
  83545. state->mode = HCRC;
  83546. case HCRC:
  83547. if (state->flags & 0x0200) {
  83548. NEEDBITS(16);
  83549. if (hold != (state->check & 0xffff)) {
  83550. strm->msg = (char *)"header crc mismatch";
  83551. state->mode = BAD;
  83552. break;
  83553. }
  83554. INITBITS();
  83555. }
  83556. if (state->head != Z_NULL) {
  83557. state->head->hcrc = (int)((state->flags >> 9) & 1);
  83558. state->head->done = 1;
  83559. }
  83560. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  83561. state->mode = TYPE;
  83562. break;
  83563. #endif
  83564. case DICTID:
  83565. NEEDBITS(32);
  83566. strm->adler = state->check = REVERSE(hold);
  83567. INITBITS();
  83568. state->mode = DICT;
  83569. case DICT:
  83570. if (state->havedict == 0) {
  83571. RESTORE();
  83572. return Z_NEED_DICT;
  83573. }
  83574. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83575. state->mode = TYPE;
  83576. case TYPE:
  83577. if (flush == Z_BLOCK) goto inf_leave;
  83578. case TYPEDO:
  83579. if (state->last) {
  83580. BYTEBITS();
  83581. state->mode = CHECK;
  83582. break;
  83583. }
  83584. NEEDBITS(3);
  83585. state->last = BITS(1);
  83586. DROPBITS(1);
  83587. switch (BITS(2)) {
  83588. case 0: /* stored block */
  83589. Tracev((stderr, "inflate: stored block%s\n",
  83590. state->last ? " (last)" : ""));
  83591. state->mode = STORED;
  83592. break;
  83593. case 1: /* fixed block */
  83594. fixedtables(state);
  83595. Tracev((stderr, "inflate: fixed codes block%s\n",
  83596. state->last ? " (last)" : ""));
  83597. state->mode = LEN; /* decode codes */
  83598. break;
  83599. case 2: /* dynamic block */
  83600. Tracev((stderr, "inflate: dynamic codes block%s\n",
  83601. state->last ? " (last)" : ""));
  83602. state->mode = TABLE;
  83603. break;
  83604. case 3:
  83605. strm->msg = (char *)"invalid block type";
  83606. state->mode = BAD;
  83607. }
  83608. DROPBITS(2);
  83609. break;
  83610. case STORED:
  83611. BYTEBITS(); /* go to byte boundary */
  83612. NEEDBITS(32);
  83613. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  83614. strm->msg = (char *)"invalid stored block lengths";
  83615. state->mode = BAD;
  83616. break;
  83617. }
  83618. state->length = (unsigned)hold & 0xffff;
  83619. Tracev((stderr, "inflate: stored length %u\n",
  83620. state->length));
  83621. INITBITS();
  83622. state->mode = COPY;
  83623. case COPY:
  83624. copy = state->length;
  83625. if (copy) {
  83626. if (copy > have) copy = have;
  83627. if (copy > left) copy = left;
  83628. if (copy == 0) goto inf_leave;
  83629. zmemcpy(put, next, copy);
  83630. have -= copy;
  83631. next += copy;
  83632. left -= copy;
  83633. put += copy;
  83634. state->length -= copy;
  83635. break;
  83636. }
  83637. Tracev((stderr, "inflate: stored end\n"));
  83638. state->mode = TYPE;
  83639. break;
  83640. case TABLE:
  83641. NEEDBITS(14);
  83642. state->nlen = BITS(5) + 257;
  83643. DROPBITS(5);
  83644. state->ndist = BITS(5) + 1;
  83645. DROPBITS(5);
  83646. state->ncode = BITS(4) + 4;
  83647. DROPBITS(4);
  83648. #ifndef PKZIP_BUG_WORKAROUND
  83649. if (state->nlen > 286 || state->ndist > 30) {
  83650. strm->msg = (char *)"too many length or distance symbols";
  83651. state->mode = BAD;
  83652. break;
  83653. }
  83654. #endif
  83655. Tracev((stderr, "inflate: table sizes ok\n"));
  83656. state->have = 0;
  83657. state->mode = LENLENS;
  83658. case LENLENS:
  83659. while (state->have < state->ncode) {
  83660. NEEDBITS(3);
  83661. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  83662. DROPBITS(3);
  83663. }
  83664. while (state->have < 19)
  83665. state->lens[order[state->have++]] = 0;
  83666. state->next = state->codes;
  83667. state->lencode = (code const FAR *)(state->next);
  83668. state->lenbits = 7;
  83669. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  83670. &(state->lenbits), state->work);
  83671. if (ret) {
  83672. strm->msg = (char *)"invalid code lengths set";
  83673. state->mode = BAD;
  83674. break;
  83675. }
  83676. Tracev((stderr, "inflate: code lengths ok\n"));
  83677. state->have = 0;
  83678. state->mode = CODELENS;
  83679. case CODELENS:
  83680. while (state->have < state->nlen + state->ndist) {
  83681. for (;;) {
  83682. thisx = state->lencode[BITS(state->lenbits)];
  83683. if ((unsigned)(thisx.bits) <= bits) break;
  83684. PULLBYTE();
  83685. }
  83686. if (thisx.val < 16) {
  83687. NEEDBITS(thisx.bits);
  83688. DROPBITS(thisx.bits);
  83689. state->lens[state->have++] = thisx.val;
  83690. }
  83691. else {
  83692. if (thisx.val == 16) {
  83693. NEEDBITS(thisx.bits + 2);
  83694. DROPBITS(thisx.bits);
  83695. if (state->have == 0) {
  83696. strm->msg = (char *)"invalid bit length repeat";
  83697. state->mode = BAD;
  83698. break;
  83699. }
  83700. len = state->lens[state->have - 1];
  83701. copy = 3 + BITS(2);
  83702. DROPBITS(2);
  83703. }
  83704. else if (thisx.val == 17) {
  83705. NEEDBITS(thisx.bits + 3);
  83706. DROPBITS(thisx.bits);
  83707. len = 0;
  83708. copy = 3 + BITS(3);
  83709. DROPBITS(3);
  83710. }
  83711. else {
  83712. NEEDBITS(thisx.bits + 7);
  83713. DROPBITS(thisx.bits);
  83714. len = 0;
  83715. copy = 11 + BITS(7);
  83716. DROPBITS(7);
  83717. }
  83718. if (state->have + copy > state->nlen + state->ndist) {
  83719. strm->msg = (char *)"invalid bit length repeat";
  83720. state->mode = BAD;
  83721. break;
  83722. }
  83723. while (copy--)
  83724. state->lens[state->have++] = (unsigned short)len;
  83725. }
  83726. }
  83727. /* handle error breaks in while */
  83728. if (state->mode == BAD) break;
  83729. /* build code tables */
  83730. state->next = state->codes;
  83731. state->lencode = (code const FAR *)(state->next);
  83732. state->lenbits = 9;
  83733. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  83734. &(state->lenbits), state->work);
  83735. if (ret) {
  83736. strm->msg = (char *)"invalid literal/lengths set";
  83737. state->mode = BAD;
  83738. break;
  83739. }
  83740. state->distcode = (code const FAR *)(state->next);
  83741. state->distbits = 6;
  83742. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  83743. &(state->next), &(state->distbits), state->work);
  83744. if (ret) {
  83745. strm->msg = (char *)"invalid distances set";
  83746. state->mode = BAD;
  83747. break;
  83748. }
  83749. Tracev((stderr, "inflate: codes ok\n"));
  83750. state->mode = LEN;
  83751. case LEN:
  83752. if (have >= 6 && left >= 258) {
  83753. RESTORE();
  83754. inflate_fast(strm, out);
  83755. LOAD();
  83756. break;
  83757. }
  83758. for (;;) {
  83759. thisx = state->lencode[BITS(state->lenbits)];
  83760. if ((unsigned)(thisx.bits) <= bits) break;
  83761. PULLBYTE();
  83762. }
  83763. if (thisx.op && (thisx.op & 0xf0) == 0) {
  83764. last = thisx;
  83765. for (;;) {
  83766. thisx = state->lencode[last.val +
  83767. (BITS(last.bits + last.op) >> last.bits)];
  83768. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83769. PULLBYTE();
  83770. }
  83771. DROPBITS(last.bits);
  83772. }
  83773. DROPBITS(thisx.bits);
  83774. state->length = (unsigned)thisx.val;
  83775. if ((int)(thisx.op) == 0) {
  83776. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83777. "inflate: literal '%c'\n" :
  83778. "inflate: literal 0x%02x\n", thisx.val));
  83779. state->mode = LIT;
  83780. break;
  83781. }
  83782. if (thisx.op & 32) {
  83783. Tracevv((stderr, "inflate: end of block\n"));
  83784. state->mode = TYPE;
  83785. break;
  83786. }
  83787. if (thisx.op & 64) {
  83788. strm->msg = (char *)"invalid literal/length code";
  83789. state->mode = BAD;
  83790. break;
  83791. }
  83792. state->extra = (unsigned)(thisx.op) & 15;
  83793. state->mode = LENEXT;
  83794. case LENEXT:
  83795. if (state->extra) {
  83796. NEEDBITS(state->extra);
  83797. state->length += BITS(state->extra);
  83798. DROPBITS(state->extra);
  83799. }
  83800. Tracevv((stderr, "inflate: length %u\n", state->length));
  83801. state->mode = DIST;
  83802. case DIST:
  83803. for (;;) {
  83804. thisx = state->distcode[BITS(state->distbits)];
  83805. if ((unsigned)(thisx.bits) <= bits) break;
  83806. PULLBYTE();
  83807. }
  83808. if ((thisx.op & 0xf0) == 0) {
  83809. last = thisx;
  83810. for (;;) {
  83811. thisx = state->distcode[last.val +
  83812. (BITS(last.bits + last.op) >> last.bits)];
  83813. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83814. PULLBYTE();
  83815. }
  83816. DROPBITS(last.bits);
  83817. }
  83818. DROPBITS(thisx.bits);
  83819. if (thisx.op & 64) {
  83820. strm->msg = (char *)"invalid distance code";
  83821. state->mode = BAD;
  83822. break;
  83823. }
  83824. state->offset = (unsigned)thisx.val;
  83825. state->extra = (unsigned)(thisx.op) & 15;
  83826. state->mode = DISTEXT;
  83827. case DISTEXT:
  83828. if (state->extra) {
  83829. NEEDBITS(state->extra);
  83830. state->offset += BITS(state->extra);
  83831. DROPBITS(state->extra);
  83832. }
  83833. #ifdef INFLATE_STRICT
  83834. if (state->offset > state->dmax) {
  83835. strm->msg = (char *)"invalid distance too far back";
  83836. state->mode = BAD;
  83837. break;
  83838. }
  83839. #endif
  83840. if (state->offset > state->whave + out - left) {
  83841. strm->msg = (char *)"invalid distance too far back";
  83842. state->mode = BAD;
  83843. break;
  83844. }
  83845. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  83846. state->mode = MATCH;
  83847. case MATCH:
  83848. if (left == 0) goto inf_leave;
  83849. copy = out - left;
  83850. if (state->offset > copy) { /* copy from window */
  83851. copy = state->offset - copy;
  83852. if (copy > state->write) {
  83853. copy -= state->write;
  83854. from = state->window + (state->wsize - copy);
  83855. }
  83856. else
  83857. from = state->window + (state->write - copy);
  83858. if (copy > state->length) copy = state->length;
  83859. }
  83860. else { /* copy from output */
  83861. from = put - state->offset;
  83862. copy = state->length;
  83863. }
  83864. if (copy > left) copy = left;
  83865. left -= copy;
  83866. state->length -= copy;
  83867. do {
  83868. *put++ = *from++;
  83869. } while (--copy);
  83870. if (state->length == 0) state->mode = LEN;
  83871. break;
  83872. case LIT:
  83873. if (left == 0) goto inf_leave;
  83874. *put++ = (unsigned char)(state->length);
  83875. left--;
  83876. state->mode = LEN;
  83877. break;
  83878. case CHECK:
  83879. if (state->wrap) {
  83880. NEEDBITS(32);
  83881. out -= left;
  83882. strm->total_out += out;
  83883. state->total += out;
  83884. if (out)
  83885. strm->adler = state->check =
  83886. UPDATE(state->check, put - out, out);
  83887. out = left;
  83888. if ((
  83889. #ifdef GUNZIP
  83890. state->flags ? hold :
  83891. #endif
  83892. REVERSE(hold)) != state->check) {
  83893. strm->msg = (char *)"incorrect data check";
  83894. state->mode = BAD;
  83895. break;
  83896. }
  83897. INITBITS();
  83898. Tracev((stderr, "inflate: check matches trailer\n"));
  83899. }
  83900. #ifdef GUNZIP
  83901. state->mode = LENGTH;
  83902. case LENGTH:
  83903. if (state->wrap && state->flags) {
  83904. NEEDBITS(32);
  83905. if (hold != (state->total & 0xffffffffUL)) {
  83906. strm->msg = (char *)"incorrect length check";
  83907. state->mode = BAD;
  83908. break;
  83909. }
  83910. INITBITS();
  83911. Tracev((stderr, "inflate: length matches trailer\n"));
  83912. }
  83913. #endif
  83914. state->mode = DONE;
  83915. case DONE:
  83916. ret = Z_STREAM_END;
  83917. goto inf_leave;
  83918. case BAD:
  83919. ret = Z_DATA_ERROR;
  83920. goto inf_leave;
  83921. case MEM:
  83922. return Z_MEM_ERROR;
  83923. case SYNC:
  83924. default:
  83925. return Z_STREAM_ERROR;
  83926. }
  83927. /*
  83928. Return from inflate(), updating the total counts and the check value.
  83929. If there was no progress during the inflate() call, return a buffer
  83930. error. Call updatewindow() to create and/or update the window state.
  83931. Note: a memory error from inflate() is non-recoverable.
  83932. */
  83933. inf_leave:
  83934. RESTORE();
  83935. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  83936. if (updatewindow(strm, out)) {
  83937. state->mode = MEM;
  83938. return Z_MEM_ERROR;
  83939. }
  83940. in -= strm->avail_in;
  83941. out -= strm->avail_out;
  83942. strm->total_in += in;
  83943. strm->total_out += out;
  83944. state->total += out;
  83945. if (state->wrap && out)
  83946. strm->adler = state->check =
  83947. UPDATE(state->check, strm->next_out - out, out);
  83948. strm->data_type = state->bits + (state->last ? 64 : 0) +
  83949. (state->mode == TYPE ? 128 : 0);
  83950. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  83951. ret = Z_BUF_ERROR;
  83952. return ret;
  83953. }
  83954. int ZEXPORT inflateEnd (z_streamp strm)
  83955. {
  83956. struct inflate_state FAR *state;
  83957. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  83958. return Z_STREAM_ERROR;
  83959. state = (struct inflate_state FAR *)strm->state;
  83960. if (state->window != Z_NULL) ZFREE(strm, state->window);
  83961. ZFREE(strm, strm->state);
  83962. strm->state = Z_NULL;
  83963. Tracev((stderr, "inflate: end\n"));
  83964. return Z_OK;
  83965. }
  83966. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  83967. {
  83968. struct inflate_state FAR *state;
  83969. unsigned long id_;
  83970. /* check state */
  83971. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83972. state = (struct inflate_state FAR *)strm->state;
  83973. if (state->wrap != 0 && state->mode != DICT)
  83974. return Z_STREAM_ERROR;
  83975. /* check for correct dictionary id */
  83976. if (state->mode == DICT) {
  83977. id_ = adler32(0L, Z_NULL, 0);
  83978. id_ = adler32(id_, dictionary, dictLength);
  83979. if (id_ != state->check)
  83980. return Z_DATA_ERROR;
  83981. }
  83982. /* copy dictionary to window */
  83983. if (updatewindow(strm, strm->avail_out)) {
  83984. state->mode = MEM;
  83985. return Z_MEM_ERROR;
  83986. }
  83987. if (dictLength > state->wsize) {
  83988. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  83989. state->wsize);
  83990. state->whave = state->wsize;
  83991. }
  83992. else {
  83993. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  83994. dictLength);
  83995. state->whave = dictLength;
  83996. }
  83997. state->havedict = 1;
  83998. Tracev((stderr, "inflate: dictionary set\n"));
  83999. return Z_OK;
  84000. }
  84001. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  84002. {
  84003. struct inflate_state FAR *state;
  84004. /* check state */
  84005. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84006. state = (struct inflate_state FAR *)strm->state;
  84007. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  84008. /* save header structure */
  84009. state->head = head;
  84010. head->done = 0;
  84011. return Z_OK;
  84012. }
  84013. /*
  84014. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  84015. or when out of input. When called, *have is the number of pattern bytes
  84016. found in order so far, in 0..3. On return *have is updated to the new
  84017. state. If on return *have equals four, then the pattern was found and the
  84018. return value is how many bytes were read including the last byte of the
  84019. pattern. If *have is less than four, then the pattern has not been found
  84020. yet and the return value is len. In the latter case, syncsearch() can be
  84021. called again with more data and the *have state. *have is initialized to
  84022. zero for the first call.
  84023. */
  84024. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84025. {
  84026. unsigned got;
  84027. unsigned next;
  84028. got = *have;
  84029. next = 0;
  84030. while (next < len && got < 4) {
  84031. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84032. got++;
  84033. else if (buf[next])
  84034. got = 0;
  84035. else
  84036. got = 4 - got;
  84037. next++;
  84038. }
  84039. *have = got;
  84040. return next;
  84041. }
  84042. int ZEXPORT inflateSync (z_streamp strm)
  84043. {
  84044. unsigned len; /* number of bytes to look at or looked at */
  84045. unsigned long in, out; /* temporary to save total_in and total_out */
  84046. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84047. struct inflate_state FAR *state;
  84048. /* check parameters */
  84049. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84050. state = (struct inflate_state FAR *)strm->state;
  84051. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84052. /* if first time, start search in bit buffer */
  84053. if (state->mode != SYNC) {
  84054. state->mode = SYNC;
  84055. state->hold <<= state->bits & 7;
  84056. state->bits -= state->bits & 7;
  84057. len = 0;
  84058. while (state->bits >= 8) {
  84059. buf[len++] = (unsigned char)(state->hold);
  84060. state->hold >>= 8;
  84061. state->bits -= 8;
  84062. }
  84063. state->have = 0;
  84064. syncsearch(&(state->have), buf, len);
  84065. }
  84066. /* search available input */
  84067. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84068. strm->avail_in -= len;
  84069. strm->next_in += len;
  84070. strm->total_in += len;
  84071. /* return no joy or set up to restart inflate() on a new block */
  84072. if (state->have != 4) return Z_DATA_ERROR;
  84073. in = strm->total_in; out = strm->total_out;
  84074. inflateReset(strm);
  84075. strm->total_in = in; strm->total_out = out;
  84076. state->mode = TYPE;
  84077. return Z_OK;
  84078. }
  84079. /*
  84080. Returns true if inflate is currently at the end of a block generated by
  84081. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84082. implementation to provide an additional safety check. PPP uses
  84083. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84084. block. When decompressing, PPP checks that at the end of input packet,
  84085. inflate is waiting for these length bytes.
  84086. */
  84087. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84088. {
  84089. struct inflate_state FAR *state;
  84090. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84091. state = (struct inflate_state FAR *)strm->state;
  84092. return state->mode == STORED && state->bits == 0;
  84093. }
  84094. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84095. {
  84096. struct inflate_state FAR *state;
  84097. struct inflate_state FAR *copy;
  84098. unsigned char FAR *window;
  84099. unsigned wsize;
  84100. /* check input */
  84101. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84102. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84103. return Z_STREAM_ERROR;
  84104. state = (struct inflate_state FAR *)source->state;
  84105. /* allocate space */
  84106. copy = (struct inflate_state FAR *)
  84107. ZALLOC(source, 1, sizeof(struct inflate_state));
  84108. if (copy == Z_NULL) return Z_MEM_ERROR;
  84109. window = Z_NULL;
  84110. if (state->window != Z_NULL) {
  84111. window = (unsigned char FAR *)
  84112. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84113. if (window == Z_NULL) {
  84114. ZFREE(source, copy);
  84115. return Z_MEM_ERROR;
  84116. }
  84117. }
  84118. /* copy state */
  84119. zmemcpy(dest, source, sizeof(z_stream));
  84120. zmemcpy(copy, state, sizeof(struct inflate_state));
  84121. if (state->lencode >= state->codes &&
  84122. state->lencode <= state->codes + ENOUGH - 1) {
  84123. copy->lencode = copy->codes + (state->lencode - state->codes);
  84124. copy->distcode = copy->codes + (state->distcode - state->codes);
  84125. }
  84126. copy->next = copy->codes + (state->next - state->codes);
  84127. if (window != Z_NULL) {
  84128. wsize = 1U << state->wbits;
  84129. zmemcpy(window, state->window, wsize);
  84130. }
  84131. copy->window = window;
  84132. dest->state = (struct internal_state FAR *)copy;
  84133. return Z_OK;
  84134. }
  84135. /*** End of inlined file: inflate.c ***/
  84136. /*** Start of inlined file: inftrees.c ***/
  84137. #define MAXBITS 15
  84138. const char inflate_copyright[] =
  84139. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84140. /*
  84141. If you use the zlib library in a product, an acknowledgment is welcome
  84142. in the documentation of your product. If for some reason you cannot
  84143. include such an acknowledgment, I would appreciate that you keep this
  84144. copyright string in the executable of your product.
  84145. */
  84146. /*
  84147. Build a set of tables to decode the provided canonical Huffman code.
  84148. The code lengths are lens[0..codes-1]. The result starts at *table,
  84149. whose indices are 0..2^bits-1. work is a writable array of at least
  84150. lens shorts, which is used as a work area. type is the type of code
  84151. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84152. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84153. on return points to the next available entry's address. bits is the
  84154. requested root table index bits, and on return it is the actual root
  84155. table index bits. It will differ if the request is greater than the
  84156. longest code or if it is less than the shortest code.
  84157. */
  84158. int inflate_table (codetype type,
  84159. unsigned short FAR *lens,
  84160. unsigned codes,
  84161. code FAR * FAR *table,
  84162. unsigned FAR *bits,
  84163. unsigned short FAR *work)
  84164. {
  84165. unsigned len; /* a code's length in bits */
  84166. unsigned sym; /* index of code symbols */
  84167. unsigned min, max; /* minimum and maximum code lengths */
  84168. unsigned root; /* number of index bits for root table */
  84169. unsigned curr; /* number of index bits for current table */
  84170. unsigned drop; /* code bits to drop for sub-table */
  84171. int left; /* number of prefix codes available */
  84172. unsigned used; /* code entries in table used */
  84173. unsigned huff; /* Huffman code */
  84174. unsigned incr; /* for incrementing code, index */
  84175. unsigned fill; /* index for replicating entries */
  84176. unsigned low; /* low bits for current root entry */
  84177. unsigned mask; /* mask for low root bits */
  84178. code thisx; /* table entry for duplication */
  84179. code FAR *next; /* next available space in table */
  84180. const unsigned short FAR *base; /* base value table to use */
  84181. const unsigned short FAR *extra; /* extra bits table to use */
  84182. int end; /* use base and extra for symbol > end */
  84183. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84184. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84185. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84186. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84187. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84188. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84189. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84190. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84191. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84192. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84193. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84194. 8193, 12289, 16385, 24577, 0, 0};
  84195. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84196. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84197. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84198. 28, 28, 29, 29, 64, 64};
  84199. /*
  84200. Process a set of code lengths to create a canonical Huffman code. The
  84201. code lengths are lens[0..codes-1]. Each length corresponds to the
  84202. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84203. symbols by length from short to long, and retaining the symbol order
  84204. for codes with equal lengths. Then the code starts with all zero bits
  84205. for the first code of the shortest length, and the codes are integer
  84206. increments for the same length, and zeros are appended as the length
  84207. increases. For the deflate format, these bits are stored backwards
  84208. from their more natural integer increment ordering, and so when the
  84209. decoding tables are built in the large loop below, the integer codes
  84210. are incremented backwards.
  84211. This routine assumes, but does not check, that all of the entries in
  84212. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84213. 1..MAXBITS is interpreted as that code length. zero means that that
  84214. symbol does not occur in this code.
  84215. The codes are sorted by computing a count of codes for each length,
  84216. creating from that a table of starting indices for each length in the
  84217. sorted table, and then entering the symbols in order in the sorted
  84218. table. The sorted table is work[], with that space being provided by
  84219. the caller.
  84220. The length counts are used for other purposes as well, i.e. finding
  84221. the minimum and maximum length codes, determining if there are any
  84222. codes at all, checking for a valid set of lengths, and looking ahead
  84223. at length counts to determine sub-table sizes when building the
  84224. decoding tables.
  84225. */
  84226. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84227. for (len = 0; len <= MAXBITS; len++)
  84228. count[len] = 0;
  84229. for (sym = 0; sym < codes; sym++)
  84230. count[lens[sym]]++;
  84231. /* bound code lengths, force root to be within code lengths */
  84232. root = *bits;
  84233. for (max = MAXBITS; max >= 1; max--)
  84234. if (count[max] != 0) break;
  84235. if (root > max) root = max;
  84236. if (max == 0) { /* no symbols to code at all */
  84237. thisx.op = (unsigned char)64; /* invalid code marker */
  84238. thisx.bits = (unsigned char)1;
  84239. thisx.val = (unsigned short)0;
  84240. *(*table)++ = thisx; /* make a table to force an error */
  84241. *(*table)++ = thisx;
  84242. *bits = 1;
  84243. return 0; /* no symbols, but wait for decoding to report error */
  84244. }
  84245. for (min = 1; min <= MAXBITS; min++)
  84246. if (count[min] != 0) break;
  84247. if (root < min) root = min;
  84248. /* check for an over-subscribed or incomplete set of lengths */
  84249. left = 1;
  84250. for (len = 1; len <= MAXBITS; len++) {
  84251. left <<= 1;
  84252. left -= count[len];
  84253. if (left < 0) return -1; /* over-subscribed */
  84254. }
  84255. if (left > 0 && (type == CODES || max != 1))
  84256. return -1; /* incomplete set */
  84257. /* generate offsets into symbol table for each length for sorting */
  84258. offs[1] = 0;
  84259. for (len = 1; len < MAXBITS; len++)
  84260. offs[len + 1] = offs[len] + count[len];
  84261. /* sort symbols by length, by symbol order within each length */
  84262. for (sym = 0; sym < codes; sym++)
  84263. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84264. /*
  84265. Create and fill in decoding tables. In this loop, the table being
  84266. filled is at next and has curr index bits. The code being used is huff
  84267. with length len. That code is converted to an index by dropping drop
  84268. bits off of the bottom. For codes where len is less than drop + curr,
  84269. those top drop + curr - len bits are incremented through all values to
  84270. fill the table with replicated entries.
  84271. root is the number of index bits for the root table. When len exceeds
  84272. root, sub-tables are created pointed to by the root entry with an index
  84273. of the low root bits of huff. This is saved in low to check for when a
  84274. new sub-table should be started. drop is zero when the root table is
  84275. being filled, and drop is root when sub-tables are being filled.
  84276. When a new sub-table is needed, it is necessary to look ahead in the
  84277. code lengths to determine what size sub-table is needed. The length
  84278. counts are used for this, and so count[] is decremented as codes are
  84279. entered in the tables.
  84280. used keeps track of how many table entries have been allocated from the
  84281. provided *table space. It is checked when a LENS table is being made
  84282. against the space in *table, ENOUGH, minus the maximum space needed by
  84283. the worst case distance code, MAXD. This should never happen, but the
  84284. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84285. This assumes that when type == LENS, bits == 9.
  84286. sym increments through all symbols, and the loop terminates when
  84287. all codes of length max, i.e. all codes, have been processed. This
  84288. routine permits incomplete codes, so another loop after this one fills
  84289. in the rest of the decoding tables with invalid code markers.
  84290. */
  84291. /* set up for code type */
  84292. switch (type) {
  84293. case CODES:
  84294. base = extra = work; /* dummy value--not used */
  84295. end = 19;
  84296. break;
  84297. case LENS:
  84298. base = lbase;
  84299. base -= 257;
  84300. extra = lext;
  84301. extra -= 257;
  84302. end = 256;
  84303. break;
  84304. default: /* DISTS */
  84305. base = dbase;
  84306. extra = dext;
  84307. end = -1;
  84308. }
  84309. /* initialize state for loop */
  84310. huff = 0; /* starting code */
  84311. sym = 0; /* starting code symbol */
  84312. len = min; /* starting code length */
  84313. next = *table; /* current table to fill in */
  84314. curr = root; /* current table index bits */
  84315. drop = 0; /* current bits to drop from code for index */
  84316. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84317. used = 1U << root; /* use root table entries */
  84318. mask = used - 1; /* mask for comparing low */
  84319. /* check available table space */
  84320. if (type == LENS && used >= ENOUGH - MAXD)
  84321. return 1;
  84322. /* process all codes and make table entries */
  84323. for (;;) {
  84324. /* create table entry */
  84325. thisx.bits = (unsigned char)(len - drop);
  84326. if ((int)(work[sym]) < end) {
  84327. thisx.op = (unsigned char)0;
  84328. thisx.val = work[sym];
  84329. }
  84330. else if ((int)(work[sym]) > end) {
  84331. thisx.op = (unsigned char)(extra[work[sym]]);
  84332. thisx.val = base[work[sym]];
  84333. }
  84334. else {
  84335. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84336. thisx.val = 0;
  84337. }
  84338. /* replicate for those indices with low len bits equal to huff */
  84339. incr = 1U << (len - drop);
  84340. fill = 1U << curr;
  84341. min = fill; /* save offset to next table */
  84342. do {
  84343. fill -= incr;
  84344. next[(huff >> drop) + fill] = thisx;
  84345. } while (fill != 0);
  84346. /* backwards increment the len-bit code huff */
  84347. incr = 1U << (len - 1);
  84348. while (huff & incr)
  84349. incr >>= 1;
  84350. if (incr != 0) {
  84351. huff &= incr - 1;
  84352. huff += incr;
  84353. }
  84354. else
  84355. huff = 0;
  84356. /* go to next symbol, update count, len */
  84357. sym++;
  84358. if (--(count[len]) == 0) {
  84359. if (len == max) break;
  84360. len = lens[work[sym]];
  84361. }
  84362. /* create new sub-table if needed */
  84363. if (len > root && (huff & mask) != low) {
  84364. /* if first time, transition to sub-tables */
  84365. if (drop == 0)
  84366. drop = root;
  84367. /* increment past last table */
  84368. next += min; /* here min is 1 << curr */
  84369. /* determine length of next table */
  84370. curr = len - drop;
  84371. left = (int)(1 << curr);
  84372. while (curr + drop < max) {
  84373. left -= count[curr + drop];
  84374. if (left <= 0) break;
  84375. curr++;
  84376. left <<= 1;
  84377. }
  84378. /* check for enough space */
  84379. used += 1U << curr;
  84380. if (type == LENS && used >= ENOUGH - MAXD)
  84381. return 1;
  84382. /* point entry in root table to sub-table */
  84383. low = huff & mask;
  84384. (*table)[low].op = (unsigned char)curr;
  84385. (*table)[low].bits = (unsigned char)root;
  84386. (*table)[low].val = (unsigned short)(next - *table);
  84387. }
  84388. }
  84389. /*
  84390. Fill in rest of table for incomplete codes. This loop is similar to the
  84391. loop above in incrementing huff for table indices. It is assumed that
  84392. len is equal to curr + drop, so there is no loop needed to increment
  84393. through high index bits. When the current sub-table is filled, the loop
  84394. drops back to the root table to fill in any remaining entries there.
  84395. */
  84396. thisx.op = (unsigned char)64; /* invalid code marker */
  84397. thisx.bits = (unsigned char)(len - drop);
  84398. thisx.val = (unsigned short)0;
  84399. while (huff != 0) {
  84400. /* when done with sub-table, drop back to root table */
  84401. if (drop != 0 && (huff & mask) != low) {
  84402. drop = 0;
  84403. len = root;
  84404. next = *table;
  84405. thisx.bits = (unsigned char)len;
  84406. }
  84407. /* put invalid code marker in table */
  84408. next[huff >> drop] = thisx;
  84409. /* backwards increment the len-bit code huff */
  84410. incr = 1U << (len - 1);
  84411. while (huff & incr)
  84412. incr >>= 1;
  84413. if (incr != 0) {
  84414. huff &= incr - 1;
  84415. huff += incr;
  84416. }
  84417. else
  84418. huff = 0;
  84419. }
  84420. /* set return parameters */
  84421. *table += used;
  84422. *bits = root;
  84423. return 0;
  84424. }
  84425. /*** End of inlined file: inftrees.c ***/
  84426. /*** Start of inlined file: trees.c ***/
  84427. /*
  84428. * ALGORITHM
  84429. *
  84430. * The "deflation" process uses several Huffman trees. The more
  84431. * common source values are represented by shorter bit sequences.
  84432. *
  84433. * Each code tree is stored in a compressed form which is itself
  84434. * a Huffman encoding of the lengths of all the code strings (in
  84435. * ascending order by source values). The actual code strings are
  84436. * reconstructed from the lengths in the inflate process, as described
  84437. * in the deflate specification.
  84438. *
  84439. * REFERENCES
  84440. *
  84441. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84442. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84443. *
  84444. * Storer, James A.
  84445. * Data Compression: Methods and Theory, pp. 49-50.
  84446. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84447. *
  84448. * Sedgewick, R.
  84449. * Algorithms, p290.
  84450. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84451. */
  84452. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84453. /* #define GEN_TREES_H */
  84454. #ifdef DEBUG
  84455. # include <ctype.h>
  84456. #endif
  84457. /* ===========================================================================
  84458. * Constants
  84459. */
  84460. #define MAX_BL_BITS 7
  84461. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84462. #define END_BLOCK 256
  84463. /* end of block literal code */
  84464. #define REP_3_6 16
  84465. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84466. #define REPZ_3_10 17
  84467. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84468. #define REPZ_11_138 18
  84469. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84470. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84471. = {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};
  84472. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84473. = {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};
  84474. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84475. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84476. local const uch bl_order[BL_CODES]
  84477. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84478. /* The lengths of the bit length codes are sent in order of decreasing
  84479. * probability, to avoid transmitting the lengths for unused bit length codes.
  84480. */
  84481. #define Buf_size (8 * 2*sizeof(char))
  84482. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84483. * more than 16 bits on some systems.)
  84484. */
  84485. /* ===========================================================================
  84486. * Local data. These are initialized only once.
  84487. */
  84488. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84489. #if defined(GEN_TREES_H) || !defined(STDC)
  84490. /* non ANSI compilers may not accept trees.h */
  84491. local ct_data static_ltree[L_CODES+2];
  84492. /* The static literal tree. Since the bit lengths are imposed, there is no
  84493. * need for the L_CODES extra codes used during heap construction. However
  84494. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84495. * below).
  84496. */
  84497. local ct_data static_dtree[D_CODES];
  84498. /* The static distance tree. (Actually a trivial tree since all codes use
  84499. * 5 bits.)
  84500. */
  84501. uch _dist_code[DIST_CODE_LEN];
  84502. /* Distance codes. The first 256 values correspond to the distances
  84503. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  84504. * the 15 bit distances.
  84505. */
  84506. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  84507. /* length code for each normalized match length (0 == MIN_MATCH) */
  84508. local int base_length[LENGTH_CODES];
  84509. /* First normalized length for each code (0 = MIN_MATCH) */
  84510. local int base_dist[D_CODES];
  84511. /* First normalized distance for each code (0 = distance of 1) */
  84512. #else
  84513. /*** Start of inlined file: trees.h ***/
  84514. local const ct_data static_ltree[L_CODES+2] = {
  84515. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  84516. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  84517. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  84518. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  84519. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  84520. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  84521. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  84522. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  84523. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  84524. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  84525. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  84526. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  84527. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  84528. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  84529. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  84530. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  84531. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  84532. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  84533. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  84534. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  84535. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  84536. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  84537. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  84538. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  84539. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  84540. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  84541. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  84542. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  84543. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  84544. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  84545. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  84546. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  84547. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  84548. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  84549. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  84550. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  84551. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  84552. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  84553. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  84554. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  84555. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  84556. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  84557. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  84558. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  84559. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  84560. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  84561. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  84562. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  84563. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  84564. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  84565. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  84566. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  84567. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  84568. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  84569. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  84570. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  84571. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  84572. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  84573. };
  84574. local const ct_data static_dtree[D_CODES] = {
  84575. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  84576. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  84577. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  84578. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  84579. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  84580. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  84581. };
  84582. const uch _dist_code[DIST_CODE_LEN] = {
  84583. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  84584. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  84585. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  84586. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  84587. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  84588. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  84589. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84590. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84591. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84592. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  84593. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84594. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84595. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  84596. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  84597. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84598. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84599. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84600. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  84601. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84602. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84603. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84604. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84605. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84606. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84607. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84608. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  84609. };
  84610. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  84611. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  84612. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  84613. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  84614. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  84615. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  84616. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  84617. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84618. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84619. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84620. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  84621. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84622. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84623. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  84624. };
  84625. local const int base_length[LENGTH_CODES] = {
  84626. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  84627. 64, 80, 96, 112, 128, 160, 192, 224, 0
  84628. };
  84629. local const int base_dist[D_CODES] = {
  84630. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  84631. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  84632. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  84633. };
  84634. /*** End of inlined file: trees.h ***/
  84635. #endif /* GEN_TREES_H */
  84636. struct static_tree_desc_s {
  84637. const ct_data *static_tree; /* static tree or NULL */
  84638. const intf *extra_bits; /* extra bits for each code or NULL */
  84639. int extra_base; /* base index for extra_bits */
  84640. int elems; /* max number of elements in the tree */
  84641. int max_length; /* max bit length for the codes */
  84642. };
  84643. local static_tree_desc static_l_desc =
  84644. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  84645. local static_tree_desc static_d_desc =
  84646. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  84647. local static_tree_desc static_bl_desc =
  84648. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  84649. /* ===========================================================================
  84650. * Local (static) routines in this file.
  84651. */
  84652. local void tr_static_init OF((void));
  84653. local void init_block OF((deflate_state *s));
  84654. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  84655. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  84656. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  84657. local void build_tree OF((deflate_state *s, tree_desc *desc));
  84658. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84659. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84660. local int build_bl_tree OF((deflate_state *s));
  84661. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  84662. int blcodes));
  84663. local void compress_block OF((deflate_state *s, ct_data *ltree,
  84664. ct_data *dtree));
  84665. local void set_data_type OF((deflate_state *s));
  84666. local unsigned bi_reverse OF((unsigned value, int length));
  84667. local void bi_windup OF((deflate_state *s));
  84668. local void bi_flush OF((deflate_state *s));
  84669. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  84670. int header));
  84671. #ifdef GEN_TREES_H
  84672. local void gen_trees_header OF((void));
  84673. #endif
  84674. #ifndef DEBUG
  84675. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  84676. /* Send a code of the given tree. c and tree must not have side effects */
  84677. #else /* DEBUG */
  84678. # define send_code(s, c, tree) \
  84679. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  84680. send_bits(s, tree[c].Code, tree[c].Len); }
  84681. #endif
  84682. /* ===========================================================================
  84683. * Output a short LSB first on the stream.
  84684. * IN assertion: there is enough room in pendingBuf.
  84685. */
  84686. #define put_short(s, w) { \
  84687. put_byte(s, (uch)((w) & 0xff)); \
  84688. put_byte(s, (uch)((ush)(w) >> 8)); \
  84689. }
  84690. /* ===========================================================================
  84691. * Send a value on a given number of bits.
  84692. * IN assertion: length <= 16 and value fits in length bits.
  84693. */
  84694. #ifdef DEBUG
  84695. local void send_bits OF((deflate_state *s, int value, int length));
  84696. local void send_bits (deflate_state *s, int value, int length)
  84697. {
  84698. Tracevv((stderr," l %2d v %4x ", length, value));
  84699. Assert(length > 0 && length <= 15, "invalid length");
  84700. s->bits_sent += (ulg)length;
  84701. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  84702. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  84703. * unused bits in value.
  84704. */
  84705. if (s->bi_valid > (int)Buf_size - length) {
  84706. s->bi_buf |= (value << s->bi_valid);
  84707. put_short(s, s->bi_buf);
  84708. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  84709. s->bi_valid += length - Buf_size;
  84710. } else {
  84711. s->bi_buf |= value << s->bi_valid;
  84712. s->bi_valid += length;
  84713. }
  84714. }
  84715. #else /* !DEBUG */
  84716. #define send_bits(s, value, length) \
  84717. { int len = length;\
  84718. if (s->bi_valid > (int)Buf_size - len) {\
  84719. int val = value;\
  84720. s->bi_buf |= (val << s->bi_valid);\
  84721. put_short(s, s->bi_buf);\
  84722. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  84723. s->bi_valid += len - Buf_size;\
  84724. } else {\
  84725. s->bi_buf |= (value) << s->bi_valid;\
  84726. s->bi_valid += len;\
  84727. }\
  84728. }
  84729. #endif /* DEBUG */
  84730. /* the arguments must not have side effects */
  84731. /* ===========================================================================
  84732. * Initialize the various 'constant' tables.
  84733. */
  84734. local void tr_static_init()
  84735. {
  84736. #if defined(GEN_TREES_H) || !defined(STDC)
  84737. static int static_init_done = 0;
  84738. int n; /* iterates over tree elements */
  84739. int bits; /* bit counter */
  84740. int length; /* length value */
  84741. int code; /* code value */
  84742. int dist; /* distance index */
  84743. ush bl_count[MAX_BITS+1];
  84744. /* number of codes at each bit length for an optimal tree */
  84745. if (static_init_done) return;
  84746. /* For some embedded targets, global variables are not initialized: */
  84747. static_l_desc.static_tree = static_ltree;
  84748. static_l_desc.extra_bits = extra_lbits;
  84749. static_d_desc.static_tree = static_dtree;
  84750. static_d_desc.extra_bits = extra_dbits;
  84751. static_bl_desc.extra_bits = extra_blbits;
  84752. /* Initialize the mapping length (0..255) -> length code (0..28) */
  84753. length = 0;
  84754. for (code = 0; code < LENGTH_CODES-1; code++) {
  84755. base_length[code] = length;
  84756. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  84757. _length_code[length++] = (uch)code;
  84758. }
  84759. }
  84760. Assert (length == 256, "tr_static_init: length != 256");
  84761. /* Note that the length 255 (match length 258) can be represented
  84762. * in two different ways: code 284 + 5 bits or code 285, so we
  84763. * overwrite length_code[255] to use the best encoding:
  84764. */
  84765. _length_code[length-1] = (uch)code;
  84766. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  84767. dist = 0;
  84768. for (code = 0 ; code < 16; code++) {
  84769. base_dist[code] = dist;
  84770. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  84771. _dist_code[dist++] = (uch)code;
  84772. }
  84773. }
  84774. Assert (dist == 256, "tr_static_init: dist != 256");
  84775. dist >>= 7; /* from now on, all distances are divided by 128 */
  84776. for ( ; code < D_CODES; code++) {
  84777. base_dist[code] = dist << 7;
  84778. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  84779. _dist_code[256 + dist++] = (uch)code;
  84780. }
  84781. }
  84782. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  84783. /* Construct the codes of the static literal tree */
  84784. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  84785. n = 0;
  84786. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  84787. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  84788. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  84789. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  84790. /* Codes 286 and 287 do not exist, but we must include them in the
  84791. * tree construction to get a canonical Huffman tree (longest code
  84792. * all ones)
  84793. */
  84794. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  84795. /* The static distance tree is trivial: */
  84796. for (n = 0; n < D_CODES; n++) {
  84797. static_dtree[n].Len = 5;
  84798. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  84799. }
  84800. static_init_done = 1;
  84801. # ifdef GEN_TREES_H
  84802. gen_trees_header();
  84803. # endif
  84804. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  84805. }
  84806. /* ===========================================================================
  84807. * Genererate the file trees.h describing the static trees.
  84808. */
  84809. #ifdef GEN_TREES_H
  84810. # ifndef DEBUG
  84811. # include <stdio.h>
  84812. # endif
  84813. # define SEPARATOR(i, last, width) \
  84814. ((i) == (last)? "\n};\n\n" : \
  84815. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  84816. void gen_trees_header()
  84817. {
  84818. FILE *header = fopen("trees.h", "w");
  84819. int i;
  84820. Assert (header != NULL, "Can't open trees.h");
  84821. fprintf(header,
  84822. "/* header created automatically with -DGEN_TREES_H */\n\n");
  84823. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  84824. for (i = 0; i < L_CODES+2; i++) {
  84825. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  84826. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  84827. }
  84828. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  84829. for (i = 0; i < D_CODES; i++) {
  84830. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  84831. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  84832. }
  84833. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  84834. for (i = 0; i < DIST_CODE_LEN; i++) {
  84835. fprintf(header, "%2u%s", _dist_code[i],
  84836. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  84837. }
  84838. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  84839. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  84840. fprintf(header, "%2u%s", _length_code[i],
  84841. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  84842. }
  84843. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  84844. for (i = 0; i < LENGTH_CODES; i++) {
  84845. fprintf(header, "%1u%s", base_length[i],
  84846. SEPARATOR(i, LENGTH_CODES-1, 20));
  84847. }
  84848. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  84849. for (i = 0; i < D_CODES; i++) {
  84850. fprintf(header, "%5u%s", base_dist[i],
  84851. SEPARATOR(i, D_CODES-1, 10));
  84852. }
  84853. fclose(header);
  84854. }
  84855. #endif /* GEN_TREES_H */
  84856. /* ===========================================================================
  84857. * Initialize the tree data structures for a new zlib stream.
  84858. */
  84859. void _tr_init(deflate_state *s)
  84860. {
  84861. tr_static_init();
  84862. s->l_desc.dyn_tree = s->dyn_ltree;
  84863. s->l_desc.stat_desc = &static_l_desc;
  84864. s->d_desc.dyn_tree = s->dyn_dtree;
  84865. s->d_desc.stat_desc = &static_d_desc;
  84866. s->bl_desc.dyn_tree = s->bl_tree;
  84867. s->bl_desc.stat_desc = &static_bl_desc;
  84868. s->bi_buf = 0;
  84869. s->bi_valid = 0;
  84870. s->last_eob_len = 8; /* enough lookahead for inflate */
  84871. #ifdef DEBUG
  84872. s->compressed_len = 0L;
  84873. s->bits_sent = 0L;
  84874. #endif
  84875. /* Initialize the first block of the first file: */
  84876. init_block(s);
  84877. }
  84878. /* ===========================================================================
  84879. * Initialize a new block.
  84880. */
  84881. local void init_block (deflate_state *s)
  84882. {
  84883. int n; /* iterates over tree elements */
  84884. /* Initialize the trees. */
  84885. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  84886. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  84887. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  84888. s->dyn_ltree[END_BLOCK].Freq = 1;
  84889. s->opt_len = s->static_len = 0L;
  84890. s->last_lit = s->matches = 0;
  84891. }
  84892. #define SMALLEST 1
  84893. /* Index within the heap array of least frequent node in the Huffman tree */
  84894. /* ===========================================================================
  84895. * Remove the smallest element from the heap and recreate the heap with
  84896. * one less element. Updates heap and heap_len.
  84897. */
  84898. #define pqremove(s, tree, top) \
  84899. {\
  84900. top = s->heap[SMALLEST]; \
  84901. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  84902. pqdownheap(s, tree, SMALLEST); \
  84903. }
  84904. /* ===========================================================================
  84905. * Compares to subtrees, using the tree depth as tie breaker when
  84906. * the subtrees have equal frequency. This minimizes the worst case length.
  84907. */
  84908. #define smaller(tree, n, m, depth) \
  84909. (tree[n].Freq < tree[m].Freq || \
  84910. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  84911. /* ===========================================================================
  84912. * Restore the heap property by moving down the tree starting at node k,
  84913. * exchanging a node with the smallest of its two sons if necessary, stopping
  84914. * when the heap property is re-established (each father smaller than its
  84915. * two sons).
  84916. */
  84917. local void pqdownheap (deflate_state *s,
  84918. ct_data *tree, /* the tree to restore */
  84919. int k) /* node to move down */
  84920. {
  84921. int v = s->heap[k];
  84922. int j = k << 1; /* left son of k */
  84923. while (j <= s->heap_len) {
  84924. /* Set j to the smallest of the two sons: */
  84925. if (j < s->heap_len &&
  84926. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  84927. j++;
  84928. }
  84929. /* Exit if v is smaller than both sons */
  84930. if (smaller(tree, v, s->heap[j], s->depth)) break;
  84931. /* Exchange v with the smallest son */
  84932. s->heap[k] = s->heap[j]; k = j;
  84933. /* And continue down the tree, setting j to the left son of k */
  84934. j <<= 1;
  84935. }
  84936. s->heap[k] = v;
  84937. }
  84938. /* ===========================================================================
  84939. * Compute the optimal bit lengths for a tree and update the total bit length
  84940. * for the current block.
  84941. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  84942. * above are the tree nodes sorted by increasing frequency.
  84943. * OUT assertions: the field len is set to the optimal bit length, the
  84944. * array bl_count contains the frequencies for each bit length.
  84945. * The length opt_len is updated; static_len is also updated if stree is
  84946. * not null.
  84947. */
  84948. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  84949. {
  84950. ct_data *tree = desc->dyn_tree;
  84951. int max_code = desc->max_code;
  84952. const ct_data *stree = desc->stat_desc->static_tree;
  84953. const intf *extra = desc->stat_desc->extra_bits;
  84954. int base = desc->stat_desc->extra_base;
  84955. int max_length = desc->stat_desc->max_length;
  84956. int h; /* heap index */
  84957. int n, m; /* iterate over the tree elements */
  84958. int bits; /* bit length */
  84959. int xbits; /* extra bits */
  84960. ush f; /* frequency */
  84961. int overflow = 0; /* number of elements with bit length too large */
  84962. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  84963. /* In a first pass, compute the optimal bit lengths (which may
  84964. * overflow in the case of the bit length tree).
  84965. */
  84966. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  84967. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  84968. n = s->heap[h];
  84969. bits = tree[tree[n].Dad].Len + 1;
  84970. if (bits > max_length) bits = max_length, overflow++;
  84971. tree[n].Len = (ush)bits;
  84972. /* We overwrite tree[n].Dad which is no longer needed */
  84973. if (n > max_code) continue; /* not a leaf node */
  84974. s->bl_count[bits]++;
  84975. xbits = 0;
  84976. if (n >= base) xbits = extra[n-base];
  84977. f = tree[n].Freq;
  84978. s->opt_len += (ulg)f * (bits + xbits);
  84979. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  84980. }
  84981. if (overflow == 0) return;
  84982. Trace((stderr,"\nbit length overflow\n"));
  84983. /* This happens for example on obj2 and pic of the Calgary corpus */
  84984. /* Find the first bit length which could increase: */
  84985. do {
  84986. bits = max_length-1;
  84987. while (s->bl_count[bits] == 0) bits--;
  84988. s->bl_count[bits]--; /* move one leaf down the tree */
  84989. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  84990. s->bl_count[max_length]--;
  84991. /* The brother of the overflow item also moves one step up,
  84992. * but this does not affect bl_count[max_length]
  84993. */
  84994. overflow -= 2;
  84995. } while (overflow > 0);
  84996. /* Now recompute all bit lengths, scanning in increasing frequency.
  84997. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  84998. * lengths instead of fixing only the wrong ones. This idea is taken
  84999. * from 'ar' written by Haruhiko Okumura.)
  85000. */
  85001. for (bits = max_length; bits != 0; bits--) {
  85002. n = s->bl_count[bits];
  85003. while (n != 0) {
  85004. m = s->heap[--h];
  85005. if (m > max_code) continue;
  85006. if ((unsigned) tree[m].Len != (unsigned) bits) {
  85007. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85008. s->opt_len += ((long)bits - (long)tree[m].Len)
  85009. *(long)tree[m].Freq;
  85010. tree[m].Len = (ush)bits;
  85011. }
  85012. n--;
  85013. }
  85014. }
  85015. }
  85016. /* ===========================================================================
  85017. * Generate the codes for a given tree and bit counts (which need not be
  85018. * optimal).
  85019. * IN assertion: the array bl_count contains the bit length statistics for
  85020. * the given tree and the field len is set for all tree elements.
  85021. * OUT assertion: the field code is set for all tree elements of non
  85022. * zero code length.
  85023. */
  85024. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85025. int max_code, /* largest code with non zero frequency */
  85026. ushf *bl_count) /* number of codes at each bit length */
  85027. {
  85028. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85029. ush code = 0; /* running code value */
  85030. int bits; /* bit index */
  85031. int n; /* code index */
  85032. /* The distribution counts are first used to generate the code values
  85033. * without bit reversal.
  85034. */
  85035. for (bits = 1; bits <= MAX_BITS; bits++) {
  85036. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85037. }
  85038. /* Check that the bit counts in bl_count are consistent. The last code
  85039. * must be all ones.
  85040. */
  85041. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85042. "inconsistent bit counts");
  85043. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85044. for (n = 0; n <= max_code; n++) {
  85045. int len = tree[n].Len;
  85046. if (len == 0) continue;
  85047. /* Now reverse the bits */
  85048. tree[n].Code = bi_reverse(next_code[len]++, len);
  85049. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85050. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85051. }
  85052. }
  85053. /* ===========================================================================
  85054. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85055. * Update the total bit length for the current block.
  85056. * IN assertion: the field freq is set for all tree elements.
  85057. * OUT assertions: the fields len and code are set to the optimal bit length
  85058. * and corresponding code. The length opt_len is updated; static_len is
  85059. * also updated if stree is not null. The field max_code is set.
  85060. */
  85061. local void build_tree (deflate_state *s,
  85062. tree_desc *desc) /* the tree descriptor */
  85063. {
  85064. ct_data *tree = desc->dyn_tree;
  85065. const ct_data *stree = desc->stat_desc->static_tree;
  85066. int elems = desc->stat_desc->elems;
  85067. int n, m; /* iterate over heap elements */
  85068. int max_code = -1; /* largest code with non zero frequency */
  85069. int node; /* new node being created */
  85070. /* Construct the initial heap, with least frequent element in
  85071. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85072. * heap[0] is not used.
  85073. */
  85074. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85075. for (n = 0; n < elems; n++) {
  85076. if (tree[n].Freq != 0) {
  85077. s->heap[++(s->heap_len)] = max_code = n;
  85078. s->depth[n] = 0;
  85079. } else {
  85080. tree[n].Len = 0;
  85081. }
  85082. }
  85083. /* The pkzip format requires that at least one distance code exists,
  85084. * and that at least one bit should be sent even if there is only one
  85085. * possible code. So to avoid special checks later on we force at least
  85086. * two codes of non zero frequency.
  85087. */
  85088. while (s->heap_len < 2) {
  85089. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85090. tree[node].Freq = 1;
  85091. s->depth[node] = 0;
  85092. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85093. /* node is 0 or 1 so it does not have extra bits */
  85094. }
  85095. desc->max_code = max_code;
  85096. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85097. * establish sub-heaps of increasing lengths:
  85098. */
  85099. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85100. /* Construct the Huffman tree by repeatedly combining the least two
  85101. * frequent nodes.
  85102. */
  85103. node = elems; /* next internal node of the tree */
  85104. do {
  85105. pqremove(s, tree, n); /* n = node of least frequency */
  85106. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85107. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85108. s->heap[--(s->heap_max)] = m;
  85109. /* Create a new node father of n and m */
  85110. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85111. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85112. s->depth[n] : s->depth[m]) + 1);
  85113. tree[n].Dad = tree[m].Dad = (ush)node;
  85114. #ifdef DUMP_BL_TREE
  85115. if (tree == s->bl_tree) {
  85116. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85117. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85118. }
  85119. #endif
  85120. /* and insert the new node in the heap */
  85121. s->heap[SMALLEST] = node++;
  85122. pqdownheap(s, tree, SMALLEST);
  85123. } while (s->heap_len >= 2);
  85124. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85125. /* At this point, the fields freq and dad are set. We can now
  85126. * generate the bit lengths.
  85127. */
  85128. gen_bitlen(s, (tree_desc *)desc);
  85129. /* The field len is now set, we can generate the bit codes */
  85130. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85131. }
  85132. /* ===========================================================================
  85133. * Scan a literal or distance tree to determine the frequencies of the codes
  85134. * in the bit length tree.
  85135. */
  85136. local void scan_tree (deflate_state *s,
  85137. ct_data *tree, /* the tree to be scanned */
  85138. int max_code) /* and its largest code of non zero frequency */
  85139. {
  85140. int n; /* iterates over all tree elements */
  85141. int prevlen = -1; /* last emitted length */
  85142. int curlen; /* length of current code */
  85143. int nextlen = tree[0].Len; /* length of next code */
  85144. int count = 0; /* repeat count of the current code */
  85145. int max_count = 7; /* max repeat count */
  85146. int min_count = 4; /* min repeat count */
  85147. if (nextlen == 0) max_count = 138, min_count = 3;
  85148. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85149. for (n = 0; n <= max_code; n++) {
  85150. curlen = nextlen; nextlen = tree[n+1].Len;
  85151. if (++count < max_count && curlen == nextlen) {
  85152. continue;
  85153. } else if (count < min_count) {
  85154. s->bl_tree[curlen].Freq += count;
  85155. } else if (curlen != 0) {
  85156. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85157. s->bl_tree[REP_3_6].Freq++;
  85158. } else if (count <= 10) {
  85159. s->bl_tree[REPZ_3_10].Freq++;
  85160. } else {
  85161. s->bl_tree[REPZ_11_138].Freq++;
  85162. }
  85163. count = 0; prevlen = curlen;
  85164. if (nextlen == 0) {
  85165. max_count = 138, min_count = 3;
  85166. } else if (curlen == nextlen) {
  85167. max_count = 6, min_count = 3;
  85168. } else {
  85169. max_count = 7, min_count = 4;
  85170. }
  85171. }
  85172. }
  85173. /* ===========================================================================
  85174. * Send a literal or distance tree in compressed form, using the codes in
  85175. * bl_tree.
  85176. */
  85177. local void send_tree (deflate_state *s,
  85178. ct_data *tree, /* the tree to be scanned */
  85179. int max_code) /* and its largest code of non zero frequency */
  85180. {
  85181. int n; /* iterates over all tree elements */
  85182. int prevlen = -1; /* last emitted length */
  85183. int curlen; /* length of current code */
  85184. int nextlen = tree[0].Len; /* length of next code */
  85185. int count = 0; /* repeat count of the current code */
  85186. int max_count = 7; /* max repeat count */
  85187. int min_count = 4; /* min repeat count */
  85188. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85189. if (nextlen == 0) max_count = 138, min_count = 3;
  85190. for (n = 0; n <= max_code; n++) {
  85191. curlen = nextlen; nextlen = tree[n+1].Len;
  85192. if (++count < max_count && curlen == nextlen) {
  85193. continue;
  85194. } else if (count < min_count) {
  85195. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85196. } else if (curlen != 0) {
  85197. if (curlen != prevlen) {
  85198. send_code(s, curlen, s->bl_tree); count--;
  85199. }
  85200. Assert(count >= 3 && count <= 6, " 3_6?");
  85201. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85202. } else if (count <= 10) {
  85203. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85204. } else {
  85205. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85206. }
  85207. count = 0; prevlen = curlen;
  85208. if (nextlen == 0) {
  85209. max_count = 138, min_count = 3;
  85210. } else if (curlen == nextlen) {
  85211. max_count = 6, min_count = 3;
  85212. } else {
  85213. max_count = 7, min_count = 4;
  85214. }
  85215. }
  85216. }
  85217. /* ===========================================================================
  85218. * Construct the Huffman tree for the bit lengths and return the index in
  85219. * bl_order of the last bit length code to send.
  85220. */
  85221. local int build_bl_tree (deflate_state *s)
  85222. {
  85223. int max_blindex; /* index of last bit length code of non zero freq */
  85224. /* Determine the bit length frequencies for literal and distance trees */
  85225. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85226. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85227. /* Build the bit length tree: */
  85228. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85229. /* opt_len now includes the length of the tree representations, except
  85230. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85231. */
  85232. /* Determine the number of bit length codes to send. The pkzip format
  85233. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85234. * 3 but the actual value used is 4.)
  85235. */
  85236. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85237. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85238. }
  85239. /* Update opt_len to include the bit length tree and counts */
  85240. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85241. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85242. s->opt_len, s->static_len));
  85243. return max_blindex;
  85244. }
  85245. /* ===========================================================================
  85246. * Send the header for a block using dynamic Huffman trees: the counts, the
  85247. * lengths of the bit length codes, the literal tree and the distance tree.
  85248. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85249. */
  85250. local void send_all_trees (deflate_state *s,
  85251. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85252. {
  85253. int rank; /* index in bl_order */
  85254. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85255. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85256. "too many codes");
  85257. Tracev((stderr, "\nbl counts: "));
  85258. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85259. send_bits(s, dcodes-1, 5);
  85260. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85261. for (rank = 0; rank < blcodes; rank++) {
  85262. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85263. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85264. }
  85265. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85266. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85267. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85268. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85269. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85270. }
  85271. /* ===========================================================================
  85272. * Send a stored block
  85273. */
  85274. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85275. {
  85276. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85277. #ifdef DEBUG
  85278. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85279. s->compressed_len += (stored_len + 4) << 3;
  85280. #endif
  85281. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85282. }
  85283. /* ===========================================================================
  85284. * Send one empty static block to give enough lookahead for inflate.
  85285. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85286. * The current inflate code requires 9 bits of lookahead. If the
  85287. * last two codes for the previous block (real code plus EOB) were coded
  85288. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85289. * the last real code. In this case we send two empty static blocks instead
  85290. * of one. (There are no problems if the previous block is stored or fixed.)
  85291. * To simplify the code, we assume the worst case of last real code encoded
  85292. * on one bit only.
  85293. */
  85294. void _tr_align (deflate_state *s)
  85295. {
  85296. send_bits(s, STATIC_TREES<<1, 3);
  85297. send_code(s, END_BLOCK, static_ltree);
  85298. #ifdef DEBUG
  85299. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85300. #endif
  85301. bi_flush(s);
  85302. /* Of the 10 bits for the empty block, we have already sent
  85303. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85304. * the EOB of the previous block) was thus at least one plus the length
  85305. * of the EOB plus what we have just sent of the empty static block.
  85306. */
  85307. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85308. send_bits(s, STATIC_TREES<<1, 3);
  85309. send_code(s, END_BLOCK, static_ltree);
  85310. #ifdef DEBUG
  85311. s->compressed_len += 10L;
  85312. #endif
  85313. bi_flush(s);
  85314. }
  85315. s->last_eob_len = 7;
  85316. }
  85317. /* ===========================================================================
  85318. * Determine the best encoding for the current block: dynamic trees, static
  85319. * trees or store, and output the encoded block to the zip file.
  85320. */
  85321. void _tr_flush_block (deflate_state *s,
  85322. charf *buf, /* input block, or NULL if too old */
  85323. ulg stored_len, /* length of input block */
  85324. int eof) /* true if this is the last block for a file */
  85325. {
  85326. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85327. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85328. /* Build the Huffman trees unless a stored block is forced */
  85329. if (s->level > 0) {
  85330. /* Check if the file is binary or text */
  85331. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85332. set_data_type(s);
  85333. /* Construct the literal and distance trees */
  85334. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85335. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85336. s->static_len));
  85337. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85338. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85339. s->static_len));
  85340. /* At this point, opt_len and static_len are the total bit lengths of
  85341. * the compressed block data, excluding the tree representations.
  85342. */
  85343. /* Build the bit length tree for the above two trees, and get the index
  85344. * in bl_order of the last bit length code to send.
  85345. */
  85346. max_blindex = build_bl_tree(s);
  85347. /* Determine the best encoding. Compute the block lengths in bytes. */
  85348. opt_lenb = (s->opt_len+3+7)>>3;
  85349. static_lenb = (s->static_len+3+7)>>3;
  85350. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85351. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85352. s->last_lit));
  85353. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85354. } else {
  85355. Assert(buf != (char*)0, "lost buf");
  85356. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85357. }
  85358. #ifdef FORCE_STORED
  85359. if (buf != (char*)0) { /* force stored block */
  85360. #else
  85361. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85362. /* 4: two words for the lengths */
  85363. #endif
  85364. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85365. * Otherwise we can't have processed more than WSIZE input bytes since
  85366. * the last block flush, because compression would have been
  85367. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85368. * transform a block into a stored block.
  85369. */
  85370. _tr_stored_block(s, buf, stored_len, eof);
  85371. #ifdef FORCE_STATIC
  85372. } else if (static_lenb >= 0) { /* force static trees */
  85373. #else
  85374. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85375. #endif
  85376. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85377. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85378. #ifdef DEBUG
  85379. s->compressed_len += 3 + s->static_len;
  85380. #endif
  85381. } else {
  85382. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85383. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85384. max_blindex+1);
  85385. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85386. #ifdef DEBUG
  85387. s->compressed_len += 3 + s->opt_len;
  85388. #endif
  85389. }
  85390. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85391. /* The above check is made mod 2^32, for files larger than 512 MB
  85392. * and uLong implemented on 32 bits.
  85393. */
  85394. init_block(s);
  85395. if (eof) {
  85396. bi_windup(s);
  85397. #ifdef DEBUG
  85398. s->compressed_len += 7; /* align on byte boundary */
  85399. #endif
  85400. }
  85401. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85402. s->compressed_len-7*eof));
  85403. }
  85404. /* ===========================================================================
  85405. * Save the match info and tally the frequency counts. Return true if
  85406. * the current block must be flushed.
  85407. */
  85408. int _tr_tally (deflate_state *s,
  85409. unsigned dist, /* distance of matched string */
  85410. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85411. {
  85412. s->d_buf[s->last_lit] = (ush)dist;
  85413. s->l_buf[s->last_lit++] = (uch)lc;
  85414. if (dist == 0) {
  85415. /* lc is the unmatched char */
  85416. s->dyn_ltree[lc].Freq++;
  85417. } else {
  85418. s->matches++;
  85419. /* Here, lc is the match length - MIN_MATCH */
  85420. dist--; /* dist = match distance - 1 */
  85421. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85422. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85423. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85424. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85425. s->dyn_dtree[d_code(dist)].Freq++;
  85426. }
  85427. #ifdef TRUNCATE_BLOCK
  85428. /* Try to guess if it is profitable to stop the current block here */
  85429. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85430. /* Compute an upper bound for the compressed length */
  85431. ulg out_length = (ulg)s->last_lit*8L;
  85432. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85433. int dcode;
  85434. for (dcode = 0; dcode < D_CODES; dcode++) {
  85435. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85436. (5L+extra_dbits[dcode]);
  85437. }
  85438. out_length >>= 3;
  85439. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85440. s->last_lit, in_length, out_length,
  85441. 100L - out_length*100L/in_length));
  85442. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85443. }
  85444. #endif
  85445. return (s->last_lit == s->lit_bufsize-1);
  85446. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85447. * on 16 bit machines and because stored blocks are restricted to
  85448. * 64K-1 bytes.
  85449. */
  85450. }
  85451. /* ===========================================================================
  85452. * Send the block data compressed using the given Huffman trees
  85453. */
  85454. local void compress_block (deflate_state *s,
  85455. ct_data *ltree, /* literal tree */
  85456. ct_data *dtree) /* distance tree */
  85457. {
  85458. unsigned dist; /* distance of matched string */
  85459. int lc; /* match length or unmatched char (if dist == 0) */
  85460. unsigned lx = 0; /* running index in l_buf */
  85461. unsigned code; /* the code to send */
  85462. int extra; /* number of extra bits to send */
  85463. if (s->last_lit != 0) do {
  85464. dist = s->d_buf[lx];
  85465. lc = s->l_buf[lx++];
  85466. if (dist == 0) {
  85467. send_code(s, lc, ltree); /* send a literal byte */
  85468. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85469. } else {
  85470. /* Here, lc is the match length - MIN_MATCH */
  85471. code = _length_code[lc];
  85472. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85473. extra = extra_lbits[code];
  85474. if (extra != 0) {
  85475. lc -= base_length[code];
  85476. send_bits(s, lc, extra); /* send the extra length bits */
  85477. }
  85478. dist--; /* dist is now the match distance - 1 */
  85479. code = d_code(dist);
  85480. Assert (code < D_CODES, "bad d_code");
  85481. send_code(s, code, dtree); /* send the distance code */
  85482. extra = extra_dbits[code];
  85483. if (extra != 0) {
  85484. dist -= base_dist[code];
  85485. send_bits(s, dist, extra); /* send the extra distance bits */
  85486. }
  85487. } /* literal or match pair ? */
  85488. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85489. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85490. "pendingBuf overflow");
  85491. } while (lx < s->last_lit);
  85492. send_code(s, END_BLOCK, ltree);
  85493. s->last_eob_len = ltree[END_BLOCK].Len;
  85494. }
  85495. /* ===========================================================================
  85496. * Set the data type to BINARY or TEXT, using a crude approximation:
  85497. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  85498. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  85499. * IN assertion: the fields Freq of dyn_ltree are set.
  85500. */
  85501. local void set_data_type (deflate_state *s)
  85502. {
  85503. int n;
  85504. for (n = 0; n < 9; n++)
  85505. if (s->dyn_ltree[n].Freq != 0)
  85506. break;
  85507. if (n == 9)
  85508. for (n = 14; n < 32; n++)
  85509. if (s->dyn_ltree[n].Freq != 0)
  85510. break;
  85511. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  85512. }
  85513. /* ===========================================================================
  85514. * Reverse the first len bits of a code, using straightforward code (a faster
  85515. * method would use a table)
  85516. * IN assertion: 1 <= len <= 15
  85517. */
  85518. local unsigned bi_reverse (unsigned code, int len)
  85519. {
  85520. register unsigned res = 0;
  85521. do {
  85522. res |= code & 1;
  85523. code >>= 1, res <<= 1;
  85524. } while (--len > 0);
  85525. return res >> 1;
  85526. }
  85527. /* ===========================================================================
  85528. * Flush the bit buffer, keeping at most 7 bits in it.
  85529. */
  85530. local void bi_flush (deflate_state *s)
  85531. {
  85532. if (s->bi_valid == 16) {
  85533. put_short(s, s->bi_buf);
  85534. s->bi_buf = 0;
  85535. s->bi_valid = 0;
  85536. } else if (s->bi_valid >= 8) {
  85537. put_byte(s, (Byte)s->bi_buf);
  85538. s->bi_buf >>= 8;
  85539. s->bi_valid -= 8;
  85540. }
  85541. }
  85542. /* ===========================================================================
  85543. * Flush the bit buffer and align the output on a byte boundary
  85544. */
  85545. local void bi_windup (deflate_state *s)
  85546. {
  85547. if (s->bi_valid > 8) {
  85548. put_short(s, s->bi_buf);
  85549. } else if (s->bi_valid > 0) {
  85550. put_byte(s, (Byte)s->bi_buf);
  85551. }
  85552. s->bi_buf = 0;
  85553. s->bi_valid = 0;
  85554. #ifdef DEBUG
  85555. s->bits_sent = (s->bits_sent+7) & ~7;
  85556. #endif
  85557. }
  85558. /* ===========================================================================
  85559. * Copy a stored block, storing first the length and its
  85560. * one's complement if requested.
  85561. */
  85562. local void copy_block(deflate_state *s,
  85563. charf *buf, /* the input data */
  85564. unsigned len, /* its length */
  85565. int header) /* true if block header must be written */
  85566. {
  85567. bi_windup(s); /* align on byte boundary */
  85568. s->last_eob_len = 8; /* enough lookahead for inflate */
  85569. if (header) {
  85570. put_short(s, (ush)len);
  85571. put_short(s, (ush)~len);
  85572. #ifdef DEBUG
  85573. s->bits_sent += 2*16;
  85574. #endif
  85575. }
  85576. #ifdef DEBUG
  85577. s->bits_sent += (ulg)len<<3;
  85578. #endif
  85579. while (len--) {
  85580. put_byte(s, *buf++);
  85581. }
  85582. }
  85583. /*** End of inlined file: trees.c ***/
  85584. /*** Start of inlined file: zutil.c ***/
  85585. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85586. #ifndef NO_DUMMY_DECL
  85587. struct internal_state {int dummy;}; /* for buggy compilers */
  85588. #endif
  85589. const char * const z_errmsg[10] = {
  85590. "need dictionary", /* Z_NEED_DICT 2 */
  85591. "stream end", /* Z_STREAM_END 1 */
  85592. "", /* Z_OK 0 */
  85593. "file error", /* Z_ERRNO (-1) */
  85594. "stream error", /* Z_STREAM_ERROR (-2) */
  85595. "data error", /* Z_DATA_ERROR (-3) */
  85596. "insufficient memory", /* Z_MEM_ERROR (-4) */
  85597. "buffer error", /* Z_BUF_ERROR (-5) */
  85598. "incompatible version",/* Z_VERSION_ERROR (-6) */
  85599. ""};
  85600. /*const char * ZEXPORT zlibVersion()
  85601. {
  85602. return ZLIB_VERSION;
  85603. }
  85604. uLong ZEXPORT zlibCompileFlags()
  85605. {
  85606. uLong flags;
  85607. flags = 0;
  85608. switch (sizeof(uInt)) {
  85609. case 2: break;
  85610. case 4: flags += 1; break;
  85611. case 8: flags += 2; break;
  85612. default: flags += 3;
  85613. }
  85614. switch (sizeof(uLong)) {
  85615. case 2: break;
  85616. case 4: flags += 1 << 2; break;
  85617. case 8: flags += 2 << 2; break;
  85618. default: flags += 3 << 2;
  85619. }
  85620. switch (sizeof(voidpf)) {
  85621. case 2: break;
  85622. case 4: flags += 1 << 4; break;
  85623. case 8: flags += 2 << 4; break;
  85624. default: flags += 3 << 4;
  85625. }
  85626. switch (sizeof(z_off_t)) {
  85627. case 2: break;
  85628. case 4: flags += 1 << 6; break;
  85629. case 8: flags += 2 << 6; break;
  85630. default: flags += 3 << 6;
  85631. }
  85632. #ifdef DEBUG
  85633. flags += 1 << 8;
  85634. #endif
  85635. #if defined(ASMV) || defined(ASMINF)
  85636. flags += 1 << 9;
  85637. #endif
  85638. #ifdef ZLIB_WINAPI
  85639. flags += 1 << 10;
  85640. #endif
  85641. #ifdef BUILDFIXED
  85642. flags += 1 << 12;
  85643. #endif
  85644. #ifdef DYNAMIC_CRC_TABLE
  85645. flags += 1 << 13;
  85646. #endif
  85647. #ifdef NO_GZCOMPRESS
  85648. flags += 1L << 16;
  85649. #endif
  85650. #ifdef NO_GZIP
  85651. flags += 1L << 17;
  85652. #endif
  85653. #ifdef PKZIP_BUG_WORKAROUND
  85654. flags += 1L << 20;
  85655. #endif
  85656. #ifdef FASTEST
  85657. flags += 1L << 21;
  85658. #endif
  85659. #ifdef STDC
  85660. # ifdef NO_vsnprintf
  85661. flags += 1L << 25;
  85662. # ifdef HAS_vsprintf_void
  85663. flags += 1L << 26;
  85664. # endif
  85665. # else
  85666. # ifdef HAS_vsnprintf_void
  85667. flags += 1L << 26;
  85668. # endif
  85669. # endif
  85670. #else
  85671. flags += 1L << 24;
  85672. # ifdef NO_snprintf
  85673. flags += 1L << 25;
  85674. # ifdef HAS_sprintf_void
  85675. flags += 1L << 26;
  85676. # endif
  85677. # else
  85678. # ifdef HAS_snprintf_void
  85679. flags += 1L << 26;
  85680. # endif
  85681. # endif
  85682. #endif
  85683. return flags;
  85684. }*/
  85685. #ifdef DEBUG
  85686. # ifndef verbose
  85687. # define verbose 0
  85688. # endif
  85689. int z_verbose = verbose;
  85690. void z_error (const char *m)
  85691. {
  85692. fprintf(stderr, "%s\n", m);
  85693. exit(1);
  85694. }
  85695. #endif
  85696. /* exported to allow conversion of error code to string for compress() and
  85697. * uncompress()
  85698. */
  85699. const char * ZEXPORT zError(int err)
  85700. {
  85701. return ERR_MSG(err);
  85702. }
  85703. #if defined(_WIN32_WCE)
  85704. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  85705. * errno. We define it as a global variable to simplify porting.
  85706. * Its value is always 0 and should not be used.
  85707. */
  85708. int errno = 0;
  85709. #endif
  85710. #ifndef HAVE_MEMCPY
  85711. void zmemcpy(dest, source, len)
  85712. Bytef* dest;
  85713. const Bytef* source;
  85714. uInt len;
  85715. {
  85716. if (len == 0) return;
  85717. do {
  85718. *dest++ = *source++; /* ??? to be unrolled */
  85719. } while (--len != 0);
  85720. }
  85721. int zmemcmp(s1, s2, len)
  85722. const Bytef* s1;
  85723. const Bytef* s2;
  85724. uInt len;
  85725. {
  85726. uInt j;
  85727. for (j = 0; j < len; j++) {
  85728. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  85729. }
  85730. return 0;
  85731. }
  85732. void zmemzero(dest, len)
  85733. Bytef* dest;
  85734. uInt len;
  85735. {
  85736. if (len == 0) return;
  85737. do {
  85738. *dest++ = 0; /* ??? to be unrolled */
  85739. } while (--len != 0);
  85740. }
  85741. #endif
  85742. #ifdef SYS16BIT
  85743. #ifdef __TURBOC__
  85744. /* Turbo C in 16-bit mode */
  85745. # define MY_ZCALLOC
  85746. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  85747. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  85748. * must fix the pointer. Warning: the pointer must be put back to its
  85749. * original form in order to free it, use zcfree().
  85750. */
  85751. #define MAX_PTR 10
  85752. /* 10*64K = 640K */
  85753. local int next_ptr = 0;
  85754. typedef struct ptr_table_s {
  85755. voidpf org_ptr;
  85756. voidpf new_ptr;
  85757. } ptr_table;
  85758. local ptr_table table[MAX_PTR];
  85759. /* This table is used to remember the original form of pointers
  85760. * to large buffers (64K). Such pointers are normalized with a zero offset.
  85761. * Since MSDOS is not a preemptive multitasking OS, this table is not
  85762. * protected from concurrent access. This hack doesn't work anyway on
  85763. * a protected system like OS/2. Use Microsoft C instead.
  85764. */
  85765. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85766. {
  85767. voidpf buf = opaque; /* just to make some compilers happy */
  85768. ulg bsize = (ulg)items*size;
  85769. /* If we allocate less than 65520 bytes, we assume that farmalloc
  85770. * will return a usable pointer which doesn't have to be normalized.
  85771. */
  85772. if (bsize < 65520L) {
  85773. buf = farmalloc(bsize);
  85774. if (*(ush*)&buf != 0) return buf;
  85775. } else {
  85776. buf = farmalloc(bsize + 16L);
  85777. }
  85778. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  85779. table[next_ptr].org_ptr = buf;
  85780. /* Normalize the pointer to seg:0 */
  85781. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  85782. *(ush*)&buf = 0;
  85783. table[next_ptr++].new_ptr = buf;
  85784. return buf;
  85785. }
  85786. void zcfree (voidpf opaque, voidpf ptr)
  85787. {
  85788. int n;
  85789. if (*(ush*)&ptr != 0) { /* object < 64K */
  85790. farfree(ptr);
  85791. return;
  85792. }
  85793. /* Find the original pointer */
  85794. for (n = 0; n < next_ptr; n++) {
  85795. if (ptr != table[n].new_ptr) continue;
  85796. farfree(table[n].org_ptr);
  85797. while (++n < next_ptr) {
  85798. table[n-1] = table[n];
  85799. }
  85800. next_ptr--;
  85801. return;
  85802. }
  85803. ptr = opaque; /* just to make some compilers happy */
  85804. Assert(0, "zcfree: ptr not found");
  85805. }
  85806. #endif /* __TURBOC__ */
  85807. #ifdef M_I86
  85808. /* Microsoft C in 16-bit mode */
  85809. # define MY_ZCALLOC
  85810. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  85811. # define _halloc halloc
  85812. # define _hfree hfree
  85813. #endif
  85814. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85815. {
  85816. if (opaque) opaque = 0; /* to make compiler happy */
  85817. return _halloc((long)items, size);
  85818. }
  85819. void zcfree (voidpf opaque, voidpf ptr)
  85820. {
  85821. if (opaque) opaque = 0; /* to make compiler happy */
  85822. _hfree(ptr);
  85823. }
  85824. #endif /* M_I86 */
  85825. #endif /* SYS16BIT */
  85826. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  85827. #ifndef STDC
  85828. extern voidp malloc OF((uInt size));
  85829. extern voidp calloc OF((uInt items, uInt size));
  85830. extern void free OF((voidpf ptr));
  85831. #endif
  85832. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85833. {
  85834. if (opaque) items += size - size; /* make compiler happy */
  85835. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  85836. (voidpf)calloc(items, size);
  85837. }
  85838. void zcfree (voidpf opaque, voidpf ptr)
  85839. {
  85840. free(ptr);
  85841. if (opaque) return; /* make compiler happy */
  85842. }
  85843. #endif /* MY_ZCALLOC */
  85844. /*** End of inlined file: zutil.c ***/
  85845. #undef Byte
  85846. #else
  85847. #include <zlib.h>
  85848. #endif
  85849. }
  85850. #if JUCE_MSVC
  85851. #pragma warning (pop)
  85852. #endif
  85853. BEGIN_JUCE_NAMESPACE
  85854. // internal helper object that holds the zlib structures so they don't have to be
  85855. // included publicly.
  85856. class GZIPDecompressorInputStream::GZIPDecompressHelper
  85857. {
  85858. public:
  85859. GZIPDecompressHelper (const bool noWrap)
  85860. : finished (true),
  85861. needsDictionary (false),
  85862. error (true),
  85863. streamIsValid (false),
  85864. data (0),
  85865. dataSize (0)
  85866. {
  85867. using namespace zlibNamespace;
  85868. zerostruct (stream);
  85869. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  85870. finished = error = ! streamIsValid;
  85871. }
  85872. ~GZIPDecompressHelper()
  85873. {
  85874. using namespace zlibNamespace;
  85875. if (streamIsValid)
  85876. inflateEnd (&stream);
  85877. }
  85878. bool needsInput() const throw() { return dataSize <= 0; }
  85879. void setInput (uint8* const data_, const int size) throw()
  85880. {
  85881. data = data_;
  85882. dataSize = size;
  85883. }
  85884. int doNextBlock (uint8* const dest, const int destSize)
  85885. {
  85886. using namespace zlibNamespace;
  85887. if (streamIsValid && data != 0 && ! finished)
  85888. {
  85889. stream.next_in = data;
  85890. stream.next_out = dest;
  85891. stream.avail_in = dataSize;
  85892. stream.avail_out = destSize;
  85893. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  85894. {
  85895. case Z_STREAM_END:
  85896. finished = true;
  85897. // deliberate fall-through
  85898. case Z_OK:
  85899. data += dataSize - stream.avail_in;
  85900. dataSize = stream.avail_in;
  85901. return destSize - stream.avail_out;
  85902. case Z_NEED_DICT:
  85903. needsDictionary = true;
  85904. data += dataSize - stream.avail_in;
  85905. dataSize = stream.avail_in;
  85906. break;
  85907. case Z_DATA_ERROR:
  85908. case Z_MEM_ERROR:
  85909. error = true;
  85910. default:
  85911. break;
  85912. }
  85913. }
  85914. return 0;
  85915. }
  85916. bool finished, needsDictionary, error, streamIsValid;
  85917. enum { gzipDecompBufferSize = 32768 };
  85918. private:
  85919. zlibNamespace::z_stream stream;
  85920. uint8* data;
  85921. int dataSize;
  85922. JUCE_DECLARE_NON_COPYABLE (GZIPDecompressHelper);
  85923. };
  85924. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  85925. const bool deleteSourceWhenDestroyed,
  85926. const bool noWrap_,
  85927. const int64 uncompressedStreamLength_)
  85928. : sourceStream (sourceStream_),
  85929. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  85930. uncompressedStreamLength (uncompressedStreamLength_),
  85931. noWrap (noWrap_),
  85932. isEof (false),
  85933. activeBufferSize (0),
  85934. originalSourcePos (sourceStream_->getPosition()),
  85935. currentPos (0),
  85936. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  85937. helper (new GZIPDecompressHelper (noWrap_))
  85938. {
  85939. }
  85940. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream& sourceStream_)
  85941. : sourceStream (&sourceStream_),
  85942. uncompressedStreamLength (-1),
  85943. noWrap (false),
  85944. isEof (false),
  85945. activeBufferSize (0),
  85946. originalSourcePos (sourceStream_.getPosition()),
  85947. currentPos (0),
  85948. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  85949. helper (new GZIPDecompressHelper (false))
  85950. {
  85951. }
  85952. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  85953. {
  85954. }
  85955. int64 GZIPDecompressorInputStream::getTotalLength()
  85956. {
  85957. return uncompressedStreamLength;
  85958. }
  85959. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  85960. {
  85961. if ((howMany > 0) && ! isEof)
  85962. {
  85963. jassert (destBuffer != 0);
  85964. if (destBuffer != 0)
  85965. {
  85966. int numRead = 0;
  85967. uint8* d = static_cast <uint8*> (destBuffer);
  85968. while (! helper->error)
  85969. {
  85970. const int n = helper->doNextBlock (d, howMany);
  85971. currentPos += n;
  85972. if (n == 0)
  85973. {
  85974. if (helper->finished || helper->needsDictionary)
  85975. {
  85976. isEof = true;
  85977. return numRead;
  85978. }
  85979. if (helper->needsInput())
  85980. {
  85981. activeBufferSize = sourceStream->read (buffer, (int) GZIPDecompressHelper::gzipDecompBufferSize);
  85982. if (activeBufferSize > 0)
  85983. {
  85984. helper->setInput (buffer, activeBufferSize);
  85985. }
  85986. else
  85987. {
  85988. isEof = true;
  85989. return numRead;
  85990. }
  85991. }
  85992. }
  85993. else
  85994. {
  85995. numRead += n;
  85996. howMany -= n;
  85997. d += n;
  85998. if (howMany <= 0)
  85999. return numRead;
  86000. }
  86001. }
  86002. }
  86003. }
  86004. return 0;
  86005. }
  86006. bool GZIPDecompressorInputStream::isExhausted()
  86007. {
  86008. return helper->error || isEof;
  86009. }
  86010. int64 GZIPDecompressorInputStream::getPosition()
  86011. {
  86012. return currentPos;
  86013. }
  86014. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  86015. {
  86016. if (newPos < currentPos)
  86017. {
  86018. // to go backwards, reset the stream and start again..
  86019. isEof = false;
  86020. activeBufferSize = 0;
  86021. currentPos = 0;
  86022. helper = new GZIPDecompressHelper (noWrap);
  86023. sourceStream->setPosition (originalSourcePos);
  86024. }
  86025. skipNextBytes (newPos - currentPos);
  86026. return true;
  86027. }
  86028. END_JUCE_NAMESPACE
  86029. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86030. #endif
  86031. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86032. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86033. #if JUCE_USE_FLAC
  86034. #if JUCE_WINDOWS
  86035. #include <windows.h>
  86036. #endif
  86037. namespace FlacNamespace
  86038. {
  86039. #if JUCE_INCLUDE_FLAC_CODE
  86040. #if JUCE_MSVC
  86041. #pragma warning (disable: 4505 181 111)
  86042. #endif
  86043. #define FLAC__NO_DLL 1
  86044. #if ! defined (SIZE_MAX)
  86045. #define SIZE_MAX 0xffffffff
  86046. #endif
  86047. #define __STDC_LIMIT_MACROS 1
  86048. /*** Start of inlined file: all.h ***/
  86049. #ifndef FLAC__ALL_H
  86050. #define FLAC__ALL_H
  86051. /*** Start of inlined file: export.h ***/
  86052. #ifndef FLAC__EXPORT_H
  86053. #define FLAC__EXPORT_H
  86054. /** \file include/FLAC/export.h
  86055. *
  86056. * \brief
  86057. * This module contains #defines and symbols for exporting function
  86058. * calls, and providing version information and compiled-in features.
  86059. *
  86060. * See the \link flac_export export \endlink module.
  86061. */
  86062. /** \defgroup flac_export FLAC/export.h: export symbols
  86063. * \ingroup flac
  86064. *
  86065. * \brief
  86066. * This module contains #defines and symbols for exporting function
  86067. * calls, and providing version information and compiled-in features.
  86068. *
  86069. * If you are compiling with MSVC and will link to the static library
  86070. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86071. * make sure the symbols are exported properly.
  86072. *
  86073. * \{
  86074. */
  86075. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86076. #define FLAC_API
  86077. #else
  86078. #ifdef FLAC_API_EXPORTS
  86079. #define FLAC_API _declspec(dllexport)
  86080. #else
  86081. #define FLAC_API _declspec(dllimport)
  86082. #endif
  86083. #endif
  86084. /** These #defines will mirror the libtool-based library version number, see
  86085. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86086. */
  86087. #define FLAC_API_VERSION_CURRENT 10
  86088. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86089. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86090. #ifdef __cplusplus
  86091. extern "C" {
  86092. #endif
  86093. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86094. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86095. #ifdef __cplusplus
  86096. }
  86097. #endif
  86098. /* \} */
  86099. #endif
  86100. /*** End of inlined file: export.h ***/
  86101. /*** Start of inlined file: assert.h ***/
  86102. #ifndef FLAC__ASSERT_H
  86103. #define FLAC__ASSERT_H
  86104. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86105. #ifdef DEBUG
  86106. #include <assert.h>
  86107. #define FLAC__ASSERT(x) assert(x)
  86108. #define FLAC__ASSERT_DECLARATION(x) x
  86109. #else
  86110. #define FLAC__ASSERT(x)
  86111. #define FLAC__ASSERT_DECLARATION(x)
  86112. #endif
  86113. #endif
  86114. /*** End of inlined file: assert.h ***/
  86115. /*** Start of inlined file: callback.h ***/
  86116. #ifndef FLAC__CALLBACK_H
  86117. #define FLAC__CALLBACK_H
  86118. /*** Start of inlined file: ordinals.h ***/
  86119. #ifndef FLAC__ORDINALS_H
  86120. #define FLAC__ORDINALS_H
  86121. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86122. #include <inttypes.h>
  86123. #endif
  86124. typedef signed char FLAC__int8;
  86125. typedef unsigned char FLAC__uint8;
  86126. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86127. typedef __int16 FLAC__int16;
  86128. typedef __int32 FLAC__int32;
  86129. typedef __int64 FLAC__int64;
  86130. typedef unsigned __int16 FLAC__uint16;
  86131. typedef unsigned __int32 FLAC__uint32;
  86132. typedef unsigned __int64 FLAC__uint64;
  86133. #elif defined(__EMX__)
  86134. typedef short FLAC__int16;
  86135. typedef long FLAC__int32;
  86136. typedef long long FLAC__int64;
  86137. typedef unsigned short FLAC__uint16;
  86138. typedef unsigned long FLAC__uint32;
  86139. typedef unsigned long long FLAC__uint64;
  86140. #else
  86141. typedef int16_t FLAC__int16;
  86142. typedef int32_t FLAC__int32;
  86143. typedef int64_t FLAC__int64;
  86144. typedef uint16_t FLAC__uint16;
  86145. typedef uint32_t FLAC__uint32;
  86146. typedef uint64_t FLAC__uint64;
  86147. #endif
  86148. typedef int FLAC__bool;
  86149. typedef FLAC__uint8 FLAC__byte;
  86150. #ifdef true
  86151. #undef true
  86152. #endif
  86153. #ifdef false
  86154. #undef false
  86155. #endif
  86156. #ifndef __cplusplus
  86157. #define true 1
  86158. #define false 0
  86159. #endif
  86160. #endif
  86161. /*** End of inlined file: ordinals.h ***/
  86162. #include <stdlib.h> /* for size_t */
  86163. /** \file include/FLAC/callback.h
  86164. *
  86165. * \brief
  86166. * This module defines the structures for describing I/O callbacks
  86167. * to the other FLAC interfaces.
  86168. *
  86169. * See the detailed documentation for callbacks in the
  86170. * \link flac_callbacks callbacks \endlink module.
  86171. */
  86172. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86173. * \ingroup flac
  86174. *
  86175. * \brief
  86176. * This module defines the structures for describing I/O callbacks
  86177. * to the other FLAC interfaces.
  86178. *
  86179. * The purpose of the I/O callback functions is to create a common way
  86180. * for the metadata interfaces to handle I/O.
  86181. *
  86182. * Originally the metadata interfaces required filenames as the way of
  86183. * specifying FLAC files to operate on. This is problematic in some
  86184. * environments so there is an additional option to specify a set of
  86185. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86186. *
  86187. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86188. * opaque structure for a data source.
  86189. *
  86190. * The callback function prototypes are similar (but not identical) to the
  86191. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86192. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86193. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86194. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86195. * is required. \warning You generally CANNOT directly use fseek or ftell
  86196. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86197. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86198. * large files. You will have to find an equivalent function (e.g. ftello),
  86199. * or write a wrapper. The same is true for feof() since this is usually
  86200. * implemented as a macro, not as a function whose address can be taken.
  86201. *
  86202. * \{
  86203. */
  86204. #ifdef __cplusplus
  86205. extern "C" {
  86206. #endif
  86207. /** This is the opaque handle type used by the callbacks. Typically
  86208. * this is a \c FILE* or address of a file descriptor.
  86209. */
  86210. typedef void* FLAC__IOHandle;
  86211. /** Signature for the read callback.
  86212. * The signature and semantics match POSIX fread() implementations
  86213. * and can generally be used interchangeably.
  86214. *
  86215. * \param ptr The address of the read buffer.
  86216. * \param size The size of the records to be read.
  86217. * \param nmemb The number of records to be read.
  86218. * \param handle The handle to the data source.
  86219. * \retval size_t
  86220. * The number of records read.
  86221. */
  86222. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86223. /** Signature for the write callback.
  86224. * The signature and semantics match POSIX fwrite() implementations
  86225. * and can generally be used interchangeably.
  86226. *
  86227. * \param ptr The address of the write buffer.
  86228. * \param size The size of the records to be written.
  86229. * \param nmemb The number of records to be written.
  86230. * \param handle The handle to the data source.
  86231. * \retval size_t
  86232. * The number of records written.
  86233. */
  86234. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86235. /** Signature for the seek callback.
  86236. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86237. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86238. * and 32-bits wide.
  86239. *
  86240. * \param handle The handle to the data source.
  86241. * \param offset The new position, relative to \a whence
  86242. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86243. * \retval int
  86244. * \c 0 on success, \c -1 on error.
  86245. */
  86246. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86247. /** Signature for the tell callback.
  86248. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86249. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86250. * and 32-bits wide.
  86251. *
  86252. * \param handle The handle to the data source.
  86253. * \retval FLAC__int64
  86254. * The current position on success, \c -1 on error.
  86255. */
  86256. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86257. /** Signature for the EOF callback.
  86258. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86259. * on many systems, feof() is a macro, so in this case a wrapper function
  86260. * must be provided instead.
  86261. *
  86262. * \param handle The handle to the data source.
  86263. * \retval int
  86264. * \c 0 if not at end of file, nonzero if at end of file.
  86265. */
  86266. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86267. /** Signature for the close callback.
  86268. * The signature and semantics match POSIX fclose() implementations
  86269. * and can generally be used interchangeably.
  86270. *
  86271. * \param handle The handle to the data source.
  86272. * \retval int
  86273. * \c 0 on success, \c EOF on error.
  86274. */
  86275. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86276. /** A structure for holding a set of callbacks.
  86277. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86278. * describe which of the callbacks are required. The ones that are not
  86279. * required may be set to NULL.
  86280. *
  86281. * If the seek requirement for an interface is optional, you can signify that
  86282. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86283. */
  86284. typedef struct {
  86285. FLAC__IOCallback_Read read;
  86286. FLAC__IOCallback_Write write;
  86287. FLAC__IOCallback_Seek seek;
  86288. FLAC__IOCallback_Tell tell;
  86289. FLAC__IOCallback_Eof eof;
  86290. FLAC__IOCallback_Close close;
  86291. } FLAC__IOCallbacks;
  86292. /* \} */
  86293. #ifdef __cplusplus
  86294. }
  86295. #endif
  86296. #endif
  86297. /*** End of inlined file: callback.h ***/
  86298. /*** Start of inlined file: format.h ***/
  86299. #ifndef FLAC__FORMAT_H
  86300. #define FLAC__FORMAT_H
  86301. #ifdef __cplusplus
  86302. extern "C" {
  86303. #endif
  86304. /** \file include/FLAC/format.h
  86305. *
  86306. * \brief
  86307. * This module contains structure definitions for the representation
  86308. * of FLAC format components in memory. These are the basic
  86309. * structures used by the rest of the interfaces.
  86310. *
  86311. * See the detailed documentation in the
  86312. * \link flac_format format \endlink module.
  86313. */
  86314. /** \defgroup flac_format FLAC/format.h: format components
  86315. * \ingroup flac
  86316. *
  86317. * \brief
  86318. * This module contains structure definitions for the representation
  86319. * of FLAC format components in memory. These are the basic
  86320. * structures used by the rest of the interfaces.
  86321. *
  86322. * First, you should be familiar with the
  86323. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86324. * follow directly from the specification. As a user of libFLAC, the
  86325. * interesting parts really are the structures that describe the frame
  86326. * header and metadata blocks.
  86327. *
  86328. * The format structures here are very primitive, designed to store
  86329. * information in an efficient way. Reading information from the
  86330. * structures is easy but creating or modifying them directly is
  86331. * more complex. For the most part, as a user of a library, editing
  86332. * is not necessary; however, for metadata blocks it is, so there are
  86333. * convenience functions provided in the \link flac_metadata metadata
  86334. * module \endlink to simplify the manipulation of metadata blocks.
  86335. *
  86336. * \note
  86337. * It's not the best convention, but symbols ending in _LEN are in bits
  86338. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86339. * global variables because they are usually used when declaring byte
  86340. * arrays and some compilers require compile-time knowledge of array
  86341. * sizes when declared on the stack.
  86342. *
  86343. * \{
  86344. */
  86345. /*
  86346. Most of the values described in this file are defined by the FLAC
  86347. format specification. There is nothing to tune here.
  86348. */
  86349. /** The largest legal metadata type code. */
  86350. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86351. /** The minimum block size, in samples, permitted by the format. */
  86352. #define FLAC__MIN_BLOCK_SIZE (16u)
  86353. /** The maximum block size, in samples, permitted by the format. */
  86354. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86355. /** The maximum block size, in samples, permitted by the FLAC subset for
  86356. * sample rates up to 48kHz. */
  86357. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86358. /** The maximum number of channels permitted by the format. */
  86359. #define FLAC__MAX_CHANNELS (8u)
  86360. /** The minimum sample resolution permitted by the format. */
  86361. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86362. /** The maximum sample resolution permitted by the format. */
  86363. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86364. /** The maximum sample resolution permitted by libFLAC.
  86365. *
  86366. * \warning
  86367. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86368. * the reference encoder/decoder is currently limited to 24 bits because
  86369. * of prevalent 32-bit math, so make sure and use this value when
  86370. * appropriate.
  86371. */
  86372. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86373. /** The maximum sample rate permitted by the format. The value is
  86374. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86375. * as to why.
  86376. */
  86377. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86378. /** The maximum LPC order permitted by the format. */
  86379. #define FLAC__MAX_LPC_ORDER (32u)
  86380. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86381. * up to 48kHz. */
  86382. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86383. /** The minimum quantized linear predictor coefficient precision
  86384. * permitted by the format.
  86385. */
  86386. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86387. /** The maximum quantized linear predictor coefficient precision
  86388. * permitted by the format.
  86389. */
  86390. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86391. /** The maximum order of the fixed predictors permitted by the format. */
  86392. #define FLAC__MAX_FIXED_ORDER (4u)
  86393. /** The maximum Rice partition order permitted by the format. */
  86394. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86395. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86396. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86397. /** The version string of the release, stamped onto the libraries and binaries.
  86398. *
  86399. * \note
  86400. * This does not correspond to the shared library version number, which
  86401. * is used to determine binary compatibility.
  86402. */
  86403. extern FLAC_API const char *FLAC__VERSION_STRING;
  86404. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86405. * This is a NUL-terminated ASCII string; when inserted into the
  86406. * VORBIS_COMMENT the trailing null is stripped.
  86407. */
  86408. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86409. /** The byte string representation of the beginning of a FLAC stream. */
  86410. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86411. /** The 32-bit integer big-endian representation of the beginning of
  86412. * a FLAC stream.
  86413. */
  86414. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86415. /** The length of the FLAC signature in bits. */
  86416. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86417. /** The length of the FLAC signature in bytes. */
  86418. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86419. /*****************************************************************************
  86420. *
  86421. * Subframe structures
  86422. *
  86423. *****************************************************************************/
  86424. /*****************************************************************************/
  86425. /** An enumeration of the available entropy coding methods. */
  86426. typedef enum {
  86427. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86428. /**< Residual is coded by partitioning into contexts, each with it's own
  86429. * 4-bit Rice parameter. */
  86430. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86431. /**< Residual is coded by partitioning into contexts, each with it's own
  86432. * 5-bit Rice parameter. */
  86433. } FLAC__EntropyCodingMethodType;
  86434. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86435. *
  86436. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86437. * give the string equivalent. The contents should not be modified.
  86438. */
  86439. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86440. /** Contents of a Rice partitioned residual
  86441. */
  86442. typedef struct {
  86443. unsigned *parameters;
  86444. /**< The Rice parameters for each context. */
  86445. unsigned *raw_bits;
  86446. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86447. * partitions and zero for unescaped partitions.
  86448. */
  86449. unsigned capacity_by_order;
  86450. /**< The capacity of the \a parameters and \a raw_bits arrays
  86451. * specified as an order, i.e. the number of array elements
  86452. * allocated is 2 ^ \a capacity_by_order.
  86453. */
  86454. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86455. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86456. */
  86457. typedef struct {
  86458. unsigned order;
  86459. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86460. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86461. /**< The context's Rice parameters and/or raw bits. */
  86462. } FLAC__EntropyCodingMethod_PartitionedRice;
  86463. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86464. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86465. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86466. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86467. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86468. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86469. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86470. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86471. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86472. */
  86473. typedef struct {
  86474. FLAC__EntropyCodingMethodType type;
  86475. union {
  86476. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86477. } data;
  86478. } FLAC__EntropyCodingMethod;
  86479. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86480. /*****************************************************************************/
  86481. /** An enumeration of the available subframe types. */
  86482. typedef enum {
  86483. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86484. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86485. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86486. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86487. } FLAC__SubframeType;
  86488. /** Maps a FLAC__SubframeType to a C string.
  86489. *
  86490. * Using a FLAC__SubframeType as the index to this array will
  86491. * give the string equivalent. The contents should not be modified.
  86492. */
  86493. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86494. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86495. */
  86496. typedef struct {
  86497. FLAC__int32 value; /**< The constant signal value. */
  86498. } FLAC__Subframe_Constant;
  86499. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  86500. */
  86501. typedef struct {
  86502. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  86503. } FLAC__Subframe_Verbatim;
  86504. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  86505. */
  86506. typedef struct {
  86507. FLAC__EntropyCodingMethod entropy_coding_method;
  86508. /**< The residual coding method. */
  86509. unsigned order;
  86510. /**< The polynomial order. */
  86511. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  86512. /**< Warmup samples to prime the predictor, length == order. */
  86513. const FLAC__int32 *residual;
  86514. /**< The residual signal, length == (blocksize minus order) samples. */
  86515. } FLAC__Subframe_Fixed;
  86516. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  86517. */
  86518. typedef struct {
  86519. FLAC__EntropyCodingMethod entropy_coding_method;
  86520. /**< The residual coding method. */
  86521. unsigned order;
  86522. /**< The FIR order. */
  86523. unsigned qlp_coeff_precision;
  86524. /**< Quantized FIR filter coefficient precision in bits. */
  86525. int quantization_level;
  86526. /**< The qlp coeff shift needed. */
  86527. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  86528. /**< FIR filter coefficients. */
  86529. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  86530. /**< Warmup samples to prime the predictor, length == order. */
  86531. const FLAC__int32 *residual;
  86532. /**< The residual signal, length == (blocksize minus order) samples. */
  86533. } FLAC__Subframe_LPC;
  86534. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  86535. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  86536. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  86537. */
  86538. typedef struct {
  86539. FLAC__SubframeType type;
  86540. union {
  86541. FLAC__Subframe_Constant constant;
  86542. FLAC__Subframe_Fixed fixed;
  86543. FLAC__Subframe_LPC lpc;
  86544. FLAC__Subframe_Verbatim verbatim;
  86545. } data;
  86546. unsigned wasted_bits;
  86547. } FLAC__Subframe;
  86548. /** == 1 (bit)
  86549. *
  86550. * This used to be a zero-padding bit (hence the name
  86551. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  86552. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  86553. * to mean something else.
  86554. */
  86555. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  86556. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  86557. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  86558. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  86559. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  86560. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  86561. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  86562. /*****************************************************************************/
  86563. /*****************************************************************************
  86564. *
  86565. * Frame structures
  86566. *
  86567. *****************************************************************************/
  86568. /** An enumeration of the available channel assignments. */
  86569. typedef enum {
  86570. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  86571. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  86572. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  86573. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  86574. } FLAC__ChannelAssignment;
  86575. /** Maps a FLAC__ChannelAssignment to a C string.
  86576. *
  86577. * Using a FLAC__ChannelAssignment as the index to this array will
  86578. * give the string equivalent. The contents should not be modified.
  86579. */
  86580. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  86581. /** An enumeration of the possible frame numbering methods. */
  86582. typedef enum {
  86583. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  86584. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  86585. } FLAC__FrameNumberType;
  86586. /** Maps a FLAC__FrameNumberType to a C string.
  86587. *
  86588. * Using a FLAC__FrameNumberType as the index to this array will
  86589. * give the string equivalent. The contents should not be modified.
  86590. */
  86591. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  86592. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  86593. */
  86594. typedef struct {
  86595. unsigned blocksize;
  86596. /**< The number of samples per subframe. */
  86597. unsigned sample_rate;
  86598. /**< The sample rate in Hz. */
  86599. unsigned channels;
  86600. /**< The number of channels (== number of subframes). */
  86601. FLAC__ChannelAssignment channel_assignment;
  86602. /**< The channel assignment for the frame. */
  86603. unsigned bits_per_sample;
  86604. /**< The sample resolution. */
  86605. FLAC__FrameNumberType number_type;
  86606. /**< The numbering scheme used for the frame. As a convenience, the
  86607. * decoder will always convert a frame number to a sample number because
  86608. * the rules are complex. */
  86609. union {
  86610. FLAC__uint32 frame_number;
  86611. FLAC__uint64 sample_number;
  86612. } number;
  86613. /**< The frame number or sample number of first sample in frame;
  86614. * use the \a number_type value to determine which to use. */
  86615. FLAC__uint8 crc;
  86616. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  86617. * of the raw frame header bytes, meaning everything before the CRC byte
  86618. * including the sync code.
  86619. */
  86620. } FLAC__FrameHeader;
  86621. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  86622. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  86623. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  86624. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  86625. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  86626. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  86627. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  86628. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  86629. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  86630. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  86631. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  86632. */
  86633. typedef struct {
  86634. FLAC__uint16 crc;
  86635. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  86636. * 0) of the bytes before the crc, back to and including the frame header
  86637. * sync code.
  86638. */
  86639. } FLAC__FrameFooter;
  86640. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  86641. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  86642. */
  86643. typedef struct {
  86644. FLAC__FrameHeader header;
  86645. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  86646. FLAC__FrameFooter footer;
  86647. } FLAC__Frame;
  86648. /*****************************************************************************/
  86649. /*****************************************************************************
  86650. *
  86651. * Meta-data structures
  86652. *
  86653. *****************************************************************************/
  86654. /** An enumeration of the available metadata block types. */
  86655. typedef enum {
  86656. FLAC__METADATA_TYPE_STREAMINFO = 0,
  86657. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  86658. FLAC__METADATA_TYPE_PADDING = 1,
  86659. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  86660. FLAC__METADATA_TYPE_APPLICATION = 2,
  86661. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  86662. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  86663. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  86664. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  86665. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  86666. FLAC__METADATA_TYPE_CUESHEET = 5,
  86667. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  86668. FLAC__METADATA_TYPE_PICTURE = 6,
  86669. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  86670. FLAC__METADATA_TYPE_UNDEFINED = 7
  86671. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  86672. } FLAC__MetadataType;
  86673. /** Maps a FLAC__MetadataType to a C string.
  86674. *
  86675. * Using a FLAC__MetadataType as the index to this array will
  86676. * give the string equivalent. The contents should not be modified.
  86677. */
  86678. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  86679. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  86680. */
  86681. typedef struct {
  86682. unsigned min_blocksize, max_blocksize;
  86683. unsigned min_framesize, max_framesize;
  86684. unsigned sample_rate;
  86685. unsigned channels;
  86686. unsigned bits_per_sample;
  86687. FLAC__uint64 total_samples;
  86688. FLAC__byte md5sum[16];
  86689. } FLAC__StreamMetadata_StreamInfo;
  86690. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86691. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86692. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86693. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86694. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  86695. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  86696. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  86697. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  86698. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  86699. /** The total stream length of the STREAMINFO block in bytes. */
  86700. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  86701. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  86702. */
  86703. typedef struct {
  86704. int dummy;
  86705. /**< Conceptually this is an empty struct since we don't store the
  86706. * padding bytes. Empty structs are not allowed by some C compilers,
  86707. * hence the dummy.
  86708. */
  86709. } FLAC__StreamMetadata_Padding;
  86710. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  86711. */
  86712. typedef struct {
  86713. FLAC__byte id[4];
  86714. FLAC__byte *data;
  86715. } FLAC__StreamMetadata_Application;
  86716. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  86717. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  86718. */
  86719. typedef struct {
  86720. FLAC__uint64 sample_number;
  86721. /**< The sample number of the target frame. */
  86722. FLAC__uint64 stream_offset;
  86723. /**< The offset, in bytes, of the target frame with respect to
  86724. * beginning of the first frame. */
  86725. unsigned frame_samples;
  86726. /**< The number of samples in the target frame. */
  86727. } FLAC__StreamMetadata_SeekPoint;
  86728. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  86729. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  86730. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  86731. /** The total stream length of a seek point in bytes. */
  86732. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  86733. /** The value used in the \a sample_number field of
  86734. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  86735. * point (== 0xffffffffffffffff).
  86736. */
  86737. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  86738. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  86739. *
  86740. * \note From the format specification:
  86741. * - The seek points must be sorted by ascending sample number.
  86742. * - Each seek point's sample number must be the first sample of the
  86743. * target frame.
  86744. * - Each seek point's sample number must be unique within the table.
  86745. * - Existence of a SEEKTABLE block implies a correct setting of
  86746. * total_samples in the stream_info block.
  86747. * - Behavior is undefined when more than one SEEKTABLE block is
  86748. * present in a stream.
  86749. */
  86750. typedef struct {
  86751. unsigned num_points;
  86752. FLAC__StreamMetadata_SeekPoint *points;
  86753. } FLAC__StreamMetadata_SeekTable;
  86754. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86755. *
  86756. * For convenience, the APIs maintain a trailing NUL character at the end of
  86757. * \a entry which is not counted toward \a length, i.e.
  86758. * \code strlen(entry) == length \endcode
  86759. */
  86760. typedef struct {
  86761. FLAC__uint32 length;
  86762. FLAC__byte *entry;
  86763. } FLAC__StreamMetadata_VorbisComment_Entry;
  86764. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  86765. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86766. */
  86767. typedef struct {
  86768. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  86769. FLAC__uint32 num_comments;
  86770. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  86771. } FLAC__StreamMetadata_VorbisComment;
  86772. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  86773. /** FLAC CUESHEET track index structure. (See the
  86774. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  86775. * the full description of each field.)
  86776. */
  86777. typedef struct {
  86778. FLAC__uint64 offset;
  86779. /**< Offset in samples, relative to the track offset, of the index
  86780. * point.
  86781. */
  86782. FLAC__byte number;
  86783. /**< The index point number. */
  86784. } FLAC__StreamMetadata_CueSheet_Index;
  86785. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  86786. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  86787. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  86788. /** FLAC CUESHEET track structure. (See the
  86789. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  86790. * the full description of each field.)
  86791. */
  86792. typedef struct {
  86793. FLAC__uint64 offset;
  86794. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  86795. FLAC__byte number;
  86796. /**< The track number. */
  86797. char isrc[13];
  86798. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  86799. unsigned type:1;
  86800. /**< The track type: 0 for audio, 1 for non-audio. */
  86801. unsigned pre_emphasis:1;
  86802. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  86803. FLAC__byte num_indices;
  86804. /**< The number of track index points. */
  86805. FLAC__StreamMetadata_CueSheet_Index *indices;
  86806. /**< NULL if num_indices == 0, else pointer to array of index points. */
  86807. } FLAC__StreamMetadata_CueSheet_Track;
  86808. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  86809. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  86810. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  86811. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  86812. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  86813. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  86814. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  86815. /** FLAC CUESHEET structure. (See the
  86816. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  86817. * for the full description of each field.)
  86818. */
  86819. typedef struct {
  86820. char media_catalog_number[129];
  86821. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  86822. * general, the media catalog number may be 0 to 128 bytes long; any
  86823. * unused characters should be right-padded with NUL characters.
  86824. */
  86825. FLAC__uint64 lead_in;
  86826. /**< The number of lead-in samples. */
  86827. FLAC__bool is_cd;
  86828. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  86829. unsigned num_tracks;
  86830. /**< The number of tracks. */
  86831. FLAC__StreamMetadata_CueSheet_Track *tracks;
  86832. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  86833. } FLAC__StreamMetadata_CueSheet;
  86834. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  86835. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  86836. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  86837. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  86838. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  86839. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  86840. typedef enum {
  86841. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  86842. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  86843. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  86844. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  86845. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  86846. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  86847. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  86848. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  86849. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  86850. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  86851. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  86852. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  86853. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  86854. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  86855. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  86856. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  86857. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  86858. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  86859. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  86860. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  86861. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  86862. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  86863. } FLAC__StreamMetadata_Picture_Type;
  86864. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  86865. *
  86866. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  86867. * will give the string equivalent. The contents should not be
  86868. * modified.
  86869. */
  86870. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  86871. /** FLAC PICTURE structure. (See the
  86872. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  86873. * for the full description of each field.)
  86874. */
  86875. typedef struct {
  86876. FLAC__StreamMetadata_Picture_Type type;
  86877. /**< The kind of picture stored. */
  86878. char *mime_type;
  86879. /**< Picture data's MIME type, in ASCII printable characters
  86880. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  86881. * use picture data of MIME type \c image/jpeg or \c image/png. A
  86882. * MIME type of '-->' is also allowed, in which case the picture
  86883. * data should be a complete URL. In file storage, the MIME type is
  86884. * stored as a 32-bit length followed by the ASCII string with no NUL
  86885. * terminator, but is converted to a plain C string in this structure
  86886. * for convenience.
  86887. */
  86888. FLAC__byte *description;
  86889. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  86890. * the description is stored as a 32-bit length followed by the UTF-8
  86891. * string with no NUL terminator, but is converted to a plain C string
  86892. * in this structure for convenience.
  86893. */
  86894. FLAC__uint32 width;
  86895. /**< Picture's width in pixels. */
  86896. FLAC__uint32 height;
  86897. /**< Picture's height in pixels. */
  86898. FLAC__uint32 depth;
  86899. /**< Picture's color depth in bits-per-pixel. */
  86900. FLAC__uint32 colors;
  86901. /**< For indexed palettes (like GIF), picture's number of colors (the
  86902. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  86903. */
  86904. FLAC__uint32 data_length;
  86905. /**< Length of binary picture data in bytes. */
  86906. FLAC__byte *data;
  86907. /**< Binary picture data. */
  86908. } FLAC__StreamMetadata_Picture;
  86909. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  86910. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  86911. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  86912. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  86913. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  86914. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  86915. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  86916. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  86917. /** Structure that is used when a metadata block of unknown type is loaded.
  86918. * The contents are opaque. The structure is used only internally to
  86919. * correctly handle unknown metadata.
  86920. */
  86921. typedef struct {
  86922. FLAC__byte *data;
  86923. } FLAC__StreamMetadata_Unknown;
  86924. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  86925. */
  86926. typedef struct {
  86927. FLAC__MetadataType type;
  86928. /**< The type of the metadata block; used determine which member of the
  86929. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  86930. * then \a data.unknown must be used. */
  86931. FLAC__bool is_last;
  86932. /**< \c true if this metadata block is the last, else \a false */
  86933. unsigned length;
  86934. /**< Length, in bytes, of the block data as it appears in the stream. */
  86935. union {
  86936. FLAC__StreamMetadata_StreamInfo stream_info;
  86937. FLAC__StreamMetadata_Padding padding;
  86938. FLAC__StreamMetadata_Application application;
  86939. FLAC__StreamMetadata_SeekTable seek_table;
  86940. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  86941. FLAC__StreamMetadata_CueSheet cue_sheet;
  86942. FLAC__StreamMetadata_Picture picture;
  86943. FLAC__StreamMetadata_Unknown unknown;
  86944. } data;
  86945. /**< Polymorphic block data; use the \a type value to determine which
  86946. * to use. */
  86947. } FLAC__StreamMetadata;
  86948. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  86949. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  86950. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  86951. /** The total stream length of a metadata block header in bytes. */
  86952. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  86953. /*****************************************************************************/
  86954. /*****************************************************************************
  86955. *
  86956. * Utility functions
  86957. *
  86958. *****************************************************************************/
  86959. /** Tests that a sample rate is valid for FLAC.
  86960. *
  86961. * \param sample_rate The sample rate to test for compliance.
  86962. * \retval FLAC__bool
  86963. * \c true if the given sample rate conforms to the specification, else
  86964. * \c false.
  86965. */
  86966. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  86967. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  86968. * for valid sample rates are slightly more complex since the rate has to
  86969. * be expressible completely in the frame header.
  86970. *
  86971. * \param sample_rate The sample rate to test for compliance.
  86972. * \retval FLAC__bool
  86973. * \c true if the given sample rate conforms to the specification for the
  86974. * subset, else \c false.
  86975. */
  86976. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  86977. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  86978. * comment specification.
  86979. *
  86980. * Vorbis comment names must be composed only of characters from
  86981. * [0x20-0x3C,0x3E-0x7D].
  86982. *
  86983. * \param name A NUL-terminated string to be checked.
  86984. * \assert
  86985. * \code name != NULL \endcode
  86986. * \retval FLAC__bool
  86987. * \c false if entry name is illegal, else \c true.
  86988. */
  86989. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  86990. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  86991. * comment specification.
  86992. *
  86993. * Vorbis comment values must be valid UTF-8 sequences.
  86994. *
  86995. * \param value A string to be checked.
  86996. * \param length A the length of \a value in bytes. May be
  86997. * \c (unsigned)(-1) to indicate that \a value is a plain
  86998. * UTF-8 NUL-terminated string.
  86999. * \assert
  87000. * \code value != NULL \endcode
  87001. * \retval FLAC__bool
  87002. * \c false if entry name is illegal, else \c true.
  87003. */
  87004. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  87005. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  87006. * comment specification.
  87007. *
  87008. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  87009. * 'value' must be legal according to
  87010. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  87011. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  87012. *
  87013. * \param entry An entry to be checked.
  87014. * \param length The length of \a entry in bytes.
  87015. * \assert
  87016. * \code value != NULL \endcode
  87017. * \retval FLAC__bool
  87018. * \c false if entry name is illegal, else \c true.
  87019. */
  87020. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  87021. /** Check a seek table to see if it conforms to the FLAC specification.
  87022. * See the format specification for limits on the contents of the
  87023. * seek table.
  87024. *
  87025. * \param seek_table A pointer to a seek table to be checked.
  87026. * \assert
  87027. * \code seek_table != NULL \endcode
  87028. * \retval FLAC__bool
  87029. * \c false if seek table is illegal, else \c true.
  87030. */
  87031. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87032. /** Sort a seek table's seek points according to the format specification.
  87033. * This includes a "unique-ification" step to remove duplicates, i.e.
  87034. * seek points with identical \a sample_number values. Duplicate seek
  87035. * points are converted into placeholder points and sorted to the end of
  87036. * the table.
  87037. *
  87038. * \param seek_table A pointer to a seek table to be sorted.
  87039. * \assert
  87040. * \code seek_table != NULL \endcode
  87041. * \retval unsigned
  87042. * The number of duplicate seek points converted into placeholders.
  87043. */
  87044. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87045. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87046. * See the format specification for limits on the contents of the
  87047. * cue sheet.
  87048. *
  87049. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87050. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87051. * stringent requirements for a CD-DA (audio) disc.
  87052. * \param violation Address of a pointer to a string. If there is a
  87053. * violation, a pointer to a string explanation of the
  87054. * violation will be returned here. \a violation may be
  87055. * \c NULL if you don't need the returned string. Do not
  87056. * free the returned string; it will always point to static
  87057. * data.
  87058. * \assert
  87059. * \code cue_sheet != NULL \endcode
  87060. * \retval FLAC__bool
  87061. * \c false if cue sheet is illegal, else \c true.
  87062. */
  87063. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87064. /** Check picture data to see if it conforms to the FLAC specification.
  87065. * See the format specification for limits on the contents of the
  87066. * PICTURE block.
  87067. *
  87068. * \param picture A pointer to existing picture data to be checked.
  87069. * \param violation Address of a pointer to a string. If there is a
  87070. * violation, a pointer to a string explanation of the
  87071. * violation will be returned here. \a violation may be
  87072. * \c NULL if you don't need the returned string. Do not
  87073. * free the returned string; it will always point to static
  87074. * data.
  87075. * \assert
  87076. * \code picture != NULL \endcode
  87077. * \retval FLAC__bool
  87078. * \c false if picture data is illegal, else \c true.
  87079. */
  87080. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87081. /* \} */
  87082. #ifdef __cplusplus
  87083. }
  87084. #endif
  87085. #endif
  87086. /*** End of inlined file: format.h ***/
  87087. /*** Start of inlined file: metadata.h ***/
  87088. #ifndef FLAC__METADATA_H
  87089. #define FLAC__METADATA_H
  87090. #include <sys/types.h> /* for off_t */
  87091. /* --------------------------------------------------------------------
  87092. (For an example of how all these routines are used, see the source
  87093. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87094. metaflac in src/metaflac/)
  87095. ------------------------------------------------------------------*/
  87096. /** \file include/FLAC/metadata.h
  87097. *
  87098. * \brief
  87099. * This module provides functions for creating and manipulating FLAC
  87100. * metadata blocks in memory, and three progressively more powerful
  87101. * interfaces for traversing and editing metadata in FLAC files.
  87102. *
  87103. * See the detailed documentation for each interface in the
  87104. * \link flac_metadata metadata \endlink module.
  87105. */
  87106. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87107. * \ingroup flac
  87108. *
  87109. * \brief
  87110. * This module provides functions for creating and manipulating FLAC
  87111. * metadata blocks in memory, and three progressively more powerful
  87112. * interfaces for traversing and editing metadata in native FLAC files.
  87113. * Note that currently only the Chain interface (level 2) supports Ogg
  87114. * FLAC files, and it is read-only i.e. no writing back changed
  87115. * metadata to file.
  87116. *
  87117. * There are three metadata interfaces of increasing complexity:
  87118. *
  87119. * Level 0:
  87120. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87121. * PICTURE blocks.
  87122. *
  87123. * Level 1:
  87124. * Read-write access to all metadata blocks. This level is write-
  87125. * efficient in most cases (more on this below), and uses less memory
  87126. * than level 2.
  87127. *
  87128. * Level 2:
  87129. * Read-write access to all metadata blocks. This level is write-
  87130. * efficient in all cases, but uses more memory since all metadata for
  87131. * the whole file is read into memory and manipulated before writing
  87132. * out again.
  87133. *
  87134. * What do we mean by efficient? Since FLAC metadata appears at the
  87135. * beginning of the file, when writing metadata back to a FLAC file
  87136. * it is possible to grow or shrink the metadata such that the entire
  87137. * file must be rewritten. However, if the size remains the same during
  87138. * changes or PADDING blocks are utilized, only the metadata needs to be
  87139. * overwritten, which is much faster.
  87140. *
  87141. * Efficient means the whole file is rewritten at most one time, and only
  87142. * when necessary. Level 1 is not efficient only in the case that you
  87143. * cause more than one metadata block to grow or shrink beyond what can
  87144. * be accomodated by padding. In this case you should probably use level
  87145. * 2, which allows you to edit all the metadata for a file in memory and
  87146. * write it out all at once.
  87147. *
  87148. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87149. * front of the file.
  87150. *
  87151. * All levels access files via their filenames. In addition, level 2
  87152. * has additional alternative read and write functions that take an I/O
  87153. * handle and callbacks, for situations where access by filename is not
  87154. * possible.
  87155. *
  87156. * In addition to the three interfaces, this module defines functions for
  87157. * creating and manipulating various metadata objects in memory. As we see
  87158. * from the Format module, FLAC metadata blocks in memory are very primitive
  87159. * structures for storing information in an efficient way. Reading
  87160. * information from the structures is easy but creating or modifying them
  87161. * directly is more complex. The metadata object routines here facilitate
  87162. * this by taking care of the consistency and memory management drudgery.
  87163. *
  87164. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87165. * metadata however, you will not probably not need these.
  87166. *
  87167. * From a dependency standpoint, none of the encoders or decoders require
  87168. * the metadata module. This is so that embedded users can strip out the
  87169. * metadata module from libFLAC to reduce the size and complexity.
  87170. */
  87171. #ifdef __cplusplus
  87172. extern "C" {
  87173. #endif
  87174. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87175. * \ingroup flac_metadata
  87176. *
  87177. * \brief
  87178. * The level 0 interface consists of individual routines to read the
  87179. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87180. * only a filename.
  87181. *
  87182. * They try to skip any ID3v2 tag at the head of the file.
  87183. *
  87184. * \{
  87185. */
  87186. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87187. * will try to skip any ID3v2 tag at the head of the file.
  87188. *
  87189. * \param filename The path to the FLAC file to read.
  87190. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87191. * FLAC__StreamMetadata is a simple structure with no
  87192. * memory allocation involved, you pass the address of
  87193. * an existing structure. It need not be initialized.
  87194. * \assert
  87195. * \code filename != NULL \endcode
  87196. * \code streaminfo != NULL \endcode
  87197. * \retval FLAC__bool
  87198. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87199. * \c false if there was a memory allocation error, a file decoder error,
  87200. * or the file contained no STREAMINFO block. (A memory allocation error
  87201. * is possible because this function must set up a file decoder.)
  87202. */
  87203. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87204. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87205. * function will try to skip any ID3v2 tag at the head of the file.
  87206. *
  87207. * \param filename The path to the FLAC file to read.
  87208. * \param tags The address where the returned pointer will be
  87209. * stored. The \a tags object must be deleted by
  87210. * the caller using FLAC__metadata_object_delete().
  87211. * \assert
  87212. * \code filename != NULL \endcode
  87213. * \code tags != NULL \endcode
  87214. * \retval FLAC__bool
  87215. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87216. * and \a *tags will be set to the address of the metadata structure.
  87217. * Returns \c false if there was a memory allocation error, a file
  87218. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87219. * \a *tags will be set to \c NULL.
  87220. */
  87221. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87222. /** Read the CUESHEET metadata block of the given FLAC file. This
  87223. * function will try to skip any ID3v2 tag at the head of the file.
  87224. *
  87225. * \param filename The path to the FLAC file to read.
  87226. * \param cuesheet The address where the returned pointer will be
  87227. * stored. The \a cuesheet object must be deleted by
  87228. * the caller using FLAC__metadata_object_delete().
  87229. * \assert
  87230. * \code filename != NULL \endcode
  87231. * \code cuesheet != NULL \endcode
  87232. * \retval FLAC__bool
  87233. * \c true if a valid CUESHEET block was read from \a filename,
  87234. * and \a *cuesheet will be set to the address of the metadata
  87235. * structure. Returns \c false if there was a memory allocation
  87236. * error, a file decoder error, or the file contained no CUESHEET
  87237. * block, and \a *cuesheet will be set to \c NULL.
  87238. */
  87239. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87240. /** Read a PICTURE metadata block of the given FLAC file. This
  87241. * function will try to skip any ID3v2 tag at the head of the file.
  87242. * Since there can be more than one PICTURE block in a file, this
  87243. * function takes a number of parameters that act as constraints to
  87244. * the search. The PICTURE block with the largest area matching all
  87245. * the constraints will be returned, or \a *picture will be set to
  87246. * \c NULL if there was no such block.
  87247. *
  87248. * \param filename The path to the FLAC file to read.
  87249. * \param picture The address where the returned pointer will be
  87250. * stored. The \a picture object must be deleted by
  87251. * the caller using FLAC__metadata_object_delete().
  87252. * \param type The desired picture type. Use \c -1 to mean
  87253. * "any type".
  87254. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87255. * string will be matched exactly. Use \c NULL to
  87256. * mean "any MIME type".
  87257. * \param description The desired description. The string will be
  87258. * matched exactly. Use \c NULL to mean "any
  87259. * description".
  87260. * \param max_width The maximum width in pixels desired. Use
  87261. * \c (unsigned)(-1) to mean "any width".
  87262. * \param max_height The maximum height in pixels desired. Use
  87263. * \c (unsigned)(-1) to mean "any height".
  87264. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87265. * Use \c (unsigned)(-1) to mean "any depth".
  87266. * \param max_colors The maximum number of colors desired. Use
  87267. * \c (unsigned)(-1) to mean "any number of colors".
  87268. * \assert
  87269. * \code filename != NULL \endcode
  87270. * \code picture != NULL \endcode
  87271. * \retval FLAC__bool
  87272. * \c true if a valid PICTURE block was read from \a filename,
  87273. * and \a *picture will be set to the address of the metadata
  87274. * structure. Returns \c false if there was a memory allocation
  87275. * error, a file decoder error, or the file contained no PICTURE
  87276. * block, and \a *picture will be set to \c NULL.
  87277. */
  87278. 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);
  87279. /* \} */
  87280. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87281. * \ingroup flac_metadata
  87282. *
  87283. * \brief
  87284. * The level 1 interface provides read-write access to FLAC file metadata and
  87285. * operates directly on the FLAC file.
  87286. *
  87287. * The general usage of this interface is:
  87288. *
  87289. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87290. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87291. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87292. * see if the file is writable, or only read access is allowed.
  87293. * - Use FLAC__metadata_simple_iterator_next() and
  87294. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87295. * This is does not read the actual blocks themselves.
  87296. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87297. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87298. * forward from the front of the file.
  87299. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87300. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87301. * the current iterator position. The returned object is yours to modify
  87302. * and free.
  87303. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87304. * back. You must have write permission to the original file. Make sure to
  87305. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87306. * below.
  87307. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87308. * Use the object creation functions from
  87309. * \link flac_metadata_object here \endlink to generate new objects.
  87310. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87311. * currently referred to by the iterator, or replace it with padding.
  87312. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87313. * finished.
  87314. *
  87315. * \note
  87316. * The FLAC file remains open the whole time between
  87317. * FLAC__metadata_simple_iterator_init() and
  87318. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87319. * the file during this time.
  87320. *
  87321. * \note
  87322. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87323. * FLAC__StreamMetadata objects. These are managed automatically.
  87324. *
  87325. * \note
  87326. * If any of the modification functions
  87327. * (FLAC__metadata_simple_iterator_set_block(),
  87328. * FLAC__metadata_simple_iterator_delete_block(),
  87329. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87330. * you should delete the iterator as it may no longer be valid.
  87331. *
  87332. * \{
  87333. */
  87334. struct FLAC__Metadata_SimpleIterator;
  87335. /** The opaque structure definition for the level 1 iterator type.
  87336. * See the
  87337. * \link flac_metadata_level1 metadata level 1 module \endlink
  87338. * for a detailed description.
  87339. */
  87340. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87341. /** Status type for FLAC__Metadata_SimpleIterator.
  87342. *
  87343. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87344. */
  87345. typedef enum {
  87346. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87347. /**< The iterator is in the normal OK state */
  87348. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87349. /**< The data passed into a function violated the function's usage criteria */
  87350. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87351. /**< The iterator could not open the target file */
  87352. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87353. /**< The iterator could not find the FLAC signature at the start of the file */
  87354. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87355. /**< The iterator tried to write to a file that was not writable */
  87356. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87357. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87358. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87359. /**< The iterator encountered an error while reading the FLAC file */
  87360. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87361. /**< The iterator encountered an error while seeking in the FLAC file */
  87362. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87363. /**< The iterator encountered an error while writing the FLAC file */
  87364. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87365. /**< The iterator encountered an error renaming the FLAC file */
  87366. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87367. /**< The iterator encountered an error removing the temporary file */
  87368. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87369. /**< Memory allocation failed */
  87370. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87371. /**< The caller violated an assertion or an unexpected error occurred */
  87372. } FLAC__Metadata_SimpleIteratorStatus;
  87373. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87374. *
  87375. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87376. * will give the string equivalent. The contents should not be modified.
  87377. */
  87378. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87379. /** Create a new iterator instance.
  87380. *
  87381. * \retval FLAC__Metadata_SimpleIterator*
  87382. * \c NULL if there was an error allocating memory, else the new instance.
  87383. */
  87384. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87385. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87386. *
  87387. * \param iterator A pointer to an existing iterator.
  87388. * \assert
  87389. * \code iterator != NULL \endcode
  87390. */
  87391. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87392. /** Get the current status of the iterator. Call this after a function
  87393. * returns \c false to get the reason for the error. Also resets the status
  87394. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87395. *
  87396. * \param iterator A pointer to an existing iterator.
  87397. * \assert
  87398. * \code iterator != NULL \endcode
  87399. * \retval FLAC__Metadata_SimpleIteratorStatus
  87400. * The current status of the iterator.
  87401. */
  87402. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87403. /** Initialize the iterator to point to the first metadata block in the
  87404. * given FLAC file.
  87405. *
  87406. * \param iterator A pointer to an existing iterator.
  87407. * \param filename The path to the FLAC file.
  87408. * \param read_only If \c true, the FLAC file will be opened
  87409. * in read-only mode; if \c false, the FLAC
  87410. * file will be opened for edit even if no
  87411. * edits are performed.
  87412. * \param preserve_file_stats If \c true, the owner and modification
  87413. * time will be preserved even if the FLAC
  87414. * file is written to.
  87415. * \assert
  87416. * \code iterator != NULL \endcode
  87417. * \code filename != NULL \endcode
  87418. * \retval FLAC__bool
  87419. * \c false if a memory allocation error occurs, the file can't be
  87420. * opened, or another error occurs, else \c true.
  87421. */
  87422. 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);
  87423. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87424. * FLAC__metadata_simple_iterator_set_block() and
  87425. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87426. *
  87427. * \param iterator A pointer to an existing iterator.
  87428. * \assert
  87429. * \code iterator != NULL \endcode
  87430. * \retval FLAC__bool
  87431. * See above.
  87432. */
  87433. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87434. /** Moves the iterator forward one metadata block, returning \c false if
  87435. * already at the end.
  87436. *
  87437. * \param iterator A pointer to an existing initialized iterator.
  87438. * \assert
  87439. * \code iterator != NULL \endcode
  87440. * \a iterator has been successfully initialized with
  87441. * FLAC__metadata_simple_iterator_init()
  87442. * \retval FLAC__bool
  87443. * \c false if already at the last metadata block of the chain, else
  87444. * \c true.
  87445. */
  87446. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87447. /** Moves the iterator backward one metadata block, returning \c false if
  87448. * already at the beginning.
  87449. *
  87450. * \param iterator A pointer to an existing initialized iterator.
  87451. * \assert
  87452. * \code iterator != NULL \endcode
  87453. * \a iterator has been successfully initialized with
  87454. * FLAC__metadata_simple_iterator_init()
  87455. * \retval FLAC__bool
  87456. * \c false if already at the first metadata block of the chain, else
  87457. * \c true.
  87458. */
  87459. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87460. /** Returns a flag telling if the current metadata block is the last.
  87461. *
  87462. * \param iterator A pointer to an existing initialized iterator.
  87463. * \assert
  87464. * \code iterator != NULL \endcode
  87465. * \a iterator has been successfully initialized with
  87466. * FLAC__metadata_simple_iterator_init()
  87467. * \retval FLAC__bool
  87468. * \c true if the current metadata block is the last in the file,
  87469. * else \c false.
  87470. */
  87471. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87472. /** Get the offset of the metadata block at the current position. This
  87473. * avoids reading the actual block data which can save time for large
  87474. * blocks.
  87475. *
  87476. * \param iterator A pointer to an existing initialized iterator.
  87477. * \assert
  87478. * \code iterator != NULL \endcode
  87479. * \a iterator has been successfully initialized with
  87480. * FLAC__metadata_simple_iterator_init()
  87481. * \retval off_t
  87482. * The offset of the metadata block at the current iterator position.
  87483. * This is the byte offset relative to the beginning of the file of
  87484. * the current metadata block's header.
  87485. */
  87486. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87487. /** Get the type of the metadata block at the current position. This
  87488. * avoids reading the actual block data which can save time for large
  87489. * blocks.
  87490. *
  87491. * \param iterator A pointer to an existing initialized iterator.
  87492. * \assert
  87493. * \code iterator != NULL \endcode
  87494. * \a iterator has been successfully initialized with
  87495. * FLAC__metadata_simple_iterator_init()
  87496. * \retval FLAC__MetadataType
  87497. * The type of the metadata block at the current iterator position.
  87498. */
  87499. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  87500. /** Get the length of the metadata block at the current position. This
  87501. * avoids reading the actual block data which can save time for large
  87502. * blocks.
  87503. *
  87504. * \param iterator A pointer to an existing initialized iterator.
  87505. * \assert
  87506. * \code iterator != NULL \endcode
  87507. * \a iterator has been successfully initialized with
  87508. * FLAC__metadata_simple_iterator_init()
  87509. * \retval unsigned
  87510. * The length of the metadata block at the current iterator position.
  87511. * The is same length as that in the
  87512. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  87513. * i.e. the length of the metadata body that follows the header.
  87514. */
  87515. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  87516. /** Get the application ID of the \c APPLICATION block at the current
  87517. * position. This avoids reading the actual block data which can save
  87518. * time for large blocks.
  87519. *
  87520. * \param iterator A pointer to an existing initialized iterator.
  87521. * \param id A pointer to a buffer of at least \c 4 bytes where
  87522. * the ID will be stored.
  87523. * \assert
  87524. * \code iterator != NULL \endcode
  87525. * \code id != NULL \endcode
  87526. * \a iterator has been successfully initialized with
  87527. * FLAC__metadata_simple_iterator_init()
  87528. * \retval FLAC__bool
  87529. * \c true if the ID was successfully read, else \c false, in which
  87530. * case you should check FLAC__metadata_simple_iterator_status() to
  87531. * find out why. If the status is
  87532. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  87533. * current metadata block is not an \c APPLICATION block. Otherwise
  87534. * if the status is
  87535. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  87536. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  87537. * occurred and the iterator can no longer be used.
  87538. */
  87539. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  87540. /** Get the metadata block at the current position. You can modify the
  87541. * block but must use FLAC__metadata_simple_iterator_set_block() to
  87542. * write it back to the FLAC file.
  87543. *
  87544. * You must call FLAC__metadata_object_delete() on the returned object
  87545. * when you are finished with it.
  87546. *
  87547. * \param iterator A pointer to an existing initialized iterator.
  87548. * \assert
  87549. * \code iterator != NULL \endcode
  87550. * \a iterator has been successfully initialized with
  87551. * FLAC__metadata_simple_iterator_init()
  87552. * \retval FLAC__StreamMetadata*
  87553. * The current metadata block, or \c NULL if there was a memory
  87554. * allocation error.
  87555. */
  87556. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  87557. /** Write a block back to the FLAC file. This function tries to be
  87558. * as efficient as possible; how the block is actually written is
  87559. * shown by the following:
  87560. *
  87561. * Existing block is a STREAMINFO block and the new block is a
  87562. * STREAMINFO block: the new block is written in place. Make sure
  87563. * you know what you're doing when changing the values of a
  87564. * STREAMINFO block.
  87565. *
  87566. * Existing block is a STREAMINFO block and the new block is a
  87567. * not a STREAMINFO block: this is an error since the first block
  87568. * must be a STREAMINFO block. Returns \c false without altering the
  87569. * file.
  87570. *
  87571. * Existing block is not a STREAMINFO block and the new block is a
  87572. * STREAMINFO block: this is an error since there may be only one
  87573. * STREAMINFO block. Returns \c false without altering the file.
  87574. *
  87575. * Existing block and new block are the same length: the existing
  87576. * block will be replaced by the new block, written in place.
  87577. *
  87578. * Existing block is longer than new block: if use_padding is \c true,
  87579. * the existing block will be overwritten in place with the new
  87580. * block followed by a PADDING block, if possible, to make the total
  87581. * size the same as the existing block. Remember that a padding
  87582. * block requires at least four bytes so if the difference in size
  87583. * between the new block and existing block is less than that, the
  87584. * entire file will have to be rewritten, using the new block's
  87585. * exact size. If use_padding is \c false, the entire file will be
  87586. * rewritten, replacing the existing block by the new block.
  87587. *
  87588. * Existing block is shorter than new block: if use_padding is \c true,
  87589. * the function will try and expand the new block into the following
  87590. * PADDING block, if it exists and doing so won't shrink the PADDING
  87591. * block to less than 4 bytes. If there is no following PADDING
  87592. * block, or it will shrink to less than 4 bytes, or use_padding is
  87593. * \c false, the entire file is rewritten, replacing the existing block
  87594. * with the new block. Note that in this case any following PADDING
  87595. * block is preserved as is.
  87596. *
  87597. * After writing the block, the iterator will remain in the same
  87598. * place, i.e. pointing to the new block.
  87599. *
  87600. * \param iterator A pointer to an existing initialized iterator.
  87601. * \param block The block to set.
  87602. * \param use_padding See above.
  87603. * \assert
  87604. * \code iterator != NULL \endcode
  87605. * \a iterator has been successfully initialized with
  87606. * FLAC__metadata_simple_iterator_init()
  87607. * \code block != NULL \endcode
  87608. * \retval FLAC__bool
  87609. * \c true if successful, else \c false.
  87610. */
  87611. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87612. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  87613. * except that instead of writing over an existing block, it appends
  87614. * a block after the existing block. \a use_padding is again used to
  87615. * tell the function to try an expand into following padding in an
  87616. * attempt to avoid rewriting the entire file.
  87617. *
  87618. * This function will fail and return \c false if given a STREAMINFO
  87619. * block.
  87620. *
  87621. * After writing the block, the iterator will be pointing to the
  87622. * new block.
  87623. *
  87624. * \param iterator A pointer to an existing initialized iterator.
  87625. * \param block The block to set.
  87626. * \param use_padding See above.
  87627. * \assert
  87628. * \code iterator != NULL \endcode
  87629. * \a iterator has been successfully initialized with
  87630. * FLAC__metadata_simple_iterator_init()
  87631. * \code block != NULL \endcode
  87632. * \retval FLAC__bool
  87633. * \c true if successful, else \c false.
  87634. */
  87635. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87636. /** Deletes the block at the current position. This will cause the
  87637. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  87638. * in which case the block will be replaced by an equal-sized PADDING
  87639. * block. The iterator will be left pointing to the block before the
  87640. * one just deleted.
  87641. *
  87642. * You may not delete the STREAMINFO block.
  87643. *
  87644. * \param iterator A pointer to an existing initialized iterator.
  87645. * \param use_padding See above.
  87646. * \assert
  87647. * \code iterator != NULL \endcode
  87648. * \a iterator has been successfully initialized with
  87649. * FLAC__metadata_simple_iterator_init()
  87650. * \retval FLAC__bool
  87651. * \c true if successful, else \c false.
  87652. */
  87653. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  87654. /* \} */
  87655. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  87656. * \ingroup flac_metadata
  87657. *
  87658. * \brief
  87659. * The level 2 interface provides read-write access to FLAC file metadata;
  87660. * all metadata is read into memory, operated on in memory, and then written
  87661. * to file, which is more efficient than level 1 when editing multiple blocks.
  87662. *
  87663. * Currently Ogg FLAC is supported for read only, via
  87664. * FLAC__metadata_chain_read_ogg() but a subsequent
  87665. * FLAC__metadata_chain_write() will fail.
  87666. *
  87667. * The general usage of this interface is:
  87668. *
  87669. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  87670. * linked list of FLAC metadata blocks.
  87671. * - Read all metadata into the the chain from a FLAC file using
  87672. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  87673. * check the status.
  87674. * - Optionally, consolidate the padding using
  87675. * FLAC__metadata_chain_merge_padding() or
  87676. * FLAC__metadata_chain_sort_padding().
  87677. * - Create a new iterator using FLAC__metadata_iterator_new()
  87678. * - Initialize the iterator to point to the first element in the chain
  87679. * using FLAC__metadata_iterator_init()
  87680. * - Traverse the chain using FLAC__metadata_iterator_next and
  87681. * FLAC__metadata_iterator_prev().
  87682. * - Get a block for reading or modification using
  87683. * FLAC__metadata_iterator_get_block(). The pointer to the object
  87684. * inside the chain is returned, so the block is yours to modify.
  87685. * Changes will be reflected in the FLAC file when you write the
  87686. * chain. You can also add and delete blocks (see functions below).
  87687. * - When done, write out the chain using FLAC__metadata_chain_write().
  87688. * Make sure to read the whole comment to the function below.
  87689. * - Delete the chain using FLAC__metadata_chain_delete().
  87690. *
  87691. * \note
  87692. * Even though the FLAC file is not open while the chain is being
  87693. * manipulated, you must not alter the file externally during
  87694. * this time. The chain assumes the FLAC file will not change
  87695. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  87696. * and FLAC__metadata_chain_write().
  87697. *
  87698. * \note
  87699. * Do not modify the is_last, length, or type fields of returned
  87700. * FLAC__StreamMetadata objects. These are managed automatically.
  87701. *
  87702. * \note
  87703. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  87704. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  87705. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  87706. * become owned by the chain and they will be deleted when the chain is
  87707. * deleted.
  87708. *
  87709. * \{
  87710. */
  87711. struct FLAC__Metadata_Chain;
  87712. /** The opaque structure definition for the level 2 chain type.
  87713. */
  87714. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  87715. struct FLAC__Metadata_Iterator;
  87716. /** The opaque structure definition for the level 2 iterator type.
  87717. */
  87718. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  87719. typedef enum {
  87720. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  87721. /**< The chain is in the normal OK state */
  87722. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  87723. /**< The data passed into a function violated the function's usage criteria */
  87724. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  87725. /**< The chain could not open the target file */
  87726. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  87727. /**< The chain could not find the FLAC signature at the start of the file */
  87728. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  87729. /**< The chain tried to write to a file that was not writable */
  87730. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  87731. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  87732. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  87733. /**< The chain encountered an error while reading the FLAC file */
  87734. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  87735. /**< The chain encountered an error while seeking in the FLAC file */
  87736. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  87737. /**< The chain encountered an error while writing the FLAC file */
  87738. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  87739. /**< The chain encountered an error renaming the FLAC file */
  87740. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  87741. /**< The chain encountered an error removing the temporary file */
  87742. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  87743. /**< Memory allocation failed */
  87744. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  87745. /**< The caller violated an assertion or an unexpected error occurred */
  87746. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  87747. /**< One or more of the required callbacks was NULL */
  87748. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  87749. /**< FLAC__metadata_chain_write() was called on a chain read by
  87750. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87751. * or
  87752. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  87753. * was called on a chain read by
  87754. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87755. * Matching read/write methods must always be used. */
  87756. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  87757. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  87758. * chain write requires a tempfile; use
  87759. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  87760. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  87761. * called when the chain write does not require a tempfile; use
  87762. * FLAC__metadata_chain_write_with_callbacks() instead.
  87763. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  87764. * before writing via callbacks. */
  87765. } FLAC__Metadata_ChainStatus;
  87766. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  87767. *
  87768. * Using a FLAC__Metadata_ChainStatus as the index to this array
  87769. * will give the string equivalent. The contents should not be modified.
  87770. */
  87771. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  87772. /*********** FLAC__Metadata_Chain ***********/
  87773. /** Create a new chain instance.
  87774. *
  87775. * \retval FLAC__Metadata_Chain*
  87776. * \c NULL if there was an error allocating memory, else the new instance.
  87777. */
  87778. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  87779. /** Free a chain instance. Deletes the object pointed to by \a chain.
  87780. *
  87781. * \param chain A pointer to an existing chain.
  87782. * \assert
  87783. * \code chain != NULL \endcode
  87784. */
  87785. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  87786. /** Get the current status of the chain. Call this after a function
  87787. * returns \c false to get the reason for the error. Also resets the
  87788. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  87789. *
  87790. * \param chain A pointer to an existing chain.
  87791. * \assert
  87792. * \code chain != NULL \endcode
  87793. * \retval FLAC__Metadata_ChainStatus
  87794. * The current status of the chain.
  87795. */
  87796. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  87797. /** Read all metadata from a FLAC file into the chain.
  87798. *
  87799. * \param chain A pointer to an existing chain.
  87800. * \param filename The path to the FLAC file to read.
  87801. * \assert
  87802. * \code chain != NULL \endcode
  87803. * \code filename != NULL \endcode
  87804. * \retval FLAC__bool
  87805. * \c true if a valid list of metadata blocks was read from
  87806. * \a filename, else \c false. On failure, check the status with
  87807. * FLAC__metadata_chain_status().
  87808. */
  87809. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  87810. /** Read all metadata from an Ogg FLAC file into the chain.
  87811. *
  87812. * \note Ogg FLAC metadata data writing is not supported yet and
  87813. * FLAC__metadata_chain_write() will fail.
  87814. *
  87815. * \param chain A pointer to an existing chain.
  87816. * \param filename The path to the Ogg FLAC file to read.
  87817. * \assert
  87818. * \code chain != NULL \endcode
  87819. * \code filename != NULL \endcode
  87820. * \retval FLAC__bool
  87821. * \c true if a valid list of metadata blocks was read from
  87822. * \a filename, else \c false. On failure, check the status with
  87823. * FLAC__metadata_chain_status().
  87824. */
  87825. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  87826. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  87827. *
  87828. * The \a handle need only be open for reading, but must be seekable.
  87829. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87830. * for Windows).
  87831. *
  87832. * \param chain A pointer to an existing chain.
  87833. * \param handle The I/O handle of the FLAC stream to read. The
  87834. * handle will NOT be closed after the metadata is read;
  87835. * that is the duty of the caller.
  87836. * \param callbacks
  87837. * A set of callbacks to use for I/O. The mandatory
  87838. * callbacks are \a read, \a seek, and \a tell.
  87839. * \assert
  87840. * \code chain != NULL \endcode
  87841. * \retval FLAC__bool
  87842. * \c true if a valid list of metadata blocks was read from
  87843. * \a handle, else \c false. On failure, check the status with
  87844. * FLAC__metadata_chain_status().
  87845. */
  87846. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87847. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  87848. *
  87849. * The \a handle need only be open for reading, but must be seekable.
  87850. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87851. * for Windows).
  87852. *
  87853. * \note Ogg FLAC metadata data writing is not supported yet and
  87854. * FLAC__metadata_chain_write() will fail.
  87855. *
  87856. * \param chain A pointer to an existing chain.
  87857. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  87858. * handle will NOT be closed after the metadata is read;
  87859. * that is the duty of the caller.
  87860. * \param callbacks
  87861. * A set of callbacks to use for I/O. The mandatory
  87862. * callbacks are \a read, \a seek, and \a tell.
  87863. * \assert
  87864. * \code chain != NULL \endcode
  87865. * \retval FLAC__bool
  87866. * \c true if a valid list of metadata blocks was read from
  87867. * \a handle, else \c false. On failure, check the status with
  87868. * FLAC__metadata_chain_status().
  87869. */
  87870. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87871. /** Checks if writing the given chain would require the use of a
  87872. * temporary file, or if it could be written in place.
  87873. *
  87874. * Under certain conditions, padding can be utilized so that writing
  87875. * edited metadata back to the FLAC file does not require rewriting the
  87876. * entire file. If rewriting is required, then a temporary workfile is
  87877. * required. When writing metadata using callbacks, you must check
  87878. * this function to know whether to call
  87879. * FLAC__metadata_chain_write_with_callbacks() or
  87880. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  87881. * writing with FLAC__metadata_chain_write(), the temporary file is
  87882. * handled internally.
  87883. *
  87884. * \param chain A pointer to an existing chain.
  87885. * \param use_padding
  87886. * Whether or not padding will be allowed to be used
  87887. * during the write. The value of \a use_padding given
  87888. * here must match the value later passed to
  87889. * FLAC__metadata_chain_write_with_callbacks() or
  87890. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  87891. * \assert
  87892. * \code chain != NULL \endcode
  87893. * \retval FLAC__bool
  87894. * \c true if writing the current chain would require a tempfile, or
  87895. * \c false if metadata can be written in place.
  87896. */
  87897. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  87898. /** Write all metadata out to the FLAC file. This function tries to be as
  87899. * efficient as possible; how the metadata is actually written is shown by
  87900. * the following:
  87901. *
  87902. * If the current chain is the same size as the existing metadata, the new
  87903. * data is written in place.
  87904. *
  87905. * If the current chain is longer than the existing metadata, and
  87906. * \a use_padding is \c true, and the last block is a PADDING block of
  87907. * sufficient length, the function will truncate the final padding block
  87908. * so that the overall size of the metadata is the same as the existing
  87909. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  87910. * the above conditions are met, the entire FLAC file must be rewritten.
  87911. * If you want to use padding this way it is a good idea to call
  87912. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  87913. * amount of padding to work with, unless you need to preserve ordering
  87914. * of the PADDING blocks for some reason.
  87915. *
  87916. * If the current chain is shorter than the existing metadata, and
  87917. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  87918. * is extended to make the overall size the same as the existing data. If
  87919. * \a use_padding is \c true and the last block is not a PADDING block, a new
  87920. * PADDING block is added to the end of the new data to make it the same
  87921. * size as the existing data (if possible, see the note to
  87922. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  87923. * and the new data is written in place. If none of the above apply or
  87924. * \a use_padding is \c false, the entire FLAC file is rewritten.
  87925. *
  87926. * If \a preserve_file_stats is \c true, the owner and modification time will
  87927. * be preserved even if the FLAC file is written.
  87928. *
  87929. * For this write function to be used, the chain must have been read with
  87930. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  87931. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  87932. *
  87933. * \param chain A pointer to an existing chain.
  87934. * \param use_padding See above.
  87935. * \param preserve_file_stats See above.
  87936. * \assert
  87937. * \code chain != NULL \endcode
  87938. * \retval FLAC__bool
  87939. * \c true if the write succeeded, else \c false. On failure,
  87940. * check the status with FLAC__metadata_chain_status().
  87941. */
  87942. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  87943. /** Write all metadata out to a FLAC stream via callbacks.
  87944. *
  87945. * (See FLAC__metadata_chain_write() for the details on how padding is
  87946. * used to write metadata in place if possible.)
  87947. *
  87948. * The \a handle must be open for updating and be seekable. The
  87949. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  87950. * for Windows).
  87951. *
  87952. * For this write function to be used, the chain must have been read with
  87953. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87954. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87955. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87956. * \c false.
  87957. *
  87958. * \param chain A pointer to an existing chain.
  87959. * \param use_padding See FLAC__metadata_chain_write()
  87960. * \param handle The I/O handle of the FLAC stream to write. The
  87961. * handle will NOT be closed after the metadata is
  87962. * written; that is the duty of the caller.
  87963. * \param callbacks A set of callbacks to use for I/O. The mandatory
  87964. * callbacks are \a write and \a seek.
  87965. * \assert
  87966. * \code chain != NULL \endcode
  87967. * \retval FLAC__bool
  87968. * \c true if the write succeeded, else \c false. On failure,
  87969. * check the status with FLAC__metadata_chain_status().
  87970. */
  87971. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87972. /** Write all metadata out to a FLAC stream via callbacks.
  87973. *
  87974. * (See FLAC__metadata_chain_write() for the details on how padding is
  87975. * used to write metadata in place if possible.)
  87976. *
  87977. * This version of the write-with-callbacks function must be used when
  87978. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  87979. * this function, you must supply an I/O handle corresponding to the
  87980. * FLAC file to edit, and a temporary handle to which the new FLAC
  87981. * file will be written. It is the caller's job to move this temporary
  87982. * FLAC file on top of the original FLAC file to complete the metadata
  87983. * edit.
  87984. *
  87985. * The \a handle must be open for reading and be seekable. The
  87986. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87987. * for Windows).
  87988. *
  87989. * The \a temp_handle must be open for writing. The
  87990. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  87991. * for Windows). It should be an empty stream, or at least positioned
  87992. * at the start-of-file (in which case it is the caller's duty to
  87993. * truncate it on return).
  87994. *
  87995. * For this write function to be used, the chain must have been read with
  87996. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87997. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87998. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87999. * \c true.
  88000. *
  88001. * \param chain A pointer to an existing chain.
  88002. * \param use_padding See FLAC__metadata_chain_write()
  88003. * \param handle The I/O handle of the original FLAC stream to read.
  88004. * The handle will NOT be closed after the metadata is
  88005. * written; that is the duty of the caller.
  88006. * \param callbacks A set of callbacks to use for I/O on \a handle.
  88007. * The mandatory callbacks are \a read, \a seek, and
  88008. * \a eof.
  88009. * \param temp_handle The I/O handle of the FLAC stream to write. The
  88010. * handle will NOT be closed after the metadata is
  88011. * written; that is the duty of the caller.
  88012. * \param temp_callbacks
  88013. * A set of callbacks to use for I/O on temp_handle.
  88014. * The only mandatory callback is \a write.
  88015. * \assert
  88016. * \code chain != NULL \endcode
  88017. * \retval FLAC__bool
  88018. * \c true if the write succeeded, else \c false. On failure,
  88019. * check the status with FLAC__metadata_chain_status().
  88020. */
  88021. 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);
  88022. /** Merge adjacent PADDING blocks into a single block.
  88023. *
  88024. * \note This function does not write to the FLAC file, it only
  88025. * modifies the chain.
  88026. *
  88027. * \warning Any iterator on the current chain will become invalid after this
  88028. * call. You should delete the iterator and get a new one.
  88029. *
  88030. * \param chain A pointer to an existing chain.
  88031. * \assert
  88032. * \code chain != NULL \endcode
  88033. */
  88034. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88035. /** This function will move all PADDING blocks to the end on the metadata,
  88036. * then merge them into a single block.
  88037. *
  88038. * \note This function does not write to the FLAC file, it only
  88039. * modifies the chain.
  88040. *
  88041. * \warning Any iterator on the current chain will become invalid after this
  88042. * call. You should delete the iterator and get a new one.
  88043. *
  88044. * \param chain A pointer to an existing chain.
  88045. * \assert
  88046. * \code chain != NULL \endcode
  88047. */
  88048. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88049. /*********** FLAC__Metadata_Iterator ***********/
  88050. /** Create a new iterator instance.
  88051. *
  88052. * \retval FLAC__Metadata_Iterator*
  88053. * \c NULL if there was an error allocating memory, else the new instance.
  88054. */
  88055. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88056. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88057. *
  88058. * \param iterator A pointer to an existing iterator.
  88059. * \assert
  88060. * \code iterator != NULL \endcode
  88061. */
  88062. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88063. /** Initialize the iterator to point to the first metadata block in the
  88064. * given chain.
  88065. *
  88066. * \param iterator A pointer to an existing iterator.
  88067. * \param chain A pointer to an existing and initialized (read) chain.
  88068. * \assert
  88069. * \code iterator != NULL \endcode
  88070. * \code chain != NULL \endcode
  88071. */
  88072. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88073. /** Moves the iterator forward one metadata block, returning \c false if
  88074. * already at the end.
  88075. *
  88076. * \param iterator A pointer to an existing initialized iterator.
  88077. * \assert
  88078. * \code iterator != NULL \endcode
  88079. * \a iterator has been successfully initialized with
  88080. * FLAC__metadata_iterator_init()
  88081. * \retval FLAC__bool
  88082. * \c false if already at the last metadata block of the chain, else
  88083. * \c true.
  88084. */
  88085. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88086. /** Moves the iterator backward one metadata block, returning \c false if
  88087. * already at the beginning.
  88088. *
  88089. * \param iterator A pointer to an existing initialized iterator.
  88090. * \assert
  88091. * \code iterator != NULL \endcode
  88092. * \a iterator has been successfully initialized with
  88093. * FLAC__metadata_iterator_init()
  88094. * \retval FLAC__bool
  88095. * \c false if already at the first metadata block of the chain, else
  88096. * \c true.
  88097. */
  88098. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88099. /** Get the type of the metadata block at the current position.
  88100. *
  88101. * \param iterator A pointer to an existing initialized iterator.
  88102. * \assert
  88103. * \code iterator != NULL \endcode
  88104. * \a iterator has been successfully initialized with
  88105. * FLAC__metadata_iterator_init()
  88106. * \retval FLAC__MetadataType
  88107. * The type of the metadata block at the current iterator position.
  88108. */
  88109. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88110. /** Get the metadata block at the current position. You can modify
  88111. * the block in place but must write the chain before the changes
  88112. * are reflected to the FLAC file. You do not need to call
  88113. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88114. * the pointer returned by FLAC__metadata_iterator_get_block()
  88115. * points directly into the chain.
  88116. *
  88117. * \warning
  88118. * Do not call FLAC__metadata_object_delete() on the returned object;
  88119. * to delete a block use FLAC__metadata_iterator_delete_block().
  88120. *
  88121. * \param iterator A pointer to an existing initialized iterator.
  88122. * \assert
  88123. * \code iterator != NULL \endcode
  88124. * \a iterator has been successfully initialized with
  88125. * FLAC__metadata_iterator_init()
  88126. * \retval FLAC__StreamMetadata*
  88127. * The current metadata block.
  88128. */
  88129. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88130. /** Set the metadata block at the current position, replacing the existing
  88131. * block. The new block passed in becomes owned by the chain and it will be
  88132. * deleted when the chain is deleted.
  88133. *
  88134. * \param iterator A pointer to an existing initialized iterator.
  88135. * \param block A pointer to a metadata block.
  88136. * \assert
  88137. * \code iterator != NULL \endcode
  88138. * \a iterator has been successfully initialized with
  88139. * FLAC__metadata_iterator_init()
  88140. * \code block != NULL \endcode
  88141. * \retval FLAC__bool
  88142. * \c false if the conditions in the above description are not met, or
  88143. * a memory allocation error occurs, otherwise \c true.
  88144. */
  88145. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88146. /** Removes the current block from the chain. If \a replace_with_padding is
  88147. * \c true, the block will instead be replaced with a padding block of equal
  88148. * size. You can not delete the STREAMINFO block. The iterator will be
  88149. * left pointing to the block before the one just "deleted", even if
  88150. * \a replace_with_padding is \c true.
  88151. *
  88152. * \param iterator A pointer to an existing initialized iterator.
  88153. * \param replace_with_padding See above.
  88154. * \assert
  88155. * \code iterator != NULL \endcode
  88156. * \a iterator has been successfully initialized with
  88157. * FLAC__metadata_iterator_init()
  88158. * \retval FLAC__bool
  88159. * \c false if the conditions in the above description are not met,
  88160. * otherwise \c true.
  88161. */
  88162. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88163. /** Insert a new block before the current block. You cannot insert a block
  88164. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88165. * as there can be only one, the one that already exists at the head when you
  88166. * read in a chain. The chain takes ownership of the new block and it will be
  88167. * deleted when the chain is deleted. The iterator will be left pointing to
  88168. * the new block.
  88169. *
  88170. * \param iterator A pointer to an existing initialized iterator.
  88171. * \param block A pointer to a metadata block to insert.
  88172. * \assert
  88173. * \code iterator != NULL \endcode
  88174. * \a iterator has been successfully initialized with
  88175. * FLAC__metadata_iterator_init()
  88176. * \retval FLAC__bool
  88177. * \c false if the conditions in the above description are not met, or
  88178. * a memory allocation error occurs, otherwise \c true.
  88179. */
  88180. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88181. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88182. * block as there can be only one, the one that already exists at the head when
  88183. * you read in a chain. The chain takes ownership of the new block and it will
  88184. * be deleted when the chain is deleted. The iterator will be left pointing to
  88185. * the new block.
  88186. *
  88187. * \param iterator A pointer to an existing initialized iterator.
  88188. * \param block A pointer to a metadata block to insert.
  88189. * \assert
  88190. * \code iterator != NULL \endcode
  88191. * \a iterator has been successfully initialized with
  88192. * FLAC__metadata_iterator_init()
  88193. * \retval FLAC__bool
  88194. * \c false if the conditions in the above description are not met, or
  88195. * a memory allocation error occurs, otherwise \c true.
  88196. */
  88197. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88198. /* \} */
  88199. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88200. * \ingroup flac_metadata
  88201. *
  88202. * \brief
  88203. * This module contains methods for manipulating FLAC metadata objects.
  88204. *
  88205. * Since many are variable length we have to be careful about the memory
  88206. * management. We decree that all pointers to data in the object are
  88207. * owned by the object and memory-managed by the object.
  88208. *
  88209. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88210. * functions to create all instances. When using the
  88211. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88212. * \a copy to \c true to have the function make it's own copy of the data, or
  88213. * to \c false to give the object ownership of your data. In the latter case
  88214. * your pointer must be freeable by free() and will be free()d when the object
  88215. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88216. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88217. * the length argument is 0 and the \a copy argument is \c false.
  88218. *
  88219. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88220. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88221. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88222. * case of a memory allocation error.
  88223. *
  88224. * We don't have the convenience of C++ here, so note that the library relies
  88225. * on you to keep the types straight. In other words, if you pass, for
  88226. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88227. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88228. * failure.
  88229. *
  88230. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88231. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88232. * toward the length or stored in the stream, but it can make working with plain
  88233. * comments (those that don't contain embedded-NULs in the value) easier.
  88234. * Entries passed into these functions have trailing NULs added if missing, and
  88235. * returned entries are guaranteed to have a trailing NUL.
  88236. *
  88237. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88238. * comment entry/name/value will first validate that it complies with the Vorbis
  88239. * comment specification and return false if it does not.
  88240. *
  88241. * There is no need to recalculate the length field on metadata blocks you
  88242. * have modified. They will be calculated automatically before they are
  88243. * written back to a file.
  88244. *
  88245. * \{
  88246. */
  88247. /** Create a new metadata object instance of the given type.
  88248. *
  88249. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88250. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88251. * the vendor string set (but zero comments).
  88252. *
  88253. * Do not pass in a value greater than or equal to
  88254. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88255. * doing.
  88256. *
  88257. * \param type Type of object to create
  88258. * \retval FLAC__StreamMetadata*
  88259. * \c NULL if there was an error allocating memory or the type code is
  88260. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88261. */
  88262. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88263. /** Create a copy of an existing metadata object.
  88264. *
  88265. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88266. * object is also copied. The caller takes ownership of the new block and
  88267. * is responsible for freeing it with FLAC__metadata_object_delete().
  88268. *
  88269. * \param object Pointer to object to copy.
  88270. * \assert
  88271. * \code object != NULL \endcode
  88272. * \retval FLAC__StreamMetadata*
  88273. * \c NULL if there was an error allocating memory, else the new instance.
  88274. */
  88275. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88276. /** Free a metadata object. Deletes the object pointed to by \a object.
  88277. *
  88278. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88279. * object is also deleted.
  88280. *
  88281. * \param object A pointer to an existing object.
  88282. * \assert
  88283. * \code object != NULL \endcode
  88284. */
  88285. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88286. /** Compares two metadata objects.
  88287. *
  88288. * The compare is "deep", i.e. dynamically allocated data within the
  88289. * object is also compared.
  88290. *
  88291. * \param block1 A pointer to an existing object.
  88292. * \param block2 A pointer to an existing object.
  88293. * \assert
  88294. * \code block1 != NULL \endcode
  88295. * \code block2 != NULL \endcode
  88296. * \retval FLAC__bool
  88297. * \c true if objects are identical, else \c false.
  88298. */
  88299. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88300. /** Sets the application data of an APPLICATION block.
  88301. *
  88302. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88303. * takes ownership of the pointer. The existing data will be freed if this
  88304. * function is successful, otherwise the original data will remain if \a copy
  88305. * is \c true and malloc() fails.
  88306. *
  88307. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88308. *
  88309. * \param object A pointer to an existing APPLICATION object.
  88310. * \param data A pointer to the data to set.
  88311. * \param length The length of \a data in bytes.
  88312. * \param copy See above.
  88313. * \assert
  88314. * \code object != NULL \endcode
  88315. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88316. * \code (data != NULL && length > 0) ||
  88317. * (data == NULL && length == 0 && copy == false) \endcode
  88318. * \retval FLAC__bool
  88319. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88320. */
  88321. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88322. /** Resize the seekpoint array.
  88323. *
  88324. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88325. * points will be added to the end.
  88326. *
  88327. * \param object A pointer to an existing SEEKTABLE object.
  88328. * \param new_num_points The desired length of the array; may be \c 0.
  88329. * \assert
  88330. * \code object != NULL \endcode
  88331. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88332. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88333. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88334. * \retval FLAC__bool
  88335. * \c false if memory allocation error, else \c true.
  88336. */
  88337. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88338. /** Set a seekpoint in a seektable.
  88339. *
  88340. * \param object A pointer to an existing SEEKTABLE object.
  88341. * \param point_num Index into seekpoint array to set.
  88342. * \param point The point to set.
  88343. * \assert
  88344. * \code object != NULL \endcode
  88345. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88346. * \code object->data.seek_table.num_points > point_num \endcode
  88347. */
  88348. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88349. /** Insert a seekpoint into a seektable.
  88350. *
  88351. * \param object A pointer to an existing SEEKTABLE object.
  88352. * \param point_num Index into seekpoint array to set.
  88353. * \param point The point to set.
  88354. * \assert
  88355. * \code object != NULL \endcode
  88356. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88357. * \code object->data.seek_table.num_points >= point_num \endcode
  88358. * \retval FLAC__bool
  88359. * \c false if memory allocation error, else \c true.
  88360. */
  88361. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88362. /** Delete a seekpoint from a seektable.
  88363. *
  88364. * \param object A pointer to an existing SEEKTABLE object.
  88365. * \param point_num Index into seekpoint array to set.
  88366. * \assert
  88367. * \code object != NULL \endcode
  88368. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88369. * \code object->data.seek_table.num_points > point_num \endcode
  88370. * \retval FLAC__bool
  88371. * \c false if memory allocation error, else \c true.
  88372. */
  88373. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88374. /** Check a seektable to see if it conforms to the FLAC specification.
  88375. * See the format specification for limits on the contents of the
  88376. * seektable.
  88377. *
  88378. * \param object A pointer to an existing SEEKTABLE object.
  88379. * \assert
  88380. * \code object != NULL \endcode
  88381. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88382. * \retval FLAC__bool
  88383. * \c false if seek table is illegal, else \c true.
  88384. */
  88385. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88386. /** Append a number of placeholder points to the end of a seek table.
  88387. *
  88388. * \note
  88389. * As with the other ..._seektable_template_... functions, you should
  88390. * call FLAC__metadata_object_seektable_template_sort() when finished
  88391. * to make the seek table legal.
  88392. *
  88393. * \param object A pointer to an existing SEEKTABLE object.
  88394. * \param num The number of placeholder points to append.
  88395. * \assert
  88396. * \code object != NULL \endcode
  88397. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88398. * \retval FLAC__bool
  88399. * \c false if memory allocation fails, else \c true.
  88400. */
  88401. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88402. /** Append a specific seek point template to the end of a seek table.
  88403. *
  88404. * \note
  88405. * As with the other ..._seektable_template_... functions, you should
  88406. * call FLAC__metadata_object_seektable_template_sort() when finished
  88407. * to make the seek table legal.
  88408. *
  88409. * \param object A pointer to an existing SEEKTABLE object.
  88410. * \param sample_number The sample number of the seek point template.
  88411. * \assert
  88412. * \code object != NULL \endcode
  88413. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88414. * \retval FLAC__bool
  88415. * \c false if memory allocation fails, else \c true.
  88416. */
  88417. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88418. /** Append specific seek point templates to the end of a seek table.
  88419. *
  88420. * \note
  88421. * As with the other ..._seektable_template_... functions, you should
  88422. * call FLAC__metadata_object_seektable_template_sort() when finished
  88423. * to make the seek table legal.
  88424. *
  88425. * \param object A pointer to an existing SEEKTABLE object.
  88426. * \param sample_numbers An array of sample numbers for the seek points.
  88427. * \param num The number of seek point templates to append.
  88428. * \assert
  88429. * \code object != NULL \endcode
  88430. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88431. * \retval FLAC__bool
  88432. * \c false if memory allocation fails, else \c true.
  88433. */
  88434. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88435. /** Append a set of evenly-spaced seek point templates to the end of a
  88436. * seek table.
  88437. *
  88438. * \note
  88439. * As with the other ..._seektable_template_... functions, you should
  88440. * call FLAC__metadata_object_seektable_template_sort() when finished
  88441. * to make the seek table legal.
  88442. *
  88443. * \param object A pointer to an existing SEEKTABLE object.
  88444. * \param num The number of placeholder points to append.
  88445. * \param total_samples The total number of samples to be encoded;
  88446. * the seekpoints will be spaced approximately
  88447. * \a total_samples / \a num samples apart.
  88448. * \assert
  88449. * \code object != NULL \endcode
  88450. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88451. * \code total_samples > 0 \endcode
  88452. * \retval FLAC__bool
  88453. * \c false if memory allocation fails, else \c true.
  88454. */
  88455. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88456. /** Append a set of evenly-spaced seek point templates to the end of a
  88457. * seek table.
  88458. *
  88459. * \note
  88460. * As with the other ..._seektable_template_... functions, you should
  88461. * call FLAC__metadata_object_seektable_template_sort() when finished
  88462. * to make the seek table legal.
  88463. *
  88464. * \param object A pointer to an existing SEEKTABLE object.
  88465. * \param samples The number of samples apart to space the placeholder
  88466. * points. The first point will be at sample \c 0, the
  88467. * second at sample \a samples, then 2*\a samples, and
  88468. * so on. As long as \a samples and \a total_samples
  88469. * are greater than \c 0, there will always be at least
  88470. * one seekpoint at sample \c 0.
  88471. * \param total_samples The total number of samples to be encoded;
  88472. * the seekpoints will be spaced
  88473. * \a samples samples apart.
  88474. * \assert
  88475. * \code object != NULL \endcode
  88476. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88477. * \code samples > 0 \endcode
  88478. * \code total_samples > 0 \endcode
  88479. * \retval FLAC__bool
  88480. * \c false if memory allocation fails, else \c true.
  88481. */
  88482. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88483. /** Sort a seek table's seek points according to the format specification,
  88484. * removing duplicates.
  88485. *
  88486. * \param object A pointer to a seek table to be sorted.
  88487. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88488. * If \c true, duplicates are deleted and the seek table is
  88489. * shrunk appropriately; the number of placeholder points
  88490. * present in the seek table will be the same after the call
  88491. * as before.
  88492. * \assert
  88493. * \code object != NULL \endcode
  88494. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88495. * \retval FLAC__bool
  88496. * \c false if realloc() fails, else \c true.
  88497. */
  88498. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  88499. /** Sets the vendor string in a VORBIS_COMMENT block.
  88500. *
  88501. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88502. * one already.
  88503. *
  88504. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88505. * takes ownership of the \c entry.entry pointer.
  88506. *
  88507. * \note If this function returns \c false, the caller still owns the
  88508. * pointer.
  88509. *
  88510. * \param object A pointer to an existing VORBIS_COMMENT object.
  88511. * \param entry The entry to set the vendor string to.
  88512. * \param copy See above.
  88513. * \assert
  88514. * \code object != NULL \endcode
  88515. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88516. * \code (entry.entry != NULL && entry.length > 0) ||
  88517. * (entry.entry == NULL && entry.length == 0) \endcode
  88518. * \retval FLAC__bool
  88519. * \c false if memory allocation fails or \a entry does not comply with the
  88520. * Vorbis comment specification, else \c true.
  88521. */
  88522. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88523. /** Resize the comment array.
  88524. *
  88525. * If the size shrinks, elements will truncated; if it grows, new empty
  88526. * fields will be added to the end.
  88527. *
  88528. * \param object A pointer to an existing VORBIS_COMMENT object.
  88529. * \param new_num_comments The desired length of the array; may be \c 0.
  88530. * \assert
  88531. * \code object != NULL \endcode
  88532. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88533. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  88534. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  88535. * \retval FLAC__bool
  88536. * \c false if memory allocation fails, else \c true.
  88537. */
  88538. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  88539. /** Sets a comment in a VORBIS_COMMENT block.
  88540. *
  88541. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88542. * one already.
  88543. *
  88544. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88545. * takes ownership of the \c entry.entry pointer.
  88546. *
  88547. * \note If this function returns \c false, the caller still owns the
  88548. * pointer.
  88549. *
  88550. * \param object A pointer to an existing VORBIS_COMMENT object.
  88551. * \param comment_num Index into comment array to set.
  88552. * \param entry The entry to set the comment to.
  88553. * \param copy See above.
  88554. * \assert
  88555. * \code object != NULL \endcode
  88556. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88557. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  88558. * \code (entry.entry != NULL && entry.length > 0) ||
  88559. * (entry.entry == NULL && entry.length == 0) \endcode
  88560. * \retval FLAC__bool
  88561. * \c false if memory allocation fails or \a entry does not comply with the
  88562. * Vorbis comment specification, else \c true.
  88563. */
  88564. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88565. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  88566. *
  88567. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88568. * one already.
  88569. *
  88570. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88571. * takes ownership of the \c entry.entry pointer.
  88572. *
  88573. * \note If this function returns \c false, the caller still owns the
  88574. * pointer.
  88575. *
  88576. * \param object A pointer to an existing VORBIS_COMMENT object.
  88577. * \param comment_num The index at which to insert the comment. The comments
  88578. * at and after \a comment_num move right one position.
  88579. * To append a comment to the end, set \a comment_num to
  88580. * \c object->data.vorbis_comment.num_comments .
  88581. * \param entry The comment to insert.
  88582. * \param copy See above.
  88583. * \assert
  88584. * \code object != NULL \endcode
  88585. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88586. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  88587. * \code (entry.entry != NULL && entry.length > 0) ||
  88588. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88589. * \retval FLAC__bool
  88590. * \c false if memory allocation fails or \a entry does not comply with the
  88591. * Vorbis comment specification, else \c true.
  88592. */
  88593. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88594. /** Appends a comment to a VORBIS_COMMENT block.
  88595. *
  88596. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88597. * one already.
  88598. *
  88599. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88600. * takes ownership of the \c entry.entry pointer.
  88601. *
  88602. * \note If this function returns \c false, the caller still owns the
  88603. * pointer.
  88604. *
  88605. * \param object A pointer to an existing VORBIS_COMMENT object.
  88606. * \param entry The comment to insert.
  88607. * \param copy See above.
  88608. * \assert
  88609. * \code object != NULL \endcode
  88610. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88611. * \code (entry.entry != NULL && entry.length > 0) ||
  88612. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88613. * \retval FLAC__bool
  88614. * \c false if memory allocation fails or \a entry does not comply with the
  88615. * Vorbis comment specification, else \c true.
  88616. */
  88617. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88618. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  88619. *
  88620. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88621. * one already.
  88622. *
  88623. * Depending on the the value of \a all, either all or just the first comment
  88624. * whose field name(s) match the given entry's name will be replaced by the
  88625. * given entry. If no comments match, \a entry will simply be appended.
  88626. *
  88627. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88628. * takes ownership of the \c entry.entry pointer.
  88629. *
  88630. * \note If this function returns \c false, the caller still owns the
  88631. * pointer.
  88632. *
  88633. * \param object A pointer to an existing VORBIS_COMMENT object.
  88634. * \param entry The comment to insert.
  88635. * \param all If \c true, all comments whose field name matches
  88636. * \a entry's field name will be removed, and \a entry will
  88637. * be inserted at the position of the first matching
  88638. * comment. If \c false, only the first comment whose
  88639. * field name matches \a entry's field name will be
  88640. * replaced with \a entry.
  88641. * \param copy See above.
  88642. * \assert
  88643. * \code object != NULL \endcode
  88644. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88645. * \code (entry.entry != NULL && entry.length > 0) ||
  88646. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88647. * \retval FLAC__bool
  88648. * \c false if memory allocation fails or \a entry does not comply with the
  88649. * Vorbis comment specification, else \c true.
  88650. */
  88651. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  88652. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  88653. *
  88654. * \param object A pointer to an existing VORBIS_COMMENT object.
  88655. * \param comment_num The index of the comment to delete.
  88656. * \assert
  88657. * \code object != NULL \endcode
  88658. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88659. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  88660. * \retval FLAC__bool
  88661. * \c false if realloc() fails, else \c true.
  88662. */
  88663. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  88664. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  88665. *
  88666. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  88667. * memory and shall be owned by the caller. For convenience the entry will
  88668. * have a terminating NUL.
  88669. *
  88670. * \param entry A pointer to a Vorbis comment entry. The entry's
  88671. * \c entry pointer should not point to allocated
  88672. * memory as it will be overwritten.
  88673. * \param field_name The field name in ASCII, \c NUL terminated.
  88674. * \param field_value The field value in UTF-8, \c NUL terminated.
  88675. * \assert
  88676. * \code entry != NULL \endcode
  88677. * \code field_name != NULL \endcode
  88678. * \code field_value != NULL \endcode
  88679. * \retval FLAC__bool
  88680. * \c false if malloc() fails, or if \a field_name or \a field_value does
  88681. * not comply with the Vorbis comment specification, else \c true.
  88682. */
  88683. 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);
  88684. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  88685. *
  88686. * The returned pointers to name and value will be allocated by malloc()
  88687. * and shall be owned by the caller.
  88688. *
  88689. * \param entry An existing Vorbis comment entry.
  88690. * \param field_name The address of where the returned pointer to the
  88691. * field name will be stored.
  88692. * \param field_value The address of where the returned pointer to the
  88693. * field value will be stored.
  88694. * \assert
  88695. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88696. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  88697. * \code field_name != NULL \endcode
  88698. * \code field_value != NULL \endcode
  88699. * \retval FLAC__bool
  88700. * \c false if memory allocation fails or \a entry does not comply with the
  88701. * Vorbis comment specification, else \c true.
  88702. */
  88703. 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);
  88704. /** Check if the given Vorbis comment entry's field name matches the given
  88705. * field name.
  88706. *
  88707. * \param entry An existing Vorbis comment entry.
  88708. * \param field_name The field name to check.
  88709. * \param field_name_length The length of \a field_name, not including the
  88710. * terminating \c NUL.
  88711. * \assert
  88712. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88713. * \retval FLAC__bool
  88714. * \c true if the field names match, else \c false
  88715. */
  88716. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  88717. /** Find a Vorbis comment with the given field name.
  88718. *
  88719. * The search begins at entry number \a offset; use an offset of 0 to
  88720. * search from the beginning of the comment array.
  88721. *
  88722. * \param object A pointer to an existing VORBIS_COMMENT object.
  88723. * \param offset The offset into the comment array from where to start
  88724. * the search.
  88725. * \param field_name The field name of the comment to find.
  88726. * \assert
  88727. * \code object != NULL \endcode
  88728. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88729. * \code field_name != NULL \endcode
  88730. * \retval int
  88731. * The offset in the comment array of the first comment whose field
  88732. * name matches \a field_name, or \c -1 if no match was found.
  88733. */
  88734. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  88735. /** Remove first Vorbis comment matching the given field name.
  88736. *
  88737. * \param object A pointer to an existing VORBIS_COMMENT object.
  88738. * \param field_name The field name of comment to delete.
  88739. * \assert
  88740. * \code object != NULL \endcode
  88741. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88742. * \retval int
  88743. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88744. * \c 1 for one matching entry deleted.
  88745. */
  88746. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  88747. /** Remove all Vorbis comments matching the given field name.
  88748. *
  88749. * \param object A pointer to an existing VORBIS_COMMENT object.
  88750. * \param field_name The field name of comments to delete.
  88751. * \assert
  88752. * \code object != NULL \endcode
  88753. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88754. * \retval int
  88755. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88756. * else the number of matching entries deleted.
  88757. */
  88758. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  88759. /** Create a new CUESHEET track instance.
  88760. *
  88761. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  88762. *
  88763. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88764. * \c NULL if there was an error allocating memory, else the new instance.
  88765. */
  88766. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  88767. /** Create a copy of an existing CUESHEET track object.
  88768. *
  88769. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88770. * object is also copied. The caller takes ownership of the new object and
  88771. * is responsible for freeing it with
  88772. * FLAC__metadata_object_cuesheet_track_delete().
  88773. *
  88774. * \param object Pointer to object to copy.
  88775. * \assert
  88776. * \code object != NULL \endcode
  88777. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88778. * \c NULL if there was an error allocating memory, else the new instance.
  88779. */
  88780. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  88781. /** Delete a CUESHEET track object
  88782. *
  88783. * \param object A pointer to an existing CUESHEET track object.
  88784. * \assert
  88785. * \code object != NULL \endcode
  88786. */
  88787. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  88788. /** Resize a track's index point array.
  88789. *
  88790. * If the size shrinks, elements will truncated; if it grows, new blank
  88791. * indices will be added to the end.
  88792. *
  88793. * \param object A pointer to an existing CUESHEET object.
  88794. * \param track_num The index of the track to modify. NOTE: this is not
  88795. * necessarily the same as the track's \a number field.
  88796. * \param new_num_indices The desired length of the array; may be \c 0.
  88797. * \assert
  88798. * \code object != NULL \endcode
  88799. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88800. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88801. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  88802. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  88803. * \retval FLAC__bool
  88804. * \c false if memory allocation error, else \c true.
  88805. */
  88806. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  88807. /** Insert an index point in a CUESHEET track at the given index.
  88808. *
  88809. * \param object A pointer to an existing CUESHEET object.
  88810. * \param track_num The index of the track to modify. NOTE: this is not
  88811. * necessarily the same as the track's \a number field.
  88812. * \param index_num The index into the track's index array at which to
  88813. * insert the index point. NOTE: this is not necessarily
  88814. * the same as the index point's \a number field. The
  88815. * indices at and after \a index_num move right one
  88816. * position. To append an index point to the end, set
  88817. * \a index_num to
  88818. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88819. * \param index The index point to insert.
  88820. * \assert
  88821. * \code object != NULL \endcode
  88822. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88823. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88824. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88825. * \retval FLAC__bool
  88826. * \c false if realloc() fails, else \c true.
  88827. */
  88828. 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);
  88829. /** Insert a blank index point in a CUESHEET track at the given index.
  88830. *
  88831. * A blank index point is one in which all field values are zero.
  88832. *
  88833. * \param object A pointer to an existing CUESHEET object.
  88834. * \param track_num The index of the track to modify. NOTE: this is not
  88835. * necessarily the same as the track's \a number field.
  88836. * \param index_num The index into the track's index array at which to
  88837. * insert the index point. NOTE: this is not necessarily
  88838. * the same as the index point's \a number field. The
  88839. * indices at and after \a index_num move right one
  88840. * position. To append an index point to the end, set
  88841. * \a index_num to
  88842. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88843. * \assert
  88844. * \code object != NULL \endcode
  88845. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88846. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88847. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88848. * \retval FLAC__bool
  88849. * \c false if realloc() fails, else \c true.
  88850. */
  88851. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88852. /** Delete an index point in a CUESHEET track at the given index.
  88853. *
  88854. * \param object A pointer to an existing CUESHEET object.
  88855. * \param track_num The index into the track array of the track to
  88856. * modify. NOTE: this is not necessarily the same
  88857. * as the track's \a number field.
  88858. * \param index_num The index into the track's index array of the index
  88859. * to delete. NOTE: this is not necessarily the same
  88860. * as the index's \a number field.
  88861. * \assert
  88862. * \code object != NULL \endcode
  88863. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88864. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88865. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  88866. * \retval FLAC__bool
  88867. * \c false if realloc() fails, else \c true.
  88868. */
  88869. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88870. /** Resize the track array.
  88871. *
  88872. * If the size shrinks, elements will truncated; if it grows, new blank
  88873. * tracks will be added to the end.
  88874. *
  88875. * \param object A pointer to an existing CUESHEET object.
  88876. * \param new_num_tracks The desired length of the array; may be \c 0.
  88877. * \assert
  88878. * \code object != NULL \endcode
  88879. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88880. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  88881. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  88882. * \retval FLAC__bool
  88883. * \c false if memory allocation error, else \c true.
  88884. */
  88885. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  88886. /** Sets a track in a CUESHEET block.
  88887. *
  88888. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88889. * takes ownership of the \a track pointer.
  88890. *
  88891. * \param object A pointer to an existing CUESHEET object.
  88892. * \param track_num Index into track array to set. NOTE: this is not
  88893. * necessarily the same as the track's \a number field.
  88894. * \param track The track to set the track to. You may safely pass in
  88895. * a const pointer if \a copy is \c true.
  88896. * \param copy See above.
  88897. * \assert
  88898. * \code object != NULL \endcode
  88899. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88900. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  88901. * \code (track->indices != NULL && track->num_indices > 0) ||
  88902. * (track->indices == NULL && track->num_indices == 0)
  88903. * \retval FLAC__bool
  88904. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88905. */
  88906. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88907. /** Insert a track in a CUESHEET block at the given index.
  88908. *
  88909. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88910. * takes ownership of the \a track pointer.
  88911. *
  88912. * \param object A pointer to an existing CUESHEET object.
  88913. * \param track_num The index at which to insert the track. NOTE: this
  88914. * is not necessarily the same as the track's \a number
  88915. * field. The tracks at and after \a track_num move right
  88916. * one position. To append a track to the end, set
  88917. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88918. * \param track The track to insert. You may safely pass in a const
  88919. * pointer if \a copy is \c true.
  88920. * \param copy See above.
  88921. * \assert
  88922. * \code object != NULL \endcode
  88923. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88924. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88925. * \retval FLAC__bool
  88926. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88927. */
  88928. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88929. /** Insert a blank track in a CUESHEET block at the given index.
  88930. *
  88931. * A blank track is one in which all field values are zero.
  88932. *
  88933. * \param object A pointer to an existing CUESHEET object.
  88934. * \param track_num The index at which to insert the track. NOTE: this
  88935. * is not necessarily the same as the track's \a number
  88936. * field. The tracks at and after \a track_num move right
  88937. * one position. To append a track to the end, set
  88938. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88939. * \assert
  88940. * \code object != NULL \endcode
  88941. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88942. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88943. * \retval FLAC__bool
  88944. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88945. */
  88946. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  88947. /** Delete a track in a CUESHEET block at the given index.
  88948. *
  88949. * \param object A pointer to an existing CUESHEET object.
  88950. * \param track_num The index into the track array of the track to
  88951. * delete. NOTE: this is not necessarily the same
  88952. * as the track's \a number field.
  88953. * \assert
  88954. * \code object != NULL \endcode
  88955. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88956. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88957. * \retval FLAC__bool
  88958. * \c false if realloc() fails, else \c true.
  88959. */
  88960. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  88961. /** Check a cue sheet to see if it conforms to the FLAC specification.
  88962. * See the format specification for limits on the contents of the
  88963. * cue sheet.
  88964. *
  88965. * \param object A pointer to an existing CUESHEET object.
  88966. * \param check_cd_da_subset If \c true, check CUESHEET against more
  88967. * stringent requirements for a CD-DA (audio) disc.
  88968. * \param violation Address of a pointer to a string. If there is a
  88969. * violation, a pointer to a string explanation of the
  88970. * violation will be returned here. \a violation may be
  88971. * \c NULL if you don't need the returned string. Do not
  88972. * free the returned string; it will always point to static
  88973. * data.
  88974. * \assert
  88975. * \code object != NULL \endcode
  88976. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88977. * \retval FLAC__bool
  88978. * \c false if cue sheet is illegal, else \c true.
  88979. */
  88980. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  88981. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  88982. * assumes the cue sheet corresponds to a CD; the result is undefined
  88983. * if the cuesheet's is_cd bit is not set.
  88984. *
  88985. * \param object A pointer to an existing CUESHEET object.
  88986. * \assert
  88987. * \code object != NULL \endcode
  88988. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88989. * \retval FLAC__uint32
  88990. * The unsigned integer representation of the CDDB/freedb ID
  88991. */
  88992. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  88993. /** Sets the MIME type of a PICTURE block.
  88994. *
  88995. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  88996. * takes ownership of the pointer. The existing string will be freed if this
  88997. * function is successful, otherwise the original string will remain if \a copy
  88998. * is \c true and malloc() fails.
  88999. *
  89000. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  89001. *
  89002. * \param object A pointer to an existing PICTURE object.
  89003. * \param mime_type A pointer to the MIME type string. The string must be
  89004. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  89005. * is done.
  89006. * \param copy See above.
  89007. * \assert
  89008. * \code object != NULL \endcode
  89009. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89010. * \code (mime_type != NULL) \endcode
  89011. * \retval FLAC__bool
  89012. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89013. */
  89014. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  89015. /** Sets the description of a PICTURE block.
  89016. *
  89017. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89018. * takes ownership of the pointer. The existing string will be freed if this
  89019. * function is successful, otherwise the original string will remain if \a copy
  89020. * is \c true and malloc() fails.
  89021. *
  89022. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89023. *
  89024. * \param object A pointer to an existing PICTURE object.
  89025. * \param description A pointer to the description string. The string must be
  89026. * valid UTF-8, NUL-terminated. No validation is done.
  89027. * \param copy See above.
  89028. * \assert
  89029. * \code object != NULL \endcode
  89030. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89031. * \code (description != NULL) \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_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89036. /** Sets the picture data of a PICTURE block.
  89037. *
  89038. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89039. * takes ownership of the pointer. Also sets the \a data_length field of the
  89040. * metadata object to what is passed in as the \a length parameter. The
  89041. * existing data will be freed if this function is successful, otherwise the
  89042. * original data and data_length will remain if \a copy is \c true and
  89043. * malloc() fails.
  89044. *
  89045. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89046. *
  89047. * \param object A pointer to an existing PICTURE object.
  89048. * \param data A pointer to the data to set.
  89049. * \param length The length of \a data in bytes.
  89050. * \param copy See above.
  89051. * \assert
  89052. * \code object != NULL \endcode
  89053. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89054. * \code (data != NULL && length > 0) ||
  89055. * (data == NULL && length == 0 && copy == false) \endcode
  89056. * \retval FLAC__bool
  89057. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89058. */
  89059. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89060. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89061. * See the format specification for limits on the contents of the
  89062. * PICTURE block.
  89063. *
  89064. * \param object A pointer to existing PICTURE block to be checked.
  89065. * \param violation Address of a pointer to a string. If there is a
  89066. * violation, a pointer to a string explanation of the
  89067. * violation will be returned here. \a violation may be
  89068. * \c NULL if you don't need the returned string. Do not
  89069. * free the returned string; it will always point to static
  89070. * data.
  89071. * \assert
  89072. * \code object != NULL \endcode
  89073. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89074. * \retval FLAC__bool
  89075. * \c false if PICTURE block is illegal, else \c true.
  89076. */
  89077. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89078. /* \} */
  89079. #ifdef __cplusplus
  89080. }
  89081. #endif
  89082. #endif
  89083. /*** End of inlined file: metadata.h ***/
  89084. /*** Start of inlined file: stream_decoder.h ***/
  89085. #ifndef FLAC__STREAM_DECODER_H
  89086. #define FLAC__STREAM_DECODER_H
  89087. #include <stdio.h> /* for FILE */
  89088. #ifdef __cplusplus
  89089. extern "C" {
  89090. #endif
  89091. /** \file include/FLAC/stream_decoder.h
  89092. *
  89093. * \brief
  89094. * This module contains the functions which implement the stream
  89095. * decoder.
  89096. *
  89097. * See the detailed documentation in the
  89098. * \link flac_stream_decoder stream decoder \endlink module.
  89099. */
  89100. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89101. * \ingroup flac
  89102. *
  89103. * \brief
  89104. * This module describes the decoder layers provided by libFLAC.
  89105. *
  89106. * The stream decoder can be used to decode complete streams either from
  89107. * the client via callbacks, or directly from a file, depending on how
  89108. * it is initialized. When decoding via callbacks, the client provides
  89109. * callbacks for reading FLAC data and writing decoded samples, and
  89110. * handling metadata and errors. If the client also supplies seek-related
  89111. * callback, the decoder function for sample-accurate seeking within the
  89112. * FLAC input is also available. When decoding from a file, the client
  89113. * needs only supply a filename or open \c FILE* and write/metadata/error
  89114. * callbacks; the rest of the callbacks are supplied internally. For more
  89115. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89116. */
  89117. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89118. * \ingroup flac_decoder
  89119. *
  89120. * \brief
  89121. * This module contains the functions which implement the stream
  89122. * decoder.
  89123. *
  89124. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89125. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89126. *
  89127. * The basic usage of this decoder is as follows:
  89128. * - The program creates an instance of a decoder using
  89129. * FLAC__stream_decoder_new().
  89130. * - The program overrides the default settings using
  89131. * FLAC__stream_decoder_set_*() functions.
  89132. * - The program initializes the instance to validate the settings and
  89133. * prepare for decoding using
  89134. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89135. * or FLAC__stream_decoder_init_file() for native FLAC,
  89136. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89137. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89138. * - The program calls the FLAC__stream_decoder_process_*() functions
  89139. * to decode data, which subsequently calls the callbacks.
  89140. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89141. * which flushes the input and output and resets the decoder to the
  89142. * uninitialized state.
  89143. * - The instance may be used again or deleted with
  89144. * FLAC__stream_decoder_delete().
  89145. *
  89146. * In more detail, the program will create a new instance by calling
  89147. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89148. * functions to override the default decoder options, and call
  89149. * one of the FLAC__stream_decoder_init_*() functions.
  89150. *
  89151. * There are three initialization functions for native FLAC, one for
  89152. * setting up the decoder to decode FLAC data from the client via
  89153. * callbacks, and two for decoding directly from a FLAC file.
  89154. *
  89155. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89156. * You must also supply several callbacks for handling I/O. Some (like
  89157. * seeking) are optional, depending on the capabilities of the input.
  89158. *
  89159. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89160. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89161. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89162. * the other callbacks internally.
  89163. *
  89164. * There are three similarly-named init functions for decoding from Ogg
  89165. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89166. * library has been built with Ogg support.
  89167. *
  89168. * Once the decoder is initialized, your program will call one of several
  89169. * functions to start the decoding process:
  89170. *
  89171. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89172. * most one metadata block or audio frame and return, calling either the
  89173. * metadata callback or write callback, respectively, once. If the decoder
  89174. * loses sync it will return with only the error callback being called.
  89175. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89176. * to process the stream from the current location and stop upon reaching
  89177. * the first audio frame. The client will get one metadata, write, or error
  89178. * callback per metadata block, audio frame, or sync error, respectively.
  89179. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89180. * to process the stream from the current location until the read callback
  89181. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89182. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89183. * write, or error callback per metadata block, audio frame, or sync error,
  89184. * respectively.
  89185. *
  89186. * When the decoder has finished decoding (normally or through an abort),
  89187. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89188. * ensures the decoder is in the correct state and frees memory. Then the
  89189. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89190. * again to decode another stream.
  89191. *
  89192. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89193. * At any point after the stream decoder has been initialized, the client can
  89194. * call this function to seek to an exact sample within the stream.
  89195. * Subsequently, the first time the write callback is called it will be
  89196. * passed a (possibly partial) block starting at that sample.
  89197. *
  89198. * If the client cannot seek via the callback interface provided, but still
  89199. * has another way of seeking, it can flush the decoder using
  89200. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89201. * through the read callback.
  89202. *
  89203. * The stream decoder also provides MD5 signature checking. If this is
  89204. * turned on before initialization, FLAC__stream_decoder_finish() will
  89205. * report when the decoded MD5 signature does not match the one stored
  89206. * in the STREAMINFO block. MD5 checking is automatically turned off
  89207. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89208. * in the STREAMINFO block or when a seek is attempted.
  89209. *
  89210. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89211. * attention. By default, the decoder only calls the metadata_callback for
  89212. * the STREAMINFO block. These functions allow you to tell the decoder
  89213. * explicitly which blocks to parse and return via the metadata_callback
  89214. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89215. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89216. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89217. * which blocks to return. Remember that metadata blocks can potentially
  89218. * be big (for example, cover art) so filtering out the ones you don't
  89219. * use can reduce the memory requirements of the decoder. Also note the
  89220. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89221. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89222. * filtering APPLICATION blocks based on the application ID.
  89223. *
  89224. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89225. * they still can legally be filtered from the metadata_callback.
  89226. *
  89227. * \note
  89228. * The "set" functions may only be called when the decoder is in the
  89229. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89230. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89231. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89232. * return \c true, otherwise \c false.
  89233. *
  89234. * \note
  89235. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89236. * defaults, including the callbacks.
  89237. *
  89238. * \{
  89239. */
  89240. /** State values for a FLAC__StreamDecoder
  89241. *
  89242. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89243. */
  89244. typedef enum {
  89245. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89246. /**< The decoder is ready to search for metadata. */
  89247. FLAC__STREAM_DECODER_READ_METADATA,
  89248. /**< The decoder is ready to or is in the process of reading metadata. */
  89249. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89250. /**< The decoder is ready to or is in the process of searching for the
  89251. * frame sync code.
  89252. */
  89253. FLAC__STREAM_DECODER_READ_FRAME,
  89254. /**< The decoder is ready to or is in the process of reading a frame. */
  89255. FLAC__STREAM_DECODER_END_OF_STREAM,
  89256. /**< The decoder has reached the end of the stream. */
  89257. FLAC__STREAM_DECODER_OGG_ERROR,
  89258. /**< An error occurred in the underlying Ogg layer. */
  89259. FLAC__STREAM_DECODER_SEEK_ERROR,
  89260. /**< An error occurred while seeking. The decoder must be flushed
  89261. * with FLAC__stream_decoder_flush() or reset with
  89262. * FLAC__stream_decoder_reset() before decoding can continue.
  89263. */
  89264. FLAC__STREAM_DECODER_ABORTED,
  89265. /**< The decoder was aborted by the read callback. */
  89266. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89267. /**< An error occurred allocating memory. The decoder is in an invalid
  89268. * state and can no longer be used.
  89269. */
  89270. FLAC__STREAM_DECODER_UNINITIALIZED
  89271. /**< The decoder is in the uninitialized state; one of the
  89272. * FLAC__stream_decoder_init_*() functions must be called before samples
  89273. * can be processed.
  89274. */
  89275. } FLAC__StreamDecoderState;
  89276. /** Maps a FLAC__StreamDecoderState to a C string.
  89277. *
  89278. * Using a FLAC__StreamDecoderState as the index to this array
  89279. * will give the string equivalent. The contents should not be modified.
  89280. */
  89281. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89282. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89283. */
  89284. typedef enum {
  89285. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89286. /**< Initialization was successful. */
  89287. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89288. /**< The library was not compiled with support for the given container
  89289. * format.
  89290. */
  89291. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89292. /**< A required callback was not supplied. */
  89293. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89294. /**< An error occurred allocating memory. */
  89295. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89296. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89297. * FLAC__stream_decoder_init_ogg_file(). */
  89298. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89299. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89300. * already initialized, usually because
  89301. * FLAC__stream_decoder_finish() was not called.
  89302. */
  89303. } FLAC__StreamDecoderInitStatus;
  89304. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89305. *
  89306. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89307. * will give the string equivalent. The contents should not be modified.
  89308. */
  89309. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89310. /** Return values for the FLAC__StreamDecoder read callback.
  89311. */
  89312. typedef enum {
  89313. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89314. /**< The read was OK and decoding can continue. */
  89315. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89316. /**< The read was attempted while at the end of the stream. Note that
  89317. * the client must only return this value when the read callback was
  89318. * called when already at the end of the stream. Otherwise, if the read
  89319. * itself moves to the end of the stream, the client should still return
  89320. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89321. * the next read callback it should return
  89322. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89323. * of \c 0.
  89324. */
  89325. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89326. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89327. } FLAC__StreamDecoderReadStatus;
  89328. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89329. *
  89330. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89331. * will give the string equivalent. The contents should not be modified.
  89332. */
  89333. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89334. /** Return values for the FLAC__StreamDecoder seek callback.
  89335. */
  89336. typedef enum {
  89337. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89338. /**< The seek was OK and decoding can continue. */
  89339. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89340. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89341. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89342. /**< Client does not support seeking. */
  89343. } FLAC__StreamDecoderSeekStatus;
  89344. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89345. *
  89346. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89347. * will give the string equivalent. The contents should not be modified.
  89348. */
  89349. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89350. /** Return values for the FLAC__StreamDecoder tell callback.
  89351. */
  89352. typedef enum {
  89353. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89354. /**< The tell was OK and decoding can continue. */
  89355. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89356. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89357. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89358. /**< Client does not support telling the position. */
  89359. } FLAC__StreamDecoderTellStatus;
  89360. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89361. *
  89362. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89363. * will give the string equivalent. The contents should not be modified.
  89364. */
  89365. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89366. /** Return values for the FLAC__StreamDecoder length callback.
  89367. */
  89368. typedef enum {
  89369. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89370. /**< The length call was OK and decoding can continue. */
  89371. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89372. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89373. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89374. /**< Client does not support reporting the length. */
  89375. } FLAC__StreamDecoderLengthStatus;
  89376. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89377. *
  89378. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89379. * will give the string equivalent. The contents should not be modified.
  89380. */
  89381. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89382. /** Return values for the FLAC__StreamDecoder write callback.
  89383. */
  89384. typedef enum {
  89385. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89386. /**< The write was OK and decoding can continue. */
  89387. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89388. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89389. } FLAC__StreamDecoderWriteStatus;
  89390. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89391. *
  89392. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89393. * will give the string equivalent. The contents should not be modified.
  89394. */
  89395. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89396. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89397. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89398. * all. The rest could be caused by bad sync (false synchronization on
  89399. * data that is not the start of a frame) or corrupted data. The error
  89400. * itself is the decoder's best guess at what happened assuming a correct
  89401. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89402. * could be caused by a correct sync on the start of a frame, but some
  89403. * data in the frame header was corrupted. Or it could be the result of
  89404. * syncing on a point the stream that looked like the starting of a frame
  89405. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89406. * could be because the decoder encountered a valid frame made by a future
  89407. * version of the encoder which it cannot parse, or because of a false
  89408. * sync making it appear as though an encountered frame was generated by
  89409. * a future encoder.
  89410. */
  89411. typedef enum {
  89412. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89413. /**< An error in the stream caused the decoder to lose synchronization. */
  89414. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89415. /**< The decoder encountered a corrupted frame header. */
  89416. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89417. /**< The frame's data did not match the CRC in the footer. */
  89418. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89419. /**< The decoder encountered reserved fields in use in the stream. */
  89420. } FLAC__StreamDecoderErrorStatus;
  89421. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89422. *
  89423. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89424. * will give the string equivalent. The contents should not be modified.
  89425. */
  89426. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89427. /***********************************************************************
  89428. *
  89429. * class FLAC__StreamDecoder
  89430. *
  89431. ***********************************************************************/
  89432. struct FLAC__StreamDecoderProtected;
  89433. struct FLAC__StreamDecoderPrivate;
  89434. /** The opaque structure definition for the stream decoder type.
  89435. * See the \link flac_stream_decoder stream decoder module \endlink
  89436. * for a detailed description.
  89437. */
  89438. typedef struct {
  89439. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89440. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89441. } FLAC__StreamDecoder;
  89442. /** Signature for the read callback.
  89443. *
  89444. * A function pointer matching this signature must be passed to
  89445. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89446. * called when the decoder needs more input data. The address of the
  89447. * buffer to be filled is supplied, along with the number of bytes the
  89448. * buffer can hold. The callback may choose to supply less data and
  89449. * modify the byte count but must be careful not to overflow the buffer.
  89450. * The callback then returns a status code chosen from
  89451. * FLAC__StreamDecoderReadStatus.
  89452. *
  89453. * Here is an example of a read callback for stdio streams:
  89454. * \code
  89455. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89456. * {
  89457. * FILE *file = ((MyClientData*)client_data)->file;
  89458. * if(*bytes > 0) {
  89459. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89460. * if(ferror(file))
  89461. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89462. * else if(*bytes == 0)
  89463. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89464. * else
  89465. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89466. * }
  89467. * else
  89468. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89469. * }
  89470. * \endcode
  89471. *
  89472. * \note In general, FLAC__StreamDecoder functions which change the
  89473. * state should not be called on the \a decoder while in the callback.
  89474. *
  89475. * \param decoder The decoder instance calling the callback.
  89476. * \param buffer A pointer to a location for the callee to store
  89477. * data to be decoded.
  89478. * \param bytes A pointer to the size of the buffer. On entry
  89479. * to the callback, it contains the maximum number
  89480. * of bytes that may be stored in \a buffer. The
  89481. * callee must set it to the actual number of bytes
  89482. * stored (0 in case of error or end-of-stream) before
  89483. * returning.
  89484. * \param client_data The callee's client data set through
  89485. * FLAC__stream_decoder_init_*().
  89486. * \retval FLAC__StreamDecoderReadStatus
  89487. * The callee's return status. Note that the callback should return
  89488. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89489. * zero bytes were read and there is no more data to be read.
  89490. */
  89491. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89492. /** Signature for the seek callback.
  89493. *
  89494. * A function pointer matching this signature may be passed to
  89495. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89496. * called when the decoder needs to seek the input stream. The decoder
  89497. * will pass the absolute byte offset to seek to, 0 meaning the
  89498. * beginning of the stream.
  89499. *
  89500. * Here is an example of a seek callback for stdio streams:
  89501. * \code
  89502. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  89503. * {
  89504. * FILE *file = ((MyClientData*)client_data)->file;
  89505. * if(file == stdin)
  89506. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  89507. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  89508. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  89509. * else
  89510. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  89511. * }
  89512. * \endcode
  89513. *
  89514. * \note In general, FLAC__StreamDecoder functions which change the
  89515. * state should not be called on the \a decoder while in the callback.
  89516. *
  89517. * \param decoder The decoder instance calling the callback.
  89518. * \param absolute_byte_offset The offset from the beginning of the stream
  89519. * to seek to.
  89520. * \param client_data The callee's client data set through
  89521. * FLAC__stream_decoder_init_*().
  89522. * \retval FLAC__StreamDecoderSeekStatus
  89523. * The callee's return status.
  89524. */
  89525. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  89526. /** Signature for the tell callback.
  89527. *
  89528. * A function pointer matching this signature may be passed to
  89529. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89530. * called when the decoder wants to know the current position of the
  89531. * stream. The callback should return the byte offset from the
  89532. * beginning of the stream.
  89533. *
  89534. * Here is an example of a tell callback for stdio streams:
  89535. * \code
  89536. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  89537. * {
  89538. * FILE *file = ((MyClientData*)client_data)->file;
  89539. * off_t pos;
  89540. * if(file == stdin)
  89541. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  89542. * else if((pos = ftello(file)) < 0)
  89543. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  89544. * else {
  89545. * *absolute_byte_offset = (FLAC__uint64)pos;
  89546. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  89547. * }
  89548. * }
  89549. * \endcode
  89550. *
  89551. * \note In general, FLAC__StreamDecoder functions which change the
  89552. * state should not be called on the \a decoder while in the callback.
  89553. *
  89554. * \param decoder The decoder instance calling the callback.
  89555. * \param absolute_byte_offset A pointer to storage for the current offset
  89556. * from the beginning of the stream.
  89557. * \param client_data The callee's client data set through
  89558. * FLAC__stream_decoder_init_*().
  89559. * \retval FLAC__StreamDecoderTellStatus
  89560. * The callee's return status.
  89561. */
  89562. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  89563. /** Signature for the length callback.
  89564. *
  89565. * A function pointer matching this signature may be passed to
  89566. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89567. * called when the decoder wants to know the total length of the stream
  89568. * in bytes.
  89569. *
  89570. * Here is an example of a length callback for stdio streams:
  89571. * \code
  89572. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  89573. * {
  89574. * FILE *file = ((MyClientData*)client_data)->file;
  89575. * struct stat filestats;
  89576. *
  89577. * if(file == stdin)
  89578. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  89579. * else if(fstat(fileno(file), &filestats) != 0)
  89580. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  89581. * else {
  89582. * *stream_length = (FLAC__uint64)filestats.st_size;
  89583. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  89584. * }
  89585. * }
  89586. * \endcode
  89587. *
  89588. * \note In general, FLAC__StreamDecoder functions which change the
  89589. * state should not be called on the \a decoder while in the callback.
  89590. *
  89591. * \param decoder The decoder instance calling the callback.
  89592. * \param stream_length A pointer to storage for the length of the stream
  89593. * in bytes.
  89594. * \param client_data The callee's client data set through
  89595. * FLAC__stream_decoder_init_*().
  89596. * \retval FLAC__StreamDecoderLengthStatus
  89597. * The callee's return status.
  89598. */
  89599. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  89600. /** Signature for the EOF callback.
  89601. *
  89602. * A function pointer matching this signature may be passed to
  89603. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89604. * called when the decoder needs to know if the end of the stream has
  89605. * been reached.
  89606. *
  89607. * Here is an example of a EOF callback for stdio streams:
  89608. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  89609. * \code
  89610. * {
  89611. * FILE *file = ((MyClientData*)client_data)->file;
  89612. * return feof(file)? true : false;
  89613. * }
  89614. * \endcode
  89615. *
  89616. * \note In general, FLAC__StreamDecoder functions which change the
  89617. * state should not be called on the \a decoder while in the callback.
  89618. *
  89619. * \param decoder The decoder instance calling the callback.
  89620. * \param client_data The callee's client data set through
  89621. * FLAC__stream_decoder_init_*().
  89622. * \retval FLAC__bool
  89623. * \c true if the currently at the end of the stream, else \c false.
  89624. */
  89625. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  89626. /** Signature for the write callback.
  89627. *
  89628. * A function pointer matching this signature must be passed to one of
  89629. * the FLAC__stream_decoder_init_*() functions.
  89630. * The supplied function will be called when the decoder has decoded a
  89631. * single audio frame. The decoder will pass the frame metadata as well
  89632. * as an array of pointers (one for each channel) pointing to the
  89633. * decoded audio.
  89634. *
  89635. * \note In general, FLAC__StreamDecoder functions which change the
  89636. * state should not be called on the \a decoder while in the callback.
  89637. *
  89638. * \param decoder The decoder instance calling the callback.
  89639. * \param frame The description of the decoded frame. See
  89640. * FLAC__Frame.
  89641. * \param buffer An array of pointers to decoded channels of data.
  89642. * Each pointer will point to an array of signed
  89643. * samples of length \a frame->header.blocksize.
  89644. * Channels will be ordered according to the FLAC
  89645. * specification; see the documentation for the
  89646. * <A HREF="../format.html#frame_header">frame header</A>.
  89647. * \param client_data The callee's client data set through
  89648. * FLAC__stream_decoder_init_*().
  89649. * \retval FLAC__StreamDecoderWriteStatus
  89650. * The callee's return status.
  89651. */
  89652. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  89653. /** Signature for the metadata callback.
  89654. *
  89655. * A function pointer matching this signature must be passed to one of
  89656. * the FLAC__stream_decoder_init_*() functions.
  89657. * The supplied function will be called when the decoder has decoded a
  89658. * metadata block. In a valid FLAC file there will always be one
  89659. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  89660. * These will be supplied by the decoder in the same order as they
  89661. * appear in the stream and always before the first audio frame (i.e.
  89662. * write callback). The metadata block that is passed in must not be
  89663. * modified, and it doesn't live beyond the callback, so you should make
  89664. * a copy of it with FLAC__metadata_object_clone() if you will need it
  89665. * elsewhere. Since metadata blocks can potentially be large, by
  89666. * default the decoder only calls the metadata callback for the
  89667. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  89668. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  89669. *
  89670. * \note In general, FLAC__StreamDecoder functions which change the
  89671. * state should not be called on the \a decoder while in the callback.
  89672. *
  89673. * \param decoder The decoder instance calling the callback.
  89674. * \param metadata The decoded metadata block.
  89675. * \param client_data The callee's client data set through
  89676. * FLAC__stream_decoder_init_*().
  89677. */
  89678. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  89679. /** Signature for the error callback.
  89680. *
  89681. * A function pointer matching this signature must be passed to one of
  89682. * the FLAC__stream_decoder_init_*() functions.
  89683. * The supplied function will be called whenever an error occurs during
  89684. * decoding.
  89685. *
  89686. * \note In general, FLAC__StreamDecoder functions which change the
  89687. * state should not be called on the \a decoder while in the callback.
  89688. *
  89689. * \param decoder The decoder instance calling the callback.
  89690. * \param status The error encountered by the decoder.
  89691. * \param client_data The callee's client data set through
  89692. * FLAC__stream_decoder_init_*().
  89693. */
  89694. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  89695. /***********************************************************************
  89696. *
  89697. * Class constructor/destructor
  89698. *
  89699. ***********************************************************************/
  89700. /** Create a new stream decoder instance. The instance is created with
  89701. * default settings; see the individual FLAC__stream_decoder_set_*()
  89702. * functions for each setting's default.
  89703. *
  89704. * \retval FLAC__StreamDecoder*
  89705. * \c NULL if there was an error allocating memory, else the new instance.
  89706. */
  89707. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  89708. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  89709. *
  89710. * \param decoder A pointer to an existing decoder.
  89711. * \assert
  89712. * \code decoder != NULL \endcode
  89713. */
  89714. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  89715. /***********************************************************************
  89716. *
  89717. * Public class method prototypes
  89718. *
  89719. ***********************************************************************/
  89720. /** Set the serial number for the FLAC stream within the Ogg container.
  89721. * The default behavior is to use the serial number of the first Ogg
  89722. * page. Setting a serial number here will explicitly specify which
  89723. * stream is to be decoded.
  89724. *
  89725. * \note
  89726. * This does not need to be set for native FLAC decoding.
  89727. *
  89728. * \default \c use serial number of first page
  89729. * \param decoder A decoder instance to set.
  89730. * \param serial_number See above.
  89731. * \assert
  89732. * \code decoder != NULL \endcode
  89733. * \retval FLAC__bool
  89734. * \c false if the decoder is already initialized, else \c true.
  89735. */
  89736. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  89737. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  89738. * compute the MD5 signature of the unencoded audio data while decoding
  89739. * and compare it to the signature from the STREAMINFO block, if it
  89740. * exists, during FLAC__stream_decoder_finish().
  89741. *
  89742. * MD5 signature checking will be turned off (until the next
  89743. * FLAC__stream_decoder_reset()) if there is no signature in the
  89744. * STREAMINFO block or when a seek is attempted.
  89745. *
  89746. * Clients that do not use the MD5 check should leave this off to speed
  89747. * up decoding.
  89748. *
  89749. * \default \c false
  89750. * \param decoder A decoder instance to set.
  89751. * \param value Flag value (see above).
  89752. * \assert
  89753. * \code decoder != NULL \endcode
  89754. * \retval FLAC__bool
  89755. * \c false if the decoder is already initialized, else \c true.
  89756. */
  89757. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  89758. /** Direct the decoder to pass on all metadata blocks of type \a type.
  89759. *
  89760. * \default By default, only the \c STREAMINFO block is returned via the
  89761. * metadata callback.
  89762. * \param decoder A decoder instance to set.
  89763. * \param type See above.
  89764. * \assert
  89765. * \code decoder != NULL \endcode
  89766. * \a type is valid
  89767. * \retval FLAC__bool
  89768. * \c false if the decoder is already initialized, else \c true.
  89769. */
  89770. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89771. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  89772. * given \a id.
  89773. *
  89774. * \default By default, only the \c STREAMINFO block is returned via the
  89775. * metadata callback.
  89776. * \param decoder A decoder instance to set.
  89777. * \param id See above.
  89778. * \assert
  89779. * \code decoder != NULL \endcode
  89780. * \code id != NULL \endcode
  89781. * \retval FLAC__bool
  89782. * \c false if the decoder is already initialized, else \c true.
  89783. */
  89784. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89785. /** Direct the decoder to pass on all metadata blocks of any type.
  89786. *
  89787. * \default By default, only the \c STREAMINFO block is returned via the
  89788. * metadata callback.
  89789. * \param decoder A decoder instance to set.
  89790. * \assert
  89791. * \code decoder != NULL \endcode
  89792. * \retval FLAC__bool
  89793. * \c false if the decoder is already initialized, else \c true.
  89794. */
  89795. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  89796. /** Direct the decoder to filter out all metadata blocks of type \a type.
  89797. *
  89798. * \default By default, only the \c STREAMINFO block is returned via the
  89799. * metadata callback.
  89800. * \param decoder A decoder instance to set.
  89801. * \param type See above.
  89802. * \assert
  89803. * \code decoder != NULL \endcode
  89804. * \a type is valid
  89805. * \retval FLAC__bool
  89806. * \c false if the decoder is already initialized, else \c true.
  89807. */
  89808. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89809. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  89810. * the given \a id.
  89811. *
  89812. * \default By default, only the \c STREAMINFO block is returned via the
  89813. * metadata callback.
  89814. * \param decoder A decoder instance to set.
  89815. * \param id See above.
  89816. * \assert
  89817. * \code decoder != NULL \endcode
  89818. * \code id != NULL \endcode
  89819. * \retval FLAC__bool
  89820. * \c false if the decoder is already initialized, else \c true.
  89821. */
  89822. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89823. /** Direct the decoder to filter out all metadata blocks of any type.
  89824. *
  89825. * \default By default, only the \c STREAMINFO block is returned via the
  89826. * metadata callback.
  89827. * \param decoder A decoder instance to set.
  89828. * \assert
  89829. * \code decoder != NULL \endcode
  89830. * \retval FLAC__bool
  89831. * \c false if the decoder is already initialized, else \c true.
  89832. */
  89833. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  89834. /** Get the current decoder state.
  89835. *
  89836. * \param decoder A decoder instance to query.
  89837. * \assert
  89838. * \code decoder != NULL \endcode
  89839. * \retval FLAC__StreamDecoderState
  89840. * The current decoder state.
  89841. */
  89842. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  89843. /** Get the current decoder state as a C string.
  89844. *
  89845. * \param decoder A decoder instance to query.
  89846. * \assert
  89847. * \code decoder != NULL \endcode
  89848. * \retval const char *
  89849. * The decoder state as a C string. Do not modify the contents.
  89850. */
  89851. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  89852. /** Get the "MD5 signature checking" flag.
  89853. * This is the value of the setting, not whether or not the decoder is
  89854. * currently checking the MD5 (remember, it can be turned off automatically
  89855. * by a seek). When the decoder is reset the flag will be restored to the
  89856. * value returned by this function.
  89857. *
  89858. * \param decoder A decoder instance to query.
  89859. * \assert
  89860. * \code decoder != NULL \endcode
  89861. * \retval FLAC__bool
  89862. * See above.
  89863. */
  89864. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  89865. /** Get the total number of samples in the stream being decoded.
  89866. * Will only be valid after decoding has started and will contain the
  89867. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  89868. *
  89869. * \param decoder A decoder instance to query.
  89870. * \assert
  89871. * \code decoder != NULL \endcode
  89872. * \retval unsigned
  89873. * See above.
  89874. */
  89875. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  89876. /** Get the current number of channels in the stream being decoded.
  89877. * Will only be valid after decoding has started and will contain the
  89878. * value from the most recently decoded frame header.
  89879. *
  89880. * \param decoder A decoder instance to query.
  89881. * \assert
  89882. * \code decoder != NULL \endcode
  89883. * \retval unsigned
  89884. * See above.
  89885. */
  89886. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  89887. /** Get the current channel assignment in the stream being decoded.
  89888. * Will only be valid after decoding has started and will contain the
  89889. * value from the most recently decoded frame header.
  89890. *
  89891. * \param decoder A decoder instance to query.
  89892. * \assert
  89893. * \code decoder != NULL \endcode
  89894. * \retval FLAC__ChannelAssignment
  89895. * See above.
  89896. */
  89897. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  89898. /** Get the current sample resolution in the stream being decoded.
  89899. * Will only be valid after decoding has started and will contain the
  89900. * value from the most recently decoded frame header.
  89901. *
  89902. * \param decoder A decoder instance to query.
  89903. * \assert
  89904. * \code decoder != NULL \endcode
  89905. * \retval unsigned
  89906. * See above.
  89907. */
  89908. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  89909. /** Get the current sample rate in Hz of the stream being decoded.
  89910. * Will only be valid after decoding has started and will contain the
  89911. * value from the most recently decoded frame header.
  89912. *
  89913. * \param decoder A decoder instance to query.
  89914. * \assert
  89915. * \code decoder != NULL \endcode
  89916. * \retval unsigned
  89917. * See above.
  89918. */
  89919. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  89920. /** Get the current blocksize of the stream being decoded.
  89921. * Will only be valid after decoding has started and will contain the
  89922. * value from the most recently decoded frame header.
  89923. *
  89924. * \param decoder A decoder instance to query.
  89925. * \assert
  89926. * \code decoder != NULL \endcode
  89927. * \retval unsigned
  89928. * See above.
  89929. */
  89930. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  89931. /** Returns the decoder's current read position within the stream.
  89932. * The position is the byte offset from the start of the stream.
  89933. * Bytes before this position have been fully decoded. Note that
  89934. * there may still be undecoded bytes in the decoder's read FIFO.
  89935. * The returned position is correct even after a seek.
  89936. *
  89937. * \warning This function currently only works for native FLAC,
  89938. * not Ogg FLAC streams.
  89939. *
  89940. * \param decoder A decoder instance to query.
  89941. * \param position Address at which to return the desired position.
  89942. * \assert
  89943. * \code decoder != NULL \endcode
  89944. * \code position != NULL \endcode
  89945. * \retval FLAC__bool
  89946. * \c true if successful, \c false if the stream is not native FLAC,
  89947. * or there was an error from the 'tell' callback or it returned
  89948. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  89949. */
  89950. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  89951. /** Initialize the decoder instance to decode native FLAC streams.
  89952. *
  89953. * This flavor of initialization sets up the decoder to decode from a
  89954. * native FLAC stream. I/O is performed via callbacks to the client.
  89955. * For decoding from a plain file via filename or open FILE*,
  89956. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  89957. * provide a simpler interface.
  89958. *
  89959. * This function should be called after FLAC__stream_decoder_new() and
  89960. * FLAC__stream_decoder_set_*() but before any of the
  89961. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89962. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89963. * if initialization succeeded.
  89964. *
  89965. * \param decoder An uninitialized decoder instance.
  89966. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  89967. * pointer must not be \c NULL.
  89968. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  89969. * pointer may be \c NULL if seeking is not
  89970. * supported. If \a seek_callback is not \c NULL then a
  89971. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  89972. * Alternatively, a dummy seek callback that just
  89973. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89974. * may also be supplied, all though this is slightly
  89975. * less efficient for the decoder.
  89976. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  89977. * pointer may be \c NULL if not supported by the client. If
  89978. * \a seek_callback is not \c NULL then a
  89979. * \a tell_callback must also be supplied.
  89980. * Alternatively, a dummy tell callback that just
  89981. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89982. * may also be supplied, all though this is slightly
  89983. * less efficient for the decoder.
  89984. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  89985. * pointer may be \c NULL if not supported by the client. If
  89986. * \a seek_callback is not \c NULL then a
  89987. * \a length_callback must also be supplied.
  89988. * Alternatively, a dummy length callback that just
  89989. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89990. * may also be supplied, all though this is slightly
  89991. * less efficient for the decoder.
  89992. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  89993. * pointer may be \c NULL if not supported by the client. If
  89994. * \a seek_callback is not \c NULL then a
  89995. * \a eof_callback must also be supplied.
  89996. * Alternatively, a dummy length callback that just
  89997. * returns \c false
  89998. * may also be supplied, all though this is slightly
  89999. * less efficient for the decoder.
  90000. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90001. * pointer must not be \c NULL.
  90002. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90003. * pointer may be \c NULL if the callback is not
  90004. * desired.
  90005. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90006. * pointer must not be \c NULL.
  90007. * \param client_data This value will be supplied to callbacks in their
  90008. * \a client_data argument.
  90009. * \assert
  90010. * \code decoder != NULL \endcode
  90011. * \retval FLAC__StreamDecoderInitStatus
  90012. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90013. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90014. */
  90015. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  90016. FLAC__StreamDecoder *decoder,
  90017. FLAC__StreamDecoderReadCallback read_callback,
  90018. FLAC__StreamDecoderSeekCallback seek_callback,
  90019. FLAC__StreamDecoderTellCallback tell_callback,
  90020. FLAC__StreamDecoderLengthCallback length_callback,
  90021. FLAC__StreamDecoderEofCallback eof_callback,
  90022. FLAC__StreamDecoderWriteCallback write_callback,
  90023. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90024. FLAC__StreamDecoderErrorCallback error_callback,
  90025. void *client_data
  90026. );
  90027. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90028. *
  90029. * This flavor of initialization sets up the decoder to decode from a
  90030. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90031. * client. For decoding from a plain file via filename or open FILE*,
  90032. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90033. * provide a simpler interface.
  90034. *
  90035. * This function should be called after FLAC__stream_decoder_new() and
  90036. * FLAC__stream_decoder_set_*() but before any of the
  90037. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90038. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90039. * if initialization succeeded.
  90040. *
  90041. * \note Support for Ogg FLAC in the library is optional. If this
  90042. * library has been built without support for Ogg FLAC, this function
  90043. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90044. *
  90045. * \param decoder An uninitialized decoder instance.
  90046. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90047. * pointer must not be \c NULL.
  90048. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90049. * pointer may be \c NULL if seeking is not
  90050. * supported. If \a seek_callback is not \c NULL then a
  90051. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90052. * Alternatively, a dummy seek callback that just
  90053. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90054. * may also be supplied, all though this is slightly
  90055. * less efficient for the decoder.
  90056. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90057. * pointer may be \c NULL if not supported by the client. If
  90058. * \a seek_callback is not \c NULL then a
  90059. * \a tell_callback must also be supplied.
  90060. * Alternatively, a dummy tell callback that just
  90061. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90062. * may also be supplied, all though this is slightly
  90063. * less efficient for the decoder.
  90064. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90065. * pointer may be \c NULL if not supported by the client. If
  90066. * \a seek_callback is not \c NULL then a
  90067. * \a length_callback must also be supplied.
  90068. * Alternatively, a dummy length callback that just
  90069. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90070. * may also be supplied, all though this is slightly
  90071. * less efficient for the decoder.
  90072. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90073. * pointer may be \c NULL if not supported by the client. If
  90074. * \a seek_callback is not \c NULL then a
  90075. * \a eof_callback must also be supplied.
  90076. * Alternatively, a dummy length callback that just
  90077. * returns \c false
  90078. * may also be supplied, all though this is slightly
  90079. * less efficient for the decoder.
  90080. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90081. * pointer must not be \c NULL.
  90082. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90083. * pointer may be \c NULL if the callback is not
  90084. * desired.
  90085. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90086. * pointer must not be \c NULL.
  90087. * \param client_data This value will be supplied to callbacks in their
  90088. * \a client_data argument.
  90089. * \assert
  90090. * \code decoder != NULL \endcode
  90091. * \retval FLAC__StreamDecoderInitStatus
  90092. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90093. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90094. */
  90095. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90096. FLAC__StreamDecoder *decoder,
  90097. FLAC__StreamDecoderReadCallback read_callback,
  90098. FLAC__StreamDecoderSeekCallback seek_callback,
  90099. FLAC__StreamDecoderTellCallback tell_callback,
  90100. FLAC__StreamDecoderLengthCallback length_callback,
  90101. FLAC__StreamDecoderEofCallback eof_callback,
  90102. FLAC__StreamDecoderWriteCallback write_callback,
  90103. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90104. FLAC__StreamDecoderErrorCallback error_callback,
  90105. void *client_data
  90106. );
  90107. /** Initialize the decoder instance to decode native FLAC files.
  90108. *
  90109. * This flavor of initialization sets up the decoder to decode from a
  90110. * plain native FLAC file. For non-stdio streams, you must use
  90111. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90112. *
  90113. * This function should be called after FLAC__stream_decoder_new() and
  90114. * FLAC__stream_decoder_set_*() but before any of the
  90115. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90116. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90117. * if initialization succeeded.
  90118. *
  90119. * \param decoder An uninitialized decoder instance.
  90120. * \param file An open FLAC file. The file should have been
  90121. * opened with mode \c "rb" and rewound. The file
  90122. * becomes owned by the decoder and should not be
  90123. * manipulated by the client while decoding.
  90124. * Unless \a file is \c stdin, it will be closed
  90125. * when FLAC__stream_decoder_finish() is called.
  90126. * Note however that seeking will not work when
  90127. * decoding from \c stdout since it is not seekable.
  90128. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90129. * pointer must not be \c NULL.
  90130. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90131. * pointer may be \c NULL if the callback is not
  90132. * desired.
  90133. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90134. * pointer must not be \c NULL.
  90135. * \param client_data This value will be supplied to callbacks in their
  90136. * \a client_data argument.
  90137. * \assert
  90138. * \code decoder != NULL \endcode
  90139. * \code file != NULL \endcode
  90140. * \retval FLAC__StreamDecoderInitStatus
  90141. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90142. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90143. */
  90144. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90145. FLAC__StreamDecoder *decoder,
  90146. FILE *file,
  90147. FLAC__StreamDecoderWriteCallback write_callback,
  90148. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90149. FLAC__StreamDecoderErrorCallback error_callback,
  90150. void *client_data
  90151. );
  90152. /** Initialize the decoder instance to decode Ogg FLAC files.
  90153. *
  90154. * This flavor of initialization sets up the decoder to decode from a
  90155. * plain Ogg FLAC file. For non-stdio streams, you must use
  90156. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90157. *
  90158. * This function should be called after FLAC__stream_decoder_new() and
  90159. * FLAC__stream_decoder_set_*() but before any of the
  90160. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90161. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90162. * if initialization succeeded.
  90163. *
  90164. * \note Support for Ogg FLAC in the library is optional. If this
  90165. * library has been built without support for Ogg FLAC, this function
  90166. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90167. *
  90168. * \param decoder An uninitialized decoder instance.
  90169. * \param file An open FLAC file. The file should have been
  90170. * opened with mode \c "rb" and rewound. The file
  90171. * becomes owned by the decoder and should not be
  90172. * manipulated by the client while decoding.
  90173. * Unless \a file is \c stdin, it will be closed
  90174. * when FLAC__stream_decoder_finish() is called.
  90175. * Note however that seeking will not work when
  90176. * decoding from \c stdout since it is not seekable.
  90177. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90178. * pointer must not be \c NULL.
  90179. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90180. * pointer may be \c NULL if the callback is not
  90181. * desired.
  90182. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90183. * pointer must not be \c NULL.
  90184. * \param client_data This value will be supplied to callbacks in their
  90185. * \a client_data argument.
  90186. * \assert
  90187. * \code decoder != NULL \endcode
  90188. * \code file != NULL \endcode
  90189. * \retval FLAC__StreamDecoderInitStatus
  90190. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90191. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90192. */
  90193. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90194. FLAC__StreamDecoder *decoder,
  90195. FILE *file,
  90196. FLAC__StreamDecoderWriteCallback write_callback,
  90197. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90198. FLAC__StreamDecoderErrorCallback error_callback,
  90199. void *client_data
  90200. );
  90201. /** Initialize the decoder instance to decode native FLAC files.
  90202. *
  90203. * This flavor of initialization sets up the decoder to decode from a plain
  90204. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90205. * example, with Unicode filenames on Windows), you must use
  90206. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90207. * and provide callbacks for the I/O.
  90208. *
  90209. * This function should be called after FLAC__stream_decoder_new() and
  90210. * FLAC__stream_decoder_set_*() but before any of the
  90211. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90212. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90213. * if initialization succeeded.
  90214. *
  90215. * \param decoder An uninitialized decoder instance.
  90216. * \param filename The name of the file to decode from. The file will
  90217. * be opened with fopen(). Use \c NULL to decode from
  90218. * \c stdin. Note that \c stdin is not seekable.
  90219. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90220. * pointer must not be \c NULL.
  90221. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90222. * pointer may be \c NULL if the callback is not
  90223. * desired.
  90224. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90225. * pointer must not be \c NULL.
  90226. * \param client_data This value will be supplied to callbacks in their
  90227. * \a client_data argument.
  90228. * \assert
  90229. * \code decoder != NULL \endcode
  90230. * \retval FLAC__StreamDecoderInitStatus
  90231. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90232. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90233. */
  90234. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90235. FLAC__StreamDecoder *decoder,
  90236. const char *filename,
  90237. FLAC__StreamDecoderWriteCallback write_callback,
  90238. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90239. FLAC__StreamDecoderErrorCallback error_callback,
  90240. void *client_data
  90241. );
  90242. /** Initialize the decoder instance to decode Ogg FLAC files.
  90243. *
  90244. * This flavor of initialization sets up the decoder to decode from a plain
  90245. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90246. * example, with Unicode filenames on Windows), you must use
  90247. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90248. * and provide callbacks for the I/O.
  90249. *
  90250. * This function should be called after FLAC__stream_decoder_new() and
  90251. * FLAC__stream_decoder_set_*() but before any of the
  90252. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90253. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90254. * if initialization succeeded.
  90255. *
  90256. * \note Support for Ogg FLAC in the library is optional. If this
  90257. * library has been built without support for Ogg FLAC, this function
  90258. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90259. *
  90260. * \param decoder An uninitialized decoder instance.
  90261. * \param filename The name of the file to decode from. The file will
  90262. * be opened with fopen(). Use \c NULL to decode from
  90263. * \c stdin. Note that \c stdin is not seekable.
  90264. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90265. * pointer must not be \c NULL.
  90266. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90267. * pointer may be \c NULL if the callback is not
  90268. * desired.
  90269. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90270. * pointer must not be \c NULL.
  90271. * \param client_data This value will be supplied to callbacks in their
  90272. * \a client_data argument.
  90273. * \assert
  90274. * \code decoder != NULL \endcode
  90275. * \retval FLAC__StreamDecoderInitStatus
  90276. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90277. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90278. */
  90279. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90280. FLAC__StreamDecoder *decoder,
  90281. const char *filename,
  90282. FLAC__StreamDecoderWriteCallback write_callback,
  90283. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90284. FLAC__StreamDecoderErrorCallback error_callback,
  90285. void *client_data
  90286. );
  90287. /** Finish the decoding process.
  90288. * Flushes the decoding buffer, releases resources, resets the decoder
  90289. * settings to their defaults, and returns the decoder state to
  90290. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90291. *
  90292. * In the event of a prematurely-terminated decode, it is not strictly
  90293. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90294. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90295. * with a FLAC__stream_decoder_finish().
  90296. *
  90297. * \param decoder An uninitialized decoder instance.
  90298. * \assert
  90299. * \code decoder != NULL \endcode
  90300. * \retval FLAC__bool
  90301. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90302. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90303. * signature does not match the one computed by the decoder; else
  90304. * \c true.
  90305. */
  90306. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90307. /** Flush the stream input.
  90308. * The decoder's input buffer will be cleared and the state set to
  90309. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90310. * off MD5 checking.
  90311. *
  90312. * \param decoder A decoder instance.
  90313. * \assert
  90314. * \code decoder != NULL \endcode
  90315. * \retval FLAC__bool
  90316. * \c true if successful, else \c false if a memory allocation
  90317. * error occurs (in which case the state will be set to
  90318. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90319. */
  90320. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90321. /** Reset the decoding process.
  90322. * The decoder's input buffer will be cleared and the state set to
  90323. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90324. * FLAC__stream_decoder_finish() except that the settings are
  90325. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90326. * before decoding again. MD5 checking will be restored to its original
  90327. * setting.
  90328. *
  90329. * If the decoder is seekable, or was initialized with
  90330. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90331. * the decoder will also attempt to seek to the beginning of the file.
  90332. * If this rewind fails, this function will return \c false. It follows
  90333. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90334. * \c stdin.
  90335. *
  90336. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90337. * and is not seekable (i.e. no seek callback was provided or the seek
  90338. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90339. * is the duty of the client to start feeding data from the beginning of
  90340. * the stream on the next FLAC__stream_decoder_process() or
  90341. * FLAC__stream_decoder_process_interleaved() call.
  90342. *
  90343. * \param decoder A decoder instance.
  90344. * \assert
  90345. * \code decoder != NULL \endcode
  90346. * \retval FLAC__bool
  90347. * \c true if successful, else \c false if a memory allocation occurs
  90348. * (in which case the state will be set to
  90349. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90350. * occurs (the state will be unchanged).
  90351. */
  90352. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90353. /** Decode one metadata block or audio frame.
  90354. * This version instructs the decoder to decode a either a single metadata
  90355. * block or a single frame and stop, unless the callbacks return a fatal
  90356. * error or the read callback returns
  90357. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90358. *
  90359. * As the decoder needs more input it will call the read callback.
  90360. * Depending on what was decoded, the metadata or write callback will be
  90361. * called with the decoded metadata block or audio frame.
  90362. *
  90363. * Unless there is a fatal read error or end of stream, this function
  90364. * will return once one whole frame is decoded. In other words, if the
  90365. * stream is not synchronized or points to a corrupt frame header, the
  90366. * decoder will continue to try and resync until it gets to a valid
  90367. * frame, then decode one frame, then return. If the decoder points to
  90368. * a frame whose frame CRC in the frame footer does not match the
  90369. * computed frame CRC, this function will issue a
  90370. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90371. * error callback, and return, having decoded one complete, although
  90372. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90373. * correct length to the write callback.)
  90374. *
  90375. * \param decoder An initialized decoder instance.
  90376. * \assert
  90377. * \code decoder != NULL \endcode
  90378. * \retval FLAC__bool
  90379. * \c false if any fatal read, write, or memory allocation error
  90380. * occurred (meaning decoding must stop), else \c true; for more
  90381. * information about the decoder, check the decoder state with
  90382. * FLAC__stream_decoder_get_state().
  90383. */
  90384. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90385. /** Decode until the end of the metadata.
  90386. * This version instructs the decoder to decode from the current position
  90387. * and continue until all the metadata has been read, or until the
  90388. * callbacks return a fatal error or the read callback returns
  90389. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90390. *
  90391. * As the decoder needs more input it will call the read callback.
  90392. * As each metadata block is decoded, the metadata callback will be called
  90393. * with the decoded metadata.
  90394. *
  90395. * \param decoder An initialized decoder instance.
  90396. * \assert
  90397. * \code decoder != NULL \endcode
  90398. * \retval FLAC__bool
  90399. * \c false if any fatal read, write, or memory allocation error
  90400. * occurred (meaning decoding must stop), else \c true; for more
  90401. * information about the decoder, check the decoder state with
  90402. * FLAC__stream_decoder_get_state().
  90403. */
  90404. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90405. /** Decode until the end of the stream.
  90406. * This version instructs the decoder to decode from the current position
  90407. * and continue until the end of stream (the read callback returns
  90408. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90409. * callbacks return a fatal error.
  90410. *
  90411. * As the decoder needs more input it will call the read callback.
  90412. * As each metadata block and frame is decoded, the metadata or write
  90413. * callback will be called with the decoded metadata or frame.
  90414. *
  90415. * \param decoder An initialized decoder instance.
  90416. * \assert
  90417. * \code decoder != NULL \endcode
  90418. * \retval FLAC__bool
  90419. * \c false if any fatal read, write, or memory allocation error
  90420. * occurred (meaning decoding must stop), else \c true; for more
  90421. * information about the decoder, check the decoder state with
  90422. * FLAC__stream_decoder_get_state().
  90423. */
  90424. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90425. /** Skip one audio frame.
  90426. * This version instructs the decoder to 'skip' a single frame and stop,
  90427. * unless the callbacks return a fatal error or the read callback returns
  90428. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90429. *
  90430. * The decoding flow is the same as what occurs when
  90431. * FLAC__stream_decoder_process_single() is called to process an audio
  90432. * frame, except that this function does not decode the parsed data into
  90433. * PCM or call the write callback. The integrity of the frame is still
  90434. * checked the same way as in the other process functions.
  90435. *
  90436. * This function will return once one whole frame is skipped, in the
  90437. * same way that FLAC__stream_decoder_process_single() will return once
  90438. * one whole frame is decoded.
  90439. *
  90440. * This function can be used in more quickly determining FLAC frame
  90441. * boundaries when decoding of the actual data is not needed, for
  90442. * example when an application is separating a FLAC stream into frames
  90443. * for editing or storing in a container. To do this, the application
  90444. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90445. * to the next frame, then use
  90446. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90447. * boundary.
  90448. *
  90449. * This function should only be called when the stream has advanced
  90450. * past all the metadata, otherwise it will return \c false.
  90451. *
  90452. * \param decoder An initialized decoder instance not in a metadata
  90453. * state.
  90454. * \assert
  90455. * \code decoder != NULL \endcode
  90456. * \retval FLAC__bool
  90457. * \c false if any fatal read, write, or memory allocation error
  90458. * occurred (meaning decoding must stop), or if the decoder
  90459. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90460. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90461. * information about the decoder, check the decoder state with
  90462. * FLAC__stream_decoder_get_state().
  90463. */
  90464. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90465. /** Flush the input and seek to an absolute sample.
  90466. * Decoding will resume at the given sample. Note that because of
  90467. * this, the next write callback may contain a partial block. The
  90468. * client must support seeking the input or this function will fail
  90469. * and return \c false. Furthermore, if the decoder state is
  90470. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90471. * with FLAC__stream_decoder_flush() or reset with
  90472. * FLAC__stream_decoder_reset() before decoding can continue.
  90473. *
  90474. * \param decoder A decoder instance.
  90475. * \param sample The target sample number to seek to.
  90476. * \assert
  90477. * \code decoder != NULL \endcode
  90478. * \retval FLAC__bool
  90479. * \c true if successful, else \c false.
  90480. */
  90481. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90482. /* \} */
  90483. #ifdef __cplusplus
  90484. }
  90485. #endif
  90486. #endif
  90487. /*** End of inlined file: stream_decoder.h ***/
  90488. /*** Start of inlined file: stream_encoder.h ***/
  90489. #ifndef FLAC__STREAM_ENCODER_H
  90490. #define FLAC__STREAM_ENCODER_H
  90491. #include <stdio.h> /* for FILE */
  90492. #ifdef __cplusplus
  90493. extern "C" {
  90494. #endif
  90495. /** \file include/FLAC/stream_encoder.h
  90496. *
  90497. * \brief
  90498. * This module contains the functions which implement the stream
  90499. * encoder.
  90500. *
  90501. * See the detailed documentation in the
  90502. * \link flac_stream_encoder stream encoder \endlink module.
  90503. */
  90504. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  90505. * \ingroup flac
  90506. *
  90507. * \brief
  90508. * This module describes the encoder layers provided by libFLAC.
  90509. *
  90510. * The stream encoder can be used to encode complete streams either to the
  90511. * client via callbacks, or directly to a file, depending on how it is
  90512. * initialized. When encoding via callbacks, the client provides a write
  90513. * callback which will be called whenever FLAC data is ready to be written.
  90514. * If the client also supplies a seek callback, the encoder will also
  90515. * automatically handle the writing back of metadata discovered while
  90516. * encoding, like stream info, seek points offsets, etc. When encoding to
  90517. * a file, the client needs only supply a filename or open \c FILE* and an
  90518. * optional progress callback for periodic notification of progress; the
  90519. * write and seek callbacks are supplied internally. For more info see the
  90520. * \link flac_stream_encoder stream encoder \endlink module.
  90521. */
  90522. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  90523. * \ingroup flac_encoder
  90524. *
  90525. * \brief
  90526. * This module contains the functions which implement the stream
  90527. * encoder.
  90528. *
  90529. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  90530. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  90531. *
  90532. * The basic usage of this encoder is as follows:
  90533. * - The program creates an instance of an encoder using
  90534. * FLAC__stream_encoder_new().
  90535. * - The program overrides the default settings using
  90536. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  90537. * functions should be called:
  90538. * - FLAC__stream_encoder_set_channels()
  90539. * - FLAC__stream_encoder_set_bits_per_sample()
  90540. * - FLAC__stream_encoder_set_sample_rate()
  90541. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  90542. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  90543. * - If the application wants to control the compression level or set its own
  90544. * metadata, then the following should also be called:
  90545. * - FLAC__stream_encoder_set_compression_level()
  90546. * - FLAC__stream_encoder_set_verify()
  90547. * - FLAC__stream_encoder_set_metadata()
  90548. * - The rest of the set functions should only be called if the client needs
  90549. * exact control over how the audio is compressed; thorough understanding
  90550. * of the FLAC format is necessary to achieve good results.
  90551. * - The program initializes the instance to validate the settings and
  90552. * prepare for encoding using
  90553. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  90554. * or FLAC__stream_encoder_init_file() for native FLAC
  90555. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  90556. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  90557. * - The program calls FLAC__stream_encoder_process() or
  90558. * FLAC__stream_encoder_process_interleaved() to encode data, which
  90559. * subsequently calls the callbacks when there is encoder data ready
  90560. * to be written.
  90561. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  90562. * which causes the encoder to encode any data still in its input pipe,
  90563. * update the metadata with the final encoding statistics if output
  90564. * seeking is possible, and finally reset the encoder to the
  90565. * uninitialized state.
  90566. * - The instance may be used again or deleted with
  90567. * FLAC__stream_encoder_delete().
  90568. *
  90569. * In more detail, the stream encoder functions similarly to the
  90570. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  90571. * callbacks and more options. Typically the client will create a new
  90572. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  90573. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  90574. * calling one of the FLAC__stream_encoder_init_*() functions.
  90575. *
  90576. * Unlike the decoders, the stream encoder has many options that can
  90577. * affect the speed and compression ratio. When setting these parameters
  90578. * you should have some basic knowledge of the format (see the
  90579. * <A HREF="../documentation.html#format">user-level documentation</A>
  90580. * or the <A HREF="../format.html">formal description</A>). The
  90581. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  90582. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  90583. * functions will do this, so make sure to pay attention to the state
  90584. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  90585. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  90586. * before FLAC__stream_encoder_init_*() will take on the defaults from
  90587. * the constructor.
  90588. *
  90589. * There are three initialization functions for native FLAC, one for
  90590. * setting up the encoder to encode FLAC data to the client via
  90591. * callbacks, and two for encoding directly to a file.
  90592. *
  90593. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  90594. * You must also supply a write callback which will be called anytime
  90595. * there is raw encoded data to write. If the client can seek the output
  90596. * it is best to also supply seek and tell callbacks, as this allows the
  90597. * encoder to go back after encoding is finished to write back
  90598. * information that was collected while encoding, like seek point offsets,
  90599. * frame sizes, etc.
  90600. *
  90601. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  90602. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  90603. * filename or open \c FILE*; the encoder will handle all the callbacks
  90604. * internally. You may also supply a progress callback for periodic
  90605. * notification of the encoding progress.
  90606. *
  90607. * There are three similarly-named init functions for encoding to Ogg
  90608. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  90609. * library has been built with Ogg support.
  90610. *
  90611. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  90612. * call the write callback several times, once with the \c fLaC signature,
  90613. * and once for each encoded metadata block. Note that for Ogg FLAC
  90614. * encoding you will usually get at least twice the number of callbacks than
  90615. * with native FLAC, one for the Ogg page header and one for the page body.
  90616. *
  90617. * After initializing the instance, the client may feed audio data to the
  90618. * encoder in one of two ways:
  90619. *
  90620. * - Channel separate, through FLAC__stream_encoder_process() - The client
  90621. * will pass an array of pointers to buffers, one for each channel, to
  90622. * the encoder, each of the same length. The samples need not be
  90623. * block-aligned, but each channel should have the same number of samples.
  90624. * - Channel interleaved, through
  90625. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  90626. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  90627. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  90628. * Again, the samples need not be block-aligned but they must be
  90629. * sample-aligned, i.e. the first value should be channel0_sample0 and
  90630. * the last value channelN_sampleM.
  90631. *
  90632. * Note that for either process call, each sample in the buffers should be a
  90633. * signed integer, right-justified to the resolution set by
  90634. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  90635. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  90636. *
  90637. * When the client is finished encoding data, it calls
  90638. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  90639. * data still in its input pipe, and call the metadata callback with the
  90640. * final encoding statistics. Then the instance may be deleted with
  90641. * FLAC__stream_encoder_delete() or initialized again to encode another
  90642. * stream.
  90643. *
  90644. * For programs that write their own metadata, but that do not know the
  90645. * actual metadata until after encoding, it is advantageous to instruct
  90646. * the encoder to write a PADDING block of the correct size, so that
  90647. * instead of rewriting the whole stream after encoding, the program can
  90648. * just overwrite the PADDING block. If only the maximum size of the
  90649. * metadata is known, the program can write a slightly larger padding
  90650. * block, then split it after encoding.
  90651. *
  90652. * Make sure you understand how lengths are calculated. All FLAC metadata
  90653. * blocks have a 4 byte header which contains the type and length. This
  90654. * length does not include the 4 bytes of the header. See the format page
  90655. * for the specification of metadata blocks and their lengths.
  90656. *
  90657. * \note
  90658. * If you are writing the FLAC data to a file via callbacks, make sure it
  90659. * is open for update (e.g. mode "w+" for stdio streams). This is because
  90660. * after the first encoding pass, the encoder will try to seek back to the
  90661. * beginning of the stream, to the STREAMINFO block, to write some data
  90662. * there. (If using FLAC__stream_encoder_init*_file() or
  90663. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  90664. *
  90665. * \note
  90666. * The "set" functions may only be called when the encoder is in the
  90667. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  90668. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  90669. * before FLAC__stream_encoder_init_*(). If this is the case they will
  90670. * return \c true, otherwise \c false.
  90671. *
  90672. * \note
  90673. * FLAC__stream_encoder_finish() resets all settings to the constructor
  90674. * defaults.
  90675. *
  90676. * \{
  90677. */
  90678. /** State values for a FLAC__StreamEncoder.
  90679. *
  90680. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  90681. *
  90682. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  90683. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  90684. * must be deleted with FLAC__stream_encoder_delete().
  90685. */
  90686. typedef enum {
  90687. FLAC__STREAM_ENCODER_OK = 0,
  90688. /**< The encoder is in the normal OK state and samples can be processed. */
  90689. FLAC__STREAM_ENCODER_UNINITIALIZED,
  90690. /**< The encoder is in the uninitialized state; one of the
  90691. * FLAC__stream_encoder_init_*() functions must be called before samples
  90692. * can be processed.
  90693. */
  90694. FLAC__STREAM_ENCODER_OGG_ERROR,
  90695. /**< An error occurred in the underlying Ogg layer. */
  90696. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  90697. /**< An error occurred in the underlying verify stream decoder;
  90698. * check FLAC__stream_encoder_get_verify_decoder_state().
  90699. */
  90700. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  90701. /**< The verify decoder detected a mismatch between the original
  90702. * audio signal and the decoded audio signal.
  90703. */
  90704. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  90705. /**< One of the callbacks returned a fatal error. */
  90706. FLAC__STREAM_ENCODER_IO_ERROR,
  90707. /**< An I/O error occurred while opening/reading/writing a file.
  90708. * Check \c errno.
  90709. */
  90710. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  90711. /**< An error occurred while writing the stream; usually, the
  90712. * write_callback returned an error.
  90713. */
  90714. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  90715. /**< Memory allocation failed. */
  90716. } FLAC__StreamEncoderState;
  90717. /** Maps a FLAC__StreamEncoderState to a C string.
  90718. *
  90719. * Using a FLAC__StreamEncoderState as the index to this array
  90720. * will give the string equivalent. The contents should not be modified.
  90721. */
  90722. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  90723. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  90724. */
  90725. typedef enum {
  90726. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  90727. /**< Initialization was successful. */
  90728. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  90729. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  90730. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  90731. /**< The library was not compiled with support for the given container
  90732. * format.
  90733. */
  90734. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  90735. /**< A required callback was not supplied. */
  90736. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  90737. /**< The encoder has an invalid setting for number of channels. */
  90738. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  90739. /**< The encoder has an invalid setting for bits-per-sample.
  90740. * FLAC supports 4-32 bps but the reference encoder currently supports
  90741. * only up to 24 bps.
  90742. */
  90743. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  90744. /**< The encoder has an invalid setting for the input sample rate. */
  90745. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  90746. /**< The encoder has an invalid setting for the block size. */
  90747. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  90748. /**< The encoder has an invalid setting for the maximum LPC order. */
  90749. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  90750. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  90751. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  90752. /**< The specified block size is less than the maximum LPC order. */
  90753. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  90754. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  90755. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  90756. /**< The metadata input to the encoder is invalid, in one of the following ways:
  90757. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  90758. * - One of the metadata blocks contains an undefined type
  90759. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  90760. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  90761. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  90762. */
  90763. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  90764. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  90765. * already initialized, usually because
  90766. * FLAC__stream_encoder_finish() was not called.
  90767. */
  90768. } FLAC__StreamEncoderInitStatus;
  90769. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  90770. *
  90771. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  90772. * will give the string equivalent. The contents should not be modified.
  90773. */
  90774. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  90775. /** Return values for the FLAC__StreamEncoder read callback.
  90776. */
  90777. typedef enum {
  90778. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  90779. /**< The read was OK and decoding can continue. */
  90780. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  90781. /**< The read was attempted at the end of the stream. */
  90782. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  90783. /**< An unrecoverable error occurred. */
  90784. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  90785. /**< Client does not support reading back from the output. */
  90786. } FLAC__StreamEncoderReadStatus;
  90787. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  90788. *
  90789. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  90790. * will give the string equivalent. The contents should not be modified.
  90791. */
  90792. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  90793. /** Return values for the FLAC__StreamEncoder write callback.
  90794. */
  90795. typedef enum {
  90796. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  90797. /**< The write was OK and encoding can continue. */
  90798. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  90799. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  90800. } FLAC__StreamEncoderWriteStatus;
  90801. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  90802. *
  90803. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  90804. * will give the string equivalent. The contents should not be modified.
  90805. */
  90806. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  90807. /** Return values for the FLAC__StreamEncoder seek callback.
  90808. */
  90809. typedef enum {
  90810. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  90811. /**< The seek was OK and encoding can continue. */
  90812. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  90813. /**< An unrecoverable error occurred. */
  90814. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  90815. /**< Client does not support seeking. */
  90816. } FLAC__StreamEncoderSeekStatus;
  90817. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  90818. *
  90819. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  90820. * will give the string equivalent. The contents should not be modified.
  90821. */
  90822. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  90823. /** Return values for the FLAC__StreamEncoder tell callback.
  90824. */
  90825. typedef enum {
  90826. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  90827. /**< The tell was OK and encoding can continue. */
  90828. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  90829. /**< An unrecoverable error occurred. */
  90830. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  90831. /**< Client does not support seeking. */
  90832. } FLAC__StreamEncoderTellStatus;
  90833. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  90834. *
  90835. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  90836. * will give the string equivalent. The contents should not be modified.
  90837. */
  90838. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  90839. /***********************************************************************
  90840. *
  90841. * class FLAC__StreamEncoder
  90842. *
  90843. ***********************************************************************/
  90844. struct FLAC__StreamEncoderProtected;
  90845. struct FLAC__StreamEncoderPrivate;
  90846. /** The opaque structure definition for the stream encoder type.
  90847. * See the \link flac_stream_encoder stream encoder module \endlink
  90848. * for a detailed description.
  90849. */
  90850. typedef struct {
  90851. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  90852. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  90853. } FLAC__StreamEncoder;
  90854. /** Signature for the read callback.
  90855. *
  90856. * A function pointer matching this signature must be passed to
  90857. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  90858. * The supplied function will be called when the encoder needs to read back
  90859. * encoded data. This happens during the metadata callback, when the encoder
  90860. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  90861. * while encoding. The address of the buffer to be filled is supplied, along
  90862. * with the number of bytes the buffer can hold. The callback may choose to
  90863. * supply less data and modify the byte count but must be careful not to
  90864. * overflow the buffer. The callback then returns a status code chosen from
  90865. * FLAC__StreamEncoderReadStatus.
  90866. *
  90867. * Here is an example of a read callback for stdio streams:
  90868. * \code
  90869. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  90870. * {
  90871. * FILE *file = ((MyClientData*)client_data)->file;
  90872. * if(*bytes > 0) {
  90873. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  90874. * if(ferror(file))
  90875. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90876. * else if(*bytes == 0)
  90877. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  90878. * else
  90879. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  90880. * }
  90881. * else
  90882. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90883. * }
  90884. * \endcode
  90885. *
  90886. * \note In general, FLAC__StreamEncoder functions which change the
  90887. * state should not be called on the \a encoder while in the callback.
  90888. *
  90889. * \param encoder The encoder instance calling the callback.
  90890. * \param buffer A pointer to a location for the callee to store
  90891. * data to be encoded.
  90892. * \param bytes A pointer to the size of the buffer. On entry
  90893. * to the callback, it contains the maximum number
  90894. * of bytes that may be stored in \a buffer. The
  90895. * callee must set it to the actual number of bytes
  90896. * stored (0 in case of error or end-of-stream) before
  90897. * returning.
  90898. * \param client_data The callee's client data set through
  90899. * FLAC__stream_encoder_set_client_data().
  90900. * \retval FLAC__StreamEncoderReadStatus
  90901. * The callee's return status.
  90902. */
  90903. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  90904. /** Signature for the write callback.
  90905. *
  90906. * A function pointer matching this signature must be passed to
  90907. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90908. * by the encoder anytime there is raw encoded data ready to write. It may
  90909. * include metadata mixed with encoded audio frames and the data is not
  90910. * guaranteed to be aligned on frame or metadata block boundaries.
  90911. *
  90912. * The only duty of the callback is to write out the \a bytes worth of data
  90913. * in \a buffer to the current position in the output stream. The arguments
  90914. * \a samples and \a current_frame are purely informational. If \a samples
  90915. * is greater than \c 0, then \a current_frame will hold the current frame
  90916. * number that is being written; otherwise it indicates that the write
  90917. * callback is being called to write metadata.
  90918. *
  90919. * \note
  90920. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  90921. * write callback will be called twice when writing each audio
  90922. * frame; once for the page header, and once for the page body.
  90923. * When writing the page header, the \a samples argument to the
  90924. * write callback will be \c 0.
  90925. *
  90926. * \note In general, FLAC__StreamEncoder functions which change the
  90927. * state should not be called on the \a encoder while in the callback.
  90928. *
  90929. * \param encoder The encoder instance calling the callback.
  90930. * \param buffer An array of encoded data of length \a bytes.
  90931. * \param bytes The byte length of \a buffer.
  90932. * \param samples The number of samples encoded by \a buffer.
  90933. * \c 0 has a special meaning; see above.
  90934. * \param current_frame The number of the current frame being encoded.
  90935. * \param client_data The callee's client data set through
  90936. * FLAC__stream_encoder_init_*().
  90937. * \retval FLAC__StreamEncoderWriteStatus
  90938. * The callee's return status.
  90939. */
  90940. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  90941. /** Signature for the seek callback.
  90942. *
  90943. * A function pointer matching this signature may be passed to
  90944. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90945. * when the encoder needs to seek the output stream. The encoder will pass
  90946. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  90947. *
  90948. * Here is an example of a seek callback for stdio streams:
  90949. * \code
  90950. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  90951. * {
  90952. * FILE *file = ((MyClientData*)client_data)->file;
  90953. * if(file == stdin)
  90954. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  90955. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  90956. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  90957. * else
  90958. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  90959. * }
  90960. * \endcode
  90961. *
  90962. * \note In general, FLAC__StreamEncoder functions which change the
  90963. * state should not be called on the \a encoder while in the callback.
  90964. *
  90965. * \param encoder The encoder instance calling the callback.
  90966. * \param absolute_byte_offset The offset from the beginning of the stream
  90967. * to seek to.
  90968. * \param client_data The callee's client data set through
  90969. * FLAC__stream_encoder_init_*().
  90970. * \retval FLAC__StreamEncoderSeekStatus
  90971. * The callee's return status.
  90972. */
  90973. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  90974. /** Signature for the tell callback.
  90975. *
  90976. * A function pointer matching this signature may be passed to
  90977. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90978. * when the encoder needs to know the current position of the output stream.
  90979. *
  90980. * \warning
  90981. * The callback must return the true current byte offset of the output to
  90982. * which the encoder is writing. If you are buffering the output, make
  90983. * sure and take this into account. If you are writing directly to a
  90984. * FILE* from your write callback, ftell() is sufficient. If you are
  90985. * writing directly to a file descriptor from your write callback, you
  90986. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  90987. * these points to rewrite metadata after encoding.
  90988. *
  90989. * Here is an example of a tell callback for stdio streams:
  90990. * \code
  90991. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  90992. * {
  90993. * FILE *file = ((MyClientData*)client_data)->file;
  90994. * off_t pos;
  90995. * if(file == stdin)
  90996. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  90997. * else if((pos = ftello(file)) < 0)
  90998. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  90999. * else {
  91000. * *absolute_byte_offset = (FLAC__uint64)pos;
  91001. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  91002. * }
  91003. * }
  91004. * \endcode
  91005. *
  91006. * \note In general, FLAC__StreamEncoder functions which change the
  91007. * state should not be called on the \a encoder while in the callback.
  91008. *
  91009. * \param encoder The encoder instance calling the callback.
  91010. * \param absolute_byte_offset The address at which to store the current
  91011. * position of the output.
  91012. * \param client_data The callee's client data set through
  91013. * FLAC__stream_encoder_init_*().
  91014. * \retval FLAC__StreamEncoderTellStatus
  91015. * The callee's return status.
  91016. */
  91017. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  91018. /** Signature for the metadata callback.
  91019. *
  91020. * A function pointer matching this signature may be passed to
  91021. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91022. * once at the end of encoding with the populated STREAMINFO structure. This
  91023. * is so the client can seek back to the beginning of the file and write the
  91024. * STREAMINFO block with the correct statistics after encoding (like
  91025. * minimum/maximum frame size and total samples).
  91026. *
  91027. * \note In general, FLAC__StreamEncoder functions which change the
  91028. * state should not be called on the \a encoder while in the callback.
  91029. *
  91030. * \param encoder The encoder instance calling the callback.
  91031. * \param metadata The final populated STREAMINFO block.
  91032. * \param client_data The callee's client data set through
  91033. * FLAC__stream_encoder_init_*().
  91034. */
  91035. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91036. /** Signature for the progress callback.
  91037. *
  91038. * A function pointer matching this signature may be passed to
  91039. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91040. * The supplied function will be called when the encoder has finished
  91041. * writing a frame. The \c total_frames_estimate argument to the
  91042. * callback will be based on the value from
  91043. * FLAC__stream_encoder_set_total_samples_estimate().
  91044. *
  91045. * \note In general, FLAC__StreamEncoder functions which change the
  91046. * state should not be called on the \a encoder while in the callback.
  91047. *
  91048. * \param encoder The encoder instance calling the callback.
  91049. * \param bytes_written Bytes written so far.
  91050. * \param samples_written Samples written so far.
  91051. * \param frames_written Frames written so far.
  91052. * \param total_frames_estimate The estimate of the total number of
  91053. * frames to be written.
  91054. * \param client_data The callee's client data set through
  91055. * FLAC__stream_encoder_init_*().
  91056. */
  91057. 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);
  91058. /***********************************************************************
  91059. *
  91060. * Class constructor/destructor
  91061. *
  91062. ***********************************************************************/
  91063. /** Create a new stream encoder instance. The instance is created with
  91064. * default settings; see the individual FLAC__stream_encoder_set_*()
  91065. * functions for each setting's default.
  91066. *
  91067. * \retval FLAC__StreamEncoder*
  91068. * \c NULL if there was an error allocating memory, else the new instance.
  91069. */
  91070. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91071. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91072. *
  91073. * \param encoder A pointer to an existing encoder.
  91074. * \assert
  91075. * \code encoder != NULL \endcode
  91076. */
  91077. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91078. /***********************************************************************
  91079. *
  91080. * Public class method prototypes
  91081. *
  91082. ***********************************************************************/
  91083. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91084. *
  91085. * \note
  91086. * This does not need to be set for native FLAC encoding.
  91087. *
  91088. * \note
  91089. * It is recommended to set a serial number explicitly as the default of '0'
  91090. * may collide with other streams.
  91091. *
  91092. * \default \c 0
  91093. * \param encoder An encoder instance to set.
  91094. * \param serial_number See above.
  91095. * \assert
  91096. * \code encoder != NULL \endcode
  91097. * \retval FLAC__bool
  91098. * \c false if the encoder is already initialized, else \c true.
  91099. */
  91100. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91101. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91102. * encoded output by feeding it through an internal decoder and comparing
  91103. * the original signal against the decoded signal. If a mismatch occurs,
  91104. * the process call will return \c false. Note that this will slow the
  91105. * encoding process by the extra time required for decoding and comparison.
  91106. *
  91107. * \default \c false
  91108. * \param encoder An encoder instance to set.
  91109. * \param value Flag value (see above).
  91110. * \assert
  91111. * \code encoder != NULL \endcode
  91112. * \retval FLAC__bool
  91113. * \c false if the encoder is already initialized, else \c true.
  91114. */
  91115. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91116. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91117. * the encoder will comply with the Subset and will check the
  91118. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91119. * comply. If \c false, the settings may take advantage of the full
  91120. * range that the format allows.
  91121. *
  91122. * Make sure you know what it entails before setting this to \c false.
  91123. *
  91124. * \default \c true
  91125. * \param encoder An encoder instance to set.
  91126. * \param value Flag value (see above).
  91127. * \assert
  91128. * \code encoder != NULL \endcode
  91129. * \retval FLAC__bool
  91130. * \c false if the encoder is already initialized, else \c true.
  91131. */
  91132. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91133. /** Set the number of channels to be encoded.
  91134. *
  91135. * \default \c 2
  91136. * \param encoder An encoder instance to set.
  91137. * \param value See above.
  91138. * \assert
  91139. * \code encoder != NULL \endcode
  91140. * \retval FLAC__bool
  91141. * \c false if the encoder is already initialized, else \c true.
  91142. */
  91143. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91144. /** Set the sample resolution of the input to be encoded.
  91145. *
  91146. * \warning
  91147. * Do not feed the encoder data that is wider than the value you
  91148. * set here or you will generate an invalid stream.
  91149. *
  91150. * \default \c 16
  91151. * \param encoder An encoder instance to set.
  91152. * \param value See above.
  91153. * \assert
  91154. * \code encoder != NULL \endcode
  91155. * \retval FLAC__bool
  91156. * \c false if the encoder is already initialized, else \c true.
  91157. */
  91158. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91159. /** Set the sample rate (in Hz) of the input to be encoded.
  91160. *
  91161. * \default \c 44100
  91162. * \param encoder An encoder instance to set.
  91163. * \param value See above.
  91164. * \assert
  91165. * \code encoder != NULL \endcode
  91166. * \retval FLAC__bool
  91167. * \c false if the encoder is already initialized, else \c true.
  91168. */
  91169. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91170. /** Set the compression level
  91171. *
  91172. * The compression level is roughly proportional to the amount of effort
  91173. * the encoder expends to compress the file. A higher level usually
  91174. * means more computation but higher compression. The default level is
  91175. * suitable for most applications.
  91176. *
  91177. * Currently the levels range from \c 0 (fastest, least compression) to
  91178. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91179. * treated as \c 8.
  91180. *
  91181. * This function automatically calls the following other \c _set_
  91182. * functions with appropriate values, so the client does not need to
  91183. * unless it specifically wants to override them:
  91184. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91185. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91186. * - FLAC__stream_encoder_set_apodization()
  91187. * - FLAC__stream_encoder_set_max_lpc_order()
  91188. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91189. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91190. * - FLAC__stream_encoder_set_do_escape_coding()
  91191. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91192. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91193. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91194. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91195. *
  91196. * The actual values set for each level are:
  91197. * <table>
  91198. * <tr>
  91199. * <td><b>level</b><td>
  91200. * <td>do mid-side stereo<td>
  91201. * <td>loose mid-side stereo<td>
  91202. * <td>apodization<td>
  91203. * <td>max lpc order<td>
  91204. * <td>qlp coeff precision<td>
  91205. * <td>qlp coeff prec search<td>
  91206. * <td>escape coding<td>
  91207. * <td>exhaustive model search<td>
  91208. * <td>min residual partition order<td>
  91209. * <td>max residual partition order<td>
  91210. * <td>rice parameter search dist<td>
  91211. * </tr>
  91212. * <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>
  91213. * <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>
  91214. * <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>
  91215. * <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>
  91216. * <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>
  91217. * <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>
  91218. * <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>
  91219. * <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>
  91220. * <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>
  91221. * </table>
  91222. *
  91223. * \default \c 5
  91224. * \param encoder An encoder instance to set.
  91225. * \param value See above.
  91226. * \assert
  91227. * \code encoder != NULL \endcode
  91228. * \retval FLAC__bool
  91229. * \c false if the encoder is already initialized, else \c true.
  91230. */
  91231. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91232. /** Set the blocksize to use while encoding.
  91233. *
  91234. * The number of samples to use per frame. Use \c 0 to let the encoder
  91235. * estimate a blocksize; this is usually best.
  91236. *
  91237. * \default \c 0
  91238. * \param encoder An encoder instance to set.
  91239. * \param value See above.
  91240. * \assert
  91241. * \code encoder != NULL \endcode
  91242. * \retval FLAC__bool
  91243. * \c false if the encoder is already initialized, else \c true.
  91244. */
  91245. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91246. /** Set to \c true to enable mid-side encoding on stereo input. The
  91247. * number of channels must be 2 for this to have any effect. Set to
  91248. * \c false to use only independent channel coding.
  91249. *
  91250. * \default \c false
  91251. * \param encoder An encoder instance to set.
  91252. * \param value Flag value (see above).
  91253. * \assert
  91254. * \code encoder != NULL \endcode
  91255. * \retval FLAC__bool
  91256. * \c false if the encoder is already initialized, else \c true.
  91257. */
  91258. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91259. /** Set to \c true to enable adaptive switching between mid-side and
  91260. * left-right encoding on stereo input. Set to \c false to use
  91261. * exhaustive searching. Setting this to \c true requires
  91262. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91263. * \c true in order to have any effect.
  91264. *
  91265. * \default \c false
  91266. * \param encoder An encoder instance to set.
  91267. * \param value Flag value (see above).
  91268. * \assert
  91269. * \code encoder != NULL \endcode
  91270. * \retval FLAC__bool
  91271. * \c false if the encoder is already initialized, else \c true.
  91272. */
  91273. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91274. /** Sets the apodization function(s) the encoder will use when windowing
  91275. * audio data for LPC analysis.
  91276. *
  91277. * The \a specification is a plain ASCII string which specifies exactly
  91278. * which functions to use. There may be more than one (up to 32),
  91279. * separated by \c ';' characters. Some functions take one or more
  91280. * comma-separated arguments in parentheses.
  91281. *
  91282. * The available functions are \c bartlett, \c bartlett_hann,
  91283. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91284. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91285. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91286. *
  91287. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91288. * (0<STDDEV<=0.5).
  91289. *
  91290. * For \c tukey(P), P specifies the fraction of the window that is
  91291. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91292. * corresponds to \c hann.
  91293. *
  91294. * Example specifications are \c "blackman" or
  91295. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91296. *
  91297. * Any function that is specified erroneously is silently dropped. Up
  91298. * to 32 functions are kept, the rest are dropped. If the specification
  91299. * is empty the encoder defaults to \c "tukey(0.5)".
  91300. *
  91301. * When more than one function is specified, then for every subframe the
  91302. * encoder will try each of them separately and choose the window that
  91303. * results in the smallest compressed subframe.
  91304. *
  91305. * Note that each function specified causes the encoder to occupy a
  91306. * floating point array in which to store the window.
  91307. *
  91308. * \default \c "tukey(0.5)"
  91309. * \param encoder An encoder instance to set.
  91310. * \param specification See above.
  91311. * \assert
  91312. * \code encoder != NULL \endcode
  91313. * \code specification != NULL \endcode
  91314. * \retval FLAC__bool
  91315. * \c false if the encoder is already initialized, else \c true.
  91316. */
  91317. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91318. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91319. *
  91320. * \default \c 0
  91321. * \param encoder An encoder instance to set.
  91322. * \param value See above.
  91323. * \assert
  91324. * \code encoder != NULL \endcode
  91325. * \retval FLAC__bool
  91326. * \c false if the encoder is already initialized, else \c true.
  91327. */
  91328. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91329. /** Set the precision, in bits, of the quantized linear predictor
  91330. * coefficients, or \c 0 to let the encoder select it based on the
  91331. * blocksize.
  91332. *
  91333. * \note
  91334. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91335. * be less than 32.
  91336. *
  91337. * \default \c 0
  91338. * \param encoder An encoder instance to set.
  91339. * \param value See above.
  91340. * \assert
  91341. * \code encoder != NULL \endcode
  91342. * \retval FLAC__bool
  91343. * \c false if the encoder is already initialized, else \c true.
  91344. */
  91345. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91346. /** Set to \c false to use only the specified quantized linear predictor
  91347. * coefficient precision, or \c true to search neighboring precision
  91348. * values and use the best one.
  91349. *
  91350. * \default \c false
  91351. * \param encoder An encoder instance to set.
  91352. * \param value See above.
  91353. * \assert
  91354. * \code encoder != NULL \endcode
  91355. * \retval FLAC__bool
  91356. * \c false if the encoder is already initialized, else \c true.
  91357. */
  91358. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91359. /** Deprecated. Setting this value has no effect.
  91360. *
  91361. * \default \c false
  91362. * \param encoder An encoder instance to set.
  91363. * \param value See above.
  91364. * \assert
  91365. * \code encoder != NULL \endcode
  91366. * \retval FLAC__bool
  91367. * \c false if the encoder is already initialized, else \c true.
  91368. */
  91369. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91370. /** Set to \c false to let the encoder estimate the best model order
  91371. * based on the residual signal energy, or \c true to force the
  91372. * encoder to evaluate all order models and select the best.
  91373. *
  91374. * \default \c false
  91375. * \param encoder An encoder instance to set.
  91376. * \param value See above.
  91377. * \assert
  91378. * \code encoder != NULL \endcode
  91379. * \retval FLAC__bool
  91380. * \c false if the encoder is already initialized, else \c true.
  91381. */
  91382. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91383. /** Set the minimum partition order to search when coding the residual.
  91384. * This is used in tandem with
  91385. * FLAC__stream_encoder_set_max_residual_partition_order().
  91386. *
  91387. * The partition order determines the context size in the residual.
  91388. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91389. *
  91390. * Set both min and max values to \c 0 to force a single context,
  91391. * whose Rice parameter is based on the residual signal variance.
  91392. * Otherwise, set a min and max order, and the encoder will search
  91393. * all orders, using the mean of each context for its Rice parameter,
  91394. * and use the best.
  91395. *
  91396. * \default \c 0
  91397. * \param encoder An encoder instance to set.
  91398. * \param value See above.
  91399. * \assert
  91400. * \code encoder != NULL \endcode
  91401. * \retval FLAC__bool
  91402. * \c false if the encoder is already initialized, else \c true.
  91403. */
  91404. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91405. /** Set the maximum partition order to search when coding the residual.
  91406. * This is used in tandem with
  91407. * FLAC__stream_encoder_set_min_residual_partition_order().
  91408. *
  91409. * The partition order determines the context size in the residual.
  91410. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91411. *
  91412. * Set both min and max values to \c 0 to force a single context,
  91413. * whose Rice parameter is based on the residual signal variance.
  91414. * Otherwise, set a min and max order, and the encoder will search
  91415. * all orders, using the mean of each context for its Rice parameter,
  91416. * and use the best.
  91417. *
  91418. * \default \c 0
  91419. * \param encoder An encoder instance to set.
  91420. * \param value See above.
  91421. * \assert
  91422. * \code encoder != NULL \endcode
  91423. * \retval FLAC__bool
  91424. * \c false if the encoder is already initialized, else \c true.
  91425. */
  91426. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91427. /** Deprecated. Setting this value has no effect.
  91428. *
  91429. * \default \c 0
  91430. * \param encoder An encoder instance to set.
  91431. * \param value See above.
  91432. * \assert
  91433. * \code encoder != NULL \endcode
  91434. * \retval FLAC__bool
  91435. * \c false if the encoder is already initialized, else \c true.
  91436. */
  91437. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91438. /** Set an estimate of the total samples that will be encoded.
  91439. * This is merely an estimate and may be set to \c 0 if unknown.
  91440. * This value will be written to the STREAMINFO block before encoding,
  91441. * and can remove the need for the caller to rewrite the value later
  91442. * if the value is known before encoding.
  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_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91453. /** Set the metadata blocks to be emitted to the stream before encoding.
  91454. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91455. * array of pointers to metadata blocks. The array is non-const since
  91456. * the encoder may need to change the \a is_last flag inside them, and
  91457. * in some cases update seek point offsets. Otherwise, the encoder will
  91458. * not modify or free the blocks. It is up to the caller to free the
  91459. * metadata blocks after encoding finishes.
  91460. *
  91461. * \note
  91462. * The encoder stores only copies of the pointers in the \a metadata array;
  91463. * the metadata blocks themselves must survive at least until after
  91464. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91465. *
  91466. * \note
  91467. * The STREAMINFO block is always written and no STREAMINFO block may
  91468. * occur in the supplied array.
  91469. *
  91470. * \note
  91471. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91472. * in the \a metadata array, but the client has specified that it does not
  91473. * support seeking, then the SEEKTABLE will be written verbatim. However
  91474. * by itself this is not very useful as the client will not know the stream
  91475. * offsets for the seekpoints ahead of time. In order to get a proper
  91476. * seektable the client must support seeking. See next note.
  91477. *
  91478. * \note
  91479. * SEEKTABLE blocks are handled specially. Since you will not know
  91480. * the values for the seek point stream offsets, you should pass in
  91481. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91482. * required sample numbers (or placeholder points), with \c 0 for the
  91483. * \a frame_samples and \a stream_offset fields for each point. If the
  91484. * client has specified that it supports seeking by providing a seek
  91485. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91486. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91487. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91488. * then while it is encoding the encoder will fill the stream offsets in
  91489. * for you and when encoding is finished, it will seek back and write the
  91490. * real values into the SEEKTABLE block in the stream. There are helper
  91491. * routines for manipulating seektable template blocks; see metadata.h:
  91492. * FLAC__metadata_object_seektable_template_*(). If the client does
  91493. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91494. * will slow down or remove the ability to seek in the FLAC stream.
  91495. *
  91496. * \note
  91497. * The encoder instance \b will modify the first \c SEEKTABLE block
  91498. * as it transforms the template to a valid seektable while encoding,
  91499. * but it is still up to the caller to free all metadata blocks after
  91500. * encoding.
  91501. *
  91502. * \note
  91503. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  91504. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  91505. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  91506. * will simply write it's own into the stream. If no VORBIS_COMMENT
  91507. * block is present in the \a metadata array, libFLAC will write an
  91508. * empty one, containing only the vendor string.
  91509. *
  91510. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  91511. * the second metadata block of the stream. The encoder already supplies
  91512. * the STREAMINFO block automatically. If \a metadata does not contain a
  91513. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  91514. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  91515. * first, the init function will reorder \a metadata by moving the
  91516. * VORBIS_COMMENT block to the front; the relative ordering of the other
  91517. * blocks will remain as they were.
  91518. *
  91519. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  91520. * stream to \c 65535. If \a num_blocks exceeds this the function will
  91521. * return \c false.
  91522. *
  91523. * \default \c NULL, 0
  91524. * \param encoder An encoder instance to set.
  91525. * \param metadata See above.
  91526. * \param num_blocks See above.
  91527. * \assert
  91528. * \code encoder != NULL \endcode
  91529. * \retval FLAC__bool
  91530. * \c false if the encoder is already initialized, else \c true.
  91531. * \c false if the encoder is already initialized, or if
  91532. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  91533. */
  91534. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  91535. /** Get the current encoder state.
  91536. *
  91537. * \param encoder An encoder instance to query.
  91538. * \assert
  91539. * \code encoder != NULL \endcode
  91540. * \retval FLAC__StreamEncoderState
  91541. * The current encoder state.
  91542. */
  91543. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  91544. /** Get the state of the verify stream decoder.
  91545. * Useful when the stream encoder state is
  91546. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  91547. *
  91548. * \param encoder An encoder instance to query.
  91549. * \assert
  91550. * \code encoder != NULL \endcode
  91551. * \retval FLAC__StreamDecoderState
  91552. * The verify stream decoder state.
  91553. */
  91554. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  91555. /** Get the current encoder state as a C string.
  91556. * This version automatically resolves
  91557. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  91558. * verify decoder's state.
  91559. *
  91560. * \param encoder A encoder instance to query.
  91561. * \assert
  91562. * \code encoder != NULL \endcode
  91563. * \retval const char *
  91564. * The encoder state as a C string. Do not modify the contents.
  91565. */
  91566. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  91567. /** Get relevant values about the nature of a verify decoder error.
  91568. * Useful when the stream encoder state is
  91569. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  91570. * be addresses in which the stats will be returned, or NULL if value
  91571. * is not desired.
  91572. *
  91573. * \param encoder An encoder instance to query.
  91574. * \param absolute_sample The absolute sample number of the mismatch.
  91575. * \param frame_number The number of the frame in which the mismatch occurred.
  91576. * \param channel The channel in which the mismatch occurred.
  91577. * \param sample The number of the sample (relative to the frame) in
  91578. * which the mismatch occurred.
  91579. * \param expected The expected value for the sample in question.
  91580. * \param got The actual value returned by the decoder.
  91581. * \assert
  91582. * \code encoder != NULL \endcode
  91583. */
  91584. 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);
  91585. /** Get the "verify" flag.
  91586. *
  91587. * \param encoder An encoder instance to query.
  91588. * \assert
  91589. * \code encoder != NULL \endcode
  91590. * \retval FLAC__bool
  91591. * See FLAC__stream_encoder_set_verify().
  91592. */
  91593. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  91594. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  91595. *
  91596. * \param encoder An encoder instance to query.
  91597. * \assert
  91598. * \code encoder != NULL \endcode
  91599. * \retval FLAC__bool
  91600. * See FLAC__stream_encoder_set_streamable_subset().
  91601. */
  91602. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  91603. /** Get the number of input channels being processed.
  91604. *
  91605. * \param encoder An encoder instance to query.
  91606. * \assert
  91607. * \code encoder != NULL \endcode
  91608. * \retval unsigned
  91609. * See FLAC__stream_encoder_set_channels().
  91610. */
  91611. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  91612. /** Get the input sample resolution setting.
  91613. *
  91614. * \param encoder An encoder instance to query.
  91615. * \assert
  91616. * \code encoder != NULL \endcode
  91617. * \retval unsigned
  91618. * See FLAC__stream_encoder_set_bits_per_sample().
  91619. */
  91620. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  91621. /** Get the input sample rate setting.
  91622. *
  91623. * \param encoder An encoder instance to query.
  91624. * \assert
  91625. * \code encoder != NULL \endcode
  91626. * \retval unsigned
  91627. * See FLAC__stream_encoder_set_sample_rate().
  91628. */
  91629. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  91630. /** Get the blocksize setting.
  91631. *
  91632. * \param encoder An encoder instance to query.
  91633. * \assert
  91634. * \code encoder != NULL \endcode
  91635. * \retval unsigned
  91636. * See FLAC__stream_encoder_set_blocksize().
  91637. */
  91638. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  91639. /** Get the "mid/side stereo coding" flag.
  91640. *
  91641. * \param encoder An encoder instance to query.
  91642. * \assert
  91643. * \code encoder != NULL \endcode
  91644. * \retval FLAC__bool
  91645. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  91646. */
  91647. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91648. /** Get the "adaptive mid/side switching" flag.
  91649. *
  91650. * \param encoder An encoder instance to query.
  91651. * \assert
  91652. * \code encoder != NULL \endcode
  91653. * \retval FLAC__bool
  91654. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  91655. */
  91656. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91657. /** Get the maximum LPC order setting.
  91658. *
  91659. * \param encoder An encoder instance to query.
  91660. * \assert
  91661. * \code encoder != NULL \endcode
  91662. * \retval unsigned
  91663. * See FLAC__stream_encoder_set_max_lpc_order().
  91664. */
  91665. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  91666. /** Get the quantized linear predictor coefficient precision setting.
  91667. *
  91668. * \param encoder An encoder instance to query.
  91669. * \assert
  91670. * \code encoder != NULL \endcode
  91671. * \retval unsigned
  91672. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  91673. */
  91674. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  91675. /** Get the qlp coefficient precision search flag.
  91676. *
  91677. * \param encoder An encoder instance to query.
  91678. * \assert
  91679. * \code encoder != NULL \endcode
  91680. * \retval FLAC__bool
  91681. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  91682. */
  91683. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  91684. /** Get the "escape coding" flag.
  91685. *
  91686. * \param encoder An encoder instance to query.
  91687. * \assert
  91688. * \code encoder != NULL \endcode
  91689. * \retval FLAC__bool
  91690. * See FLAC__stream_encoder_set_do_escape_coding().
  91691. */
  91692. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  91693. /** Get the exhaustive model search flag.
  91694. *
  91695. * \param encoder An encoder instance to query.
  91696. * \assert
  91697. * \code encoder != NULL \endcode
  91698. * \retval FLAC__bool
  91699. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  91700. */
  91701. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  91702. /** Get the minimum residual partition order setting.
  91703. *
  91704. * \param encoder An encoder instance to query.
  91705. * \assert
  91706. * \code encoder != NULL \endcode
  91707. * \retval unsigned
  91708. * See FLAC__stream_encoder_set_min_residual_partition_order().
  91709. */
  91710. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91711. /** Get maximum residual partition order setting.
  91712. *
  91713. * \param encoder An encoder instance to query.
  91714. * \assert
  91715. * \code encoder != NULL \endcode
  91716. * \retval unsigned
  91717. * See FLAC__stream_encoder_set_max_residual_partition_order().
  91718. */
  91719. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91720. /** Get the Rice parameter search distance setting.
  91721. *
  91722. * \param encoder An encoder instance to query.
  91723. * \assert
  91724. * \code encoder != NULL \endcode
  91725. * \retval unsigned
  91726. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  91727. */
  91728. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  91729. /** Get the previously set estimate of the total samples to be encoded.
  91730. * The encoder merely mimics back the value given to
  91731. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  91732. * other way of knowing how many samples the client will encode.
  91733. *
  91734. * \param encoder An encoder instance to set.
  91735. * \assert
  91736. * \code encoder != NULL \endcode
  91737. * \retval FLAC__uint64
  91738. * See FLAC__stream_encoder_get_total_samples_estimate().
  91739. */
  91740. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  91741. /** Initialize the encoder instance to encode native FLAC streams.
  91742. *
  91743. * This flavor of initialization sets up the encoder to encode to a
  91744. * native FLAC stream. I/O is performed via callbacks to the client.
  91745. * For encoding to a plain file via filename or open \c FILE*,
  91746. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  91747. * provide a simpler interface.
  91748. *
  91749. * This function should be called after FLAC__stream_encoder_new() and
  91750. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91751. * or FLAC__stream_encoder_process_interleaved().
  91752. * initialization succeeded.
  91753. *
  91754. * The call to FLAC__stream_encoder_init_stream() currently will also
  91755. * immediately call the write callback several times, once with the \c fLaC
  91756. * signature, and once for each encoded metadata block.
  91757. *
  91758. * \param encoder An uninitialized encoder instance.
  91759. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91760. * pointer must not be \c NULL.
  91761. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91762. * pointer may be \c NULL if seeking is not
  91763. * supported. The encoder uses seeking to go back
  91764. * and write some some stream statistics to the
  91765. * STREAMINFO block; this is recommended but not
  91766. * necessary to create a valid FLAC stream. If
  91767. * \a seek_callback is not \c NULL then a
  91768. * \a tell_callback must also be supplied.
  91769. * Alternatively, a dummy seek callback that just
  91770. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91771. * may also be supplied, all though this is slightly
  91772. * less efficient for the encoder.
  91773. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91774. * pointer may be \c NULL if seeking is not
  91775. * supported. If \a seek_callback is \c NULL then
  91776. * this argument will be ignored. If
  91777. * \a seek_callback is not \c NULL then a
  91778. * \a tell_callback must also be supplied.
  91779. * Alternatively, a dummy tell callback that just
  91780. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91781. * may also be supplied, all though this is slightly
  91782. * less efficient for the encoder.
  91783. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91784. * pointer may be \c NULL if the callback is not
  91785. * desired. If the client provides a seek callback,
  91786. * this function is not necessary as the encoder
  91787. * will automatically seek back and update the
  91788. * STREAMINFO block. It may also be \c NULL if the
  91789. * client does not support seeking, since it will
  91790. * have no way of going back to update the
  91791. * STREAMINFO. However the client can still supply
  91792. * a callback if it would like to know the details
  91793. * from the STREAMINFO.
  91794. * \param client_data This value will be supplied to callbacks in their
  91795. * \a client_data argument.
  91796. * \assert
  91797. * \code encoder != NULL \endcode
  91798. * \retval FLAC__StreamEncoderInitStatus
  91799. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91800. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91801. */
  91802. 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);
  91803. /** Initialize the encoder instance to encode Ogg FLAC streams.
  91804. *
  91805. * This flavor of initialization sets up the encoder to encode to a FLAC
  91806. * stream in an Ogg container. I/O is performed via callbacks to the
  91807. * client. For encoding to a plain file via filename or open \c FILE*,
  91808. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  91809. * provide a simpler interface.
  91810. *
  91811. * This function should be called after FLAC__stream_encoder_new() and
  91812. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91813. * or FLAC__stream_encoder_process_interleaved().
  91814. * initialization succeeded.
  91815. *
  91816. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  91817. * immediately call the write callback several times to write the metadata
  91818. * packets.
  91819. *
  91820. * \param encoder An uninitialized encoder instance.
  91821. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  91822. * pointer must not be \c NULL if \a seek_callback
  91823. * is non-NULL since they are both needed to be
  91824. * able to write data back to the Ogg FLAC stream
  91825. * in the post-encode phase.
  91826. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91827. * pointer must not be \c NULL.
  91828. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91829. * pointer may be \c NULL if seeking is not
  91830. * supported. The encoder uses seeking to go back
  91831. * and write some some stream statistics to the
  91832. * STREAMINFO block; this is recommended but not
  91833. * necessary to create a valid FLAC stream. If
  91834. * \a seek_callback is not \c NULL then a
  91835. * \a tell_callback must also be supplied.
  91836. * Alternatively, a dummy seek callback that just
  91837. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91838. * may also be supplied, all though this is slightly
  91839. * less efficient for the encoder.
  91840. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91841. * pointer may be \c NULL if seeking is not
  91842. * supported. If \a seek_callback is \c NULL then
  91843. * this argument will be ignored. If
  91844. * \a seek_callback is not \c NULL then a
  91845. * \a tell_callback must also be supplied.
  91846. * Alternatively, a dummy tell callback that just
  91847. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91848. * may also be supplied, all though this is slightly
  91849. * less efficient for the encoder.
  91850. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91851. * pointer may be \c NULL if the callback is not
  91852. * desired. If the client provides a seek callback,
  91853. * this function is not necessary as the encoder
  91854. * will automatically seek back and update the
  91855. * STREAMINFO block. It may also be \c NULL if the
  91856. * client does not support seeking, since it will
  91857. * have no way of going back to update the
  91858. * STREAMINFO. However the client can still supply
  91859. * a callback if it would like to know the details
  91860. * from the STREAMINFO.
  91861. * \param client_data This value will be supplied to callbacks in their
  91862. * \a client_data argument.
  91863. * \assert
  91864. * \code encoder != NULL \endcode
  91865. * \retval FLAC__StreamEncoderInitStatus
  91866. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91867. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91868. */
  91869. 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);
  91870. /** Initialize the encoder instance to encode native FLAC files.
  91871. *
  91872. * This flavor of initialization sets up the encoder to encode to a
  91873. * plain native FLAC file. For non-stdio streams, you must use
  91874. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  91875. *
  91876. * This function should be called after FLAC__stream_encoder_new() and
  91877. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91878. * or FLAC__stream_encoder_process_interleaved().
  91879. * initialization succeeded.
  91880. *
  91881. * \param encoder An uninitialized encoder instance.
  91882. * \param file An open file. The file should have been opened
  91883. * with mode \c "w+b" and rewound. The file
  91884. * becomes owned by the encoder and should not be
  91885. * manipulated by the client while encoding.
  91886. * Unless \a file is \c stdout, it will be closed
  91887. * when FLAC__stream_encoder_finish() is called.
  91888. * Note however that a proper SEEKTABLE cannot be
  91889. * created when encoding to \c stdout since it is
  91890. * not seekable.
  91891. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91892. * pointer may be \c NULL if the callback is not
  91893. * desired.
  91894. * \param client_data This value will be supplied to callbacks in their
  91895. * \a client_data argument.
  91896. * \assert
  91897. * \code encoder != NULL \endcode
  91898. * \code file != NULL \endcode
  91899. * \retval FLAC__StreamEncoderInitStatus
  91900. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91901. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91902. */
  91903. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91904. /** Initialize the encoder instance to encode Ogg FLAC files.
  91905. *
  91906. * This flavor of initialization sets up the encoder to encode to a
  91907. * plain Ogg FLAC file. For non-stdio streams, you must use
  91908. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  91909. *
  91910. * This function should be called after FLAC__stream_encoder_new() and
  91911. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91912. * or FLAC__stream_encoder_process_interleaved().
  91913. * initialization succeeded.
  91914. *
  91915. * \param encoder An uninitialized encoder instance.
  91916. * \param file An open file. The file should have been opened
  91917. * with mode \c "w+b" and rewound. The file
  91918. * becomes owned by the encoder and should not be
  91919. * manipulated by the client while encoding.
  91920. * Unless \a file is \c stdout, it will be closed
  91921. * when FLAC__stream_encoder_finish() is called.
  91922. * Note however that a proper SEEKTABLE cannot be
  91923. * created when encoding to \c stdout since it is
  91924. * not seekable.
  91925. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91926. * pointer may be \c NULL if the callback is not
  91927. * desired.
  91928. * \param client_data This value will be supplied to callbacks in their
  91929. * \a client_data argument.
  91930. * \assert
  91931. * \code encoder != NULL \endcode
  91932. * \code file != NULL \endcode
  91933. * \retval FLAC__StreamEncoderInitStatus
  91934. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91935. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91936. */
  91937. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91938. /** Initialize the encoder instance to encode native FLAC files.
  91939. *
  91940. * This flavor of initialization sets up the encoder to encode to a plain
  91941. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91942. * with Unicode filenames on Windows), you must use
  91943. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  91944. * and provide callbacks for the I/O.
  91945. *
  91946. * This function should be called after FLAC__stream_encoder_new() and
  91947. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91948. * or FLAC__stream_encoder_process_interleaved().
  91949. * initialization succeeded.
  91950. *
  91951. * \param encoder An uninitialized encoder instance.
  91952. * \param filename The name of the file to encode to. The file will
  91953. * be opened with fopen(). Use \c NULL to encode to
  91954. * \c stdout. Note however that a proper SEEKTABLE
  91955. * cannot be created when encoding to \c stdout since
  91956. * it is not seekable.
  91957. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91958. * pointer may be \c NULL if the callback is not
  91959. * desired.
  91960. * \param client_data This value will be supplied to callbacks in their
  91961. * \a client_data argument.
  91962. * \assert
  91963. * \code encoder != NULL \endcode
  91964. * \retval FLAC__StreamEncoderInitStatus
  91965. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91966. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91967. */
  91968. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91969. /** Initialize the encoder instance to encode Ogg FLAC files.
  91970. *
  91971. * This flavor of initialization sets up the encoder to encode to a plain
  91972. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91973. * with Unicode filenames on Windows), you must use
  91974. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  91975. * and provide callbacks for the I/O.
  91976. *
  91977. * This function should be called after FLAC__stream_encoder_new() and
  91978. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91979. * or FLAC__stream_encoder_process_interleaved().
  91980. * initialization succeeded.
  91981. *
  91982. * \param encoder An uninitialized encoder instance.
  91983. * \param filename The name of the file to encode to. The file will
  91984. * be opened with fopen(). Use \c NULL to encode to
  91985. * \c stdout. Note however that a proper SEEKTABLE
  91986. * cannot be created when encoding to \c stdout since
  91987. * it is not seekable.
  91988. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91989. * pointer may be \c NULL if the callback is not
  91990. * desired.
  91991. * \param client_data This value will be supplied to callbacks in their
  91992. * \a client_data argument.
  91993. * \assert
  91994. * \code encoder != NULL \endcode
  91995. * \retval FLAC__StreamEncoderInitStatus
  91996. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91997. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91998. */
  91999. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92000. /** Finish the encoding process.
  92001. * Flushes the encoding buffer, releases resources, resets the encoder
  92002. * settings to their defaults, and returns the encoder state to
  92003. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  92004. * one or more write callbacks before returning, and will generate
  92005. * a metadata callback.
  92006. *
  92007. * Note that in the course of processing the last frame, errors can
  92008. * occur, so the caller should be sure to check the return value to
  92009. * ensure the file was encoded properly.
  92010. *
  92011. * In the event of a prematurely-terminated encode, it is not strictly
  92012. * necessary to call this immediately before FLAC__stream_encoder_delete()
  92013. * but it is good practice to match every FLAC__stream_encoder_init_*()
  92014. * with a FLAC__stream_encoder_finish().
  92015. *
  92016. * \param encoder An uninitialized encoder instance.
  92017. * \assert
  92018. * \code encoder != NULL \endcode
  92019. * \retval FLAC__bool
  92020. * \c false if an error occurred processing the last frame; or if verify
  92021. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92022. * verify mismatch; else \c true. If \c false, caller should check the
  92023. * state with FLAC__stream_encoder_get_state() for more information
  92024. * about the error.
  92025. */
  92026. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92027. /** Submit data for encoding.
  92028. * This version allows you to supply the input data via an array of
  92029. * pointers, each pointer pointing to an array of \a samples samples
  92030. * representing one channel. The samples need not be block-aligned,
  92031. * but each channel should have the same number of samples. Each sample
  92032. * should be a signed integer, right-justified to the resolution set by
  92033. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92034. * resolution is 16 bits per sample, the samples should all be in the
  92035. * range [-32768,32767].
  92036. *
  92037. * For applications where channel order is important, channels must
  92038. * follow the order as described in the
  92039. * <A HREF="../format.html#frame_header">frame header</A>.
  92040. *
  92041. * \param encoder An initialized encoder instance in the OK state.
  92042. * \param buffer An array of pointers to each channel's signal.
  92043. * \param samples The number of samples in one channel.
  92044. * \assert
  92045. * \code encoder != NULL \endcode
  92046. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92047. * \retval FLAC__bool
  92048. * \c true if successful, else \c false; in this case, check the
  92049. * encoder state with FLAC__stream_encoder_get_state() to see what
  92050. * went wrong.
  92051. */
  92052. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92053. /** Submit data for encoding.
  92054. * This version allows you to supply the input data where the channels
  92055. * are interleaved into a single array (i.e. channel0_sample0,
  92056. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92057. * The samples need not be block-aligned but they must be
  92058. * sample-aligned, i.e. the first value should be channel0_sample0
  92059. * and the last value channelN_sampleM. Each sample should be a signed
  92060. * integer, right-justified to the resolution set by
  92061. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92062. * resolution is 16 bits per sample, the samples should all be in the
  92063. * range [-32768,32767].
  92064. *
  92065. * For applications where channel order is important, channels must
  92066. * follow the order as described in the
  92067. * <A HREF="../format.html#frame_header">frame header</A>.
  92068. *
  92069. * \param encoder An initialized encoder instance in the OK state.
  92070. * \param buffer An array of channel-interleaved data (see above).
  92071. * \param samples The number of samples in one channel, the same as for
  92072. * FLAC__stream_encoder_process(). For example, if
  92073. * encoding two channels, \c 1000 \a samples corresponds
  92074. * to a \a buffer of 2000 values.
  92075. * \assert
  92076. * \code encoder != NULL \endcode
  92077. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92078. * \retval FLAC__bool
  92079. * \c true if successful, else \c false; in this case, check the
  92080. * encoder state with FLAC__stream_encoder_get_state() to see what
  92081. * went wrong.
  92082. */
  92083. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92084. /* \} */
  92085. #ifdef __cplusplus
  92086. }
  92087. #endif
  92088. #endif
  92089. /*** End of inlined file: stream_encoder.h ***/
  92090. #ifdef _MSC_VER
  92091. /* OPT: an MSVC built-in would be better */
  92092. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92093. {
  92094. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92095. return (x>>16) | (x<<16);
  92096. }
  92097. #endif
  92098. #if defined(_MSC_VER) && defined(_X86_)
  92099. /* OPT: an MSVC built-in would be better */
  92100. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92101. {
  92102. __asm {
  92103. mov edx, start
  92104. mov ecx, len
  92105. test ecx, ecx
  92106. loop1:
  92107. jz done1
  92108. mov eax, [edx]
  92109. bswap eax
  92110. mov [edx], eax
  92111. add edx, 4
  92112. dec ecx
  92113. jmp short loop1
  92114. done1:
  92115. }
  92116. }
  92117. #endif
  92118. /** \mainpage
  92119. *
  92120. * \section intro Introduction
  92121. *
  92122. * This is the documentation for the FLAC C and C++ APIs. It is
  92123. * highly interconnected; this introduction should give you a top
  92124. * level idea of the structure and how to find the information you
  92125. * need. As a prerequisite you should have at least a basic
  92126. * knowledge of the FLAC format, documented
  92127. * <A HREF="../format.html">here</A>.
  92128. *
  92129. * \section c_api FLAC C API
  92130. *
  92131. * The FLAC C API is the interface to libFLAC, a set of structures
  92132. * describing the components of FLAC streams, and functions for
  92133. * encoding and decoding streams, as well as manipulating FLAC
  92134. * metadata in files. The public include files will be installed
  92135. * in your include area (for example /usr/include/FLAC/...).
  92136. *
  92137. * By writing a little code and linking against libFLAC, it is
  92138. * relatively easy to add FLAC support to another program. The
  92139. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92140. * Complete source code of libFLAC as well as the command-line
  92141. * encoder and plugins is available and is a useful source of
  92142. * examples.
  92143. *
  92144. * Aside from encoders and decoders, libFLAC provides a powerful
  92145. * metadata interface for manipulating metadata in FLAC files. It
  92146. * allows the user to add, delete, and modify FLAC metadata blocks
  92147. * and it can automatically take advantage of PADDING blocks to avoid
  92148. * rewriting the entire FLAC file when changing the size of the
  92149. * metadata.
  92150. *
  92151. * libFLAC usually only requires the standard C library and C math
  92152. * library. In particular, threading is not used so there is no
  92153. * dependency on a thread library. However, libFLAC does not use
  92154. * global variables and should be thread-safe.
  92155. *
  92156. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92157. * However the metadata editing interfaces currently have limited
  92158. * read-only support for Ogg FLAC files.
  92159. *
  92160. * \section cpp_api FLAC C++ API
  92161. *
  92162. * The FLAC C++ API is a set of classes that encapsulate the
  92163. * structures and functions in libFLAC. They provide slightly more
  92164. * functionality with respect to metadata but are otherwise
  92165. * equivalent. For the most part, they share the same usage as
  92166. * their counterparts in libFLAC, and the FLAC C API documentation
  92167. * can be used as a supplement. The public include files
  92168. * for the C++ API will be installed in your include area (for
  92169. * example /usr/include/FLAC++/...).
  92170. *
  92171. * libFLAC++ is also licensed under
  92172. * <A HREF="../license.html">Xiph's BSD license</A>.
  92173. *
  92174. * \section getting_started Getting Started
  92175. *
  92176. * A good starting point for learning the API is to browse through
  92177. * the <A HREF="modules.html">modules</A>. Modules are logical
  92178. * groupings of related functions or classes, which correspond roughly
  92179. * to header files or sections of header files. Each module includes a
  92180. * detailed description of the general usage of its functions or
  92181. * classes.
  92182. *
  92183. * From there you can go on to look at the documentation of
  92184. * individual functions. You can see different views of the individual
  92185. * functions through the links in top bar across this page.
  92186. *
  92187. * If you prefer a more hands-on approach, you can jump right to some
  92188. * <A HREF="../documentation_example_code.html">example code</A>.
  92189. *
  92190. * \section porting_guide Porting Guide
  92191. *
  92192. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92193. * has been introduced which gives detailed instructions on how to
  92194. * port your code to newer versions of FLAC.
  92195. *
  92196. * \section embedded_developers Embedded Developers
  92197. *
  92198. * libFLAC has grown larger over time as more functionality has been
  92199. * included, but much of it may be unnecessary for a particular embedded
  92200. * implementation. Unused parts may be pruned by some simple editing of
  92201. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92202. * metadata interface are all independent from each other.
  92203. *
  92204. * It is easiest to just describe the dependencies:
  92205. *
  92206. * - All modules depend on the \link flac_format Format \endlink module.
  92207. * - The decoders and encoders depend on the bitbuffer.
  92208. * - The decoder is independent of the encoder. The encoder uses the
  92209. * decoder because of the verify feature, but this can be removed if
  92210. * not needed.
  92211. * - Parts of the metadata interface require the stream decoder (but not
  92212. * the encoder).
  92213. * - Ogg support is selectable through the compile time macro
  92214. * \c FLAC__HAS_OGG.
  92215. *
  92216. * For example, if your application only requires the stream decoder, no
  92217. * encoder, and no metadata interface, you can remove the stream encoder
  92218. * and the metadata interface, which will greatly reduce the size of the
  92219. * library.
  92220. *
  92221. * Also, there are several places in the libFLAC code with comments marked
  92222. * with "OPT:" where a #define can be changed to enable code that might be
  92223. * faster on a specific platform. Experimenting with these can yield faster
  92224. * binaries.
  92225. */
  92226. /** \defgroup porting Porting Guide for New Versions
  92227. *
  92228. * This module describes differences in the library interfaces from
  92229. * version to version. It assists in the porting of code that uses
  92230. * the libraries to newer versions of FLAC.
  92231. *
  92232. * One simple facility for making porting easier that has been added
  92233. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92234. * library's includes (e.g. \c include/FLAC/export.h). The
  92235. * \c #defines mirror the libraries'
  92236. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92237. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92238. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92239. * These can be used to support multiple versions of an API during the
  92240. * transition phase, e.g.
  92241. *
  92242. * \code
  92243. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92244. * legacy code
  92245. * #else
  92246. * new code
  92247. * #endif
  92248. * \endcode
  92249. *
  92250. * The the source will work for multiple versions and the legacy code can
  92251. * easily be removed when the transition is complete.
  92252. *
  92253. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92254. * include/FLAC/export.h), which can be used to determine whether or not
  92255. * the library has been compiled with support for Ogg FLAC. This is
  92256. * simpler than trying to call an Ogg init function and catching the
  92257. * error.
  92258. */
  92259. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92260. * \ingroup porting
  92261. *
  92262. * \brief
  92263. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92264. *
  92265. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92266. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92267. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92268. * decoding layers and three encoding layers have been merged into a
  92269. * single stream decoder and stream encoder. That is, the functionality
  92270. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92271. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92272. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92273. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92274. * is there is now a single API that can be used to encode or decode
  92275. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92276. * on both seekable and non-seekable streams.
  92277. *
  92278. * Instead of creating an encoder or decoder of a certain layer, now the
  92279. * client will always create a FLAC__StreamEncoder or
  92280. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92281. * initialization function. For example, for the decoder,
  92282. * FLAC__stream_decoder_init() has been replaced by
  92283. * FLAC__stream_decoder_init_stream(). This init function takes
  92284. * callbacks for the I/O, and the seeking callbacks are optional. This
  92285. * allows the client to use the same object for seekable and
  92286. * non-seekable streams. For decoding a FLAC file directly, the client
  92287. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92288. * and fewer callbacks; most of the other callbacks are supplied
  92289. * internally. For situations where fopen()ing by filename is not
  92290. * possible (e.g. Unicode filenames on Windows) the client can instead
  92291. * open the file itself and supply the FILE* to
  92292. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92293. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92294. * Since the callbacks and client data are now passed to the init
  92295. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92296. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92297. * rest of the calls to the decoder are the same as before.
  92298. *
  92299. * There are counterpart init functions for Ogg FLAC, e.g.
  92300. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92301. * and callbacks are the same as for native FLAC.
  92302. *
  92303. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92304. * been set up like so:
  92305. *
  92306. * \code
  92307. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92308. * if(decoder == NULL) do_something;
  92309. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92310. * [... other settings ...]
  92311. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92312. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92313. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92314. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92315. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92316. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92317. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92318. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92319. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92320. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92321. * \endcode
  92322. *
  92323. * In FLAC 1.1.3 it is like this:
  92324. *
  92325. * \code
  92326. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92327. * if(decoder == NULL) do_something;
  92328. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92329. * [... other settings ...]
  92330. * if(FLAC__stream_decoder_init_stream(
  92331. * decoder,
  92332. * my_read_callback,
  92333. * my_seek_callback, // or NULL
  92334. * my_tell_callback, // or NULL
  92335. * my_length_callback, // or NULL
  92336. * my_eof_callback, // or NULL
  92337. * my_write_callback,
  92338. * my_metadata_callback, // or NULL
  92339. * my_error_callback,
  92340. * my_client_data
  92341. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92342. * \endcode
  92343. *
  92344. * or you could do;
  92345. *
  92346. * \code
  92347. * [...]
  92348. * FILE *file = fopen("somefile.flac","rb");
  92349. * if(file == NULL) do_somthing;
  92350. * if(FLAC__stream_decoder_init_FILE(
  92351. * decoder,
  92352. * file,
  92353. * my_write_callback,
  92354. * my_metadata_callback, // or NULL
  92355. * my_error_callback,
  92356. * my_client_data
  92357. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92358. * \endcode
  92359. *
  92360. * or just:
  92361. *
  92362. * \code
  92363. * [...]
  92364. * if(FLAC__stream_decoder_init_file(
  92365. * decoder,
  92366. * "somefile.flac",
  92367. * my_write_callback,
  92368. * my_metadata_callback, // or NULL
  92369. * my_error_callback,
  92370. * my_client_data
  92371. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92372. * \endcode
  92373. *
  92374. * Another small change to the decoder is in how it handles unparseable
  92375. * streams. Before, when the decoder found an unparseable stream
  92376. * (reserved for when the decoder encounters a stream from a future
  92377. * encoder that it can't parse), it changed the state to
  92378. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92379. * drops sync and calls the error callback with a new error code
  92380. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92381. * more robust. If your error callback does not discriminate on the the
  92382. * error state, your code does not need to be changed.
  92383. *
  92384. * The encoder now has a new setting:
  92385. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92386. * method used to window the data before LPC analysis. You only need to
  92387. * add a call to this function if the default is not suitable. There
  92388. * are also two new convenience functions that may be useful:
  92389. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92390. * FLAC__metadata_get_cuesheet().
  92391. *
  92392. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92393. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92394. * is now \c size_t instead of \c unsigned.
  92395. */
  92396. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92397. * \ingroup porting
  92398. *
  92399. * \brief
  92400. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92401. *
  92402. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92403. * There was a slight change in the implementation of
  92404. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92405. * of the \a metadata array of pointers so the client no longer needs
  92406. * to maintain it after the call. The objects themselves that are
  92407. * pointed to by the array are still not copied though and must be
  92408. * maintained until the call to FLAC__stream_encoder_finish().
  92409. */
  92410. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92411. * \ingroup porting
  92412. *
  92413. * \brief
  92414. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92415. *
  92416. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92417. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92418. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92419. *
  92420. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92421. * has changed to reflect the conversion of one of the reserved bits
  92422. * into active use. It used to be \c 2 and now is \c 1. However the
  92423. * FLAC frame header length has not changed, so to skip the proper
  92424. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92425. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92426. */
  92427. /** \defgroup flac FLAC C API
  92428. *
  92429. * The FLAC C API is the interface to libFLAC, a set of structures
  92430. * describing the components of FLAC streams, and functions for
  92431. * encoding and decoding streams, as well as manipulating FLAC
  92432. * metadata in files.
  92433. *
  92434. * You should start with the format components as all other modules
  92435. * are dependent on it.
  92436. */
  92437. #endif
  92438. /*** End of inlined file: all.h ***/
  92439. /*** Start of inlined file: bitmath.c ***/
  92440. /*** Start of inlined file: juce_FlacHeader.h ***/
  92441. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92442. // tasks..
  92443. #define VERSION "1.2.1"
  92444. #define FLAC__NO_DLL 1
  92445. #if JUCE_MSVC
  92446. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92447. #endif
  92448. #if JUCE_MAC
  92449. #define FLAC__SYS_DARWIN 1
  92450. #endif
  92451. /*** End of inlined file: juce_FlacHeader.h ***/
  92452. #if JUCE_USE_FLAC
  92453. #if HAVE_CONFIG_H
  92454. # include <config.h>
  92455. #endif
  92456. /*** Start of inlined file: bitmath.h ***/
  92457. #ifndef FLAC__PRIVATE__BITMATH_H
  92458. #define FLAC__PRIVATE__BITMATH_H
  92459. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92460. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92461. unsigned FLAC__bitmath_silog2(int v);
  92462. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92463. #endif
  92464. /*** End of inlined file: bitmath.h ***/
  92465. /* An example of what FLAC__bitmath_ilog2() computes:
  92466. *
  92467. * ilog2( 0) = assertion failure
  92468. * ilog2( 1) = 0
  92469. * ilog2( 2) = 1
  92470. * ilog2( 3) = 1
  92471. * ilog2( 4) = 2
  92472. * ilog2( 5) = 2
  92473. * ilog2( 6) = 2
  92474. * ilog2( 7) = 2
  92475. * ilog2( 8) = 3
  92476. * ilog2( 9) = 3
  92477. * ilog2(10) = 3
  92478. * ilog2(11) = 3
  92479. * ilog2(12) = 3
  92480. * ilog2(13) = 3
  92481. * ilog2(14) = 3
  92482. * ilog2(15) = 3
  92483. * ilog2(16) = 4
  92484. * ilog2(17) = 4
  92485. * ilog2(18) = 4
  92486. */
  92487. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92488. {
  92489. unsigned l = 0;
  92490. FLAC__ASSERT(v > 0);
  92491. while(v >>= 1)
  92492. l++;
  92493. return l;
  92494. }
  92495. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92496. {
  92497. unsigned l = 0;
  92498. FLAC__ASSERT(v > 0);
  92499. while(v >>= 1)
  92500. l++;
  92501. return l;
  92502. }
  92503. /* An example of what FLAC__bitmath_silog2() computes:
  92504. *
  92505. * silog2(-10) = 5
  92506. * silog2(- 9) = 5
  92507. * silog2(- 8) = 4
  92508. * silog2(- 7) = 4
  92509. * silog2(- 6) = 4
  92510. * silog2(- 5) = 4
  92511. * silog2(- 4) = 3
  92512. * silog2(- 3) = 3
  92513. * silog2(- 2) = 2
  92514. * silog2(- 1) = 2
  92515. * silog2( 0) = 0
  92516. * silog2( 1) = 2
  92517. * silog2( 2) = 3
  92518. * silog2( 3) = 3
  92519. * silog2( 4) = 4
  92520. * silog2( 5) = 4
  92521. * silog2( 6) = 4
  92522. * silog2( 7) = 4
  92523. * silog2( 8) = 5
  92524. * silog2( 9) = 5
  92525. * silog2( 10) = 5
  92526. */
  92527. unsigned FLAC__bitmath_silog2(int v)
  92528. {
  92529. while(1) {
  92530. if(v == 0) {
  92531. return 0;
  92532. }
  92533. else if(v > 0) {
  92534. unsigned l = 0;
  92535. while(v) {
  92536. l++;
  92537. v >>= 1;
  92538. }
  92539. return l+1;
  92540. }
  92541. else if(v == -1) {
  92542. return 2;
  92543. }
  92544. else {
  92545. v++;
  92546. v = -v;
  92547. }
  92548. }
  92549. }
  92550. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  92551. {
  92552. while(1) {
  92553. if(v == 0) {
  92554. return 0;
  92555. }
  92556. else if(v > 0) {
  92557. unsigned l = 0;
  92558. while(v) {
  92559. l++;
  92560. v >>= 1;
  92561. }
  92562. return l+1;
  92563. }
  92564. else if(v == -1) {
  92565. return 2;
  92566. }
  92567. else {
  92568. v++;
  92569. v = -v;
  92570. }
  92571. }
  92572. }
  92573. #endif
  92574. /*** End of inlined file: bitmath.c ***/
  92575. /*** Start of inlined file: bitreader.c ***/
  92576. /*** Start of inlined file: juce_FlacHeader.h ***/
  92577. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92578. // tasks..
  92579. #define VERSION "1.2.1"
  92580. #define FLAC__NO_DLL 1
  92581. #if JUCE_MSVC
  92582. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92583. #endif
  92584. #if JUCE_MAC
  92585. #define FLAC__SYS_DARWIN 1
  92586. #endif
  92587. /*** End of inlined file: juce_FlacHeader.h ***/
  92588. #if JUCE_USE_FLAC
  92589. #if HAVE_CONFIG_H
  92590. # include <config.h>
  92591. #endif
  92592. #include <stdlib.h> /* for malloc() */
  92593. #include <string.h> /* for memcpy(), memset() */
  92594. #ifdef _MSC_VER
  92595. #include <winsock.h> /* for ntohl() */
  92596. #elif defined FLAC__SYS_DARWIN
  92597. #include <machine/endian.h> /* for ntohl() */
  92598. #elif defined __MINGW32__
  92599. #include <winsock.h> /* for ntohl() */
  92600. #else
  92601. #include <netinet/in.h> /* for ntohl() */
  92602. #endif
  92603. /*** Start of inlined file: bitreader.h ***/
  92604. #ifndef FLAC__PRIVATE__BITREADER_H
  92605. #define FLAC__PRIVATE__BITREADER_H
  92606. #include <stdio.h> /* for FILE */
  92607. /*** Start of inlined file: cpu.h ***/
  92608. #ifndef FLAC__PRIVATE__CPU_H
  92609. #define FLAC__PRIVATE__CPU_H
  92610. #ifdef HAVE_CONFIG_H
  92611. #include <config.h>
  92612. #endif
  92613. typedef enum {
  92614. FLAC__CPUINFO_TYPE_IA32,
  92615. FLAC__CPUINFO_TYPE_PPC,
  92616. FLAC__CPUINFO_TYPE_UNKNOWN
  92617. } FLAC__CPUInfo_Type;
  92618. typedef struct {
  92619. FLAC__bool cpuid;
  92620. FLAC__bool bswap;
  92621. FLAC__bool cmov;
  92622. FLAC__bool mmx;
  92623. FLAC__bool fxsr;
  92624. FLAC__bool sse;
  92625. FLAC__bool sse2;
  92626. FLAC__bool sse3;
  92627. FLAC__bool ssse3;
  92628. FLAC__bool _3dnow;
  92629. FLAC__bool ext3dnow;
  92630. FLAC__bool extmmx;
  92631. } FLAC__CPUInfo_IA32;
  92632. typedef struct {
  92633. FLAC__bool altivec;
  92634. FLAC__bool ppc64;
  92635. } FLAC__CPUInfo_PPC;
  92636. typedef struct {
  92637. FLAC__bool use_asm;
  92638. FLAC__CPUInfo_Type type;
  92639. union {
  92640. FLAC__CPUInfo_IA32 ia32;
  92641. FLAC__CPUInfo_PPC ppc;
  92642. } data;
  92643. } FLAC__CPUInfo;
  92644. void FLAC__cpu_info(FLAC__CPUInfo *info);
  92645. #ifndef FLAC__NO_ASM
  92646. #ifdef FLAC__CPU_IA32
  92647. #ifdef FLAC__HAS_NASM
  92648. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  92649. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  92650. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  92651. #endif
  92652. #endif
  92653. #endif
  92654. #endif
  92655. /*** End of inlined file: cpu.h ***/
  92656. /*
  92657. * opaque structure definition
  92658. */
  92659. struct FLAC__BitReader;
  92660. typedef struct FLAC__BitReader FLAC__BitReader;
  92661. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  92662. /*
  92663. * construction, deletion, initialization, etc functions
  92664. */
  92665. FLAC__BitReader *FLAC__bitreader_new(void);
  92666. void FLAC__bitreader_delete(FLAC__BitReader *br);
  92667. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  92668. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  92669. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  92670. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  92671. /*
  92672. * CRC functions
  92673. */
  92674. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  92675. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  92676. /*
  92677. * info functions
  92678. */
  92679. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  92680. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  92681. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  92682. /*
  92683. * read functions
  92684. */
  92685. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  92686. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  92687. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  92688. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  92689. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  92690. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  92691. 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! */
  92692. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  92693. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92694. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92695. #ifndef FLAC__NO_ASM
  92696. # ifdef FLAC__CPU_IA32
  92697. # ifdef FLAC__HAS_NASM
  92698. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92699. # endif
  92700. # endif
  92701. #endif
  92702. #if 0 /* UNUSED */
  92703. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92704. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  92705. #endif
  92706. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  92707. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  92708. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  92709. #endif
  92710. /*** End of inlined file: bitreader.h ***/
  92711. /*** Start of inlined file: crc.h ***/
  92712. #ifndef FLAC__PRIVATE__CRC_H
  92713. #define FLAC__PRIVATE__CRC_H
  92714. /* 8 bit CRC generator, MSB shifted first
  92715. ** polynomial = x^8 + x^2 + x^1 + x^0
  92716. ** init = 0
  92717. */
  92718. extern FLAC__byte const FLAC__crc8_table[256];
  92719. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  92720. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  92721. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  92722. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  92723. /* 16 bit CRC generator, MSB shifted first
  92724. ** polynomial = x^16 + x^15 + x^2 + x^0
  92725. ** init = 0
  92726. */
  92727. extern unsigned FLAC__crc16_table[256];
  92728. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  92729. /* this alternate may be faster on some systems/compilers */
  92730. #if 0
  92731. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  92732. #endif
  92733. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  92734. #endif
  92735. /*** End of inlined file: crc.h ***/
  92736. /* Things should be fastest when this matches the machine word size */
  92737. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  92738. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  92739. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  92740. typedef FLAC__uint32 brword;
  92741. #define FLAC__BYTES_PER_WORD 4
  92742. #define FLAC__BITS_PER_WORD 32
  92743. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  92744. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  92745. #if WORDS_BIGENDIAN
  92746. #define SWAP_BE_WORD_TO_HOST(x) (x)
  92747. #else
  92748. #if defined (_MSC_VER) && defined (_X86_)
  92749. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  92750. #else
  92751. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  92752. #endif
  92753. #endif
  92754. /* counts the # of zero MSBs in a word */
  92755. #define COUNT_ZERO_MSBS(word) ( \
  92756. (word) <= 0xffff ? \
  92757. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  92758. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  92759. )
  92760. /* this alternate might be slightly faster on some systems/compilers: */
  92761. #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])) )
  92762. /*
  92763. * This should be at least twice as large as the largest number of words
  92764. * required to represent any 'number' (in any encoding) you are going to
  92765. * read. With FLAC this is on the order of maybe a few hundred bits.
  92766. * If the buffer is smaller than that, the decoder won't be able to read
  92767. * in a whole number that is in a variable length encoding (e.g. Rice).
  92768. * But to be practical it should be at least 1K bytes.
  92769. *
  92770. * Increase this number to decrease the number of read callbacks, at the
  92771. * expense of using more memory. Or decrease for the reverse effect,
  92772. * keeping in mind the limit from the first paragraph. The optimal size
  92773. * also depends on the CPU cache size and other factors; some twiddling
  92774. * may be necessary to squeeze out the best performance.
  92775. */
  92776. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  92777. static const unsigned char byte_to_unary_table[] = {
  92778. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  92779. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  92780. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92781. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92782. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92783. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92784. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92785. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  92794. };
  92795. #ifdef min
  92796. #undef min
  92797. #endif
  92798. #define min(x,y) ((x)<(y)?(x):(y))
  92799. #ifdef max
  92800. #undef max
  92801. #endif
  92802. #define max(x,y) ((x)>(y)?(x):(y))
  92803. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92804. #ifdef _MSC_VER
  92805. #define FLAC__U64L(x) x
  92806. #else
  92807. #define FLAC__U64L(x) x##LLU
  92808. #endif
  92809. #ifndef FLaC__INLINE
  92810. #define FLaC__INLINE
  92811. #endif
  92812. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  92813. struct FLAC__BitReader {
  92814. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  92815. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  92816. brword *buffer;
  92817. unsigned capacity; /* in words */
  92818. unsigned words; /* # of completed words in buffer */
  92819. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  92820. unsigned consumed_words; /* #words ... */
  92821. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  92822. unsigned read_crc16; /* the running frame CRC */
  92823. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  92824. FLAC__BitReaderReadCallback read_callback;
  92825. void *client_data;
  92826. FLAC__CPUInfo cpu_info;
  92827. };
  92828. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  92829. {
  92830. register unsigned crc = br->read_crc16;
  92831. #if FLAC__BYTES_PER_WORD == 4
  92832. switch(br->crc16_align) {
  92833. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  92834. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92835. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92836. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92837. }
  92838. #elif FLAC__BYTES_PER_WORD == 8
  92839. switch(br->crc16_align) {
  92840. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  92841. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  92842. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  92843. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  92844. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  92845. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92846. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92847. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92848. }
  92849. #else
  92850. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  92851. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  92852. br->read_crc16 = crc;
  92853. #endif
  92854. br->crc16_align = 0;
  92855. }
  92856. /* would be static except it needs to be called by asm routines */
  92857. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  92858. {
  92859. unsigned start, end;
  92860. size_t bytes;
  92861. FLAC__byte *target;
  92862. /* first shift the unconsumed buffer data toward the front as much as possible */
  92863. if(br->consumed_words > 0) {
  92864. start = br->consumed_words;
  92865. end = br->words + (br->bytes? 1:0);
  92866. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  92867. br->words -= start;
  92868. br->consumed_words = 0;
  92869. }
  92870. /*
  92871. * set the target for reading, taking into account word alignment and endianness
  92872. */
  92873. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  92874. if(bytes == 0)
  92875. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  92876. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  92877. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  92878. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  92879. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  92880. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  92881. * ^^-------target, bytes=3
  92882. * on LE machines, have to byteswap the odd tail word so nothing is
  92883. * overwritten:
  92884. */
  92885. #if WORDS_BIGENDIAN
  92886. #else
  92887. if(br->bytes)
  92888. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  92889. #endif
  92890. /* now it looks like:
  92891. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  92892. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  92893. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  92894. * ^^-------target, bytes=3
  92895. */
  92896. /* read in the data; note that the callback may return a smaller number of bytes */
  92897. if(!br->read_callback(target, &bytes, br->client_data))
  92898. return false;
  92899. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  92900. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92901. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92902. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  92903. * now have to byteswap on LE machines:
  92904. */
  92905. #if WORDS_BIGENDIAN
  92906. #else
  92907. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  92908. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  92909. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  92910. start = br->words;
  92911. local_swap32_block_(br->buffer + start, end - start);
  92912. }
  92913. else
  92914. # endif
  92915. for(start = br->words; start < end; start++)
  92916. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  92917. #endif
  92918. /* now it looks like:
  92919. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92920. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92921. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  92922. * finally we'll update the reader values:
  92923. */
  92924. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  92925. br->words = end / FLAC__BYTES_PER_WORD;
  92926. br->bytes = end % FLAC__BYTES_PER_WORD;
  92927. return true;
  92928. }
  92929. /***********************************************************************
  92930. *
  92931. * Class constructor/destructor
  92932. *
  92933. ***********************************************************************/
  92934. FLAC__BitReader *FLAC__bitreader_new(void)
  92935. {
  92936. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  92937. /* calloc() implies:
  92938. memset(br, 0, sizeof(FLAC__BitReader));
  92939. br->buffer = 0;
  92940. br->capacity = 0;
  92941. br->words = br->bytes = 0;
  92942. br->consumed_words = br->consumed_bits = 0;
  92943. br->read_callback = 0;
  92944. br->client_data = 0;
  92945. */
  92946. return br;
  92947. }
  92948. void FLAC__bitreader_delete(FLAC__BitReader *br)
  92949. {
  92950. FLAC__ASSERT(0 != br);
  92951. FLAC__bitreader_free(br);
  92952. free(br);
  92953. }
  92954. /***********************************************************************
  92955. *
  92956. * Public class methods
  92957. *
  92958. ***********************************************************************/
  92959. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  92960. {
  92961. FLAC__ASSERT(0 != br);
  92962. br->words = br->bytes = 0;
  92963. br->consumed_words = br->consumed_bits = 0;
  92964. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  92965. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  92966. if(br->buffer == 0)
  92967. return false;
  92968. br->read_callback = rcb;
  92969. br->client_data = cd;
  92970. br->cpu_info = cpu;
  92971. return true;
  92972. }
  92973. void FLAC__bitreader_free(FLAC__BitReader *br)
  92974. {
  92975. FLAC__ASSERT(0 != br);
  92976. if(0 != br->buffer)
  92977. free(br->buffer);
  92978. br->buffer = 0;
  92979. br->capacity = 0;
  92980. br->words = br->bytes = 0;
  92981. br->consumed_words = br->consumed_bits = 0;
  92982. br->read_callback = 0;
  92983. br->client_data = 0;
  92984. }
  92985. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  92986. {
  92987. br->words = br->bytes = 0;
  92988. br->consumed_words = br->consumed_bits = 0;
  92989. return true;
  92990. }
  92991. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  92992. {
  92993. unsigned i, j;
  92994. if(br == 0) {
  92995. fprintf(out, "bitreader is NULL\n");
  92996. }
  92997. else {
  92998. 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);
  92999. for(i = 0; i < br->words; i++) {
  93000. fprintf(out, "%08X: ", i);
  93001. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93002. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93003. fprintf(out, ".");
  93004. else
  93005. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93006. fprintf(out, "\n");
  93007. }
  93008. if(br->bytes > 0) {
  93009. fprintf(out, "%08X: ", i);
  93010. for(j = 0; j < br->bytes*8; j++)
  93011. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93012. fprintf(out, ".");
  93013. else
  93014. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  93015. fprintf(out, "\n");
  93016. }
  93017. }
  93018. }
  93019. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93020. {
  93021. FLAC__ASSERT(0 != br);
  93022. FLAC__ASSERT(0 != br->buffer);
  93023. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93024. br->read_crc16 = (unsigned)seed;
  93025. br->crc16_align = br->consumed_bits;
  93026. }
  93027. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93028. {
  93029. FLAC__ASSERT(0 != br);
  93030. FLAC__ASSERT(0 != br->buffer);
  93031. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93032. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93033. /* CRC any tail bytes in a partially-consumed word */
  93034. if(br->consumed_bits) {
  93035. const brword tail = br->buffer[br->consumed_words];
  93036. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93037. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93038. }
  93039. return br->read_crc16;
  93040. }
  93041. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93042. {
  93043. return ((br->consumed_bits & 7) == 0);
  93044. }
  93045. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93046. {
  93047. return 8 - (br->consumed_bits & 7);
  93048. }
  93049. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93050. {
  93051. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93052. }
  93053. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93054. {
  93055. FLAC__ASSERT(0 != br);
  93056. FLAC__ASSERT(0 != br->buffer);
  93057. FLAC__ASSERT(bits <= 32);
  93058. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93059. FLAC__ASSERT(br->consumed_words <= br->words);
  93060. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93061. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93062. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93063. *val = 0;
  93064. return true;
  93065. }
  93066. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93067. if(!bitreader_read_from_client_(br))
  93068. return false;
  93069. }
  93070. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93071. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93072. if(br->consumed_bits) {
  93073. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93074. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93075. const brword word = br->buffer[br->consumed_words];
  93076. if(bits < n) {
  93077. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93078. br->consumed_bits += bits;
  93079. return true;
  93080. }
  93081. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93082. bits -= n;
  93083. crc16_update_word_(br, word);
  93084. br->consumed_words++;
  93085. br->consumed_bits = 0;
  93086. 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 */
  93087. *val <<= bits;
  93088. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93089. br->consumed_bits = bits;
  93090. }
  93091. return true;
  93092. }
  93093. else {
  93094. const brword word = br->buffer[br->consumed_words];
  93095. if(bits < FLAC__BITS_PER_WORD) {
  93096. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93097. br->consumed_bits = bits;
  93098. return true;
  93099. }
  93100. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93101. *val = word;
  93102. crc16_update_word_(br, word);
  93103. br->consumed_words++;
  93104. return true;
  93105. }
  93106. }
  93107. else {
  93108. /* in this case we're starting our read at a partial tail word;
  93109. * the reader has guaranteed that we have at least 'bits' bits
  93110. * available to read, which makes this case simpler.
  93111. */
  93112. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93113. if(br->consumed_bits) {
  93114. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93115. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93116. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93117. br->consumed_bits += bits;
  93118. return true;
  93119. }
  93120. else {
  93121. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93122. br->consumed_bits += bits;
  93123. return true;
  93124. }
  93125. }
  93126. }
  93127. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93128. {
  93129. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93130. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93131. return false;
  93132. /* sign-extend: */
  93133. *val <<= (32-bits);
  93134. *val >>= (32-bits);
  93135. return true;
  93136. }
  93137. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93138. {
  93139. FLAC__uint32 hi, lo;
  93140. if(bits > 32) {
  93141. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93142. return false;
  93143. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93144. return false;
  93145. *val = hi;
  93146. *val <<= 32;
  93147. *val |= lo;
  93148. }
  93149. else {
  93150. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93151. return false;
  93152. *val = lo;
  93153. }
  93154. return true;
  93155. }
  93156. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93157. {
  93158. FLAC__uint32 x8, x32 = 0;
  93159. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93160. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93161. return false;
  93162. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93163. return false;
  93164. x32 |= (x8 << 8);
  93165. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93166. return false;
  93167. x32 |= (x8 << 16);
  93168. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93169. return false;
  93170. x32 |= (x8 << 24);
  93171. *val = x32;
  93172. return true;
  93173. }
  93174. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93175. {
  93176. /*
  93177. * OPT: a faster implementation is possible but probably not that useful
  93178. * since this is only called a couple of times in the metadata readers.
  93179. */
  93180. FLAC__ASSERT(0 != br);
  93181. FLAC__ASSERT(0 != br->buffer);
  93182. if(bits > 0) {
  93183. const unsigned n = br->consumed_bits & 7;
  93184. unsigned m;
  93185. FLAC__uint32 x;
  93186. if(n != 0) {
  93187. m = min(8-n, bits);
  93188. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93189. return false;
  93190. bits -= m;
  93191. }
  93192. m = bits / 8;
  93193. if(m > 0) {
  93194. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93195. return false;
  93196. bits %= 8;
  93197. }
  93198. if(bits > 0) {
  93199. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93200. return false;
  93201. }
  93202. }
  93203. return true;
  93204. }
  93205. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93206. {
  93207. FLAC__uint32 x;
  93208. FLAC__ASSERT(0 != br);
  93209. FLAC__ASSERT(0 != br->buffer);
  93210. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93211. /* step 1: skip over partial head word to get word aligned */
  93212. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93213. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93214. return false;
  93215. nvals--;
  93216. }
  93217. if(0 == nvals)
  93218. return true;
  93219. /* step 2: skip whole words in chunks */
  93220. while(nvals >= FLAC__BYTES_PER_WORD) {
  93221. if(br->consumed_words < br->words) {
  93222. br->consumed_words++;
  93223. nvals -= FLAC__BYTES_PER_WORD;
  93224. }
  93225. else if(!bitreader_read_from_client_(br))
  93226. return false;
  93227. }
  93228. /* step 3: skip any remainder from partial tail bytes */
  93229. while(nvals) {
  93230. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93231. return false;
  93232. nvals--;
  93233. }
  93234. return true;
  93235. }
  93236. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93237. {
  93238. FLAC__uint32 x;
  93239. FLAC__ASSERT(0 != br);
  93240. FLAC__ASSERT(0 != br->buffer);
  93241. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93242. /* step 1: read from partial head word to get word aligned */
  93243. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93244. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93245. return false;
  93246. *val++ = (FLAC__byte)x;
  93247. nvals--;
  93248. }
  93249. if(0 == nvals)
  93250. return true;
  93251. /* step 2: read whole words in chunks */
  93252. while(nvals >= FLAC__BYTES_PER_WORD) {
  93253. if(br->consumed_words < br->words) {
  93254. const brword word = br->buffer[br->consumed_words++];
  93255. #if FLAC__BYTES_PER_WORD == 4
  93256. val[0] = (FLAC__byte)(word >> 24);
  93257. val[1] = (FLAC__byte)(word >> 16);
  93258. val[2] = (FLAC__byte)(word >> 8);
  93259. val[3] = (FLAC__byte)word;
  93260. #elif FLAC__BYTES_PER_WORD == 8
  93261. val[0] = (FLAC__byte)(word >> 56);
  93262. val[1] = (FLAC__byte)(word >> 48);
  93263. val[2] = (FLAC__byte)(word >> 40);
  93264. val[3] = (FLAC__byte)(word >> 32);
  93265. val[4] = (FLAC__byte)(word >> 24);
  93266. val[5] = (FLAC__byte)(word >> 16);
  93267. val[6] = (FLAC__byte)(word >> 8);
  93268. val[7] = (FLAC__byte)word;
  93269. #else
  93270. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93271. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93272. #endif
  93273. val += FLAC__BYTES_PER_WORD;
  93274. nvals -= FLAC__BYTES_PER_WORD;
  93275. }
  93276. else if(!bitreader_read_from_client_(br))
  93277. return false;
  93278. }
  93279. /* step 3: read any remainder from partial tail bytes */
  93280. while(nvals) {
  93281. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93282. return false;
  93283. *val++ = (FLAC__byte)x;
  93284. nvals--;
  93285. }
  93286. return true;
  93287. }
  93288. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93289. #if 0 /* slow but readable version */
  93290. {
  93291. unsigned bit;
  93292. FLAC__ASSERT(0 != br);
  93293. FLAC__ASSERT(0 != br->buffer);
  93294. *val = 0;
  93295. while(1) {
  93296. if(!FLAC__bitreader_read_bit(br, &bit))
  93297. return false;
  93298. if(bit)
  93299. break;
  93300. else
  93301. *val++;
  93302. }
  93303. return true;
  93304. }
  93305. #else
  93306. {
  93307. unsigned i;
  93308. FLAC__ASSERT(0 != br);
  93309. FLAC__ASSERT(0 != br->buffer);
  93310. *val = 0;
  93311. while(1) {
  93312. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93313. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93314. if(b) {
  93315. i = COUNT_ZERO_MSBS(b);
  93316. *val += i;
  93317. i++;
  93318. br->consumed_bits += i;
  93319. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93320. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93321. br->consumed_words++;
  93322. br->consumed_bits = 0;
  93323. }
  93324. return true;
  93325. }
  93326. else {
  93327. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93328. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93329. br->consumed_words++;
  93330. br->consumed_bits = 0;
  93331. /* didn't find stop bit yet, have to keep going... */
  93332. }
  93333. }
  93334. /* at this point we've eaten up all the whole words; have to try
  93335. * reading through any tail bytes before calling the read callback.
  93336. * this is a repeat of the above logic adjusted for the fact we
  93337. * don't have a whole word. note though if the client is feeding
  93338. * us data a byte at a time (unlikely), br->consumed_bits may not
  93339. * be zero.
  93340. */
  93341. if(br->bytes) {
  93342. const unsigned end = br->bytes * 8;
  93343. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93344. if(b) {
  93345. i = COUNT_ZERO_MSBS(b);
  93346. *val += i;
  93347. i++;
  93348. br->consumed_bits += i;
  93349. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93350. return true;
  93351. }
  93352. else {
  93353. *val += end - br->consumed_bits;
  93354. br->consumed_bits += end;
  93355. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93356. /* didn't find stop bit yet, have to keep going... */
  93357. }
  93358. }
  93359. if(!bitreader_read_from_client_(br))
  93360. return false;
  93361. }
  93362. }
  93363. #endif
  93364. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93365. {
  93366. FLAC__uint32 lsbs = 0, msbs = 0;
  93367. unsigned uval;
  93368. FLAC__ASSERT(0 != br);
  93369. FLAC__ASSERT(0 != br->buffer);
  93370. FLAC__ASSERT(parameter <= 31);
  93371. /* read the unary MSBs and end bit */
  93372. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93373. return false;
  93374. /* read the binary LSBs */
  93375. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93376. return false;
  93377. /* compose the value */
  93378. uval = (msbs << parameter) | lsbs;
  93379. if(uval & 1)
  93380. *val = -((int)(uval >> 1)) - 1;
  93381. else
  93382. *val = (int)(uval >> 1);
  93383. return true;
  93384. }
  93385. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93386. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93387. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93388. /* OPT: possibly faster version for use with MSVC */
  93389. #ifdef _MSC_VER
  93390. {
  93391. unsigned i;
  93392. unsigned uval = 0;
  93393. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93394. /* try and get br->consumed_words and br->consumed_bits into register;
  93395. * must remember to flush them back to *br before calling other
  93396. * bitwriter functions that use them, and before returning */
  93397. register unsigned cwords;
  93398. register unsigned cbits;
  93399. FLAC__ASSERT(0 != br);
  93400. FLAC__ASSERT(0 != br->buffer);
  93401. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93402. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93403. FLAC__ASSERT(parameter < 32);
  93404. /* 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 */
  93405. if(nvals == 0)
  93406. return true;
  93407. cbits = br->consumed_bits;
  93408. cwords = br->consumed_words;
  93409. while(1) {
  93410. /* read unary part */
  93411. while(1) {
  93412. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93413. brword b = br->buffer[cwords] << cbits;
  93414. if(b) {
  93415. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93416. __asm {
  93417. bsr eax, b
  93418. not eax
  93419. and eax, 31
  93420. mov i, eax
  93421. }
  93422. #else
  93423. i = COUNT_ZERO_MSBS(b);
  93424. #endif
  93425. uval += i;
  93426. bits = parameter;
  93427. i++;
  93428. cbits += i;
  93429. if(cbits == FLAC__BITS_PER_WORD) {
  93430. crc16_update_word_(br, br->buffer[cwords]);
  93431. cwords++;
  93432. cbits = 0;
  93433. }
  93434. goto break1;
  93435. }
  93436. else {
  93437. uval += FLAC__BITS_PER_WORD - cbits;
  93438. crc16_update_word_(br, br->buffer[cwords]);
  93439. cwords++;
  93440. cbits = 0;
  93441. /* didn't find stop bit yet, have to keep going... */
  93442. }
  93443. }
  93444. /* at this point we've eaten up all the whole words; have to try
  93445. * reading through any tail bytes before calling the read callback.
  93446. * this is a repeat of the above logic adjusted for the fact we
  93447. * don't have a whole word. note though if the client is feeding
  93448. * us data a byte at a time (unlikely), br->consumed_bits may not
  93449. * be zero.
  93450. */
  93451. if(br->bytes) {
  93452. const unsigned end = br->bytes * 8;
  93453. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93454. if(b) {
  93455. i = COUNT_ZERO_MSBS(b);
  93456. uval += i;
  93457. bits = parameter;
  93458. i++;
  93459. cbits += i;
  93460. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93461. goto break1;
  93462. }
  93463. else {
  93464. uval += end - cbits;
  93465. cbits += end;
  93466. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93467. /* didn't find stop bit yet, have to keep going... */
  93468. }
  93469. }
  93470. /* flush registers and read; bitreader_read_from_client_() does
  93471. * not touch br->consumed_bits at all but we still need to set
  93472. * it in case it fails and we have to return false.
  93473. */
  93474. br->consumed_bits = cbits;
  93475. br->consumed_words = cwords;
  93476. if(!bitreader_read_from_client_(br))
  93477. return false;
  93478. cwords = br->consumed_words;
  93479. }
  93480. break1:
  93481. /* read binary part */
  93482. FLAC__ASSERT(cwords <= br->words);
  93483. if(bits) {
  93484. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93485. /* flush registers and read; bitreader_read_from_client_() does
  93486. * not touch br->consumed_bits at all but we still need to set
  93487. * it in case it fails and we have to return false.
  93488. */
  93489. br->consumed_bits = cbits;
  93490. br->consumed_words = cwords;
  93491. if(!bitreader_read_from_client_(br))
  93492. return false;
  93493. cwords = br->consumed_words;
  93494. }
  93495. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93496. if(cbits) {
  93497. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93498. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93499. const brword word = br->buffer[cwords];
  93500. if(bits < n) {
  93501. uval <<= bits;
  93502. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  93503. cbits += bits;
  93504. goto break2;
  93505. }
  93506. uval <<= n;
  93507. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93508. bits -= n;
  93509. crc16_update_word_(br, word);
  93510. cwords++;
  93511. cbits = 0;
  93512. 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 */
  93513. uval <<= bits;
  93514. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  93515. cbits = bits;
  93516. }
  93517. goto break2;
  93518. }
  93519. else {
  93520. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  93521. uval <<= bits;
  93522. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93523. cbits = bits;
  93524. goto break2;
  93525. }
  93526. }
  93527. else {
  93528. /* in this case we're starting our read at a partial tail word;
  93529. * the reader has guaranteed that we have at least 'bits' bits
  93530. * available to read, which makes this case simpler.
  93531. */
  93532. uval <<= bits;
  93533. if(cbits) {
  93534. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93535. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  93536. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  93537. cbits += bits;
  93538. goto break2;
  93539. }
  93540. else {
  93541. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93542. cbits += bits;
  93543. goto break2;
  93544. }
  93545. }
  93546. }
  93547. break2:
  93548. /* compose the value */
  93549. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93550. /* are we done? */
  93551. --nvals;
  93552. if(nvals == 0) {
  93553. br->consumed_bits = cbits;
  93554. br->consumed_words = cwords;
  93555. return true;
  93556. }
  93557. uval = 0;
  93558. ++vals;
  93559. }
  93560. }
  93561. #else
  93562. {
  93563. unsigned i;
  93564. unsigned uval = 0;
  93565. /* try and get br->consumed_words and br->consumed_bits into register;
  93566. * must remember to flush them back to *br before calling other
  93567. * bitwriter functions that use them, and before returning */
  93568. register unsigned cwords;
  93569. register unsigned cbits;
  93570. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  93571. FLAC__ASSERT(0 != br);
  93572. FLAC__ASSERT(0 != br->buffer);
  93573. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93574. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93575. FLAC__ASSERT(parameter < 32);
  93576. /* 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 */
  93577. if(nvals == 0)
  93578. return true;
  93579. cbits = br->consumed_bits;
  93580. cwords = br->consumed_words;
  93581. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93582. while(1) {
  93583. /* read unary part */
  93584. while(1) {
  93585. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93586. brword b = br->buffer[cwords] << cbits;
  93587. if(b) {
  93588. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  93589. asm volatile (
  93590. "bsrl %1, %0;"
  93591. "notl %0;"
  93592. "andl $31, %0;"
  93593. : "=r"(i)
  93594. : "r"(b)
  93595. );
  93596. #else
  93597. i = COUNT_ZERO_MSBS(b);
  93598. #endif
  93599. uval += i;
  93600. cbits += i;
  93601. cbits++; /* skip over stop bit */
  93602. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  93603. crc16_update_word_(br, br->buffer[cwords]);
  93604. cwords++;
  93605. cbits = 0;
  93606. }
  93607. goto break1;
  93608. }
  93609. else {
  93610. uval += FLAC__BITS_PER_WORD - cbits;
  93611. crc16_update_word_(br, br->buffer[cwords]);
  93612. cwords++;
  93613. cbits = 0;
  93614. /* didn't find stop bit yet, have to keep going... */
  93615. }
  93616. }
  93617. /* at this point we've eaten up all the whole words; have to try
  93618. * reading through any tail bytes before calling the read callback.
  93619. * this is a repeat of the above logic adjusted for the fact we
  93620. * don't have a whole word. note though if the client is feeding
  93621. * us data a byte at a time (unlikely), br->consumed_bits may not
  93622. * be zero.
  93623. */
  93624. if(br->bytes) {
  93625. const unsigned end = br->bytes * 8;
  93626. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  93627. if(b) {
  93628. i = COUNT_ZERO_MSBS(b);
  93629. uval += i;
  93630. cbits += i;
  93631. cbits++; /* skip over stop bit */
  93632. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93633. goto break1;
  93634. }
  93635. else {
  93636. uval += end - cbits;
  93637. cbits += end;
  93638. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93639. /* didn't find stop bit yet, have to keep going... */
  93640. }
  93641. }
  93642. /* flush registers and read; bitreader_read_from_client_() does
  93643. * not touch br->consumed_bits at all but we still need to set
  93644. * it in case it fails and we have to return false.
  93645. */
  93646. br->consumed_bits = cbits;
  93647. br->consumed_words = cwords;
  93648. if(!bitreader_read_from_client_(br))
  93649. return false;
  93650. cwords = br->consumed_words;
  93651. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  93652. /* + uval to offset our count by the # of unary bits already
  93653. * consumed before the read, because we will add these back
  93654. * in all at once at break1
  93655. */
  93656. }
  93657. break1:
  93658. ucbits -= uval;
  93659. ucbits--; /* account for stop bit */
  93660. /* read binary part */
  93661. FLAC__ASSERT(cwords <= br->words);
  93662. if(parameter) {
  93663. while(ucbits < parameter) {
  93664. /* flush registers and read; bitreader_read_from_client_() does
  93665. * not touch br->consumed_bits at all but we still need to set
  93666. * it in case it fails and we have to return false.
  93667. */
  93668. br->consumed_bits = cbits;
  93669. br->consumed_words = cwords;
  93670. if(!bitreader_read_from_client_(br))
  93671. return false;
  93672. cwords = br->consumed_words;
  93673. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93674. }
  93675. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93676. if(cbits) {
  93677. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  93678. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93679. const brword word = br->buffer[cwords];
  93680. if(parameter < n) {
  93681. uval <<= parameter;
  93682. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  93683. cbits += parameter;
  93684. }
  93685. else {
  93686. uval <<= n;
  93687. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93688. crc16_update_word_(br, word);
  93689. cwords++;
  93690. cbits = parameter - n;
  93691. 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 */
  93692. uval <<= cbits;
  93693. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  93694. }
  93695. }
  93696. }
  93697. else {
  93698. cbits = parameter;
  93699. uval <<= parameter;
  93700. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93701. }
  93702. }
  93703. else {
  93704. /* in this case we're starting our read at a partial tail word;
  93705. * the reader has guaranteed that we have at least 'parameter'
  93706. * bits available to read, which makes this case simpler.
  93707. */
  93708. uval <<= parameter;
  93709. if(cbits) {
  93710. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93711. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  93712. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  93713. cbits += parameter;
  93714. }
  93715. else {
  93716. cbits = parameter;
  93717. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93718. }
  93719. }
  93720. }
  93721. ucbits -= parameter;
  93722. /* compose the value */
  93723. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93724. /* are we done? */
  93725. --nvals;
  93726. if(nvals == 0) {
  93727. br->consumed_bits = cbits;
  93728. br->consumed_words = cwords;
  93729. return true;
  93730. }
  93731. uval = 0;
  93732. ++vals;
  93733. }
  93734. }
  93735. #endif
  93736. #if 0 /* UNUSED */
  93737. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93738. {
  93739. FLAC__uint32 lsbs = 0, msbs = 0;
  93740. unsigned bit, uval, k;
  93741. FLAC__ASSERT(0 != br);
  93742. FLAC__ASSERT(0 != br->buffer);
  93743. k = FLAC__bitmath_ilog2(parameter);
  93744. /* read the unary MSBs and end bit */
  93745. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93746. return false;
  93747. /* read the binary LSBs */
  93748. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93749. return false;
  93750. if(parameter == 1u<<k) {
  93751. /* compose the value */
  93752. uval = (msbs << k) | lsbs;
  93753. }
  93754. else {
  93755. unsigned d = (1 << (k+1)) - parameter;
  93756. if(lsbs >= d) {
  93757. if(!FLAC__bitreader_read_bit(br, &bit))
  93758. return false;
  93759. lsbs <<= 1;
  93760. lsbs |= bit;
  93761. lsbs -= d;
  93762. }
  93763. /* compose the value */
  93764. uval = msbs * parameter + lsbs;
  93765. }
  93766. /* unfold unsigned to signed */
  93767. if(uval & 1)
  93768. *val = -((int)(uval >> 1)) - 1;
  93769. else
  93770. *val = (int)(uval >> 1);
  93771. return true;
  93772. }
  93773. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  93774. {
  93775. FLAC__uint32 lsbs, msbs = 0;
  93776. unsigned bit, k;
  93777. FLAC__ASSERT(0 != br);
  93778. FLAC__ASSERT(0 != br->buffer);
  93779. k = FLAC__bitmath_ilog2(parameter);
  93780. /* read the unary MSBs and end bit */
  93781. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93782. return false;
  93783. /* read the binary LSBs */
  93784. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93785. return false;
  93786. if(parameter == 1u<<k) {
  93787. /* compose the value */
  93788. *val = (msbs << k) | lsbs;
  93789. }
  93790. else {
  93791. unsigned d = (1 << (k+1)) - parameter;
  93792. if(lsbs >= d) {
  93793. if(!FLAC__bitreader_read_bit(br, &bit))
  93794. return false;
  93795. lsbs <<= 1;
  93796. lsbs |= bit;
  93797. lsbs -= d;
  93798. }
  93799. /* compose the value */
  93800. *val = msbs * parameter + lsbs;
  93801. }
  93802. return true;
  93803. }
  93804. #endif /* UNUSED */
  93805. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93806. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  93807. {
  93808. FLAC__uint32 v = 0;
  93809. FLAC__uint32 x;
  93810. unsigned i;
  93811. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93812. return false;
  93813. if(raw)
  93814. raw[(*rawlen)++] = (FLAC__byte)x;
  93815. if(!(x & 0x80)) { /* 0xxxxxxx */
  93816. v = x;
  93817. i = 0;
  93818. }
  93819. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93820. v = x & 0x1F;
  93821. i = 1;
  93822. }
  93823. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93824. v = x & 0x0F;
  93825. i = 2;
  93826. }
  93827. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93828. v = x & 0x07;
  93829. i = 3;
  93830. }
  93831. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93832. v = x & 0x03;
  93833. i = 4;
  93834. }
  93835. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93836. v = x & 0x01;
  93837. i = 5;
  93838. }
  93839. else {
  93840. *val = 0xffffffff;
  93841. return true;
  93842. }
  93843. for( ; i; i--) {
  93844. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93845. return false;
  93846. if(raw)
  93847. raw[(*rawlen)++] = (FLAC__byte)x;
  93848. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93849. *val = 0xffffffff;
  93850. return true;
  93851. }
  93852. v <<= 6;
  93853. v |= (x & 0x3F);
  93854. }
  93855. *val = v;
  93856. return true;
  93857. }
  93858. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93859. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  93860. {
  93861. FLAC__uint64 v = 0;
  93862. FLAC__uint32 x;
  93863. unsigned i;
  93864. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93865. return false;
  93866. if(raw)
  93867. raw[(*rawlen)++] = (FLAC__byte)x;
  93868. if(!(x & 0x80)) { /* 0xxxxxxx */
  93869. v = x;
  93870. i = 0;
  93871. }
  93872. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93873. v = x & 0x1F;
  93874. i = 1;
  93875. }
  93876. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93877. v = x & 0x0F;
  93878. i = 2;
  93879. }
  93880. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93881. v = x & 0x07;
  93882. i = 3;
  93883. }
  93884. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93885. v = x & 0x03;
  93886. i = 4;
  93887. }
  93888. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93889. v = x & 0x01;
  93890. i = 5;
  93891. }
  93892. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  93893. v = 0;
  93894. i = 6;
  93895. }
  93896. else {
  93897. *val = FLAC__U64L(0xffffffffffffffff);
  93898. return true;
  93899. }
  93900. for( ; i; i--) {
  93901. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93902. return false;
  93903. if(raw)
  93904. raw[(*rawlen)++] = (FLAC__byte)x;
  93905. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93906. *val = FLAC__U64L(0xffffffffffffffff);
  93907. return true;
  93908. }
  93909. v <<= 6;
  93910. v |= (x & 0x3F);
  93911. }
  93912. *val = v;
  93913. return true;
  93914. }
  93915. #endif
  93916. /*** End of inlined file: bitreader.c ***/
  93917. /*** Start of inlined file: bitwriter.c ***/
  93918. /*** Start of inlined file: juce_FlacHeader.h ***/
  93919. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93920. // tasks..
  93921. #define VERSION "1.2.1"
  93922. #define FLAC__NO_DLL 1
  93923. #if JUCE_MSVC
  93924. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93925. #endif
  93926. #if JUCE_MAC
  93927. #define FLAC__SYS_DARWIN 1
  93928. #endif
  93929. /*** End of inlined file: juce_FlacHeader.h ***/
  93930. #if JUCE_USE_FLAC
  93931. #if HAVE_CONFIG_H
  93932. # include <config.h>
  93933. #endif
  93934. #include <stdlib.h> /* for malloc() */
  93935. #include <string.h> /* for memcpy(), memset() */
  93936. #ifdef _MSC_VER
  93937. #include <winsock.h> /* for ntohl() */
  93938. #elif defined FLAC__SYS_DARWIN
  93939. #include <machine/endian.h> /* for ntohl() */
  93940. #elif defined __MINGW32__
  93941. #include <winsock.h> /* for ntohl() */
  93942. #else
  93943. #include <netinet/in.h> /* for ntohl() */
  93944. #endif
  93945. #if 0 /* UNUSED */
  93946. #endif
  93947. /*** Start of inlined file: bitwriter.h ***/
  93948. #ifndef FLAC__PRIVATE__BITWRITER_H
  93949. #define FLAC__PRIVATE__BITWRITER_H
  93950. #include <stdio.h> /* for FILE */
  93951. /*
  93952. * opaque structure definition
  93953. */
  93954. struct FLAC__BitWriter;
  93955. typedef struct FLAC__BitWriter FLAC__BitWriter;
  93956. /*
  93957. * construction, deletion, initialization, etc functions
  93958. */
  93959. FLAC__BitWriter *FLAC__bitwriter_new(void);
  93960. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  93961. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  93962. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  93963. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  93964. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  93965. /*
  93966. * CRC functions
  93967. *
  93968. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  93969. */
  93970. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  93971. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  93972. /*
  93973. * info functions
  93974. */
  93975. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  93976. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  93977. /*
  93978. * direct buffer access
  93979. *
  93980. * there may be no calls on the bitwriter between get and release.
  93981. * the bitwriter continues to own the returned buffer.
  93982. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  93983. */
  93984. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  93985. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  93986. /*
  93987. * write functions
  93988. */
  93989. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  93990. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  93991. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  93992. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  93993. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  93994. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  93995. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  93996. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  93997. #if 0 /* UNUSED */
  93998. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  93999. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  94000. #endif
  94001. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  94002. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  94003. #if 0 /* UNUSED */
  94004. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  94005. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  94006. #endif
  94007. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  94008. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  94009. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  94010. #endif
  94011. /*** End of inlined file: bitwriter.h ***/
  94012. /*** Start of inlined file: alloc.h ***/
  94013. #ifndef FLAC__SHARE__ALLOC_H
  94014. #define FLAC__SHARE__ALLOC_H
  94015. #if HAVE_CONFIG_H
  94016. # include <config.h>
  94017. #endif
  94018. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94019. * before #including this file, otherwise SIZE_MAX might not be defined
  94020. */
  94021. #include <limits.h> /* for SIZE_MAX */
  94022. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94023. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94024. #endif
  94025. #include <stdlib.h> /* for size_t, malloc(), etc */
  94026. #ifndef SIZE_MAX
  94027. # ifndef SIZE_T_MAX
  94028. # ifdef _MSC_VER
  94029. # define SIZE_T_MAX UINT_MAX
  94030. # else
  94031. # error
  94032. # endif
  94033. # endif
  94034. # define SIZE_MAX SIZE_T_MAX
  94035. #endif
  94036. #ifndef FLaC__INLINE
  94037. #define FLaC__INLINE
  94038. #endif
  94039. /* avoid malloc()ing 0 bytes, see:
  94040. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94041. */
  94042. static FLaC__INLINE void *safe_malloc_(size_t size)
  94043. {
  94044. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94045. if(!size)
  94046. size++;
  94047. return malloc(size);
  94048. }
  94049. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94050. {
  94051. if(!nmemb || !size)
  94052. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94053. return calloc(nmemb, size);
  94054. }
  94055. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94056. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94057. {
  94058. size2 += size1;
  94059. if(size2 < size1)
  94060. return 0;
  94061. return safe_malloc_(size2);
  94062. }
  94063. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94064. {
  94065. size2 += size1;
  94066. if(size2 < size1)
  94067. return 0;
  94068. size3 += size2;
  94069. if(size3 < size2)
  94070. return 0;
  94071. return safe_malloc_(size3);
  94072. }
  94073. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94074. {
  94075. size2 += size1;
  94076. if(size2 < size1)
  94077. return 0;
  94078. size3 += size2;
  94079. if(size3 < size2)
  94080. return 0;
  94081. size4 += size3;
  94082. if(size4 < size3)
  94083. return 0;
  94084. return safe_malloc_(size4);
  94085. }
  94086. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94087. #if 0
  94088. needs support for cases where sizeof(size_t) != 4
  94089. {
  94090. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94091. if(sizeof(size_t) == 4) {
  94092. if ((double)size1 * (double)size2 < 4294967296.0)
  94093. return malloc(size1*size2);
  94094. }
  94095. return 0;
  94096. }
  94097. #else
  94098. /* better? */
  94099. {
  94100. if(!size1 || !size2)
  94101. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94102. if(size1 > SIZE_MAX / size2)
  94103. return 0;
  94104. return malloc(size1*size2);
  94105. }
  94106. #endif
  94107. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94108. {
  94109. if(!size1 || !size2 || !size3)
  94110. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94111. if(size1 > SIZE_MAX / size2)
  94112. return 0;
  94113. size1 *= size2;
  94114. if(size1 > SIZE_MAX / size3)
  94115. return 0;
  94116. return malloc(size1*size3);
  94117. }
  94118. /* size1*size2 + size3 */
  94119. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94120. {
  94121. if(!size1 || !size2)
  94122. return safe_malloc_(size3);
  94123. if(size1 > SIZE_MAX / size2)
  94124. return 0;
  94125. return safe_malloc_add_2op_(size1*size2, size3);
  94126. }
  94127. /* size1 * (size2 + size3) */
  94128. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94129. {
  94130. if(!size1 || (!size2 && !size3))
  94131. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94132. size2 += size3;
  94133. if(size2 < size3)
  94134. return 0;
  94135. return safe_malloc_mul_2op_(size1, size2);
  94136. }
  94137. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94138. {
  94139. size2 += size1;
  94140. if(size2 < size1)
  94141. return 0;
  94142. return realloc(ptr, size2);
  94143. }
  94144. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94145. {
  94146. size2 += size1;
  94147. if(size2 < size1)
  94148. return 0;
  94149. size3 += size2;
  94150. if(size3 < size2)
  94151. return 0;
  94152. return realloc(ptr, size3);
  94153. }
  94154. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94155. {
  94156. size2 += size1;
  94157. if(size2 < size1)
  94158. return 0;
  94159. size3 += size2;
  94160. if(size3 < size2)
  94161. return 0;
  94162. size4 += size3;
  94163. if(size4 < size3)
  94164. return 0;
  94165. return realloc(ptr, size4);
  94166. }
  94167. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94168. {
  94169. if(!size1 || !size2)
  94170. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94171. if(size1 > SIZE_MAX / size2)
  94172. return 0;
  94173. return realloc(ptr, size1*size2);
  94174. }
  94175. /* size1 * (size2 + size3) */
  94176. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94177. {
  94178. if(!size1 || (!size2 && !size3))
  94179. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94180. size2 += size3;
  94181. if(size2 < size3)
  94182. return 0;
  94183. return safe_realloc_mul_2op_(ptr, size1, size2);
  94184. }
  94185. #endif
  94186. /*** End of inlined file: alloc.h ***/
  94187. /* Things should be fastest when this matches the machine word size */
  94188. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94189. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94190. typedef FLAC__uint32 bwword;
  94191. #define FLAC__BYTES_PER_WORD 4
  94192. #define FLAC__BITS_PER_WORD 32
  94193. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94194. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94195. #if WORDS_BIGENDIAN
  94196. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94197. #else
  94198. #ifdef _MSC_VER
  94199. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94200. #else
  94201. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94202. #endif
  94203. #endif
  94204. /*
  94205. * The default capacity here doesn't matter too much. The buffer always grows
  94206. * to hold whatever is written to it. Usually the encoder will stop adding at
  94207. * a frame or metadata block, then write that out and clear the buffer for the
  94208. * next one.
  94209. */
  94210. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94211. /* When growing, increment 4K at a time */
  94212. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94213. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94214. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94215. #ifdef min
  94216. #undef min
  94217. #endif
  94218. #define min(x,y) ((x)<(y)?(x):(y))
  94219. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94220. #ifdef _MSC_VER
  94221. #define FLAC__U64L(x) x
  94222. #else
  94223. #define FLAC__U64L(x) x##LLU
  94224. #endif
  94225. #ifndef FLaC__INLINE
  94226. #define FLaC__INLINE
  94227. #endif
  94228. struct FLAC__BitWriter {
  94229. bwword *buffer;
  94230. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94231. unsigned capacity; /* capacity of buffer in words */
  94232. unsigned words; /* # of complete words in buffer */
  94233. unsigned bits; /* # of used bits in accum */
  94234. };
  94235. /* * WATCHOUT: The current implementation only grows the buffer. */
  94236. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94237. {
  94238. unsigned new_capacity;
  94239. bwword *new_buffer;
  94240. FLAC__ASSERT(0 != bw);
  94241. FLAC__ASSERT(0 != bw->buffer);
  94242. /* calculate total words needed to store 'bits_to_add' additional bits */
  94243. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94244. /* it's possible (due to pessimism in the growth estimation that
  94245. * leads to this call) that we don't actually need to grow
  94246. */
  94247. if(bw->capacity >= new_capacity)
  94248. return true;
  94249. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94250. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94251. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94252. /* make sure we got everything right */
  94253. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94254. FLAC__ASSERT(new_capacity > bw->capacity);
  94255. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94256. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94257. if(new_buffer == 0)
  94258. return false;
  94259. bw->buffer = new_buffer;
  94260. bw->capacity = new_capacity;
  94261. return true;
  94262. }
  94263. /***********************************************************************
  94264. *
  94265. * Class constructor/destructor
  94266. *
  94267. ***********************************************************************/
  94268. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94269. {
  94270. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94271. /* note that calloc() sets all members to 0 for us */
  94272. return bw;
  94273. }
  94274. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94275. {
  94276. FLAC__ASSERT(0 != bw);
  94277. FLAC__bitwriter_free(bw);
  94278. free(bw);
  94279. }
  94280. /***********************************************************************
  94281. *
  94282. * Public class methods
  94283. *
  94284. ***********************************************************************/
  94285. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94286. {
  94287. FLAC__ASSERT(0 != bw);
  94288. bw->words = bw->bits = 0;
  94289. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94290. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94291. if(bw->buffer == 0)
  94292. return false;
  94293. return true;
  94294. }
  94295. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94296. {
  94297. FLAC__ASSERT(0 != bw);
  94298. if(0 != bw->buffer)
  94299. free(bw->buffer);
  94300. bw->buffer = 0;
  94301. bw->capacity = 0;
  94302. bw->words = bw->bits = 0;
  94303. }
  94304. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94305. {
  94306. bw->words = bw->bits = 0;
  94307. }
  94308. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94309. {
  94310. unsigned i, j;
  94311. if(bw == 0) {
  94312. fprintf(out, "bitwriter is NULL\n");
  94313. }
  94314. else {
  94315. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94316. for(i = 0; i < bw->words; i++) {
  94317. fprintf(out, "%08X: ", i);
  94318. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94319. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94320. fprintf(out, "\n");
  94321. }
  94322. if(bw->bits > 0) {
  94323. fprintf(out, "%08X: ", i);
  94324. for(j = 0; j < bw->bits; j++)
  94325. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94326. fprintf(out, "\n");
  94327. }
  94328. }
  94329. }
  94330. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94331. {
  94332. const FLAC__byte *buffer;
  94333. size_t bytes;
  94334. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94335. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94336. return false;
  94337. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94338. FLAC__bitwriter_release_buffer(bw);
  94339. return true;
  94340. }
  94341. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94342. {
  94343. const FLAC__byte *buffer;
  94344. size_t bytes;
  94345. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94346. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94347. return false;
  94348. *crc = FLAC__crc8(buffer, bytes);
  94349. FLAC__bitwriter_release_buffer(bw);
  94350. return true;
  94351. }
  94352. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94353. {
  94354. return ((bw->bits & 7) == 0);
  94355. }
  94356. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94357. {
  94358. return FLAC__TOTAL_BITS(bw);
  94359. }
  94360. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94361. {
  94362. FLAC__ASSERT((bw->bits & 7) == 0);
  94363. /* double protection */
  94364. if(bw->bits & 7)
  94365. return false;
  94366. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94367. if(bw->bits) {
  94368. FLAC__ASSERT(bw->words <= bw->capacity);
  94369. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94370. return false;
  94371. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94372. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94373. }
  94374. /* now we can just return what we have */
  94375. *buffer = (FLAC__byte*)bw->buffer;
  94376. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94377. return true;
  94378. }
  94379. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94380. {
  94381. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94382. * get-mode' flag could be added everywhere and then cleared here
  94383. */
  94384. (void)bw;
  94385. }
  94386. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94387. {
  94388. unsigned n;
  94389. FLAC__ASSERT(0 != bw);
  94390. FLAC__ASSERT(0 != bw->buffer);
  94391. if(bits == 0)
  94392. return true;
  94393. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94394. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94395. return false;
  94396. /* first part gets to word alignment */
  94397. if(bw->bits) {
  94398. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94399. bw->accum <<= n;
  94400. bits -= n;
  94401. bw->bits += n;
  94402. if(bw->bits == FLAC__BITS_PER_WORD) {
  94403. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94404. bw->bits = 0;
  94405. }
  94406. else
  94407. return true;
  94408. }
  94409. /* do whole words */
  94410. while(bits >= FLAC__BITS_PER_WORD) {
  94411. bw->buffer[bw->words++] = 0;
  94412. bits -= FLAC__BITS_PER_WORD;
  94413. }
  94414. /* do any leftovers */
  94415. if(bits > 0) {
  94416. bw->accum = 0;
  94417. bw->bits = bits;
  94418. }
  94419. return true;
  94420. }
  94421. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94422. {
  94423. register unsigned left;
  94424. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94425. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94426. FLAC__ASSERT(0 != bw);
  94427. FLAC__ASSERT(0 != bw->buffer);
  94428. FLAC__ASSERT(bits <= 32);
  94429. if(bits == 0)
  94430. return true;
  94431. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94432. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94433. return false;
  94434. left = FLAC__BITS_PER_WORD - bw->bits;
  94435. if(bits < left) {
  94436. bw->accum <<= bits;
  94437. bw->accum |= val;
  94438. bw->bits += bits;
  94439. }
  94440. 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 */
  94441. bw->accum <<= left;
  94442. bw->accum |= val >> (bw->bits = bits - left);
  94443. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94444. bw->accum = val;
  94445. }
  94446. else {
  94447. bw->accum = val;
  94448. bw->bits = 0;
  94449. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94450. }
  94451. return true;
  94452. }
  94453. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94454. {
  94455. /* zero-out unused bits */
  94456. if(bits < 32)
  94457. val &= (~(0xffffffff << bits));
  94458. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94459. }
  94460. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94461. {
  94462. /* this could be a little faster but it's not used for much */
  94463. if(bits > 32) {
  94464. return
  94465. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94466. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94467. }
  94468. else
  94469. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94470. }
  94471. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94472. {
  94473. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94474. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94475. return false;
  94476. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94477. return false;
  94478. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94479. return false;
  94480. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94481. return false;
  94482. return true;
  94483. }
  94484. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94485. {
  94486. unsigned i;
  94487. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94488. for(i = 0; i < nvals; i++) {
  94489. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94490. return false;
  94491. }
  94492. return true;
  94493. }
  94494. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94495. {
  94496. if(val < 32)
  94497. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  94498. else
  94499. return
  94500. FLAC__bitwriter_write_zeroes(bw, val) &&
  94501. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  94502. }
  94503. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  94504. {
  94505. FLAC__uint32 uval;
  94506. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  94507. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94508. uval = (val<<1) ^ (val>>31);
  94509. return 1 + parameter + (uval >> parameter);
  94510. }
  94511. #if 0 /* UNUSED */
  94512. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  94513. {
  94514. unsigned bits, msbs, uval;
  94515. unsigned k;
  94516. FLAC__ASSERT(parameter > 0);
  94517. /* fold signed to unsigned */
  94518. if(val < 0)
  94519. uval = (unsigned)(((-(++val)) << 1) + 1);
  94520. else
  94521. uval = (unsigned)(val << 1);
  94522. k = FLAC__bitmath_ilog2(parameter);
  94523. if(parameter == 1u<<k) {
  94524. FLAC__ASSERT(k <= 30);
  94525. msbs = uval >> k;
  94526. bits = 1 + k + msbs;
  94527. }
  94528. else {
  94529. unsigned q, r, d;
  94530. d = (1 << (k+1)) - parameter;
  94531. q = uval / parameter;
  94532. r = uval - (q * parameter);
  94533. bits = 1 + q + k;
  94534. if(r >= d)
  94535. bits++;
  94536. }
  94537. return bits;
  94538. }
  94539. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  94540. {
  94541. unsigned bits, msbs;
  94542. unsigned k;
  94543. FLAC__ASSERT(parameter > 0);
  94544. k = FLAC__bitmath_ilog2(parameter);
  94545. if(parameter == 1u<<k) {
  94546. FLAC__ASSERT(k <= 30);
  94547. msbs = uval >> k;
  94548. bits = 1 + k + msbs;
  94549. }
  94550. else {
  94551. unsigned q, r, d;
  94552. d = (1 << (k+1)) - parameter;
  94553. q = uval / parameter;
  94554. r = uval - (q * parameter);
  94555. bits = 1 + q + k;
  94556. if(r >= d)
  94557. bits++;
  94558. }
  94559. return bits;
  94560. }
  94561. #endif /* UNUSED */
  94562. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  94563. {
  94564. unsigned total_bits, interesting_bits, msbs;
  94565. FLAC__uint32 uval, pattern;
  94566. FLAC__ASSERT(0 != bw);
  94567. FLAC__ASSERT(0 != bw->buffer);
  94568. FLAC__ASSERT(parameter < 8*sizeof(uval));
  94569. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94570. uval = (val<<1) ^ (val>>31);
  94571. msbs = uval >> parameter;
  94572. interesting_bits = 1 + parameter;
  94573. total_bits = interesting_bits + msbs;
  94574. pattern = 1 << parameter; /* the unary end bit */
  94575. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  94576. if(total_bits <= 32)
  94577. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  94578. else
  94579. return
  94580. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  94581. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  94582. }
  94583. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  94584. {
  94585. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  94586. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  94587. FLAC__uint32 uval;
  94588. unsigned left;
  94589. const unsigned lsbits = 1 + parameter;
  94590. unsigned msbits;
  94591. FLAC__ASSERT(0 != bw);
  94592. FLAC__ASSERT(0 != bw->buffer);
  94593. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  94594. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94595. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94596. while(nvals) {
  94597. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94598. uval = (*vals<<1) ^ (*vals>>31);
  94599. msbits = uval >> parameter;
  94600. #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) */
  94601. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94602. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94603. bw->bits = bw->bits + msbits + lsbits;
  94604. uval |= mask1; /* set stop bit */
  94605. uval &= mask2; /* mask off unused top bits */
  94606. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  94607. bw->accum <<= msbits;
  94608. bw->accum <<= lsbits;
  94609. bw->accum |= uval;
  94610. if(bw->bits == FLAC__BITS_PER_WORD) {
  94611. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94612. bw->bits = 0;
  94613. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  94614. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  94615. FLAC__ASSERT(bw->capacity == bw->words);
  94616. return false;
  94617. }
  94618. }
  94619. }
  94620. else {
  94621. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  94622. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94623. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94624. bw->bits = bw->bits + msbits + lsbits;
  94625. uval |= mask1; /* set stop bit */
  94626. uval &= mask2; /* mask off unused top bits */
  94627. bw->accum <<= msbits + lsbits;
  94628. bw->accum |= uval;
  94629. }
  94630. else {
  94631. #endif
  94632. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94633. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  94634. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  94635. return false;
  94636. if(msbits) {
  94637. /* first part gets to word alignment */
  94638. if(bw->bits) {
  94639. left = FLAC__BITS_PER_WORD - bw->bits;
  94640. if(msbits < left) {
  94641. bw->accum <<= msbits;
  94642. bw->bits += msbits;
  94643. goto break1;
  94644. }
  94645. else {
  94646. bw->accum <<= left;
  94647. msbits -= left;
  94648. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94649. bw->bits = 0;
  94650. }
  94651. }
  94652. /* do whole words */
  94653. while(msbits >= FLAC__BITS_PER_WORD) {
  94654. bw->buffer[bw->words++] = 0;
  94655. msbits -= FLAC__BITS_PER_WORD;
  94656. }
  94657. /* do any leftovers */
  94658. if(msbits > 0) {
  94659. bw->accum = 0;
  94660. bw->bits = msbits;
  94661. }
  94662. }
  94663. break1:
  94664. uval |= mask1; /* set stop bit */
  94665. uval &= mask2; /* mask off unused top bits */
  94666. left = FLAC__BITS_PER_WORD - bw->bits;
  94667. if(lsbits < left) {
  94668. bw->accum <<= lsbits;
  94669. bw->accum |= uval;
  94670. bw->bits += lsbits;
  94671. }
  94672. else {
  94673. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  94674. * be > lsbits (because of previous assertions) so it would have
  94675. * triggered the (lsbits<left) case above.
  94676. */
  94677. FLAC__ASSERT(bw->bits);
  94678. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  94679. bw->accum <<= left;
  94680. bw->accum |= uval >> (bw->bits = lsbits - left);
  94681. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94682. bw->accum = uval;
  94683. }
  94684. #if 1
  94685. }
  94686. #endif
  94687. vals++;
  94688. nvals--;
  94689. }
  94690. return true;
  94691. }
  94692. #if 0 /* UNUSED */
  94693. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  94694. {
  94695. unsigned total_bits, msbs, uval;
  94696. unsigned k;
  94697. FLAC__ASSERT(0 != bw);
  94698. FLAC__ASSERT(0 != bw->buffer);
  94699. FLAC__ASSERT(parameter > 0);
  94700. /* fold signed to unsigned */
  94701. if(val < 0)
  94702. uval = (unsigned)(((-(++val)) << 1) + 1);
  94703. else
  94704. uval = (unsigned)(val << 1);
  94705. k = FLAC__bitmath_ilog2(parameter);
  94706. if(parameter == 1u<<k) {
  94707. unsigned pattern;
  94708. FLAC__ASSERT(k <= 30);
  94709. msbs = uval >> k;
  94710. total_bits = 1 + k + msbs;
  94711. pattern = 1 << k; /* the unary end bit */
  94712. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94713. if(total_bits <= 32) {
  94714. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94715. return false;
  94716. }
  94717. else {
  94718. /* write the unary MSBs */
  94719. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94720. return false;
  94721. /* write the unary end bit and binary LSBs */
  94722. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94723. return false;
  94724. }
  94725. }
  94726. else {
  94727. unsigned q, r, d;
  94728. d = (1 << (k+1)) - parameter;
  94729. q = uval / parameter;
  94730. r = uval - (q * parameter);
  94731. /* write the unary MSBs */
  94732. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94733. return false;
  94734. /* write the unary end bit */
  94735. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94736. return false;
  94737. /* write the binary LSBs */
  94738. if(r >= d) {
  94739. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94740. return false;
  94741. }
  94742. else {
  94743. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94744. return false;
  94745. }
  94746. }
  94747. return true;
  94748. }
  94749. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  94750. {
  94751. unsigned total_bits, msbs;
  94752. unsigned k;
  94753. FLAC__ASSERT(0 != bw);
  94754. FLAC__ASSERT(0 != bw->buffer);
  94755. FLAC__ASSERT(parameter > 0);
  94756. k = FLAC__bitmath_ilog2(parameter);
  94757. if(parameter == 1u<<k) {
  94758. unsigned pattern;
  94759. FLAC__ASSERT(k <= 30);
  94760. msbs = uval >> k;
  94761. total_bits = 1 + k + msbs;
  94762. pattern = 1 << k; /* the unary end bit */
  94763. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94764. if(total_bits <= 32) {
  94765. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94766. return false;
  94767. }
  94768. else {
  94769. /* write the unary MSBs */
  94770. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94771. return false;
  94772. /* write the unary end bit and binary LSBs */
  94773. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94774. return false;
  94775. }
  94776. }
  94777. else {
  94778. unsigned q, r, d;
  94779. d = (1 << (k+1)) - parameter;
  94780. q = uval / parameter;
  94781. r = uval - (q * parameter);
  94782. /* write the unary MSBs */
  94783. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94784. return false;
  94785. /* write the unary end bit */
  94786. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94787. return false;
  94788. /* write the binary LSBs */
  94789. if(r >= d) {
  94790. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94791. return false;
  94792. }
  94793. else {
  94794. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94795. return false;
  94796. }
  94797. }
  94798. return true;
  94799. }
  94800. #endif /* UNUSED */
  94801. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  94802. {
  94803. FLAC__bool ok = 1;
  94804. FLAC__ASSERT(0 != bw);
  94805. FLAC__ASSERT(0 != bw->buffer);
  94806. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  94807. if(val < 0x80) {
  94808. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  94809. }
  94810. else if(val < 0x800) {
  94811. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  94812. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94813. }
  94814. else if(val < 0x10000) {
  94815. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  94816. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94817. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94818. }
  94819. else if(val < 0x200000) {
  94820. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  94821. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94822. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94823. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94824. }
  94825. else if(val < 0x4000000) {
  94826. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  94827. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94828. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94829. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94830. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94831. }
  94832. else {
  94833. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  94834. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  94835. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94836. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94837. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94838. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94839. }
  94840. return ok;
  94841. }
  94842. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  94843. {
  94844. FLAC__bool ok = 1;
  94845. FLAC__ASSERT(0 != bw);
  94846. FLAC__ASSERT(0 != bw->buffer);
  94847. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  94848. if(val < 0x80) {
  94849. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  94850. }
  94851. else if(val < 0x800) {
  94852. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  94853. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94854. }
  94855. else if(val < 0x10000) {
  94856. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  94857. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94858. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94859. }
  94860. else if(val < 0x200000) {
  94861. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  94862. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94863. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94864. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94865. }
  94866. else if(val < 0x4000000) {
  94867. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  94868. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94869. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94870. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94871. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94872. }
  94873. else if(val < 0x80000000) {
  94874. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  94875. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94876. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94877. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94878. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94879. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94880. }
  94881. else {
  94882. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  94883. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  94884. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94885. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94886. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94887. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94888. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94889. }
  94890. return ok;
  94891. }
  94892. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  94893. {
  94894. /* 0-pad to byte boundary */
  94895. if(bw->bits & 7u)
  94896. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  94897. else
  94898. return true;
  94899. }
  94900. #endif
  94901. /*** End of inlined file: bitwriter.c ***/
  94902. /*** Start of inlined file: cpu.c ***/
  94903. /*** Start of inlined file: juce_FlacHeader.h ***/
  94904. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94905. // tasks..
  94906. #define VERSION "1.2.1"
  94907. #define FLAC__NO_DLL 1
  94908. #if JUCE_MSVC
  94909. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94910. #endif
  94911. #if JUCE_MAC
  94912. #define FLAC__SYS_DARWIN 1
  94913. #endif
  94914. /*** End of inlined file: juce_FlacHeader.h ***/
  94915. #if JUCE_USE_FLAC
  94916. #if HAVE_CONFIG_H
  94917. # include <config.h>
  94918. #endif
  94919. #include <stdlib.h>
  94920. #include <stdio.h>
  94921. #if defined FLAC__CPU_IA32
  94922. # include <signal.h>
  94923. #elif defined FLAC__CPU_PPC
  94924. # if !defined FLAC__NO_ASM
  94925. # if defined FLAC__SYS_DARWIN
  94926. # include <sys/sysctl.h>
  94927. # include <mach/mach.h>
  94928. # include <mach/mach_host.h>
  94929. # include <mach/host_info.h>
  94930. # include <mach/machine.h>
  94931. # ifndef CPU_SUBTYPE_POWERPC_970
  94932. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  94933. # endif
  94934. # else /* FLAC__SYS_DARWIN */
  94935. # include <signal.h>
  94936. # include <setjmp.h>
  94937. static sigjmp_buf jmpbuf;
  94938. static volatile sig_atomic_t canjump = 0;
  94939. static void sigill_handler (int sig)
  94940. {
  94941. if (!canjump) {
  94942. signal (sig, SIG_DFL);
  94943. raise (sig);
  94944. }
  94945. canjump = 0;
  94946. siglongjmp (jmpbuf, 1);
  94947. }
  94948. # endif /* FLAC__SYS_DARWIN */
  94949. # endif /* FLAC__NO_ASM */
  94950. #endif /* FLAC__CPU_PPC */
  94951. #if defined (__NetBSD__) || defined(__OpenBSD__)
  94952. #include <sys/param.h>
  94953. #include <sys/sysctl.h>
  94954. #include <machine/cpu.h>
  94955. #endif
  94956. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  94957. #include <sys/types.h>
  94958. #include <sys/sysctl.h>
  94959. #endif
  94960. #if defined(__APPLE__)
  94961. /* how to get sysctlbyname()? */
  94962. #endif
  94963. /* these are flags in EDX of CPUID AX=00000001 */
  94964. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  94965. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  94966. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  94967. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  94968. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  94969. /* these are flags in ECX of CPUID AX=00000001 */
  94970. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  94971. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  94972. /* these are flags in EDX of CPUID AX=80000001 */
  94973. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  94974. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  94975. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  94976. /*
  94977. * Extra stuff needed for detection of OS support for SSE on IA-32
  94978. */
  94979. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  94980. # if defined(__linux__)
  94981. /*
  94982. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  94983. * modify the return address to jump over the offending SSE instruction
  94984. * and also the operation following it that indicates the instruction
  94985. * executed successfully. In this way we use no global variables and
  94986. * stay thread-safe.
  94987. *
  94988. * 3 + 3 + 6:
  94989. * 3 bytes for "xorps xmm0,xmm0"
  94990. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  94991. * 6 bytes extra in case our estimate is wrong
  94992. * 12 bytes puts us in the NOP "landing zone"
  94993. */
  94994. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  94995. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  94996. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  94997. {
  94998. (void)signal;
  94999. sc.eip += 3 + 3 + 6;
  95000. }
  95001. # else
  95002. # include <sys/ucontext.h>
  95003. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  95004. {
  95005. (void)signal, (void)si;
  95006. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  95007. }
  95008. # endif
  95009. # elif defined(_MSC_VER)
  95010. # include <windows.h>
  95011. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  95012. # ifdef USE_TRY_CATCH_FLAVOR
  95013. # else
  95014. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  95015. {
  95016. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  95017. ep->ContextRecord->Eip += 3 + 3 + 6;
  95018. return EXCEPTION_CONTINUE_EXECUTION;
  95019. }
  95020. return EXCEPTION_CONTINUE_SEARCH;
  95021. }
  95022. # endif
  95023. # endif
  95024. #endif
  95025. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95026. {
  95027. /*
  95028. * IA32-specific
  95029. */
  95030. #ifdef FLAC__CPU_IA32
  95031. info->type = FLAC__CPUINFO_TYPE_IA32;
  95032. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95033. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95034. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95035. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95036. info->data.ia32.cmov = false;
  95037. info->data.ia32.mmx = false;
  95038. info->data.ia32.fxsr = false;
  95039. info->data.ia32.sse = false;
  95040. info->data.ia32.sse2 = false;
  95041. info->data.ia32.sse3 = false;
  95042. info->data.ia32.ssse3 = false;
  95043. info->data.ia32._3dnow = false;
  95044. info->data.ia32.ext3dnow = false;
  95045. info->data.ia32.extmmx = false;
  95046. if(info->data.ia32.cpuid) {
  95047. /* http://www.sandpile.org/ia32/cpuid.htm */
  95048. FLAC__uint32 flags_edx, flags_ecx;
  95049. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95050. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95051. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95052. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95053. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95054. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95055. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95056. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95057. #ifdef FLAC__USE_3DNOW
  95058. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95059. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95060. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95061. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95062. #else
  95063. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95064. #endif
  95065. #ifdef DEBUG
  95066. fprintf(stderr, "CPU info (IA-32):\n");
  95067. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95068. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95069. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95070. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95071. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95072. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95073. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95074. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95075. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95076. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95077. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95078. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95079. #endif
  95080. /*
  95081. * now have to check for OS support of SSE/SSE2
  95082. */
  95083. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95084. #if defined FLAC__NO_SSE_OS
  95085. /* assume user knows better than us; turn it off */
  95086. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95087. #elif defined FLAC__SSE_OS
  95088. /* assume user knows better than us; leave as detected above */
  95089. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95090. int sse = 0;
  95091. size_t len;
  95092. /* at least one of these must work: */
  95093. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95094. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95095. if(!sse)
  95096. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95097. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95098. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95099. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95100. size_t len = sizeof(val);
  95101. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95102. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95103. else { /* double-check SSE2 */
  95104. mib[1] = CPU_SSE2;
  95105. len = sizeof(val);
  95106. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95107. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95108. }
  95109. # else
  95110. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95111. # endif
  95112. #elif defined(__linux__)
  95113. int sse = 0;
  95114. struct sigaction sigill_save;
  95115. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95116. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95117. #else
  95118. struct sigaction sigill_sse;
  95119. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95120. __sigemptyset(&sigill_sse.sa_mask);
  95121. 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 */
  95122. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95123. #endif
  95124. {
  95125. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95126. /* see sigill_handler_sse_os() for an explanation of the following: */
  95127. asm volatile (
  95128. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95129. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95130. "incl %0\n\t" /* SIGILL handler will jump over this */
  95131. /* landing zone */
  95132. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95133. "nop\n\t"
  95134. "nop\n\t"
  95135. "nop\n\t"
  95136. "nop\n\t"
  95137. "nop\n\t"
  95138. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95139. "nop\n\t"
  95140. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95141. : "=r"(sse)
  95142. : "r"(sse)
  95143. );
  95144. sigaction(SIGILL, &sigill_save, NULL);
  95145. }
  95146. if(!sse)
  95147. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95148. #elif defined(_MSC_VER)
  95149. # ifdef USE_TRY_CATCH_FLAVOR
  95150. _try {
  95151. __asm {
  95152. # if _MSC_VER <= 1200
  95153. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95154. _emit 0x0F
  95155. _emit 0x57
  95156. _emit 0xC0
  95157. # else
  95158. xorps xmm0,xmm0
  95159. # endif
  95160. }
  95161. }
  95162. _except(EXCEPTION_EXECUTE_HANDLER) {
  95163. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95164. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95165. }
  95166. # else
  95167. int sse = 0;
  95168. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95169. /* see GCC version above for explanation */
  95170. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95171. /* http://www.codeproject.com/cpp/gccasm.asp */
  95172. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95173. __asm {
  95174. # if _MSC_VER <= 1200
  95175. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95176. _emit 0x0F
  95177. _emit 0x57
  95178. _emit 0xC0
  95179. # else
  95180. xorps xmm0,xmm0
  95181. # endif
  95182. inc sse
  95183. nop
  95184. nop
  95185. nop
  95186. nop
  95187. nop
  95188. nop
  95189. nop
  95190. nop
  95191. nop
  95192. }
  95193. SetUnhandledExceptionFilter(save);
  95194. if(!sse)
  95195. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95196. # endif
  95197. #else
  95198. /* no way to test, disable to be safe */
  95199. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95200. #endif
  95201. #ifdef DEBUG
  95202. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95203. #endif
  95204. }
  95205. }
  95206. #else
  95207. info->use_asm = false;
  95208. #endif
  95209. /*
  95210. * PPC-specific
  95211. */
  95212. #elif defined FLAC__CPU_PPC
  95213. info->type = FLAC__CPUINFO_TYPE_PPC;
  95214. # if !defined FLAC__NO_ASM
  95215. info->use_asm = true;
  95216. # ifdef FLAC__USE_ALTIVEC
  95217. # if defined FLAC__SYS_DARWIN
  95218. {
  95219. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95220. size_t len = sizeof(val);
  95221. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95222. }
  95223. {
  95224. host_basic_info_data_t hostInfo;
  95225. mach_msg_type_number_t infoCount;
  95226. infoCount = HOST_BASIC_INFO_COUNT;
  95227. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95228. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95229. }
  95230. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95231. {
  95232. /* no Darwin, do it the brute-force way */
  95233. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95234. info->data.ppc.altivec = 0;
  95235. info->data.ppc.ppc64 = 0;
  95236. signal (SIGILL, sigill_handler);
  95237. canjump = 0;
  95238. if (!sigsetjmp (jmpbuf, 1)) {
  95239. canjump = 1;
  95240. asm volatile (
  95241. "mtspr 256, %0\n\t"
  95242. "vand %%v0, %%v0, %%v0"
  95243. :
  95244. : "r" (-1)
  95245. );
  95246. info->data.ppc.altivec = 1;
  95247. }
  95248. canjump = 0;
  95249. if (!sigsetjmp (jmpbuf, 1)) {
  95250. int x = 0;
  95251. canjump = 1;
  95252. /* PPC64 hardware implements the cntlzd instruction */
  95253. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95254. info->data.ppc.ppc64 = 1;
  95255. }
  95256. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95257. }
  95258. # endif
  95259. # else /* !FLAC__USE_ALTIVEC */
  95260. info->data.ppc.altivec = 0;
  95261. info->data.ppc.ppc64 = 0;
  95262. # endif
  95263. # else
  95264. info->use_asm = false;
  95265. # endif
  95266. /*
  95267. * unknown CPI
  95268. */
  95269. #else
  95270. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95271. info->use_asm = false;
  95272. #endif
  95273. }
  95274. #endif
  95275. /*** End of inlined file: cpu.c ***/
  95276. /*** Start of inlined file: crc.c ***/
  95277. /*** Start of inlined file: juce_FlacHeader.h ***/
  95278. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95279. // tasks..
  95280. #define VERSION "1.2.1"
  95281. #define FLAC__NO_DLL 1
  95282. #if JUCE_MSVC
  95283. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95284. #endif
  95285. #if JUCE_MAC
  95286. #define FLAC__SYS_DARWIN 1
  95287. #endif
  95288. /*** End of inlined file: juce_FlacHeader.h ***/
  95289. #if JUCE_USE_FLAC
  95290. #if HAVE_CONFIG_H
  95291. # include <config.h>
  95292. #endif
  95293. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95294. FLAC__byte const FLAC__crc8_table[256] = {
  95295. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95296. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95297. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95298. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95299. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95300. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95301. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95302. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95303. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95304. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95305. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95306. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95307. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95308. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95309. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95310. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95311. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95312. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95313. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95314. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95315. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95316. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95317. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95318. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95319. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95320. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95321. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95322. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95323. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95324. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95325. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95326. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95327. };
  95328. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95329. unsigned FLAC__crc16_table[256] = {
  95330. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95331. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95332. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95333. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95334. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95335. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95336. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95337. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95338. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95339. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95340. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95341. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95342. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95343. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95344. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95345. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95346. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95347. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95348. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95349. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95350. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95351. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95352. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95353. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95354. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95355. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95356. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95357. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95358. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95359. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95360. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95361. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95362. };
  95363. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95364. {
  95365. *crc = FLAC__crc8_table[*crc ^ data];
  95366. }
  95367. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95368. {
  95369. while(len--)
  95370. *crc = FLAC__crc8_table[*crc ^ *data++];
  95371. }
  95372. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95373. {
  95374. FLAC__uint8 crc = 0;
  95375. while(len--)
  95376. crc = FLAC__crc8_table[crc ^ *data++];
  95377. return crc;
  95378. }
  95379. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95380. {
  95381. unsigned crc = 0;
  95382. while(len--)
  95383. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95384. return crc;
  95385. }
  95386. #endif
  95387. /*** End of inlined file: crc.c ***/
  95388. /*** Start of inlined file: fixed.c ***/
  95389. /*** Start of inlined file: juce_FlacHeader.h ***/
  95390. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95391. // tasks..
  95392. #define VERSION "1.2.1"
  95393. #define FLAC__NO_DLL 1
  95394. #if JUCE_MSVC
  95395. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95396. #endif
  95397. #if JUCE_MAC
  95398. #define FLAC__SYS_DARWIN 1
  95399. #endif
  95400. /*** End of inlined file: juce_FlacHeader.h ***/
  95401. #if JUCE_USE_FLAC
  95402. #if HAVE_CONFIG_H
  95403. # include <config.h>
  95404. #endif
  95405. #include <math.h>
  95406. #include <string.h>
  95407. /*** Start of inlined file: fixed.h ***/
  95408. #ifndef FLAC__PRIVATE__FIXED_H
  95409. #define FLAC__PRIVATE__FIXED_H
  95410. #ifdef HAVE_CONFIG_H
  95411. #include <config.h>
  95412. #endif
  95413. /*** Start of inlined file: float.h ***/
  95414. #ifndef FLAC__PRIVATE__FLOAT_H
  95415. #define FLAC__PRIVATE__FLOAT_H
  95416. #ifdef HAVE_CONFIG_H
  95417. #include <config.h>
  95418. #endif
  95419. /*
  95420. * These typedefs make it easier to ensure that integer versions of
  95421. * the library really only contain integer operations. All the code
  95422. * in libFLAC should use FLAC__float and FLAC__double in place of
  95423. * float and double, and be protected by checks of the macro
  95424. * FLAC__INTEGER_ONLY_LIBRARY.
  95425. *
  95426. * FLAC__real is the basic floating point type used in LPC analysis.
  95427. */
  95428. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95429. typedef double FLAC__double;
  95430. typedef float FLAC__float;
  95431. /*
  95432. * WATCHOUT: changing FLAC__real will change the signatures of many
  95433. * functions that have assembly language equivalents and break them.
  95434. */
  95435. typedef float FLAC__real;
  95436. #else
  95437. /*
  95438. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95439. * for the integer part and lower 16 bits for the fractional part.
  95440. */
  95441. typedef FLAC__int32 FLAC__fixedpoint;
  95442. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95443. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95444. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95445. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95446. extern const FLAC__fixedpoint FLAC__FP_E;
  95447. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95448. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95449. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95450. /*
  95451. * FLAC__fixedpoint_log2()
  95452. * --------------------------------------------------------------------
  95453. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95454. * algorithm by Knuth for x >= 1.0
  95455. *
  95456. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95457. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95458. *
  95459. * 'precision' roughly limits the number of iterations that are done;
  95460. * use (unsigned)(-1) for maximum precision.
  95461. *
  95462. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95463. * function will punt and return 0.
  95464. *
  95465. * The return value will also have 'fracbits' fractional bits.
  95466. */
  95467. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95468. #endif
  95469. #endif
  95470. /*** End of inlined file: float.h ***/
  95471. /*** Start of inlined file: format.h ***/
  95472. #ifndef FLAC__PRIVATE__FORMAT_H
  95473. #define FLAC__PRIVATE__FORMAT_H
  95474. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95475. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95476. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95477. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95478. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95479. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95480. #endif
  95481. /*** End of inlined file: format.h ***/
  95482. /*
  95483. * FLAC__fixed_compute_best_predictor()
  95484. * --------------------------------------------------------------------
  95485. * Compute the best fixed predictor and the expected bits-per-sample
  95486. * of the residual signal for each order. The _wide() version uses
  95487. * 64-bit integers which is statistically necessary when bits-per-
  95488. * sample + log2(blocksize) > 30
  95489. *
  95490. * IN data[0,data_len-1]
  95491. * IN data_len
  95492. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95493. */
  95494. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95495. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95496. # ifndef FLAC__NO_ASM
  95497. # ifdef FLAC__CPU_IA32
  95498. # ifdef FLAC__HAS_NASM
  95499. 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]);
  95500. # endif
  95501. # endif
  95502. # endif
  95503. 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]);
  95504. #else
  95505. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95506. 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]);
  95507. #endif
  95508. /*
  95509. * FLAC__fixed_compute_residual()
  95510. * --------------------------------------------------------------------
  95511. * Compute the residual signal obtained from sutracting the predicted
  95512. * signal from the original.
  95513. *
  95514. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  95515. * IN data_len length of original signal
  95516. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95517. * OUT residual[0,data_len-1] residual signal
  95518. */
  95519. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  95520. /*
  95521. * FLAC__fixed_restore_signal()
  95522. * --------------------------------------------------------------------
  95523. * Restore the original signal by summing the residual and the
  95524. * predictor.
  95525. *
  95526. * IN residual[0,data_len-1] residual signal
  95527. * IN data_len length of original signal
  95528. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95529. * *** IMPORTANT: the caller must pass in the historical samples:
  95530. * IN data[-order,-1] previously-reconstructed historical samples
  95531. * OUT data[0,data_len-1] original signal
  95532. */
  95533. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  95534. #endif
  95535. /*** End of inlined file: fixed.h ***/
  95536. #ifndef M_LN2
  95537. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  95538. #define M_LN2 0.69314718055994530942
  95539. #endif
  95540. #ifdef min
  95541. #undef min
  95542. #endif
  95543. #define min(x,y) ((x) < (y)? (x) : (y))
  95544. #ifdef local_abs
  95545. #undef local_abs
  95546. #endif
  95547. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  95548. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95549. /* rbps stands for residual bits per sample
  95550. *
  95551. * (ln(2) * err)
  95552. * rbps = log (-----------)
  95553. * 2 ( n )
  95554. */
  95555. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  95556. {
  95557. FLAC__uint32 rbps;
  95558. unsigned bits; /* the number of bits required to represent a number */
  95559. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95560. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95561. FLAC__ASSERT(err > 0);
  95562. FLAC__ASSERT(n > 0);
  95563. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95564. if(err <= n)
  95565. return 0;
  95566. /*
  95567. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95568. * These allow us later to know we won't lose too much precision in the
  95569. * fixed-point division (err<<fracbits)/n.
  95570. */
  95571. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  95572. err <<= fracbits;
  95573. err /= n;
  95574. /* err now holds err/n with fracbits fractional bits */
  95575. /*
  95576. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95577. * our purposes.
  95578. */
  95579. FLAC__ASSERT(err > 0);
  95580. bits = FLAC__bitmath_ilog2(err)+1;
  95581. if(bits > 16) {
  95582. err >>= (bits-16);
  95583. fracbits -= (bits-16);
  95584. }
  95585. rbps = (FLAC__uint32)err;
  95586. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95587. rbps *= FLAC__FP_LN2;
  95588. fracbits += 16;
  95589. FLAC__ASSERT(fracbits >= 0);
  95590. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95591. {
  95592. const int f = fracbits & 3;
  95593. if(f) {
  95594. rbps >>= f;
  95595. fracbits -= f;
  95596. }
  95597. }
  95598. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95599. if(rbps == 0)
  95600. return 0;
  95601. /*
  95602. * The return value must have 16 fractional bits. Since the whole part
  95603. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95604. * must be >= -3, these assertion allows us to be able to shift rbps
  95605. * left if necessary to get 16 fracbits without losing any bits of the
  95606. * whole part of rbps.
  95607. *
  95608. * There is a slight chance due to accumulated error that the whole part
  95609. * will require 6 bits, so we use 6 in the assertion. Really though as
  95610. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95611. */
  95612. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95613. FLAC__ASSERT(fracbits >= -3);
  95614. /* now shift the decimal point into place */
  95615. if(fracbits < 16)
  95616. return rbps << (16-fracbits);
  95617. else if(fracbits > 16)
  95618. return rbps >> (fracbits-16);
  95619. else
  95620. return rbps;
  95621. }
  95622. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  95623. {
  95624. FLAC__uint32 rbps;
  95625. unsigned bits; /* the number of bits required to represent a number */
  95626. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95627. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95628. FLAC__ASSERT(err > 0);
  95629. FLAC__ASSERT(n > 0);
  95630. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95631. if(err <= n)
  95632. return 0;
  95633. /*
  95634. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95635. * These allow us later to know we won't lose too much precision in the
  95636. * fixed-point division (err<<fracbits)/n.
  95637. */
  95638. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  95639. err <<= fracbits;
  95640. err /= n;
  95641. /* err now holds err/n with fracbits fractional bits */
  95642. /*
  95643. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95644. * our purposes.
  95645. */
  95646. FLAC__ASSERT(err > 0);
  95647. bits = FLAC__bitmath_ilog2_wide(err)+1;
  95648. if(bits > 16) {
  95649. err >>= (bits-16);
  95650. fracbits -= (bits-16);
  95651. }
  95652. rbps = (FLAC__uint32)err;
  95653. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95654. rbps *= FLAC__FP_LN2;
  95655. fracbits += 16;
  95656. FLAC__ASSERT(fracbits >= 0);
  95657. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95658. {
  95659. const int f = fracbits & 3;
  95660. if(f) {
  95661. rbps >>= f;
  95662. fracbits -= f;
  95663. }
  95664. }
  95665. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95666. if(rbps == 0)
  95667. return 0;
  95668. /*
  95669. * The return value must have 16 fractional bits. Since the whole part
  95670. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95671. * must be >= -3, these assertion allows us to be able to shift rbps
  95672. * left if necessary to get 16 fracbits without losing any bits of the
  95673. * whole part of rbps.
  95674. *
  95675. * There is a slight chance due to accumulated error that the whole part
  95676. * will require 6 bits, so we use 6 in the assertion. Really though as
  95677. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95678. */
  95679. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95680. FLAC__ASSERT(fracbits >= -3);
  95681. /* now shift the decimal point into place */
  95682. if(fracbits < 16)
  95683. return rbps << (16-fracbits);
  95684. else if(fracbits > 16)
  95685. return rbps >> (fracbits-16);
  95686. else
  95687. return rbps;
  95688. }
  95689. #endif
  95690. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95691. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95692. #else
  95693. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95694. #endif
  95695. {
  95696. FLAC__int32 last_error_0 = data[-1];
  95697. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95698. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95699. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95700. FLAC__int32 error, save;
  95701. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95702. unsigned i, order;
  95703. for(i = 0; i < data_len; i++) {
  95704. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95705. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95706. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95707. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95708. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95709. }
  95710. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95711. order = 0;
  95712. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95713. order = 1;
  95714. else if(total_error_2 < min(total_error_3, total_error_4))
  95715. order = 2;
  95716. else if(total_error_3 < total_error_4)
  95717. order = 3;
  95718. else
  95719. order = 4;
  95720. /* Estimate the expected number of bits per residual signal sample. */
  95721. /* 'total_error*' is linearly related to the variance of the residual */
  95722. /* signal, so we use it directly to compute E(|x|) */
  95723. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95724. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95725. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95726. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95727. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95728. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95729. 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);
  95730. 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);
  95731. 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);
  95732. 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);
  95733. 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);
  95734. #else
  95735. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  95736. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  95737. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  95738. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  95739. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  95740. #endif
  95741. return order;
  95742. }
  95743. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95744. 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])
  95745. #else
  95746. 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])
  95747. #endif
  95748. {
  95749. FLAC__int32 last_error_0 = data[-1];
  95750. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95751. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95752. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95753. FLAC__int32 error, save;
  95754. /* total_error_* are 64-bits to avoid overflow when encoding
  95755. * erratic signals when the bits-per-sample and blocksize are
  95756. * large.
  95757. */
  95758. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95759. unsigned i, order;
  95760. for(i = 0; i < data_len; i++) {
  95761. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95762. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95763. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95764. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95765. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95766. }
  95767. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95768. order = 0;
  95769. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95770. order = 1;
  95771. else if(total_error_2 < min(total_error_3, total_error_4))
  95772. order = 2;
  95773. else if(total_error_3 < total_error_4)
  95774. order = 3;
  95775. else
  95776. order = 4;
  95777. /* Estimate the expected number of bits per residual signal sample. */
  95778. /* 'total_error*' is linearly related to the variance of the residual */
  95779. /* signal, so we use it directly to compute E(|x|) */
  95780. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95781. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95782. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95783. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95784. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95785. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95786. #if defined _MSC_VER || defined __MINGW32__
  95787. /* with MSVC you have to spoon feed it the casting */
  95788. 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);
  95789. 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);
  95790. 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);
  95791. 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);
  95792. 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);
  95793. #else
  95794. 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);
  95795. 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);
  95796. 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);
  95797. 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);
  95798. 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);
  95799. #endif
  95800. #else
  95801. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  95802. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  95803. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  95804. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  95805. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  95806. #endif
  95807. return order;
  95808. }
  95809. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  95810. {
  95811. const int idata_len = (int)data_len;
  95812. int i;
  95813. switch(order) {
  95814. case 0:
  95815. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95816. memcpy(residual, data, sizeof(residual[0])*data_len);
  95817. break;
  95818. case 1:
  95819. for(i = 0; i < idata_len; i++)
  95820. residual[i] = data[i] - data[i-1];
  95821. break;
  95822. case 2:
  95823. for(i = 0; i < idata_len; i++)
  95824. #if 1 /* OPT: may be faster with some compilers on some systems */
  95825. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  95826. #else
  95827. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  95828. #endif
  95829. break;
  95830. case 3:
  95831. for(i = 0; i < idata_len; i++)
  95832. #if 1 /* OPT: may be faster with some compilers on some systems */
  95833. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  95834. #else
  95835. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  95836. #endif
  95837. break;
  95838. case 4:
  95839. for(i = 0; i < idata_len; i++)
  95840. #if 1 /* OPT: may be faster with some compilers on some systems */
  95841. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  95842. #else
  95843. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  95844. #endif
  95845. break;
  95846. default:
  95847. FLAC__ASSERT(0);
  95848. }
  95849. }
  95850. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  95851. {
  95852. int i, idata_len = (int)data_len;
  95853. switch(order) {
  95854. case 0:
  95855. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95856. memcpy(data, residual, sizeof(residual[0])*data_len);
  95857. break;
  95858. case 1:
  95859. for(i = 0; i < idata_len; i++)
  95860. data[i] = residual[i] + data[i-1];
  95861. break;
  95862. case 2:
  95863. for(i = 0; i < idata_len; i++)
  95864. #if 1 /* OPT: may be faster with some compilers on some systems */
  95865. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  95866. #else
  95867. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  95868. #endif
  95869. break;
  95870. case 3:
  95871. for(i = 0; i < idata_len; i++)
  95872. #if 1 /* OPT: may be faster with some compilers on some systems */
  95873. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  95874. #else
  95875. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  95876. #endif
  95877. break;
  95878. case 4:
  95879. for(i = 0; i < idata_len; i++)
  95880. #if 1 /* OPT: may be faster with some compilers on some systems */
  95881. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  95882. #else
  95883. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  95884. #endif
  95885. break;
  95886. default:
  95887. FLAC__ASSERT(0);
  95888. }
  95889. }
  95890. #endif
  95891. /*** End of inlined file: fixed.c ***/
  95892. /*** Start of inlined file: float.c ***/
  95893. /*** Start of inlined file: juce_FlacHeader.h ***/
  95894. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95895. // tasks..
  95896. #define VERSION "1.2.1"
  95897. #define FLAC__NO_DLL 1
  95898. #if JUCE_MSVC
  95899. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95900. #endif
  95901. #if JUCE_MAC
  95902. #define FLAC__SYS_DARWIN 1
  95903. #endif
  95904. /*** End of inlined file: juce_FlacHeader.h ***/
  95905. #if JUCE_USE_FLAC
  95906. #if HAVE_CONFIG_H
  95907. # include <config.h>
  95908. #endif
  95909. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95910. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95911. #ifdef _MSC_VER
  95912. #define FLAC__U64L(x) x
  95913. #else
  95914. #define FLAC__U64L(x) x##LLU
  95915. #endif
  95916. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  95917. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  95918. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  95919. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  95920. const FLAC__fixedpoint FLAC__FP_E = 178145;
  95921. /* Lookup tables for Knuth's logarithm algorithm */
  95922. #define LOG2_LOOKUP_PRECISION 16
  95923. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  95924. {
  95925. /*
  95926. * 0 fraction bits
  95927. */
  95928. /* undefined */ 0x00000000,
  95929. /* lg(2/1) = */ 0x00000001,
  95930. /* lg(4/3) = */ 0x00000000,
  95931. /* lg(8/7) = */ 0x00000000,
  95932. /* lg(16/15) = */ 0x00000000,
  95933. /* lg(32/31) = */ 0x00000000,
  95934. /* lg(64/63) = */ 0x00000000,
  95935. /* lg(128/127) = */ 0x00000000,
  95936. /* lg(256/255) = */ 0x00000000,
  95937. /* lg(512/511) = */ 0x00000000,
  95938. /* lg(1024/1023) = */ 0x00000000,
  95939. /* lg(2048/2047) = */ 0x00000000,
  95940. /* lg(4096/4095) = */ 0x00000000,
  95941. /* lg(8192/8191) = */ 0x00000000,
  95942. /* lg(16384/16383) = */ 0x00000000,
  95943. /* lg(32768/32767) = */ 0x00000000
  95944. },
  95945. {
  95946. /*
  95947. * 4 fraction bits
  95948. */
  95949. /* undefined */ 0x00000000,
  95950. /* lg(2/1) = */ 0x00000010,
  95951. /* lg(4/3) = */ 0x00000007,
  95952. /* lg(8/7) = */ 0x00000003,
  95953. /* lg(16/15) = */ 0x00000001,
  95954. /* lg(32/31) = */ 0x00000001,
  95955. /* lg(64/63) = */ 0x00000000,
  95956. /* lg(128/127) = */ 0x00000000,
  95957. /* lg(256/255) = */ 0x00000000,
  95958. /* lg(512/511) = */ 0x00000000,
  95959. /* lg(1024/1023) = */ 0x00000000,
  95960. /* lg(2048/2047) = */ 0x00000000,
  95961. /* lg(4096/4095) = */ 0x00000000,
  95962. /* lg(8192/8191) = */ 0x00000000,
  95963. /* lg(16384/16383) = */ 0x00000000,
  95964. /* lg(32768/32767) = */ 0x00000000
  95965. },
  95966. {
  95967. /*
  95968. * 8 fraction bits
  95969. */
  95970. /* undefined */ 0x00000000,
  95971. /* lg(2/1) = */ 0x00000100,
  95972. /* lg(4/3) = */ 0x0000006a,
  95973. /* lg(8/7) = */ 0x00000031,
  95974. /* lg(16/15) = */ 0x00000018,
  95975. /* lg(32/31) = */ 0x0000000c,
  95976. /* lg(64/63) = */ 0x00000006,
  95977. /* lg(128/127) = */ 0x00000003,
  95978. /* lg(256/255) = */ 0x00000001,
  95979. /* lg(512/511) = */ 0x00000001,
  95980. /* lg(1024/1023) = */ 0x00000000,
  95981. /* lg(2048/2047) = */ 0x00000000,
  95982. /* lg(4096/4095) = */ 0x00000000,
  95983. /* lg(8192/8191) = */ 0x00000000,
  95984. /* lg(16384/16383) = */ 0x00000000,
  95985. /* lg(32768/32767) = */ 0x00000000
  95986. },
  95987. {
  95988. /*
  95989. * 12 fraction bits
  95990. */
  95991. /* undefined */ 0x00000000,
  95992. /* lg(2/1) = */ 0x00001000,
  95993. /* lg(4/3) = */ 0x000006a4,
  95994. /* lg(8/7) = */ 0x00000315,
  95995. /* lg(16/15) = */ 0x0000017d,
  95996. /* lg(32/31) = */ 0x000000bc,
  95997. /* lg(64/63) = */ 0x0000005d,
  95998. /* lg(128/127) = */ 0x0000002e,
  95999. /* lg(256/255) = */ 0x00000017,
  96000. /* lg(512/511) = */ 0x0000000c,
  96001. /* lg(1024/1023) = */ 0x00000006,
  96002. /* lg(2048/2047) = */ 0x00000003,
  96003. /* lg(4096/4095) = */ 0x00000001,
  96004. /* lg(8192/8191) = */ 0x00000001,
  96005. /* lg(16384/16383) = */ 0x00000000,
  96006. /* lg(32768/32767) = */ 0x00000000
  96007. },
  96008. {
  96009. /*
  96010. * 16 fraction bits
  96011. */
  96012. /* undefined */ 0x00000000,
  96013. /* lg(2/1) = */ 0x00010000,
  96014. /* lg(4/3) = */ 0x00006a40,
  96015. /* lg(8/7) = */ 0x00003151,
  96016. /* lg(16/15) = */ 0x000017d6,
  96017. /* lg(32/31) = */ 0x00000bba,
  96018. /* lg(64/63) = */ 0x000005d1,
  96019. /* lg(128/127) = */ 0x000002e6,
  96020. /* lg(256/255) = */ 0x00000172,
  96021. /* lg(512/511) = */ 0x000000b9,
  96022. /* lg(1024/1023) = */ 0x0000005c,
  96023. /* lg(2048/2047) = */ 0x0000002e,
  96024. /* lg(4096/4095) = */ 0x00000017,
  96025. /* lg(8192/8191) = */ 0x0000000c,
  96026. /* lg(16384/16383) = */ 0x00000006,
  96027. /* lg(32768/32767) = */ 0x00000003
  96028. },
  96029. {
  96030. /*
  96031. * 20 fraction bits
  96032. */
  96033. /* undefined */ 0x00000000,
  96034. /* lg(2/1) = */ 0x00100000,
  96035. /* lg(4/3) = */ 0x0006a3fe,
  96036. /* lg(8/7) = */ 0x00031513,
  96037. /* lg(16/15) = */ 0x00017d60,
  96038. /* lg(32/31) = */ 0x0000bb9d,
  96039. /* lg(64/63) = */ 0x00005d10,
  96040. /* lg(128/127) = */ 0x00002e59,
  96041. /* lg(256/255) = */ 0x00001721,
  96042. /* lg(512/511) = */ 0x00000b8e,
  96043. /* lg(1024/1023) = */ 0x000005c6,
  96044. /* lg(2048/2047) = */ 0x000002e3,
  96045. /* lg(4096/4095) = */ 0x00000171,
  96046. /* lg(8192/8191) = */ 0x000000b9,
  96047. /* lg(16384/16383) = */ 0x0000005c,
  96048. /* lg(32768/32767) = */ 0x0000002e
  96049. },
  96050. {
  96051. /*
  96052. * 24 fraction bits
  96053. */
  96054. /* undefined */ 0x00000000,
  96055. /* lg(2/1) = */ 0x01000000,
  96056. /* lg(4/3) = */ 0x006a3fe6,
  96057. /* lg(8/7) = */ 0x00315130,
  96058. /* lg(16/15) = */ 0x0017d605,
  96059. /* lg(32/31) = */ 0x000bb9ca,
  96060. /* lg(64/63) = */ 0x0005d0fc,
  96061. /* lg(128/127) = */ 0x0002e58f,
  96062. /* lg(256/255) = */ 0x0001720e,
  96063. /* lg(512/511) = */ 0x0000b8d8,
  96064. /* lg(1024/1023) = */ 0x00005c61,
  96065. /* lg(2048/2047) = */ 0x00002e2d,
  96066. /* lg(4096/4095) = */ 0x00001716,
  96067. /* lg(8192/8191) = */ 0x00000b8b,
  96068. /* lg(16384/16383) = */ 0x000005c5,
  96069. /* lg(32768/32767) = */ 0x000002e3
  96070. },
  96071. {
  96072. /*
  96073. * 28 fraction bits
  96074. */
  96075. /* undefined */ 0x00000000,
  96076. /* lg(2/1) = */ 0x10000000,
  96077. /* lg(4/3) = */ 0x06a3fe5c,
  96078. /* lg(8/7) = */ 0x03151301,
  96079. /* lg(16/15) = */ 0x017d6049,
  96080. /* lg(32/31) = */ 0x00bb9ca6,
  96081. /* lg(64/63) = */ 0x005d0fba,
  96082. /* lg(128/127) = */ 0x002e58f7,
  96083. /* lg(256/255) = */ 0x001720da,
  96084. /* lg(512/511) = */ 0x000b8d87,
  96085. /* lg(1024/1023) = */ 0x0005c60b,
  96086. /* lg(2048/2047) = */ 0x0002e2d7,
  96087. /* lg(4096/4095) = */ 0x00017160,
  96088. /* lg(8192/8191) = */ 0x0000b8ad,
  96089. /* lg(16384/16383) = */ 0x00005c56,
  96090. /* lg(32768/32767) = */ 0x00002e2b
  96091. }
  96092. };
  96093. #if 0
  96094. static const FLAC__uint64 log2_lookup_wide[] = {
  96095. {
  96096. /*
  96097. * 32 fraction bits
  96098. */
  96099. /* undefined */ 0x00000000,
  96100. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96101. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96102. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96103. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96104. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96105. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96106. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96107. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96108. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96109. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96110. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96111. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96112. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96113. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96114. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96115. },
  96116. {
  96117. /*
  96118. * 48 fraction bits
  96119. */
  96120. /* undefined */ 0x00000000,
  96121. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96122. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96123. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96124. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96125. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96126. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96127. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96128. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96129. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96130. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96131. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96132. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96133. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96134. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96135. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96136. }
  96137. };
  96138. #endif
  96139. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96140. {
  96141. const FLAC__uint32 ONE = (1u << fracbits);
  96142. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96143. FLAC__ASSERT(fracbits < 32);
  96144. FLAC__ASSERT((fracbits & 0x3) == 0);
  96145. if(x < ONE)
  96146. return 0;
  96147. if(precision > LOG2_LOOKUP_PRECISION)
  96148. precision = LOG2_LOOKUP_PRECISION;
  96149. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96150. {
  96151. FLAC__uint32 y = 0;
  96152. FLAC__uint32 z = x >> 1, k = 1;
  96153. while (x > ONE && k < precision) {
  96154. if (x - z >= ONE) {
  96155. x -= z;
  96156. z = x >> k;
  96157. y += table[k];
  96158. }
  96159. else {
  96160. z >>= 1;
  96161. k++;
  96162. }
  96163. }
  96164. return y;
  96165. }
  96166. }
  96167. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96168. #endif
  96169. /*** End of inlined file: float.c ***/
  96170. /*** Start of inlined file: format.c ***/
  96171. /*** Start of inlined file: juce_FlacHeader.h ***/
  96172. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96173. // tasks..
  96174. #define VERSION "1.2.1"
  96175. #define FLAC__NO_DLL 1
  96176. #if JUCE_MSVC
  96177. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96178. #endif
  96179. #if JUCE_MAC
  96180. #define FLAC__SYS_DARWIN 1
  96181. #endif
  96182. /*** End of inlined file: juce_FlacHeader.h ***/
  96183. #if JUCE_USE_FLAC
  96184. #if HAVE_CONFIG_H
  96185. # include <config.h>
  96186. #endif
  96187. #include <stdio.h>
  96188. #include <stdlib.h> /* for qsort() */
  96189. #include <string.h> /* for memset() */
  96190. #ifndef FLaC__INLINE
  96191. #define FLaC__INLINE
  96192. #endif
  96193. #ifdef min
  96194. #undef min
  96195. #endif
  96196. #define min(a,b) ((a)<(b)?(a):(b))
  96197. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96198. #ifdef _MSC_VER
  96199. #define FLAC__U64L(x) x
  96200. #else
  96201. #define FLAC__U64L(x) x##LLU
  96202. #endif
  96203. /* VERSION should come from configure */
  96204. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96205. ;
  96206. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96207. /* yet one more hack because of MSVC6: */
  96208. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96209. #else
  96210. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96211. #endif
  96212. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96213. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96214. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96215. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96216. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96217. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96218. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96219. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96220. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96221. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96222. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96223. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96224. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96225. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96226. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96227. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96228. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96229. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96230. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96231. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96232. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96233. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96234. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96235. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96236. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96237. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96238. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96239. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96240. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96241. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96242. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96243. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96244. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96245. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96246. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96247. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96248. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96249. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96250. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96251. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96252. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96253. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96254. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96255. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96256. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96257. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96258. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96259. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96260. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96261. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96262. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96263. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96264. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96265. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96266. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96267. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96268. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96269. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96270. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96271. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96272. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96273. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96274. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96275. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96276. "PARTITIONED_RICE",
  96277. "PARTITIONED_RICE2"
  96278. };
  96279. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96280. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96281. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96282. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96283. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96284. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96285. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96286. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96287. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96288. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96289. "CONSTANT",
  96290. "VERBATIM",
  96291. "FIXED",
  96292. "LPC"
  96293. };
  96294. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96295. "INDEPENDENT",
  96296. "LEFT_SIDE",
  96297. "RIGHT_SIDE",
  96298. "MID_SIDE"
  96299. };
  96300. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96301. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96302. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96303. };
  96304. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96305. "STREAMINFO",
  96306. "PADDING",
  96307. "APPLICATION",
  96308. "SEEKTABLE",
  96309. "VORBIS_COMMENT",
  96310. "CUESHEET",
  96311. "PICTURE"
  96312. };
  96313. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96314. "Other",
  96315. "32x32 pixels 'file icon' (PNG only)",
  96316. "Other file icon",
  96317. "Cover (front)",
  96318. "Cover (back)",
  96319. "Leaflet page",
  96320. "Media (e.g. label side of CD)",
  96321. "Lead artist/lead performer/soloist",
  96322. "Artist/performer",
  96323. "Conductor",
  96324. "Band/Orchestra",
  96325. "Composer",
  96326. "Lyricist/text writer",
  96327. "Recording Location",
  96328. "During recording",
  96329. "During performance",
  96330. "Movie/video screen capture",
  96331. "A bright coloured fish",
  96332. "Illustration",
  96333. "Band/artist logotype",
  96334. "Publisher/Studio logotype"
  96335. };
  96336. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96337. {
  96338. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96339. return false;
  96340. }
  96341. else
  96342. return true;
  96343. }
  96344. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96345. {
  96346. if(
  96347. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96348. (
  96349. sample_rate >= (1u << 16) &&
  96350. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96351. )
  96352. ) {
  96353. return false;
  96354. }
  96355. else
  96356. return true;
  96357. }
  96358. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96359. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96360. {
  96361. unsigned i;
  96362. FLAC__uint64 prev_sample_number = 0;
  96363. FLAC__bool got_prev = false;
  96364. FLAC__ASSERT(0 != seek_table);
  96365. for(i = 0; i < seek_table->num_points; i++) {
  96366. if(got_prev) {
  96367. if(
  96368. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96369. seek_table->points[i].sample_number <= prev_sample_number
  96370. )
  96371. return false;
  96372. }
  96373. prev_sample_number = seek_table->points[i].sample_number;
  96374. got_prev = true;
  96375. }
  96376. return true;
  96377. }
  96378. /* used as the sort predicate for qsort() */
  96379. static int JUCE_CDECL seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96380. {
  96381. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96382. if(l->sample_number == r->sample_number)
  96383. return 0;
  96384. else if(l->sample_number < r->sample_number)
  96385. return -1;
  96386. else
  96387. return 1;
  96388. }
  96389. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96390. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96391. {
  96392. unsigned i, j;
  96393. FLAC__bool first;
  96394. FLAC__ASSERT(0 != seek_table);
  96395. /* sort the seekpoints */
  96396. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (JUCE_CDECL *)(const void *, const void *))seekpoint_compare_);
  96397. /* uniquify the seekpoints */
  96398. first = true;
  96399. for(i = j = 0; i < seek_table->num_points; i++) {
  96400. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96401. if(!first) {
  96402. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96403. continue;
  96404. }
  96405. }
  96406. first = false;
  96407. seek_table->points[j++] = seek_table->points[i];
  96408. }
  96409. for(i = j; i < seek_table->num_points; i++) {
  96410. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96411. seek_table->points[i].stream_offset = 0;
  96412. seek_table->points[i].frame_samples = 0;
  96413. }
  96414. return j;
  96415. }
  96416. /*
  96417. * also disallows non-shortest-form encodings, c.f.
  96418. * http://www.unicode.org/versions/corrigendum1.html
  96419. * and a more clear explanation at the end of this section:
  96420. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96421. */
  96422. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96423. {
  96424. FLAC__ASSERT(0 != utf8);
  96425. if ((utf8[0] & 0x80) == 0) {
  96426. return 1;
  96427. }
  96428. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96429. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96430. return 0;
  96431. return 2;
  96432. }
  96433. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96434. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96435. return 0;
  96436. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96437. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96438. return 0;
  96439. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96440. return 0;
  96441. return 3;
  96442. }
  96443. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96444. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96445. return 0;
  96446. return 4;
  96447. }
  96448. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96449. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96450. return 0;
  96451. return 5;
  96452. }
  96453. 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) {
  96454. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96455. return 0;
  96456. return 6;
  96457. }
  96458. else {
  96459. return 0;
  96460. }
  96461. }
  96462. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96463. {
  96464. char c;
  96465. for(c = *name; c; c = *(++name))
  96466. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96467. return false;
  96468. return true;
  96469. }
  96470. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96471. {
  96472. if(length == (unsigned)(-1)) {
  96473. while(*value) {
  96474. unsigned n = utf8len_(value);
  96475. if(n == 0)
  96476. return false;
  96477. value += n;
  96478. }
  96479. }
  96480. else {
  96481. const FLAC__byte *end = value + length;
  96482. while(value < end) {
  96483. unsigned n = utf8len_(value);
  96484. if(n == 0)
  96485. return false;
  96486. value += n;
  96487. }
  96488. if(value != end)
  96489. return false;
  96490. }
  96491. return true;
  96492. }
  96493. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96494. {
  96495. const FLAC__byte *s, *end;
  96496. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  96497. if(*s < 0x20 || *s > 0x7D)
  96498. return false;
  96499. }
  96500. if(s == end)
  96501. return false;
  96502. s++; /* skip '=' */
  96503. while(s < end) {
  96504. unsigned n = utf8len_(s);
  96505. if(n == 0)
  96506. return false;
  96507. s += n;
  96508. }
  96509. if(s != end)
  96510. return false;
  96511. return true;
  96512. }
  96513. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96514. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  96515. {
  96516. unsigned i, j;
  96517. if(check_cd_da_subset) {
  96518. if(cue_sheet->lead_in < 2 * 44100) {
  96519. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  96520. return false;
  96521. }
  96522. if(cue_sheet->lead_in % 588 != 0) {
  96523. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  96524. return false;
  96525. }
  96526. }
  96527. if(cue_sheet->num_tracks == 0) {
  96528. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  96529. return false;
  96530. }
  96531. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  96532. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  96533. return false;
  96534. }
  96535. for(i = 0; i < cue_sheet->num_tracks; i++) {
  96536. if(cue_sheet->tracks[i].number == 0) {
  96537. if(violation) *violation = "cue sheet may not have a track number 0";
  96538. return false;
  96539. }
  96540. if(check_cd_da_subset) {
  96541. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  96542. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  96543. return false;
  96544. }
  96545. }
  96546. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  96547. if(violation) {
  96548. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  96549. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  96550. else
  96551. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  96552. }
  96553. return false;
  96554. }
  96555. if(i < cue_sheet->num_tracks - 1) {
  96556. if(cue_sheet->tracks[i].num_indices == 0) {
  96557. if(violation) *violation = "cue sheet track must have at least one index point";
  96558. return false;
  96559. }
  96560. if(cue_sheet->tracks[i].indices[0].number > 1) {
  96561. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  96562. return false;
  96563. }
  96564. }
  96565. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  96566. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  96567. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  96568. return false;
  96569. }
  96570. if(j > 0) {
  96571. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  96572. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  96573. return false;
  96574. }
  96575. }
  96576. }
  96577. }
  96578. return true;
  96579. }
  96580. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96581. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  96582. {
  96583. char *p;
  96584. FLAC__byte *b;
  96585. for(p = picture->mime_type; *p; p++) {
  96586. if(*p < 0x20 || *p > 0x7e) {
  96587. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  96588. return false;
  96589. }
  96590. }
  96591. for(b = picture->description; *b; ) {
  96592. unsigned n = utf8len_(b);
  96593. if(n == 0) {
  96594. if(violation) *violation = "description string must be valid UTF-8";
  96595. return false;
  96596. }
  96597. b += n;
  96598. }
  96599. return true;
  96600. }
  96601. /*
  96602. * These routines are private to libFLAC
  96603. */
  96604. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  96605. {
  96606. return
  96607. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  96608. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  96609. blocksize,
  96610. predictor_order
  96611. );
  96612. }
  96613. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  96614. {
  96615. unsigned max_rice_partition_order = 0;
  96616. while(!(blocksize & 1)) {
  96617. max_rice_partition_order++;
  96618. blocksize >>= 1;
  96619. }
  96620. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  96621. }
  96622. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  96623. {
  96624. unsigned max_rice_partition_order = limit;
  96625. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  96626. max_rice_partition_order--;
  96627. FLAC__ASSERT(
  96628. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  96629. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  96630. );
  96631. return max_rice_partition_order;
  96632. }
  96633. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96634. {
  96635. FLAC__ASSERT(0 != object);
  96636. object->parameters = 0;
  96637. object->raw_bits = 0;
  96638. object->capacity_by_order = 0;
  96639. }
  96640. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96641. {
  96642. FLAC__ASSERT(0 != object);
  96643. if(0 != object->parameters)
  96644. free(object->parameters);
  96645. if(0 != object->raw_bits)
  96646. free(object->raw_bits);
  96647. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  96648. }
  96649. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  96650. {
  96651. FLAC__ASSERT(0 != object);
  96652. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  96653. if(object->capacity_by_order < max_partition_order) {
  96654. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  96655. return false;
  96656. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  96657. return false;
  96658. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  96659. object->capacity_by_order = max_partition_order;
  96660. }
  96661. return true;
  96662. }
  96663. #endif
  96664. /*** End of inlined file: format.c ***/
  96665. /*** Start of inlined file: lpc_flac.c ***/
  96666. /*** Start of inlined file: juce_FlacHeader.h ***/
  96667. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96668. // tasks..
  96669. #define VERSION "1.2.1"
  96670. #define FLAC__NO_DLL 1
  96671. #if JUCE_MSVC
  96672. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96673. #endif
  96674. #if JUCE_MAC
  96675. #define FLAC__SYS_DARWIN 1
  96676. #endif
  96677. /*** End of inlined file: juce_FlacHeader.h ***/
  96678. #if JUCE_USE_FLAC
  96679. #if HAVE_CONFIG_H
  96680. # include <config.h>
  96681. #endif
  96682. #include <math.h>
  96683. /*** Start of inlined file: lpc.h ***/
  96684. #ifndef FLAC__PRIVATE__LPC_H
  96685. #define FLAC__PRIVATE__LPC_H
  96686. #ifdef HAVE_CONFIG_H
  96687. #include <config.h>
  96688. #endif
  96689. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96690. /*
  96691. * FLAC__lpc_window_data()
  96692. * --------------------------------------------------------------------
  96693. * Applies the given window to the data.
  96694. * OPT: asm implementation
  96695. *
  96696. * IN in[0,data_len-1]
  96697. * IN window[0,data_len-1]
  96698. * OUT out[0,lag-1]
  96699. * IN data_len
  96700. */
  96701. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  96702. /*
  96703. * FLAC__lpc_compute_autocorrelation()
  96704. * --------------------------------------------------------------------
  96705. * Compute the autocorrelation for lags between 0 and lag-1.
  96706. * Assumes data[] outside of [0,data_len-1] == 0.
  96707. * Asserts that lag > 0.
  96708. *
  96709. * IN data[0,data_len-1]
  96710. * IN data_len
  96711. * IN 0 < lag <= data_len
  96712. * OUT autoc[0,lag-1]
  96713. */
  96714. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96715. #ifndef FLAC__NO_ASM
  96716. # ifdef FLAC__CPU_IA32
  96717. # ifdef FLAC__HAS_NASM
  96718. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96719. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96720. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96721. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96722. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96723. # endif
  96724. # endif
  96725. #endif
  96726. /*
  96727. * FLAC__lpc_compute_lp_coefficients()
  96728. * --------------------------------------------------------------------
  96729. * Computes LP coefficients for orders 1..max_order.
  96730. * Do not call if autoc[0] == 0.0. This means the signal is zero
  96731. * and there is no point in calculating a predictor.
  96732. *
  96733. * IN autoc[0,max_order] autocorrelation values
  96734. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  96735. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  96736. * *** IMPORTANT:
  96737. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  96738. * OUT error[0,max_order-1] error for each order (more
  96739. * specifically, the variance of
  96740. * the error signal times # of
  96741. * samples in the signal)
  96742. *
  96743. * Example: if max_order is 9, the LP coefficients for order 9 will be
  96744. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  96745. * in lp_coeff[7][0,7], etc.
  96746. */
  96747. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  96748. /*
  96749. * FLAC__lpc_quantize_coefficients()
  96750. * --------------------------------------------------------------------
  96751. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  96752. * must be less than 32 (sizeof(FLAC__int32)*8).
  96753. *
  96754. * IN lp_coeff[0,order-1] LP coefficients
  96755. * IN order LP order
  96756. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  96757. * desired precision (in bits, including sign
  96758. * bit) of largest coefficient
  96759. * OUT qlp_coeff[0,order-1] quantized coefficients
  96760. * OUT shift # of bits to shift right to get approximated
  96761. * LP coefficients. NOTE: could be negative.
  96762. * RETURN 0 => quantization OK
  96763. * 1 => coefficients require too much shifting for *shift to
  96764. * fit in the LPC subframe header. 'shift' is unset.
  96765. * 2 => coefficients are all zero, which is bad. 'shift' is
  96766. * unset.
  96767. */
  96768. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  96769. /*
  96770. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  96771. * --------------------------------------------------------------------
  96772. * Compute the residual signal obtained from sutracting the predicted
  96773. * signal from the original.
  96774. *
  96775. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96776. * IN data_len length of original signal
  96777. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96778. * IN order > 0 LP order
  96779. * IN lp_quantization quantization of LP coefficients in bits
  96780. * OUT residual[0,data_len-1] residual signal
  96781. */
  96782. 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[]);
  96783. 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[]);
  96784. #ifndef FLAC__NO_ASM
  96785. # ifdef FLAC__CPU_IA32
  96786. # ifdef FLAC__HAS_NASM
  96787. 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[]);
  96788. 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[]);
  96789. # endif
  96790. # endif
  96791. #endif
  96792. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96793. /*
  96794. * FLAC__lpc_restore_signal()
  96795. * --------------------------------------------------------------------
  96796. * Restore the original signal by summing the residual and the
  96797. * predictor.
  96798. *
  96799. * IN residual[0,data_len-1] residual signal
  96800. * IN data_len length of original signal
  96801. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96802. * IN order > 0 LP order
  96803. * IN lp_quantization quantization of LP coefficients in bits
  96804. * *** IMPORTANT: the caller must pass in the historical samples:
  96805. * IN data[-order,-1] previously-reconstructed historical samples
  96806. * OUT data[0,data_len-1] original signal
  96807. */
  96808. 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[]);
  96809. 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[]);
  96810. #ifndef FLAC__NO_ASM
  96811. # ifdef FLAC__CPU_IA32
  96812. # ifdef FLAC__HAS_NASM
  96813. 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[]);
  96814. 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[]);
  96815. # endif /* FLAC__HAS_NASM */
  96816. # elif defined FLAC__CPU_PPC
  96817. 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[]);
  96818. 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[]);
  96819. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  96820. #endif /* FLAC__NO_ASM */
  96821. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96822. /*
  96823. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  96824. * --------------------------------------------------------------------
  96825. * Compute the expected number of bits per residual signal sample
  96826. * based on the LP error (which is related to the residual variance).
  96827. *
  96828. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  96829. * IN total_samples > 0 # of samples in residual signal
  96830. * RETURN expected bits per sample
  96831. */
  96832. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  96833. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  96834. /*
  96835. * FLAC__lpc_compute_best_order()
  96836. * --------------------------------------------------------------------
  96837. * Compute the best order from the array of signal errors returned
  96838. * during coefficient computation.
  96839. *
  96840. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  96841. * IN max_order > 0 max LP order
  96842. * IN total_samples > 0 # of samples in residual signal
  96843. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  96844. * (includes warmup sample size and quantized LP coefficient)
  96845. * RETURN [1,max_order] best order
  96846. */
  96847. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  96848. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96849. #endif
  96850. /*** End of inlined file: lpc.h ***/
  96851. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  96852. #include <stdio.h>
  96853. #endif
  96854. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96855. #ifndef M_LN2
  96856. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  96857. #define M_LN2 0.69314718055994530942
  96858. #endif
  96859. /* OPT: #undef'ing this may improve the speed on some architectures */
  96860. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  96861. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  96862. {
  96863. unsigned i;
  96864. for(i = 0; i < data_len; i++)
  96865. out[i] = in[i] * window[i];
  96866. }
  96867. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  96868. {
  96869. /* a readable, but slower, version */
  96870. #if 0
  96871. FLAC__real d;
  96872. unsigned i;
  96873. FLAC__ASSERT(lag > 0);
  96874. FLAC__ASSERT(lag <= data_len);
  96875. /*
  96876. * Technically we should subtract the mean first like so:
  96877. * for(i = 0; i < data_len; i++)
  96878. * data[i] -= mean;
  96879. * but it appears not to make enough of a difference to matter, and
  96880. * most signals are already closely centered around zero
  96881. */
  96882. while(lag--) {
  96883. for(i = lag, d = 0.0; i < data_len; i++)
  96884. d += data[i] * data[i - lag];
  96885. autoc[lag] = d;
  96886. }
  96887. #endif
  96888. /*
  96889. * this version tends to run faster because of better data locality
  96890. * ('data_len' is usually much larger than 'lag')
  96891. */
  96892. FLAC__real d;
  96893. unsigned sample, coeff;
  96894. const unsigned limit = data_len - lag;
  96895. FLAC__ASSERT(lag > 0);
  96896. FLAC__ASSERT(lag <= data_len);
  96897. for(coeff = 0; coeff < lag; coeff++)
  96898. autoc[coeff] = 0.0;
  96899. for(sample = 0; sample <= limit; sample++) {
  96900. d = data[sample];
  96901. for(coeff = 0; coeff < lag; coeff++)
  96902. autoc[coeff] += d * data[sample+coeff];
  96903. }
  96904. for(; sample < data_len; sample++) {
  96905. d = data[sample];
  96906. for(coeff = 0; coeff < data_len - sample; coeff++)
  96907. autoc[coeff] += d * data[sample+coeff];
  96908. }
  96909. }
  96910. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  96911. {
  96912. unsigned i, j;
  96913. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  96914. FLAC__ASSERT(0 != max_order);
  96915. FLAC__ASSERT(0 < *max_order);
  96916. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  96917. FLAC__ASSERT(autoc[0] != 0.0);
  96918. err = autoc[0];
  96919. for(i = 0; i < *max_order; i++) {
  96920. /* Sum up this iteration's reflection coefficient. */
  96921. r = -autoc[i+1];
  96922. for(j = 0; j < i; j++)
  96923. r -= lpc[j] * autoc[i-j];
  96924. ref[i] = (r/=err);
  96925. /* Update LPC coefficients and total error. */
  96926. lpc[i]=r;
  96927. for(j = 0; j < (i>>1); j++) {
  96928. FLAC__double tmp = lpc[j];
  96929. lpc[j] += r * lpc[i-1-j];
  96930. lpc[i-1-j] += r * tmp;
  96931. }
  96932. if(i & 1)
  96933. lpc[j] += lpc[j] * r;
  96934. err *= (1.0 - r * r);
  96935. /* save this order */
  96936. for(j = 0; j <= i; j++)
  96937. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  96938. error[i] = err;
  96939. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  96940. if(err == 0.0) {
  96941. *max_order = i+1;
  96942. return;
  96943. }
  96944. }
  96945. }
  96946. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  96947. {
  96948. unsigned i;
  96949. FLAC__double cmax;
  96950. FLAC__int32 qmax, qmin;
  96951. FLAC__ASSERT(precision > 0);
  96952. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  96953. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  96954. precision--;
  96955. qmax = 1 << precision;
  96956. qmin = -qmax;
  96957. qmax--;
  96958. /* calc cmax = max( |lp_coeff[i]| ) */
  96959. cmax = 0.0;
  96960. for(i = 0; i < order; i++) {
  96961. const FLAC__double d = fabs(lp_coeff[i]);
  96962. if(d > cmax)
  96963. cmax = d;
  96964. }
  96965. if(cmax <= 0.0) {
  96966. /* => coefficients are all 0, which means our constant-detect didn't work */
  96967. return 2;
  96968. }
  96969. else {
  96970. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  96971. const int min_shiftlimit = -max_shiftlimit - 1;
  96972. int log2cmax;
  96973. (void)frexp(cmax, &log2cmax);
  96974. log2cmax--;
  96975. *shift = (int)precision - log2cmax - 1;
  96976. if(*shift > max_shiftlimit)
  96977. *shift = max_shiftlimit;
  96978. else if(*shift < min_shiftlimit)
  96979. return 1;
  96980. }
  96981. if(*shift >= 0) {
  96982. FLAC__double error = 0.0;
  96983. FLAC__int32 q;
  96984. for(i = 0; i < order; i++) {
  96985. error += lp_coeff[i] * (1 << *shift);
  96986. #if 1 /* unfortunately lround() is C99 */
  96987. if(error >= 0.0)
  96988. q = (FLAC__int32)(error + 0.5);
  96989. else
  96990. q = (FLAC__int32)(error - 0.5);
  96991. #else
  96992. q = lround(error);
  96993. #endif
  96994. #ifdef FLAC__OVERFLOW_DETECT
  96995. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  96996. 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]);
  96997. else if(q < qmin)
  96998. 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]);
  96999. #endif
  97000. if(q > qmax)
  97001. q = qmax;
  97002. else if(q < qmin)
  97003. q = qmin;
  97004. error -= q;
  97005. qlp_coeff[i] = q;
  97006. }
  97007. }
  97008. /* negative shift is very rare but due to design flaw, negative shift is
  97009. * a NOP in the decoder, so it must be handled specially by scaling down
  97010. * coeffs
  97011. */
  97012. else {
  97013. const int nshift = -(*shift);
  97014. FLAC__double error = 0.0;
  97015. FLAC__int32 q;
  97016. #ifdef DEBUG
  97017. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  97018. #endif
  97019. for(i = 0; i < order; i++) {
  97020. error += lp_coeff[i] / (1 << nshift);
  97021. #if 1 /* unfortunately lround() is C99 */
  97022. if(error >= 0.0)
  97023. q = (FLAC__int32)(error + 0.5);
  97024. else
  97025. q = (FLAC__int32)(error - 0.5);
  97026. #else
  97027. q = lround(error);
  97028. #endif
  97029. #ifdef FLAC__OVERFLOW_DETECT
  97030. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97031. 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]);
  97032. else if(q < qmin)
  97033. 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]);
  97034. #endif
  97035. if(q > qmax)
  97036. q = qmax;
  97037. else if(q < qmin)
  97038. q = qmin;
  97039. error -= q;
  97040. qlp_coeff[i] = q;
  97041. }
  97042. *shift = 0;
  97043. }
  97044. return 0;
  97045. }
  97046. 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[])
  97047. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97048. {
  97049. FLAC__int64 sumo;
  97050. unsigned i, j;
  97051. FLAC__int32 sum;
  97052. const FLAC__int32 *history;
  97053. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97054. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97055. for(i=0;i<order;i++)
  97056. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97057. fprintf(stderr,"\n");
  97058. #endif
  97059. FLAC__ASSERT(order > 0);
  97060. for(i = 0; i < data_len; i++) {
  97061. sumo = 0;
  97062. sum = 0;
  97063. history = data;
  97064. for(j = 0; j < order; j++) {
  97065. sum += qlp_coeff[j] * (*(--history));
  97066. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97067. #if defined _MSC_VER
  97068. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97069. 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);
  97070. #else
  97071. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97072. 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);
  97073. #endif
  97074. }
  97075. *(residual++) = *(data++) - (sum >> lp_quantization);
  97076. }
  97077. /* Here's a slower but clearer version:
  97078. for(i = 0; i < data_len; i++) {
  97079. sum = 0;
  97080. for(j = 0; j < order; j++)
  97081. sum += qlp_coeff[j] * data[i-j-1];
  97082. residual[i] = data[i] - (sum >> lp_quantization);
  97083. }
  97084. */
  97085. }
  97086. #else /* fully unrolled version for normal use */
  97087. {
  97088. int i;
  97089. FLAC__int32 sum;
  97090. FLAC__ASSERT(order > 0);
  97091. FLAC__ASSERT(order <= 32);
  97092. /*
  97093. * We do unique versions up to 12th order since that's the subset limit.
  97094. * Also they are roughly ordered to match frequency of occurrence to
  97095. * minimize branching.
  97096. */
  97097. if(order <= 12) {
  97098. if(order > 8) {
  97099. if(order > 10) {
  97100. if(order == 12) {
  97101. for(i = 0; i < (int)data_len; i++) {
  97102. sum = 0;
  97103. sum += qlp_coeff[11] * data[i-12];
  97104. sum += qlp_coeff[10] * data[i-11];
  97105. sum += qlp_coeff[9] * data[i-10];
  97106. sum += qlp_coeff[8] * data[i-9];
  97107. sum += qlp_coeff[7] * data[i-8];
  97108. sum += qlp_coeff[6] * data[i-7];
  97109. sum += qlp_coeff[5] * data[i-6];
  97110. sum += qlp_coeff[4] * data[i-5];
  97111. sum += qlp_coeff[3] * data[i-4];
  97112. sum += qlp_coeff[2] * data[i-3];
  97113. sum += qlp_coeff[1] * data[i-2];
  97114. sum += qlp_coeff[0] * data[i-1];
  97115. residual[i] = data[i] - (sum >> lp_quantization);
  97116. }
  97117. }
  97118. else { /* order == 11 */
  97119. for(i = 0; i < (int)data_len; i++) {
  97120. sum = 0;
  97121. sum += qlp_coeff[10] * data[i-11];
  97122. sum += qlp_coeff[9] * data[i-10];
  97123. sum += qlp_coeff[8] * data[i-9];
  97124. sum += qlp_coeff[7] * data[i-8];
  97125. sum += qlp_coeff[6] * data[i-7];
  97126. sum += qlp_coeff[5] * data[i-6];
  97127. sum += qlp_coeff[4] * data[i-5];
  97128. sum += qlp_coeff[3] * data[i-4];
  97129. sum += qlp_coeff[2] * data[i-3];
  97130. sum += qlp_coeff[1] * data[i-2];
  97131. sum += qlp_coeff[0] * data[i-1];
  97132. residual[i] = data[i] - (sum >> lp_quantization);
  97133. }
  97134. }
  97135. }
  97136. else {
  97137. if(order == 10) {
  97138. for(i = 0; i < (int)data_len; i++) {
  97139. sum = 0;
  97140. sum += qlp_coeff[9] * data[i-10];
  97141. sum += qlp_coeff[8] * data[i-9];
  97142. sum += qlp_coeff[7] * data[i-8];
  97143. sum += qlp_coeff[6] * data[i-7];
  97144. sum += qlp_coeff[5] * data[i-6];
  97145. sum += qlp_coeff[4] * data[i-5];
  97146. sum += qlp_coeff[3] * data[i-4];
  97147. sum += qlp_coeff[2] * data[i-3];
  97148. sum += qlp_coeff[1] * data[i-2];
  97149. sum += qlp_coeff[0] * data[i-1];
  97150. residual[i] = data[i] - (sum >> lp_quantization);
  97151. }
  97152. }
  97153. else { /* order == 9 */
  97154. for(i = 0; i < (int)data_len; i++) {
  97155. sum = 0;
  97156. sum += qlp_coeff[8] * data[i-9];
  97157. sum += qlp_coeff[7] * data[i-8];
  97158. sum += qlp_coeff[6] * data[i-7];
  97159. sum += qlp_coeff[5] * data[i-6];
  97160. sum += qlp_coeff[4] * data[i-5];
  97161. sum += qlp_coeff[3] * data[i-4];
  97162. sum += qlp_coeff[2] * data[i-3];
  97163. sum += qlp_coeff[1] * data[i-2];
  97164. sum += qlp_coeff[0] * data[i-1];
  97165. residual[i] = data[i] - (sum >> lp_quantization);
  97166. }
  97167. }
  97168. }
  97169. }
  97170. else if(order > 4) {
  97171. if(order > 6) {
  97172. if(order == 8) {
  97173. for(i = 0; i < (int)data_len; i++) {
  97174. sum = 0;
  97175. sum += qlp_coeff[7] * data[i-8];
  97176. sum += qlp_coeff[6] * data[i-7];
  97177. sum += qlp_coeff[5] * data[i-6];
  97178. sum += qlp_coeff[4] * data[i-5];
  97179. sum += qlp_coeff[3] * data[i-4];
  97180. sum += qlp_coeff[2] * data[i-3];
  97181. sum += qlp_coeff[1] * data[i-2];
  97182. sum += qlp_coeff[0] * data[i-1];
  97183. residual[i] = data[i] - (sum >> lp_quantization);
  97184. }
  97185. }
  97186. else { /* order == 7 */
  97187. for(i = 0; i < (int)data_len; i++) {
  97188. sum = 0;
  97189. sum += qlp_coeff[6] * data[i-7];
  97190. sum += qlp_coeff[5] * data[i-6];
  97191. sum += qlp_coeff[4] * data[i-5];
  97192. sum += qlp_coeff[3] * data[i-4];
  97193. sum += qlp_coeff[2] * data[i-3];
  97194. sum += qlp_coeff[1] * data[i-2];
  97195. sum += qlp_coeff[0] * data[i-1];
  97196. residual[i] = data[i] - (sum >> lp_quantization);
  97197. }
  97198. }
  97199. }
  97200. else {
  97201. if(order == 6) {
  97202. for(i = 0; i < (int)data_len; i++) {
  97203. sum = 0;
  97204. sum += qlp_coeff[5] * data[i-6];
  97205. sum += qlp_coeff[4] * data[i-5];
  97206. sum += qlp_coeff[3] * data[i-4];
  97207. sum += qlp_coeff[2] * data[i-3];
  97208. sum += qlp_coeff[1] * data[i-2];
  97209. sum += qlp_coeff[0] * data[i-1];
  97210. residual[i] = data[i] - (sum >> lp_quantization);
  97211. }
  97212. }
  97213. else { /* order == 5 */
  97214. for(i = 0; i < (int)data_len; i++) {
  97215. sum = 0;
  97216. sum += qlp_coeff[4] * data[i-5];
  97217. sum += qlp_coeff[3] * data[i-4];
  97218. sum += qlp_coeff[2] * data[i-3];
  97219. sum += qlp_coeff[1] * data[i-2];
  97220. sum += qlp_coeff[0] * data[i-1];
  97221. residual[i] = data[i] - (sum >> lp_quantization);
  97222. }
  97223. }
  97224. }
  97225. }
  97226. else {
  97227. if(order > 2) {
  97228. if(order == 4) {
  97229. for(i = 0; i < (int)data_len; i++) {
  97230. sum = 0;
  97231. sum += qlp_coeff[3] * data[i-4];
  97232. sum += qlp_coeff[2] * data[i-3];
  97233. sum += qlp_coeff[1] * data[i-2];
  97234. sum += qlp_coeff[0] * data[i-1];
  97235. residual[i] = data[i] - (sum >> lp_quantization);
  97236. }
  97237. }
  97238. else { /* order == 3 */
  97239. for(i = 0; i < (int)data_len; i++) {
  97240. sum = 0;
  97241. sum += qlp_coeff[2] * data[i-3];
  97242. sum += qlp_coeff[1] * data[i-2];
  97243. sum += qlp_coeff[0] * data[i-1];
  97244. residual[i] = data[i] - (sum >> lp_quantization);
  97245. }
  97246. }
  97247. }
  97248. else {
  97249. if(order == 2) {
  97250. for(i = 0; i < (int)data_len; i++) {
  97251. sum = 0;
  97252. sum += qlp_coeff[1] * data[i-2];
  97253. sum += qlp_coeff[0] * data[i-1];
  97254. residual[i] = data[i] - (sum >> lp_quantization);
  97255. }
  97256. }
  97257. else { /* order == 1 */
  97258. for(i = 0; i < (int)data_len; i++)
  97259. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97260. }
  97261. }
  97262. }
  97263. }
  97264. else { /* order > 12 */
  97265. for(i = 0; i < (int)data_len; i++) {
  97266. sum = 0;
  97267. switch(order) {
  97268. case 32: sum += qlp_coeff[31] * data[i-32];
  97269. case 31: sum += qlp_coeff[30] * data[i-31];
  97270. case 30: sum += qlp_coeff[29] * data[i-30];
  97271. case 29: sum += qlp_coeff[28] * data[i-29];
  97272. case 28: sum += qlp_coeff[27] * data[i-28];
  97273. case 27: sum += qlp_coeff[26] * data[i-27];
  97274. case 26: sum += qlp_coeff[25] * data[i-26];
  97275. case 25: sum += qlp_coeff[24] * data[i-25];
  97276. case 24: sum += qlp_coeff[23] * data[i-24];
  97277. case 23: sum += qlp_coeff[22] * data[i-23];
  97278. case 22: sum += qlp_coeff[21] * data[i-22];
  97279. case 21: sum += qlp_coeff[20] * data[i-21];
  97280. case 20: sum += qlp_coeff[19] * data[i-20];
  97281. case 19: sum += qlp_coeff[18] * data[i-19];
  97282. case 18: sum += qlp_coeff[17] * data[i-18];
  97283. case 17: sum += qlp_coeff[16] * data[i-17];
  97284. case 16: sum += qlp_coeff[15] * data[i-16];
  97285. case 15: sum += qlp_coeff[14] * data[i-15];
  97286. case 14: sum += qlp_coeff[13] * data[i-14];
  97287. case 13: sum += qlp_coeff[12] * data[i-13];
  97288. sum += qlp_coeff[11] * data[i-12];
  97289. sum += qlp_coeff[10] * data[i-11];
  97290. sum += qlp_coeff[ 9] * data[i-10];
  97291. sum += qlp_coeff[ 8] * data[i- 9];
  97292. sum += qlp_coeff[ 7] * data[i- 8];
  97293. sum += qlp_coeff[ 6] * data[i- 7];
  97294. sum += qlp_coeff[ 5] * data[i- 6];
  97295. sum += qlp_coeff[ 4] * data[i- 5];
  97296. sum += qlp_coeff[ 3] * data[i- 4];
  97297. sum += qlp_coeff[ 2] * data[i- 3];
  97298. sum += qlp_coeff[ 1] * data[i- 2];
  97299. sum += qlp_coeff[ 0] * data[i- 1];
  97300. }
  97301. residual[i] = data[i] - (sum >> lp_quantization);
  97302. }
  97303. }
  97304. }
  97305. #endif
  97306. 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[])
  97307. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97308. {
  97309. unsigned i, j;
  97310. FLAC__int64 sum;
  97311. const FLAC__int32 *history;
  97312. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97313. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97314. for(i=0;i<order;i++)
  97315. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97316. fprintf(stderr,"\n");
  97317. #endif
  97318. FLAC__ASSERT(order > 0);
  97319. for(i = 0; i < data_len; i++) {
  97320. sum = 0;
  97321. history = data;
  97322. for(j = 0; j < order; j++)
  97323. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97324. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97325. #if defined _MSC_VER
  97326. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97327. #else
  97328. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97329. #endif
  97330. break;
  97331. }
  97332. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97333. #if defined _MSC_VER
  97334. 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));
  97335. #else
  97336. 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)));
  97337. #endif
  97338. break;
  97339. }
  97340. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97341. }
  97342. }
  97343. #else /* fully unrolled version for normal use */
  97344. {
  97345. int i;
  97346. FLAC__int64 sum;
  97347. FLAC__ASSERT(order > 0);
  97348. FLAC__ASSERT(order <= 32);
  97349. /*
  97350. * We do unique versions up to 12th order since that's the subset limit.
  97351. * Also they are roughly ordered to match frequency of occurrence to
  97352. * minimize branching.
  97353. */
  97354. if(order <= 12) {
  97355. if(order > 8) {
  97356. if(order > 10) {
  97357. if(order == 12) {
  97358. for(i = 0; i < (int)data_len; i++) {
  97359. sum = 0;
  97360. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97361. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97362. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97363. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97364. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97365. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97366. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97367. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97368. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97369. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97370. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97371. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97372. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97373. }
  97374. }
  97375. else { /* order == 11 */
  97376. for(i = 0; i < (int)data_len; i++) {
  97377. sum = 0;
  97378. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97379. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97380. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97381. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97382. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97383. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97384. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97385. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97386. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97387. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97388. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97389. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97390. }
  97391. }
  97392. }
  97393. else {
  97394. if(order == 10) {
  97395. for(i = 0; i < (int)data_len; i++) {
  97396. sum = 0;
  97397. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97398. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97399. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97400. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97401. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97402. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97403. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97404. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97405. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97406. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97407. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97408. }
  97409. }
  97410. else { /* order == 9 */
  97411. for(i = 0; i < (int)data_len; i++) {
  97412. sum = 0;
  97413. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97414. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97415. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97416. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97417. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97418. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97419. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97420. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97421. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97422. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97423. }
  97424. }
  97425. }
  97426. }
  97427. else if(order > 4) {
  97428. if(order > 6) {
  97429. if(order == 8) {
  97430. for(i = 0; i < (int)data_len; i++) {
  97431. sum = 0;
  97432. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97433. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97434. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97435. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97436. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97437. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97438. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97439. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97440. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97441. }
  97442. }
  97443. else { /* order == 7 */
  97444. for(i = 0; i < (int)data_len; i++) {
  97445. sum = 0;
  97446. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97447. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97448. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97449. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97450. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97451. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97452. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97453. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97454. }
  97455. }
  97456. }
  97457. else {
  97458. if(order == 6) {
  97459. for(i = 0; i < (int)data_len; i++) {
  97460. sum = 0;
  97461. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97462. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97463. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97464. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97465. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97466. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97467. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97468. }
  97469. }
  97470. else { /* order == 5 */
  97471. for(i = 0; i < (int)data_len; i++) {
  97472. sum = 0;
  97473. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97474. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97475. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97476. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97477. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97478. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97479. }
  97480. }
  97481. }
  97482. }
  97483. else {
  97484. if(order > 2) {
  97485. if(order == 4) {
  97486. for(i = 0; i < (int)data_len; i++) {
  97487. sum = 0;
  97488. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97489. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97490. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97491. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97492. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97493. }
  97494. }
  97495. else { /* order == 3 */
  97496. for(i = 0; i < (int)data_len; i++) {
  97497. sum = 0;
  97498. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97499. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97500. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97501. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97502. }
  97503. }
  97504. }
  97505. else {
  97506. if(order == 2) {
  97507. for(i = 0; i < (int)data_len; i++) {
  97508. sum = 0;
  97509. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97510. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97511. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97512. }
  97513. }
  97514. else { /* order == 1 */
  97515. for(i = 0; i < (int)data_len; i++)
  97516. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97517. }
  97518. }
  97519. }
  97520. }
  97521. else { /* order > 12 */
  97522. for(i = 0; i < (int)data_len; i++) {
  97523. sum = 0;
  97524. switch(order) {
  97525. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97526. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97527. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97528. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97529. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97530. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97531. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97532. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97533. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97534. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97535. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97536. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97537. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97538. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97539. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97540. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97541. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97542. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97543. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97544. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97545. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97546. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97547. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97548. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97549. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97550. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97551. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97552. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97553. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97554. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97555. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97556. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97557. }
  97558. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97559. }
  97560. }
  97561. }
  97562. #endif
  97563. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97564. 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[])
  97565. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97566. {
  97567. FLAC__int64 sumo;
  97568. unsigned i, j;
  97569. FLAC__int32 sum;
  97570. const FLAC__int32 *r = residual, *history;
  97571. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97572. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97573. for(i=0;i<order;i++)
  97574. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97575. fprintf(stderr,"\n");
  97576. #endif
  97577. FLAC__ASSERT(order > 0);
  97578. for(i = 0; i < data_len; i++) {
  97579. sumo = 0;
  97580. sum = 0;
  97581. history = data;
  97582. for(j = 0; j < order; j++) {
  97583. sum += qlp_coeff[j] * (*(--history));
  97584. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97585. #if defined _MSC_VER
  97586. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97587. 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);
  97588. #else
  97589. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97590. 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);
  97591. #endif
  97592. }
  97593. *(data++) = *(r++) + (sum >> lp_quantization);
  97594. }
  97595. /* Here's a slower but clearer version:
  97596. for(i = 0; i < data_len; i++) {
  97597. sum = 0;
  97598. for(j = 0; j < order; j++)
  97599. sum += qlp_coeff[j] * data[i-j-1];
  97600. data[i] = residual[i] + (sum >> lp_quantization);
  97601. }
  97602. */
  97603. }
  97604. #else /* fully unrolled version for normal use */
  97605. {
  97606. int i;
  97607. FLAC__int32 sum;
  97608. FLAC__ASSERT(order > 0);
  97609. FLAC__ASSERT(order <= 32);
  97610. /*
  97611. * We do unique versions up to 12th order since that's the subset limit.
  97612. * Also they are roughly ordered to match frequency of occurrence to
  97613. * minimize branching.
  97614. */
  97615. if(order <= 12) {
  97616. if(order > 8) {
  97617. if(order > 10) {
  97618. if(order == 12) {
  97619. for(i = 0; i < (int)data_len; i++) {
  97620. sum = 0;
  97621. sum += qlp_coeff[11] * data[i-12];
  97622. sum += qlp_coeff[10] * data[i-11];
  97623. sum += qlp_coeff[9] * data[i-10];
  97624. sum += qlp_coeff[8] * data[i-9];
  97625. sum += qlp_coeff[7] * data[i-8];
  97626. sum += qlp_coeff[6] * data[i-7];
  97627. sum += qlp_coeff[5] * data[i-6];
  97628. sum += qlp_coeff[4] * data[i-5];
  97629. sum += qlp_coeff[3] * data[i-4];
  97630. sum += qlp_coeff[2] * data[i-3];
  97631. sum += qlp_coeff[1] * data[i-2];
  97632. sum += qlp_coeff[0] * data[i-1];
  97633. data[i] = residual[i] + (sum >> lp_quantization);
  97634. }
  97635. }
  97636. else { /* order == 11 */
  97637. for(i = 0; i < (int)data_len; i++) {
  97638. sum = 0;
  97639. sum += qlp_coeff[10] * data[i-11];
  97640. sum += qlp_coeff[9] * data[i-10];
  97641. sum += qlp_coeff[8] * data[i-9];
  97642. sum += qlp_coeff[7] * data[i-8];
  97643. sum += qlp_coeff[6] * data[i-7];
  97644. sum += qlp_coeff[5] * data[i-6];
  97645. sum += qlp_coeff[4] * data[i-5];
  97646. sum += qlp_coeff[3] * data[i-4];
  97647. sum += qlp_coeff[2] * data[i-3];
  97648. sum += qlp_coeff[1] * data[i-2];
  97649. sum += qlp_coeff[0] * data[i-1];
  97650. data[i] = residual[i] + (sum >> lp_quantization);
  97651. }
  97652. }
  97653. }
  97654. else {
  97655. if(order == 10) {
  97656. for(i = 0; i < (int)data_len; i++) {
  97657. sum = 0;
  97658. sum += qlp_coeff[9] * data[i-10];
  97659. sum += qlp_coeff[8] * data[i-9];
  97660. sum += qlp_coeff[7] * data[i-8];
  97661. sum += qlp_coeff[6] * data[i-7];
  97662. sum += qlp_coeff[5] * data[i-6];
  97663. sum += qlp_coeff[4] * data[i-5];
  97664. sum += qlp_coeff[3] * data[i-4];
  97665. sum += qlp_coeff[2] * data[i-3];
  97666. sum += qlp_coeff[1] * data[i-2];
  97667. sum += qlp_coeff[0] * data[i-1];
  97668. data[i] = residual[i] + (sum >> lp_quantization);
  97669. }
  97670. }
  97671. else { /* order == 9 */
  97672. for(i = 0; i < (int)data_len; i++) {
  97673. sum = 0;
  97674. sum += qlp_coeff[8] * data[i-9];
  97675. sum += qlp_coeff[7] * data[i-8];
  97676. sum += qlp_coeff[6] * data[i-7];
  97677. sum += qlp_coeff[5] * data[i-6];
  97678. sum += qlp_coeff[4] * data[i-5];
  97679. sum += qlp_coeff[3] * data[i-4];
  97680. sum += qlp_coeff[2] * data[i-3];
  97681. sum += qlp_coeff[1] * data[i-2];
  97682. sum += qlp_coeff[0] * data[i-1];
  97683. data[i] = residual[i] + (sum >> lp_quantization);
  97684. }
  97685. }
  97686. }
  97687. }
  97688. else if(order > 4) {
  97689. if(order > 6) {
  97690. if(order == 8) {
  97691. for(i = 0; i < (int)data_len; i++) {
  97692. sum = 0;
  97693. sum += qlp_coeff[7] * data[i-8];
  97694. sum += qlp_coeff[6] * data[i-7];
  97695. sum += qlp_coeff[5] * data[i-6];
  97696. sum += qlp_coeff[4] * data[i-5];
  97697. sum += qlp_coeff[3] * data[i-4];
  97698. sum += qlp_coeff[2] * data[i-3];
  97699. sum += qlp_coeff[1] * data[i-2];
  97700. sum += qlp_coeff[0] * data[i-1];
  97701. data[i] = residual[i] + (sum >> lp_quantization);
  97702. }
  97703. }
  97704. else { /* order == 7 */
  97705. for(i = 0; i < (int)data_len; i++) {
  97706. sum = 0;
  97707. sum += qlp_coeff[6] * data[i-7];
  97708. sum += qlp_coeff[5] * data[i-6];
  97709. sum += qlp_coeff[4] * data[i-5];
  97710. sum += qlp_coeff[3] * data[i-4];
  97711. sum += qlp_coeff[2] * data[i-3];
  97712. sum += qlp_coeff[1] * data[i-2];
  97713. sum += qlp_coeff[0] * data[i-1];
  97714. data[i] = residual[i] + (sum >> lp_quantization);
  97715. }
  97716. }
  97717. }
  97718. else {
  97719. if(order == 6) {
  97720. for(i = 0; i < (int)data_len; i++) {
  97721. sum = 0;
  97722. sum += qlp_coeff[5] * data[i-6];
  97723. sum += qlp_coeff[4] * data[i-5];
  97724. sum += qlp_coeff[3] * data[i-4];
  97725. sum += qlp_coeff[2] * data[i-3];
  97726. sum += qlp_coeff[1] * data[i-2];
  97727. sum += qlp_coeff[0] * data[i-1];
  97728. data[i] = residual[i] + (sum >> lp_quantization);
  97729. }
  97730. }
  97731. else { /* order == 5 */
  97732. for(i = 0; i < (int)data_len; i++) {
  97733. sum = 0;
  97734. sum += qlp_coeff[4] * data[i-5];
  97735. sum += qlp_coeff[3] * data[i-4];
  97736. sum += qlp_coeff[2] * data[i-3];
  97737. sum += qlp_coeff[1] * data[i-2];
  97738. sum += qlp_coeff[0] * data[i-1];
  97739. data[i] = residual[i] + (sum >> lp_quantization);
  97740. }
  97741. }
  97742. }
  97743. }
  97744. else {
  97745. if(order > 2) {
  97746. if(order == 4) {
  97747. for(i = 0; i < (int)data_len; i++) {
  97748. sum = 0;
  97749. sum += qlp_coeff[3] * data[i-4];
  97750. sum += qlp_coeff[2] * data[i-3];
  97751. sum += qlp_coeff[1] * data[i-2];
  97752. sum += qlp_coeff[0] * data[i-1];
  97753. data[i] = residual[i] + (sum >> lp_quantization);
  97754. }
  97755. }
  97756. else { /* order == 3 */
  97757. for(i = 0; i < (int)data_len; i++) {
  97758. sum = 0;
  97759. sum += qlp_coeff[2] * data[i-3];
  97760. sum += qlp_coeff[1] * data[i-2];
  97761. sum += qlp_coeff[0] * data[i-1];
  97762. data[i] = residual[i] + (sum >> lp_quantization);
  97763. }
  97764. }
  97765. }
  97766. else {
  97767. if(order == 2) {
  97768. for(i = 0; i < (int)data_len; i++) {
  97769. sum = 0;
  97770. sum += qlp_coeff[1] * data[i-2];
  97771. sum += qlp_coeff[0] * data[i-1];
  97772. data[i] = residual[i] + (sum >> lp_quantization);
  97773. }
  97774. }
  97775. else { /* order == 1 */
  97776. for(i = 0; i < (int)data_len; i++)
  97777. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97778. }
  97779. }
  97780. }
  97781. }
  97782. else { /* order > 12 */
  97783. for(i = 0; i < (int)data_len; i++) {
  97784. sum = 0;
  97785. switch(order) {
  97786. case 32: sum += qlp_coeff[31] * data[i-32];
  97787. case 31: sum += qlp_coeff[30] * data[i-31];
  97788. case 30: sum += qlp_coeff[29] * data[i-30];
  97789. case 29: sum += qlp_coeff[28] * data[i-29];
  97790. case 28: sum += qlp_coeff[27] * data[i-28];
  97791. case 27: sum += qlp_coeff[26] * data[i-27];
  97792. case 26: sum += qlp_coeff[25] * data[i-26];
  97793. case 25: sum += qlp_coeff[24] * data[i-25];
  97794. case 24: sum += qlp_coeff[23] * data[i-24];
  97795. case 23: sum += qlp_coeff[22] * data[i-23];
  97796. case 22: sum += qlp_coeff[21] * data[i-22];
  97797. case 21: sum += qlp_coeff[20] * data[i-21];
  97798. case 20: sum += qlp_coeff[19] * data[i-20];
  97799. case 19: sum += qlp_coeff[18] * data[i-19];
  97800. case 18: sum += qlp_coeff[17] * data[i-18];
  97801. case 17: sum += qlp_coeff[16] * data[i-17];
  97802. case 16: sum += qlp_coeff[15] * data[i-16];
  97803. case 15: sum += qlp_coeff[14] * data[i-15];
  97804. case 14: sum += qlp_coeff[13] * data[i-14];
  97805. case 13: sum += qlp_coeff[12] * data[i-13];
  97806. sum += qlp_coeff[11] * data[i-12];
  97807. sum += qlp_coeff[10] * data[i-11];
  97808. sum += qlp_coeff[ 9] * data[i-10];
  97809. sum += qlp_coeff[ 8] * data[i- 9];
  97810. sum += qlp_coeff[ 7] * data[i- 8];
  97811. sum += qlp_coeff[ 6] * data[i- 7];
  97812. sum += qlp_coeff[ 5] * data[i- 6];
  97813. sum += qlp_coeff[ 4] * data[i- 5];
  97814. sum += qlp_coeff[ 3] * data[i- 4];
  97815. sum += qlp_coeff[ 2] * data[i- 3];
  97816. sum += qlp_coeff[ 1] * data[i- 2];
  97817. sum += qlp_coeff[ 0] * data[i- 1];
  97818. }
  97819. data[i] = residual[i] + (sum >> lp_quantization);
  97820. }
  97821. }
  97822. }
  97823. #endif
  97824. 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[])
  97825. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97826. {
  97827. unsigned i, j;
  97828. FLAC__int64 sum;
  97829. const FLAC__int32 *r = residual, *history;
  97830. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97831. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97832. for(i=0;i<order;i++)
  97833. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97834. fprintf(stderr,"\n");
  97835. #endif
  97836. FLAC__ASSERT(order > 0);
  97837. for(i = 0; i < data_len; i++) {
  97838. sum = 0;
  97839. history = data;
  97840. for(j = 0; j < order; j++)
  97841. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97842. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97843. #ifdef _MSC_VER
  97844. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97845. #else
  97846. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97847. #endif
  97848. break;
  97849. }
  97850. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  97851. #ifdef _MSC_VER
  97852. 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));
  97853. #else
  97854. 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)));
  97855. #endif
  97856. break;
  97857. }
  97858. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  97859. }
  97860. }
  97861. #else /* fully unrolled version for normal use */
  97862. {
  97863. int i;
  97864. FLAC__int64 sum;
  97865. FLAC__ASSERT(order > 0);
  97866. FLAC__ASSERT(order <= 32);
  97867. /*
  97868. * We do unique versions up to 12th order since that's the subset limit.
  97869. * Also they are roughly ordered to match frequency of occurrence to
  97870. * minimize branching.
  97871. */
  97872. if(order <= 12) {
  97873. if(order > 8) {
  97874. if(order > 10) {
  97875. if(order == 12) {
  97876. for(i = 0; i < (int)data_len; i++) {
  97877. sum = 0;
  97878. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97879. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97880. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97881. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97882. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97883. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97884. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97885. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97886. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97887. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97888. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97889. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97890. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97891. }
  97892. }
  97893. else { /* order == 11 */
  97894. for(i = 0; i < (int)data_len; i++) {
  97895. sum = 0;
  97896. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97897. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97898. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97899. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97900. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97901. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97902. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97903. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97904. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97905. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97906. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97907. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97908. }
  97909. }
  97910. }
  97911. else {
  97912. if(order == 10) {
  97913. for(i = 0; i < (int)data_len; i++) {
  97914. sum = 0;
  97915. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97916. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97917. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97918. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97919. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97920. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97921. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97922. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97923. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97924. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97925. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97926. }
  97927. }
  97928. else { /* order == 9 */
  97929. for(i = 0; i < (int)data_len; i++) {
  97930. sum = 0;
  97931. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97932. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97933. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97934. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97935. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97936. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97937. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97938. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97939. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97940. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97941. }
  97942. }
  97943. }
  97944. }
  97945. else if(order > 4) {
  97946. if(order > 6) {
  97947. if(order == 8) {
  97948. for(i = 0; i < (int)data_len; i++) {
  97949. sum = 0;
  97950. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97951. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97952. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97953. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97954. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97955. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97956. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97957. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97958. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97959. }
  97960. }
  97961. else { /* order == 7 */
  97962. for(i = 0; i < (int)data_len; i++) {
  97963. sum = 0;
  97964. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97965. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97966. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97967. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97968. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97969. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97970. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97971. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97972. }
  97973. }
  97974. }
  97975. else {
  97976. if(order == 6) {
  97977. for(i = 0; i < (int)data_len; i++) {
  97978. sum = 0;
  97979. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97980. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97981. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97982. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97983. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97984. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97985. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97986. }
  97987. }
  97988. else { /* order == 5 */
  97989. for(i = 0; i < (int)data_len; i++) {
  97990. sum = 0;
  97991. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97992. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97993. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97994. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97995. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97996. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97997. }
  97998. }
  97999. }
  98000. }
  98001. else {
  98002. if(order > 2) {
  98003. if(order == 4) {
  98004. for(i = 0; i < (int)data_len; i++) {
  98005. sum = 0;
  98006. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98007. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98008. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98009. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98010. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98011. }
  98012. }
  98013. else { /* order == 3 */
  98014. for(i = 0; i < (int)data_len; i++) {
  98015. sum = 0;
  98016. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98017. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98018. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98019. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98020. }
  98021. }
  98022. }
  98023. else {
  98024. if(order == 2) {
  98025. for(i = 0; i < (int)data_len; i++) {
  98026. sum = 0;
  98027. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98028. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98029. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98030. }
  98031. }
  98032. else { /* order == 1 */
  98033. for(i = 0; i < (int)data_len; i++)
  98034. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98035. }
  98036. }
  98037. }
  98038. }
  98039. else { /* order > 12 */
  98040. for(i = 0; i < (int)data_len; i++) {
  98041. sum = 0;
  98042. switch(order) {
  98043. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98044. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98045. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98046. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98047. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98048. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98049. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98050. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98051. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98052. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98053. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98054. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98055. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98056. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98057. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98058. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98059. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98060. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98061. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98062. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98063. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98064. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98065. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98066. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98067. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98068. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98069. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98070. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98071. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98072. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98073. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98074. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98075. }
  98076. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98077. }
  98078. }
  98079. }
  98080. #endif
  98081. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98082. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98083. {
  98084. FLAC__double error_scale;
  98085. FLAC__ASSERT(total_samples > 0);
  98086. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98087. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98088. }
  98089. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98090. {
  98091. if(lpc_error > 0.0) {
  98092. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98093. if(bps >= 0.0)
  98094. return bps;
  98095. else
  98096. return 0.0;
  98097. }
  98098. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98099. return 1e32;
  98100. }
  98101. else {
  98102. return 0.0;
  98103. }
  98104. }
  98105. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98106. {
  98107. 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 */
  98108. FLAC__double bits, best_bits, error_scale;
  98109. FLAC__ASSERT(max_order > 0);
  98110. FLAC__ASSERT(total_samples > 0);
  98111. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98112. best_index = 0;
  98113. best_bits = (unsigned)(-1);
  98114. for(index = 0, order = 1; index < max_order; index++, order++) {
  98115. 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);
  98116. if(bits < best_bits) {
  98117. best_index = index;
  98118. best_bits = bits;
  98119. }
  98120. }
  98121. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98122. }
  98123. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98124. #endif
  98125. /*** End of inlined file: lpc_flac.c ***/
  98126. /*** Start of inlined file: md5.c ***/
  98127. /*** Start of inlined file: juce_FlacHeader.h ***/
  98128. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98129. // tasks..
  98130. #define VERSION "1.2.1"
  98131. #define FLAC__NO_DLL 1
  98132. #if JUCE_MSVC
  98133. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98134. #endif
  98135. #if JUCE_MAC
  98136. #define FLAC__SYS_DARWIN 1
  98137. #endif
  98138. /*** End of inlined file: juce_FlacHeader.h ***/
  98139. #if JUCE_USE_FLAC
  98140. #if HAVE_CONFIG_H
  98141. # include <config.h>
  98142. #endif
  98143. #include <stdlib.h> /* for malloc() */
  98144. #include <string.h> /* for memcpy() */
  98145. /*** Start of inlined file: md5.h ***/
  98146. #ifndef FLAC__PRIVATE__MD5_H
  98147. #define FLAC__PRIVATE__MD5_H
  98148. /*
  98149. * This is the header file for the MD5 message-digest algorithm.
  98150. * The algorithm is due to Ron Rivest. This code was
  98151. * written by Colin Plumb in 1993, no copyright is claimed.
  98152. * This code is in the public domain; do with it what you wish.
  98153. *
  98154. * Equivalent code is available from RSA Data Security, Inc.
  98155. * This code has been tested against that, and is equivalent,
  98156. * except that you don't need to include two pages of legalese
  98157. * with every copy.
  98158. *
  98159. * To compute the message digest of a chunk of bytes, declare an
  98160. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98161. * needed on buffers full of bytes, and then call MD5Final, which
  98162. * will fill a supplied 16-byte array with the digest.
  98163. *
  98164. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98165. * header definitions; now uses stuff from dpkg's config.h
  98166. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98167. * Still in the public domain.
  98168. *
  98169. * Josh Coalson: made some changes to integrate with libFLAC.
  98170. * Still in the public domain, with no warranty.
  98171. */
  98172. typedef struct {
  98173. FLAC__uint32 in[16];
  98174. FLAC__uint32 buf[4];
  98175. FLAC__uint32 bytes[2];
  98176. FLAC__byte *internal_buf;
  98177. size_t capacity;
  98178. } FLAC__MD5Context;
  98179. void FLAC__MD5Init(FLAC__MD5Context *context);
  98180. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98181. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98182. #endif
  98183. /*** End of inlined file: md5.h ***/
  98184. #ifndef FLaC__INLINE
  98185. #define FLaC__INLINE
  98186. #endif
  98187. /*
  98188. * This code implements the MD5 message-digest algorithm.
  98189. * The algorithm is due to Ron Rivest. This code was
  98190. * written by Colin Plumb in 1993, no copyright is claimed.
  98191. * This code is in the public domain; do with it what you wish.
  98192. *
  98193. * Equivalent code is available from RSA Data Security, Inc.
  98194. * This code has been tested against that, and is equivalent,
  98195. * except that you don't need to include two pages of legalese
  98196. * with every copy.
  98197. *
  98198. * To compute the message digest of a chunk of bytes, declare an
  98199. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98200. * needed on buffers full of bytes, and then call MD5Final, which
  98201. * will fill a supplied 16-byte array with the digest.
  98202. *
  98203. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98204. * definitions; now uses stuff from dpkg's config.h.
  98205. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98206. * Still in the public domain.
  98207. *
  98208. * Josh Coalson: made some changes to integrate with libFLAC.
  98209. * Still in the public domain.
  98210. */
  98211. /* The four core functions - F1 is optimized somewhat */
  98212. /* #define F1(x, y, z) (x & y | ~x & z) */
  98213. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98214. #define F2(x, y, z) F1(z, x, y)
  98215. #define F3(x, y, z) (x ^ y ^ z)
  98216. #define F4(x, y, z) (y ^ (x | ~z))
  98217. /* This is the central step in the MD5 algorithm. */
  98218. #define MD5STEP(f,w,x,y,z,in,s) \
  98219. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98220. /*
  98221. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98222. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98223. * the data and converts bytes into longwords for this routine.
  98224. */
  98225. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98226. {
  98227. register FLAC__uint32 a, b, c, d;
  98228. a = buf[0];
  98229. b = buf[1];
  98230. c = buf[2];
  98231. d = buf[3];
  98232. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98233. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98234. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98235. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98236. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98237. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98238. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98239. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98240. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98241. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98242. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98243. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98244. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98245. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98246. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98247. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98248. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98249. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98250. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98251. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98252. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98253. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98254. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98255. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98256. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98257. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98258. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98259. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98260. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98261. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98262. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98263. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98264. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98265. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98266. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98267. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98268. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98269. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98270. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98271. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98272. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98273. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98274. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98275. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98276. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98277. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98278. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98279. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98280. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98281. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98282. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98283. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98284. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98285. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98286. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98287. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98288. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98289. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98290. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98291. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98292. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98293. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98294. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98295. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98296. buf[0] += a;
  98297. buf[1] += b;
  98298. buf[2] += c;
  98299. buf[3] += d;
  98300. }
  98301. #if WORDS_BIGENDIAN
  98302. //@@@@@@ OPT: use bswap/intrinsics
  98303. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98304. {
  98305. register FLAC__uint32 x;
  98306. do {
  98307. x = *buf;
  98308. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98309. *buf++ = (x >> 16) | (x << 16);
  98310. } while (--words);
  98311. }
  98312. static void byteSwapX16(FLAC__uint32 *buf)
  98313. {
  98314. register FLAC__uint32 x;
  98315. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98316. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98317. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98318. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98319. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98320. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98321. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98322. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98323. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98324. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98325. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98326. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98327. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98328. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98329. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98330. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98331. }
  98332. #else
  98333. #define byteSwap(buf, words)
  98334. #define byteSwapX16(buf)
  98335. #endif
  98336. /*
  98337. * Update context to reflect the concatenation of another buffer full
  98338. * of bytes.
  98339. */
  98340. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98341. {
  98342. FLAC__uint32 t;
  98343. /* Update byte count */
  98344. t = ctx->bytes[0];
  98345. if ((ctx->bytes[0] = t + len) < t)
  98346. ctx->bytes[1]++; /* Carry from low to high */
  98347. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98348. if (t > len) {
  98349. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98350. return;
  98351. }
  98352. /* First chunk is an odd size */
  98353. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98354. byteSwapX16(ctx->in);
  98355. FLAC__MD5Transform(ctx->buf, ctx->in);
  98356. buf += t;
  98357. len -= t;
  98358. /* Process data in 64-byte chunks */
  98359. while (len >= 64) {
  98360. memcpy(ctx->in, buf, 64);
  98361. byteSwapX16(ctx->in);
  98362. FLAC__MD5Transform(ctx->buf, ctx->in);
  98363. buf += 64;
  98364. len -= 64;
  98365. }
  98366. /* Handle any remaining bytes of data. */
  98367. memcpy(ctx->in, buf, len);
  98368. }
  98369. /*
  98370. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98371. * initialization constants.
  98372. */
  98373. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98374. {
  98375. ctx->buf[0] = 0x67452301;
  98376. ctx->buf[1] = 0xefcdab89;
  98377. ctx->buf[2] = 0x98badcfe;
  98378. ctx->buf[3] = 0x10325476;
  98379. ctx->bytes[0] = 0;
  98380. ctx->bytes[1] = 0;
  98381. ctx->internal_buf = 0;
  98382. ctx->capacity = 0;
  98383. }
  98384. /*
  98385. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98386. * 1 0* (64-bit count of bits processed, MSB-first)
  98387. */
  98388. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98389. {
  98390. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98391. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98392. /* Set the first char of padding to 0x80. There is always room. */
  98393. *p++ = 0x80;
  98394. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98395. count = 56 - 1 - count;
  98396. if (count < 0) { /* Padding forces an extra block */
  98397. memset(p, 0, count + 8);
  98398. byteSwapX16(ctx->in);
  98399. FLAC__MD5Transform(ctx->buf, ctx->in);
  98400. p = (FLAC__byte *)ctx->in;
  98401. count = 56;
  98402. }
  98403. memset(p, 0, count);
  98404. byteSwap(ctx->in, 14);
  98405. /* Append length in bits and transform */
  98406. ctx->in[14] = ctx->bytes[0] << 3;
  98407. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98408. FLAC__MD5Transform(ctx->buf, ctx->in);
  98409. byteSwap(ctx->buf, 4);
  98410. memcpy(digest, ctx->buf, 16);
  98411. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98412. if(0 != ctx->internal_buf) {
  98413. free(ctx->internal_buf);
  98414. ctx->internal_buf = 0;
  98415. ctx->capacity = 0;
  98416. }
  98417. }
  98418. /*
  98419. * Convert the incoming audio signal to a byte stream
  98420. */
  98421. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98422. {
  98423. unsigned channel, sample;
  98424. register FLAC__int32 a_word;
  98425. register FLAC__byte *buf_ = buf;
  98426. #if WORDS_BIGENDIAN
  98427. #else
  98428. if(channels == 2 && bytes_per_sample == 2) {
  98429. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98430. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98431. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98432. *buf1_ = (FLAC__int16)signal[1][sample];
  98433. }
  98434. else if(channels == 1 && bytes_per_sample == 2) {
  98435. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98436. for(sample = 0; sample < samples; sample++)
  98437. *buf1_++ = (FLAC__int16)signal[0][sample];
  98438. }
  98439. else
  98440. #endif
  98441. if(bytes_per_sample == 2) {
  98442. if(channels == 2) {
  98443. for(sample = 0; sample < samples; sample++) {
  98444. a_word = signal[0][sample];
  98445. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98446. *buf_++ = (FLAC__byte)a_word;
  98447. a_word = signal[1][sample];
  98448. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98449. *buf_++ = (FLAC__byte)a_word;
  98450. }
  98451. }
  98452. else if(channels == 1) {
  98453. for(sample = 0; sample < samples; sample++) {
  98454. a_word = signal[0][sample];
  98455. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98456. *buf_++ = (FLAC__byte)a_word;
  98457. }
  98458. }
  98459. else {
  98460. for(sample = 0; sample < samples; sample++) {
  98461. for(channel = 0; channel < channels; channel++) {
  98462. a_word = signal[channel][sample];
  98463. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98464. *buf_++ = (FLAC__byte)a_word;
  98465. }
  98466. }
  98467. }
  98468. }
  98469. else if(bytes_per_sample == 3) {
  98470. if(channels == 2) {
  98471. for(sample = 0; sample < samples; sample++) {
  98472. a_word = signal[0][sample];
  98473. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98474. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98475. *buf_++ = (FLAC__byte)a_word;
  98476. a_word = signal[1][sample];
  98477. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98478. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98479. *buf_++ = (FLAC__byte)a_word;
  98480. }
  98481. }
  98482. else if(channels == 1) {
  98483. for(sample = 0; sample < samples; sample++) {
  98484. a_word = signal[0][sample];
  98485. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98486. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98487. *buf_++ = (FLAC__byte)a_word;
  98488. }
  98489. }
  98490. else {
  98491. for(sample = 0; sample < samples; sample++) {
  98492. for(channel = 0; channel < channels; channel++) {
  98493. a_word = signal[channel][sample];
  98494. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98495. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98496. *buf_++ = (FLAC__byte)a_word;
  98497. }
  98498. }
  98499. }
  98500. }
  98501. else if(bytes_per_sample == 1) {
  98502. if(channels == 2) {
  98503. for(sample = 0; sample < samples; sample++) {
  98504. a_word = signal[0][sample];
  98505. *buf_++ = (FLAC__byte)a_word;
  98506. a_word = signal[1][sample];
  98507. *buf_++ = (FLAC__byte)a_word;
  98508. }
  98509. }
  98510. else if(channels == 1) {
  98511. for(sample = 0; sample < samples; sample++) {
  98512. a_word = signal[0][sample];
  98513. *buf_++ = (FLAC__byte)a_word;
  98514. }
  98515. }
  98516. else {
  98517. for(sample = 0; sample < samples; sample++) {
  98518. for(channel = 0; channel < channels; channel++) {
  98519. a_word = signal[channel][sample];
  98520. *buf_++ = (FLAC__byte)a_word;
  98521. }
  98522. }
  98523. }
  98524. }
  98525. else { /* bytes_per_sample == 4, maybe optimize more later */
  98526. for(sample = 0; sample < samples; sample++) {
  98527. for(channel = 0; channel < channels; channel++) {
  98528. a_word = signal[channel][sample];
  98529. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98530. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98531. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98532. *buf_++ = (FLAC__byte)a_word;
  98533. }
  98534. }
  98535. }
  98536. }
  98537. /*
  98538. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  98539. */
  98540. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98541. {
  98542. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  98543. /* overflow check */
  98544. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  98545. return false;
  98546. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  98547. return false;
  98548. if(ctx->capacity < bytes_needed) {
  98549. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  98550. if(0 == tmp) {
  98551. free(ctx->internal_buf);
  98552. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  98553. return false;
  98554. }
  98555. ctx->internal_buf = tmp;
  98556. ctx->capacity = bytes_needed;
  98557. }
  98558. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  98559. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  98560. return true;
  98561. }
  98562. #endif
  98563. /*** End of inlined file: md5.c ***/
  98564. /*** Start of inlined file: memory.c ***/
  98565. /*** Start of inlined file: juce_FlacHeader.h ***/
  98566. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98567. // tasks..
  98568. #define VERSION "1.2.1"
  98569. #define FLAC__NO_DLL 1
  98570. #if JUCE_MSVC
  98571. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98572. #endif
  98573. #if JUCE_MAC
  98574. #define FLAC__SYS_DARWIN 1
  98575. #endif
  98576. /*** End of inlined file: juce_FlacHeader.h ***/
  98577. #if JUCE_USE_FLAC
  98578. #if HAVE_CONFIG_H
  98579. # include <config.h>
  98580. #endif
  98581. /*** Start of inlined file: memory.h ***/
  98582. #ifndef FLAC__PRIVATE__MEMORY_H
  98583. #define FLAC__PRIVATE__MEMORY_H
  98584. #ifdef HAVE_CONFIG_H
  98585. #include <config.h>
  98586. #endif
  98587. #include <stdlib.h> /* for size_t */
  98588. /* Returns the unaligned address returned by malloc.
  98589. * Use free() on this address to deallocate.
  98590. */
  98591. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  98592. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  98593. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  98594. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  98595. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  98596. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98597. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  98598. #endif
  98599. #endif
  98600. /*** End of inlined file: memory.h ***/
  98601. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  98602. {
  98603. void *x;
  98604. FLAC__ASSERT(0 != aligned_address);
  98605. #ifdef FLAC__ALIGN_MALLOC_DATA
  98606. /* align on 32-byte (256-bit) boundary */
  98607. x = safe_malloc_add_2op_(bytes, /*+*/31);
  98608. #ifdef SIZEOF_VOIDP
  98609. #if SIZEOF_VOIDP == 4
  98610. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  98611. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98612. #elif SIZEOF_VOIDP == 8
  98613. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98614. #else
  98615. # error Unsupported sizeof(void*)
  98616. #endif
  98617. #else
  98618. /* there's got to be a better way to do this right for all archs */
  98619. if(sizeof(void*) == sizeof(unsigned))
  98620. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98621. else if(sizeof(void*) == sizeof(FLAC__uint64))
  98622. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98623. else
  98624. return 0;
  98625. #endif
  98626. #else
  98627. x = safe_malloc_(bytes);
  98628. *aligned_address = x;
  98629. #endif
  98630. return x;
  98631. }
  98632. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  98633. {
  98634. FLAC__int32 *pu; /* unaligned pointer */
  98635. union { /* union needed to comply with C99 pointer aliasing rules */
  98636. FLAC__int32 *pa; /* aligned pointer */
  98637. void *pv; /* aligned pointer alias */
  98638. } u;
  98639. FLAC__ASSERT(elements > 0);
  98640. FLAC__ASSERT(0 != unaligned_pointer);
  98641. FLAC__ASSERT(0 != aligned_pointer);
  98642. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98643. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  98644. if(0 == pu) {
  98645. return false;
  98646. }
  98647. else {
  98648. if(*unaligned_pointer != 0)
  98649. free(*unaligned_pointer);
  98650. *unaligned_pointer = pu;
  98651. *aligned_pointer = u.pa;
  98652. return true;
  98653. }
  98654. }
  98655. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  98656. {
  98657. FLAC__uint32 *pu; /* unaligned pointer */
  98658. union { /* union needed to comply with C99 pointer aliasing rules */
  98659. FLAC__uint32 *pa; /* aligned pointer */
  98660. void *pv; /* aligned pointer alias */
  98661. } u;
  98662. FLAC__ASSERT(elements > 0);
  98663. FLAC__ASSERT(0 != unaligned_pointer);
  98664. FLAC__ASSERT(0 != aligned_pointer);
  98665. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98666. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98667. if(0 == pu) {
  98668. return false;
  98669. }
  98670. else {
  98671. if(*unaligned_pointer != 0)
  98672. free(*unaligned_pointer);
  98673. *unaligned_pointer = pu;
  98674. *aligned_pointer = u.pa;
  98675. return true;
  98676. }
  98677. }
  98678. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  98679. {
  98680. FLAC__uint64 *pu; /* unaligned pointer */
  98681. union { /* union needed to comply with C99 pointer aliasing rules */
  98682. FLAC__uint64 *pa; /* aligned pointer */
  98683. void *pv; /* aligned pointer alias */
  98684. } u;
  98685. FLAC__ASSERT(elements > 0);
  98686. FLAC__ASSERT(0 != unaligned_pointer);
  98687. FLAC__ASSERT(0 != aligned_pointer);
  98688. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98689. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98690. if(0 == pu) {
  98691. return false;
  98692. }
  98693. else {
  98694. if(*unaligned_pointer != 0)
  98695. free(*unaligned_pointer);
  98696. *unaligned_pointer = pu;
  98697. *aligned_pointer = u.pa;
  98698. return true;
  98699. }
  98700. }
  98701. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  98702. {
  98703. unsigned *pu; /* unaligned pointer */
  98704. union { /* union needed to comply with C99 pointer aliasing rules */
  98705. unsigned *pa; /* aligned pointer */
  98706. void *pv; /* aligned pointer alias */
  98707. } u;
  98708. FLAC__ASSERT(elements > 0);
  98709. FLAC__ASSERT(0 != unaligned_pointer);
  98710. FLAC__ASSERT(0 != aligned_pointer);
  98711. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98712. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98713. if(0 == pu) {
  98714. return false;
  98715. }
  98716. else {
  98717. if(*unaligned_pointer != 0)
  98718. free(*unaligned_pointer);
  98719. *unaligned_pointer = pu;
  98720. *aligned_pointer = u.pa;
  98721. return true;
  98722. }
  98723. }
  98724. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98725. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  98726. {
  98727. FLAC__real *pu; /* unaligned pointer */
  98728. union { /* union needed to comply with C99 pointer aliasing rules */
  98729. FLAC__real *pa; /* aligned pointer */
  98730. void *pv; /* aligned pointer alias */
  98731. } u;
  98732. FLAC__ASSERT(elements > 0);
  98733. FLAC__ASSERT(0 != unaligned_pointer);
  98734. FLAC__ASSERT(0 != aligned_pointer);
  98735. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98736. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98737. if(0 == pu) {
  98738. return false;
  98739. }
  98740. else {
  98741. if(*unaligned_pointer != 0)
  98742. free(*unaligned_pointer);
  98743. *unaligned_pointer = pu;
  98744. *aligned_pointer = u.pa;
  98745. return true;
  98746. }
  98747. }
  98748. #endif
  98749. #endif
  98750. /*** End of inlined file: memory.c ***/
  98751. /*** Start of inlined file: stream_decoder.c ***/
  98752. /*** Start of inlined file: juce_FlacHeader.h ***/
  98753. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98754. // tasks..
  98755. #define VERSION "1.2.1"
  98756. #define FLAC__NO_DLL 1
  98757. #if JUCE_MSVC
  98758. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98759. #endif
  98760. #if JUCE_MAC
  98761. #define FLAC__SYS_DARWIN 1
  98762. #endif
  98763. /*** End of inlined file: juce_FlacHeader.h ***/
  98764. #if JUCE_USE_FLAC
  98765. #if HAVE_CONFIG_H
  98766. # include <config.h>
  98767. #endif
  98768. #if defined _MSC_VER || defined __MINGW32__
  98769. #include <io.h> /* for _setmode() */
  98770. #include <fcntl.h> /* for _O_BINARY */
  98771. #endif
  98772. #if defined __CYGWIN__ || defined __EMX__
  98773. #include <io.h> /* for setmode(), O_BINARY */
  98774. #include <fcntl.h> /* for _O_BINARY */
  98775. #endif
  98776. #include <stdio.h>
  98777. #include <stdlib.h> /* for malloc() */
  98778. #include <string.h> /* for memset/memcpy() */
  98779. #include <sys/stat.h> /* for stat() */
  98780. #include <sys/types.h> /* for off_t */
  98781. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  98782. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  98783. #define fseeko fseek
  98784. #define ftello ftell
  98785. #endif
  98786. #endif
  98787. /*** Start of inlined file: stream_decoder.h ***/
  98788. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  98789. #define FLAC__PROTECTED__STREAM_DECODER_H
  98790. #if FLAC__HAS_OGG
  98791. #include "include/private/ogg_decoder_aspect.h"
  98792. #endif
  98793. typedef struct FLAC__StreamDecoderProtected {
  98794. FLAC__StreamDecoderState state;
  98795. unsigned channels;
  98796. FLAC__ChannelAssignment channel_assignment;
  98797. unsigned bits_per_sample;
  98798. unsigned sample_rate; /* in Hz */
  98799. unsigned blocksize; /* in samples (per channel) */
  98800. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  98801. #if FLAC__HAS_OGG
  98802. FLAC__OggDecoderAspect ogg_decoder_aspect;
  98803. #endif
  98804. } FLAC__StreamDecoderProtected;
  98805. /*
  98806. * return the number of input bytes consumed
  98807. */
  98808. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  98809. #endif
  98810. /*** End of inlined file: stream_decoder.h ***/
  98811. #ifdef max
  98812. #undef max
  98813. #endif
  98814. #define max(a,b) ((a)>(b)?(a):(b))
  98815. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  98816. #ifdef _MSC_VER
  98817. #define FLAC__U64L(x) x
  98818. #else
  98819. #define FLAC__U64L(x) x##LLU
  98820. #endif
  98821. /* technically this should be in an "export.c" but this is convenient enough */
  98822. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  98823. #if FLAC__HAS_OGG
  98824. 1
  98825. #else
  98826. 0
  98827. #endif
  98828. ;
  98829. /***********************************************************************
  98830. *
  98831. * Private static data
  98832. *
  98833. ***********************************************************************/
  98834. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  98835. /***********************************************************************
  98836. *
  98837. * Private class method prototypes
  98838. *
  98839. ***********************************************************************/
  98840. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  98841. static FILE *get_binary_stdin_(void);
  98842. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  98843. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  98844. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  98845. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  98846. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98847. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98848. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  98849. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  98850. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  98851. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  98852. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  98853. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  98854. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  98855. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98856. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98857. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98858. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98859. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98860. 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);
  98861. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  98862. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  98863. #if FLAC__HAS_OGG
  98864. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  98865. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98866. #endif
  98867. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  98868. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  98869. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98870. #if FLAC__HAS_OGG
  98871. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98872. #endif
  98873. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98874. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  98875. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  98876. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  98877. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  98878. /***********************************************************************
  98879. *
  98880. * Private class data
  98881. *
  98882. ***********************************************************************/
  98883. typedef struct FLAC__StreamDecoderPrivate {
  98884. #if FLAC__HAS_OGG
  98885. FLAC__bool is_ogg;
  98886. #endif
  98887. FLAC__StreamDecoderReadCallback read_callback;
  98888. FLAC__StreamDecoderSeekCallback seek_callback;
  98889. FLAC__StreamDecoderTellCallback tell_callback;
  98890. FLAC__StreamDecoderLengthCallback length_callback;
  98891. FLAC__StreamDecoderEofCallback eof_callback;
  98892. FLAC__StreamDecoderWriteCallback write_callback;
  98893. FLAC__StreamDecoderMetadataCallback metadata_callback;
  98894. FLAC__StreamDecoderErrorCallback error_callback;
  98895. /* generic 32-bit datapath: */
  98896. 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[]);
  98897. /* generic 64-bit datapath: */
  98898. 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[]);
  98899. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  98900. 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[]);
  98901. /* 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: */
  98902. 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[]);
  98903. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  98904. void *client_data;
  98905. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  98906. FLAC__BitReader *input;
  98907. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  98908. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  98909. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  98910. unsigned output_capacity, output_channels;
  98911. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  98912. FLAC__uint64 samples_decoded;
  98913. FLAC__bool has_stream_info, has_seek_table;
  98914. FLAC__StreamMetadata stream_info;
  98915. FLAC__StreamMetadata seek_table;
  98916. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  98917. FLAC__byte *metadata_filter_ids;
  98918. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  98919. FLAC__Frame frame;
  98920. FLAC__bool cached; /* true if there is a byte in lookahead */
  98921. FLAC__CPUInfo cpuinfo;
  98922. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  98923. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  98924. /* unaligned (original) pointers to allocated data */
  98925. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  98926. 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 */
  98927. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  98928. FLAC__bool is_seeking;
  98929. FLAC__MD5Context md5context;
  98930. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  98931. /* (the rest of these are only used for seeking) */
  98932. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  98933. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  98934. FLAC__uint64 target_sample;
  98935. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  98936. #if FLAC__HAS_OGG
  98937. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  98938. #endif
  98939. } FLAC__StreamDecoderPrivate;
  98940. /***********************************************************************
  98941. *
  98942. * Public static class data
  98943. *
  98944. ***********************************************************************/
  98945. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  98946. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  98947. "FLAC__STREAM_DECODER_READ_METADATA",
  98948. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  98949. "FLAC__STREAM_DECODER_READ_FRAME",
  98950. "FLAC__STREAM_DECODER_END_OF_STREAM",
  98951. "FLAC__STREAM_DECODER_OGG_ERROR",
  98952. "FLAC__STREAM_DECODER_SEEK_ERROR",
  98953. "FLAC__STREAM_DECODER_ABORTED",
  98954. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  98955. "FLAC__STREAM_DECODER_UNINITIALIZED"
  98956. };
  98957. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  98958. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  98959. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  98960. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  98961. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  98962. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  98963. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  98964. };
  98965. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  98966. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  98967. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  98968. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  98969. };
  98970. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  98971. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  98972. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  98973. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  98974. };
  98975. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  98976. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  98977. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  98978. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  98979. };
  98980. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  98981. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  98982. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  98983. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  98984. };
  98985. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  98986. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  98987. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  98988. };
  98989. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  98990. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  98991. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  98992. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  98993. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  98994. };
  98995. /***********************************************************************
  98996. *
  98997. * Class constructor/destructor
  98998. *
  98999. ***********************************************************************/
  99000. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  99001. {
  99002. FLAC__StreamDecoder *decoder;
  99003. unsigned i;
  99004. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99005. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  99006. if(decoder == 0) {
  99007. return 0;
  99008. }
  99009. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  99010. if(decoder->protected_ == 0) {
  99011. free(decoder);
  99012. return 0;
  99013. }
  99014. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  99015. if(decoder->private_ == 0) {
  99016. free(decoder->protected_);
  99017. free(decoder);
  99018. return 0;
  99019. }
  99020. decoder->private_->input = FLAC__bitreader_new();
  99021. if(decoder->private_->input == 0) {
  99022. free(decoder->private_);
  99023. free(decoder->protected_);
  99024. free(decoder);
  99025. return 0;
  99026. }
  99027. decoder->private_->metadata_filter_ids_capacity = 16;
  99028. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99029. FLAC__bitreader_delete(decoder->private_->input);
  99030. free(decoder->private_);
  99031. free(decoder->protected_);
  99032. free(decoder);
  99033. return 0;
  99034. }
  99035. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99036. decoder->private_->output[i] = 0;
  99037. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99038. }
  99039. decoder->private_->output_capacity = 0;
  99040. decoder->private_->output_channels = 0;
  99041. decoder->private_->has_seek_table = false;
  99042. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99043. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99044. decoder->private_->file = 0;
  99045. set_defaults_dec(decoder);
  99046. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99047. return decoder;
  99048. }
  99049. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99050. {
  99051. unsigned i;
  99052. FLAC__ASSERT(0 != decoder);
  99053. FLAC__ASSERT(0 != decoder->protected_);
  99054. FLAC__ASSERT(0 != decoder->private_);
  99055. FLAC__ASSERT(0 != decoder->private_->input);
  99056. (void)FLAC__stream_decoder_finish(decoder);
  99057. if(0 != decoder->private_->metadata_filter_ids)
  99058. free(decoder->private_->metadata_filter_ids);
  99059. FLAC__bitreader_delete(decoder->private_->input);
  99060. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99061. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99062. free(decoder->private_);
  99063. free(decoder->protected_);
  99064. free(decoder);
  99065. }
  99066. /***********************************************************************
  99067. *
  99068. * Public class methods
  99069. *
  99070. ***********************************************************************/
  99071. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99072. FLAC__StreamDecoder *decoder,
  99073. FLAC__StreamDecoderReadCallback read_callback,
  99074. FLAC__StreamDecoderSeekCallback seek_callback,
  99075. FLAC__StreamDecoderTellCallback tell_callback,
  99076. FLAC__StreamDecoderLengthCallback length_callback,
  99077. FLAC__StreamDecoderEofCallback eof_callback,
  99078. FLAC__StreamDecoderWriteCallback write_callback,
  99079. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99080. FLAC__StreamDecoderErrorCallback error_callback,
  99081. void *client_data,
  99082. FLAC__bool is_ogg
  99083. )
  99084. {
  99085. FLAC__ASSERT(0 != decoder);
  99086. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99087. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99088. #if !FLAC__HAS_OGG
  99089. if(is_ogg)
  99090. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99091. #endif
  99092. if(
  99093. 0 == read_callback ||
  99094. 0 == write_callback ||
  99095. 0 == error_callback ||
  99096. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99097. )
  99098. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99099. #if FLAC__HAS_OGG
  99100. decoder->private_->is_ogg = is_ogg;
  99101. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99102. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99103. #endif
  99104. /*
  99105. * get the CPU info and set the function pointers
  99106. */
  99107. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99108. /* first default to the non-asm routines */
  99109. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99110. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99111. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99112. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99113. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99114. /* now override with asm where appropriate */
  99115. #ifndef FLAC__NO_ASM
  99116. if(decoder->private_->cpuinfo.use_asm) {
  99117. #ifdef FLAC__CPU_IA32
  99118. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99119. #ifdef FLAC__HAS_NASM
  99120. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99121. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99122. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99123. #endif
  99124. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99125. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99126. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99127. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99128. }
  99129. else {
  99130. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99131. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99132. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99133. }
  99134. #endif
  99135. #elif defined FLAC__CPU_PPC
  99136. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99137. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99138. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99139. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99140. }
  99141. #endif
  99142. }
  99143. #endif
  99144. /* from here on, errors are fatal */
  99145. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99146. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99147. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99148. }
  99149. decoder->private_->read_callback = read_callback;
  99150. decoder->private_->seek_callback = seek_callback;
  99151. decoder->private_->tell_callback = tell_callback;
  99152. decoder->private_->length_callback = length_callback;
  99153. decoder->private_->eof_callback = eof_callback;
  99154. decoder->private_->write_callback = write_callback;
  99155. decoder->private_->metadata_callback = metadata_callback;
  99156. decoder->private_->error_callback = error_callback;
  99157. decoder->private_->client_data = client_data;
  99158. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99159. decoder->private_->samples_decoded = 0;
  99160. decoder->private_->has_stream_info = false;
  99161. decoder->private_->cached = false;
  99162. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99163. decoder->private_->is_seeking = false;
  99164. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99165. if(!FLAC__stream_decoder_reset(decoder)) {
  99166. /* above call sets the state for us */
  99167. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99168. }
  99169. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99170. }
  99171. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99172. FLAC__StreamDecoder *decoder,
  99173. FLAC__StreamDecoderReadCallback read_callback,
  99174. FLAC__StreamDecoderSeekCallback seek_callback,
  99175. FLAC__StreamDecoderTellCallback tell_callback,
  99176. FLAC__StreamDecoderLengthCallback length_callback,
  99177. FLAC__StreamDecoderEofCallback eof_callback,
  99178. FLAC__StreamDecoderWriteCallback write_callback,
  99179. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99180. FLAC__StreamDecoderErrorCallback error_callback,
  99181. void *client_data
  99182. )
  99183. {
  99184. return init_stream_internal_dec(
  99185. decoder,
  99186. read_callback,
  99187. seek_callback,
  99188. tell_callback,
  99189. length_callback,
  99190. eof_callback,
  99191. write_callback,
  99192. metadata_callback,
  99193. error_callback,
  99194. client_data,
  99195. /*is_ogg=*/false
  99196. );
  99197. }
  99198. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99199. FLAC__StreamDecoder *decoder,
  99200. FLAC__StreamDecoderReadCallback read_callback,
  99201. FLAC__StreamDecoderSeekCallback seek_callback,
  99202. FLAC__StreamDecoderTellCallback tell_callback,
  99203. FLAC__StreamDecoderLengthCallback length_callback,
  99204. FLAC__StreamDecoderEofCallback eof_callback,
  99205. FLAC__StreamDecoderWriteCallback write_callback,
  99206. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99207. FLAC__StreamDecoderErrorCallback error_callback,
  99208. void *client_data
  99209. )
  99210. {
  99211. return init_stream_internal_dec(
  99212. decoder,
  99213. read_callback,
  99214. seek_callback,
  99215. tell_callback,
  99216. length_callback,
  99217. eof_callback,
  99218. write_callback,
  99219. metadata_callback,
  99220. error_callback,
  99221. client_data,
  99222. /*is_ogg=*/true
  99223. );
  99224. }
  99225. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99226. FLAC__StreamDecoder *decoder,
  99227. FILE *file,
  99228. FLAC__StreamDecoderWriteCallback write_callback,
  99229. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99230. FLAC__StreamDecoderErrorCallback error_callback,
  99231. void *client_data,
  99232. FLAC__bool is_ogg
  99233. )
  99234. {
  99235. FLAC__ASSERT(0 != decoder);
  99236. FLAC__ASSERT(0 != file);
  99237. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99238. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99239. if(0 == write_callback || 0 == error_callback)
  99240. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99241. /*
  99242. * To make sure that our file does not go unclosed after an error, we
  99243. * must assign the FILE pointer before any further error can occur in
  99244. * this routine.
  99245. */
  99246. if(file == stdin)
  99247. file = get_binary_stdin_(); /* just to be safe */
  99248. decoder->private_->file = file;
  99249. return init_stream_internal_dec(
  99250. decoder,
  99251. file_read_callback_dec,
  99252. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99253. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99254. decoder->private_->file == stdin? 0: file_length_callback_,
  99255. file_eof_callback_,
  99256. write_callback,
  99257. metadata_callback,
  99258. error_callback,
  99259. client_data,
  99260. is_ogg
  99261. );
  99262. }
  99263. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99264. FLAC__StreamDecoder *decoder,
  99265. FILE *file,
  99266. FLAC__StreamDecoderWriteCallback write_callback,
  99267. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99268. FLAC__StreamDecoderErrorCallback error_callback,
  99269. void *client_data
  99270. )
  99271. {
  99272. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99273. }
  99274. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99275. FLAC__StreamDecoder *decoder,
  99276. FILE *file,
  99277. FLAC__StreamDecoderWriteCallback write_callback,
  99278. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99279. FLAC__StreamDecoderErrorCallback error_callback,
  99280. void *client_data
  99281. )
  99282. {
  99283. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99284. }
  99285. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99286. FLAC__StreamDecoder *decoder,
  99287. const char *filename,
  99288. FLAC__StreamDecoderWriteCallback write_callback,
  99289. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99290. FLAC__StreamDecoderErrorCallback error_callback,
  99291. void *client_data,
  99292. FLAC__bool is_ogg
  99293. )
  99294. {
  99295. FILE *file;
  99296. FLAC__ASSERT(0 != decoder);
  99297. /*
  99298. * To make sure that our file does not go unclosed after an error, we
  99299. * have to do the same entrance checks here that are later performed
  99300. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99301. */
  99302. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99303. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99304. if(0 == write_callback || 0 == error_callback)
  99305. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99306. file = filename? fopen(filename, "rb") : stdin;
  99307. if(0 == file)
  99308. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99309. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99310. }
  99311. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99312. FLAC__StreamDecoder *decoder,
  99313. const char *filename,
  99314. FLAC__StreamDecoderWriteCallback write_callback,
  99315. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99316. FLAC__StreamDecoderErrorCallback error_callback,
  99317. void *client_data
  99318. )
  99319. {
  99320. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99321. }
  99322. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99323. FLAC__StreamDecoder *decoder,
  99324. const char *filename,
  99325. FLAC__StreamDecoderWriteCallback write_callback,
  99326. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99327. FLAC__StreamDecoderErrorCallback error_callback,
  99328. void *client_data
  99329. )
  99330. {
  99331. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99332. }
  99333. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99334. {
  99335. FLAC__bool md5_failed = false;
  99336. unsigned i;
  99337. FLAC__ASSERT(0 != decoder);
  99338. FLAC__ASSERT(0 != decoder->private_);
  99339. FLAC__ASSERT(0 != decoder->protected_);
  99340. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99341. return true;
  99342. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99343. * always call FLAC__MD5Final()
  99344. */
  99345. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99346. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99347. free(decoder->private_->seek_table.data.seek_table.points);
  99348. decoder->private_->seek_table.data.seek_table.points = 0;
  99349. decoder->private_->has_seek_table = false;
  99350. }
  99351. FLAC__bitreader_free(decoder->private_->input);
  99352. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99353. /* WATCHOUT:
  99354. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99355. * output arrays have a buffer of up to 3 zeroes in front
  99356. * (at negative indices) for alignment purposes; we use 4
  99357. * to keep the data well-aligned.
  99358. */
  99359. if(0 != decoder->private_->output[i]) {
  99360. free(decoder->private_->output[i]-4);
  99361. decoder->private_->output[i] = 0;
  99362. }
  99363. if(0 != decoder->private_->residual_unaligned[i]) {
  99364. free(decoder->private_->residual_unaligned[i]);
  99365. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99366. }
  99367. }
  99368. decoder->private_->output_capacity = 0;
  99369. decoder->private_->output_channels = 0;
  99370. #if FLAC__HAS_OGG
  99371. if(decoder->private_->is_ogg)
  99372. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99373. #endif
  99374. if(0 != decoder->private_->file) {
  99375. if(decoder->private_->file != stdin)
  99376. fclose(decoder->private_->file);
  99377. decoder->private_->file = 0;
  99378. }
  99379. if(decoder->private_->do_md5_checking) {
  99380. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99381. md5_failed = true;
  99382. }
  99383. decoder->private_->is_seeking = false;
  99384. set_defaults_dec(decoder);
  99385. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99386. return !md5_failed;
  99387. }
  99388. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99389. {
  99390. FLAC__ASSERT(0 != decoder);
  99391. FLAC__ASSERT(0 != decoder->private_);
  99392. FLAC__ASSERT(0 != decoder->protected_);
  99393. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99394. return false;
  99395. #if FLAC__HAS_OGG
  99396. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99397. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99398. return true;
  99399. #else
  99400. (void)value;
  99401. return false;
  99402. #endif
  99403. }
  99404. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99405. {
  99406. FLAC__ASSERT(0 != decoder);
  99407. FLAC__ASSERT(0 != decoder->protected_);
  99408. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99409. return false;
  99410. decoder->protected_->md5_checking = value;
  99411. return true;
  99412. }
  99413. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99414. {
  99415. FLAC__ASSERT(0 != decoder);
  99416. FLAC__ASSERT(0 != decoder->private_);
  99417. FLAC__ASSERT(0 != decoder->protected_);
  99418. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99419. /* double protection */
  99420. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99421. return false;
  99422. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99423. return false;
  99424. decoder->private_->metadata_filter[type] = true;
  99425. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99426. decoder->private_->metadata_filter_ids_count = 0;
  99427. return true;
  99428. }
  99429. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99430. {
  99431. FLAC__ASSERT(0 != decoder);
  99432. FLAC__ASSERT(0 != decoder->private_);
  99433. FLAC__ASSERT(0 != decoder->protected_);
  99434. FLAC__ASSERT(0 != id);
  99435. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99436. return false;
  99437. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99438. return true;
  99439. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99440. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99441. 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))) {
  99442. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99443. return false;
  99444. }
  99445. decoder->private_->metadata_filter_ids_capacity *= 2;
  99446. }
  99447. 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));
  99448. decoder->private_->metadata_filter_ids_count++;
  99449. return true;
  99450. }
  99451. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99452. {
  99453. unsigned i;
  99454. FLAC__ASSERT(0 != decoder);
  99455. FLAC__ASSERT(0 != decoder->private_);
  99456. FLAC__ASSERT(0 != decoder->protected_);
  99457. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99458. return false;
  99459. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99460. decoder->private_->metadata_filter[i] = true;
  99461. decoder->private_->metadata_filter_ids_count = 0;
  99462. return true;
  99463. }
  99464. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99465. {
  99466. FLAC__ASSERT(0 != decoder);
  99467. FLAC__ASSERT(0 != decoder->private_);
  99468. FLAC__ASSERT(0 != decoder->protected_);
  99469. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99470. /* double protection */
  99471. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99472. return false;
  99473. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99474. return false;
  99475. decoder->private_->metadata_filter[type] = false;
  99476. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99477. decoder->private_->metadata_filter_ids_count = 0;
  99478. return true;
  99479. }
  99480. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99481. {
  99482. FLAC__ASSERT(0 != decoder);
  99483. FLAC__ASSERT(0 != decoder->private_);
  99484. FLAC__ASSERT(0 != decoder->protected_);
  99485. FLAC__ASSERT(0 != id);
  99486. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99487. return false;
  99488. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99489. return true;
  99490. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99491. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99492. 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))) {
  99493. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99494. return false;
  99495. }
  99496. decoder->private_->metadata_filter_ids_capacity *= 2;
  99497. }
  99498. 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));
  99499. decoder->private_->metadata_filter_ids_count++;
  99500. return true;
  99501. }
  99502. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  99503. {
  99504. FLAC__ASSERT(0 != decoder);
  99505. FLAC__ASSERT(0 != decoder->private_);
  99506. FLAC__ASSERT(0 != decoder->protected_);
  99507. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99508. return false;
  99509. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99510. decoder->private_->metadata_filter_ids_count = 0;
  99511. return true;
  99512. }
  99513. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  99514. {
  99515. FLAC__ASSERT(0 != decoder);
  99516. FLAC__ASSERT(0 != decoder->protected_);
  99517. return decoder->protected_->state;
  99518. }
  99519. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  99520. {
  99521. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  99522. }
  99523. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  99524. {
  99525. FLAC__ASSERT(0 != decoder);
  99526. FLAC__ASSERT(0 != decoder->protected_);
  99527. return decoder->protected_->md5_checking;
  99528. }
  99529. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  99530. {
  99531. FLAC__ASSERT(0 != decoder);
  99532. FLAC__ASSERT(0 != decoder->protected_);
  99533. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  99534. }
  99535. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  99536. {
  99537. FLAC__ASSERT(0 != decoder);
  99538. FLAC__ASSERT(0 != decoder->protected_);
  99539. return decoder->protected_->channels;
  99540. }
  99541. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  99542. {
  99543. FLAC__ASSERT(0 != decoder);
  99544. FLAC__ASSERT(0 != decoder->protected_);
  99545. return decoder->protected_->channel_assignment;
  99546. }
  99547. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  99548. {
  99549. FLAC__ASSERT(0 != decoder);
  99550. FLAC__ASSERT(0 != decoder->protected_);
  99551. return decoder->protected_->bits_per_sample;
  99552. }
  99553. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  99554. {
  99555. FLAC__ASSERT(0 != decoder);
  99556. FLAC__ASSERT(0 != decoder->protected_);
  99557. return decoder->protected_->sample_rate;
  99558. }
  99559. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  99560. {
  99561. FLAC__ASSERT(0 != decoder);
  99562. FLAC__ASSERT(0 != decoder->protected_);
  99563. return decoder->protected_->blocksize;
  99564. }
  99565. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  99566. {
  99567. FLAC__ASSERT(0 != decoder);
  99568. FLAC__ASSERT(0 != decoder->private_);
  99569. FLAC__ASSERT(0 != position);
  99570. #if FLAC__HAS_OGG
  99571. if(decoder->private_->is_ogg)
  99572. return false;
  99573. #endif
  99574. if(0 == decoder->private_->tell_callback)
  99575. return false;
  99576. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  99577. return false;
  99578. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  99579. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  99580. return false;
  99581. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  99582. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  99583. return true;
  99584. }
  99585. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  99586. {
  99587. FLAC__ASSERT(0 != decoder);
  99588. FLAC__ASSERT(0 != decoder->private_);
  99589. FLAC__ASSERT(0 != decoder->protected_);
  99590. decoder->private_->samples_decoded = 0;
  99591. decoder->private_->do_md5_checking = false;
  99592. #if FLAC__HAS_OGG
  99593. if(decoder->private_->is_ogg)
  99594. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  99595. #endif
  99596. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  99597. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99598. return false;
  99599. }
  99600. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99601. return true;
  99602. }
  99603. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  99604. {
  99605. FLAC__ASSERT(0 != decoder);
  99606. FLAC__ASSERT(0 != decoder->private_);
  99607. FLAC__ASSERT(0 != decoder->protected_);
  99608. if(!FLAC__stream_decoder_flush(decoder)) {
  99609. /* above call sets the state for us */
  99610. return false;
  99611. }
  99612. #if FLAC__HAS_OGG
  99613. /*@@@ could go in !internal_reset_hack block below */
  99614. if(decoder->private_->is_ogg)
  99615. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  99616. #endif
  99617. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  99618. * (internal_reset_hack) don't try to rewind since we are already at
  99619. * the beginning of the stream and don't want to fail if the input is
  99620. * not seekable.
  99621. */
  99622. if(!decoder->private_->internal_reset_hack) {
  99623. if(decoder->private_->file == stdin)
  99624. return false; /* can't rewind stdin, reset fails */
  99625. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  99626. return false; /* seekable and seek fails, reset fails */
  99627. }
  99628. else
  99629. decoder->private_->internal_reset_hack = false;
  99630. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  99631. decoder->private_->has_stream_info = false;
  99632. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99633. free(decoder->private_->seek_table.data.seek_table.points);
  99634. decoder->private_->seek_table.data.seek_table.points = 0;
  99635. decoder->private_->has_seek_table = false;
  99636. }
  99637. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99638. /*
  99639. * This goes in reset() and not flush() because according to the spec, a
  99640. * fixed-blocksize stream must stay that way through the whole stream.
  99641. */
  99642. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99643. /* We initialize the FLAC__MD5Context even though we may never use it. This
  99644. * is because md5 checking may be turned on to start and then turned off if
  99645. * a seek occurs. So we init the context here and finalize it in
  99646. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  99647. * properly.
  99648. */
  99649. FLAC__MD5Init(&decoder->private_->md5context);
  99650. decoder->private_->first_frame_offset = 0;
  99651. decoder->private_->unparseable_frame_count = 0;
  99652. return true;
  99653. }
  99654. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  99655. {
  99656. FLAC__bool got_a_frame;
  99657. FLAC__ASSERT(0 != decoder);
  99658. FLAC__ASSERT(0 != decoder->protected_);
  99659. while(1) {
  99660. switch(decoder->protected_->state) {
  99661. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99662. if(!find_metadata_(decoder))
  99663. return false; /* above function sets the status for us */
  99664. break;
  99665. case FLAC__STREAM_DECODER_READ_METADATA:
  99666. if(!read_metadata_(decoder))
  99667. return false; /* above function sets the status for us */
  99668. else
  99669. return true;
  99670. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99671. if(!frame_sync_(decoder))
  99672. return true; /* above function sets the status for us */
  99673. break;
  99674. case FLAC__STREAM_DECODER_READ_FRAME:
  99675. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  99676. return false; /* above function sets the status for us */
  99677. if(got_a_frame)
  99678. return true; /* above function sets the status for us */
  99679. break;
  99680. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99681. case FLAC__STREAM_DECODER_ABORTED:
  99682. return true;
  99683. default:
  99684. FLAC__ASSERT(0);
  99685. return false;
  99686. }
  99687. }
  99688. }
  99689. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  99690. {
  99691. FLAC__ASSERT(0 != decoder);
  99692. FLAC__ASSERT(0 != decoder->protected_);
  99693. while(1) {
  99694. switch(decoder->protected_->state) {
  99695. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99696. if(!find_metadata_(decoder))
  99697. return false; /* above function sets the status for us */
  99698. break;
  99699. case FLAC__STREAM_DECODER_READ_METADATA:
  99700. if(!read_metadata_(decoder))
  99701. return false; /* above function sets the status for us */
  99702. break;
  99703. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99704. case FLAC__STREAM_DECODER_READ_FRAME:
  99705. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99706. case FLAC__STREAM_DECODER_ABORTED:
  99707. return true;
  99708. default:
  99709. FLAC__ASSERT(0);
  99710. return false;
  99711. }
  99712. }
  99713. }
  99714. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  99715. {
  99716. FLAC__bool dummy;
  99717. FLAC__ASSERT(0 != decoder);
  99718. FLAC__ASSERT(0 != decoder->protected_);
  99719. while(1) {
  99720. switch(decoder->protected_->state) {
  99721. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99722. if(!find_metadata_(decoder))
  99723. return false; /* above function sets the status for us */
  99724. break;
  99725. case FLAC__STREAM_DECODER_READ_METADATA:
  99726. if(!read_metadata_(decoder))
  99727. return false; /* above function sets the status for us */
  99728. break;
  99729. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99730. if(!frame_sync_(decoder))
  99731. return true; /* above function sets the status for us */
  99732. break;
  99733. case FLAC__STREAM_DECODER_READ_FRAME:
  99734. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  99735. return false; /* above function sets the status for us */
  99736. break;
  99737. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99738. case FLAC__STREAM_DECODER_ABORTED:
  99739. return true;
  99740. default:
  99741. FLAC__ASSERT(0);
  99742. return false;
  99743. }
  99744. }
  99745. }
  99746. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  99747. {
  99748. FLAC__bool got_a_frame;
  99749. FLAC__ASSERT(0 != decoder);
  99750. FLAC__ASSERT(0 != decoder->protected_);
  99751. while(1) {
  99752. switch(decoder->protected_->state) {
  99753. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99754. case FLAC__STREAM_DECODER_READ_METADATA:
  99755. return false; /* above function sets the status for us */
  99756. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99757. if(!frame_sync_(decoder))
  99758. return true; /* above function sets the status for us */
  99759. break;
  99760. case FLAC__STREAM_DECODER_READ_FRAME:
  99761. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  99762. return false; /* above function sets the status for us */
  99763. if(got_a_frame)
  99764. return true; /* above function sets the status for us */
  99765. break;
  99766. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99767. case FLAC__STREAM_DECODER_ABORTED:
  99768. return true;
  99769. default:
  99770. FLAC__ASSERT(0);
  99771. return false;
  99772. }
  99773. }
  99774. }
  99775. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  99776. {
  99777. FLAC__uint64 length;
  99778. FLAC__ASSERT(0 != decoder);
  99779. if(
  99780. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  99781. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  99782. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  99783. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  99784. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  99785. )
  99786. return false;
  99787. if(0 == decoder->private_->seek_callback)
  99788. return false;
  99789. FLAC__ASSERT(decoder->private_->seek_callback);
  99790. FLAC__ASSERT(decoder->private_->tell_callback);
  99791. FLAC__ASSERT(decoder->private_->length_callback);
  99792. FLAC__ASSERT(decoder->private_->eof_callback);
  99793. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  99794. return false;
  99795. decoder->private_->is_seeking = true;
  99796. /* turn off md5 checking if a seek is attempted */
  99797. decoder->private_->do_md5_checking = false;
  99798. /* 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) */
  99799. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  99800. decoder->private_->is_seeking = false;
  99801. return false;
  99802. }
  99803. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  99804. if(
  99805. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  99806. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  99807. ) {
  99808. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  99809. /* above call sets the state for us */
  99810. decoder->private_->is_seeking = false;
  99811. return false;
  99812. }
  99813. /* check this again in case we didn't know total_samples the first time */
  99814. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  99815. decoder->private_->is_seeking = false;
  99816. return false;
  99817. }
  99818. }
  99819. {
  99820. const FLAC__bool ok =
  99821. #if FLAC__HAS_OGG
  99822. decoder->private_->is_ogg?
  99823. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  99824. #endif
  99825. seek_to_absolute_sample_(decoder, length, sample)
  99826. ;
  99827. decoder->private_->is_seeking = false;
  99828. return ok;
  99829. }
  99830. }
  99831. /***********************************************************************
  99832. *
  99833. * Protected class methods
  99834. *
  99835. ***********************************************************************/
  99836. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  99837. {
  99838. FLAC__ASSERT(0 != decoder);
  99839. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99840. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  99841. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  99842. }
  99843. /***********************************************************************
  99844. *
  99845. * Private class methods
  99846. *
  99847. ***********************************************************************/
  99848. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  99849. {
  99850. #if FLAC__HAS_OGG
  99851. decoder->private_->is_ogg = false;
  99852. #endif
  99853. decoder->private_->read_callback = 0;
  99854. decoder->private_->seek_callback = 0;
  99855. decoder->private_->tell_callback = 0;
  99856. decoder->private_->length_callback = 0;
  99857. decoder->private_->eof_callback = 0;
  99858. decoder->private_->write_callback = 0;
  99859. decoder->private_->metadata_callback = 0;
  99860. decoder->private_->error_callback = 0;
  99861. decoder->private_->client_data = 0;
  99862. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99863. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  99864. decoder->private_->metadata_filter_ids_count = 0;
  99865. decoder->protected_->md5_checking = false;
  99866. #if FLAC__HAS_OGG
  99867. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  99868. #endif
  99869. }
  99870. /*
  99871. * This will forcibly set stdin to binary mode (for OSes that require it)
  99872. */
  99873. FILE *get_binary_stdin_(void)
  99874. {
  99875. /* if something breaks here it is probably due to the presence or
  99876. * absence of an underscore before the identifiers 'setmode',
  99877. * 'fileno', and/or 'O_BINARY'; check your system header files.
  99878. */
  99879. #if defined _MSC_VER || defined __MINGW32__
  99880. _setmode(_fileno(stdin), _O_BINARY);
  99881. #elif defined __CYGWIN__
  99882. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  99883. setmode(_fileno(stdin), _O_BINARY);
  99884. #elif defined __EMX__
  99885. setmode(fileno(stdin), O_BINARY);
  99886. #endif
  99887. return stdin;
  99888. }
  99889. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  99890. {
  99891. unsigned i;
  99892. FLAC__int32 *tmp;
  99893. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  99894. return true;
  99895. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  99896. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99897. if(0 != decoder->private_->output[i]) {
  99898. free(decoder->private_->output[i]-4);
  99899. decoder->private_->output[i] = 0;
  99900. }
  99901. if(0 != decoder->private_->residual_unaligned[i]) {
  99902. free(decoder->private_->residual_unaligned[i]);
  99903. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99904. }
  99905. }
  99906. for(i = 0; i < channels; i++) {
  99907. /* WATCHOUT:
  99908. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99909. * output arrays have a buffer of up to 3 zeroes in front
  99910. * (at negative indices) for alignment purposes; we use 4
  99911. * to keep the data well-aligned.
  99912. */
  99913. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  99914. if(tmp == 0) {
  99915. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99916. return false;
  99917. }
  99918. memset(tmp, 0, sizeof(FLAC__int32)*4);
  99919. decoder->private_->output[i] = tmp + 4;
  99920. /* WATCHOUT:
  99921. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  99922. */
  99923. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  99924. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99925. return false;
  99926. }
  99927. }
  99928. decoder->private_->output_capacity = size;
  99929. decoder->private_->output_channels = channels;
  99930. return true;
  99931. }
  99932. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  99933. {
  99934. size_t i;
  99935. FLAC__ASSERT(0 != decoder);
  99936. FLAC__ASSERT(0 != decoder->private_);
  99937. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  99938. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  99939. return true;
  99940. return false;
  99941. }
  99942. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  99943. {
  99944. FLAC__uint32 x;
  99945. unsigned i, id_;
  99946. FLAC__bool first = true;
  99947. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99948. for(i = id_ = 0; i < 4; ) {
  99949. if(decoder->private_->cached) {
  99950. x = (FLAC__uint32)decoder->private_->lookahead;
  99951. decoder->private_->cached = false;
  99952. }
  99953. else {
  99954. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99955. return false; /* read_callback_ sets the state for us */
  99956. }
  99957. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  99958. first = true;
  99959. i++;
  99960. id_ = 0;
  99961. continue;
  99962. }
  99963. if(x == ID3V2_TAG_[id_]) {
  99964. id_++;
  99965. i = 0;
  99966. if(id_ == 3) {
  99967. if(!skip_id3v2_tag_(decoder))
  99968. return false; /* skip_id3v2_tag_ sets the state for us */
  99969. }
  99970. continue;
  99971. }
  99972. id_ = 0;
  99973. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99974. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  99975. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99976. return false; /* read_callback_ sets the state for us */
  99977. /* 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 */
  99978. /* else we have to check if the second byte is the end of a sync code */
  99979. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99980. decoder->private_->lookahead = (FLAC__byte)x;
  99981. decoder->private_->cached = true;
  99982. }
  99983. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  99984. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  99985. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  99986. return true;
  99987. }
  99988. }
  99989. i = 0;
  99990. if(first) {
  99991. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  99992. first = false;
  99993. }
  99994. }
  99995. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  99996. return true;
  99997. }
  99998. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  99999. {
  100000. FLAC__bool is_last;
  100001. FLAC__uint32 i, x, type, length;
  100002. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100003. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100004. return false; /* read_callback_ sets the state for us */
  100005. is_last = x? true : false;
  100006. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  100007. return false; /* read_callback_ sets the state for us */
  100008. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  100009. return false; /* read_callback_ sets the state for us */
  100010. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  100011. if(!read_metadata_streaminfo_(decoder, is_last, length))
  100012. return false;
  100013. decoder->private_->has_stream_info = true;
  100014. 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))
  100015. decoder->private_->do_md5_checking = false;
  100016. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  100017. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  100018. }
  100019. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100020. if(!read_metadata_seektable_(decoder, is_last, length))
  100021. return false;
  100022. decoder->private_->has_seek_table = true;
  100023. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100024. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100025. }
  100026. else {
  100027. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100028. unsigned real_length = length;
  100029. FLAC__StreamMetadata block;
  100030. block.is_last = is_last;
  100031. block.type = (FLAC__MetadataType)type;
  100032. block.length = length;
  100033. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100034. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100035. return false; /* read_callback_ sets the state for us */
  100036. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100037. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100038. return false;
  100039. }
  100040. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100041. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100042. skip_it = !skip_it;
  100043. }
  100044. if(skip_it) {
  100045. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100046. return false; /* read_callback_ sets the state for us */
  100047. }
  100048. else {
  100049. switch(type) {
  100050. case FLAC__METADATA_TYPE_PADDING:
  100051. /* skip the padding bytes */
  100052. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100053. return false; /* read_callback_ sets the state for us */
  100054. break;
  100055. case FLAC__METADATA_TYPE_APPLICATION:
  100056. /* remember, we read the ID already */
  100057. if(real_length > 0) {
  100058. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100059. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100060. return false;
  100061. }
  100062. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100063. return false; /* read_callback_ sets the state for us */
  100064. }
  100065. else
  100066. block.data.application.data = 0;
  100067. break;
  100068. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100069. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100070. return false;
  100071. break;
  100072. case FLAC__METADATA_TYPE_CUESHEET:
  100073. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100074. return false;
  100075. break;
  100076. case FLAC__METADATA_TYPE_PICTURE:
  100077. if(!read_metadata_picture_(decoder, &block.data.picture))
  100078. return false;
  100079. break;
  100080. case FLAC__METADATA_TYPE_STREAMINFO:
  100081. case FLAC__METADATA_TYPE_SEEKTABLE:
  100082. FLAC__ASSERT(0);
  100083. break;
  100084. default:
  100085. if(real_length > 0) {
  100086. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100087. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100088. return false;
  100089. }
  100090. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100091. return false; /* read_callback_ sets the state for us */
  100092. }
  100093. else
  100094. block.data.unknown.data = 0;
  100095. break;
  100096. }
  100097. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100098. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100099. /* now we have to free any malloc()ed data in the block */
  100100. switch(type) {
  100101. case FLAC__METADATA_TYPE_PADDING:
  100102. break;
  100103. case FLAC__METADATA_TYPE_APPLICATION:
  100104. if(0 != block.data.application.data)
  100105. free(block.data.application.data);
  100106. break;
  100107. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100108. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100109. free(block.data.vorbis_comment.vendor_string.entry);
  100110. if(block.data.vorbis_comment.num_comments > 0)
  100111. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100112. if(0 != block.data.vorbis_comment.comments[i].entry)
  100113. free(block.data.vorbis_comment.comments[i].entry);
  100114. if(0 != block.data.vorbis_comment.comments)
  100115. free(block.data.vorbis_comment.comments);
  100116. break;
  100117. case FLAC__METADATA_TYPE_CUESHEET:
  100118. if(block.data.cue_sheet.num_tracks > 0)
  100119. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100120. if(0 != block.data.cue_sheet.tracks[i].indices)
  100121. free(block.data.cue_sheet.tracks[i].indices);
  100122. if(0 != block.data.cue_sheet.tracks)
  100123. free(block.data.cue_sheet.tracks);
  100124. break;
  100125. case FLAC__METADATA_TYPE_PICTURE:
  100126. if(0 != block.data.picture.mime_type)
  100127. free(block.data.picture.mime_type);
  100128. if(0 != block.data.picture.description)
  100129. free(block.data.picture.description);
  100130. if(0 != block.data.picture.data)
  100131. free(block.data.picture.data);
  100132. break;
  100133. case FLAC__METADATA_TYPE_STREAMINFO:
  100134. case FLAC__METADATA_TYPE_SEEKTABLE:
  100135. FLAC__ASSERT(0);
  100136. default:
  100137. if(0 != block.data.unknown.data)
  100138. free(block.data.unknown.data);
  100139. break;
  100140. }
  100141. }
  100142. }
  100143. if(is_last) {
  100144. /* if this fails, it's OK, it's just a hint for the seek routine */
  100145. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100146. decoder->private_->first_frame_offset = 0;
  100147. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100148. }
  100149. return true;
  100150. }
  100151. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100152. {
  100153. FLAC__uint32 x;
  100154. unsigned bits, used_bits = 0;
  100155. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100156. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100157. decoder->private_->stream_info.is_last = is_last;
  100158. decoder->private_->stream_info.length = length;
  100159. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100160. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100161. return false; /* read_callback_ sets the state for us */
  100162. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100163. used_bits += bits;
  100164. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100165. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100166. return false; /* read_callback_ sets the state for us */
  100167. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100168. used_bits += bits;
  100169. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100170. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100171. return false; /* read_callback_ sets the state for us */
  100172. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100173. used_bits += bits;
  100174. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100175. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100176. return false; /* read_callback_ sets the state for us */
  100177. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100178. used_bits += bits;
  100179. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100180. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100181. return false; /* read_callback_ sets the state for us */
  100182. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100183. used_bits += bits;
  100184. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100185. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100186. return false; /* read_callback_ sets the state for us */
  100187. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100188. used_bits += bits;
  100189. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100190. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100191. return false; /* read_callback_ sets the state for us */
  100192. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100193. used_bits += bits;
  100194. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100195. 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))
  100196. return false; /* read_callback_ sets the state for us */
  100197. used_bits += bits;
  100198. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100199. return false; /* read_callback_ sets the state for us */
  100200. used_bits += 16*8;
  100201. /* skip the rest of the block */
  100202. FLAC__ASSERT(used_bits % 8 == 0);
  100203. length -= (used_bits / 8);
  100204. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100205. return false; /* read_callback_ sets the state for us */
  100206. return true;
  100207. }
  100208. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100209. {
  100210. FLAC__uint32 i, x;
  100211. FLAC__uint64 xx;
  100212. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100213. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100214. decoder->private_->seek_table.is_last = is_last;
  100215. decoder->private_->seek_table.length = length;
  100216. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100217. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100218. 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)))) {
  100219. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100220. return false;
  100221. }
  100222. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100223. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100224. return false; /* read_callback_ sets the state for us */
  100225. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100226. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100227. return false; /* read_callback_ sets the state for us */
  100228. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100229. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100230. return false; /* read_callback_ sets the state for us */
  100231. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100232. }
  100233. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100234. /* if there is a partial point left, skip over it */
  100235. if(length > 0) {
  100236. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100237. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100238. return false; /* read_callback_ sets the state for us */
  100239. }
  100240. return true;
  100241. }
  100242. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100243. {
  100244. FLAC__uint32 i;
  100245. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100246. /* read vendor string */
  100247. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100248. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100249. return false; /* read_callback_ sets the state for us */
  100250. if(obj->vendor_string.length > 0) {
  100251. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100252. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100253. return false;
  100254. }
  100255. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100256. return false; /* read_callback_ sets the state for us */
  100257. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100258. }
  100259. else
  100260. obj->vendor_string.entry = 0;
  100261. /* read num comments */
  100262. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100263. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100264. return false; /* read_callback_ sets the state for us */
  100265. /* read comments */
  100266. if(obj->num_comments > 0) {
  100267. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100268. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100269. return false;
  100270. }
  100271. for(i = 0; i < obj->num_comments; i++) {
  100272. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100273. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100274. return false; /* read_callback_ sets the state for us */
  100275. if(obj->comments[i].length > 0) {
  100276. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100277. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100278. return false;
  100279. }
  100280. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100281. return false; /* read_callback_ sets the state for us */
  100282. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100283. }
  100284. else
  100285. obj->comments[i].entry = 0;
  100286. }
  100287. }
  100288. else {
  100289. obj->comments = 0;
  100290. }
  100291. return true;
  100292. }
  100293. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100294. {
  100295. FLAC__uint32 i, j, x;
  100296. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100297. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100298. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100299. 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))
  100300. return false; /* read_callback_ sets the state for us */
  100301. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100302. return false; /* read_callback_ sets the state for us */
  100303. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100304. return false; /* read_callback_ sets the state for us */
  100305. obj->is_cd = x? true : false;
  100306. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100307. return false; /* read_callback_ sets the state for us */
  100308. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100309. return false; /* read_callback_ sets the state for us */
  100310. obj->num_tracks = x;
  100311. if(obj->num_tracks > 0) {
  100312. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100313. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100314. return false;
  100315. }
  100316. for(i = 0; i < obj->num_tracks; i++) {
  100317. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100318. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100319. return false; /* read_callback_ sets the state for us */
  100320. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100321. return false; /* read_callback_ sets the state for us */
  100322. track->number = (FLAC__byte)x;
  100323. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100324. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100325. return false; /* read_callback_ sets the state for us */
  100326. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100327. return false; /* read_callback_ sets the state for us */
  100328. track->type = x;
  100329. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100330. return false; /* read_callback_ sets the state for us */
  100331. track->pre_emphasis = x;
  100332. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100333. return false; /* read_callback_ sets the state for us */
  100334. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100335. return false; /* read_callback_ sets the state for us */
  100336. track->num_indices = (FLAC__byte)x;
  100337. if(track->num_indices > 0) {
  100338. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100339. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100340. return false;
  100341. }
  100342. for(j = 0; j < track->num_indices; j++) {
  100343. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100344. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100345. return false; /* read_callback_ sets the state for us */
  100346. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100347. return false; /* read_callback_ sets the state for us */
  100348. index->number = (FLAC__byte)x;
  100349. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100350. return false; /* read_callback_ sets the state for us */
  100351. }
  100352. }
  100353. }
  100354. }
  100355. return true;
  100356. }
  100357. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100358. {
  100359. FLAC__uint32 x;
  100360. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100361. /* read type */
  100362. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100363. return false; /* read_callback_ sets the state for us */
  100364. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100365. /* read MIME type */
  100366. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100367. return false; /* read_callback_ sets the state for us */
  100368. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100369. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100370. return false;
  100371. }
  100372. if(x > 0) {
  100373. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100374. return false; /* read_callback_ sets the state for us */
  100375. }
  100376. obj->mime_type[x] = '\0';
  100377. /* read description */
  100378. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100379. return false; /* read_callback_ sets the state for us */
  100380. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100381. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100382. return false;
  100383. }
  100384. if(x > 0) {
  100385. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100386. return false; /* read_callback_ sets the state for us */
  100387. }
  100388. obj->description[x] = '\0';
  100389. /* read width */
  100390. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100391. return false; /* read_callback_ sets the state for us */
  100392. /* read height */
  100393. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100394. return false; /* read_callback_ sets the state for us */
  100395. /* read depth */
  100396. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100397. return false; /* read_callback_ sets the state for us */
  100398. /* read colors */
  100399. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100400. return false; /* read_callback_ sets the state for us */
  100401. /* read data */
  100402. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100403. return false; /* read_callback_ sets the state for us */
  100404. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100405. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100406. return false;
  100407. }
  100408. if(obj->data_length > 0) {
  100409. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100410. return false; /* read_callback_ sets the state for us */
  100411. }
  100412. return true;
  100413. }
  100414. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100415. {
  100416. FLAC__uint32 x;
  100417. unsigned i, skip;
  100418. /* skip the version and flags bytes */
  100419. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100420. return false; /* read_callback_ sets the state for us */
  100421. /* get the size (in bytes) to skip */
  100422. skip = 0;
  100423. for(i = 0; i < 4; i++) {
  100424. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100425. return false; /* read_callback_ sets the state for us */
  100426. skip <<= 7;
  100427. skip |= (x & 0x7f);
  100428. }
  100429. /* skip the rest of the tag */
  100430. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100431. return false; /* read_callback_ sets the state for us */
  100432. return true;
  100433. }
  100434. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100435. {
  100436. FLAC__uint32 x;
  100437. FLAC__bool first = true;
  100438. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100439. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100440. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100441. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100442. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100443. return true;
  100444. }
  100445. }
  100446. /* make sure we're byte aligned */
  100447. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100448. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100449. return false; /* read_callback_ sets the state for us */
  100450. }
  100451. while(1) {
  100452. if(decoder->private_->cached) {
  100453. x = (FLAC__uint32)decoder->private_->lookahead;
  100454. decoder->private_->cached = false;
  100455. }
  100456. else {
  100457. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100458. return false; /* read_callback_ sets the state for us */
  100459. }
  100460. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100461. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100462. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100463. return false; /* read_callback_ sets the state for us */
  100464. /* we have to check if we just read two 0xff's in a row; the second may actually be the beginning of the sync code */
  100465. /* else we have to check if the second byte is the end of a sync code */
  100466. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100467. decoder->private_->lookahead = (FLAC__byte)x;
  100468. decoder->private_->cached = true;
  100469. }
  100470. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100471. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100472. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100473. return true;
  100474. }
  100475. }
  100476. if(first) {
  100477. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100478. first = false;
  100479. }
  100480. }
  100481. return true;
  100482. }
  100483. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100484. {
  100485. unsigned channel;
  100486. unsigned i;
  100487. FLAC__int32 mid, side;
  100488. unsigned frame_crc; /* the one we calculate from the input stream */
  100489. FLAC__uint32 x;
  100490. *got_a_frame = false;
  100491. /* init the CRC */
  100492. frame_crc = 0;
  100493. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100494. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100495. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100496. if(!read_frame_header_(decoder))
  100497. return false;
  100498. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  100499. return true;
  100500. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  100501. return false;
  100502. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100503. /*
  100504. * first figure the correct bits-per-sample of the subframe
  100505. */
  100506. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  100507. switch(decoder->private_->frame.header.channel_assignment) {
  100508. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100509. /* no adjustment needed */
  100510. break;
  100511. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100512. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100513. if(channel == 1)
  100514. bps++;
  100515. break;
  100516. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100517. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100518. if(channel == 0)
  100519. bps++;
  100520. break;
  100521. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100522. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100523. if(channel == 1)
  100524. bps++;
  100525. break;
  100526. default:
  100527. FLAC__ASSERT(0);
  100528. }
  100529. /*
  100530. * now read it
  100531. */
  100532. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  100533. return false;
  100534. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100535. return true;
  100536. }
  100537. if(!read_zero_padding_(decoder))
  100538. return false;
  100539. 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) */
  100540. return true;
  100541. /*
  100542. * Read the frame CRC-16 from the footer and check
  100543. */
  100544. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  100545. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  100546. return false; /* read_callback_ sets the state for us */
  100547. if(frame_crc == x) {
  100548. if(do_full_decode) {
  100549. /* Undo any special channel coding */
  100550. switch(decoder->private_->frame.header.channel_assignment) {
  100551. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100552. /* do nothing */
  100553. break;
  100554. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100555. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100556. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100557. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  100558. break;
  100559. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100560. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100561. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100562. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  100563. break;
  100564. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100565. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100566. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100567. #if 1
  100568. mid = decoder->private_->output[0][i];
  100569. side = decoder->private_->output[1][i];
  100570. mid <<= 1;
  100571. mid |= (side & 1); /* i.e. if 'side' is odd... */
  100572. decoder->private_->output[0][i] = (mid + side) >> 1;
  100573. decoder->private_->output[1][i] = (mid - side) >> 1;
  100574. #else
  100575. /* OPT: without 'side' temp variable */
  100576. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  100577. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  100578. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  100579. #endif
  100580. }
  100581. break;
  100582. default:
  100583. FLAC__ASSERT(0);
  100584. break;
  100585. }
  100586. }
  100587. }
  100588. else {
  100589. /* Bad frame, emit error and zero the output signal */
  100590. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  100591. if(do_full_decode) {
  100592. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100593. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100594. }
  100595. }
  100596. }
  100597. *got_a_frame = true;
  100598. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  100599. if(decoder->private_->next_fixed_block_size)
  100600. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  100601. /* put the latest values into the public section of the decoder instance */
  100602. decoder->protected_->channels = decoder->private_->frame.header.channels;
  100603. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  100604. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  100605. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  100606. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  100607. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100608. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  100609. /* write it */
  100610. if(do_full_decode) {
  100611. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  100612. return false;
  100613. }
  100614. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100615. return true;
  100616. }
  100617. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  100618. {
  100619. FLAC__uint32 x;
  100620. FLAC__uint64 xx;
  100621. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  100622. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  100623. unsigned raw_header_len;
  100624. FLAC__bool is_unparseable = false;
  100625. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100626. /* init the raw header with the saved bits from synchronization */
  100627. raw_header[0] = decoder->private_->header_warmup[0];
  100628. raw_header[1] = decoder->private_->header_warmup[1];
  100629. raw_header_len = 2;
  100630. /* check to make sure that reserved bit is 0 */
  100631. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  100632. is_unparseable = true;
  100633. /*
  100634. * Note that along the way as we read the header, we look for a sync
  100635. * code inside. If we find one it would indicate that our original
  100636. * sync was bad since there cannot be a sync code in a valid header.
  100637. *
  100638. * Three kinds of things can go wrong when reading the frame header:
  100639. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  100640. * If we don't find a sync code, it can end up looking like we read
  100641. * a valid but unparseable header, until getting to the frame header
  100642. * CRC. Even then we could get a false positive on the CRC.
  100643. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  100644. * future encoder).
  100645. * 3) We may be on a damaged frame which appears valid but unparseable.
  100646. *
  100647. * For all these reasons, we try and read a complete frame header as
  100648. * long as it seems valid, even if unparseable, up until the frame
  100649. * header CRC.
  100650. */
  100651. /*
  100652. * read in the raw header as bytes so we can CRC it, and parse it on the way
  100653. */
  100654. for(i = 0; i < 2; i++) {
  100655. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100656. return false; /* read_callback_ sets the state for us */
  100657. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100658. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  100659. decoder->private_->lookahead = (FLAC__byte)x;
  100660. decoder->private_->cached = true;
  100661. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100662. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100663. return true;
  100664. }
  100665. raw_header[raw_header_len++] = (FLAC__byte)x;
  100666. }
  100667. switch(x = raw_header[2] >> 4) {
  100668. case 0:
  100669. is_unparseable = true;
  100670. break;
  100671. case 1:
  100672. decoder->private_->frame.header.blocksize = 192;
  100673. break;
  100674. case 2:
  100675. case 3:
  100676. case 4:
  100677. case 5:
  100678. decoder->private_->frame.header.blocksize = 576 << (x-2);
  100679. break;
  100680. case 6:
  100681. case 7:
  100682. blocksize_hint = x;
  100683. break;
  100684. case 8:
  100685. case 9:
  100686. case 10:
  100687. case 11:
  100688. case 12:
  100689. case 13:
  100690. case 14:
  100691. case 15:
  100692. decoder->private_->frame.header.blocksize = 256 << (x-8);
  100693. break;
  100694. default:
  100695. FLAC__ASSERT(0);
  100696. break;
  100697. }
  100698. switch(x = raw_header[2] & 0x0f) {
  100699. case 0:
  100700. if(decoder->private_->has_stream_info)
  100701. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  100702. else
  100703. is_unparseable = true;
  100704. break;
  100705. case 1:
  100706. decoder->private_->frame.header.sample_rate = 88200;
  100707. break;
  100708. case 2:
  100709. decoder->private_->frame.header.sample_rate = 176400;
  100710. break;
  100711. case 3:
  100712. decoder->private_->frame.header.sample_rate = 192000;
  100713. break;
  100714. case 4:
  100715. decoder->private_->frame.header.sample_rate = 8000;
  100716. break;
  100717. case 5:
  100718. decoder->private_->frame.header.sample_rate = 16000;
  100719. break;
  100720. case 6:
  100721. decoder->private_->frame.header.sample_rate = 22050;
  100722. break;
  100723. case 7:
  100724. decoder->private_->frame.header.sample_rate = 24000;
  100725. break;
  100726. case 8:
  100727. decoder->private_->frame.header.sample_rate = 32000;
  100728. break;
  100729. case 9:
  100730. decoder->private_->frame.header.sample_rate = 44100;
  100731. break;
  100732. case 10:
  100733. decoder->private_->frame.header.sample_rate = 48000;
  100734. break;
  100735. case 11:
  100736. decoder->private_->frame.header.sample_rate = 96000;
  100737. break;
  100738. case 12:
  100739. case 13:
  100740. case 14:
  100741. sample_rate_hint = x;
  100742. break;
  100743. case 15:
  100744. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100745. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100746. return true;
  100747. default:
  100748. FLAC__ASSERT(0);
  100749. }
  100750. x = (unsigned)(raw_header[3] >> 4);
  100751. if(x & 8) {
  100752. decoder->private_->frame.header.channels = 2;
  100753. switch(x & 7) {
  100754. case 0:
  100755. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  100756. break;
  100757. case 1:
  100758. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  100759. break;
  100760. case 2:
  100761. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  100762. break;
  100763. default:
  100764. is_unparseable = true;
  100765. break;
  100766. }
  100767. }
  100768. else {
  100769. decoder->private_->frame.header.channels = (unsigned)x + 1;
  100770. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  100771. }
  100772. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  100773. case 0:
  100774. if(decoder->private_->has_stream_info)
  100775. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  100776. else
  100777. is_unparseable = true;
  100778. break;
  100779. case 1:
  100780. decoder->private_->frame.header.bits_per_sample = 8;
  100781. break;
  100782. case 2:
  100783. decoder->private_->frame.header.bits_per_sample = 12;
  100784. break;
  100785. case 4:
  100786. decoder->private_->frame.header.bits_per_sample = 16;
  100787. break;
  100788. case 5:
  100789. decoder->private_->frame.header.bits_per_sample = 20;
  100790. break;
  100791. case 6:
  100792. decoder->private_->frame.header.bits_per_sample = 24;
  100793. break;
  100794. case 3:
  100795. case 7:
  100796. is_unparseable = true;
  100797. break;
  100798. default:
  100799. FLAC__ASSERT(0);
  100800. break;
  100801. }
  100802. /* check to make sure that reserved bit is 0 */
  100803. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  100804. is_unparseable = true;
  100805. /* read the frame's starting sample number (or frame number as the case may be) */
  100806. if(
  100807. raw_header[1] & 0x01 ||
  100808. /*@@@ 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 */
  100809. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  100810. ) { /* variable blocksize */
  100811. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  100812. return false; /* read_callback_ sets the state for us */
  100813. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  100814. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100815. decoder->private_->cached = true;
  100816. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100817. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100818. return true;
  100819. }
  100820. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100821. decoder->private_->frame.header.number.sample_number = xx;
  100822. }
  100823. else { /* fixed blocksize */
  100824. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  100825. return false; /* read_callback_ sets the state for us */
  100826. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  100827. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100828. decoder->private_->cached = true;
  100829. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100830. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100831. return true;
  100832. }
  100833. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  100834. decoder->private_->frame.header.number.frame_number = x;
  100835. }
  100836. if(blocksize_hint) {
  100837. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100838. return false; /* read_callback_ sets the state for us */
  100839. raw_header[raw_header_len++] = (FLAC__byte)x;
  100840. if(blocksize_hint == 7) {
  100841. FLAC__uint32 _x;
  100842. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100843. return false; /* read_callback_ sets the state for us */
  100844. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100845. x = (x << 8) | _x;
  100846. }
  100847. decoder->private_->frame.header.blocksize = x+1;
  100848. }
  100849. if(sample_rate_hint) {
  100850. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100851. return false; /* read_callback_ sets the state for us */
  100852. raw_header[raw_header_len++] = (FLAC__byte)x;
  100853. if(sample_rate_hint != 12) {
  100854. FLAC__uint32 _x;
  100855. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100856. return false; /* read_callback_ sets the state for us */
  100857. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100858. x = (x << 8) | _x;
  100859. }
  100860. if(sample_rate_hint == 12)
  100861. decoder->private_->frame.header.sample_rate = x*1000;
  100862. else if(sample_rate_hint == 13)
  100863. decoder->private_->frame.header.sample_rate = x;
  100864. else
  100865. decoder->private_->frame.header.sample_rate = x*10;
  100866. }
  100867. /* read the CRC-8 byte */
  100868. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100869. return false; /* read_callback_ sets the state for us */
  100870. crc8 = (FLAC__byte)x;
  100871. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  100872. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100873. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100874. return true;
  100875. }
  100876. /* calculate the sample number from the frame number if needed */
  100877. decoder->private_->next_fixed_block_size = 0;
  100878. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  100879. x = decoder->private_->frame.header.number.frame_number;
  100880. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100881. if(decoder->private_->fixed_block_size)
  100882. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  100883. else if(decoder->private_->has_stream_info) {
  100884. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  100885. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  100886. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  100887. }
  100888. else
  100889. is_unparseable = true;
  100890. }
  100891. else if(x == 0) {
  100892. decoder->private_->frame.header.number.sample_number = 0;
  100893. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  100894. }
  100895. else {
  100896. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  100897. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  100898. }
  100899. }
  100900. if(is_unparseable) {
  100901. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100902. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100903. return true;
  100904. }
  100905. return true;
  100906. }
  100907. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100908. {
  100909. FLAC__uint32 x;
  100910. FLAC__bool wasted_bits;
  100911. unsigned i;
  100912. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  100913. return false; /* read_callback_ sets the state for us */
  100914. wasted_bits = (x & 1);
  100915. x &= 0xfe;
  100916. if(wasted_bits) {
  100917. unsigned u;
  100918. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  100919. return false; /* read_callback_ sets the state for us */
  100920. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  100921. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  100922. }
  100923. else
  100924. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  100925. /*
  100926. * Lots of magic numbers here
  100927. */
  100928. if(x & 0x80) {
  100929. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100930. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100931. return true;
  100932. }
  100933. else if(x == 0) {
  100934. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  100935. return false;
  100936. }
  100937. else if(x == 2) {
  100938. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  100939. return false;
  100940. }
  100941. else if(x < 16) {
  100942. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100943. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100944. return true;
  100945. }
  100946. else if(x <= 24) {
  100947. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  100948. return false;
  100949. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100950. return true;
  100951. }
  100952. else if(x < 64) {
  100953. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100954. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100955. return true;
  100956. }
  100957. else {
  100958. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  100959. return false;
  100960. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100961. return true;
  100962. }
  100963. if(wasted_bits && do_full_decode) {
  100964. x = decoder->private_->frame.subframes[channel].wasted_bits;
  100965. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100966. decoder->private_->output[channel][i] <<= x;
  100967. }
  100968. return true;
  100969. }
  100970. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100971. {
  100972. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  100973. FLAC__int32 x;
  100974. unsigned i;
  100975. FLAC__int32 *output = decoder->private_->output[channel];
  100976. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  100977. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  100978. return false; /* read_callback_ sets the state for us */
  100979. subframe->value = x;
  100980. /* decode the subframe */
  100981. if(do_full_decode) {
  100982. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100983. output[i] = x;
  100984. }
  100985. return true;
  100986. }
  100987. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  100988. {
  100989. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  100990. FLAC__int32 i32;
  100991. FLAC__uint32 u32;
  100992. unsigned u;
  100993. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  100994. subframe->residual = decoder->private_->residual[channel];
  100995. subframe->order = order;
  100996. /* read warm-up samples */
  100997. for(u = 0; u < order; u++) {
  100998. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  100999. return false; /* read_callback_ sets the state for us */
  101000. subframe->warmup[u] = i32;
  101001. }
  101002. /* read entropy coding method info */
  101003. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101004. return false; /* read_callback_ sets the state for us */
  101005. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101006. switch(subframe->entropy_coding_method.type) {
  101007. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101008. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101009. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101010. return false; /* read_callback_ sets the state for us */
  101011. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101012. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101013. break;
  101014. default:
  101015. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101016. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101017. return true;
  101018. }
  101019. /* read residual */
  101020. switch(subframe->entropy_coding_method.type) {
  101021. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101022. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101023. 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))
  101024. return false;
  101025. break;
  101026. default:
  101027. FLAC__ASSERT(0);
  101028. }
  101029. /* decode the subframe */
  101030. if(do_full_decode) {
  101031. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101032. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101033. }
  101034. return true;
  101035. }
  101036. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101037. {
  101038. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101039. FLAC__int32 i32;
  101040. FLAC__uint32 u32;
  101041. unsigned u;
  101042. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101043. subframe->residual = decoder->private_->residual[channel];
  101044. subframe->order = order;
  101045. /* read warm-up samples */
  101046. for(u = 0; u < order; u++) {
  101047. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101048. return false; /* read_callback_ sets the state for us */
  101049. subframe->warmup[u] = i32;
  101050. }
  101051. /* read qlp coeff precision */
  101052. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101053. return false; /* read_callback_ sets the state for us */
  101054. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101055. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101056. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101057. return true;
  101058. }
  101059. subframe->qlp_coeff_precision = u32+1;
  101060. /* read qlp shift */
  101061. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101062. return false; /* read_callback_ sets the state for us */
  101063. subframe->quantization_level = i32;
  101064. /* read quantized lp coefficiencts */
  101065. for(u = 0; u < order; u++) {
  101066. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101067. return false; /* read_callback_ sets the state for us */
  101068. subframe->qlp_coeff[u] = i32;
  101069. }
  101070. /* read entropy coding method info */
  101071. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101072. return false; /* read_callback_ sets the state for us */
  101073. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101074. switch(subframe->entropy_coding_method.type) {
  101075. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101076. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101077. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101078. return false; /* read_callback_ sets the state for us */
  101079. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101080. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101081. break;
  101082. default:
  101083. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101084. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101085. return true;
  101086. }
  101087. /* read residual */
  101088. switch(subframe->entropy_coding_method.type) {
  101089. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101090. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101091. 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))
  101092. return false;
  101093. break;
  101094. default:
  101095. FLAC__ASSERT(0);
  101096. }
  101097. /* decode the subframe */
  101098. if(do_full_decode) {
  101099. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101100. /*@@@@@@ technically not pessimistic enough, should be more like
  101101. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101102. */
  101103. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101104. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101105. if(order <= 8)
  101106. 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);
  101107. else
  101108. 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);
  101109. }
  101110. else
  101111. 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);
  101112. else
  101113. 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);
  101114. }
  101115. return true;
  101116. }
  101117. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101118. {
  101119. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101120. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101121. unsigned i;
  101122. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101123. subframe->data = residual;
  101124. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101125. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101126. return false; /* read_callback_ sets the state for us */
  101127. residual[i] = x;
  101128. }
  101129. /* decode the subframe */
  101130. if(do_full_decode)
  101131. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101132. return true;
  101133. }
  101134. 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)
  101135. {
  101136. FLAC__uint32 rice_parameter;
  101137. int i;
  101138. unsigned partition, sample, u;
  101139. const unsigned partitions = 1u << partition_order;
  101140. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101141. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101142. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101143. /* sanity checks */
  101144. if(partition_order == 0) {
  101145. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101146. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101147. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101148. return true;
  101149. }
  101150. }
  101151. else {
  101152. if(partition_samples < predictor_order) {
  101153. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101154. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101155. return true;
  101156. }
  101157. }
  101158. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101159. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101160. return false;
  101161. }
  101162. sample = 0;
  101163. for(partition = 0; partition < partitions; partition++) {
  101164. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101165. return false; /* read_callback_ sets the state for us */
  101166. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101167. if(rice_parameter < pesc) {
  101168. partitioned_rice_contents->raw_bits[partition] = 0;
  101169. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101170. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101171. return false; /* read_callback_ sets the state for us */
  101172. sample += u;
  101173. }
  101174. else {
  101175. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101176. return false; /* read_callback_ sets the state for us */
  101177. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101178. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101179. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101180. return false; /* read_callback_ sets the state for us */
  101181. residual[sample] = i;
  101182. }
  101183. }
  101184. }
  101185. return true;
  101186. }
  101187. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101188. {
  101189. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101190. FLAC__uint32 zero = 0;
  101191. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101192. return false; /* read_callback_ sets the state for us */
  101193. if(zero != 0) {
  101194. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101195. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101196. }
  101197. }
  101198. return true;
  101199. }
  101200. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101201. {
  101202. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101203. if(
  101204. #if FLAC__HAS_OGG
  101205. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101206. !decoder->private_->is_ogg &&
  101207. #endif
  101208. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101209. ) {
  101210. *bytes = 0;
  101211. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101212. return false;
  101213. }
  101214. else if(*bytes > 0) {
  101215. /* While seeking, it is possible for our seek to land in the
  101216. * middle of audio data that looks exactly like a frame header
  101217. * from a future version of an encoder. When that happens, our
  101218. * error callback will get an
  101219. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101220. * unparseable_frame_count. But there is a remote possibility
  101221. * that it is properly synced at such a "future-codec frame",
  101222. * so to make sure, we wait to see many "unparseable" errors in
  101223. * a row before bailing out.
  101224. */
  101225. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101226. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101227. return false;
  101228. }
  101229. else {
  101230. const FLAC__StreamDecoderReadStatus status =
  101231. #if FLAC__HAS_OGG
  101232. decoder->private_->is_ogg?
  101233. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101234. #endif
  101235. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101236. ;
  101237. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101238. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101239. return false;
  101240. }
  101241. else if(*bytes == 0) {
  101242. if(
  101243. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101244. (
  101245. #if FLAC__HAS_OGG
  101246. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101247. !decoder->private_->is_ogg &&
  101248. #endif
  101249. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101250. )
  101251. ) {
  101252. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101253. return false;
  101254. }
  101255. else
  101256. return true;
  101257. }
  101258. else
  101259. return true;
  101260. }
  101261. }
  101262. else {
  101263. /* abort to avoid a deadlock */
  101264. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101265. return false;
  101266. }
  101267. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101268. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101269. * and at the same time hit the end of the stream (for example, seeking
  101270. * to a point that is after the beginning of the last Ogg page). There
  101271. * is no way to report an Ogg sync loss through the callbacks (see note
  101272. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101273. * So to keep the decoder from stopping at this point we gate the call
  101274. * to the eof_callback and let the Ogg decoder aspect set the
  101275. * end-of-stream state when it is needed.
  101276. */
  101277. }
  101278. #if FLAC__HAS_OGG
  101279. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101280. {
  101281. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101282. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101283. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101284. /* we don't really have a way to handle lost sync via read
  101285. * callback so we'll let it pass and let the underlying
  101286. * FLAC decoder catch the error
  101287. */
  101288. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101289. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101290. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101291. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101292. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101293. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101294. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101295. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101296. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101297. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101298. default:
  101299. FLAC__ASSERT(0);
  101300. /* double protection */
  101301. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101302. }
  101303. }
  101304. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101305. {
  101306. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101307. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101308. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101309. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101310. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101311. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101312. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101313. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101314. default:
  101315. /* double protection: */
  101316. FLAC__ASSERT(0);
  101317. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101318. }
  101319. }
  101320. #endif
  101321. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101322. {
  101323. if(decoder->private_->is_seeking) {
  101324. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101325. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101326. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101327. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101328. #if FLAC__HAS_OGG
  101329. decoder->private_->got_a_frame = true;
  101330. #endif
  101331. decoder->private_->last_frame = *frame; /* save the frame */
  101332. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101333. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101334. /* kick out of seek mode */
  101335. decoder->private_->is_seeking = false;
  101336. /* shift out the samples before target_sample */
  101337. if(delta > 0) {
  101338. unsigned channel;
  101339. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101340. for(channel = 0; channel < frame->header.channels; channel++)
  101341. newbuffer[channel] = buffer[channel] + delta;
  101342. decoder->private_->last_frame.header.blocksize -= delta;
  101343. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101344. /* write the relevant samples */
  101345. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101346. }
  101347. else {
  101348. /* write the relevant samples */
  101349. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101350. }
  101351. }
  101352. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101353. }
  101354. /*
  101355. * If we never got STREAMINFO, turn off MD5 checking to save
  101356. * cycles since we don't have a sum to compare to anyway
  101357. */
  101358. if(!decoder->private_->has_stream_info)
  101359. decoder->private_->do_md5_checking = false;
  101360. if(decoder->private_->do_md5_checking) {
  101361. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101362. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101363. }
  101364. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101365. }
  101366. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101367. {
  101368. if(!decoder->private_->is_seeking)
  101369. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101370. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101371. decoder->private_->unparseable_frame_count++;
  101372. }
  101373. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101374. {
  101375. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101376. FLAC__int64 pos = -1;
  101377. int i;
  101378. unsigned approx_bytes_per_frame;
  101379. FLAC__bool first_seek = true;
  101380. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101381. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101382. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101383. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101384. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101385. /* take these from the current frame in case they've changed mid-stream */
  101386. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101387. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101388. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101389. /* use values from stream info if we didn't decode a frame */
  101390. if(channels == 0)
  101391. channels = decoder->private_->stream_info.data.stream_info.channels;
  101392. if(bps == 0)
  101393. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101394. /* we are just guessing here */
  101395. if(max_framesize > 0)
  101396. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101397. /*
  101398. * Check if it's a known fixed-blocksize stream. Note that though
  101399. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101400. * never get a STREAMINFO block when decoding so the value of
  101401. * min_blocksize might be zero.
  101402. */
  101403. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101404. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101405. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101406. }
  101407. else
  101408. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101409. /*
  101410. * First, we set an upper and lower bound on where in the
  101411. * stream we will search. For now we assume the worst case
  101412. * scenario, which is our best guess at the beginning of
  101413. * the first frame and end of the stream.
  101414. */
  101415. lower_bound = first_frame_offset;
  101416. lower_bound_sample = 0;
  101417. upper_bound = stream_length;
  101418. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101419. /*
  101420. * Now we refine the bounds if we have a seektable with
  101421. * suitable points. Note that according to the spec they
  101422. * must be ordered by ascending sample number.
  101423. *
  101424. * Note: to protect against invalid seek tables we will ignore points
  101425. * that have frame_samples==0 or sample_number>=total_samples
  101426. */
  101427. if(seek_table) {
  101428. FLAC__uint64 new_lower_bound = lower_bound;
  101429. FLAC__uint64 new_upper_bound = upper_bound;
  101430. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101431. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101432. /* find the closest seek point <= target_sample, if it exists */
  101433. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101434. if(
  101435. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101436. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101437. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101438. seek_table->points[i].sample_number <= target_sample
  101439. )
  101440. break;
  101441. }
  101442. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101443. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101444. new_lower_bound_sample = seek_table->points[i].sample_number;
  101445. }
  101446. /* find the closest seek point > target_sample, if it exists */
  101447. for(i = 0; i < (int)seek_table->num_points; i++) {
  101448. if(
  101449. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101450. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101451. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101452. seek_table->points[i].sample_number > target_sample
  101453. )
  101454. break;
  101455. }
  101456. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101457. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101458. new_upper_bound_sample = seek_table->points[i].sample_number;
  101459. }
  101460. /* final protection against unsorted seek tables; keep original values if bogus */
  101461. if(new_upper_bound >= new_lower_bound) {
  101462. lower_bound = new_lower_bound;
  101463. upper_bound = new_upper_bound;
  101464. lower_bound_sample = new_lower_bound_sample;
  101465. upper_bound_sample = new_upper_bound_sample;
  101466. }
  101467. }
  101468. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101469. /* there are 2 insidious ways that the following equality occurs, which
  101470. * we need to fix:
  101471. * 1) total_samples is 0 (unknown) and target_sample is 0
  101472. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101473. * exactly equal to the last seek point in the seek table; this
  101474. * means there is no seek point above it, and upper_bound_samples
  101475. * remains equal to the estimate (of target_samples) we made above
  101476. * in either case it does not hurt to move upper_bound_sample up by 1
  101477. */
  101478. if(upper_bound_sample == lower_bound_sample)
  101479. upper_bound_sample++;
  101480. decoder->private_->target_sample = target_sample;
  101481. while(1) {
  101482. /* check if the bounds are still ok */
  101483. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101484. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101485. return false;
  101486. }
  101487. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101488. #if defined _MSC_VER || defined __MINGW32__
  101489. /* with VC++ you have to spoon feed it the casting */
  101490. 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;
  101491. #else
  101492. 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;
  101493. #endif
  101494. #else
  101495. /* a little less accurate: */
  101496. if(upper_bound - lower_bound < 0xffffffff)
  101497. 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;
  101498. else /* @@@ WATCHOUT, ~2TB limit */
  101499. 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;
  101500. #endif
  101501. if(pos >= (FLAC__int64)upper_bound)
  101502. pos = (FLAC__int64)upper_bound - 1;
  101503. if(pos < (FLAC__int64)lower_bound)
  101504. pos = (FLAC__int64)lower_bound;
  101505. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101506. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101507. return false;
  101508. }
  101509. if(!FLAC__stream_decoder_flush(decoder)) {
  101510. /* above call sets the state for us */
  101511. return false;
  101512. }
  101513. /* Now we need to get a frame. First we need to reset our
  101514. * unparseable_frame_count; if we get too many unparseable
  101515. * frames in a row, the read callback will return
  101516. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  101517. * FLAC__stream_decoder_process_single() to return false.
  101518. */
  101519. decoder->private_->unparseable_frame_count = 0;
  101520. if(!FLAC__stream_decoder_process_single(decoder)) {
  101521. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101522. return false;
  101523. }
  101524. /* our write callback will change the state when it gets to the target frame */
  101525. /* 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 */
  101526. #if 0
  101527. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  101528. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  101529. break;
  101530. #endif
  101531. if(!decoder->private_->is_seeking)
  101532. break;
  101533. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101534. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101535. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  101536. if (pos == (FLAC__int64)lower_bound) {
  101537. /* can't move back any more than the first frame, something is fatally wrong */
  101538. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101539. return false;
  101540. }
  101541. /* our last move backwards wasn't big enough, try again */
  101542. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  101543. continue;
  101544. }
  101545. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  101546. first_seek = false;
  101547. /* make sure we are not seeking in corrupted stream */
  101548. if (this_frame_sample < lower_bound_sample) {
  101549. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101550. return false;
  101551. }
  101552. /* we need to narrow the search */
  101553. if(target_sample < this_frame_sample) {
  101554. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101555. /*@@@@@@ what will decode position be if at end of stream? */
  101556. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  101557. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101558. return false;
  101559. }
  101560. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  101561. }
  101562. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  101563. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101564. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  101565. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101566. return false;
  101567. }
  101568. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  101569. }
  101570. }
  101571. return true;
  101572. }
  101573. #if FLAC__HAS_OGG
  101574. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101575. {
  101576. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  101577. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  101578. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  101579. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  101580. FLAC__bool did_a_seek;
  101581. unsigned iteration = 0;
  101582. /* In the first iterations, we will calculate the target byte position
  101583. * by the distance from the target sample to left_sample and
  101584. * right_sample (let's call it "proportional search"). After that, we
  101585. * will switch to binary search.
  101586. */
  101587. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  101588. /* We will switch to a linear search once our current sample is less
  101589. * than this number of samples ahead of the target sample
  101590. */
  101591. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  101592. /* If the total number of samples is unknown, use a large value, and
  101593. * force binary search immediately.
  101594. */
  101595. if(right_sample == 0) {
  101596. right_sample = (FLAC__uint64)(-1);
  101597. BINARY_SEARCH_AFTER_ITERATION = 0;
  101598. }
  101599. decoder->private_->target_sample = target_sample;
  101600. for( ; ; iteration++) {
  101601. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  101602. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  101603. pos = (right_pos + left_pos) / 2;
  101604. }
  101605. else {
  101606. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101607. #if defined _MSC_VER || defined __MINGW32__
  101608. /* with MSVC you have to spoon feed it the casting */
  101609. 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));
  101610. #else
  101611. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  101612. #endif
  101613. #else
  101614. /* a little less accurate: */
  101615. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  101616. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  101617. else /* @@@ WATCHOUT, ~2TB limit */
  101618. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  101619. #endif
  101620. /* @@@ TODO: might want to limit pos to some distance
  101621. * before EOF, to make sure we land before the last frame,
  101622. * thereby getting a this_frame_sample and so having a better
  101623. * estimate.
  101624. */
  101625. }
  101626. /* physical seek */
  101627. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101628. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101629. return false;
  101630. }
  101631. if(!FLAC__stream_decoder_flush(decoder)) {
  101632. /* above call sets the state for us */
  101633. return false;
  101634. }
  101635. did_a_seek = true;
  101636. }
  101637. else
  101638. did_a_seek = false;
  101639. decoder->private_->got_a_frame = false;
  101640. if(!FLAC__stream_decoder_process_single(decoder)) {
  101641. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101642. return false;
  101643. }
  101644. if(!decoder->private_->got_a_frame) {
  101645. if(did_a_seek) {
  101646. /* this can happen if we seek to a point after the last frame; we drop
  101647. * to binary search right away in this case to avoid any wasted
  101648. * iterations of proportional search.
  101649. */
  101650. right_pos = pos;
  101651. BINARY_SEARCH_AFTER_ITERATION = 0;
  101652. }
  101653. else {
  101654. /* this can probably only happen if total_samples is unknown and the
  101655. * target_sample is past the end of the stream
  101656. */
  101657. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101658. return false;
  101659. }
  101660. }
  101661. /* our write callback will change the state when it gets to the target frame */
  101662. else if(!decoder->private_->is_seeking) {
  101663. break;
  101664. }
  101665. else {
  101666. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101667. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101668. if (did_a_seek) {
  101669. if (this_frame_sample <= target_sample) {
  101670. /* The 'equal' case should not happen, since
  101671. * FLAC__stream_decoder_process_single()
  101672. * should recognize that it has hit the
  101673. * target sample and we would exit through
  101674. * the 'break' above.
  101675. */
  101676. FLAC__ASSERT(this_frame_sample != target_sample);
  101677. left_sample = this_frame_sample;
  101678. /* sanity check to avoid infinite loop */
  101679. if (left_pos == pos) {
  101680. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101681. return false;
  101682. }
  101683. left_pos = pos;
  101684. }
  101685. else if(this_frame_sample > target_sample) {
  101686. right_sample = this_frame_sample;
  101687. /* sanity check to avoid infinite loop */
  101688. if (right_pos == pos) {
  101689. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101690. return false;
  101691. }
  101692. right_pos = pos;
  101693. }
  101694. }
  101695. }
  101696. }
  101697. return true;
  101698. }
  101699. #endif
  101700. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101701. {
  101702. (void)client_data;
  101703. if(*bytes > 0) {
  101704. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  101705. if(ferror(decoder->private_->file))
  101706. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101707. else if(*bytes == 0)
  101708. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101709. else
  101710. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101711. }
  101712. else
  101713. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  101714. }
  101715. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  101716. {
  101717. (void)client_data;
  101718. if(decoder->private_->file == stdin)
  101719. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  101720. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  101721. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  101722. else
  101723. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  101724. }
  101725. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  101726. {
  101727. off_t pos;
  101728. (void)client_data;
  101729. if(decoder->private_->file == stdin)
  101730. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  101731. else if((pos = ftello(decoder->private_->file)) < 0)
  101732. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  101733. else {
  101734. *absolute_byte_offset = (FLAC__uint64)pos;
  101735. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  101736. }
  101737. }
  101738. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  101739. {
  101740. struct stat filestats;
  101741. (void)client_data;
  101742. if(decoder->private_->file == stdin)
  101743. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  101744. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  101745. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  101746. else {
  101747. *stream_length = (FLAC__uint64)filestats.st_size;
  101748. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  101749. }
  101750. }
  101751. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  101752. {
  101753. (void)client_data;
  101754. return feof(decoder->private_->file)? true : false;
  101755. }
  101756. #endif
  101757. /*** End of inlined file: stream_decoder.c ***/
  101758. /*** Start of inlined file: stream_encoder.c ***/
  101759. /*** Start of inlined file: juce_FlacHeader.h ***/
  101760. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101761. // tasks..
  101762. #define VERSION "1.2.1"
  101763. #define FLAC__NO_DLL 1
  101764. #if JUCE_MSVC
  101765. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101766. #endif
  101767. #if JUCE_MAC
  101768. #define FLAC__SYS_DARWIN 1
  101769. #endif
  101770. /*** End of inlined file: juce_FlacHeader.h ***/
  101771. #if JUCE_USE_FLAC
  101772. #if HAVE_CONFIG_H
  101773. # include <config.h>
  101774. #endif
  101775. #if defined _MSC_VER || defined __MINGW32__
  101776. #include <io.h> /* for _setmode() */
  101777. #include <fcntl.h> /* for _O_BINARY */
  101778. #endif
  101779. #if defined __CYGWIN__ || defined __EMX__
  101780. #include <io.h> /* for setmode(), O_BINARY */
  101781. #include <fcntl.h> /* for _O_BINARY */
  101782. #endif
  101783. #include <limits.h>
  101784. #include <stdio.h>
  101785. #include <stdlib.h> /* for malloc() */
  101786. #include <string.h> /* for memcpy() */
  101787. #include <sys/types.h> /* for off_t */
  101788. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  101789. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  101790. #define fseeko fseek
  101791. #define ftello ftell
  101792. #endif
  101793. #endif
  101794. /*** Start of inlined file: stream_encoder.h ***/
  101795. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  101796. #define FLAC__PROTECTED__STREAM_ENCODER_H
  101797. #if FLAC__HAS_OGG
  101798. #include "private/ogg_encoder_aspect.h"
  101799. #endif
  101800. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101801. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  101802. typedef enum {
  101803. FLAC__APODIZATION_BARTLETT,
  101804. FLAC__APODIZATION_BARTLETT_HANN,
  101805. FLAC__APODIZATION_BLACKMAN,
  101806. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  101807. FLAC__APODIZATION_CONNES,
  101808. FLAC__APODIZATION_FLATTOP,
  101809. FLAC__APODIZATION_GAUSS,
  101810. FLAC__APODIZATION_HAMMING,
  101811. FLAC__APODIZATION_HANN,
  101812. FLAC__APODIZATION_KAISER_BESSEL,
  101813. FLAC__APODIZATION_NUTTALL,
  101814. FLAC__APODIZATION_RECTANGLE,
  101815. FLAC__APODIZATION_TRIANGLE,
  101816. FLAC__APODIZATION_TUKEY,
  101817. FLAC__APODIZATION_WELCH
  101818. } FLAC__ApodizationFunction;
  101819. typedef struct {
  101820. FLAC__ApodizationFunction type;
  101821. union {
  101822. struct {
  101823. FLAC__real stddev;
  101824. } gauss;
  101825. struct {
  101826. FLAC__real p;
  101827. } tukey;
  101828. } parameters;
  101829. } FLAC__ApodizationSpecification;
  101830. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101831. typedef struct FLAC__StreamEncoderProtected {
  101832. FLAC__StreamEncoderState state;
  101833. FLAC__bool verify;
  101834. FLAC__bool streamable_subset;
  101835. FLAC__bool do_md5;
  101836. FLAC__bool do_mid_side_stereo;
  101837. FLAC__bool loose_mid_side_stereo;
  101838. unsigned channels;
  101839. unsigned bits_per_sample;
  101840. unsigned sample_rate;
  101841. unsigned blocksize;
  101842. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101843. unsigned num_apodizations;
  101844. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  101845. #endif
  101846. unsigned max_lpc_order;
  101847. unsigned qlp_coeff_precision;
  101848. FLAC__bool do_qlp_coeff_prec_search;
  101849. FLAC__bool do_exhaustive_model_search;
  101850. FLAC__bool do_escape_coding;
  101851. unsigned min_residual_partition_order;
  101852. unsigned max_residual_partition_order;
  101853. unsigned rice_parameter_search_dist;
  101854. FLAC__uint64 total_samples_estimate;
  101855. FLAC__StreamMetadata **metadata;
  101856. unsigned num_metadata_blocks;
  101857. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  101858. #if FLAC__HAS_OGG
  101859. FLAC__OggEncoderAspect ogg_encoder_aspect;
  101860. #endif
  101861. } FLAC__StreamEncoderProtected;
  101862. #endif
  101863. /*** End of inlined file: stream_encoder.h ***/
  101864. #if FLAC__HAS_OGG
  101865. #include "include/private/ogg_helper.h"
  101866. #include "include/private/ogg_mapping.h"
  101867. #endif
  101868. /*** Start of inlined file: stream_encoder_framing.h ***/
  101869. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101870. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101871. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  101872. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  101873. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101874. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101875. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101876. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101877. #endif
  101878. /*** End of inlined file: stream_encoder_framing.h ***/
  101879. /*** Start of inlined file: window.h ***/
  101880. #ifndef FLAC__PRIVATE__WINDOW_H
  101881. #define FLAC__PRIVATE__WINDOW_H
  101882. #ifdef HAVE_CONFIG_H
  101883. #include <config.h>
  101884. #endif
  101885. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101886. /*
  101887. * FLAC__window_*()
  101888. * --------------------------------------------------------------------
  101889. * Calculates window coefficients according to different apodization
  101890. * functions.
  101891. *
  101892. * OUT window[0,L-1]
  101893. * IN L (number of points in window)
  101894. */
  101895. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  101896. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  101897. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  101898. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  101899. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  101900. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  101901. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  101902. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  101903. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  101904. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  101905. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  101906. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  101907. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  101908. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  101909. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  101910. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  101911. #endif
  101912. /*** End of inlined file: window.h ***/
  101913. #ifndef FLaC__INLINE
  101914. #define FLaC__INLINE
  101915. #endif
  101916. #ifdef min
  101917. #undef min
  101918. #endif
  101919. #define min(x,y) ((x)<(y)?(x):(y))
  101920. #ifdef max
  101921. #undef max
  101922. #endif
  101923. #define max(x,y) ((x)>(y)?(x):(y))
  101924. /* Exact Rice codeword length calculation is off by default. The simple
  101925. * (and fast) estimation (of how many bits a residual value will be
  101926. * encoded with) in this encoder is very good, almost always yielding
  101927. * compression within 0.1% of exact calculation.
  101928. */
  101929. #undef EXACT_RICE_BITS_CALCULATION
  101930. /* Rice parameter searching is off by default. The simple (and fast)
  101931. * parameter estimation in this encoder is very good, almost always
  101932. * yielding compression within 0.1% of the optimal parameters.
  101933. */
  101934. #undef ENABLE_RICE_PARAMETER_SEARCH
  101935. typedef struct {
  101936. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  101937. unsigned size; /* of each data[] in samples */
  101938. unsigned tail;
  101939. } verify_input_fifo;
  101940. typedef struct {
  101941. const FLAC__byte *data;
  101942. unsigned capacity;
  101943. unsigned bytes;
  101944. } verify_output;
  101945. typedef enum {
  101946. ENCODER_IN_MAGIC = 0,
  101947. ENCODER_IN_METADATA = 1,
  101948. ENCODER_IN_AUDIO = 2
  101949. } EncoderStateHint;
  101950. static struct CompressionLevels {
  101951. FLAC__bool do_mid_side_stereo;
  101952. FLAC__bool loose_mid_side_stereo;
  101953. unsigned max_lpc_order;
  101954. unsigned qlp_coeff_precision;
  101955. FLAC__bool do_qlp_coeff_prec_search;
  101956. FLAC__bool do_escape_coding;
  101957. FLAC__bool do_exhaustive_model_search;
  101958. unsigned min_residual_partition_order;
  101959. unsigned max_residual_partition_order;
  101960. unsigned rice_parameter_search_dist;
  101961. } compression_levels_[] = {
  101962. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  101963. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  101964. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  101965. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  101966. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  101967. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  101968. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  101969. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  101970. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  101971. };
  101972. /***********************************************************************
  101973. *
  101974. * Private class method prototypes
  101975. *
  101976. ***********************************************************************/
  101977. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  101978. static void free_(FLAC__StreamEncoder *encoder);
  101979. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  101980. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  101981. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  101982. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  101983. #if FLAC__HAS_OGG
  101984. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  101985. #endif
  101986. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  101987. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  101988. static FLAC__bool process_subframe_(
  101989. FLAC__StreamEncoder *encoder,
  101990. unsigned min_partition_order,
  101991. unsigned max_partition_order,
  101992. const FLAC__FrameHeader *frame_header,
  101993. unsigned subframe_bps,
  101994. const FLAC__int32 integer_signal[],
  101995. FLAC__Subframe *subframe[2],
  101996. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  101997. FLAC__int32 *residual[2],
  101998. unsigned *best_subframe,
  101999. unsigned *best_bits
  102000. );
  102001. static FLAC__bool add_subframe_(
  102002. FLAC__StreamEncoder *encoder,
  102003. unsigned blocksize,
  102004. unsigned subframe_bps,
  102005. const FLAC__Subframe *subframe,
  102006. FLAC__BitWriter *frame
  102007. );
  102008. static unsigned evaluate_constant_subframe_(
  102009. FLAC__StreamEncoder *encoder,
  102010. const FLAC__int32 signal,
  102011. unsigned blocksize,
  102012. unsigned subframe_bps,
  102013. FLAC__Subframe *subframe
  102014. );
  102015. static unsigned evaluate_fixed_subframe_(
  102016. FLAC__StreamEncoder *encoder,
  102017. const FLAC__int32 signal[],
  102018. FLAC__int32 residual[],
  102019. FLAC__uint64 abs_residual_partition_sums[],
  102020. unsigned raw_bits_per_partition[],
  102021. unsigned blocksize,
  102022. unsigned subframe_bps,
  102023. unsigned order,
  102024. unsigned rice_parameter,
  102025. unsigned rice_parameter_limit,
  102026. unsigned min_partition_order,
  102027. unsigned max_partition_order,
  102028. FLAC__bool do_escape_coding,
  102029. unsigned rice_parameter_search_dist,
  102030. FLAC__Subframe *subframe,
  102031. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102032. );
  102033. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102034. static unsigned evaluate_lpc_subframe_(
  102035. FLAC__StreamEncoder *encoder,
  102036. const FLAC__int32 signal[],
  102037. FLAC__int32 residual[],
  102038. FLAC__uint64 abs_residual_partition_sums[],
  102039. unsigned raw_bits_per_partition[],
  102040. const FLAC__real lp_coeff[],
  102041. unsigned blocksize,
  102042. unsigned subframe_bps,
  102043. unsigned order,
  102044. unsigned qlp_coeff_precision,
  102045. unsigned rice_parameter,
  102046. unsigned rice_parameter_limit,
  102047. unsigned min_partition_order,
  102048. unsigned max_partition_order,
  102049. FLAC__bool do_escape_coding,
  102050. unsigned rice_parameter_search_dist,
  102051. FLAC__Subframe *subframe,
  102052. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102053. );
  102054. #endif
  102055. static unsigned evaluate_verbatim_subframe_(
  102056. FLAC__StreamEncoder *encoder,
  102057. const FLAC__int32 signal[],
  102058. unsigned blocksize,
  102059. unsigned subframe_bps,
  102060. FLAC__Subframe *subframe
  102061. );
  102062. static unsigned find_best_partition_order_(
  102063. struct FLAC__StreamEncoderPrivate *private_,
  102064. const FLAC__int32 residual[],
  102065. FLAC__uint64 abs_residual_partition_sums[],
  102066. unsigned raw_bits_per_partition[],
  102067. unsigned residual_samples,
  102068. unsigned predictor_order,
  102069. unsigned rice_parameter,
  102070. unsigned rice_parameter_limit,
  102071. unsigned min_partition_order,
  102072. unsigned max_partition_order,
  102073. unsigned bps,
  102074. FLAC__bool do_escape_coding,
  102075. unsigned rice_parameter_search_dist,
  102076. FLAC__EntropyCodingMethod *best_ecm
  102077. );
  102078. static void precompute_partition_info_sums_(
  102079. const FLAC__int32 residual[],
  102080. FLAC__uint64 abs_residual_partition_sums[],
  102081. unsigned residual_samples,
  102082. unsigned predictor_order,
  102083. unsigned min_partition_order,
  102084. unsigned max_partition_order,
  102085. unsigned bps
  102086. );
  102087. static void precompute_partition_info_escapes_(
  102088. const FLAC__int32 residual[],
  102089. unsigned raw_bits_per_partition[],
  102090. unsigned residual_samples,
  102091. unsigned predictor_order,
  102092. unsigned min_partition_order,
  102093. unsigned max_partition_order
  102094. );
  102095. static FLAC__bool set_partitioned_rice_(
  102096. #ifdef EXACT_RICE_BITS_CALCULATION
  102097. const FLAC__int32 residual[],
  102098. #endif
  102099. const FLAC__uint64 abs_residual_partition_sums[],
  102100. const unsigned raw_bits_per_partition[],
  102101. const unsigned residual_samples,
  102102. const unsigned predictor_order,
  102103. const unsigned suggested_rice_parameter,
  102104. const unsigned rice_parameter_limit,
  102105. const unsigned rice_parameter_search_dist,
  102106. const unsigned partition_order,
  102107. const FLAC__bool search_for_escapes,
  102108. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102109. unsigned *bits
  102110. );
  102111. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102112. /* verify-related routines: */
  102113. static void append_to_verify_fifo_(
  102114. verify_input_fifo *fifo,
  102115. const FLAC__int32 * const input[],
  102116. unsigned input_offset,
  102117. unsigned channels,
  102118. unsigned wide_samples
  102119. );
  102120. static void append_to_verify_fifo_interleaved_(
  102121. verify_input_fifo *fifo,
  102122. const FLAC__int32 input[],
  102123. unsigned input_offset,
  102124. unsigned channels,
  102125. unsigned wide_samples
  102126. );
  102127. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102128. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102129. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102130. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102131. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102132. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102133. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102134. 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);
  102135. static FILE *get_binary_stdout_(void);
  102136. /***********************************************************************
  102137. *
  102138. * Private class data
  102139. *
  102140. ***********************************************************************/
  102141. typedef struct FLAC__StreamEncoderPrivate {
  102142. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102143. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102144. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102145. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102146. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102147. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102148. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102149. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102150. #endif
  102151. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102152. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102153. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102154. FLAC__int32 *residual_workspace_mid_side[2][2];
  102155. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102156. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102157. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102158. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102159. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102160. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102161. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102162. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102163. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102164. unsigned best_subframe_mid_side[2];
  102165. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102166. unsigned best_subframe_bits_mid_side[2];
  102167. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102168. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102169. FLAC__BitWriter *frame; /* the current frame being worked on */
  102170. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102171. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102172. FLAC__ChannelAssignment last_channel_assignment;
  102173. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102174. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102175. unsigned current_sample_number;
  102176. unsigned current_frame_number;
  102177. FLAC__MD5Context md5context;
  102178. FLAC__CPUInfo cpuinfo;
  102179. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102180. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102181. #else
  102182. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102183. #endif
  102184. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102185. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102186. 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[]);
  102187. 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[]);
  102188. 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[]);
  102189. #endif
  102190. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102191. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102192. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102193. FLAC__bool disable_constant_subframes;
  102194. FLAC__bool disable_fixed_subframes;
  102195. FLAC__bool disable_verbatim_subframes;
  102196. #if FLAC__HAS_OGG
  102197. FLAC__bool is_ogg;
  102198. #endif
  102199. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102200. FLAC__StreamEncoderSeekCallback seek_callback;
  102201. FLAC__StreamEncoderTellCallback tell_callback;
  102202. FLAC__StreamEncoderWriteCallback write_callback;
  102203. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102204. FLAC__StreamEncoderProgressCallback progress_callback;
  102205. void *client_data;
  102206. unsigned first_seekpoint_to_check;
  102207. FILE *file; /* only used when encoding to a file */
  102208. FLAC__uint64 bytes_written;
  102209. FLAC__uint64 samples_written;
  102210. unsigned frames_written;
  102211. unsigned total_frames_estimate;
  102212. /* unaligned (original) pointers to allocated data */
  102213. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102214. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102215. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102216. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102217. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102218. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102219. FLAC__real *windowed_signal_unaligned;
  102220. #endif
  102221. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102222. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102223. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102224. unsigned *raw_bits_per_partition_unaligned;
  102225. /*
  102226. * These fields have been moved here from private function local
  102227. * declarations merely to save stack space during encoding.
  102228. */
  102229. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102230. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102231. #endif
  102232. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102233. /*
  102234. * The data for the verify section
  102235. */
  102236. struct {
  102237. FLAC__StreamDecoder *decoder;
  102238. EncoderStateHint state_hint;
  102239. FLAC__bool needs_magic_hack;
  102240. verify_input_fifo input_fifo;
  102241. verify_output output;
  102242. struct {
  102243. FLAC__uint64 absolute_sample;
  102244. unsigned frame_number;
  102245. unsigned channel;
  102246. unsigned sample;
  102247. FLAC__int32 expected;
  102248. FLAC__int32 got;
  102249. } error_stats;
  102250. } verify;
  102251. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102252. } FLAC__StreamEncoderPrivate;
  102253. /***********************************************************************
  102254. *
  102255. * Public static class data
  102256. *
  102257. ***********************************************************************/
  102258. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102259. "FLAC__STREAM_ENCODER_OK",
  102260. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102261. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102262. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102263. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102264. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102265. "FLAC__STREAM_ENCODER_IO_ERROR",
  102266. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102267. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102268. };
  102269. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102270. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102271. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102272. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102273. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102274. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102275. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102276. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102277. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102278. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102279. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102280. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102281. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102282. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102283. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102284. };
  102285. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102286. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102287. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102288. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102289. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102290. };
  102291. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102292. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102293. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102294. };
  102295. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102296. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102297. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102298. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102299. };
  102300. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102301. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102302. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102303. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102304. };
  102305. /* Number of samples that will be overread to watch for end of stream. By
  102306. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102307. * always try to read blocksize+1 samples before encoding a block, so that
  102308. * even if the stream has a total sample count that is an integral multiple
  102309. * of the blocksize, we will still notice when we are encoding the last
  102310. * block. This is needed, for example, to correctly set the end-of-stream
  102311. * marker in Ogg FLAC.
  102312. *
  102313. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102314. * not really any reason to change it.
  102315. */
  102316. static const unsigned OVERREAD_ = 1;
  102317. /***********************************************************************
  102318. *
  102319. * Class constructor/destructor
  102320. *
  102321. */
  102322. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102323. {
  102324. FLAC__StreamEncoder *encoder;
  102325. unsigned i;
  102326. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102327. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102328. if(encoder == 0) {
  102329. return 0;
  102330. }
  102331. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102332. if(encoder->protected_ == 0) {
  102333. free(encoder);
  102334. return 0;
  102335. }
  102336. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102337. if(encoder->private_ == 0) {
  102338. free(encoder->protected_);
  102339. free(encoder);
  102340. return 0;
  102341. }
  102342. encoder->private_->frame = FLAC__bitwriter_new();
  102343. if(encoder->private_->frame == 0) {
  102344. free(encoder->private_);
  102345. free(encoder->protected_);
  102346. free(encoder);
  102347. return 0;
  102348. }
  102349. encoder->private_->file = 0;
  102350. set_defaults_enc(encoder);
  102351. encoder->private_->is_being_deleted = false;
  102352. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102353. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102354. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102355. }
  102356. for(i = 0; i < 2; i++) {
  102357. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102358. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102359. }
  102360. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102361. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102362. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102363. }
  102364. for(i = 0; i < 2; i++) {
  102365. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102366. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102367. }
  102368. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102369. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102370. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102371. }
  102372. for(i = 0; i < 2; i++) {
  102373. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102374. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102375. }
  102376. for(i = 0; i < 2; i++)
  102377. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102378. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102379. return encoder;
  102380. }
  102381. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102382. {
  102383. unsigned i;
  102384. FLAC__ASSERT(0 != encoder);
  102385. FLAC__ASSERT(0 != encoder->protected_);
  102386. FLAC__ASSERT(0 != encoder->private_);
  102387. FLAC__ASSERT(0 != encoder->private_->frame);
  102388. encoder->private_->is_being_deleted = true;
  102389. (void)FLAC__stream_encoder_finish(encoder);
  102390. if(0 != encoder->private_->verify.decoder)
  102391. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102392. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102393. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102394. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102395. }
  102396. for(i = 0; i < 2; i++) {
  102397. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102398. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102399. }
  102400. for(i = 0; i < 2; i++)
  102401. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102402. FLAC__bitwriter_delete(encoder->private_->frame);
  102403. free(encoder->private_);
  102404. free(encoder->protected_);
  102405. free(encoder);
  102406. }
  102407. /***********************************************************************
  102408. *
  102409. * Public class methods
  102410. *
  102411. ***********************************************************************/
  102412. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102413. FLAC__StreamEncoder *encoder,
  102414. FLAC__StreamEncoderReadCallback read_callback,
  102415. FLAC__StreamEncoderWriteCallback write_callback,
  102416. FLAC__StreamEncoderSeekCallback seek_callback,
  102417. FLAC__StreamEncoderTellCallback tell_callback,
  102418. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102419. void *client_data,
  102420. FLAC__bool is_ogg
  102421. )
  102422. {
  102423. unsigned i;
  102424. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102425. FLAC__ASSERT(0 != encoder);
  102426. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102427. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102428. #if !FLAC__HAS_OGG
  102429. if(is_ogg)
  102430. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102431. #endif
  102432. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102433. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102434. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102435. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102436. if(encoder->protected_->channels != 2) {
  102437. encoder->protected_->do_mid_side_stereo = false;
  102438. encoder->protected_->loose_mid_side_stereo = false;
  102439. }
  102440. else if(!encoder->protected_->do_mid_side_stereo)
  102441. encoder->protected_->loose_mid_side_stereo = false;
  102442. if(encoder->protected_->bits_per_sample >= 32)
  102443. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102444. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102445. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102446. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102447. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102448. if(encoder->protected_->blocksize == 0) {
  102449. if(encoder->protected_->max_lpc_order == 0)
  102450. encoder->protected_->blocksize = 1152;
  102451. else
  102452. encoder->protected_->blocksize = 4096;
  102453. }
  102454. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102455. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102456. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102457. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102458. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102459. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102460. if(encoder->protected_->qlp_coeff_precision == 0) {
  102461. if(encoder->protected_->bits_per_sample < 16) {
  102462. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102463. /* @@@ until then we'll make a guess */
  102464. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102465. }
  102466. else if(encoder->protected_->bits_per_sample == 16) {
  102467. if(encoder->protected_->blocksize <= 192)
  102468. encoder->protected_->qlp_coeff_precision = 7;
  102469. else if(encoder->protected_->blocksize <= 384)
  102470. encoder->protected_->qlp_coeff_precision = 8;
  102471. else if(encoder->protected_->blocksize <= 576)
  102472. encoder->protected_->qlp_coeff_precision = 9;
  102473. else if(encoder->protected_->blocksize <= 1152)
  102474. encoder->protected_->qlp_coeff_precision = 10;
  102475. else if(encoder->protected_->blocksize <= 2304)
  102476. encoder->protected_->qlp_coeff_precision = 11;
  102477. else if(encoder->protected_->blocksize <= 4608)
  102478. encoder->protected_->qlp_coeff_precision = 12;
  102479. else
  102480. encoder->protected_->qlp_coeff_precision = 13;
  102481. }
  102482. else {
  102483. if(encoder->protected_->blocksize <= 384)
  102484. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102485. else if(encoder->protected_->blocksize <= 1152)
  102486. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102487. else
  102488. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102489. }
  102490. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102491. }
  102492. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102493. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102494. if(encoder->protected_->streamable_subset) {
  102495. if(
  102496. encoder->protected_->blocksize != 192 &&
  102497. encoder->protected_->blocksize != 576 &&
  102498. encoder->protected_->blocksize != 1152 &&
  102499. encoder->protected_->blocksize != 2304 &&
  102500. encoder->protected_->blocksize != 4608 &&
  102501. encoder->protected_->blocksize != 256 &&
  102502. encoder->protected_->blocksize != 512 &&
  102503. encoder->protected_->blocksize != 1024 &&
  102504. encoder->protected_->blocksize != 2048 &&
  102505. encoder->protected_->blocksize != 4096 &&
  102506. encoder->protected_->blocksize != 8192 &&
  102507. encoder->protected_->blocksize != 16384
  102508. )
  102509. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102510. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  102511. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102512. if(
  102513. encoder->protected_->bits_per_sample != 8 &&
  102514. encoder->protected_->bits_per_sample != 12 &&
  102515. encoder->protected_->bits_per_sample != 16 &&
  102516. encoder->protected_->bits_per_sample != 20 &&
  102517. encoder->protected_->bits_per_sample != 24
  102518. )
  102519. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102520. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  102521. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102522. if(
  102523. encoder->protected_->sample_rate <= 48000 &&
  102524. (
  102525. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  102526. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  102527. )
  102528. ) {
  102529. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102530. }
  102531. }
  102532. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102533. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  102534. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  102535. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  102536. #if FLAC__HAS_OGG
  102537. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  102538. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  102539. unsigned i;
  102540. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  102541. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102542. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  102543. for( ; i > 0; i--)
  102544. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  102545. encoder->protected_->metadata[0] = vc;
  102546. break;
  102547. }
  102548. }
  102549. }
  102550. #endif
  102551. /* keep track of any SEEKTABLE block */
  102552. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  102553. unsigned i;
  102554. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102555. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102556. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  102557. break; /* take only the first one */
  102558. }
  102559. }
  102560. }
  102561. /* validate metadata */
  102562. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  102563. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102564. metadata_has_seektable = false;
  102565. metadata_has_vorbis_comment = false;
  102566. metadata_picture_has_type1 = false;
  102567. metadata_picture_has_type2 = false;
  102568. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102569. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  102570. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  102571. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102572. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102573. if(metadata_has_seektable) /* only one is allowed */
  102574. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102575. metadata_has_seektable = true;
  102576. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  102577. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102578. }
  102579. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102580. if(metadata_has_vorbis_comment) /* only one is allowed */
  102581. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102582. metadata_has_vorbis_comment = true;
  102583. }
  102584. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  102585. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  102586. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102587. }
  102588. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  102589. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  102590. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102591. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  102592. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  102593. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102594. metadata_picture_has_type1 = true;
  102595. /* standard icon must be 32x32 pixel PNG */
  102596. if(
  102597. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  102598. (
  102599. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  102600. m->data.picture.width != 32 ||
  102601. m->data.picture.height != 32
  102602. )
  102603. )
  102604. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102605. }
  102606. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  102607. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  102608. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102609. metadata_picture_has_type2 = true;
  102610. }
  102611. }
  102612. }
  102613. encoder->private_->input_capacity = 0;
  102614. for(i = 0; i < encoder->protected_->channels; i++) {
  102615. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  102616. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102617. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  102618. #endif
  102619. }
  102620. for(i = 0; i < 2; i++) {
  102621. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  102622. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102623. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  102624. #endif
  102625. }
  102626. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102627. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  102628. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  102629. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  102630. #endif
  102631. for(i = 0; i < encoder->protected_->channels; i++) {
  102632. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  102633. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  102634. encoder->private_->best_subframe[i] = 0;
  102635. }
  102636. for(i = 0; i < 2; i++) {
  102637. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  102638. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  102639. encoder->private_->best_subframe_mid_side[i] = 0;
  102640. }
  102641. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  102642. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  102643. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102644. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  102645. #else
  102646. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  102647. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  102648. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  102649. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  102650. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  102651. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  102652. 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);
  102653. #endif
  102654. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  102655. encoder->private_->loose_mid_side_stereo_frames = 1;
  102656. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  102657. encoder->private_->current_sample_number = 0;
  102658. encoder->private_->current_frame_number = 0;
  102659. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  102660. 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? */
  102661. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  102662. /*
  102663. * get the CPU info and set the function pointers
  102664. */
  102665. FLAC__cpu_info(&encoder->private_->cpuinfo);
  102666. /* first default to the non-asm routines */
  102667. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102668. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  102669. #endif
  102670. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  102671. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102672. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102673. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  102674. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102675. #endif
  102676. /* now override with asm where appropriate */
  102677. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102678. # ifndef FLAC__NO_ASM
  102679. if(encoder->private_->cpuinfo.use_asm) {
  102680. # ifdef FLAC__CPU_IA32
  102681. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  102682. # ifdef FLAC__HAS_NASM
  102683. if(encoder->private_->cpuinfo.data.ia32.sse) {
  102684. if(encoder->protected_->max_lpc_order < 4)
  102685. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  102686. else if(encoder->protected_->max_lpc_order < 8)
  102687. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  102688. else if(encoder->protected_->max_lpc_order < 12)
  102689. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  102690. else
  102691. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102692. }
  102693. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  102694. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  102695. else
  102696. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102697. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  102698. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102699. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  102700. }
  102701. else {
  102702. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102703. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102704. }
  102705. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  102706. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  102707. # endif /* FLAC__HAS_NASM */
  102708. # endif /* FLAC__CPU_IA32 */
  102709. }
  102710. # endif /* !FLAC__NO_ASM */
  102711. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  102712. /* finally override based on wide-ness if necessary */
  102713. if(encoder->private_->use_wide_by_block) {
  102714. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  102715. }
  102716. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  102717. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  102718. #if FLAC__HAS_OGG
  102719. encoder->private_->is_ogg = is_ogg;
  102720. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  102721. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  102722. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102723. }
  102724. #endif
  102725. encoder->private_->read_callback = read_callback;
  102726. encoder->private_->write_callback = write_callback;
  102727. encoder->private_->seek_callback = seek_callback;
  102728. encoder->private_->tell_callback = tell_callback;
  102729. encoder->private_->metadata_callback = metadata_callback;
  102730. encoder->private_->client_data = client_data;
  102731. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  102732. /* the above function sets the state for us in case of an error */
  102733. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102734. }
  102735. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  102736. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102737. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102738. }
  102739. /*
  102740. * Set up the verify stuff if necessary
  102741. */
  102742. if(encoder->protected_->verify) {
  102743. /*
  102744. * First, set up the fifo which will hold the
  102745. * original signal to compare against
  102746. */
  102747. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  102748. for(i = 0; i < encoder->protected_->channels; i++) {
  102749. 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))) {
  102750. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102751. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102752. }
  102753. }
  102754. encoder->private_->verify.input_fifo.tail = 0;
  102755. /*
  102756. * Now set up a stream decoder for verification
  102757. */
  102758. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  102759. if(0 == encoder->private_->verify.decoder) {
  102760. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102761. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102762. }
  102763. 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) {
  102764. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102765. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102766. }
  102767. }
  102768. encoder->private_->verify.error_stats.absolute_sample = 0;
  102769. encoder->private_->verify.error_stats.frame_number = 0;
  102770. encoder->private_->verify.error_stats.channel = 0;
  102771. encoder->private_->verify.error_stats.sample = 0;
  102772. encoder->private_->verify.error_stats.expected = 0;
  102773. encoder->private_->verify.error_stats.got = 0;
  102774. /*
  102775. * These must be done before we write any metadata, because that
  102776. * calls the write_callback, which uses these values.
  102777. */
  102778. encoder->private_->first_seekpoint_to_check = 0;
  102779. encoder->private_->samples_written = 0;
  102780. encoder->protected_->streaminfo_offset = 0;
  102781. encoder->protected_->seektable_offset = 0;
  102782. encoder->protected_->audio_offset = 0;
  102783. /*
  102784. * write the stream header
  102785. */
  102786. if(encoder->protected_->verify)
  102787. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  102788. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  102789. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102790. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102791. }
  102792. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102793. /* the above function sets the state for us in case of an error */
  102794. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102795. }
  102796. /*
  102797. * write the STREAMINFO metadata block
  102798. */
  102799. if(encoder->protected_->verify)
  102800. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  102801. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  102802. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  102803. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  102804. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  102805. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  102806. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  102807. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  102808. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  102809. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  102810. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  102811. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  102812. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  102813. if(encoder->protected_->do_md5)
  102814. FLAC__MD5Init(&encoder->private_->md5context);
  102815. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  102816. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102817. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102818. }
  102819. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102820. /* the above function sets the state for us in case of an error */
  102821. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102822. }
  102823. /*
  102824. * Now that the STREAMINFO block is written, we can init this to an
  102825. * absurdly-high value...
  102826. */
  102827. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  102828. /* ... and clear this to 0 */
  102829. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  102830. /*
  102831. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  102832. * if not, we will write an empty one (FLAC__add_metadata_block()
  102833. * automatically supplies the vendor string).
  102834. *
  102835. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  102836. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  102837. * true it will have already insured that the metadata list is properly
  102838. * ordered.)
  102839. */
  102840. if(!metadata_has_vorbis_comment) {
  102841. FLAC__StreamMetadata vorbis_comment;
  102842. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  102843. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  102844. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  102845. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  102846. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  102847. vorbis_comment.data.vorbis_comment.num_comments = 0;
  102848. vorbis_comment.data.vorbis_comment.comments = 0;
  102849. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  102850. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102851. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102852. }
  102853. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102854. /* the above function sets the state for us in case of an error */
  102855. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102856. }
  102857. }
  102858. /*
  102859. * write the user's metadata blocks
  102860. */
  102861. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102862. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  102863. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  102864. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102865. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102866. }
  102867. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102868. /* the above function sets the state for us in case of an error */
  102869. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102870. }
  102871. }
  102872. /* now that all the metadata is written, we save the stream offset */
  102873. 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 */
  102874. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  102875. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102876. }
  102877. if(encoder->protected_->verify)
  102878. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  102879. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  102880. }
  102881. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  102882. FLAC__StreamEncoder *encoder,
  102883. FLAC__StreamEncoderWriteCallback write_callback,
  102884. FLAC__StreamEncoderSeekCallback seek_callback,
  102885. FLAC__StreamEncoderTellCallback tell_callback,
  102886. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102887. void *client_data
  102888. )
  102889. {
  102890. return init_stream_internal_enc(
  102891. encoder,
  102892. /*read_callback=*/0,
  102893. write_callback,
  102894. seek_callback,
  102895. tell_callback,
  102896. metadata_callback,
  102897. client_data,
  102898. /*is_ogg=*/false
  102899. );
  102900. }
  102901. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  102902. FLAC__StreamEncoder *encoder,
  102903. FLAC__StreamEncoderReadCallback read_callback,
  102904. FLAC__StreamEncoderWriteCallback write_callback,
  102905. FLAC__StreamEncoderSeekCallback seek_callback,
  102906. FLAC__StreamEncoderTellCallback tell_callback,
  102907. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102908. void *client_data
  102909. )
  102910. {
  102911. return init_stream_internal_enc(
  102912. encoder,
  102913. read_callback,
  102914. write_callback,
  102915. seek_callback,
  102916. tell_callback,
  102917. metadata_callback,
  102918. client_data,
  102919. /*is_ogg=*/true
  102920. );
  102921. }
  102922. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  102923. FLAC__StreamEncoder *encoder,
  102924. FILE *file,
  102925. FLAC__StreamEncoderProgressCallback progress_callback,
  102926. void *client_data,
  102927. FLAC__bool is_ogg
  102928. )
  102929. {
  102930. FLAC__StreamEncoderInitStatus init_status;
  102931. FLAC__ASSERT(0 != encoder);
  102932. FLAC__ASSERT(0 != file);
  102933. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102934. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102935. /* double protection */
  102936. if(file == 0) {
  102937. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  102938. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102939. }
  102940. /*
  102941. * To make sure that our file does not go unclosed after an error, we
  102942. * must assign the FILE pointer before any further error can occur in
  102943. * this routine.
  102944. */
  102945. if(file == stdout)
  102946. file = get_binary_stdout_(); /* just to be safe */
  102947. encoder->private_->file = file;
  102948. encoder->private_->progress_callback = progress_callback;
  102949. encoder->private_->bytes_written = 0;
  102950. encoder->private_->samples_written = 0;
  102951. encoder->private_->frames_written = 0;
  102952. init_status = init_stream_internal_enc(
  102953. encoder,
  102954. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  102955. file_write_callback_,
  102956. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  102957. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  102958. /*metadata_callback=*/0,
  102959. client_data,
  102960. is_ogg
  102961. );
  102962. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  102963. /* the above function sets the state for us in case of an error */
  102964. return init_status;
  102965. }
  102966. {
  102967. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  102968. FLAC__ASSERT(blocksize != 0);
  102969. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  102970. }
  102971. return init_status;
  102972. }
  102973. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  102974. FLAC__StreamEncoder *encoder,
  102975. FILE *file,
  102976. FLAC__StreamEncoderProgressCallback progress_callback,
  102977. void *client_data
  102978. )
  102979. {
  102980. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  102981. }
  102982. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  102983. FLAC__StreamEncoder *encoder,
  102984. FILE *file,
  102985. FLAC__StreamEncoderProgressCallback progress_callback,
  102986. void *client_data
  102987. )
  102988. {
  102989. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  102990. }
  102991. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  102992. FLAC__StreamEncoder *encoder,
  102993. const char *filename,
  102994. FLAC__StreamEncoderProgressCallback progress_callback,
  102995. void *client_data,
  102996. FLAC__bool is_ogg
  102997. )
  102998. {
  102999. FILE *file;
  103000. FLAC__ASSERT(0 != encoder);
  103001. /*
  103002. * To make sure that our file does not go unclosed after an error, we
  103003. * have to do the same entrance checks here that are later performed
  103004. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  103005. */
  103006. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103007. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103008. file = filename? fopen(filename, "w+b") : stdout;
  103009. if(file == 0) {
  103010. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103011. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103012. }
  103013. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  103014. }
  103015. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  103016. FLAC__StreamEncoder *encoder,
  103017. const char *filename,
  103018. FLAC__StreamEncoderProgressCallback progress_callback,
  103019. void *client_data
  103020. )
  103021. {
  103022. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103023. }
  103024. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103025. FLAC__StreamEncoder *encoder,
  103026. const char *filename,
  103027. FLAC__StreamEncoderProgressCallback progress_callback,
  103028. void *client_data
  103029. )
  103030. {
  103031. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103032. }
  103033. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103034. {
  103035. FLAC__bool error = false;
  103036. FLAC__ASSERT(0 != encoder);
  103037. FLAC__ASSERT(0 != encoder->private_);
  103038. FLAC__ASSERT(0 != encoder->protected_);
  103039. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  103040. return true;
  103041. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103042. if(encoder->private_->current_sample_number != 0) {
  103043. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103044. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103045. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103046. error = true;
  103047. }
  103048. }
  103049. if(encoder->protected_->do_md5)
  103050. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103051. if(!encoder->private_->is_being_deleted) {
  103052. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103053. if(encoder->private_->seek_callback) {
  103054. #if FLAC__HAS_OGG
  103055. if(encoder->private_->is_ogg)
  103056. update_ogg_metadata_(encoder);
  103057. else
  103058. #endif
  103059. update_metadata_(encoder);
  103060. /* check if an error occurred while updating metadata */
  103061. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103062. error = true;
  103063. }
  103064. if(encoder->private_->metadata_callback)
  103065. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103066. }
  103067. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103068. if(!error)
  103069. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103070. error = true;
  103071. }
  103072. }
  103073. if(0 != encoder->private_->file) {
  103074. if(encoder->private_->file != stdout)
  103075. fclose(encoder->private_->file);
  103076. encoder->private_->file = 0;
  103077. }
  103078. #if FLAC__HAS_OGG
  103079. if(encoder->private_->is_ogg)
  103080. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103081. #endif
  103082. free_(encoder);
  103083. set_defaults_enc(encoder);
  103084. if(!error)
  103085. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103086. return !error;
  103087. }
  103088. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103089. {
  103090. FLAC__ASSERT(0 != encoder);
  103091. FLAC__ASSERT(0 != encoder->private_);
  103092. FLAC__ASSERT(0 != encoder->protected_);
  103093. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103094. return false;
  103095. #if FLAC__HAS_OGG
  103096. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103097. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103098. return true;
  103099. #else
  103100. (void)value;
  103101. return false;
  103102. #endif
  103103. }
  103104. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103105. {
  103106. FLAC__ASSERT(0 != encoder);
  103107. FLAC__ASSERT(0 != encoder->private_);
  103108. FLAC__ASSERT(0 != encoder->protected_);
  103109. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103110. return false;
  103111. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103112. encoder->protected_->verify = value;
  103113. #endif
  103114. return true;
  103115. }
  103116. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103117. {
  103118. FLAC__ASSERT(0 != encoder);
  103119. FLAC__ASSERT(0 != encoder->private_);
  103120. FLAC__ASSERT(0 != encoder->protected_);
  103121. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103122. return false;
  103123. encoder->protected_->streamable_subset = value;
  103124. return true;
  103125. }
  103126. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103127. {
  103128. FLAC__ASSERT(0 != encoder);
  103129. FLAC__ASSERT(0 != encoder->private_);
  103130. FLAC__ASSERT(0 != encoder->protected_);
  103131. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103132. return false;
  103133. encoder->protected_->do_md5 = value;
  103134. return true;
  103135. }
  103136. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  103137. {
  103138. FLAC__ASSERT(0 != encoder);
  103139. FLAC__ASSERT(0 != encoder->private_);
  103140. FLAC__ASSERT(0 != encoder->protected_);
  103141. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103142. return false;
  103143. encoder->protected_->channels = value;
  103144. return true;
  103145. }
  103146. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103147. {
  103148. FLAC__ASSERT(0 != encoder);
  103149. FLAC__ASSERT(0 != encoder->private_);
  103150. FLAC__ASSERT(0 != encoder->protected_);
  103151. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103152. return false;
  103153. encoder->protected_->bits_per_sample = value;
  103154. return true;
  103155. }
  103156. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103157. {
  103158. FLAC__ASSERT(0 != encoder);
  103159. FLAC__ASSERT(0 != encoder->private_);
  103160. FLAC__ASSERT(0 != encoder->protected_);
  103161. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103162. return false;
  103163. encoder->protected_->sample_rate = value;
  103164. return true;
  103165. }
  103166. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103167. {
  103168. FLAC__bool ok = true;
  103169. FLAC__ASSERT(0 != encoder);
  103170. FLAC__ASSERT(0 != encoder->private_);
  103171. FLAC__ASSERT(0 != encoder->protected_);
  103172. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103173. return false;
  103174. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103175. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103176. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103177. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103178. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103179. #if 0
  103180. /* was: */
  103181. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103182. /* but it's too hard to specify the string in a locale-specific way */
  103183. #else
  103184. encoder->protected_->num_apodizations = 1;
  103185. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103186. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103187. #endif
  103188. #endif
  103189. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103190. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103191. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103192. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103193. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103194. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103195. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103196. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103197. return ok;
  103198. }
  103199. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103200. {
  103201. FLAC__ASSERT(0 != encoder);
  103202. FLAC__ASSERT(0 != encoder->private_);
  103203. FLAC__ASSERT(0 != encoder->protected_);
  103204. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103205. return false;
  103206. encoder->protected_->blocksize = value;
  103207. return true;
  103208. }
  103209. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103210. {
  103211. FLAC__ASSERT(0 != encoder);
  103212. FLAC__ASSERT(0 != encoder->private_);
  103213. FLAC__ASSERT(0 != encoder->protected_);
  103214. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103215. return false;
  103216. encoder->protected_->do_mid_side_stereo = value;
  103217. return true;
  103218. }
  103219. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103220. {
  103221. FLAC__ASSERT(0 != encoder);
  103222. FLAC__ASSERT(0 != encoder->private_);
  103223. FLAC__ASSERT(0 != encoder->protected_);
  103224. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103225. return false;
  103226. encoder->protected_->loose_mid_side_stereo = value;
  103227. return true;
  103228. }
  103229. /*@@@@add to tests*/
  103230. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103231. {
  103232. FLAC__ASSERT(0 != encoder);
  103233. FLAC__ASSERT(0 != encoder->private_);
  103234. FLAC__ASSERT(0 != encoder->protected_);
  103235. FLAC__ASSERT(0 != specification);
  103236. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103237. return false;
  103238. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103239. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103240. #else
  103241. encoder->protected_->num_apodizations = 0;
  103242. while(1) {
  103243. const char *s = strchr(specification, ';');
  103244. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103245. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103246. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103247. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103248. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103249. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103250. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103251. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103252. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103253. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103254. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103255. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103256. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103257. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103258. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103259. if (stddev > 0.0 && stddev <= 0.5) {
  103260. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103261. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103262. }
  103263. }
  103264. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103265. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103266. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103267. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103268. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103269. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103270. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103271. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103272. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103273. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103274. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103275. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103276. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103277. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103278. if (p >= 0.0 && p <= 1.0) {
  103279. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103280. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103281. }
  103282. }
  103283. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103284. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103285. if (encoder->protected_->num_apodizations == 32)
  103286. break;
  103287. if (s)
  103288. specification = s+1;
  103289. else
  103290. break;
  103291. }
  103292. if(encoder->protected_->num_apodizations == 0) {
  103293. encoder->protected_->num_apodizations = 1;
  103294. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103295. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103296. }
  103297. #endif
  103298. return true;
  103299. }
  103300. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103301. {
  103302. FLAC__ASSERT(0 != encoder);
  103303. FLAC__ASSERT(0 != encoder->private_);
  103304. FLAC__ASSERT(0 != encoder->protected_);
  103305. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103306. return false;
  103307. encoder->protected_->max_lpc_order = value;
  103308. return true;
  103309. }
  103310. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103311. {
  103312. FLAC__ASSERT(0 != encoder);
  103313. FLAC__ASSERT(0 != encoder->private_);
  103314. FLAC__ASSERT(0 != encoder->protected_);
  103315. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103316. return false;
  103317. encoder->protected_->qlp_coeff_precision = value;
  103318. return true;
  103319. }
  103320. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103321. {
  103322. FLAC__ASSERT(0 != encoder);
  103323. FLAC__ASSERT(0 != encoder->private_);
  103324. FLAC__ASSERT(0 != encoder->protected_);
  103325. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103326. return false;
  103327. encoder->protected_->do_qlp_coeff_prec_search = value;
  103328. return true;
  103329. }
  103330. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103331. {
  103332. FLAC__ASSERT(0 != encoder);
  103333. FLAC__ASSERT(0 != encoder->private_);
  103334. FLAC__ASSERT(0 != encoder->protected_);
  103335. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103336. return false;
  103337. #if 0
  103338. /*@@@ deprecated: */
  103339. encoder->protected_->do_escape_coding = value;
  103340. #else
  103341. (void)value;
  103342. #endif
  103343. return true;
  103344. }
  103345. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103346. {
  103347. FLAC__ASSERT(0 != encoder);
  103348. FLAC__ASSERT(0 != encoder->private_);
  103349. FLAC__ASSERT(0 != encoder->protected_);
  103350. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103351. return false;
  103352. encoder->protected_->do_exhaustive_model_search = value;
  103353. return true;
  103354. }
  103355. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103356. {
  103357. FLAC__ASSERT(0 != encoder);
  103358. FLAC__ASSERT(0 != encoder->private_);
  103359. FLAC__ASSERT(0 != encoder->protected_);
  103360. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103361. return false;
  103362. encoder->protected_->min_residual_partition_order = value;
  103363. return true;
  103364. }
  103365. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103366. {
  103367. FLAC__ASSERT(0 != encoder);
  103368. FLAC__ASSERT(0 != encoder->private_);
  103369. FLAC__ASSERT(0 != encoder->protected_);
  103370. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103371. return false;
  103372. encoder->protected_->max_residual_partition_order = value;
  103373. return true;
  103374. }
  103375. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103376. {
  103377. FLAC__ASSERT(0 != encoder);
  103378. FLAC__ASSERT(0 != encoder->private_);
  103379. FLAC__ASSERT(0 != encoder->protected_);
  103380. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103381. return false;
  103382. #if 0
  103383. /*@@@ deprecated: */
  103384. encoder->protected_->rice_parameter_search_dist = value;
  103385. #else
  103386. (void)value;
  103387. #endif
  103388. return true;
  103389. }
  103390. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103391. {
  103392. FLAC__ASSERT(0 != encoder);
  103393. FLAC__ASSERT(0 != encoder->private_);
  103394. FLAC__ASSERT(0 != encoder->protected_);
  103395. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103396. return false;
  103397. encoder->protected_->total_samples_estimate = value;
  103398. return true;
  103399. }
  103400. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103401. {
  103402. FLAC__ASSERT(0 != encoder);
  103403. FLAC__ASSERT(0 != encoder->private_);
  103404. FLAC__ASSERT(0 != encoder->protected_);
  103405. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103406. return false;
  103407. if(0 == metadata)
  103408. num_blocks = 0;
  103409. if(0 == num_blocks)
  103410. metadata = 0;
  103411. /* realloc() does not do exactly what we want so... */
  103412. if(encoder->protected_->metadata) {
  103413. free(encoder->protected_->metadata);
  103414. encoder->protected_->metadata = 0;
  103415. encoder->protected_->num_metadata_blocks = 0;
  103416. }
  103417. if(num_blocks) {
  103418. FLAC__StreamMetadata **m;
  103419. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103420. return false;
  103421. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103422. encoder->protected_->metadata = m;
  103423. encoder->protected_->num_metadata_blocks = num_blocks;
  103424. }
  103425. #if FLAC__HAS_OGG
  103426. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103427. return false;
  103428. #endif
  103429. return true;
  103430. }
  103431. /*
  103432. * These three functions are not static, but not publically exposed in
  103433. * include/FLAC/ either. They are used by the test suite.
  103434. */
  103435. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103436. {
  103437. FLAC__ASSERT(0 != encoder);
  103438. FLAC__ASSERT(0 != encoder->private_);
  103439. FLAC__ASSERT(0 != encoder->protected_);
  103440. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103441. return false;
  103442. encoder->private_->disable_constant_subframes = value;
  103443. return true;
  103444. }
  103445. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103446. {
  103447. FLAC__ASSERT(0 != encoder);
  103448. FLAC__ASSERT(0 != encoder->private_);
  103449. FLAC__ASSERT(0 != encoder->protected_);
  103450. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103451. return false;
  103452. encoder->private_->disable_fixed_subframes = value;
  103453. return true;
  103454. }
  103455. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103456. {
  103457. FLAC__ASSERT(0 != encoder);
  103458. FLAC__ASSERT(0 != encoder->private_);
  103459. FLAC__ASSERT(0 != encoder->protected_);
  103460. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103461. return false;
  103462. encoder->private_->disable_verbatim_subframes = value;
  103463. return true;
  103464. }
  103465. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103466. {
  103467. FLAC__ASSERT(0 != encoder);
  103468. FLAC__ASSERT(0 != encoder->private_);
  103469. FLAC__ASSERT(0 != encoder->protected_);
  103470. return encoder->protected_->state;
  103471. }
  103472. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103473. {
  103474. FLAC__ASSERT(0 != encoder);
  103475. FLAC__ASSERT(0 != encoder->private_);
  103476. FLAC__ASSERT(0 != encoder->protected_);
  103477. if(encoder->protected_->verify)
  103478. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103479. else
  103480. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103481. }
  103482. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  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_VERIFY_DECODER_ERROR)
  103488. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103489. else
  103490. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103491. }
  103492. 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)
  103493. {
  103494. FLAC__ASSERT(0 != encoder);
  103495. FLAC__ASSERT(0 != encoder->private_);
  103496. FLAC__ASSERT(0 != encoder->protected_);
  103497. if(0 != absolute_sample)
  103498. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  103499. if(0 != frame_number)
  103500. *frame_number = encoder->private_->verify.error_stats.frame_number;
  103501. if(0 != channel)
  103502. *channel = encoder->private_->verify.error_stats.channel;
  103503. if(0 != sample)
  103504. *sample = encoder->private_->verify.error_stats.sample;
  103505. if(0 != expected)
  103506. *expected = encoder->private_->verify.error_stats.expected;
  103507. if(0 != got)
  103508. *got = encoder->private_->verify.error_stats.got;
  103509. }
  103510. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  103511. {
  103512. FLAC__ASSERT(0 != encoder);
  103513. FLAC__ASSERT(0 != encoder->private_);
  103514. FLAC__ASSERT(0 != encoder->protected_);
  103515. return encoder->protected_->verify;
  103516. }
  103517. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  103518. {
  103519. FLAC__ASSERT(0 != encoder);
  103520. FLAC__ASSERT(0 != encoder->private_);
  103521. FLAC__ASSERT(0 != encoder->protected_);
  103522. return encoder->protected_->streamable_subset;
  103523. }
  103524. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  103525. {
  103526. FLAC__ASSERT(0 != encoder);
  103527. FLAC__ASSERT(0 != encoder->private_);
  103528. FLAC__ASSERT(0 != encoder->protected_);
  103529. return encoder->protected_->do_md5;
  103530. }
  103531. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  103532. {
  103533. FLAC__ASSERT(0 != encoder);
  103534. FLAC__ASSERT(0 != encoder->private_);
  103535. FLAC__ASSERT(0 != encoder->protected_);
  103536. return encoder->protected_->channels;
  103537. }
  103538. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  103539. {
  103540. FLAC__ASSERT(0 != encoder);
  103541. FLAC__ASSERT(0 != encoder->private_);
  103542. FLAC__ASSERT(0 != encoder->protected_);
  103543. return encoder->protected_->bits_per_sample;
  103544. }
  103545. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  103546. {
  103547. FLAC__ASSERT(0 != encoder);
  103548. FLAC__ASSERT(0 != encoder->private_);
  103549. FLAC__ASSERT(0 != encoder->protected_);
  103550. return encoder->protected_->sample_rate;
  103551. }
  103552. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  103553. {
  103554. FLAC__ASSERT(0 != encoder);
  103555. FLAC__ASSERT(0 != encoder->private_);
  103556. FLAC__ASSERT(0 != encoder->protected_);
  103557. return encoder->protected_->blocksize;
  103558. }
  103559. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103560. {
  103561. FLAC__ASSERT(0 != encoder);
  103562. FLAC__ASSERT(0 != encoder->private_);
  103563. FLAC__ASSERT(0 != encoder->protected_);
  103564. return encoder->protected_->do_mid_side_stereo;
  103565. }
  103566. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103567. {
  103568. FLAC__ASSERT(0 != encoder);
  103569. FLAC__ASSERT(0 != encoder->private_);
  103570. FLAC__ASSERT(0 != encoder->protected_);
  103571. return encoder->protected_->loose_mid_side_stereo;
  103572. }
  103573. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  103574. {
  103575. FLAC__ASSERT(0 != encoder);
  103576. FLAC__ASSERT(0 != encoder->private_);
  103577. FLAC__ASSERT(0 != encoder->protected_);
  103578. return encoder->protected_->max_lpc_order;
  103579. }
  103580. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  103581. {
  103582. FLAC__ASSERT(0 != encoder);
  103583. FLAC__ASSERT(0 != encoder->private_);
  103584. FLAC__ASSERT(0 != encoder->protected_);
  103585. return encoder->protected_->qlp_coeff_precision;
  103586. }
  103587. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  103588. {
  103589. FLAC__ASSERT(0 != encoder);
  103590. FLAC__ASSERT(0 != encoder->private_);
  103591. FLAC__ASSERT(0 != encoder->protected_);
  103592. return encoder->protected_->do_qlp_coeff_prec_search;
  103593. }
  103594. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  103595. {
  103596. FLAC__ASSERT(0 != encoder);
  103597. FLAC__ASSERT(0 != encoder->private_);
  103598. FLAC__ASSERT(0 != encoder->protected_);
  103599. return encoder->protected_->do_escape_coding;
  103600. }
  103601. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  103602. {
  103603. FLAC__ASSERT(0 != encoder);
  103604. FLAC__ASSERT(0 != encoder->private_);
  103605. FLAC__ASSERT(0 != encoder->protected_);
  103606. return encoder->protected_->do_exhaustive_model_search;
  103607. }
  103608. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103609. {
  103610. FLAC__ASSERT(0 != encoder);
  103611. FLAC__ASSERT(0 != encoder->private_);
  103612. FLAC__ASSERT(0 != encoder->protected_);
  103613. return encoder->protected_->min_residual_partition_order;
  103614. }
  103615. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103616. {
  103617. FLAC__ASSERT(0 != encoder);
  103618. FLAC__ASSERT(0 != encoder->private_);
  103619. FLAC__ASSERT(0 != encoder->protected_);
  103620. return encoder->protected_->max_residual_partition_order;
  103621. }
  103622. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  103623. {
  103624. FLAC__ASSERT(0 != encoder);
  103625. FLAC__ASSERT(0 != encoder->private_);
  103626. FLAC__ASSERT(0 != encoder->protected_);
  103627. return encoder->protected_->rice_parameter_search_dist;
  103628. }
  103629. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  103630. {
  103631. FLAC__ASSERT(0 != encoder);
  103632. FLAC__ASSERT(0 != encoder->private_);
  103633. FLAC__ASSERT(0 != encoder->protected_);
  103634. return encoder->protected_->total_samples_estimate;
  103635. }
  103636. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  103637. {
  103638. unsigned i, j = 0, channel;
  103639. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103640. FLAC__ASSERT(0 != encoder);
  103641. FLAC__ASSERT(0 != encoder->private_);
  103642. FLAC__ASSERT(0 != encoder->protected_);
  103643. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103644. do {
  103645. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  103646. if(encoder->protected_->verify)
  103647. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  103648. for(channel = 0; channel < channels; channel++)
  103649. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  103650. if(encoder->protected_->do_mid_side_stereo) {
  103651. FLAC__ASSERT(channels == 2);
  103652. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103653. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103654. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  103655. 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' ! */
  103656. }
  103657. }
  103658. else
  103659. j += n;
  103660. encoder->private_->current_sample_number += n;
  103661. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103662. if(encoder->private_->current_sample_number > blocksize) {
  103663. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  103664. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103665. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103666. return false;
  103667. /* move unprocessed overread samples to beginnings of arrays */
  103668. for(channel = 0; channel < channels; channel++)
  103669. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103670. if(encoder->protected_->do_mid_side_stereo) {
  103671. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103672. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103673. }
  103674. encoder->private_->current_sample_number = 1;
  103675. }
  103676. } while(j < samples);
  103677. return true;
  103678. }
  103679. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  103680. {
  103681. unsigned i, j, k, channel;
  103682. FLAC__int32 x, mid, side;
  103683. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103684. FLAC__ASSERT(0 != encoder);
  103685. FLAC__ASSERT(0 != encoder->private_);
  103686. FLAC__ASSERT(0 != encoder->protected_);
  103687. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103688. j = k = 0;
  103689. /*
  103690. * we have several flavors of the same basic loop, optimized for
  103691. * different conditions:
  103692. */
  103693. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  103694. /*
  103695. * stereo coding: unroll channel loop
  103696. */
  103697. do {
  103698. if(encoder->protected_->verify)
  103699. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103700. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103701. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103702. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  103703. x = buffer[k++];
  103704. encoder->private_->integer_signal[1][i] = x;
  103705. mid += x;
  103706. side -= x;
  103707. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  103708. encoder->private_->integer_signal_mid_side[1][i] = side;
  103709. encoder->private_->integer_signal_mid_side[0][i] = mid;
  103710. }
  103711. encoder->private_->current_sample_number = i;
  103712. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103713. if(i > blocksize) {
  103714. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103715. return false;
  103716. /* move unprocessed overread samples to beginnings of arrays */
  103717. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103718. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103719. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  103720. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  103721. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103722. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103723. encoder->private_->current_sample_number = 1;
  103724. }
  103725. } while(j < samples);
  103726. }
  103727. else {
  103728. /*
  103729. * independent channel coding: buffer each channel in inner loop
  103730. */
  103731. do {
  103732. if(encoder->protected_->verify)
  103733. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103734. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103735. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103736. for(channel = 0; channel < channels; channel++)
  103737. encoder->private_->integer_signal[channel][i] = buffer[k++];
  103738. }
  103739. encoder->private_->current_sample_number = i;
  103740. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103741. if(i > blocksize) {
  103742. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103743. return false;
  103744. /* move unprocessed overread samples to beginnings of arrays */
  103745. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103746. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103747. for(channel = 0; channel < channels; channel++)
  103748. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103749. encoder->private_->current_sample_number = 1;
  103750. }
  103751. } while(j < samples);
  103752. }
  103753. return true;
  103754. }
  103755. /***********************************************************************
  103756. *
  103757. * Private class methods
  103758. *
  103759. ***********************************************************************/
  103760. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  103761. {
  103762. FLAC__ASSERT(0 != encoder);
  103763. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103764. encoder->protected_->verify = true;
  103765. #else
  103766. encoder->protected_->verify = false;
  103767. #endif
  103768. encoder->protected_->streamable_subset = true;
  103769. encoder->protected_->do_md5 = true;
  103770. encoder->protected_->do_mid_side_stereo = false;
  103771. encoder->protected_->loose_mid_side_stereo = false;
  103772. encoder->protected_->channels = 2;
  103773. encoder->protected_->bits_per_sample = 16;
  103774. encoder->protected_->sample_rate = 44100;
  103775. encoder->protected_->blocksize = 0;
  103776. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103777. encoder->protected_->num_apodizations = 1;
  103778. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103779. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103780. #endif
  103781. encoder->protected_->max_lpc_order = 0;
  103782. encoder->protected_->qlp_coeff_precision = 0;
  103783. encoder->protected_->do_qlp_coeff_prec_search = false;
  103784. encoder->protected_->do_exhaustive_model_search = false;
  103785. encoder->protected_->do_escape_coding = false;
  103786. encoder->protected_->min_residual_partition_order = 0;
  103787. encoder->protected_->max_residual_partition_order = 0;
  103788. encoder->protected_->rice_parameter_search_dist = 0;
  103789. encoder->protected_->total_samples_estimate = 0;
  103790. encoder->protected_->metadata = 0;
  103791. encoder->protected_->num_metadata_blocks = 0;
  103792. encoder->private_->seek_table = 0;
  103793. encoder->private_->disable_constant_subframes = false;
  103794. encoder->private_->disable_fixed_subframes = false;
  103795. encoder->private_->disable_verbatim_subframes = false;
  103796. #if FLAC__HAS_OGG
  103797. encoder->private_->is_ogg = false;
  103798. #endif
  103799. encoder->private_->read_callback = 0;
  103800. encoder->private_->write_callback = 0;
  103801. encoder->private_->seek_callback = 0;
  103802. encoder->private_->tell_callback = 0;
  103803. encoder->private_->metadata_callback = 0;
  103804. encoder->private_->progress_callback = 0;
  103805. encoder->private_->client_data = 0;
  103806. #if FLAC__HAS_OGG
  103807. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  103808. #endif
  103809. }
  103810. void free_(FLAC__StreamEncoder *encoder)
  103811. {
  103812. unsigned i, channel;
  103813. FLAC__ASSERT(0 != encoder);
  103814. if(encoder->protected_->metadata) {
  103815. free(encoder->protected_->metadata);
  103816. encoder->protected_->metadata = 0;
  103817. encoder->protected_->num_metadata_blocks = 0;
  103818. }
  103819. for(i = 0; i < encoder->protected_->channels; i++) {
  103820. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  103821. free(encoder->private_->integer_signal_unaligned[i]);
  103822. encoder->private_->integer_signal_unaligned[i] = 0;
  103823. }
  103824. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103825. if(0 != encoder->private_->real_signal_unaligned[i]) {
  103826. free(encoder->private_->real_signal_unaligned[i]);
  103827. encoder->private_->real_signal_unaligned[i] = 0;
  103828. }
  103829. #endif
  103830. }
  103831. for(i = 0; i < 2; i++) {
  103832. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  103833. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  103834. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  103835. }
  103836. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103837. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  103838. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  103839. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  103840. }
  103841. #endif
  103842. }
  103843. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103844. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  103845. if(0 != encoder->private_->window_unaligned[i]) {
  103846. free(encoder->private_->window_unaligned[i]);
  103847. encoder->private_->window_unaligned[i] = 0;
  103848. }
  103849. }
  103850. if(0 != encoder->private_->windowed_signal_unaligned) {
  103851. free(encoder->private_->windowed_signal_unaligned);
  103852. encoder->private_->windowed_signal_unaligned = 0;
  103853. }
  103854. #endif
  103855. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  103856. for(i = 0; i < 2; i++) {
  103857. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  103858. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  103859. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  103860. }
  103861. }
  103862. }
  103863. for(channel = 0; channel < 2; channel++) {
  103864. for(i = 0; i < 2; i++) {
  103865. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  103866. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  103867. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  103868. }
  103869. }
  103870. }
  103871. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  103872. free(encoder->private_->abs_residual_partition_sums_unaligned);
  103873. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  103874. }
  103875. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  103876. free(encoder->private_->raw_bits_per_partition_unaligned);
  103877. encoder->private_->raw_bits_per_partition_unaligned = 0;
  103878. }
  103879. if(encoder->protected_->verify) {
  103880. for(i = 0; i < encoder->protected_->channels; i++) {
  103881. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  103882. free(encoder->private_->verify.input_fifo.data[i]);
  103883. encoder->private_->verify.input_fifo.data[i] = 0;
  103884. }
  103885. }
  103886. }
  103887. FLAC__bitwriter_free(encoder->private_->frame);
  103888. }
  103889. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  103890. {
  103891. FLAC__bool ok;
  103892. unsigned i, channel;
  103893. FLAC__ASSERT(new_blocksize > 0);
  103894. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103895. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  103896. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  103897. if(new_blocksize <= encoder->private_->input_capacity)
  103898. return true;
  103899. ok = true;
  103900. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  103901. * requires that the input arrays (in our case the integer signals)
  103902. * have a buffer of up to 3 zeroes in front (at negative indices) for
  103903. * alignment purposes; we use 4 in front to keep the data well-aligned.
  103904. */
  103905. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  103906. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  103907. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  103908. encoder->private_->integer_signal[i] += 4;
  103909. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103910. #if 0 /* @@@ currently unused */
  103911. if(encoder->protected_->max_lpc_order > 0)
  103912. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  103913. #endif
  103914. #endif
  103915. }
  103916. for(i = 0; ok && i < 2; i++) {
  103917. 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]);
  103918. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  103919. encoder->private_->integer_signal_mid_side[i] += 4;
  103920. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103921. #if 0 /* @@@ currently unused */
  103922. if(encoder->protected_->max_lpc_order > 0)
  103923. 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]);
  103924. #endif
  103925. #endif
  103926. }
  103927. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103928. if(ok && encoder->protected_->max_lpc_order > 0) {
  103929. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  103930. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  103931. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  103932. }
  103933. #endif
  103934. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  103935. for(i = 0; ok && i < 2; i++) {
  103936. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  103937. }
  103938. }
  103939. for(channel = 0; ok && channel < 2; channel++) {
  103940. for(i = 0; ok && i < 2; i++) {
  103941. 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]);
  103942. }
  103943. }
  103944. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  103945. /*@@@ 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) */
  103946. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  103947. if(encoder->protected_->do_escape_coding)
  103948. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  103949. /* now adjust the windows if the blocksize has changed */
  103950. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103951. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  103952. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  103953. switch(encoder->protected_->apodizations[i].type) {
  103954. case FLAC__APODIZATION_BARTLETT:
  103955. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  103956. break;
  103957. case FLAC__APODIZATION_BARTLETT_HANN:
  103958. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  103959. break;
  103960. case FLAC__APODIZATION_BLACKMAN:
  103961. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  103962. break;
  103963. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  103964. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  103965. break;
  103966. case FLAC__APODIZATION_CONNES:
  103967. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  103968. break;
  103969. case FLAC__APODIZATION_FLATTOP:
  103970. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  103971. break;
  103972. case FLAC__APODIZATION_GAUSS:
  103973. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  103974. break;
  103975. case FLAC__APODIZATION_HAMMING:
  103976. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  103977. break;
  103978. case FLAC__APODIZATION_HANN:
  103979. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103980. break;
  103981. case FLAC__APODIZATION_KAISER_BESSEL:
  103982. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  103983. break;
  103984. case FLAC__APODIZATION_NUTTALL:
  103985. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  103986. break;
  103987. case FLAC__APODIZATION_RECTANGLE:
  103988. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  103989. break;
  103990. case FLAC__APODIZATION_TRIANGLE:
  103991. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  103992. break;
  103993. case FLAC__APODIZATION_TUKEY:
  103994. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  103995. break;
  103996. case FLAC__APODIZATION_WELCH:
  103997. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  103998. break;
  103999. default:
  104000. FLAC__ASSERT(0);
  104001. /* double protection */
  104002. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104003. break;
  104004. }
  104005. }
  104006. }
  104007. #endif
  104008. if(ok)
  104009. encoder->private_->input_capacity = new_blocksize;
  104010. else
  104011. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104012. return ok;
  104013. }
  104014. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  104015. {
  104016. const FLAC__byte *buffer;
  104017. size_t bytes;
  104018. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104019. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104020. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104021. return false;
  104022. }
  104023. if(encoder->protected_->verify) {
  104024. encoder->private_->verify.output.data = buffer;
  104025. encoder->private_->verify.output.bytes = bytes;
  104026. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104027. encoder->private_->verify.needs_magic_hack = true;
  104028. }
  104029. else {
  104030. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104031. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104032. FLAC__bitwriter_clear(encoder->private_->frame);
  104033. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104034. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104035. return false;
  104036. }
  104037. }
  104038. }
  104039. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104040. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104041. FLAC__bitwriter_clear(encoder->private_->frame);
  104042. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104043. return false;
  104044. }
  104045. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104046. FLAC__bitwriter_clear(encoder->private_->frame);
  104047. if(samples > 0) {
  104048. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104049. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104050. }
  104051. return true;
  104052. }
  104053. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104054. {
  104055. FLAC__StreamEncoderWriteStatus status;
  104056. FLAC__uint64 output_position = 0;
  104057. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104058. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104059. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104060. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104061. }
  104062. /*
  104063. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104064. */
  104065. if(samples == 0) {
  104066. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104067. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104068. encoder->protected_->streaminfo_offset = output_position;
  104069. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104070. encoder->protected_->seektable_offset = output_position;
  104071. }
  104072. /*
  104073. * Mark the current seek point if hit (if audio_offset == 0 that
  104074. * means we're still writing metadata and haven't hit the first
  104075. * frame yet)
  104076. */
  104077. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104078. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104079. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104080. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104081. FLAC__uint64 test_sample;
  104082. unsigned i;
  104083. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104084. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104085. if(test_sample > frame_last_sample) {
  104086. break;
  104087. }
  104088. else if(test_sample >= frame_first_sample) {
  104089. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104090. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104091. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104092. encoder->private_->first_seekpoint_to_check++;
  104093. /* DO NOT: "break;" and here's why:
  104094. * The seektable template may contain more than one target
  104095. * sample for any given frame; we will keep looping, generating
  104096. * duplicate seekpoints for them, and we'll clean it up later,
  104097. * just before writing the seektable back to the metadata.
  104098. */
  104099. }
  104100. else {
  104101. encoder->private_->first_seekpoint_to_check++;
  104102. }
  104103. }
  104104. }
  104105. #if FLAC__HAS_OGG
  104106. if(encoder->private_->is_ogg) {
  104107. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104108. &encoder->protected_->ogg_encoder_aspect,
  104109. buffer,
  104110. bytes,
  104111. samples,
  104112. encoder->private_->current_frame_number,
  104113. is_last_block,
  104114. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104115. encoder,
  104116. encoder->private_->client_data
  104117. );
  104118. }
  104119. else
  104120. #endif
  104121. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104122. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104123. encoder->private_->bytes_written += bytes;
  104124. encoder->private_->samples_written += samples;
  104125. /* we keep a high watermark on the number of frames written because
  104126. * when the encoder goes back to write metadata, 'current_frame'
  104127. * will drop back to 0.
  104128. */
  104129. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104130. }
  104131. else
  104132. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104133. return status;
  104134. }
  104135. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104136. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104137. {
  104138. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104139. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104140. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104141. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104142. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104143. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104144. FLAC__StreamEncoderSeekStatus seek_status;
  104145. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104146. /* All this is based on intimate knowledge of the stream header
  104147. * layout, but a change to the header format that would break this
  104148. * would also break all streams encoded in the previous format.
  104149. */
  104150. /*
  104151. * Write MD5 signature
  104152. */
  104153. {
  104154. const unsigned md5_offset =
  104155. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104156. (
  104157. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104158. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104159. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104160. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104161. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104162. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104163. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104164. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104165. ) / 8;
  104166. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104167. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104168. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104169. return;
  104170. }
  104171. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104172. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104173. return;
  104174. }
  104175. }
  104176. /*
  104177. * Write total samples
  104178. */
  104179. {
  104180. const unsigned total_samples_byte_offset =
  104181. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104182. (
  104183. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104184. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104185. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104186. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104187. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104188. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104189. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104190. - 4
  104191. ) / 8;
  104192. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104193. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104194. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104195. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104196. b[4] = (FLAC__byte)(samples & 0xFF);
  104197. 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) {
  104198. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104199. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104200. return;
  104201. }
  104202. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104203. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104204. return;
  104205. }
  104206. }
  104207. /*
  104208. * Write min/max framesize
  104209. */
  104210. {
  104211. const unsigned min_framesize_offset =
  104212. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104213. (
  104214. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104215. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104216. ) / 8;
  104217. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104218. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104219. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104220. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104221. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104222. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104223. 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) {
  104224. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104225. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104226. return;
  104227. }
  104228. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104229. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104230. return;
  104231. }
  104232. }
  104233. /*
  104234. * Write seektable
  104235. */
  104236. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104237. unsigned i;
  104238. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104239. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104240. 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) {
  104241. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104242. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104243. return;
  104244. }
  104245. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104246. FLAC__uint64 xx;
  104247. unsigned x;
  104248. xx = encoder->private_->seek_table->points[i].sample_number;
  104249. b[7] = (FLAC__byte)xx; xx >>= 8;
  104250. b[6] = (FLAC__byte)xx; xx >>= 8;
  104251. b[5] = (FLAC__byte)xx; xx >>= 8;
  104252. b[4] = (FLAC__byte)xx; xx >>= 8;
  104253. b[3] = (FLAC__byte)xx; xx >>= 8;
  104254. b[2] = (FLAC__byte)xx; xx >>= 8;
  104255. b[1] = (FLAC__byte)xx; xx >>= 8;
  104256. b[0] = (FLAC__byte)xx; xx >>= 8;
  104257. xx = encoder->private_->seek_table->points[i].stream_offset;
  104258. b[15] = (FLAC__byte)xx; xx >>= 8;
  104259. b[14] = (FLAC__byte)xx; xx >>= 8;
  104260. b[13] = (FLAC__byte)xx; xx >>= 8;
  104261. b[12] = (FLAC__byte)xx; xx >>= 8;
  104262. b[11] = (FLAC__byte)xx; xx >>= 8;
  104263. b[10] = (FLAC__byte)xx; xx >>= 8;
  104264. b[9] = (FLAC__byte)xx; xx >>= 8;
  104265. b[8] = (FLAC__byte)xx; xx >>= 8;
  104266. x = encoder->private_->seek_table->points[i].frame_samples;
  104267. b[17] = (FLAC__byte)x; x >>= 8;
  104268. b[16] = (FLAC__byte)x; x >>= 8;
  104269. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104270. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104271. return;
  104272. }
  104273. }
  104274. }
  104275. }
  104276. #if FLAC__HAS_OGG
  104277. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104278. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104279. {
  104280. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104281. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104282. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104283. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104284. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104285. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104286. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104287. FLAC__STREAM_SYNC_LENGTH
  104288. ;
  104289. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104290. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104291. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104292. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104293. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104294. ogg_page page;
  104295. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104296. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104297. /* Pre-check that client supports seeking, since we don't want the
  104298. * ogg_helper code to ever have to deal with this condition.
  104299. */
  104300. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104301. return;
  104302. /* All this is based on intimate knowledge of the stream header
  104303. * layout, but a change to the header format that would break this
  104304. * would also break all streams encoded in the previous format.
  104305. */
  104306. /**
  104307. ** Write STREAMINFO stats
  104308. **/
  104309. simple_ogg_page__init(&page);
  104310. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104311. simple_ogg_page__clear(&page);
  104312. return; /* state already set */
  104313. }
  104314. /*
  104315. * Write MD5 signature
  104316. */
  104317. {
  104318. const unsigned md5_offset =
  104319. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104320. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104321. (
  104322. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104323. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104324. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104325. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104326. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104327. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104328. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104329. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104330. ) / 8;
  104331. if(md5_offset + 16 > (unsigned)page.body_len) {
  104332. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104333. simple_ogg_page__clear(&page);
  104334. return;
  104335. }
  104336. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104337. }
  104338. /*
  104339. * Write total samples
  104340. */
  104341. {
  104342. const unsigned total_samples_byte_offset =
  104343. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104344. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104345. (
  104346. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104347. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104348. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104349. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104350. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104351. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104352. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104353. - 4
  104354. ) / 8;
  104355. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104356. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104357. simple_ogg_page__clear(&page);
  104358. return;
  104359. }
  104360. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104361. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104362. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104363. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104364. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104365. b[4] = (FLAC__byte)(samples & 0xFF);
  104366. memcpy(page.body + total_samples_byte_offset, b, 5);
  104367. }
  104368. /*
  104369. * Write min/max framesize
  104370. */
  104371. {
  104372. const unsigned min_framesize_offset =
  104373. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104374. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104375. (
  104376. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104377. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104378. ) / 8;
  104379. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104380. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104381. simple_ogg_page__clear(&page);
  104382. return;
  104383. }
  104384. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104385. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104386. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104387. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104388. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104389. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104390. memcpy(page.body + min_framesize_offset, b, 6);
  104391. }
  104392. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104393. simple_ogg_page__clear(&page);
  104394. return; /* state already set */
  104395. }
  104396. simple_ogg_page__clear(&page);
  104397. /*
  104398. * Write seektable
  104399. */
  104400. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104401. unsigned i;
  104402. FLAC__byte *p;
  104403. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104404. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104405. simple_ogg_page__init(&page);
  104406. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104407. simple_ogg_page__clear(&page);
  104408. return; /* state already set */
  104409. }
  104410. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104411. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104412. simple_ogg_page__clear(&page);
  104413. return;
  104414. }
  104415. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104416. FLAC__uint64 xx;
  104417. unsigned x;
  104418. xx = encoder->private_->seek_table->points[i].sample_number;
  104419. b[7] = (FLAC__byte)xx; xx >>= 8;
  104420. b[6] = (FLAC__byte)xx; xx >>= 8;
  104421. b[5] = (FLAC__byte)xx; xx >>= 8;
  104422. b[4] = (FLAC__byte)xx; xx >>= 8;
  104423. b[3] = (FLAC__byte)xx; xx >>= 8;
  104424. b[2] = (FLAC__byte)xx; xx >>= 8;
  104425. b[1] = (FLAC__byte)xx; xx >>= 8;
  104426. b[0] = (FLAC__byte)xx; xx >>= 8;
  104427. xx = encoder->private_->seek_table->points[i].stream_offset;
  104428. b[15] = (FLAC__byte)xx; xx >>= 8;
  104429. b[14] = (FLAC__byte)xx; xx >>= 8;
  104430. b[13] = (FLAC__byte)xx; xx >>= 8;
  104431. b[12] = (FLAC__byte)xx; xx >>= 8;
  104432. b[11] = (FLAC__byte)xx; xx >>= 8;
  104433. b[10] = (FLAC__byte)xx; xx >>= 8;
  104434. b[9] = (FLAC__byte)xx; xx >>= 8;
  104435. b[8] = (FLAC__byte)xx; xx >>= 8;
  104436. x = encoder->private_->seek_table->points[i].frame_samples;
  104437. b[17] = (FLAC__byte)x; x >>= 8;
  104438. b[16] = (FLAC__byte)x; x >>= 8;
  104439. memcpy(p, b, 18);
  104440. }
  104441. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104442. simple_ogg_page__clear(&page);
  104443. return; /* state already set */
  104444. }
  104445. simple_ogg_page__clear(&page);
  104446. }
  104447. }
  104448. #endif
  104449. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104450. {
  104451. FLAC__uint16 crc;
  104452. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104453. /*
  104454. * Accumulate raw signal to the MD5 signature
  104455. */
  104456. 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)) {
  104457. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104458. return false;
  104459. }
  104460. /*
  104461. * Process the frame header and subframes into the frame bitbuffer
  104462. */
  104463. if(!process_subframes_(encoder, is_fractional_block)) {
  104464. /* the above function sets the state for us in case of an error */
  104465. return false;
  104466. }
  104467. /*
  104468. * Zero-pad the frame to a byte_boundary
  104469. */
  104470. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104471. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104472. return false;
  104473. }
  104474. /*
  104475. * CRC-16 the whole thing
  104476. */
  104477. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104478. if(
  104479. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104480. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104481. ) {
  104482. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104483. return false;
  104484. }
  104485. /*
  104486. * Write it
  104487. */
  104488. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104489. /* the above function sets the state for us in case of an error */
  104490. return false;
  104491. }
  104492. /*
  104493. * Get ready for the next frame
  104494. */
  104495. encoder->private_->current_sample_number = 0;
  104496. encoder->private_->current_frame_number++;
  104497. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  104498. return true;
  104499. }
  104500. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  104501. {
  104502. FLAC__FrameHeader frame_header;
  104503. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  104504. FLAC__bool do_independent, do_mid_side;
  104505. /*
  104506. * Calculate the min,max Rice partition orders
  104507. */
  104508. if(is_fractional_block) {
  104509. max_partition_order = 0;
  104510. }
  104511. else {
  104512. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  104513. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  104514. }
  104515. min_partition_order = min(min_partition_order, max_partition_order);
  104516. /*
  104517. * Setup the frame
  104518. */
  104519. frame_header.blocksize = encoder->protected_->blocksize;
  104520. frame_header.sample_rate = encoder->protected_->sample_rate;
  104521. frame_header.channels = encoder->protected_->channels;
  104522. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  104523. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  104524. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  104525. frame_header.number.frame_number = encoder->private_->current_frame_number;
  104526. /*
  104527. * Figure out what channel assignments to try
  104528. */
  104529. if(encoder->protected_->do_mid_side_stereo) {
  104530. if(encoder->protected_->loose_mid_side_stereo) {
  104531. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  104532. do_independent = true;
  104533. do_mid_side = true;
  104534. }
  104535. else {
  104536. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  104537. do_mid_side = !do_independent;
  104538. }
  104539. }
  104540. else {
  104541. do_independent = true;
  104542. do_mid_side = true;
  104543. }
  104544. }
  104545. else {
  104546. do_independent = true;
  104547. do_mid_side = false;
  104548. }
  104549. FLAC__ASSERT(do_independent || do_mid_side);
  104550. /*
  104551. * Check for wasted bits; set effective bps for each subframe
  104552. */
  104553. if(do_independent) {
  104554. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104555. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  104556. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  104557. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  104558. }
  104559. }
  104560. if(do_mid_side) {
  104561. FLAC__ASSERT(encoder->protected_->channels == 2);
  104562. for(channel = 0; channel < 2; channel++) {
  104563. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  104564. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  104565. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  104566. }
  104567. }
  104568. /*
  104569. * First do a normal encoding pass of each independent channel
  104570. */
  104571. if(do_independent) {
  104572. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104573. if(!
  104574. process_subframe_(
  104575. encoder,
  104576. min_partition_order,
  104577. max_partition_order,
  104578. &frame_header,
  104579. encoder->private_->subframe_bps[channel],
  104580. encoder->private_->integer_signal[channel],
  104581. encoder->private_->subframe_workspace_ptr[channel],
  104582. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  104583. encoder->private_->residual_workspace[channel],
  104584. encoder->private_->best_subframe+channel,
  104585. encoder->private_->best_subframe_bits+channel
  104586. )
  104587. )
  104588. return false;
  104589. }
  104590. }
  104591. /*
  104592. * Now do mid and side channels if requested
  104593. */
  104594. if(do_mid_side) {
  104595. FLAC__ASSERT(encoder->protected_->channels == 2);
  104596. for(channel = 0; channel < 2; channel++) {
  104597. if(!
  104598. process_subframe_(
  104599. encoder,
  104600. min_partition_order,
  104601. max_partition_order,
  104602. &frame_header,
  104603. encoder->private_->subframe_bps_mid_side[channel],
  104604. encoder->private_->integer_signal_mid_side[channel],
  104605. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  104606. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  104607. encoder->private_->residual_workspace_mid_side[channel],
  104608. encoder->private_->best_subframe_mid_side+channel,
  104609. encoder->private_->best_subframe_bits_mid_side+channel
  104610. )
  104611. )
  104612. return false;
  104613. }
  104614. }
  104615. /*
  104616. * Compose the frame bitbuffer
  104617. */
  104618. if(do_mid_side) {
  104619. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  104620. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  104621. FLAC__ChannelAssignment channel_assignment;
  104622. FLAC__ASSERT(encoder->protected_->channels == 2);
  104623. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  104624. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  104625. }
  104626. else {
  104627. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  104628. unsigned min_bits;
  104629. int ca;
  104630. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  104631. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  104632. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  104633. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  104634. FLAC__ASSERT(do_independent && do_mid_side);
  104635. /* We have to figure out which channel assignent results in the smallest frame */
  104636. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  104637. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  104638. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  104639. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  104640. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  104641. min_bits = bits[channel_assignment];
  104642. for(ca = 1; ca <= 3; ca++) {
  104643. if(bits[ca] < min_bits) {
  104644. min_bits = bits[ca];
  104645. channel_assignment = (FLAC__ChannelAssignment)ca;
  104646. }
  104647. }
  104648. }
  104649. frame_header.channel_assignment = channel_assignment;
  104650. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104651. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104652. return false;
  104653. }
  104654. switch(channel_assignment) {
  104655. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104656. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104657. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104658. break;
  104659. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104660. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104661. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104662. break;
  104663. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104664. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104665. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104666. break;
  104667. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104668. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  104669. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104670. break;
  104671. default:
  104672. FLAC__ASSERT(0);
  104673. }
  104674. switch(channel_assignment) {
  104675. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104676. left_bps = encoder->private_->subframe_bps [0];
  104677. right_bps = encoder->private_->subframe_bps [1];
  104678. break;
  104679. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104680. left_bps = encoder->private_->subframe_bps [0];
  104681. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104682. break;
  104683. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104684. left_bps = encoder->private_->subframe_bps_mid_side[1];
  104685. right_bps = encoder->private_->subframe_bps [1];
  104686. break;
  104687. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104688. left_bps = encoder->private_->subframe_bps_mid_side[0];
  104689. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104690. break;
  104691. default:
  104692. FLAC__ASSERT(0);
  104693. }
  104694. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  104695. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  104696. return false;
  104697. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  104698. return false;
  104699. }
  104700. else {
  104701. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104702. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104703. return false;
  104704. }
  104705. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104706. 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)) {
  104707. /* the above function sets the state for us in case of an error */
  104708. return false;
  104709. }
  104710. }
  104711. }
  104712. if(encoder->protected_->loose_mid_side_stereo) {
  104713. encoder->private_->loose_mid_side_stereo_frame_count++;
  104714. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  104715. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  104716. }
  104717. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  104718. return true;
  104719. }
  104720. FLAC__bool process_subframe_(
  104721. FLAC__StreamEncoder *encoder,
  104722. unsigned min_partition_order,
  104723. unsigned max_partition_order,
  104724. const FLAC__FrameHeader *frame_header,
  104725. unsigned subframe_bps,
  104726. const FLAC__int32 integer_signal[],
  104727. FLAC__Subframe *subframe[2],
  104728. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  104729. FLAC__int32 *residual[2],
  104730. unsigned *best_subframe,
  104731. unsigned *best_bits
  104732. )
  104733. {
  104734. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104735. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104736. #else
  104737. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104738. #endif
  104739. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104740. FLAC__double lpc_residual_bits_per_sample;
  104741. 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 */
  104742. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  104743. unsigned min_lpc_order, max_lpc_order, lpc_order;
  104744. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  104745. #endif
  104746. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  104747. unsigned rice_parameter;
  104748. unsigned _candidate_bits, _best_bits;
  104749. unsigned _best_subframe;
  104750. /* only use RICE2 partitions if stream bps > 16 */
  104751. 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;
  104752. FLAC__ASSERT(frame_header->blocksize > 0);
  104753. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  104754. _best_subframe = 0;
  104755. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  104756. _best_bits = UINT_MAX;
  104757. else
  104758. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104759. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  104760. unsigned signal_is_constant = false;
  104761. 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);
  104762. /* check for constant subframe */
  104763. if(
  104764. !encoder->private_->disable_constant_subframes &&
  104765. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104766. fixed_residual_bits_per_sample[1] == 0.0
  104767. #else
  104768. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  104769. #endif
  104770. ) {
  104771. /* the above means it's possible all samples are the same value; now double-check it: */
  104772. unsigned i;
  104773. signal_is_constant = true;
  104774. for(i = 1; i < frame_header->blocksize; i++) {
  104775. if(integer_signal[0] != integer_signal[i]) {
  104776. signal_is_constant = false;
  104777. break;
  104778. }
  104779. }
  104780. }
  104781. if(signal_is_constant) {
  104782. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  104783. if(_candidate_bits < _best_bits) {
  104784. _best_subframe = !_best_subframe;
  104785. _best_bits = _candidate_bits;
  104786. }
  104787. }
  104788. else {
  104789. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  104790. /* encode fixed */
  104791. if(encoder->protected_->do_exhaustive_model_search) {
  104792. min_fixed_order = 0;
  104793. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  104794. }
  104795. else {
  104796. min_fixed_order = max_fixed_order = guess_fixed_order;
  104797. }
  104798. if(max_fixed_order >= frame_header->blocksize)
  104799. max_fixed_order = frame_header->blocksize - 1;
  104800. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  104801. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104802. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  104803. continue; /* don't even try */
  104804. 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 */
  104805. #else
  104806. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  104807. continue; /* don't even try */
  104808. 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 */
  104809. #endif
  104810. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104811. if(rice_parameter >= rice_parameter_limit) {
  104812. #ifdef DEBUG_VERBOSE
  104813. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  104814. #endif
  104815. rice_parameter = rice_parameter_limit - 1;
  104816. }
  104817. _candidate_bits =
  104818. evaluate_fixed_subframe_(
  104819. encoder,
  104820. integer_signal,
  104821. residual[!_best_subframe],
  104822. encoder->private_->abs_residual_partition_sums,
  104823. encoder->private_->raw_bits_per_partition,
  104824. frame_header->blocksize,
  104825. subframe_bps,
  104826. fixed_order,
  104827. rice_parameter,
  104828. rice_parameter_limit,
  104829. min_partition_order,
  104830. max_partition_order,
  104831. encoder->protected_->do_escape_coding,
  104832. encoder->protected_->rice_parameter_search_dist,
  104833. subframe[!_best_subframe],
  104834. partitioned_rice_contents[!_best_subframe]
  104835. );
  104836. if(_candidate_bits < _best_bits) {
  104837. _best_subframe = !_best_subframe;
  104838. _best_bits = _candidate_bits;
  104839. }
  104840. }
  104841. }
  104842. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104843. /* encode lpc */
  104844. if(encoder->protected_->max_lpc_order > 0) {
  104845. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  104846. max_lpc_order = frame_header->blocksize-1;
  104847. else
  104848. max_lpc_order = encoder->protected_->max_lpc_order;
  104849. if(max_lpc_order > 0) {
  104850. unsigned a;
  104851. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  104852. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  104853. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  104854. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  104855. if(autoc[0] != 0.0) {
  104856. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  104857. if(encoder->protected_->do_exhaustive_model_search) {
  104858. min_lpc_order = 1;
  104859. }
  104860. else {
  104861. const unsigned guess_lpc_order =
  104862. FLAC__lpc_compute_best_order(
  104863. lpc_error,
  104864. max_lpc_order,
  104865. frame_header->blocksize,
  104866. subframe_bps + (
  104867. encoder->protected_->do_qlp_coeff_prec_search?
  104868. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  104869. encoder->protected_->qlp_coeff_precision
  104870. )
  104871. );
  104872. min_lpc_order = max_lpc_order = guess_lpc_order;
  104873. }
  104874. if(max_lpc_order >= frame_header->blocksize)
  104875. max_lpc_order = frame_header->blocksize - 1;
  104876. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  104877. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  104878. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  104879. continue; /* don't even try */
  104880. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  104881. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104882. if(rice_parameter >= rice_parameter_limit) {
  104883. #ifdef DEBUG_VERBOSE
  104884. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  104885. #endif
  104886. rice_parameter = rice_parameter_limit - 1;
  104887. }
  104888. if(encoder->protected_->do_qlp_coeff_prec_search) {
  104889. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  104890. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  104891. if(subframe_bps <= 17) {
  104892. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  104893. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  104894. }
  104895. else
  104896. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  104897. }
  104898. else {
  104899. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  104900. }
  104901. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  104902. _candidate_bits =
  104903. evaluate_lpc_subframe_(
  104904. encoder,
  104905. integer_signal,
  104906. residual[!_best_subframe],
  104907. encoder->private_->abs_residual_partition_sums,
  104908. encoder->private_->raw_bits_per_partition,
  104909. encoder->private_->lp_coeff[lpc_order-1],
  104910. frame_header->blocksize,
  104911. subframe_bps,
  104912. lpc_order,
  104913. qlp_coeff_precision,
  104914. rice_parameter,
  104915. rice_parameter_limit,
  104916. min_partition_order,
  104917. max_partition_order,
  104918. encoder->protected_->do_escape_coding,
  104919. encoder->protected_->rice_parameter_search_dist,
  104920. subframe[!_best_subframe],
  104921. partitioned_rice_contents[!_best_subframe]
  104922. );
  104923. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  104924. if(_candidate_bits < _best_bits) {
  104925. _best_subframe = !_best_subframe;
  104926. _best_bits = _candidate_bits;
  104927. }
  104928. }
  104929. }
  104930. }
  104931. }
  104932. }
  104933. }
  104934. }
  104935. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  104936. }
  104937. }
  104938. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  104939. if(_best_bits == UINT_MAX) {
  104940. FLAC__ASSERT(_best_subframe == 0);
  104941. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104942. }
  104943. *best_subframe = _best_subframe;
  104944. *best_bits = _best_bits;
  104945. return true;
  104946. }
  104947. FLAC__bool add_subframe_(
  104948. FLAC__StreamEncoder *encoder,
  104949. unsigned blocksize,
  104950. unsigned subframe_bps,
  104951. const FLAC__Subframe *subframe,
  104952. FLAC__BitWriter *frame
  104953. )
  104954. {
  104955. switch(subframe->type) {
  104956. case FLAC__SUBFRAME_TYPE_CONSTANT:
  104957. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  104958. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104959. return false;
  104960. }
  104961. break;
  104962. case FLAC__SUBFRAME_TYPE_FIXED:
  104963. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  104964. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104965. return false;
  104966. }
  104967. break;
  104968. case FLAC__SUBFRAME_TYPE_LPC:
  104969. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  104970. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104971. return false;
  104972. }
  104973. break;
  104974. case FLAC__SUBFRAME_TYPE_VERBATIM:
  104975. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  104976. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104977. return false;
  104978. }
  104979. break;
  104980. default:
  104981. FLAC__ASSERT(0);
  104982. }
  104983. return true;
  104984. }
  104985. #define SPOTCHECK_ESTIMATE 0
  104986. #if SPOTCHECK_ESTIMATE
  104987. static void spotcheck_subframe_estimate_(
  104988. FLAC__StreamEncoder *encoder,
  104989. unsigned blocksize,
  104990. unsigned subframe_bps,
  104991. const FLAC__Subframe *subframe,
  104992. unsigned estimate
  104993. )
  104994. {
  104995. FLAC__bool ret;
  104996. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  104997. if(frame == 0) {
  104998. fprintf(stderr, "EST: can't allocate frame\n");
  104999. return;
  105000. }
  105001. if(!FLAC__bitwriter_init(frame)) {
  105002. fprintf(stderr, "EST: can't init frame\n");
  105003. return;
  105004. }
  105005. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  105006. FLAC__ASSERT(ret);
  105007. {
  105008. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  105009. if(estimate != actual)
  105010. 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);
  105011. }
  105012. FLAC__bitwriter_delete(frame);
  105013. }
  105014. #endif
  105015. unsigned evaluate_constant_subframe_(
  105016. FLAC__StreamEncoder *encoder,
  105017. const FLAC__int32 signal,
  105018. unsigned blocksize,
  105019. unsigned subframe_bps,
  105020. FLAC__Subframe *subframe
  105021. )
  105022. {
  105023. unsigned estimate;
  105024. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105025. subframe->data.constant.value = signal;
  105026. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105027. #if SPOTCHECK_ESTIMATE
  105028. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105029. #else
  105030. (void)encoder, (void)blocksize;
  105031. #endif
  105032. return estimate;
  105033. }
  105034. unsigned evaluate_fixed_subframe_(
  105035. FLAC__StreamEncoder *encoder,
  105036. const FLAC__int32 signal[],
  105037. FLAC__int32 residual[],
  105038. FLAC__uint64 abs_residual_partition_sums[],
  105039. unsigned raw_bits_per_partition[],
  105040. unsigned blocksize,
  105041. unsigned subframe_bps,
  105042. unsigned order,
  105043. unsigned rice_parameter,
  105044. unsigned rice_parameter_limit,
  105045. unsigned min_partition_order,
  105046. unsigned max_partition_order,
  105047. FLAC__bool do_escape_coding,
  105048. unsigned rice_parameter_search_dist,
  105049. FLAC__Subframe *subframe,
  105050. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105051. )
  105052. {
  105053. unsigned i, residual_bits, estimate;
  105054. const unsigned residual_samples = blocksize - order;
  105055. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105056. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105057. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105058. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105059. subframe->data.fixed.residual = residual;
  105060. residual_bits =
  105061. find_best_partition_order_(
  105062. encoder->private_,
  105063. residual,
  105064. abs_residual_partition_sums,
  105065. raw_bits_per_partition,
  105066. residual_samples,
  105067. order,
  105068. rice_parameter,
  105069. rice_parameter_limit,
  105070. min_partition_order,
  105071. max_partition_order,
  105072. subframe_bps,
  105073. do_escape_coding,
  105074. rice_parameter_search_dist,
  105075. &subframe->data.fixed.entropy_coding_method
  105076. );
  105077. subframe->data.fixed.order = order;
  105078. for(i = 0; i < order; i++)
  105079. subframe->data.fixed.warmup[i] = signal[i];
  105080. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105081. #if SPOTCHECK_ESTIMATE
  105082. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105083. #endif
  105084. return estimate;
  105085. }
  105086. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105087. unsigned evaluate_lpc_subframe_(
  105088. FLAC__StreamEncoder *encoder,
  105089. const FLAC__int32 signal[],
  105090. FLAC__int32 residual[],
  105091. FLAC__uint64 abs_residual_partition_sums[],
  105092. unsigned raw_bits_per_partition[],
  105093. const FLAC__real lp_coeff[],
  105094. unsigned blocksize,
  105095. unsigned subframe_bps,
  105096. unsigned order,
  105097. unsigned qlp_coeff_precision,
  105098. unsigned rice_parameter,
  105099. unsigned rice_parameter_limit,
  105100. unsigned min_partition_order,
  105101. unsigned max_partition_order,
  105102. FLAC__bool do_escape_coding,
  105103. unsigned rice_parameter_search_dist,
  105104. FLAC__Subframe *subframe,
  105105. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105106. )
  105107. {
  105108. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105109. unsigned i, residual_bits, estimate;
  105110. int quantization, ret;
  105111. const unsigned residual_samples = blocksize - order;
  105112. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105113. if(subframe_bps <= 16) {
  105114. FLAC__ASSERT(order > 0);
  105115. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105116. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105117. }
  105118. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105119. if(ret != 0)
  105120. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105121. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105122. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105123. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105124. else
  105125. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105126. else
  105127. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105128. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105129. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105130. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105131. subframe->data.lpc.residual = residual;
  105132. residual_bits =
  105133. find_best_partition_order_(
  105134. encoder->private_,
  105135. residual,
  105136. abs_residual_partition_sums,
  105137. raw_bits_per_partition,
  105138. residual_samples,
  105139. order,
  105140. rice_parameter,
  105141. rice_parameter_limit,
  105142. min_partition_order,
  105143. max_partition_order,
  105144. subframe_bps,
  105145. do_escape_coding,
  105146. rice_parameter_search_dist,
  105147. &subframe->data.lpc.entropy_coding_method
  105148. );
  105149. subframe->data.lpc.order = order;
  105150. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105151. subframe->data.lpc.quantization_level = quantization;
  105152. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105153. for(i = 0; i < order; i++)
  105154. subframe->data.lpc.warmup[i] = signal[i];
  105155. 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;
  105156. #if SPOTCHECK_ESTIMATE
  105157. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105158. #endif
  105159. return estimate;
  105160. }
  105161. #endif
  105162. unsigned evaluate_verbatim_subframe_(
  105163. FLAC__StreamEncoder *encoder,
  105164. const FLAC__int32 signal[],
  105165. unsigned blocksize,
  105166. unsigned subframe_bps,
  105167. FLAC__Subframe *subframe
  105168. )
  105169. {
  105170. unsigned estimate;
  105171. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105172. subframe->data.verbatim.data = signal;
  105173. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105174. #if SPOTCHECK_ESTIMATE
  105175. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105176. #else
  105177. (void)encoder;
  105178. #endif
  105179. return estimate;
  105180. }
  105181. unsigned find_best_partition_order_(
  105182. FLAC__StreamEncoderPrivate *private_,
  105183. const FLAC__int32 residual[],
  105184. FLAC__uint64 abs_residual_partition_sums[],
  105185. unsigned raw_bits_per_partition[],
  105186. unsigned residual_samples,
  105187. unsigned predictor_order,
  105188. unsigned rice_parameter,
  105189. unsigned rice_parameter_limit,
  105190. unsigned min_partition_order,
  105191. unsigned max_partition_order,
  105192. unsigned bps,
  105193. FLAC__bool do_escape_coding,
  105194. unsigned rice_parameter_search_dist,
  105195. FLAC__EntropyCodingMethod *best_ecm
  105196. )
  105197. {
  105198. unsigned residual_bits, best_residual_bits = 0;
  105199. unsigned best_parameters_index = 0;
  105200. unsigned best_partition_order = 0;
  105201. const unsigned blocksize = residual_samples + predictor_order;
  105202. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105203. min_partition_order = min(min_partition_order, max_partition_order);
  105204. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105205. if(do_escape_coding)
  105206. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105207. {
  105208. int partition_order;
  105209. unsigned sum;
  105210. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105211. if(!
  105212. set_partitioned_rice_(
  105213. #ifdef EXACT_RICE_BITS_CALCULATION
  105214. residual,
  105215. #endif
  105216. abs_residual_partition_sums+sum,
  105217. raw_bits_per_partition+sum,
  105218. residual_samples,
  105219. predictor_order,
  105220. rice_parameter,
  105221. rice_parameter_limit,
  105222. rice_parameter_search_dist,
  105223. (unsigned)partition_order,
  105224. do_escape_coding,
  105225. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105226. &residual_bits
  105227. )
  105228. )
  105229. {
  105230. FLAC__ASSERT(best_residual_bits != 0);
  105231. break;
  105232. }
  105233. sum += 1u << partition_order;
  105234. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105235. best_residual_bits = residual_bits;
  105236. best_parameters_index = !best_parameters_index;
  105237. best_partition_order = partition_order;
  105238. }
  105239. }
  105240. }
  105241. best_ecm->data.partitioned_rice.order = best_partition_order;
  105242. {
  105243. /*
  105244. * We are allowed to de-const the pointer based on our special
  105245. * knowledge; it is const to the outside world.
  105246. */
  105247. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105248. unsigned partition;
  105249. /* save best parameters and raw_bits */
  105250. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105251. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105252. if(do_escape_coding)
  105253. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105254. /*
  105255. * Now need to check if the type should be changed to
  105256. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105257. * size of the rice parameters.
  105258. */
  105259. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105260. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105261. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105262. break;
  105263. }
  105264. }
  105265. }
  105266. return best_residual_bits;
  105267. }
  105268. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105269. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105270. const FLAC__int32 residual[],
  105271. FLAC__uint64 abs_residual_partition_sums[],
  105272. unsigned blocksize,
  105273. unsigned predictor_order,
  105274. unsigned min_partition_order,
  105275. unsigned max_partition_order
  105276. );
  105277. #endif
  105278. void precompute_partition_info_sums_(
  105279. const FLAC__int32 residual[],
  105280. FLAC__uint64 abs_residual_partition_sums[],
  105281. unsigned residual_samples,
  105282. unsigned predictor_order,
  105283. unsigned min_partition_order,
  105284. unsigned max_partition_order,
  105285. unsigned bps
  105286. )
  105287. {
  105288. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105289. unsigned partitions = 1u << max_partition_order;
  105290. FLAC__ASSERT(default_partition_samples > predictor_order);
  105291. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105292. /* slightly pessimistic but still catches all common cases */
  105293. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105294. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105295. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105296. return;
  105297. }
  105298. #endif
  105299. /* first do max_partition_order */
  105300. {
  105301. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105302. /* slightly pessimistic but still catches all common cases */
  105303. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105304. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105305. FLAC__uint32 abs_residual_partition_sum;
  105306. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105307. end += default_partition_samples;
  105308. abs_residual_partition_sum = 0;
  105309. for( ; residual_sample < end; residual_sample++)
  105310. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105311. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105312. }
  105313. }
  105314. else { /* have to pessimistically use 64 bits for accumulator */
  105315. FLAC__uint64 abs_residual_partition_sum;
  105316. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105317. end += default_partition_samples;
  105318. abs_residual_partition_sum = 0;
  105319. for( ; residual_sample < end; residual_sample++)
  105320. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105321. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105322. }
  105323. }
  105324. }
  105325. /* now merge partitions for lower orders */
  105326. {
  105327. unsigned from_partition = 0, to_partition = partitions;
  105328. int partition_order;
  105329. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105330. unsigned i;
  105331. partitions >>= 1;
  105332. for(i = 0; i < partitions; i++) {
  105333. abs_residual_partition_sums[to_partition++] =
  105334. abs_residual_partition_sums[from_partition ] +
  105335. abs_residual_partition_sums[from_partition+1];
  105336. from_partition += 2;
  105337. }
  105338. }
  105339. }
  105340. }
  105341. void precompute_partition_info_escapes_(
  105342. const FLAC__int32 residual[],
  105343. unsigned raw_bits_per_partition[],
  105344. unsigned residual_samples,
  105345. unsigned predictor_order,
  105346. unsigned min_partition_order,
  105347. unsigned max_partition_order
  105348. )
  105349. {
  105350. int partition_order;
  105351. unsigned from_partition, to_partition = 0;
  105352. const unsigned blocksize = residual_samples + predictor_order;
  105353. /* first do max_partition_order */
  105354. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105355. FLAC__int32 r;
  105356. FLAC__uint32 rmax;
  105357. unsigned partition, partition_sample, partition_samples, residual_sample;
  105358. const unsigned partitions = 1u << partition_order;
  105359. const unsigned default_partition_samples = blocksize >> partition_order;
  105360. FLAC__ASSERT(default_partition_samples > predictor_order);
  105361. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105362. partition_samples = default_partition_samples;
  105363. if(partition == 0)
  105364. partition_samples -= predictor_order;
  105365. rmax = 0;
  105366. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105367. r = residual[residual_sample++];
  105368. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105369. if(r < 0)
  105370. rmax |= ~r;
  105371. else
  105372. rmax |= r;
  105373. }
  105374. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105375. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105376. }
  105377. to_partition = partitions;
  105378. break; /*@@@ yuck, should remove the 'for' loop instead */
  105379. }
  105380. /* now merge partitions for lower orders */
  105381. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105382. unsigned m;
  105383. unsigned i;
  105384. const unsigned partitions = 1u << partition_order;
  105385. for(i = 0; i < partitions; i++) {
  105386. m = raw_bits_per_partition[from_partition];
  105387. from_partition++;
  105388. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105389. from_partition++;
  105390. to_partition++;
  105391. }
  105392. }
  105393. }
  105394. #ifdef EXACT_RICE_BITS_CALCULATION
  105395. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105396. const unsigned rice_parameter,
  105397. const unsigned partition_samples,
  105398. const FLAC__int32 *residual
  105399. )
  105400. {
  105401. unsigned i, partition_bits =
  105402. 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 */
  105403. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105404. ;
  105405. for(i = 0; i < partition_samples; i++)
  105406. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105407. return partition_bits;
  105408. }
  105409. #else
  105410. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105411. const unsigned rice_parameter,
  105412. const unsigned partition_samples,
  105413. const FLAC__uint64 abs_residual_partition_sum
  105414. )
  105415. {
  105416. return
  105417. 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 */
  105418. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105419. (
  105420. rice_parameter?
  105421. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105422. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105423. )
  105424. - (partition_samples >> 1)
  105425. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105426. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105427. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105428. * So the subtraction term tries to guess how many extra bits were contributed.
  105429. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105430. */
  105431. ;
  105432. }
  105433. #endif
  105434. FLAC__bool set_partitioned_rice_(
  105435. #ifdef EXACT_RICE_BITS_CALCULATION
  105436. const FLAC__int32 residual[],
  105437. #endif
  105438. const FLAC__uint64 abs_residual_partition_sums[],
  105439. const unsigned raw_bits_per_partition[],
  105440. const unsigned residual_samples,
  105441. const unsigned predictor_order,
  105442. const unsigned suggested_rice_parameter,
  105443. const unsigned rice_parameter_limit,
  105444. const unsigned rice_parameter_search_dist,
  105445. const unsigned partition_order,
  105446. const FLAC__bool search_for_escapes,
  105447. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105448. unsigned *bits
  105449. )
  105450. {
  105451. unsigned rice_parameter, partition_bits;
  105452. unsigned best_partition_bits, best_rice_parameter = 0;
  105453. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105454. unsigned *parameters, *raw_bits;
  105455. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105456. unsigned min_rice_parameter, max_rice_parameter;
  105457. #else
  105458. (void)rice_parameter_search_dist;
  105459. #endif
  105460. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105461. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105462. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105463. parameters = partitioned_rice_contents->parameters;
  105464. raw_bits = partitioned_rice_contents->raw_bits;
  105465. if(partition_order == 0) {
  105466. best_partition_bits = (unsigned)(-1);
  105467. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105468. if(rice_parameter_search_dist) {
  105469. if(suggested_rice_parameter < rice_parameter_search_dist)
  105470. min_rice_parameter = 0;
  105471. else
  105472. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105473. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105474. if(max_rice_parameter >= rice_parameter_limit) {
  105475. #ifdef DEBUG_VERBOSE
  105476. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105477. #endif
  105478. max_rice_parameter = rice_parameter_limit - 1;
  105479. }
  105480. }
  105481. else
  105482. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105483. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105484. #else
  105485. rice_parameter = suggested_rice_parameter;
  105486. #endif
  105487. #ifdef EXACT_RICE_BITS_CALCULATION
  105488. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105489. #else
  105490. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105491. #endif
  105492. if(partition_bits < best_partition_bits) {
  105493. best_rice_parameter = rice_parameter;
  105494. best_partition_bits = partition_bits;
  105495. }
  105496. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105497. }
  105498. #endif
  105499. if(search_for_escapes) {
  105500. 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;
  105501. if(partition_bits <= best_partition_bits) {
  105502. raw_bits[0] = raw_bits_per_partition[0];
  105503. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105504. best_partition_bits = partition_bits;
  105505. }
  105506. else
  105507. raw_bits[0] = 0;
  105508. }
  105509. parameters[0] = best_rice_parameter;
  105510. bits_ += best_partition_bits;
  105511. }
  105512. else {
  105513. unsigned partition, residual_sample;
  105514. unsigned partition_samples;
  105515. FLAC__uint64 mean, k;
  105516. const unsigned partitions = 1u << partition_order;
  105517. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105518. partition_samples = (residual_samples+predictor_order) >> partition_order;
  105519. if(partition == 0) {
  105520. if(partition_samples <= predictor_order)
  105521. return false;
  105522. else
  105523. partition_samples -= predictor_order;
  105524. }
  105525. mean = abs_residual_partition_sums[partition];
  105526. /* we are basically calculating the size in bits of the
  105527. * average residual magnitude in the partition:
  105528. * rice_parameter = floor(log2(mean/partition_samples))
  105529. * 'mean' is not a good name for the variable, it is
  105530. * actually the sum of magnitudes of all residual values
  105531. * in the partition, so the actual mean is
  105532. * mean/partition_samples
  105533. */
  105534. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  105535. ;
  105536. if(rice_parameter >= rice_parameter_limit) {
  105537. #ifdef DEBUG_VERBOSE
  105538. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  105539. #endif
  105540. rice_parameter = rice_parameter_limit - 1;
  105541. }
  105542. best_partition_bits = (unsigned)(-1);
  105543. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105544. if(rice_parameter_search_dist) {
  105545. if(rice_parameter < rice_parameter_search_dist)
  105546. min_rice_parameter = 0;
  105547. else
  105548. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  105549. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  105550. if(max_rice_parameter >= rice_parameter_limit) {
  105551. #ifdef DEBUG_VERBOSE
  105552. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  105553. #endif
  105554. max_rice_parameter = rice_parameter_limit - 1;
  105555. }
  105556. }
  105557. else
  105558. min_rice_parameter = max_rice_parameter = rice_parameter;
  105559. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105560. #endif
  105561. #ifdef EXACT_RICE_BITS_CALCULATION
  105562. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  105563. #else
  105564. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  105565. #endif
  105566. if(partition_bits < best_partition_bits) {
  105567. best_rice_parameter = rice_parameter;
  105568. best_partition_bits = partition_bits;
  105569. }
  105570. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105571. }
  105572. #endif
  105573. if(search_for_escapes) {
  105574. 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;
  105575. if(partition_bits <= best_partition_bits) {
  105576. raw_bits[partition] = raw_bits_per_partition[partition];
  105577. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105578. best_partition_bits = partition_bits;
  105579. }
  105580. else
  105581. raw_bits[partition] = 0;
  105582. }
  105583. parameters[partition] = best_rice_parameter;
  105584. bits_ += best_partition_bits;
  105585. residual_sample += partition_samples;
  105586. }
  105587. }
  105588. *bits = bits_;
  105589. return true;
  105590. }
  105591. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  105592. {
  105593. unsigned i, shift;
  105594. FLAC__int32 x = 0;
  105595. for(i = 0; i < samples && !(x&1); i++)
  105596. x |= signal[i];
  105597. if(x == 0) {
  105598. shift = 0;
  105599. }
  105600. else {
  105601. for(shift = 0; !(x&1); shift++)
  105602. x >>= 1;
  105603. }
  105604. if(shift > 0) {
  105605. for(i = 0; i < samples; i++)
  105606. signal[i] >>= shift;
  105607. }
  105608. return shift;
  105609. }
  105610. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105611. {
  105612. unsigned channel;
  105613. for(channel = 0; channel < channels; channel++)
  105614. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  105615. fifo->tail += wide_samples;
  105616. FLAC__ASSERT(fifo->tail <= fifo->size);
  105617. }
  105618. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105619. {
  105620. unsigned channel;
  105621. unsigned sample, wide_sample;
  105622. unsigned tail = fifo->tail;
  105623. sample = input_offset * channels;
  105624. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  105625. for(channel = 0; channel < channels; channel++)
  105626. fifo->data[channel][tail] = input[sample++];
  105627. tail++;
  105628. }
  105629. fifo->tail = tail;
  105630. FLAC__ASSERT(fifo->tail <= fifo->size);
  105631. }
  105632. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105633. {
  105634. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105635. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  105636. (void)decoder;
  105637. if(encoder->private_->verify.needs_magic_hack) {
  105638. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  105639. *bytes = FLAC__STREAM_SYNC_LENGTH;
  105640. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  105641. encoder->private_->verify.needs_magic_hack = false;
  105642. }
  105643. else {
  105644. if(encoded_bytes == 0) {
  105645. /*
  105646. * If we get here, a FIFO underflow has occurred,
  105647. * which means there is a bug somewhere.
  105648. */
  105649. FLAC__ASSERT(0);
  105650. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  105651. }
  105652. else if(encoded_bytes < *bytes)
  105653. *bytes = encoded_bytes;
  105654. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  105655. encoder->private_->verify.output.data += *bytes;
  105656. encoder->private_->verify.output.bytes -= *bytes;
  105657. }
  105658. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  105659. }
  105660. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  105661. {
  105662. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  105663. unsigned channel;
  105664. const unsigned channels = frame->header.channels;
  105665. const unsigned blocksize = frame->header.blocksize;
  105666. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  105667. (void)decoder;
  105668. for(channel = 0; channel < channels; channel++) {
  105669. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  105670. unsigned i, sample = 0;
  105671. FLAC__int32 expect = 0, got = 0;
  105672. for(i = 0; i < blocksize; i++) {
  105673. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  105674. sample = i;
  105675. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  105676. got = (FLAC__int32)buffer[channel][i];
  105677. break;
  105678. }
  105679. }
  105680. FLAC__ASSERT(i < blocksize);
  105681. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  105682. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  105683. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  105684. encoder->private_->verify.error_stats.channel = channel;
  105685. encoder->private_->verify.error_stats.sample = sample;
  105686. encoder->private_->verify.error_stats.expected = expect;
  105687. encoder->private_->verify.error_stats.got = got;
  105688. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  105689. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  105690. }
  105691. }
  105692. /* dequeue the frame from the fifo */
  105693. encoder->private_->verify.input_fifo.tail -= blocksize;
  105694. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  105695. for(channel = 0; channel < channels; channel++)
  105696. 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]));
  105697. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  105698. }
  105699. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  105700. {
  105701. (void)decoder, (void)metadata, (void)client_data;
  105702. }
  105703. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  105704. {
  105705. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105706. (void)decoder, (void)status;
  105707. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  105708. }
  105709. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105710. {
  105711. (void)client_data;
  105712. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  105713. if (*bytes == 0) {
  105714. if (feof(encoder->private_->file))
  105715. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  105716. else if (ferror(encoder->private_->file))
  105717. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  105718. }
  105719. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  105720. }
  105721. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  105722. {
  105723. (void)client_data;
  105724. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  105725. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  105726. else
  105727. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  105728. }
  105729. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  105730. {
  105731. off_t offset;
  105732. (void)client_data;
  105733. offset = ftello(encoder->private_->file);
  105734. if(offset < 0) {
  105735. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  105736. }
  105737. else {
  105738. *absolute_byte_offset = (FLAC__uint64)offset;
  105739. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  105740. }
  105741. }
  105742. #ifdef FLAC__VALGRIND_TESTING
  105743. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  105744. {
  105745. size_t ret = fwrite(ptr, size, nmemb, stream);
  105746. if(!ferror(stream))
  105747. fflush(stream);
  105748. return ret;
  105749. }
  105750. #else
  105751. #define local__fwrite fwrite
  105752. #endif
  105753. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  105754. {
  105755. (void)client_data, (void)current_frame;
  105756. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  105757. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  105758. #if FLAC__HAS_OGG
  105759. /* We would like to be able to use 'samples > 0' in the
  105760. * clause here but currently because of the nature of our
  105761. * Ogg writing implementation, 'samples' is always 0 (see
  105762. * ogg_encoder_aspect.c). The downside is extra progress
  105763. * callbacks.
  105764. */
  105765. encoder->private_->is_ogg? true :
  105766. #endif
  105767. samples > 0
  105768. );
  105769. if(call_it) {
  105770. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  105771. * because at this point in the callback chain, the stats
  105772. * have not been updated. Only after we return and control
  105773. * gets back to write_frame_() are the stats updated
  105774. */
  105775. 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);
  105776. }
  105777. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  105778. }
  105779. else
  105780. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  105781. }
  105782. /*
  105783. * This will forcibly set stdout to binary mode (for OSes that require it)
  105784. */
  105785. FILE *get_binary_stdout_(void)
  105786. {
  105787. /* if something breaks here it is probably due to the presence or
  105788. * absence of an underscore before the identifiers 'setmode',
  105789. * 'fileno', and/or 'O_BINARY'; check your system header files.
  105790. */
  105791. #if defined _MSC_VER || defined __MINGW32__
  105792. _setmode(_fileno(stdout), _O_BINARY);
  105793. #elif defined __CYGWIN__
  105794. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  105795. setmode(_fileno(stdout), _O_BINARY);
  105796. #elif defined __EMX__
  105797. setmode(fileno(stdout), O_BINARY);
  105798. #endif
  105799. return stdout;
  105800. }
  105801. #endif
  105802. /*** End of inlined file: stream_encoder.c ***/
  105803. /*** Start of inlined file: stream_encoder_framing.c ***/
  105804. /*** Start of inlined file: juce_FlacHeader.h ***/
  105805. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  105806. // tasks..
  105807. #define VERSION "1.2.1"
  105808. #define FLAC__NO_DLL 1
  105809. #if JUCE_MSVC
  105810. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  105811. #endif
  105812. #if JUCE_MAC
  105813. #define FLAC__SYS_DARWIN 1
  105814. #endif
  105815. /*** End of inlined file: juce_FlacHeader.h ***/
  105816. #if JUCE_USE_FLAC
  105817. #if HAVE_CONFIG_H
  105818. # include <config.h>
  105819. #endif
  105820. #include <stdio.h>
  105821. #include <string.h> /* for strlen() */
  105822. #ifdef max
  105823. #undef max
  105824. #endif
  105825. #define max(x,y) ((x)>(y)?(x):(y))
  105826. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  105827. 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);
  105828. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  105829. {
  105830. unsigned i, j;
  105831. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  105832. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  105833. return false;
  105834. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  105835. return false;
  105836. /*
  105837. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  105838. */
  105839. i = metadata->length;
  105840. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  105841. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  105842. i -= metadata->data.vorbis_comment.vendor_string.length;
  105843. i += vendor_string_length;
  105844. }
  105845. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  105846. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  105847. return false;
  105848. switch(metadata->type) {
  105849. case FLAC__METADATA_TYPE_STREAMINFO:
  105850. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  105851. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  105852. return false;
  105853. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  105854. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  105855. return false;
  105856. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  105857. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  105858. return false;
  105859. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  105860. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  105861. return false;
  105862. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  105863. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  105864. return false;
  105865. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  105866. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  105867. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  105868. return false;
  105869. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  105870. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  105871. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  105872. return false;
  105873. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  105874. return false;
  105875. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  105876. return false;
  105877. break;
  105878. case FLAC__METADATA_TYPE_PADDING:
  105879. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  105880. return false;
  105881. break;
  105882. case FLAC__METADATA_TYPE_APPLICATION:
  105883. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  105884. return false;
  105885. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  105886. return false;
  105887. break;
  105888. case FLAC__METADATA_TYPE_SEEKTABLE:
  105889. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  105890. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  105891. return false;
  105892. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  105893. return false;
  105894. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  105895. return false;
  105896. }
  105897. break;
  105898. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  105899. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  105900. return false;
  105901. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  105902. return false;
  105903. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  105904. return false;
  105905. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  105906. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  105907. return false;
  105908. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  105909. return false;
  105910. }
  105911. break;
  105912. case FLAC__METADATA_TYPE_CUESHEET:
  105913. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  105914. 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))
  105915. return false;
  105916. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  105917. return false;
  105918. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  105919. return false;
  105920. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  105921. return false;
  105922. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  105923. return false;
  105924. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  105925. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  105926. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  105927. return false;
  105928. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  105929. return false;
  105930. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  105931. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  105932. return false;
  105933. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  105934. return false;
  105935. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  105936. return false;
  105937. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  105938. return false;
  105939. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  105940. return false;
  105941. for(j = 0; j < track->num_indices; j++) {
  105942. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  105943. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  105944. return false;
  105945. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  105946. return false;
  105947. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  105948. return false;
  105949. }
  105950. }
  105951. break;
  105952. case FLAC__METADATA_TYPE_PICTURE:
  105953. {
  105954. size_t len;
  105955. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  105956. return false;
  105957. len = strlen(metadata->data.picture.mime_type);
  105958. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  105959. return false;
  105960. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  105961. return false;
  105962. len = strlen((const char *)metadata->data.picture.description);
  105963. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  105964. return false;
  105965. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  105966. return false;
  105967. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  105968. return false;
  105969. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  105970. return false;
  105971. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  105972. return false;
  105973. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  105974. return false;
  105975. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  105976. return false;
  105977. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  105978. return false;
  105979. }
  105980. break;
  105981. default:
  105982. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  105983. return false;
  105984. break;
  105985. }
  105986. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105987. return true;
  105988. }
  105989. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  105990. {
  105991. unsigned u, blocksize_hint, sample_rate_hint;
  105992. FLAC__byte crc;
  105993. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105994. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  105995. return false;
  105996. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  105997. return false;
  105998. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  105999. return false;
  106000. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  106001. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  106002. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  106003. blocksize_hint = 0;
  106004. switch(header->blocksize) {
  106005. case 192: u = 1; break;
  106006. case 576: u = 2; break;
  106007. case 1152: u = 3; break;
  106008. case 2304: u = 4; break;
  106009. case 4608: u = 5; break;
  106010. case 256: u = 8; break;
  106011. case 512: u = 9; break;
  106012. case 1024: u = 10; break;
  106013. case 2048: u = 11; break;
  106014. case 4096: u = 12; break;
  106015. case 8192: u = 13; break;
  106016. case 16384: u = 14; break;
  106017. case 32768: u = 15; break;
  106018. default:
  106019. if(header->blocksize <= 0x100)
  106020. blocksize_hint = u = 6;
  106021. else
  106022. blocksize_hint = u = 7;
  106023. break;
  106024. }
  106025. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106026. return false;
  106027. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106028. sample_rate_hint = 0;
  106029. switch(header->sample_rate) {
  106030. case 88200: u = 1; break;
  106031. case 176400: u = 2; break;
  106032. case 192000: u = 3; break;
  106033. case 8000: u = 4; break;
  106034. case 16000: u = 5; break;
  106035. case 22050: u = 6; break;
  106036. case 24000: u = 7; break;
  106037. case 32000: u = 8; break;
  106038. case 44100: u = 9; break;
  106039. case 48000: u = 10; break;
  106040. case 96000: u = 11; break;
  106041. default:
  106042. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106043. sample_rate_hint = u = 12;
  106044. else if(header->sample_rate % 10 == 0)
  106045. sample_rate_hint = u = 14;
  106046. else if(header->sample_rate <= 0xffff)
  106047. sample_rate_hint = u = 13;
  106048. else
  106049. u = 0;
  106050. break;
  106051. }
  106052. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106053. return false;
  106054. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106055. switch(header->channel_assignment) {
  106056. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106057. u = header->channels - 1;
  106058. break;
  106059. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106060. FLAC__ASSERT(header->channels == 2);
  106061. u = 8;
  106062. break;
  106063. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106064. FLAC__ASSERT(header->channels == 2);
  106065. u = 9;
  106066. break;
  106067. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106068. FLAC__ASSERT(header->channels == 2);
  106069. u = 10;
  106070. break;
  106071. default:
  106072. FLAC__ASSERT(0);
  106073. }
  106074. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106075. return false;
  106076. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106077. switch(header->bits_per_sample) {
  106078. case 8 : u = 1; break;
  106079. case 12: u = 2; break;
  106080. case 16: u = 4; break;
  106081. case 20: u = 5; break;
  106082. case 24: u = 6; break;
  106083. default: u = 0; break;
  106084. }
  106085. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106086. return false;
  106087. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106088. return false;
  106089. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106090. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106091. return false;
  106092. }
  106093. else {
  106094. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106095. return false;
  106096. }
  106097. if(blocksize_hint)
  106098. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106099. return false;
  106100. switch(sample_rate_hint) {
  106101. case 12:
  106102. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106103. return false;
  106104. break;
  106105. case 13:
  106106. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106107. return false;
  106108. break;
  106109. case 14:
  106110. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106111. return false;
  106112. break;
  106113. }
  106114. /* write the CRC */
  106115. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106116. return false;
  106117. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106118. return false;
  106119. return true;
  106120. }
  106121. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106122. {
  106123. FLAC__bool ok;
  106124. ok =
  106125. 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) &&
  106126. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106127. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106128. ;
  106129. return ok;
  106130. }
  106131. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106132. {
  106133. unsigned i;
  106134. 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))
  106135. return false;
  106136. if(wasted_bits)
  106137. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106138. return false;
  106139. for(i = 0; i < subframe->order; i++)
  106140. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106141. return false;
  106142. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106143. return false;
  106144. switch(subframe->entropy_coding_method.type) {
  106145. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106146. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106147. if(!add_residual_partitioned_rice_(
  106148. bw,
  106149. subframe->residual,
  106150. residual_samples,
  106151. subframe->order,
  106152. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106153. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106154. subframe->entropy_coding_method.data.partitioned_rice.order,
  106155. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106156. ))
  106157. return false;
  106158. break;
  106159. default:
  106160. FLAC__ASSERT(0);
  106161. }
  106162. return true;
  106163. }
  106164. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106165. {
  106166. unsigned i;
  106167. 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))
  106168. return false;
  106169. if(wasted_bits)
  106170. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106171. return false;
  106172. for(i = 0; i < subframe->order; i++)
  106173. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106174. return false;
  106175. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106176. return false;
  106177. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106178. return false;
  106179. for(i = 0; i < subframe->order; i++)
  106180. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106181. return false;
  106182. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106183. return false;
  106184. switch(subframe->entropy_coding_method.type) {
  106185. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106186. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106187. if(!add_residual_partitioned_rice_(
  106188. bw,
  106189. subframe->residual,
  106190. residual_samples,
  106191. subframe->order,
  106192. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106193. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106194. subframe->entropy_coding_method.data.partitioned_rice.order,
  106195. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106196. ))
  106197. return false;
  106198. break;
  106199. default:
  106200. FLAC__ASSERT(0);
  106201. }
  106202. return true;
  106203. }
  106204. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106205. {
  106206. unsigned i;
  106207. const FLAC__int32 *signal = subframe->data;
  106208. 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))
  106209. return false;
  106210. if(wasted_bits)
  106211. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106212. return false;
  106213. for(i = 0; i < samples; i++)
  106214. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106215. return false;
  106216. return true;
  106217. }
  106218. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106219. {
  106220. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106221. return false;
  106222. switch(method->type) {
  106223. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106224. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106225. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106226. return false;
  106227. break;
  106228. default:
  106229. FLAC__ASSERT(0);
  106230. }
  106231. return true;
  106232. }
  106233. 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)
  106234. {
  106235. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106236. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106237. if(partition_order == 0) {
  106238. unsigned i;
  106239. if(raw_bits[0] == 0) {
  106240. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106241. return false;
  106242. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106243. return false;
  106244. }
  106245. else {
  106246. FLAC__ASSERT(rice_parameters[0] == 0);
  106247. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106248. return false;
  106249. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106250. return false;
  106251. for(i = 0; i < residual_samples; i++) {
  106252. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106253. return false;
  106254. }
  106255. }
  106256. return true;
  106257. }
  106258. else {
  106259. unsigned i, j, k = 0, k_last = 0;
  106260. unsigned partition_samples;
  106261. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106262. for(i = 0; i < (1u<<partition_order); i++) {
  106263. partition_samples = default_partition_samples;
  106264. if(i == 0)
  106265. partition_samples -= predictor_order;
  106266. k += partition_samples;
  106267. if(raw_bits[i] == 0) {
  106268. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106269. return false;
  106270. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106271. return false;
  106272. }
  106273. else {
  106274. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106275. return false;
  106276. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106277. return false;
  106278. for(j = k_last; j < k; j++) {
  106279. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106280. return false;
  106281. }
  106282. }
  106283. k_last = k;
  106284. }
  106285. return true;
  106286. }
  106287. }
  106288. #endif
  106289. /*** End of inlined file: stream_encoder_framing.c ***/
  106290. /*** Start of inlined file: window_flac.c ***/
  106291. /*** Start of inlined file: juce_FlacHeader.h ***/
  106292. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106293. // tasks..
  106294. #define VERSION "1.2.1"
  106295. #define FLAC__NO_DLL 1
  106296. #if JUCE_MSVC
  106297. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106298. #endif
  106299. #if JUCE_MAC
  106300. #define FLAC__SYS_DARWIN 1
  106301. #endif
  106302. /*** End of inlined file: juce_FlacHeader.h ***/
  106303. #if JUCE_USE_FLAC
  106304. #if HAVE_CONFIG_H
  106305. # include <config.h>
  106306. #endif
  106307. #include <math.h>
  106308. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106309. #ifndef M_PI
  106310. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106311. #define M_PI 3.14159265358979323846
  106312. #endif
  106313. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106314. {
  106315. const FLAC__int32 N = L - 1;
  106316. FLAC__int32 n;
  106317. if (L & 1) {
  106318. for (n = 0; n <= N/2; n++)
  106319. window[n] = 2.0f * n / (float)N;
  106320. for (; n <= N; n++)
  106321. window[n] = 2.0f - 2.0f * n / (float)N;
  106322. }
  106323. else {
  106324. for (n = 0; n <= L/2-1; n++)
  106325. window[n] = 2.0f * n / (float)N;
  106326. for (; n <= N; n++)
  106327. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106328. }
  106329. }
  106330. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106331. {
  106332. const FLAC__int32 N = L - 1;
  106333. FLAC__int32 n;
  106334. for (n = 0; n < L; n++)
  106335. 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)));
  106336. }
  106337. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106338. {
  106339. const FLAC__int32 N = L - 1;
  106340. FLAC__int32 n;
  106341. for (n = 0; n < L; n++)
  106342. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106343. }
  106344. /* 4-term -92dB side-lobe */
  106345. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106346. {
  106347. const FLAC__int32 N = L - 1;
  106348. FLAC__int32 n;
  106349. for (n = 0; n <= N; n++)
  106350. 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));
  106351. }
  106352. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106353. {
  106354. const FLAC__int32 N = L - 1;
  106355. const double N2 = (double)N / 2.;
  106356. FLAC__int32 n;
  106357. for (n = 0; n <= N; n++) {
  106358. double k = ((double)n - N2) / N2;
  106359. k = 1.0f - k * k;
  106360. window[n] = (FLAC__real)(k * k);
  106361. }
  106362. }
  106363. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106364. {
  106365. const FLAC__int32 N = L - 1;
  106366. FLAC__int32 n;
  106367. for (n = 0; n < L; n++)
  106368. 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));
  106369. }
  106370. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106371. {
  106372. const FLAC__int32 N = L - 1;
  106373. const double N2 = (double)N / 2.;
  106374. FLAC__int32 n;
  106375. for (n = 0; n <= N; n++) {
  106376. const double k = ((double)n - N2) / (stddev * N2);
  106377. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106378. }
  106379. }
  106380. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106381. {
  106382. const FLAC__int32 N = L - 1;
  106383. FLAC__int32 n;
  106384. for (n = 0; n < L; n++)
  106385. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106386. }
  106387. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106388. {
  106389. const FLAC__int32 N = L - 1;
  106390. FLAC__int32 n;
  106391. for (n = 0; n < L; n++)
  106392. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106393. }
  106394. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106395. {
  106396. const FLAC__int32 N = L - 1;
  106397. FLAC__int32 n;
  106398. for (n = 0; n < L; n++)
  106399. 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));
  106400. }
  106401. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106402. {
  106403. const FLAC__int32 N = L - 1;
  106404. FLAC__int32 n;
  106405. for (n = 0; n < L; n++)
  106406. 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));
  106407. }
  106408. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106409. {
  106410. FLAC__int32 n;
  106411. for (n = 0; n < L; n++)
  106412. window[n] = 1.0f;
  106413. }
  106414. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106415. {
  106416. FLAC__int32 n;
  106417. if (L & 1) {
  106418. for (n = 1; n <= L+1/2; n++)
  106419. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106420. for (; n <= L; n++)
  106421. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106422. }
  106423. else {
  106424. for (n = 1; n <= L/2; n++)
  106425. window[n-1] = 2.0f * n / (float)L;
  106426. for (; n <= L; n++)
  106427. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106428. }
  106429. }
  106430. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106431. {
  106432. if (p <= 0.0)
  106433. FLAC__window_rectangle(window, L);
  106434. else if (p >= 1.0)
  106435. FLAC__window_hann(window, L);
  106436. else {
  106437. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106438. FLAC__int32 n;
  106439. /* start with rectangle... */
  106440. FLAC__window_rectangle(window, L);
  106441. /* ...replace ends with hann */
  106442. if (Np > 0) {
  106443. for (n = 0; n <= Np; n++) {
  106444. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106445. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106446. }
  106447. }
  106448. }
  106449. }
  106450. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106451. {
  106452. const FLAC__int32 N = L - 1;
  106453. const double N2 = (double)N / 2.;
  106454. FLAC__int32 n;
  106455. for (n = 0; n <= N; n++) {
  106456. const double k = ((double)n - N2) / N2;
  106457. window[n] = (FLAC__real)(1.0f - k * k);
  106458. }
  106459. }
  106460. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106461. #endif
  106462. /*** End of inlined file: window_flac.c ***/
  106463. #else
  106464. #include <FLAC/all.h>
  106465. #endif
  106466. }
  106467. #undef max
  106468. #undef min
  106469. BEGIN_JUCE_NAMESPACE
  106470. static const char* const flacFormatName = "FLAC file";
  106471. static const char* const flacExtensions[] = { ".flac", 0 };
  106472. class FlacReader : public AudioFormatReader
  106473. {
  106474. public:
  106475. FlacReader (InputStream* const in)
  106476. : AudioFormatReader (in, TRANS (flacFormatName)),
  106477. reservoir (2, 0),
  106478. reservoirStart (0),
  106479. samplesInReservoir (0),
  106480. scanningForLength (false)
  106481. {
  106482. using namespace FlacNamespace;
  106483. lengthInSamples = 0;
  106484. decoder = FLAC__stream_decoder_new();
  106485. ok = FLAC__stream_decoder_init_stream (decoder,
  106486. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106487. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106488. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106489. if (ok)
  106490. {
  106491. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106492. if (lengthInSamples == 0 && sampleRate > 0)
  106493. {
  106494. // the length hasn't been stored in the metadata, so we'll need to
  106495. // work it out the length the hard way, by scanning the whole file..
  106496. scanningForLength = true;
  106497. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  106498. scanningForLength = false;
  106499. const int64 tempLength = lengthInSamples;
  106500. FLAC__stream_decoder_reset (decoder);
  106501. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106502. lengthInSamples = tempLength;
  106503. }
  106504. }
  106505. }
  106506. ~FlacReader()
  106507. {
  106508. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  106509. }
  106510. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  106511. {
  106512. sampleRate = info.sample_rate;
  106513. bitsPerSample = info.bits_per_sample;
  106514. lengthInSamples = (unsigned int) info.total_samples;
  106515. numChannels = info.channels;
  106516. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  106517. }
  106518. // returns the number of samples read
  106519. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  106520. int64 startSampleInFile, int numSamples)
  106521. {
  106522. using namespace FlacNamespace;
  106523. if (! ok)
  106524. return false;
  106525. while (numSamples > 0)
  106526. {
  106527. if (startSampleInFile >= reservoirStart
  106528. && startSampleInFile < reservoirStart + samplesInReservoir)
  106529. {
  106530. const int num = (int) jmin ((int64) numSamples,
  106531. reservoirStart + samplesInReservoir - startSampleInFile);
  106532. jassert (num > 0);
  106533. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  106534. if (destSamples[i] != 0)
  106535. memcpy (destSamples[i] + startOffsetInDestBuffer,
  106536. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  106537. sizeof (int) * num);
  106538. startOffsetInDestBuffer += num;
  106539. startSampleInFile += num;
  106540. numSamples -= num;
  106541. }
  106542. else
  106543. {
  106544. if (startSampleInFile >= (int) lengthInSamples)
  106545. {
  106546. samplesInReservoir = 0;
  106547. }
  106548. else if (startSampleInFile < reservoirStart
  106549. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  106550. {
  106551. // had some problems with flac crashing if the read pos is aligned more
  106552. // accurately than this. Probably fixed in newer versions of the library, though.
  106553. reservoirStart = (int) (startSampleInFile & ~511);
  106554. samplesInReservoir = 0;
  106555. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  106556. }
  106557. else
  106558. {
  106559. reservoirStart += samplesInReservoir;
  106560. samplesInReservoir = 0;
  106561. FLAC__stream_decoder_process_single (decoder);
  106562. }
  106563. if (samplesInReservoir == 0)
  106564. break;
  106565. }
  106566. }
  106567. if (numSamples > 0)
  106568. {
  106569. for (int i = numDestChannels; --i >= 0;)
  106570. if (destSamples[i] != 0)
  106571. zeromem (destSamples[i] + startOffsetInDestBuffer,
  106572. sizeof (int) * numSamples);
  106573. }
  106574. return true;
  106575. }
  106576. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  106577. {
  106578. if (scanningForLength)
  106579. {
  106580. lengthInSamples += numSamples;
  106581. }
  106582. else
  106583. {
  106584. if (numSamples > reservoir.getNumSamples())
  106585. reservoir.setSize (numChannels, numSamples, false, false, true);
  106586. const int bitsToShift = 32 - bitsPerSample;
  106587. for (int i = 0; i < (int) numChannels; ++i)
  106588. {
  106589. const FlacNamespace::FLAC__int32* src = buffer[i];
  106590. int n = i;
  106591. while (src == 0 && n > 0)
  106592. src = buffer [--n];
  106593. if (src != 0)
  106594. {
  106595. int* dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  106596. for (int j = 0; j < numSamples; ++j)
  106597. dest[j] = src[j] << bitsToShift;
  106598. }
  106599. }
  106600. samplesInReservoir = numSamples;
  106601. }
  106602. }
  106603. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  106604. {
  106605. using namespace FlacNamespace;
  106606. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  106607. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106608. }
  106609. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  106610. {
  106611. using namespace FlacNamespace;
  106612. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  106613. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  106614. }
  106615. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106616. {
  106617. using namespace FlacNamespace;
  106618. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  106619. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  106620. }
  106621. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  106622. {
  106623. using namespace FlacNamespace;
  106624. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  106625. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  106626. }
  106627. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  106628. {
  106629. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  106630. }
  106631. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106632. const FlacNamespace::FLAC__Frame* frame,
  106633. const FlacNamespace::FLAC__int32* const buffer[],
  106634. void* client_data)
  106635. {
  106636. using namespace FlacNamespace;
  106637. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  106638. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106639. }
  106640. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106641. const FlacNamespace::FLAC__StreamMetadata* metadata,
  106642. void* client_data)
  106643. {
  106644. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  106645. }
  106646. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  106647. {
  106648. }
  106649. private:
  106650. FlacNamespace::FLAC__StreamDecoder* decoder;
  106651. AudioSampleBuffer reservoir;
  106652. int reservoirStart, samplesInReservoir;
  106653. bool ok, scanningForLength;
  106654. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacReader);
  106655. };
  106656. class FlacWriter : public AudioFormatWriter
  106657. {
  106658. public:
  106659. FlacWriter (OutputStream* const out, double sampleRate_,
  106660. int numChannels_, int bitsPerSample_, int qualityOptionIndex)
  106661. : AudioFormatWriter (out, TRANS (flacFormatName),
  106662. sampleRate_, numChannels_, bitsPerSample_)
  106663. {
  106664. using namespace FlacNamespace;
  106665. encoder = FLAC__stream_encoder_new();
  106666. if (qualityOptionIndex > 0)
  106667. FLAC__stream_encoder_set_compression_level (encoder, jmin (8, qualityOptionIndex));
  106668. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  106669. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  106670. FLAC__stream_encoder_set_channels (encoder, numChannels);
  106671. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  106672. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  106673. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  106674. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  106675. ok = FLAC__stream_encoder_init_stream (encoder,
  106676. encodeWriteCallback, encodeSeekCallback,
  106677. encodeTellCallback, encodeMetadataCallback,
  106678. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  106679. }
  106680. ~FlacWriter()
  106681. {
  106682. if (ok)
  106683. {
  106684. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  106685. output->flush();
  106686. }
  106687. else
  106688. {
  106689. output = 0; // to stop the base class deleting this, as it needs to be returned
  106690. // to the caller of createWriter()
  106691. }
  106692. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  106693. }
  106694. bool write (const int** samplesToWrite, int numSamples)
  106695. {
  106696. using namespace FlacNamespace;
  106697. if (! ok)
  106698. return false;
  106699. int* buf[3];
  106700. HeapBlock<int> temp;
  106701. const int bitsToShift = 32 - bitsPerSample;
  106702. if (bitsToShift > 0)
  106703. {
  106704. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  106705. temp.malloc (numSamples * numChannelsToWrite);
  106706. buf[0] = temp.getData();
  106707. buf[1] = temp.getData() + numSamples;
  106708. buf[2] = 0;
  106709. for (int i = numChannelsToWrite; --i >= 0;)
  106710. if (samplesToWrite[i] != 0)
  106711. for (int j = 0; j < numSamples; ++j)
  106712. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  106713. samplesToWrite = const_cast<const int**> (buf);
  106714. }
  106715. return FLAC__stream_encoder_process (encoder, (const FLAC__int32**) samplesToWrite, numSamples) != 0;
  106716. }
  106717. bool writeData (const void* const data, const int size) const
  106718. {
  106719. return output->write (data, size);
  106720. }
  106721. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  106722. {
  106723. using namespace FlacNamespace;
  106724. b += bytes;
  106725. for (int i = 0; i < bytes; ++i)
  106726. {
  106727. *(--b) = (FLAC__byte) (val & 0xff);
  106728. val >>= 8;
  106729. }
  106730. }
  106731. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  106732. {
  106733. using namespace FlacNamespace;
  106734. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  106735. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  106736. const unsigned int channelsMinus1 = info.channels - 1;
  106737. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  106738. packUint32 (info.min_blocksize, buffer, 2);
  106739. packUint32 (info.max_blocksize, buffer + 2, 2);
  106740. packUint32 (info.min_framesize, buffer + 4, 3);
  106741. packUint32 (info.max_framesize, buffer + 7, 3);
  106742. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  106743. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  106744. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  106745. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  106746. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  106747. memcpy (buffer + 18, info.md5sum, 16);
  106748. const bool seekOk = output->setPosition (4);
  106749. (void) seekOk;
  106750. // if this fails, you've given it an output stream that can't seek! It needs
  106751. // to be able to seek back to write the header
  106752. jassert (seekOk);
  106753. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106754. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106755. }
  106756. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  106757. const FlacNamespace::FLAC__byte buffer[],
  106758. size_t bytes,
  106759. unsigned int /*samples*/,
  106760. unsigned int /*current_frame*/,
  106761. void* client_data)
  106762. {
  106763. using namespace FlacNamespace;
  106764. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  106765. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  106766. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106767. }
  106768. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  106769. {
  106770. using namespace FlacNamespace;
  106771. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  106772. }
  106773. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106774. {
  106775. using namespace FlacNamespace;
  106776. if (client_data == 0)
  106777. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  106778. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  106779. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106780. }
  106781. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  106782. {
  106783. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  106784. }
  106785. bool ok;
  106786. private:
  106787. FlacNamespace::FLAC__StreamEncoder* encoder;
  106788. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacWriter);
  106789. };
  106790. FlacAudioFormat::FlacAudioFormat()
  106791. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  106792. {
  106793. }
  106794. FlacAudioFormat::~FlacAudioFormat()
  106795. {
  106796. }
  106797. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  106798. {
  106799. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  106800. return Array <int> (rates);
  106801. }
  106802. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  106803. {
  106804. const int depths[] = { 16, 24, 0 };
  106805. return Array <int> (depths);
  106806. }
  106807. bool FlacAudioFormat::canDoStereo() { return true; }
  106808. bool FlacAudioFormat::canDoMono() { return true; }
  106809. bool FlacAudioFormat::isCompressed() { return true; }
  106810. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  106811. const bool deleteStreamIfOpeningFails)
  106812. {
  106813. ScopedPointer<FlacReader> r (new FlacReader (in));
  106814. if (r->sampleRate != 0)
  106815. return r.release();
  106816. if (! deleteStreamIfOpeningFails)
  106817. r->input = 0;
  106818. return 0;
  106819. }
  106820. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  106821. double sampleRate,
  106822. unsigned int numberOfChannels,
  106823. int bitsPerSample,
  106824. const StringPairArray& /*metadataValues*/,
  106825. int qualityOptionIndex)
  106826. {
  106827. if (getPossibleBitDepths().contains (bitsPerSample))
  106828. {
  106829. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample, qualityOptionIndex));
  106830. if (w->ok)
  106831. return w.release();
  106832. }
  106833. return 0;
  106834. }
  106835. END_JUCE_NAMESPACE
  106836. #endif
  106837. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  106838. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  106839. #if JUCE_USE_OGGVORBIS
  106840. #if JUCE_MAC
  106841. #define __MACOSX__ 1
  106842. #endif
  106843. namespace OggVorbisNamespace
  106844. {
  106845. #if JUCE_INCLUDE_OGGVORBIS_CODE
  106846. /*** Start of inlined file: vorbisenc.h ***/
  106847. #ifndef _OV_ENC_H_
  106848. #define _OV_ENC_H_
  106849. #ifdef __cplusplus
  106850. extern "C"
  106851. {
  106852. #endif /* __cplusplus */
  106853. /*** Start of inlined file: codec.h ***/
  106854. #ifndef _vorbis_codec_h_
  106855. #define _vorbis_codec_h_
  106856. #ifdef __cplusplus
  106857. extern "C"
  106858. {
  106859. #endif /* __cplusplus */
  106860. /*** Start of inlined file: ogg.h ***/
  106861. #ifndef _OGG_H
  106862. #define _OGG_H
  106863. #ifdef __cplusplus
  106864. extern "C" {
  106865. #endif
  106866. /*** Start of inlined file: os_types.h ***/
  106867. #ifndef _OS_TYPES_H
  106868. #define _OS_TYPES_H
  106869. /* make it easy on the folks that want to compile the libs with a
  106870. different malloc than stdlib */
  106871. #define _ogg_malloc malloc
  106872. #define _ogg_calloc calloc
  106873. #define _ogg_realloc realloc
  106874. #define _ogg_free free
  106875. #if defined(_WIN32)
  106876. # if defined(__CYGWIN__)
  106877. # include <_G_config.h>
  106878. typedef _G_int64_t ogg_int64_t;
  106879. typedef _G_int32_t ogg_int32_t;
  106880. typedef _G_uint32_t ogg_uint32_t;
  106881. typedef _G_int16_t ogg_int16_t;
  106882. typedef _G_uint16_t ogg_uint16_t;
  106883. # elif defined(__MINGW32__)
  106884. typedef short ogg_int16_t;
  106885. typedef unsigned short ogg_uint16_t;
  106886. typedef int ogg_int32_t;
  106887. typedef unsigned int ogg_uint32_t;
  106888. typedef long long ogg_int64_t;
  106889. typedef unsigned long long ogg_uint64_t;
  106890. # elif defined(__MWERKS__)
  106891. typedef long long ogg_int64_t;
  106892. typedef int ogg_int32_t;
  106893. typedef unsigned int ogg_uint32_t;
  106894. typedef short ogg_int16_t;
  106895. typedef unsigned short ogg_uint16_t;
  106896. # else
  106897. /* MSVC/Borland */
  106898. typedef __int64 ogg_int64_t;
  106899. typedef __int32 ogg_int32_t;
  106900. typedef unsigned __int32 ogg_uint32_t;
  106901. typedef __int16 ogg_int16_t;
  106902. typedef unsigned __int16 ogg_uint16_t;
  106903. # endif
  106904. #elif defined(__MACOS__)
  106905. # include <sys/types.h>
  106906. typedef SInt16 ogg_int16_t;
  106907. typedef UInt16 ogg_uint16_t;
  106908. typedef SInt32 ogg_int32_t;
  106909. typedef UInt32 ogg_uint32_t;
  106910. typedef SInt64 ogg_int64_t;
  106911. #elif defined(__MACOSX__) /* MacOS X Framework build */
  106912. # include <sys/types.h>
  106913. typedef int16_t ogg_int16_t;
  106914. typedef u_int16_t ogg_uint16_t;
  106915. typedef int32_t ogg_int32_t;
  106916. typedef u_int32_t ogg_uint32_t;
  106917. typedef int64_t ogg_int64_t;
  106918. #elif defined(__BEOS__)
  106919. /* Be */
  106920. # include <inttypes.h>
  106921. typedef int16_t ogg_int16_t;
  106922. typedef u_int16_t ogg_uint16_t;
  106923. typedef int32_t ogg_int32_t;
  106924. typedef u_int32_t ogg_uint32_t;
  106925. typedef int64_t ogg_int64_t;
  106926. #elif defined (__EMX__)
  106927. /* OS/2 GCC */
  106928. typedef short ogg_int16_t;
  106929. typedef unsigned short ogg_uint16_t;
  106930. typedef int ogg_int32_t;
  106931. typedef unsigned int ogg_uint32_t;
  106932. typedef long long ogg_int64_t;
  106933. #elif defined (DJGPP)
  106934. /* DJGPP */
  106935. typedef short ogg_int16_t;
  106936. typedef int ogg_int32_t;
  106937. typedef unsigned int ogg_uint32_t;
  106938. typedef long long ogg_int64_t;
  106939. #elif defined(R5900)
  106940. /* PS2 EE */
  106941. typedef long ogg_int64_t;
  106942. typedef int ogg_int32_t;
  106943. typedef unsigned ogg_uint32_t;
  106944. typedef short ogg_int16_t;
  106945. #elif defined(__SYMBIAN32__)
  106946. /* Symbian GCC */
  106947. typedef signed short ogg_int16_t;
  106948. typedef unsigned short ogg_uint16_t;
  106949. typedef signed int ogg_int32_t;
  106950. typedef unsigned int ogg_uint32_t;
  106951. typedef long long int ogg_int64_t;
  106952. #else
  106953. # include <sys/types.h>
  106954. /*** Start of inlined file: config_types.h ***/
  106955. #ifndef __CONFIG_TYPES_H__
  106956. #define __CONFIG_TYPES_H__
  106957. typedef int16_t ogg_int16_t;
  106958. typedef unsigned short ogg_uint16_t;
  106959. typedef int32_t ogg_int32_t;
  106960. typedef unsigned int ogg_uint32_t;
  106961. typedef int64_t ogg_int64_t;
  106962. #endif
  106963. /*** End of inlined file: config_types.h ***/
  106964. #endif
  106965. #endif /* _OS_TYPES_H */
  106966. /*** End of inlined file: os_types.h ***/
  106967. typedef struct {
  106968. long endbyte;
  106969. int endbit;
  106970. unsigned char *buffer;
  106971. unsigned char *ptr;
  106972. long storage;
  106973. } oggpack_buffer;
  106974. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  106975. typedef struct {
  106976. unsigned char *header;
  106977. long header_len;
  106978. unsigned char *body;
  106979. long body_len;
  106980. } ogg_page;
  106981. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  106982. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  106983. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  106984. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  106985. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  106986. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  106987. }
  106988. /* ogg_stream_state contains the current encode/decode state of a logical
  106989. Ogg bitstream **********************************************************/
  106990. typedef struct {
  106991. unsigned char *body_data; /* bytes from packet bodies */
  106992. long body_storage; /* storage elements allocated */
  106993. long body_fill; /* elements stored; fill mark */
  106994. long body_returned; /* elements of fill returned */
  106995. int *lacing_vals; /* The values that will go to the segment table */
  106996. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  106997. this way, but it is simple coupled to the
  106998. lacing fifo */
  106999. long lacing_storage;
  107000. long lacing_fill;
  107001. long lacing_packet;
  107002. long lacing_returned;
  107003. unsigned char header[282]; /* working space for header encode */
  107004. int header_fill;
  107005. int e_o_s; /* set when we have buffered the last packet in the
  107006. logical bitstream */
  107007. int b_o_s; /* set after we've written the initial page
  107008. of a logical bitstream */
  107009. long serialno;
  107010. long pageno;
  107011. ogg_int64_t packetno; /* sequence number for decode; the framing
  107012. knows where there's a hole in the data,
  107013. but we need coupling so that the codec
  107014. (which is in a seperate abstraction
  107015. layer) also knows about the gap */
  107016. ogg_int64_t granulepos;
  107017. } ogg_stream_state;
  107018. /* ogg_packet is used to encapsulate the data and metadata belonging
  107019. to a single raw Ogg/Vorbis packet *************************************/
  107020. typedef struct {
  107021. unsigned char *packet;
  107022. long bytes;
  107023. long b_o_s;
  107024. long e_o_s;
  107025. ogg_int64_t granulepos;
  107026. ogg_int64_t packetno; /* sequence number for decode; the framing
  107027. knows where there's a hole in the data,
  107028. but we need coupling so that the codec
  107029. (which is in a seperate abstraction
  107030. layer) also knows about the gap */
  107031. } ogg_packet;
  107032. typedef struct {
  107033. unsigned char *data;
  107034. int storage;
  107035. int fill;
  107036. int returned;
  107037. int unsynced;
  107038. int headerbytes;
  107039. int bodybytes;
  107040. } ogg_sync_state;
  107041. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107042. extern void oggpack_writeinit(oggpack_buffer *b);
  107043. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107044. extern void oggpack_writealign(oggpack_buffer *b);
  107045. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107046. extern void oggpack_reset(oggpack_buffer *b);
  107047. extern void oggpack_writeclear(oggpack_buffer *b);
  107048. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107049. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107050. extern long oggpack_look(oggpack_buffer *b,int bits);
  107051. extern long oggpack_look1(oggpack_buffer *b);
  107052. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107053. extern void oggpack_adv1(oggpack_buffer *b);
  107054. extern long oggpack_read(oggpack_buffer *b,int bits);
  107055. extern long oggpack_read1(oggpack_buffer *b);
  107056. extern long oggpack_bytes(oggpack_buffer *b);
  107057. extern long oggpack_bits(oggpack_buffer *b);
  107058. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107059. extern void oggpackB_writeinit(oggpack_buffer *b);
  107060. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107061. extern void oggpackB_writealign(oggpack_buffer *b);
  107062. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107063. extern void oggpackB_reset(oggpack_buffer *b);
  107064. extern void oggpackB_writeclear(oggpack_buffer *b);
  107065. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107066. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107067. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107068. extern long oggpackB_look1(oggpack_buffer *b);
  107069. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107070. extern void oggpackB_adv1(oggpack_buffer *b);
  107071. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107072. extern long oggpackB_read1(oggpack_buffer *b);
  107073. extern long oggpackB_bytes(oggpack_buffer *b);
  107074. extern long oggpackB_bits(oggpack_buffer *b);
  107075. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107076. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107077. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107078. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107079. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107080. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107081. extern int ogg_sync_init(ogg_sync_state *oy);
  107082. extern int ogg_sync_clear(ogg_sync_state *oy);
  107083. extern int ogg_sync_reset(ogg_sync_state *oy);
  107084. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107085. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107086. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107087. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107088. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107089. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107090. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107091. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107092. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107093. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107094. extern int ogg_stream_clear(ogg_stream_state *os);
  107095. extern int ogg_stream_reset(ogg_stream_state *os);
  107096. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107097. extern int ogg_stream_destroy(ogg_stream_state *os);
  107098. extern int ogg_stream_eos(ogg_stream_state *os);
  107099. extern void ogg_page_checksum_set(ogg_page *og);
  107100. extern int ogg_page_version(ogg_page *og);
  107101. extern int ogg_page_continued(ogg_page *og);
  107102. extern int ogg_page_bos(ogg_page *og);
  107103. extern int ogg_page_eos(ogg_page *og);
  107104. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107105. extern int ogg_page_serialno(ogg_page *og);
  107106. extern long ogg_page_pageno(ogg_page *og);
  107107. extern int ogg_page_packets(ogg_page *og);
  107108. extern void ogg_packet_clear(ogg_packet *op);
  107109. #ifdef __cplusplus
  107110. }
  107111. #endif
  107112. #endif /* _OGG_H */
  107113. /*** End of inlined file: ogg.h ***/
  107114. typedef struct vorbis_info{
  107115. int version;
  107116. int channels;
  107117. long rate;
  107118. /* The below bitrate declarations are *hints*.
  107119. Combinations of the three values carry the following implications:
  107120. all three set to the same value:
  107121. implies a fixed rate bitstream
  107122. only nominal set:
  107123. implies a VBR stream that averages the nominal bitrate. No hard
  107124. upper/lower limit
  107125. upper and or lower set:
  107126. implies a VBR bitstream that obeys the bitrate limits. nominal
  107127. may also be set to give a nominal rate.
  107128. none set:
  107129. the coder does not care to speculate.
  107130. */
  107131. long bitrate_upper;
  107132. long bitrate_nominal;
  107133. long bitrate_lower;
  107134. long bitrate_window;
  107135. void *codec_setup;
  107136. } vorbis_info;
  107137. /* vorbis_dsp_state buffers the current vorbis audio
  107138. analysis/synthesis state. The DSP state belongs to a specific
  107139. logical bitstream ****************************************************/
  107140. typedef struct vorbis_dsp_state{
  107141. int analysisp;
  107142. vorbis_info *vi;
  107143. float **pcm;
  107144. float **pcmret;
  107145. int pcm_storage;
  107146. int pcm_current;
  107147. int pcm_returned;
  107148. int preextrapolate;
  107149. int eofflag;
  107150. long lW;
  107151. long W;
  107152. long nW;
  107153. long centerW;
  107154. ogg_int64_t granulepos;
  107155. ogg_int64_t sequence;
  107156. ogg_int64_t glue_bits;
  107157. ogg_int64_t time_bits;
  107158. ogg_int64_t floor_bits;
  107159. ogg_int64_t res_bits;
  107160. void *backend_state;
  107161. } vorbis_dsp_state;
  107162. typedef struct vorbis_block{
  107163. /* necessary stream state for linking to the framing abstraction */
  107164. float **pcm; /* this is a pointer into local storage */
  107165. oggpack_buffer opb;
  107166. long lW;
  107167. long W;
  107168. long nW;
  107169. int pcmend;
  107170. int mode;
  107171. int eofflag;
  107172. ogg_int64_t granulepos;
  107173. ogg_int64_t sequence;
  107174. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107175. /* local storage to avoid remallocing; it's up to the mapping to
  107176. structure it */
  107177. void *localstore;
  107178. long localtop;
  107179. long localalloc;
  107180. long totaluse;
  107181. struct alloc_chain *reap;
  107182. /* bitmetrics for the frame */
  107183. long glue_bits;
  107184. long time_bits;
  107185. long floor_bits;
  107186. long res_bits;
  107187. void *internal;
  107188. } vorbis_block;
  107189. /* vorbis_block is a single block of data to be processed as part of
  107190. the analysis/synthesis stream; it belongs to a specific logical
  107191. bitstream, but is independant from other vorbis_blocks belonging to
  107192. that logical bitstream. *************************************************/
  107193. struct alloc_chain{
  107194. void *ptr;
  107195. struct alloc_chain *next;
  107196. };
  107197. /* vorbis_info contains all the setup information specific to the
  107198. specific compression/decompression mode in progress (eg,
  107199. psychoacoustic settings, channel setup, options, codebook
  107200. etc). vorbis_info and substructures are in backends.h.
  107201. *********************************************************************/
  107202. /* the comments are not part of vorbis_info so that vorbis_info can be
  107203. static storage */
  107204. typedef struct vorbis_comment{
  107205. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107206. whatever vendor is set to in encode */
  107207. char **user_comments;
  107208. int *comment_lengths;
  107209. int comments;
  107210. char *vendor;
  107211. } vorbis_comment;
  107212. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107213. and produce a packet (see docs/analysis.txt). The packet is then
  107214. coded into a framed OggSquish bitstream by the second layer (see
  107215. docs/framing.txt). Decode is the reverse process; we sync/frame
  107216. the bitstream and extract individual packets, then decode the
  107217. packet back into PCM audio.
  107218. The extra framing/packetizing is used in streaming formats, such as
  107219. files. Over the net (such as with UDP), the framing and
  107220. packetization aren't necessary as they're provided by the transport
  107221. and the streaming layer is not used */
  107222. /* Vorbis PRIMITIVES: general ***************************************/
  107223. extern void vorbis_info_init(vorbis_info *vi);
  107224. extern void vorbis_info_clear(vorbis_info *vi);
  107225. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107226. extern void vorbis_comment_init(vorbis_comment *vc);
  107227. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107228. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107229. const char *tag, char *contents);
  107230. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107231. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107232. extern void vorbis_comment_clear(vorbis_comment *vc);
  107233. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107234. extern int vorbis_block_clear(vorbis_block *vb);
  107235. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107236. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107237. ogg_int64_t granulepos);
  107238. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107239. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107240. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107241. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107242. vorbis_comment *vc,
  107243. ogg_packet *op,
  107244. ogg_packet *op_comm,
  107245. ogg_packet *op_code);
  107246. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107247. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107248. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107249. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107250. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107251. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107252. ogg_packet *op);
  107253. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107254. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107255. ogg_packet *op);
  107256. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107257. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107258. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107259. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107260. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107261. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107262. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107263. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107264. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107265. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107266. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107267. /* Vorbis ERRORS and return codes ***********************************/
  107268. #define OV_FALSE -1
  107269. #define OV_EOF -2
  107270. #define OV_HOLE -3
  107271. #define OV_EREAD -128
  107272. #define OV_EFAULT -129
  107273. #define OV_EIMPL -130
  107274. #define OV_EINVAL -131
  107275. #define OV_ENOTVORBIS -132
  107276. #define OV_EBADHEADER -133
  107277. #define OV_EVERSION -134
  107278. #define OV_ENOTAUDIO -135
  107279. #define OV_EBADPACKET -136
  107280. #define OV_EBADLINK -137
  107281. #define OV_ENOSEEK -138
  107282. #ifdef __cplusplus
  107283. }
  107284. #endif /* __cplusplus */
  107285. #endif
  107286. /*** End of inlined file: codec.h ***/
  107287. extern int vorbis_encode_init(vorbis_info *vi,
  107288. long channels,
  107289. long rate,
  107290. long max_bitrate,
  107291. long nominal_bitrate,
  107292. long min_bitrate);
  107293. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107294. long channels,
  107295. long rate,
  107296. long max_bitrate,
  107297. long nominal_bitrate,
  107298. long min_bitrate);
  107299. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107300. long channels,
  107301. long rate,
  107302. float quality /* quality level from 0. (lo) to 1. (hi) */
  107303. );
  107304. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107305. long channels,
  107306. long rate,
  107307. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107308. );
  107309. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107310. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107311. /* deprecated rate management supported only for compatability */
  107312. #define OV_ECTL_RATEMANAGE_GET 0x10
  107313. #define OV_ECTL_RATEMANAGE_SET 0x11
  107314. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107315. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107316. struct ovectl_ratemanage_arg {
  107317. int management_active;
  107318. long bitrate_hard_min;
  107319. long bitrate_hard_max;
  107320. double bitrate_hard_window;
  107321. long bitrate_av_lo;
  107322. long bitrate_av_hi;
  107323. double bitrate_av_window;
  107324. double bitrate_av_window_center;
  107325. };
  107326. /* new rate setup */
  107327. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107328. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107329. struct ovectl_ratemanage2_arg {
  107330. int management_active;
  107331. long bitrate_limit_min_kbps;
  107332. long bitrate_limit_max_kbps;
  107333. long bitrate_limit_reservoir_bits;
  107334. double bitrate_limit_reservoir_bias;
  107335. long bitrate_average_kbps;
  107336. double bitrate_average_damping;
  107337. };
  107338. #define OV_ECTL_LOWPASS_GET 0x20
  107339. #define OV_ECTL_LOWPASS_SET 0x21
  107340. #define OV_ECTL_IBLOCK_GET 0x30
  107341. #define OV_ECTL_IBLOCK_SET 0x31
  107342. #ifdef __cplusplus
  107343. }
  107344. #endif /* __cplusplus */
  107345. #endif
  107346. /*** End of inlined file: vorbisenc.h ***/
  107347. /*** Start of inlined file: vorbisfile.h ***/
  107348. #ifndef _OV_FILE_H_
  107349. #define _OV_FILE_H_
  107350. #ifdef __cplusplus
  107351. extern "C"
  107352. {
  107353. #endif /* __cplusplus */
  107354. #include <stdio.h>
  107355. /* The function prototypes for the callbacks are basically the same as for
  107356. * the stdio functions fread, fseek, fclose, ftell.
  107357. * The one difference is that the FILE * arguments have been replaced with
  107358. * a void * - this is to be used as a pointer to whatever internal data these
  107359. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107360. *
  107361. * If you use other functions, check the docs for these functions and return
  107362. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107363. * unseekable
  107364. */
  107365. typedef struct {
  107366. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107367. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107368. int (*close_func) (void *datasource);
  107369. long (*tell_func) (void *datasource);
  107370. } ov_callbacks;
  107371. #define NOTOPEN 0
  107372. #define PARTOPEN 1
  107373. #define OPENED 2
  107374. #define STREAMSET 3
  107375. #define INITSET 4
  107376. typedef struct OggVorbis_File {
  107377. void *datasource; /* Pointer to a FILE *, etc. */
  107378. int seekable;
  107379. ogg_int64_t offset;
  107380. ogg_int64_t end;
  107381. ogg_sync_state oy;
  107382. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107383. stream appears */
  107384. int links;
  107385. ogg_int64_t *offsets;
  107386. ogg_int64_t *dataoffsets;
  107387. long *serialnos;
  107388. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107389. compatability; x2 size, stores both
  107390. beginning and end values */
  107391. vorbis_info *vi;
  107392. vorbis_comment *vc;
  107393. /* Decoding working state local storage */
  107394. ogg_int64_t pcm_offset;
  107395. int ready_state;
  107396. long current_serialno;
  107397. int current_link;
  107398. double bittrack;
  107399. double samptrack;
  107400. ogg_stream_state os; /* take physical pages, weld into a logical
  107401. stream of packets */
  107402. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107403. vorbis_block vb; /* local working space for packet->PCM decode */
  107404. ov_callbacks callbacks;
  107405. } OggVorbis_File;
  107406. extern int ov_clear(OggVorbis_File *vf);
  107407. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107408. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107409. char *initial, long ibytes, ov_callbacks callbacks);
  107410. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107411. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107412. char *initial, long ibytes, ov_callbacks callbacks);
  107413. extern int ov_test_open(OggVorbis_File *vf);
  107414. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107415. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107416. extern long ov_streams(OggVorbis_File *vf);
  107417. extern long ov_seekable(OggVorbis_File *vf);
  107418. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107419. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107420. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107421. extern double ov_time_total(OggVorbis_File *vf,int i);
  107422. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107423. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107424. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107425. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107426. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107427. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107428. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107429. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107430. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107431. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107432. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107433. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107434. extern double ov_time_tell(OggVorbis_File *vf);
  107435. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107436. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107437. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107438. int *bitstream);
  107439. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107440. int bigendianp,int word,int sgned,int *bitstream);
  107441. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107442. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107443. extern int ov_halfrate_p(OggVorbis_File *vf);
  107444. #ifdef __cplusplus
  107445. }
  107446. #endif /* __cplusplus */
  107447. #endif
  107448. /*** End of inlined file: vorbisfile.h ***/
  107449. /*** Start of inlined file: bitwise.c ***/
  107450. /* We're 'LSb' endian; if we write a word but read individual bits,
  107451. then we'll read the lsb first */
  107452. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107453. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107454. // tasks..
  107455. #if JUCE_MSVC
  107456. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107457. #endif
  107458. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107459. #if JUCE_USE_OGGVORBIS
  107460. #include <string.h>
  107461. #include <stdlib.h>
  107462. #define BUFFER_INCREMENT 256
  107463. static const unsigned long mask[]=
  107464. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107465. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107466. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107467. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107468. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107469. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107470. 0x3fffffff,0x7fffffff,0xffffffff };
  107471. static const unsigned int mask8B[]=
  107472. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107473. void oggpack_writeinit(oggpack_buffer *b){
  107474. memset(b,0,sizeof(*b));
  107475. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107476. b->buffer[0]='\0';
  107477. b->storage=BUFFER_INCREMENT;
  107478. }
  107479. void oggpackB_writeinit(oggpack_buffer *b){
  107480. oggpack_writeinit(b);
  107481. }
  107482. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107483. long bytes=bits>>3;
  107484. bits-=bytes*8;
  107485. b->ptr=b->buffer+bytes;
  107486. b->endbit=bits;
  107487. b->endbyte=bytes;
  107488. *b->ptr&=mask[bits];
  107489. }
  107490. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107491. long bytes=bits>>3;
  107492. bits-=bytes*8;
  107493. b->ptr=b->buffer+bytes;
  107494. b->endbit=bits;
  107495. b->endbyte=bytes;
  107496. *b->ptr&=mask8B[bits];
  107497. }
  107498. /* Takes only up to 32 bits. */
  107499. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  107500. if(b->endbyte+4>=b->storage){
  107501. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107502. b->storage+=BUFFER_INCREMENT;
  107503. b->ptr=b->buffer+b->endbyte;
  107504. }
  107505. value&=mask[bits];
  107506. bits+=b->endbit;
  107507. b->ptr[0]|=value<<b->endbit;
  107508. if(bits>=8){
  107509. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  107510. if(bits>=16){
  107511. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  107512. if(bits>=24){
  107513. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  107514. if(bits>=32){
  107515. if(b->endbit)
  107516. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  107517. else
  107518. b->ptr[4]=0;
  107519. }
  107520. }
  107521. }
  107522. }
  107523. b->endbyte+=bits/8;
  107524. b->ptr+=bits/8;
  107525. b->endbit=bits&7;
  107526. }
  107527. /* Takes only up to 32 bits. */
  107528. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  107529. if(b->endbyte+4>=b->storage){
  107530. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107531. b->storage+=BUFFER_INCREMENT;
  107532. b->ptr=b->buffer+b->endbyte;
  107533. }
  107534. value=(value&mask[bits])<<(32-bits);
  107535. bits+=b->endbit;
  107536. b->ptr[0]|=value>>(24+b->endbit);
  107537. if(bits>=8){
  107538. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  107539. if(bits>=16){
  107540. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  107541. if(bits>=24){
  107542. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  107543. if(bits>=32){
  107544. if(b->endbit)
  107545. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  107546. else
  107547. b->ptr[4]=0;
  107548. }
  107549. }
  107550. }
  107551. }
  107552. b->endbyte+=bits/8;
  107553. b->ptr+=bits/8;
  107554. b->endbit=bits&7;
  107555. }
  107556. void oggpack_writealign(oggpack_buffer *b){
  107557. int bits=8-b->endbit;
  107558. if(bits<8)
  107559. oggpack_write(b,0,bits);
  107560. }
  107561. void oggpackB_writealign(oggpack_buffer *b){
  107562. int bits=8-b->endbit;
  107563. if(bits<8)
  107564. oggpackB_write(b,0,bits);
  107565. }
  107566. static void oggpack_writecopy_helper(oggpack_buffer *b,
  107567. void *source,
  107568. long bits,
  107569. void (*w)(oggpack_buffer *,
  107570. unsigned long,
  107571. int),
  107572. int msb){
  107573. unsigned char *ptr=(unsigned char *)source;
  107574. long bytes=bits/8;
  107575. bits-=bytes*8;
  107576. if(b->endbit){
  107577. int i;
  107578. /* unaligned copy. Do it the hard way. */
  107579. for(i=0;i<bytes;i++)
  107580. w(b,(unsigned long)(ptr[i]),8);
  107581. }else{
  107582. /* aligned block copy */
  107583. if(b->endbyte+bytes+1>=b->storage){
  107584. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  107585. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  107586. b->ptr=b->buffer+b->endbyte;
  107587. }
  107588. memmove(b->ptr,source,bytes);
  107589. b->ptr+=bytes;
  107590. b->endbyte+=bytes;
  107591. *b->ptr=0;
  107592. }
  107593. if(bits){
  107594. if(msb)
  107595. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  107596. else
  107597. w(b,(unsigned long)(ptr[bytes]),bits);
  107598. }
  107599. }
  107600. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  107601. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  107602. }
  107603. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  107604. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  107605. }
  107606. void oggpack_reset(oggpack_buffer *b){
  107607. b->ptr=b->buffer;
  107608. b->buffer[0]=0;
  107609. b->endbit=b->endbyte=0;
  107610. }
  107611. void oggpackB_reset(oggpack_buffer *b){
  107612. oggpack_reset(b);
  107613. }
  107614. void oggpack_writeclear(oggpack_buffer *b){
  107615. _ogg_free(b->buffer);
  107616. memset(b,0,sizeof(*b));
  107617. }
  107618. void oggpackB_writeclear(oggpack_buffer *b){
  107619. oggpack_writeclear(b);
  107620. }
  107621. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107622. memset(b,0,sizeof(*b));
  107623. b->buffer=b->ptr=buf;
  107624. b->storage=bytes;
  107625. }
  107626. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107627. oggpack_readinit(b,buf,bytes);
  107628. }
  107629. /* Read in bits without advancing the bitptr; bits <= 32 */
  107630. long oggpack_look(oggpack_buffer *b,int bits){
  107631. unsigned long ret;
  107632. unsigned long m=mask[bits];
  107633. bits+=b->endbit;
  107634. if(b->endbyte+4>=b->storage){
  107635. /* not the main path */
  107636. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107637. }
  107638. ret=b->ptr[0]>>b->endbit;
  107639. if(bits>8){
  107640. ret|=b->ptr[1]<<(8-b->endbit);
  107641. if(bits>16){
  107642. ret|=b->ptr[2]<<(16-b->endbit);
  107643. if(bits>24){
  107644. ret|=b->ptr[3]<<(24-b->endbit);
  107645. if(bits>32 && b->endbit)
  107646. ret|=b->ptr[4]<<(32-b->endbit);
  107647. }
  107648. }
  107649. }
  107650. return(m&ret);
  107651. }
  107652. /* Read in bits without advancing the bitptr; bits <= 32 */
  107653. long oggpackB_look(oggpack_buffer *b,int bits){
  107654. unsigned long ret;
  107655. int m=32-bits;
  107656. bits+=b->endbit;
  107657. if(b->endbyte+4>=b->storage){
  107658. /* not the main path */
  107659. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107660. }
  107661. ret=b->ptr[0]<<(24+b->endbit);
  107662. if(bits>8){
  107663. ret|=b->ptr[1]<<(16+b->endbit);
  107664. if(bits>16){
  107665. ret|=b->ptr[2]<<(8+b->endbit);
  107666. if(bits>24){
  107667. ret|=b->ptr[3]<<(b->endbit);
  107668. if(bits>32 && b->endbit)
  107669. ret|=b->ptr[4]>>(8-b->endbit);
  107670. }
  107671. }
  107672. }
  107673. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  107674. }
  107675. long oggpack_look1(oggpack_buffer *b){
  107676. if(b->endbyte>=b->storage)return(-1);
  107677. return((b->ptr[0]>>b->endbit)&1);
  107678. }
  107679. long oggpackB_look1(oggpack_buffer *b){
  107680. if(b->endbyte>=b->storage)return(-1);
  107681. return((b->ptr[0]>>(7-b->endbit))&1);
  107682. }
  107683. void oggpack_adv(oggpack_buffer *b,int bits){
  107684. bits+=b->endbit;
  107685. b->ptr+=bits/8;
  107686. b->endbyte+=bits/8;
  107687. b->endbit=bits&7;
  107688. }
  107689. void oggpackB_adv(oggpack_buffer *b,int bits){
  107690. oggpack_adv(b,bits);
  107691. }
  107692. void oggpack_adv1(oggpack_buffer *b){
  107693. if(++(b->endbit)>7){
  107694. b->endbit=0;
  107695. b->ptr++;
  107696. b->endbyte++;
  107697. }
  107698. }
  107699. void oggpackB_adv1(oggpack_buffer *b){
  107700. oggpack_adv1(b);
  107701. }
  107702. /* bits <= 32 */
  107703. long oggpack_read(oggpack_buffer *b,int bits){
  107704. long ret;
  107705. unsigned long m=mask[bits];
  107706. bits+=b->endbit;
  107707. if(b->endbyte+4>=b->storage){
  107708. /* not the main path */
  107709. ret=-1L;
  107710. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107711. }
  107712. ret=b->ptr[0]>>b->endbit;
  107713. if(bits>8){
  107714. ret|=b->ptr[1]<<(8-b->endbit);
  107715. if(bits>16){
  107716. ret|=b->ptr[2]<<(16-b->endbit);
  107717. if(bits>24){
  107718. ret|=b->ptr[3]<<(24-b->endbit);
  107719. if(bits>32 && b->endbit){
  107720. ret|=b->ptr[4]<<(32-b->endbit);
  107721. }
  107722. }
  107723. }
  107724. }
  107725. ret&=m;
  107726. overflow:
  107727. b->ptr+=bits/8;
  107728. b->endbyte+=bits/8;
  107729. b->endbit=bits&7;
  107730. return(ret);
  107731. }
  107732. /* bits <= 32 */
  107733. long oggpackB_read(oggpack_buffer *b,int bits){
  107734. long ret;
  107735. long m=32-bits;
  107736. bits+=b->endbit;
  107737. if(b->endbyte+4>=b->storage){
  107738. /* not the main path */
  107739. ret=-1L;
  107740. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107741. }
  107742. ret=b->ptr[0]<<(24+b->endbit);
  107743. if(bits>8){
  107744. ret|=b->ptr[1]<<(16+b->endbit);
  107745. if(bits>16){
  107746. ret|=b->ptr[2]<<(8+b->endbit);
  107747. if(bits>24){
  107748. ret|=b->ptr[3]<<(b->endbit);
  107749. if(bits>32 && b->endbit)
  107750. ret|=b->ptr[4]>>(8-b->endbit);
  107751. }
  107752. }
  107753. }
  107754. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  107755. overflow:
  107756. b->ptr+=bits/8;
  107757. b->endbyte+=bits/8;
  107758. b->endbit=bits&7;
  107759. return(ret);
  107760. }
  107761. long oggpack_read1(oggpack_buffer *b){
  107762. long ret;
  107763. if(b->endbyte>=b->storage){
  107764. /* not the main path */
  107765. ret=-1L;
  107766. goto overflow;
  107767. }
  107768. ret=(b->ptr[0]>>b->endbit)&1;
  107769. overflow:
  107770. b->endbit++;
  107771. if(b->endbit>7){
  107772. b->endbit=0;
  107773. b->ptr++;
  107774. b->endbyte++;
  107775. }
  107776. return(ret);
  107777. }
  107778. long oggpackB_read1(oggpack_buffer *b){
  107779. long ret;
  107780. if(b->endbyte>=b->storage){
  107781. /* not the main path */
  107782. ret=-1L;
  107783. goto overflow;
  107784. }
  107785. ret=(b->ptr[0]>>(7-b->endbit))&1;
  107786. overflow:
  107787. b->endbit++;
  107788. if(b->endbit>7){
  107789. b->endbit=0;
  107790. b->ptr++;
  107791. b->endbyte++;
  107792. }
  107793. return(ret);
  107794. }
  107795. long oggpack_bytes(oggpack_buffer *b){
  107796. return(b->endbyte+(b->endbit+7)/8);
  107797. }
  107798. long oggpack_bits(oggpack_buffer *b){
  107799. return(b->endbyte*8+b->endbit);
  107800. }
  107801. long oggpackB_bytes(oggpack_buffer *b){
  107802. return oggpack_bytes(b);
  107803. }
  107804. long oggpackB_bits(oggpack_buffer *b){
  107805. return oggpack_bits(b);
  107806. }
  107807. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  107808. return(b->buffer);
  107809. }
  107810. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  107811. return oggpack_get_buffer(b);
  107812. }
  107813. /* Self test of the bitwise routines; everything else is based on
  107814. them, so they damned well better be solid. */
  107815. #ifdef _V_SELFTEST
  107816. #include <stdio.h>
  107817. static int ilog(unsigned int v){
  107818. int ret=0;
  107819. while(v){
  107820. ret++;
  107821. v>>=1;
  107822. }
  107823. return(ret);
  107824. }
  107825. oggpack_buffer o;
  107826. oggpack_buffer r;
  107827. void report(char *in){
  107828. fprintf(stderr,"%s",in);
  107829. exit(1);
  107830. }
  107831. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107832. long bytes,i;
  107833. unsigned char *buffer;
  107834. oggpack_reset(&o);
  107835. for(i=0;i<vals;i++)
  107836. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  107837. buffer=oggpack_get_buffer(&o);
  107838. bytes=oggpack_bytes(&o);
  107839. if(bytes!=compsize)report("wrong number of bytes!\n");
  107840. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107841. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107842. report("wrote incorrect value!\n");
  107843. }
  107844. oggpack_readinit(&r,buffer,bytes);
  107845. for(i=0;i<vals;i++){
  107846. int tbit=bits?bits:ilog(b[i]);
  107847. if(oggpack_look(&r,tbit)==-1)
  107848. report("out of data!\n");
  107849. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  107850. report("looked at incorrect value!\n");
  107851. if(tbit==1)
  107852. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  107853. report("looked at single bit incorrect value!\n");
  107854. if(tbit==1){
  107855. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  107856. report("read incorrect single bit value!\n");
  107857. }else{
  107858. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  107859. report("read incorrect value!\n");
  107860. }
  107861. }
  107862. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107863. }
  107864. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107865. long bytes,i;
  107866. unsigned char *buffer;
  107867. oggpackB_reset(&o);
  107868. for(i=0;i<vals;i++)
  107869. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  107870. buffer=oggpackB_get_buffer(&o);
  107871. bytes=oggpackB_bytes(&o);
  107872. if(bytes!=compsize)report("wrong number of bytes!\n");
  107873. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107874. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107875. report("wrote incorrect value!\n");
  107876. }
  107877. oggpackB_readinit(&r,buffer,bytes);
  107878. for(i=0;i<vals;i++){
  107879. int tbit=bits?bits:ilog(b[i]);
  107880. if(oggpackB_look(&r,tbit)==-1)
  107881. report("out of data!\n");
  107882. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  107883. report("looked at incorrect value!\n");
  107884. if(tbit==1)
  107885. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  107886. report("looked at single bit incorrect value!\n");
  107887. if(tbit==1){
  107888. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  107889. report("read incorrect single bit value!\n");
  107890. }else{
  107891. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  107892. report("read incorrect value!\n");
  107893. }
  107894. }
  107895. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107896. }
  107897. int main(void){
  107898. unsigned char *buffer;
  107899. long bytes,i;
  107900. static unsigned long testbuffer1[]=
  107901. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  107902. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  107903. int test1size=43;
  107904. static unsigned long testbuffer2[]=
  107905. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  107906. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  107907. 85525151,0,12321,1,349528352};
  107908. int test2size=21;
  107909. static unsigned long testbuffer3[]=
  107910. {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,
  107911. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  107912. int test3size=56;
  107913. static unsigned long large[]=
  107914. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  107915. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  107916. 85525151,0,12321,1,2146528352};
  107917. int onesize=33;
  107918. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  107919. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  107920. 223,4};
  107921. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  107922. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  107923. 245,251,128};
  107924. int twosize=6;
  107925. static int two[6]={61,255,255,251,231,29};
  107926. static int twoB[6]={247,63,255,253,249,120};
  107927. int threesize=54;
  107928. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  107929. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  107930. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  107931. 100,52,4,14,18,86,77,1};
  107932. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  107933. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  107934. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  107935. 200,20,254,4,58,106,176,144,0};
  107936. int foursize=38;
  107937. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  107938. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  107939. 28,2,133,0,1};
  107940. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  107941. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  107942. 129,10,4,32};
  107943. int fivesize=45;
  107944. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  107945. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  107946. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  107947. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  107948. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  107949. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  107950. int sixsize=7;
  107951. static int six[7]={17,177,170,242,169,19,148};
  107952. static int sixB[7]={136,141,85,79,149,200,41};
  107953. /* Test read/write together */
  107954. /* Later we test against pregenerated bitstreams */
  107955. oggpack_writeinit(&o);
  107956. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  107957. cliptest(testbuffer1,test1size,0,one,onesize);
  107958. fprintf(stderr,"ok.");
  107959. fprintf(stderr,"\nNull bit call (LSb): ");
  107960. cliptest(testbuffer3,test3size,0,two,twosize);
  107961. fprintf(stderr,"ok.");
  107962. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  107963. cliptest(testbuffer2,test2size,0,three,threesize);
  107964. fprintf(stderr,"ok.");
  107965. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  107966. oggpack_reset(&o);
  107967. for(i=0;i<test2size;i++)
  107968. oggpack_write(&o,large[i],32);
  107969. buffer=oggpack_get_buffer(&o);
  107970. bytes=oggpack_bytes(&o);
  107971. oggpack_readinit(&r,buffer,bytes);
  107972. for(i=0;i<test2size;i++){
  107973. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  107974. if(oggpack_look(&r,32)!=large[i]){
  107975. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  107976. oggpack_look(&r,32),large[i]);
  107977. report("read incorrect value!\n");
  107978. }
  107979. oggpack_adv(&r,32);
  107980. }
  107981. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107982. fprintf(stderr,"ok.");
  107983. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  107984. cliptest(testbuffer1,test1size,7,four,foursize);
  107985. fprintf(stderr,"ok.");
  107986. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  107987. cliptest(testbuffer2,test2size,17,five,fivesize);
  107988. fprintf(stderr,"ok.");
  107989. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  107990. cliptest(testbuffer3,test3size,1,six,sixsize);
  107991. fprintf(stderr,"ok.");
  107992. fprintf(stderr,"\nTesting read past end (LSb): ");
  107993. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107994. for(i=0;i<64;i++){
  107995. if(oggpack_read(&r,1)!=0){
  107996. fprintf(stderr,"failed; got -1 prematurely.\n");
  107997. exit(1);
  107998. }
  107999. }
  108000. if(oggpack_look(&r,1)!=-1 ||
  108001. oggpack_read(&r,1)!=-1){
  108002. fprintf(stderr,"failed; read past end without -1.\n");
  108003. exit(1);
  108004. }
  108005. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108006. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  108007. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108008. exit(1);
  108009. }
  108010. if(oggpack_look(&r,18)!=0 ||
  108011. oggpack_look(&r,18)!=0){
  108012. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108013. exit(1);
  108014. }
  108015. if(oggpack_look(&r,19)!=-1 ||
  108016. oggpack_look(&r,19)!=-1){
  108017. fprintf(stderr,"failed; read past end without -1.\n");
  108018. exit(1);
  108019. }
  108020. if(oggpack_look(&r,32)!=-1 ||
  108021. oggpack_look(&r,32)!=-1){
  108022. fprintf(stderr,"failed; read past end without -1.\n");
  108023. exit(1);
  108024. }
  108025. oggpack_writeclear(&o);
  108026. fprintf(stderr,"ok.\n");
  108027. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108028. /* Test read/write together */
  108029. /* Later we test against pregenerated bitstreams */
  108030. oggpackB_writeinit(&o);
  108031. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108032. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108033. fprintf(stderr,"ok.");
  108034. fprintf(stderr,"\nNull bit call (MSb): ");
  108035. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108036. fprintf(stderr,"ok.");
  108037. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108038. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108039. fprintf(stderr,"ok.");
  108040. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108041. oggpackB_reset(&o);
  108042. for(i=0;i<test2size;i++)
  108043. oggpackB_write(&o,large[i],32);
  108044. buffer=oggpackB_get_buffer(&o);
  108045. bytes=oggpackB_bytes(&o);
  108046. oggpackB_readinit(&r,buffer,bytes);
  108047. for(i=0;i<test2size;i++){
  108048. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108049. if(oggpackB_look(&r,32)!=large[i]){
  108050. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108051. oggpackB_look(&r,32),large[i]);
  108052. report("read incorrect value!\n");
  108053. }
  108054. oggpackB_adv(&r,32);
  108055. }
  108056. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108057. fprintf(stderr,"ok.");
  108058. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108059. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108060. fprintf(stderr,"ok.");
  108061. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108062. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108063. fprintf(stderr,"ok.");
  108064. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108065. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108066. fprintf(stderr,"ok.");
  108067. fprintf(stderr,"\nTesting read past end (MSb): ");
  108068. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108069. for(i=0;i<64;i++){
  108070. if(oggpackB_read(&r,1)!=0){
  108071. fprintf(stderr,"failed; got -1 prematurely.\n");
  108072. exit(1);
  108073. }
  108074. }
  108075. if(oggpackB_look(&r,1)!=-1 ||
  108076. oggpackB_read(&r,1)!=-1){
  108077. fprintf(stderr,"failed; read past end without -1.\n");
  108078. exit(1);
  108079. }
  108080. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108081. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108082. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108083. exit(1);
  108084. }
  108085. if(oggpackB_look(&r,18)!=0 ||
  108086. oggpackB_look(&r,18)!=0){
  108087. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108088. exit(1);
  108089. }
  108090. if(oggpackB_look(&r,19)!=-1 ||
  108091. oggpackB_look(&r,19)!=-1){
  108092. fprintf(stderr,"failed; read past end without -1.\n");
  108093. exit(1);
  108094. }
  108095. if(oggpackB_look(&r,32)!=-1 ||
  108096. oggpackB_look(&r,32)!=-1){
  108097. fprintf(stderr,"failed; read past end without -1.\n");
  108098. exit(1);
  108099. }
  108100. oggpackB_writeclear(&o);
  108101. fprintf(stderr,"ok.\n\n");
  108102. return(0);
  108103. }
  108104. #endif /* _V_SELFTEST */
  108105. #undef BUFFER_INCREMENT
  108106. #endif
  108107. /*** End of inlined file: bitwise.c ***/
  108108. /*** Start of inlined file: framing.c ***/
  108109. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108110. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108111. // tasks..
  108112. #if JUCE_MSVC
  108113. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108114. #endif
  108115. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108116. #if JUCE_USE_OGGVORBIS
  108117. #include <stdlib.h>
  108118. #include <string.h>
  108119. /* A complete description of Ogg framing exists in docs/framing.html */
  108120. int ogg_page_version(ogg_page *og){
  108121. return((int)(og->header[4]));
  108122. }
  108123. int ogg_page_continued(ogg_page *og){
  108124. return((int)(og->header[5]&0x01));
  108125. }
  108126. int ogg_page_bos(ogg_page *og){
  108127. return((int)(og->header[5]&0x02));
  108128. }
  108129. int ogg_page_eos(ogg_page *og){
  108130. return((int)(og->header[5]&0x04));
  108131. }
  108132. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108133. unsigned char *page=og->header;
  108134. ogg_int64_t granulepos=page[13]&(0xff);
  108135. granulepos= (granulepos<<8)|(page[12]&0xff);
  108136. granulepos= (granulepos<<8)|(page[11]&0xff);
  108137. granulepos= (granulepos<<8)|(page[10]&0xff);
  108138. granulepos= (granulepos<<8)|(page[9]&0xff);
  108139. granulepos= (granulepos<<8)|(page[8]&0xff);
  108140. granulepos= (granulepos<<8)|(page[7]&0xff);
  108141. granulepos= (granulepos<<8)|(page[6]&0xff);
  108142. return(granulepos);
  108143. }
  108144. int ogg_page_serialno(ogg_page *og){
  108145. return(og->header[14] |
  108146. (og->header[15]<<8) |
  108147. (og->header[16]<<16) |
  108148. (og->header[17]<<24));
  108149. }
  108150. long ogg_page_pageno(ogg_page *og){
  108151. return(og->header[18] |
  108152. (og->header[19]<<8) |
  108153. (og->header[20]<<16) |
  108154. (og->header[21]<<24));
  108155. }
  108156. /* returns the number of packets that are completed on this page (if
  108157. the leading packet is begun on a previous page, but ends on this
  108158. page, it's counted */
  108159. /* NOTE:
  108160. If a page consists of a packet begun on a previous page, and a new
  108161. packet begun (but not completed) on this page, the return will be:
  108162. ogg_page_packets(page) ==1,
  108163. ogg_page_continued(page) !=0
  108164. If a page happens to be a single packet that was begun on a
  108165. previous page, and spans to the next page (in the case of a three or
  108166. more page packet), the return will be:
  108167. ogg_page_packets(page) ==0,
  108168. ogg_page_continued(page) !=0
  108169. */
  108170. int ogg_page_packets(ogg_page *og){
  108171. int i,n=og->header[26],count=0;
  108172. for(i=0;i<n;i++)
  108173. if(og->header[27+i]<255)count++;
  108174. return(count);
  108175. }
  108176. #if 0
  108177. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108178. use the static init below) */
  108179. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108180. int i;
  108181. unsigned long r;
  108182. r = index << 24;
  108183. for (i=0; i<8; i++)
  108184. if (r & 0x80000000UL)
  108185. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108186. polynomial, although we use an
  108187. unreflected alg and an init/final
  108188. of 0, not 0xffffffff */
  108189. else
  108190. r<<=1;
  108191. return (r & 0xffffffffUL);
  108192. }
  108193. #endif
  108194. static const ogg_uint32_t crc_lookup[256]={
  108195. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108196. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108197. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108198. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108199. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108200. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108201. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108202. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108203. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108204. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108205. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108206. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108207. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108208. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108209. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108210. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108211. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108212. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108213. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108214. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108215. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108216. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108217. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108218. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108219. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108220. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108221. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108222. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108223. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108224. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108225. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108226. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108227. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108228. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108229. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108230. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108231. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108232. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108233. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108234. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108235. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108236. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108237. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108238. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108239. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108240. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108241. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108242. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108243. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108244. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108245. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108246. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108247. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108248. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108249. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108250. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108251. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108252. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108253. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108254. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108255. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108256. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108257. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108258. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108259. /* init the encode/decode logical stream state */
  108260. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108261. if(os){
  108262. memset(os,0,sizeof(*os));
  108263. os->body_storage=16*1024;
  108264. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108265. os->lacing_storage=1024;
  108266. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108267. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108268. os->serialno=serialno;
  108269. return(0);
  108270. }
  108271. return(-1);
  108272. }
  108273. /* _clear does not free os, only the non-flat storage within */
  108274. int ogg_stream_clear(ogg_stream_state *os){
  108275. if(os){
  108276. if(os->body_data)_ogg_free(os->body_data);
  108277. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108278. if(os->granule_vals)_ogg_free(os->granule_vals);
  108279. memset(os,0,sizeof(*os));
  108280. }
  108281. return(0);
  108282. }
  108283. int ogg_stream_destroy(ogg_stream_state *os){
  108284. if(os){
  108285. ogg_stream_clear(os);
  108286. _ogg_free(os);
  108287. }
  108288. return(0);
  108289. }
  108290. /* Helpers for ogg_stream_encode; this keeps the structure and
  108291. what's happening fairly clear */
  108292. static void _os_body_expand(ogg_stream_state *os,int needed){
  108293. if(os->body_storage<=os->body_fill+needed){
  108294. os->body_storage+=(needed+1024);
  108295. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108296. }
  108297. }
  108298. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108299. if(os->lacing_storage<=os->lacing_fill+needed){
  108300. os->lacing_storage+=(needed+32);
  108301. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108302. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108303. }
  108304. }
  108305. /* checksum the page */
  108306. /* Direct table CRC; note that this will be faster in the future if we
  108307. perform the checksum silmultaneously with other copies */
  108308. void ogg_page_checksum_set(ogg_page *og){
  108309. if(og){
  108310. ogg_uint32_t crc_reg=0;
  108311. int i;
  108312. /* safety; needed for API behavior, but not framing code */
  108313. og->header[22]=0;
  108314. og->header[23]=0;
  108315. og->header[24]=0;
  108316. og->header[25]=0;
  108317. for(i=0;i<og->header_len;i++)
  108318. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108319. for(i=0;i<og->body_len;i++)
  108320. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108321. og->header[22]=(unsigned char)(crc_reg&0xff);
  108322. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108323. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108324. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108325. }
  108326. }
  108327. /* submit data to the internal buffer of the framing engine */
  108328. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108329. int lacing_vals=op->bytes/255+1,i;
  108330. if(os->body_returned){
  108331. /* advance packet data according to the body_returned pointer. We
  108332. had to keep it around to return a pointer into the buffer last
  108333. call */
  108334. os->body_fill-=os->body_returned;
  108335. if(os->body_fill)
  108336. memmove(os->body_data,os->body_data+os->body_returned,
  108337. os->body_fill);
  108338. os->body_returned=0;
  108339. }
  108340. /* make sure we have the buffer storage */
  108341. _os_body_expand(os,op->bytes);
  108342. _os_lacing_expand(os,lacing_vals);
  108343. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108344. the liability of overly clean abstraction for the time being. It
  108345. will actually be fairly easy to eliminate the extra copy in the
  108346. future */
  108347. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108348. os->body_fill+=op->bytes;
  108349. /* Store lacing vals for this packet */
  108350. for(i=0;i<lacing_vals-1;i++){
  108351. os->lacing_vals[os->lacing_fill+i]=255;
  108352. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108353. }
  108354. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108355. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108356. /* flag the first segment as the beginning of the packet */
  108357. os->lacing_vals[os->lacing_fill]|= 0x100;
  108358. os->lacing_fill+=lacing_vals;
  108359. /* for the sake of completeness */
  108360. os->packetno++;
  108361. if(op->e_o_s)os->e_o_s=1;
  108362. return(0);
  108363. }
  108364. /* This will flush remaining packets into a page (returning nonzero),
  108365. even if there is not enough data to trigger a flush normally
  108366. (undersized page). If there are no packets or partial packets to
  108367. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108368. try to flush a normal sized page like ogg_stream_pageout; a call to
  108369. ogg_stream_flush does not guarantee that all packets have flushed.
  108370. Only a return value of 0 from ogg_stream_flush indicates all packet
  108371. data is flushed into pages.
  108372. since ogg_stream_flush will flush the last page in a stream even if
  108373. it's undersized, you almost certainly want to use ogg_stream_pageout
  108374. (and *not* ogg_stream_flush) unless you specifically need to flush
  108375. an page regardless of size in the middle of a stream. */
  108376. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108377. int i;
  108378. int vals=0;
  108379. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108380. int bytes=0;
  108381. long acc=0;
  108382. ogg_int64_t granule_pos=-1;
  108383. if(maxvals==0)return(0);
  108384. /* construct a page */
  108385. /* decide how many segments to include */
  108386. /* If this is the initial header case, the first page must only include
  108387. the initial header packet */
  108388. if(os->b_o_s==0){ /* 'initial header page' case */
  108389. granule_pos=0;
  108390. for(vals=0;vals<maxvals;vals++){
  108391. if((os->lacing_vals[vals]&0x0ff)<255){
  108392. vals++;
  108393. break;
  108394. }
  108395. }
  108396. }else{
  108397. for(vals=0;vals<maxvals;vals++){
  108398. if(acc>4096)break;
  108399. acc+=os->lacing_vals[vals]&0x0ff;
  108400. if((os->lacing_vals[vals]&0xff)<255)
  108401. granule_pos=os->granule_vals[vals];
  108402. }
  108403. }
  108404. /* construct the header in temp storage */
  108405. memcpy(os->header,"OggS",4);
  108406. /* stream structure version */
  108407. os->header[4]=0x00;
  108408. /* continued packet flag? */
  108409. os->header[5]=0x00;
  108410. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108411. /* first page flag? */
  108412. if(os->b_o_s==0)os->header[5]|=0x02;
  108413. /* last page flag? */
  108414. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108415. os->b_o_s=1;
  108416. /* 64 bits of PCM position */
  108417. for(i=6;i<14;i++){
  108418. os->header[i]=(unsigned char)(granule_pos&0xff);
  108419. granule_pos>>=8;
  108420. }
  108421. /* 32 bits of stream serial number */
  108422. {
  108423. long serialno=os->serialno;
  108424. for(i=14;i<18;i++){
  108425. os->header[i]=(unsigned char)(serialno&0xff);
  108426. serialno>>=8;
  108427. }
  108428. }
  108429. /* 32 bits of page counter (we have both counter and page header
  108430. because this val can roll over) */
  108431. if(os->pageno==-1)os->pageno=0; /* because someone called
  108432. stream_reset; this would be a
  108433. strange thing to do in an
  108434. encode stream, but it has
  108435. plausible uses */
  108436. {
  108437. long pageno=os->pageno++;
  108438. for(i=18;i<22;i++){
  108439. os->header[i]=(unsigned char)(pageno&0xff);
  108440. pageno>>=8;
  108441. }
  108442. }
  108443. /* zero for computation; filled in later */
  108444. os->header[22]=0;
  108445. os->header[23]=0;
  108446. os->header[24]=0;
  108447. os->header[25]=0;
  108448. /* segment table */
  108449. os->header[26]=(unsigned char)(vals&0xff);
  108450. for(i=0;i<vals;i++)
  108451. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108452. /* set pointers in the ogg_page struct */
  108453. og->header=os->header;
  108454. og->header_len=os->header_fill=vals+27;
  108455. og->body=os->body_data+os->body_returned;
  108456. og->body_len=bytes;
  108457. /* advance the lacing data and set the body_returned pointer */
  108458. os->lacing_fill-=vals;
  108459. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108460. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108461. os->body_returned+=bytes;
  108462. /* calculate the checksum */
  108463. ogg_page_checksum_set(og);
  108464. /* done */
  108465. return(1);
  108466. }
  108467. /* This constructs pages from buffered packet segments. The pointers
  108468. returned are to static buffers; do not free. The returned buffers are
  108469. good only until the next call (using the same ogg_stream_state) */
  108470. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108471. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108472. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108473. os->lacing_fill>=255 || /* 'segment table full' case */
  108474. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108475. return(ogg_stream_flush(os,og));
  108476. }
  108477. /* not enough data to construct a page and not end of stream */
  108478. return(0);
  108479. }
  108480. int ogg_stream_eos(ogg_stream_state *os){
  108481. return os->e_o_s;
  108482. }
  108483. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108484. /* This has two layers to place more of the multi-serialno and paging
  108485. control in the application's hands. First, we expose a data buffer
  108486. using ogg_sync_buffer(). The app either copies into the
  108487. buffer, or passes it directly to read(), etc. We then call
  108488. ogg_sync_wrote() to tell how many bytes we just added.
  108489. Pages are returned (pointers into the buffer in ogg_sync_state)
  108490. by ogg_sync_pageout(). The page is then submitted to
  108491. ogg_stream_pagein() along with the appropriate
  108492. ogg_stream_state* (ie, matching serialno). We then get raw
  108493. packets out calling ogg_stream_packetout() with a
  108494. ogg_stream_state. */
  108495. /* initialize the struct to a known state */
  108496. int ogg_sync_init(ogg_sync_state *oy){
  108497. if(oy){
  108498. memset(oy,0,sizeof(*oy));
  108499. }
  108500. return(0);
  108501. }
  108502. /* clear non-flat storage within */
  108503. int ogg_sync_clear(ogg_sync_state *oy){
  108504. if(oy){
  108505. if(oy->data)_ogg_free(oy->data);
  108506. ogg_sync_init(oy);
  108507. }
  108508. return(0);
  108509. }
  108510. int ogg_sync_destroy(ogg_sync_state *oy){
  108511. if(oy){
  108512. ogg_sync_clear(oy);
  108513. _ogg_free(oy);
  108514. }
  108515. return(0);
  108516. }
  108517. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  108518. /* first, clear out any space that has been previously returned */
  108519. if(oy->returned){
  108520. oy->fill-=oy->returned;
  108521. if(oy->fill>0)
  108522. memmove(oy->data,oy->data+oy->returned,oy->fill);
  108523. oy->returned=0;
  108524. }
  108525. if(size>oy->storage-oy->fill){
  108526. /* We need to extend the internal buffer */
  108527. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  108528. if(oy->data)
  108529. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  108530. else
  108531. oy->data=(unsigned char*) _ogg_malloc(newsize);
  108532. oy->storage=newsize;
  108533. }
  108534. /* expose a segment at least as large as requested at the fill mark */
  108535. return((char *)oy->data+oy->fill);
  108536. }
  108537. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  108538. if(oy->fill+bytes>oy->storage)return(-1);
  108539. oy->fill+=bytes;
  108540. return(0);
  108541. }
  108542. /* sync the stream. This is meant to be useful for finding page
  108543. boundaries.
  108544. return values for this:
  108545. -n) skipped n bytes
  108546. 0) page not ready; more data (no bytes skipped)
  108547. n) page synced at current location; page length n bytes
  108548. */
  108549. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  108550. unsigned char *page=oy->data+oy->returned;
  108551. unsigned char *next;
  108552. long bytes=oy->fill-oy->returned;
  108553. if(oy->headerbytes==0){
  108554. int headerbytes,i;
  108555. if(bytes<27)return(0); /* not enough for a header */
  108556. /* verify capture pattern */
  108557. if(memcmp(page,"OggS",4))goto sync_fail;
  108558. headerbytes=page[26]+27;
  108559. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  108560. /* count up body length in the segment table */
  108561. for(i=0;i<page[26];i++)
  108562. oy->bodybytes+=page[27+i];
  108563. oy->headerbytes=headerbytes;
  108564. }
  108565. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  108566. /* The whole test page is buffered. Verify the checksum */
  108567. {
  108568. /* Grab the checksum bytes, set the header field to zero */
  108569. char chksum[4];
  108570. ogg_page log;
  108571. memcpy(chksum,page+22,4);
  108572. memset(page+22,0,4);
  108573. /* set up a temp page struct and recompute the checksum */
  108574. log.header=page;
  108575. log.header_len=oy->headerbytes;
  108576. log.body=page+oy->headerbytes;
  108577. log.body_len=oy->bodybytes;
  108578. ogg_page_checksum_set(&log);
  108579. /* Compare */
  108580. if(memcmp(chksum,page+22,4)){
  108581. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  108582. at all) */
  108583. /* replace the computed checksum with the one actually read in */
  108584. memcpy(page+22,chksum,4);
  108585. /* Bad checksum. Lose sync */
  108586. goto sync_fail;
  108587. }
  108588. }
  108589. /* yes, have a whole page all ready to go */
  108590. {
  108591. unsigned char *page=oy->data+oy->returned;
  108592. long bytes;
  108593. if(og){
  108594. og->header=page;
  108595. og->header_len=oy->headerbytes;
  108596. og->body=page+oy->headerbytes;
  108597. og->body_len=oy->bodybytes;
  108598. }
  108599. oy->unsynced=0;
  108600. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  108601. oy->headerbytes=0;
  108602. oy->bodybytes=0;
  108603. return(bytes);
  108604. }
  108605. sync_fail:
  108606. oy->headerbytes=0;
  108607. oy->bodybytes=0;
  108608. /* search for possible capture */
  108609. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  108610. if(!next)
  108611. next=oy->data+oy->fill;
  108612. oy->returned=next-oy->data;
  108613. return(-(next-page));
  108614. }
  108615. /* sync the stream and get a page. Keep trying until we find a page.
  108616. Supress 'sync errors' after reporting the first.
  108617. return values:
  108618. -1) recapture (hole in data)
  108619. 0) need more data
  108620. 1) page returned
  108621. Returns pointers into buffered data; invalidated by next call to
  108622. _stream, _clear, _init, or _buffer */
  108623. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  108624. /* all we need to do is verify a page at the head of the stream
  108625. buffer. If it doesn't verify, we look for the next potential
  108626. frame */
  108627. for(;;){
  108628. long ret=ogg_sync_pageseek(oy,og);
  108629. if(ret>0){
  108630. /* have a page */
  108631. return(1);
  108632. }
  108633. if(ret==0){
  108634. /* need more data */
  108635. return(0);
  108636. }
  108637. /* head did not start a synced page... skipped some bytes */
  108638. if(!oy->unsynced){
  108639. oy->unsynced=1;
  108640. return(-1);
  108641. }
  108642. /* loop. keep looking */
  108643. }
  108644. }
  108645. /* add the incoming page to the stream state; we decompose the page
  108646. into packet segments here as well. */
  108647. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  108648. unsigned char *header=og->header;
  108649. unsigned char *body=og->body;
  108650. long bodysize=og->body_len;
  108651. int segptr=0;
  108652. int version=ogg_page_version(og);
  108653. int continued=ogg_page_continued(og);
  108654. int bos=ogg_page_bos(og);
  108655. int eos=ogg_page_eos(og);
  108656. ogg_int64_t granulepos=ogg_page_granulepos(og);
  108657. int serialno=ogg_page_serialno(og);
  108658. long pageno=ogg_page_pageno(og);
  108659. int segments=header[26];
  108660. /* clean up 'returned data' */
  108661. {
  108662. long lr=os->lacing_returned;
  108663. long br=os->body_returned;
  108664. /* body data */
  108665. if(br){
  108666. os->body_fill-=br;
  108667. if(os->body_fill)
  108668. memmove(os->body_data,os->body_data+br,os->body_fill);
  108669. os->body_returned=0;
  108670. }
  108671. if(lr){
  108672. /* segment table */
  108673. if(os->lacing_fill-lr){
  108674. memmove(os->lacing_vals,os->lacing_vals+lr,
  108675. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  108676. memmove(os->granule_vals,os->granule_vals+lr,
  108677. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  108678. }
  108679. os->lacing_fill-=lr;
  108680. os->lacing_packet-=lr;
  108681. os->lacing_returned=0;
  108682. }
  108683. }
  108684. /* check the serial number */
  108685. if(serialno!=os->serialno)return(-1);
  108686. if(version>0)return(-1);
  108687. _os_lacing_expand(os,segments+1);
  108688. /* are we in sequence? */
  108689. if(pageno!=os->pageno){
  108690. int i;
  108691. /* unroll previous partial packet (if any) */
  108692. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  108693. os->body_fill-=os->lacing_vals[i]&0xff;
  108694. os->lacing_fill=os->lacing_packet;
  108695. /* make a note of dropped data in segment table */
  108696. if(os->pageno!=-1){
  108697. os->lacing_vals[os->lacing_fill++]=0x400;
  108698. os->lacing_packet++;
  108699. }
  108700. }
  108701. /* are we a 'continued packet' page? If so, we may need to skip
  108702. some segments */
  108703. if(continued){
  108704. if(os->lacing_fill<1 ||
  108705. os->lacing_vals[os->lacing_fill-1]==0x400){
  108706. bos=0;
  108707. for(;segptr<segments;segptr++){
  108708. int val=header[27+segptr];
  108709. body+=val;
  108710. bodysize-=val;
  108711. if(val<255){
  108712. segptr++;
  108713. break;
  108714. }
  108715. }
  108716. }
  108717. }
  108718. if(bodysize){
  108719. _os_body_expand(os,bodysize);
  108720. memcpy(os->body_data+os->body_fill,body,bodysize);
  108721. os->body_fill+=bodysize;
  108722. }
  108723. {
  108724. int saved=-1;
  108725. while(segptr<segments){
  108726. int val=header[27+segptr];
  108727. os->lacing_vals[os->lacing_fill]=val;
  108728. os->granule_vals[os->lacing_fill]=-1;
  108729. if(bos){
  108730. os->lacing_vals[os->lacing_fill]|=0x100;
  108731. bos=0;
  108732. }
  108733. if(val<255)saved=os->lacing_fill;
  108734. os->lacing_fill++;
  108735. segptr++;
  108736. if(val<255)os->lacing_packet=os->lacing_fill;
  108737. }
  108738. /* set the granulepos on the last granuleval of the last full packet */
  108739. if(saved!=-1){
  108740. os->granule_vals[saved]=granulepos;
  108741. }
  108742. }
  108743. if(eos){
  108744. os->e_o_s=1;
  108745. if(os->lacing_fill>0)
  108746. os->lacing_vals[os->lacing_fill-1]|=0x200;
  108747. }
  108748. os->pageno=pageno+1;
  108749. return(0);
  108750. }
  108751. /* clear things to an initial state. Good to call, eg, before seeking */
  108752. int ogg_sync_reset(ogg_sync_state *oy){
  108753. oy->fill=0;
  108754. oy->returned=0;
  108755. oy->unsynced=0;
  108756. oy->headerbytes=0;
  108757. oy->bodybytes=0;
  108758. return(0);
  108759. }
  108760. int ogg_stream_reset(ogg_stream_state *os){
  108761. os->body_fill=0;
  108762. os->body_returned=0;
  108763. os->lacing_fill=0;
  108764. os->lacing_packet=0;
  108765. os->lacing_returned=0;
  108766. os->header_fill=0;
  108767. os->e_o_s=0;
  108768. os->b_o_s=0;
  108769. os->pageno=-1;
  108770. os->packetno=0;
  108771. os->granulepos=0;
  108772. return(0);
  108773. }
  108774. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  108775. ogg_stream_reset(os);
  108776. os->serialno=serialno;
  108777. return(0);
  108778. }
  108779. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  108780. /* The last part of decode. We have the stream broken into packet
  108781. segments. Now we need to group them into packets (or return the
  108782. out of sync markers) */
  108783. int ptr=os->lacing_returned;
  108784. if(os->lacing_packet<=ptr)return(0);
  108785. if(os->lacing_vals[ptr]&0x400){
  108786. /* we need to tell the codec there's a gap; it might need to
  108787. handle previous packet dependencies. */
  108788. os->lacing_returned++;
  108789. os->packetno++;
  108790. return(-1);
  108791. }
  108792. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  108793. to ask if there's a whole packet
  108794. waiting */
  108795. /* Gather the whole packet. We'll have no holes or a partial packet */
  108796. {
  108797. int size=os->lacing_vals[ptr]&0xff;
  108798. int bytes=size;
  108799. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  108800. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  108801. while(size==255){
  108802. int val=os->lacing_vals[++ptr];
  108803. size=val&0xff;
  108804. if(val&0x200)eos=0x200;
  108805. bytes+=size;
  108806. }
  108807. if(op){
  108808. op->e_o_s=eos;
  108809. op->b_o_s=bos;
  108810. op->packet=os->body_data+os->body_returned;
  108811. op->packetno=os->packetno;
  108812. op->granulepos=os->granule_vals[ptr];
  108813. op->bytes=bytes;
  108814. }
  108815. if(adv){
  108816. os->body_returned+=bytes;
  108817. os->lacing_returned=ptr+1;
  108818. os->packetno++;
  108819. }
  108820. }
  108821. return(1);
  108822. }
  108823. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  108824. return _packetout(os,op,1);
  108825. }
  108826. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  108827. return _packetout(os,op,0);
  108828. }
  108829. void ogg_packet_clear(ogg_packet *op) {
  108830. _ogg_free(op->packet);
  108831. memset(op, 0, sizeof(*op));
  108832. }
  108833. #ifdef _V_SELFTEST
  108834. #include <stdio.h>
  108835. ogg_stream_state os_en, os_de;
  108836. ogg_sync_state oy;
  108837. void checkpacket(ogg_packet *op,int len, int no, int pos){
  108838. long j;
  108839. static int sequence=0;
  108840. static int lastno=0;
  108841. if(op->bytes!=len){
  108842. fprintf(stderr,"incorrect packet length!\n");
  108843. exit(1);
  108844. }
  108845. if(op->granulepos!=pos){
  108846. fprintf(stderr,"incorrect packet position!\n");
  108847. exit(1);
  108848. }
  108849. /* packet number just follows sequence/gap; adjust the input number
  108850. for that */
  108851. if(no==0){
  108852. sequence=0;
  108853. }else{
  108854. sequence++;
  108855. if(no>lastno+1)
  108856. sequence++;
  108857. }
  108858. lastno=no;
  108859. if(op->packetno!=sequence){
  108860. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  108861. (long)(op->packetno),sequence);
  108862. exit(1);
  108863. }
  108864. /* Test data */
  108865. for(j=0;j<op->bytes;j++)
  108866. if(op->packet[j]!=((j+no)&0xff)){
  108867. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  108868. j,op->packet[j],(j+no)&0xff);
  108869. exit(1);
  108870. }
  108871. }
  108872. void check_page(unsigned char *data,const int *header,ogg_page *og){
  108873. long j;
  108874. /* Test data */
  108875. for(j=0;j<og->body_len;j++)
  108876. if(og->body[j]!=data[j]){
  108877. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  108878. j,data[j],og->body[j]);
  108879. exit(1);
  108880. }
  108881. /* Test header */
  108882. for(j=0;j<og->header_len;j++){
  108883. if(og->header[j]!=header[j]){
  108884. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  108885. for(j=0;j<header[26]+27;j++)
  108886. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  108887. fprintf(stderr,"\n");
  108888. exit(1);
  108889. }
  108890. }
  108891. if(og->header_len!=header[26]+27){
  108892. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  108893. og->header_len,header[26]+27);
  108894. exit(1);
  108895. }
  108896. }
  108897. void print_header(ogg_page *og){
  108898. int j;
  108899. fprintf(stderr,"\nHEADER:\n");
  108900. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  108901. og->header[0],og->header[1],og->header[2],og->header[3],
  108902. (int)og->header[4],(int)og->header[5]);
  108903. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  108904. (og->header[9]<<24)|(og->header[8]<<16)|
  108905. (og->header[7]<<8)|og->header[6],
  108906. (og->header[17]<<24)|(og->header[16]<<16)|
  108907. (og->header[15]<<8)|og->header[14],
  108908. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  108909. (og->header[19]<<8)|og->header[18]);
  108910. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  108911. (int)og->header[22],(int)og->header[23],
  108912. (int)og->header[24],(int)og->header[25],
  108913. (int)og->header[26]);
  108914. for(j=27;j<og->header_len;j++)
  108915. fprintf(stderr,"%d ",(int)og->header[j]);
  108916. fprintf(stderr,")\n\n");
  108917. }
  108918. void copy_page(ogg_page *og){
  108919. unsigned char *temp=_ogg_malloc(og->header_len);
  108920. memcpy(temp,og->header,og->header_len);
  108921. og->header=temp;
  108922. temp=_ogg_malloc(og->body_len);
  108923. memcpy(temp,og->body,og->body_len);
  108924. og->body=temp;
  108925. }
  108926. void free_page(ogg_page *og){
  108927. _ogg_free (og->header);
  108928. _ogg_free (og->body);
  108929. }
  108930. void error(void){
  108931. fprintf(stderr,"error!\n");
  108932. exit(1);
  108933. }
  108934. /* 17 only */
  108935. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  108936. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108937. 0x01,0x02,0x03,0x04,0,0,0,0,
  108938. 0x15,0xed,0xec,0x91,
  108939. 1,
  108940. 17};
  108941. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  108942. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108943. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108944. 0x01,0x02,0x03,0x04,0,0,0,0,
  108945. 0x59,0x10,0x6c,0x2c,
  108946. 1,
  108947. 17};
  108948. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108949. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  108950. 0x01,0x02,0x03,0x04,1,0,0,0,
  108951. 0x89,0x33,0x85,0xce,
  108952. 13,
  108953. 254,255,0,255,1,255,245,255,255,0,
  108954. 255,255,90};
  108955. /* nil packets; beginning,middle,end */
  108956. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108957. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108958. 0x01,0x02,0x03,0x04,0,0,0,0,
  108959. 0xff,0x7b,0x23,0x17,
  108960. 1,
  108961. 0};
  108962. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108963. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  108964. 0x01,0x02,0x03,0x04,1,0,0,0,
  108965. 0x5c,0x3f,0x66,0xcb,
  108966. 17,
  108967. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  108968. 255,255,90,0};
  108969. /* large initial packet */
  108970. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108971. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108972. 0x01,0x02,0x03,0x04,0,0,0,0,
  108973. 0x01,0x27,0x31,0xaa,
  108974. 18,
  108975. 255,255,255,255,255,255,255,255,
  108976. 255,255,255,255,255,255,255,255,255,10};
  108977. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108978. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  108979. 0x01,0x02,0x03,0x04,1,0,0,0,
  108980. 0x7f,0x4e,0x8a,0xd2,
  108981. 4,
  108982. 255,4,255,0};
  108983. /* continuing packet test */
  108984. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108985. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108986. 0x01,0x02,0x03,0x04,0,0,0,0,
  108987. 0xff,0x7b,0x23,0x17,
  108988. 1,
  108989. 0};
  108990. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108991. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  108992. 0x01,0x02,0x03,0x04,1,0,0,0,
  108993. 0x54,0x05,0x51,0xc8,
  108994. 17,
  108995. 255,255,255,255,255,255,255,255,
  108996. 255,255,255,255,255,255,255,255,255};
  108997. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108998. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  108999. 0x01,0x02,0x03,0x04,2,0,0,0,
  109000. 0xc8,0xc3,0xcb,0xed,
  109001. 5,
  109002. 10,255,4,255,0};
  109003. /* page with the 255 segment limit */
  109004. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109005. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109006. 0x01,0x02,0x03,0x04,0,0,0,0,
  109007. 0xff,0x7b,0x23,0x17,
  109008. 1,
  109009. 0};
  109010. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109011. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  109012. 0x01,0x02,0x03,0x04,1,0,0,0,
  109013. 0xed,0x2a,0x2e,0xa7,
  109014. 255,
  109015. 10,10,10,10,10,10,10,10,
  109016. 10,10,10,10,10,10,10,10,
  109017. 10,10,10,10,10,10,10,10,
  109018. 10,10,10,10,10,10,10,10,
  109019. 10,10,10,10,10,10,10,10,
  109020. 10,10,10,10,10,10,10,10,
  109021. 10,10,10,10,10,10,10,10,
  109022. 10,10,10,10,10,10,10,10,
  109023. 10,10,10,10,10,10,10,10,
  109024. 10,10,10,10,10,10,10,10,
  109025. 10,10,10,10,10,10,10,10,
  109026. 10,10,10,10,10,10,10,10,
  109027. 10,10,10,10,10,10,10,10,
  109028. 10,10,10,10,10,10,10,10,
  109029. 10,10,10,10,10,10,10,10,
  109030. 10,10,10,10,10,10,10,10,
  109031. 10,10,10,10,10,10,10,10,
  109032. 10,10,10,10,10,10,10,10,
  109033. 10,10,10,10,10,10,10,10,
  109034. 10,10,10,10,10,10,10,10,
  109035. 10,10,10,10,10,10,10,10,
  109036. 10,10,10,10,10,10,10,10,
  109037. 10,10,10,10,10,10,10,10,
  109038. 10,10,10,10,10,10,10,10,
  109039. 10,10,10,10,10,10,10,10,
  109040. 10,10,10,10,10,10,10,10,
  109041. 10,10,10,10,10,10,10,10,
  109042. 10,10,10,10,10,10,10,10,
  109043. 10,10,10,10,10,10,10,10,
  109044. 10,10,10,10,10,10,10,10,
  109045. 10,10,10,10,10,10,10,10,
  109046. 10,10,10,10,10,10,10};
  109047. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109048. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109049. 0x01,0x02,0x03,0x04,2,0,0,0,
  109050. 0x6c,0x3b,0x82,0x3d,
  109051. 1,
  109052. 50};
  109053. /* packet that overspans over an entire page */
  109054. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109055. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109056. 0x01,0x02,0x03,0x04,0,0,0,0,
  109057. 0xff,0x7b,0x23,0x17,
  109058. 1,
  109059. 0};
  109060. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109061. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109062. 0x01,0x02,0x03,0x04,1,0,0,0,
  109063. 0x3c,0xd9,0x4d,0x3f,
  109064. 17,
  109065. 100,255,255,255,255,255,255,255,255,
  109066. 255,255,255,255,255,255,255,255};
  109067. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109068. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109069. 0x01,0x02,0x03,0x04,2,0,0,0,
  109070. 0x01,0xd2,0xe5,0xe5,
  109071. 17,
  109072. 255,255,255,255,255,255,255,255,
  109073. 255,255,255,255,255,255,255,255,255};
  109074. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109075. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109076. 0x01,0x02,0x03,0x04,3,0,0,0,
  109077. 0xef,0xdd,0x88,0xde,
  109078. 7,
  109079. 255,255,75,255,4,255,0};
  109080. /* packet that overspans over an entire page */
  109081. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109082. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109083. 0x01,0x02,0x03,0x04,0,0,0,0,
  109084. 0xff,0x7b,0x23,0x17,
  109085. 1,
  109086. 0};
  109087. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109088. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109089. 0x01,0x02,0x03,0x04,1,0,0,0,
  109090. 0x3c,0xd9,0x4d,0x3f,
  109091. 17,
  109092. 100,255,255,255,255,255,255,255,255,
  109093. 255,255,255,255,255,255,255,255};
  109094. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109095. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109096. 0x01,0x02,0x03,0x04,2,0,0,0,
  109097. 0xd4,0xe0,0x60,0xe5,
  109098. 1,0};
  109099. void test_pack(const int *pl, const int **headers, int byteskip,
  109100. int pageskip, int packetskip){
  109101. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109102. long inptr=0;
  109103. long outptr=0;
  109104. long deptr=0;
  109105. long depacket=0;
  109106. long granule_pos=7,pageno=0;
  109107. int i,j,packets,pageout=pageskip;
  109108. int eosflag=0;
  109109. int bosflag=0;
  109110. int byteskipcount=0;
  109111. ogg_stream_reset(&os_en);
  109112. ogg_stream_reset(&os_de);
  109113. ogg_sync_reset(&oy);
  109114. for(packets=0;packets<packetskip;packets++)
  109115. depacket+=pl[packets];
  109116. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109117. for(i=0;i<packets;i++){
  109118. /* construct a test packet */
  109119. ogg_packet op;
  109120. int len=pl[i];
  109121. op.packet=data+inptr;
  109122. op.bytes=len;
  109123. op.e_o_s=(pl[i+1]<0?1:0);
  109124. op.granulepos=granule_pos;
  109125. granule_pos+=1024;
  109126. for(j=0;j<len;j++)data[inptr++]=i+j;
  109127. /* submit the test packet */
  109128. ogg_stream_packetin(&os_en,&op);
  109129. /* retrieve any finished pages */
  109130. {
  109131. ogg_page og;
  109132. while(ogg_stream_pageout(&os_en,&og)){
  109133. /* We have a page. Check it carefully */
  109134. fprintf(stderr,"%ld, ",pageno);
  109135. if(headers[pageno]==NULL){
  109136. fprintf(stderr,"coded too many pages!\n");
  109137. exit(1);
  109138. }
  109139. check_page(data+outptr,headers[pageno],&og);
  109140. outptr+=og.body_len;
  109141. pageno++;
  109142. if(pageskip){
  109143. bosflag=1;
  109144. pageskip--;
  109145. deptr+=og.body_len;
  109146. }
  109147. /* have a complete page; submit it to sync/decode */
  109148. {
  109149. ogg_page og_de;
  109150. ogg_packet op_de,op_de2;
  109151. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109152. char *next=buf;
  109153. byteskipcount+=og.header_len;
  109154. if(byteskipcount>byteskip){
  109155. memcpy(next,og.header,byteskipcount-byteskip);
  109156. next+=byteskipcount-byteskip;
  109157. byteskipcount=byteskip;
  109158. }
  109159. byteskipcount+=og.body_len;
  109160. if(byteskipcount>byteskip){
  109161. memcpy(next,og.body,byteskipcount-byteskip);
  109162. next+=byteskipcount-byteskip;
  109163. byteskipcount=byteskip;
  109164. }
  109165. ogg_sync_wrote(&oy,next-buf);
  109166. while(1){
  109167. int ret=ogg_sync_pageout(&oy,&og_de);
  109168. if(ret==0)break;
  109169. if(ret<0)continue;
  109170. /* got a page. Happy happy. Verify that it's good. */
  109171. fprintf(stderr,"(%ld), ",pageout);
  109172. check_page(data+deptr,headers[pageout],&og_de);
  109173. deptr+=og_de.body_len;
  109174. pageout++;
  109175. /* submit it to deconstitution */
  109176. ogg_stream_pagein(&os_de,&og_de);
  109177. /* packets out? */
  109178. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109179. ogg_stream_packetpeek(&os_de,NULL);
  109180. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109181. /* verify peek and out match */
  109182. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109183. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109184. depacket);
  109185. exit(1);
  109186. }
  109187. /* verify the packet! */
  109188. /* check data */
  109189. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109190. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109191. depacket);
  109192. exit(1);
  109193. }
  109194. /* check bos flag */
  109195. if(bosflag==0 && op_de.b_o_s==0){
  109196. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109197. exit(1);
  109198. }
  109199. if(bosflag && op_de.b_o_s){
  109200. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109201. exit(1);
  109202. }
  109203. bosflag=1;
  109204. depacket+=op_de.bytes;
  109205. /* check eos flag */
  109206. if(eosflag){
  109207. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109208. exit(1);
  109209. }
  109210. if(op_de.e_o_s)eosflag=1;
  109211. /* check granulepos flag */
  109212. if(op_de.granulepos!=-1){
  109213. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109214. }
  109215. }
  109216. }
  109217. }
  109218. }
  109219. }
  109220. }
  109221. _ogg_free(data);
  109222. if(headers[pageno]!=NULL){
  109223. fprintf(stderr,"did not write last page!\n");
  109224. exit(1);
  109225. }
  109226. if(headers[pageout]!=NULL){
  109227. fprintf(stderr,"did not decode last page!\n");
  109228. exit(1);
  109229. }
  109230. if(inptr!=outptr){
  109231. fprintf(stderr,"encoded page data incomplete!\n");
  109232. exit(1);
  109233. }
  109234. if(inptr!=deptr){
  109235. fprintf(stderr,"decoded page data incomplete!\n");
  109236. exit(1);
  109237. }
  109238. if(inptr!=depacket){
  109239. fprintf(stderr,"decoded packet data incomplete!\n");
  109240. exit(1);
  109241. }
  109242. if(!eosflag){
  109243. fprintf(stderr,"Never got a packet with EOS set!\n");
  109244. exit(1);
  109245. }
  109246. fprintf(stderr,"ok.\n");
  109247. }
  109248. int main(void){
  109249. ogg_stream_init(&os_en,0x04030201);
  109250. ogg_stream_init(&os_de,0x04030201);
  109251. ogg_sync_init(&oy);
  109252. /* Exercise each code path in the framing code. Also verify that
  109253. the checksums are working. */
  109254. {
  109255. /* 17 only */
  109256. const int packets[]={17, -1};
  109257. const int *headret[]={head1_0,NULL};
  109258. fprintf(stderr,"testing single page encoding... ");
  109259. test_pack(packets,headret,0,0,0);
  109260. }
  109261. {
  109262. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109263. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109264. const int *headret[]={head1_1,head2_1,NULL};
  109265. fprintf(stderr,"testing basic page encoding... ");
  109266. test_pack(packets,headret,0,0,0);
  109267. }
  109268. {
  109269. /* nil packets; beginning,middle,end */
  109270. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109271. const int *headret[]={head1_2,head2_2,NULL};
  109272. fprintf(stderr,"testing basic nil packets... ");
  109273. test_pack(packets,headret,0,0,0);
  109274. }
  109275. {
  109276. /* large initial packet */
  109277. const int packets[]={4345,259,255,-1};
  109278. const int *headret[]={head1_3,head2_3,NULL};
  109279. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109280. test_pack(packets,headret,0,0,0);
  109281. }
  109282. {
  109283. /* continuing packet test */
  109284. const int packets[]={0,4345,259,255,-1};
  109285. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109286. fprintf(stderr,"testing single packet page span... ");
  109287. test_pack(packets,headret,0,0,0);
  109288. }
  109289. /* page with the 255 segment limit */
  109290. {
  109291. const int packets[]={0,10,10,10,10,10,10,10,10,
  109292. 10,10,10,10,10,10,10,10,
  109293. 10,10,10,10,10,10,10,10,
  109294. 10,10,10,10,10,10,10,10,
  109295. 10,10,10,10,10,10,10,10,
  109296. 10,10,10,10,10,10,10,10,
  109297. 10,10,10,10,10,10,10,10,
  109298. 10,10,10,10,10,10,10,10,
  109299. 10,10,10,10,10,10,10,10,
  109300. 10,10,10,10,10,10,10,10,
  109301. 10,10,10,10,10,10,10,10,
  109302. 10,10,10,10,10,10,10,10,
  109303. 10,10,10,10,10,10,10,10,
  109304. 10,10,10,10,10,10,10,10,
  109305. 10,10,10,10,10,10,10,10,
  109306. 10,10,10,10,10,10,10,10,
  109307. 10,10,10,10,10,10,10,10,
  109308. 10,10,10,10,10,10,10,10,
  109309. 10,10,10,10,10,10,10,10,
  109310. 10,10,10,10,10,10,10,10,
  109311. 10,10,10,10,10,10,10,10,
  109312. 10,10,10,10,10,10,10,10,
  109313. 10,10,10,10,10,10,10,10,
  109314. 10,10,10,10,10,10,10,10,
  109315. 10,10,10,10,10,10,10,10,
  109316. 10,10,10,10,10,10,10,10,
  109317. 10,10,10,10,10,10,10,10,
  109318. 10,10,10,10,10,10,10,10,
  109319. 10,10,10,10,10,10,10,10,
  109320. 10,10,10,10,10,10,10,10,
  109321. 10,10,10,10,10,10,10,10,
  109322. 10,10,10,10,10,10,10,50,-1};
  109323. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109324. fprintf(stderr,"testing max packet segments... ");
  109325. test_pack(packets,headret,0,0,0);
  109326. }
  109327. {
  109328. /* packet that overspans over an entire page */
  109329. const int packets[]={0,100,9000,259,255,-1};
  109330. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109331. fprintf(stderr,"testing very large packets... ");
  109332. test_pack(packets,headret,0,0,0);
  109333. }
  109334. {
  109335. /* test for the libogg 1.1.1 resync in large continuation bug
  109336. found by Josh Coalson) */
  109337. const int packets[]={0,100,9000,259,255,-1};
  109338. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109339. fprintf(stderr,"testing continuation resync in very large packets... ");
  109340. test_pack(packets,headret,100,2,3);
  109341. }
  109342. {
  109343. /* term only page. why not? */
  109344. const int packets[]={0,100,4080,-1};
  109345. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109346. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109347. test_pack(packets,headret,0,0,0);
  109348. }
  109349. {
  109350. /* build a bunch of pages for testing */
  109351. unsigned char *data=_ogg_malloc(1024*1024);
  109352. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109353. int inptr=0,i,j;
  109354. ogg_page og[5];
  109355. ogg_stream_reset(&os_en);
  109356. for(i=0;pl[i]!=-1;i++){
  109357. ogg_packet op;
  109358. int len=pl[i];
  109359. op.packet=data+inptr;
  109360. op.bytes=len;
  109361. op.e_o_s=(pl[i+1]<0?1:0);
  109362. op.granulepos=(i+1)*1000;
  109363. for(j=0;j<len;j++)data[inptr++]=i+j;
  109364. ogg_stream_packetin(&os_en,&op);
  109365. }
  109366. _ogg_free(data);
  109367. /* retrieve finished pages */
  109368. for(i=0;i<5;i++){
  109369. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109370. fprintf(stderr,"Too few pages output building sync tests!\n");
  109371. exit(1);
  109372. }
  109373. copy_page(&og[i]);
  109374. }
  109375. /* Test lost pages on pagein/packetout: no rollback */
  109376. {
  109377. ogg_page temp;
  109378. ogg_packet test;
  109379. fprintf(stderr,"Testing loss of pages... ");
  109380. ogg_sync_reset(&oy);
  109381. ogg_stream_reset(&os_de);
  109382. for(i=0;i<5;i++){
  109383. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109384. og[i].header_len);
  109385. ogg_sync_wrote(&oy,og[i].header_len);
  109386. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109387. ogg_sync_wrote(&oy,og[i].body_len);
  109388. }
  109389. ogg_sync_pageout(&oy,&temp);
  109390. ogg_stream_pagein(&os_de,&temp);
  109391. ogg_sync_pageout(&oy,&temp);
  109392. ogg_stream_pagein(&os_de,&temp);
  109393. ogg_sync_pageout(&oy,&temp);
  109394. /* skip */
  109395. ogg_sync_pageout(&oy,&temp);
  109396. ogg_stream_pagein(&os_de,&temp);
  109397. /* do we get the expected results/packets? */
  109398. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109399. checkpacket(&test,0,0,0);
  109400. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109401. checkpacket(&test,100,1,-1);
  109402. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109403. checkpacket(&test,4079,2,3000);
  109404. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109405. fprintf(stderr,"Error: loss of page did not return error\n");
  109406. exit(1);
  109407. }
  109408. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109409. checkpacket(&test,76,5,-1);
  109410. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109411. checkpacket(&test,34,6,-1);
  109412. fprintf(stderr,"ok.\n");
  109413. }
  109414. /* Test lost pages on pagein/packetout: rollback with continuation */
  109415. {
  109416. ogg_page temp;
  109417. ogg_packet test;
  109418. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109419. ogg_sync_reset(&oy);
  109420. ogg_stream_reset(&os_de);
  109421. for(i=0;i<5;i++){
  109422. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109423. og[i].header_len);
  109424. ogg_sync_wrote(&oy,og[i].header_len);
  109425. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109426. ogg_sync_wrote(&oy,og[i].body_len);
  109427. }
  109428. ogg_sync_pageout(&oy,&temp);
  109429. ogg_stream_pagein(&os_de,&temp);
  109430. ogg_sync_pageout(&oy,&temp);
  109431. ogg_stream_pagein(&os_de,&temp);
  109432. ogg_sync_pageout(&oy,&temp);
  109433. ogg_stream_pagein(&os_de,&temp);
  109434. ogg_sync_pageout(&oy,&temp);
  109435. /* skip */
  109436. ogg_sync_pageout(&oy,&temp);
  109437. ogg_stream_pagein(&os_de,&temp);
  109438. /* do we get the expected results/packets? */
  109439. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109440. checkpacket(&test,0,0,0);
  109441. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109442. checkpacket(&test,100,1,-1);
  109443. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109444. checkpacket(&test,4079,2,3000);
  109445. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109446. checkpacket(&test,2956,3,4000);
  109447. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109448. fprintf(stderr,"Error: loss of page did not return error\n");
  109449. exit(1);
  109450. }
  109451. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109452. checkpacket(&test,300,13,14000);
  109453. fprintf(stderr,"ok.\n");
  109454. }
  109455. /* the rest only test sync */
  109456. {
  109457. ogg_page og_de;
  109458. /* Test fractional page inputs: incomplete capture */
  109459. fprintf(stderr,"Testing sync on partial inputs... ");
  109460. ogg_sync_reset(&oy);
  109461. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109462. 3);
  109463. ogg_sync_wrote(&oy,3);
  109464. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109465. /* Test fractional page inputs: incomplete fixed header */
  109466. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109467. 20);
  109468. ogg_sync_wrote(&oy,20);
  109469. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109470. /* Test fractional page inputs: incomplete header */
  109471. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109472. 5);
  109473. ogg_sync_wrote(&oy,5);
  109474. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109475. /* Test fractional page inputs: incomplete body */
  109476. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109477. og[1].header_len-28);
  109478. ogg_sync_wrote(&oy,og[1].header_len-28);
  109479. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109480. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109481. ogg_sync_wrote(&oy,1000);
  109482. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109483. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109484. og[1].body_len-1000);
  109485. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109486. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109487. fprintf(stderr,"ok.\n");
  109488. }
  109489. /* Test fractional page inputs: page + incomplete capture */
  109490. {
  109491. ogg_page og_de;
  109492. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  109493. ogg_sync_reset(&oy);
  109494. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109495. og[1].header_len);
  109496. ogg_sync_wrote(&oy,og[1].header_len);
  109497. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109498. og[1].body_len);
  109499. ogg_sync_wrote(&oy,og[1].body_len);
  109500. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109501. 20);
  109502. ogg_sync_wrote(&oy,20);
  109503. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109504. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109505. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  109506. og[1].header_len-20);
  109507. ogg_sync_wrote(&oy,og[1].header_len-20);
  109508. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109509. og[1].body_len);
  109510. ogg_sync_wrote(&oy,og[1].body_len);
  109511. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109512. fprintf(stderr,"ok.\n");
  109513. }
  109514. /* Test recapture: garbage + page */
  109515. {
  109516. ogg_page og_de;
  109517. fprintf(stderr,"Testing search for capture... ");
  109518. ogg_sync_reset(&oy);
  109519. /* 'garbage' */
  109520. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109521. og[1].body_len);
  109522. ogg_sync_wrote(&oy,og[1].body_len);
  109523. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109524. og[1].header_len);
  109525. ogg_sync_wrote(&oy,og[1].header_len);
  109526. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109527. og[1].body_len);
  109528. ogg_sync_wrote(&oy,og[1].body_len);
  109529. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109530. 20);
  109531. ogg_sync_wrote(&oy,20);
  109532. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109533. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109534. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109535. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  109536. og[2].header_len-20);
  109537. ogg_sync_wrote(&oy,og[2].header_len-20);
  109538. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109539. og[2].body_len);
  109540. ogg_sync_wrote(&oy,og[2].body_len);
  109541. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109542. fprintf(stderr,"ok.\n");
  109543. }
  109544. /* Test recapture: page + garbage + page */
  109545. {
  109546. ogg_page og_de;
  109547. fprintf(stderr,"Testing recapture... ");
  109548. ogg_sync_reset(&oy);
  109549. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109550. og[1].header_len);
  109551. ogg_sync_wrote(&oy,og[1].header_len);
  109552. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109553. og[1].body_len);
  109554. ogg_sync_wrote(&oy,og[1].body_len);
  109555. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109556. og[2].header_len);
  109557. ogg_sync_wrote(&oy,og[2].header_len);
  109558. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109559. og[2].header_len);
  109560. ogg_sync_wrote(&oy,og[2].header_len);
  109561. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109562. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109563. og[2].body_len-5);
  109564. ogg_sync_wrote(&oy,og[2].body_len-5);
  109565. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  109566. og[3].header_len);
  109567. ogg_sync_wrote(&oy,og[3].header_len);
  109568. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  109569. og[3].body_len);
  109570. ogg_sync_wrote(&oy,og[3].body_len);
  109571. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109572. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109573. fprintf(stderr,"ok.\n");
  109574. }
  109575. /* Free page data that was previously copied */
  109576. {
  109577. for(i=0;i<5;i++){
  109578. free_page(&og[i]);
  109579. }
  109580. }
  109581. }
  109582. return(0);
  109583. }
  109584. #endif
  109585. #endif
  109586. /*** End of inlined file: framing.c ***/
  109587. /*** Start of inlined file: analysis.c ***/
  109588. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109589. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109590. // tasks..
  109591. #if JUCE_MSVC
  109592. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109593. #endif
  109594. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109595. #if JUCE_USE_OGGVORBIS
  109596. #include <stdio.h>
  109597. #include <string.h>
  109598. #include <math.h>
  109599. /*** Start of inlined file: codec_internal.h ***/
  109600. #ifndef _V_CODECI_H_
  109601. #define _V_CODECI_H_
  109602. /*** Start of inlined file: envelope.h ***/
  109603. #ifndef _V_ENVELOPE_
  109604. #define _V_ENVELOPE_
  109605. /*** Start of inlined file: mdct.h ***/
  109606. #ifndef _OGG_mdct_H_
  109607. #define _OGG_mdct_H_
  109608. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  109609. #ifdef MDCT_INTEGERIZED
  109610. #define DATA_TYPE int
  109611. #define REG_TYPE register int
  109612. #define TRIGBITS 14
  109613. #define cPI3_8 6270
  109614. #define cPI2_8 11585
  109615. #define cPI1_8 15137
  109616. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  109617. #define MULT_NORM(x) ((x)>>TRIGBITS)
  109618. #define HALVE(x) ((x)>>1)
  109619. #else
  109620. #define DATA_TYPE float
  109621. #define REG_TYPE float
  109622. #define cPI3_8 .38268343236508977175F
  109623. #define cPI2_8 .70710678118654752441F
  109624. #define cPI1_8 .92387953251128675613F
  109625. #define FLOAT_CONV(x) (x)
  109626. #define MULT_NORM(x) (x)
  109627. #define HALVE(x) ((x)*.5f)
  109628. #endif
  109629. typedef struct {
  109630. int n;
  109631. int log2n;
  109632. DATA_TYPE *trig;
  109633. int *bitrev;
  109634. DATA_TYPE scale;
  109635. } mdct_lookup;
  109636. extern void mdct_init(mdct_lookup *lookup,int n);
  109637. extern void mdct_clear(mdct_lookup *l);
  109638. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109639. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109640. #endif
  109641. /*** End of inlined file: mdct.h ***/
  109642. #define VE_PRE 16
  109643. #define VE_WIN 4
  109644. #define VE_POST 2
  109645. #define VE_AMP (VE_PRE+VE_POST-1)
  109646. #define VE_BANDS 7
  109647. #define VE_NEARDC 15
  109648. #define VE_MINSTRETCH 2 /* a bit less than short block */
  109649. #define VE_MAXSTRETCH 12 /* one-third full block */
  109650. typedef struct {
  109651. float ampbuf[VE_AMP];
  109652. int ampptr;
  109653. float nearDC[VE_NEARDC];
  109654. float nearDC_acc;
  109655. float nearDC_partialacc;
  109656. int nearptr;
  109657. } envelope_filter_state;
  109658. typedef struct {
  109659. int begin;
  109660. int end;
  109661. float *window;
  109662. float total;
  109663. } envelope_band;
  109664. typedef struct {
  109665. int ch;
  109666. int winlength;
  109667. int searchstep;
  109668. float minenergy;
  109669. mdct_lookup mdct;
  109670. float *mdct_win;
  109671. envelope_band band[VE_BANDS];
  109672. envelope_filter_state *filter;
  109673. int stretch;
  109674. int *mark;
  109675. long storage;
  109676. long current;
  109677. long curmark;
  109678. long cursor;
  109679. } envelope_lookup;
  109680. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  109681. extern void _ve_envelope_clear(envelope_lookup *e);
  109682. extern long _ve_envelope_search(vorbis_dsp_state *v);
  109683. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  109684. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  109685. #endif
  109686. /*** End of inlined file: envelope.h ***/
  109687. /*** Start of inlined file: codebook.h ***/
  109688. #ifndef _V_CODEBOOK_H_
  109689. #define _V_CODEBOOK_H_
  109690. /* This structure encapsulates huffman and VQ style encoding books; it
  109691. doesn't do anything specific to either.
  109692. valuelist/quantlist are nonNULL (and q_* significant) only if
  109693. there's entry->value mapping to be done.
  109694. If encode-side mapping must be done (and thus the entry needs to be
  109695. hunted), the auxiliary encode pointer will point to a decision
  109696. tree. This is true of both VQ and huffman, but is mostly useful
  109697. with VQ.
  109698. */
  109699. typedef struct static_codebook{
  109700. long dim; /* codebook dimensions (elements per vector) */
  109701. long entries; /* codebook entries */
  109702. long *lengthlist; /* codeword lengths in bits */
  109703. /* mapping ***************************************************************/
  109704. int maptype; /* 0=none
  109705. 1=implicitly populated values from map column
  109706. 2=listed arbitrary values */
  109707. /* The below does a linear, single monotonic sequence mapping. */
  109708. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  109709. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  109710. int q_quant; /* bits: 0 < quant <= 16 */
  109711. int q_sequencep; /* bitflag */
  109712. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  109713. map == 2: list of dim*entries quantized entry vals
  109714. */
  109715. /* encode helpers ********************************************************/
  109716. struct encode_aux_nearestmatch *nearest_tree;
  109717. struct encode_aux_threshmatch *thresh_tree;
  109718. struct encode_aux_pigeonhole *pigeon_tree;
  109719. int allocedp;
  109720. } static_codebook;
  109721. /* this structures an arbitrary trained book to quickly find the
  109722. nearest cell match */
  109723. typedef struct encode_aux_nearestmatch{
  109724. /* pre-calculated partitioning tree */
  109725. long *ptr0;
  109726. long *ptr1;
  109727. long *p; /* decision points (each is an entry) */
  109728. long *q; /* decision points (each is an entry) */
  109729. long aux; /* number of tree entries */
  109730. long alloc;
  109731. } encode_aux_nearestmatch;
  109732. /* assumes a maptype of 1; encode side only, so that's OK */
  109733. typedef struct encode_aux_threshmatch{
  109734. float *quantthresh;
  109735. long *quantmap;
  109736. int quantvals;
  109737. int threshvals;
  109738. } encode_aux_threshmatch;
  109739. typedef struct encode_aux_pigeonhole{
  109740. float min;
  109741. float del;
  109742. int mapentries;
  109743. int quantvals;
  109744. long *pigeonmap;
  109745. long fittotal;
  109746. long *fitlist;
  109747. long *fitmap;
  109748. long *fitlength;
  109749. } encode_aux_pigeonhole;
  109750. typedef struct codebook{
  109751. long dim; /* codebook dimensions (elements per vector) */
  109752. long entries; /* codebook entries */
  109753. long used_entries; /* populated codebook entries */
  109754. const static_codebook *c;
  109755. /* for encode, the below are entry-ordered, fully populated */
  109756. /* for decode, the below are ordered by bitreversed codeword and only
  109757. used entries are populated */
  109758. float *valuelist; /* list of dim*entries actual entry values */
  109759. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  109760. int *dec_index; /* only used if sparseness collapsed */
  109761. char *dec_codelengths;
  109762. ogg_uint32_t *dec_firsttable;
  109763. int dec_firsttablen;
  109764. int dec_maxlength;
  109765. } codebook;
  109766. extern void vorbis_staticbook_clear(static_codebook *b);
  109767. extern void vorbis_staticbook_destroy(static_codebook *b);
  109768. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  109769. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  109770. extern void vorbis_book_clear(codebook *b);
  109771. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  109772. extern float *_book_logdist(const static_codebook *b,float *vals);
  109773. extern float _float32_unpack(long val);
  109774. extern long _float32_pack(float val);
  109775. extern int _best(codebook *book, float *a, int step);
  109776. extern int _ilog(unsigned int v);
  109777. extern long _book_maptype1_quantvals(const static_codebook *b);
  109778. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  109779. extern long vorbis_book_codeword(codebook *book,int entry);
  109780. extern long vorbis_book_codelen(codebook *book,int entry);
  109781. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  109782. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  109783. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  109784. extern int vorbis_book_errorv(codebook *book, float *a);
  109785. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  109786. oggpack_buffer *b);
  109787. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  109788. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  109789. oggpack_buffer *b,int n);
  109790. extern long vorbis_book_decodev_set(codebook *book, float *a,
  109791. oggpack_buffer *b,int n);
  109792. extern long vorbis_book_decodev_add(codebook *book, float *a,
  109793. oggpack_buffer *b,int n);
  109794. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  109795. long off,int ch,
  109796. oggpack_buffer *b,int n);
  109797. #endif
  109798. /*** End of inlined file: codebook.h ***/
  109799. #define BLOCKTYPE_IMPULSE 0
  109800. #define BLOCKTYPE_PADDING 1
  109801. #define BLOCKTYPE_TRANSITION 0
  109802. #define BLOCKTYPE_LONG 1
  109803. #define PACKETBLOBS 15
  109804. typedef struct vorbis_block_internal{
  109805. float **pcmdelay; /* this is a pointer into local storage */
  109806. float ampmax;
  109807. int blocktype;
  109808. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  109809. blob [PACKETBLOBS/2] points to
  109810. the oggpack_buffer in the
  109811. main vorbis_block */
  109812. } vorbis_block_internal;
  109813. typedef void vorbis_look_floor;
  109814. typedef void vorbis_look_residue;
  109815. typedef void vorbis_look_transform;
  109816. /* mode ************************************************************/
  109817. typedef struct {
  109818. int blockflag;
  109819. int windowtype;
  109820. int transformtype;
  109821. int mapping;
  109822. } vorbis_info_mode;
  109823. typedef void vorbis_info_floor;
  109824. typedef void vorbis_info_residue;
  109825. typedef void vorbis_info_mapping;
  109826. /*** Start of inlined file: psy.h ***/
  109827. #ifndef _V_PSY_H_
  109828. #define _V_PSY_H_
  109829. /*** Start of inlined file: smallft.h ***/
  109830. #ifndef _V_SMFT_H_
  109831. #define _V_SMFT_H_
  109832. typedef struct {
  109833. int n;
  109834. float *trigcache;
  109835. int *splitcache;
  109836. } drft_lookup;
  109837. extern void drft_forward(drft_lookup *l,float *data);
  109838. extern void drft_backward(drft_lookup *l,float *data);
  109839. extern void drft_init(drft_lookup *l,int n);
  109840. extern void drft_clear(drft_lookup *l);
  109841. #endif
  109842. /*** End of inlined file: smallft.h ***/
  109843. /*** Start of inlined file: backends.h ***/
  109844. /* this is exposed up here because we need it for static modes.
  109845. Lookups for each backend aren't exposed because there's no reason
  109846. to do so */
  109847. #ifndef _vorbis_backend_h_
  109848. #define _vorbis_backend_h_
  109849. /* this would all be simpler/shorter with templates, but.... */
  109850. /* Floor backend generic *****************************************/
  109851. typedef struct{
  109852. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  109853. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  109854. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  109855. void (*free_info) (vorbis_info_floor *);
  109856. void (*free_look) (vorbis_look_floor *);
  109857. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  109858. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  109859. void *buffer,float *);
  109860. } vorbis_func_floor;
  109861. typedef struct{
  109862. int order;
  109863. long rate;
  109864. long barkmap;
  109865. int ampbits;
  109866. int ampdB;
  109867. int numbooks; /* <= 16 */
  109868. int books[16];
  109869. float lessthan; /* encode-only config setting hacks for libvorbis */
  109870. float greaterthan; /* encode-only config setting hacks for libvorbis */
  109871. } vorbis_info_floor0;
  109872. #define VIF_POSIT 63
  109873. #define VIF_CLASS 16
  109874. #define VIF_PARTS 31
  109875. typedef struct{
  109876. int partitions; /* 0 to 31 */
  109877. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  109878. int class_dim[VIF_CLASS]; /* 1 to 8 */
  109879. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  109880. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  109881. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  109882. int mult; /* 1 2 3 or 4 */
  109883. int postlist[VIF_POSIT+2]; /* first two implicit */
  109884. /* encode side analysis parameters */
  109885. float maxover;
  109886. float maxunder;
  109887. float maxerr;
  109888. float twofitweight;
  109889. float twofitatten;
  109890. int n;
  109891. } vorbis_info_floor1;
  109892. /* Residue backend generic *****************************************/
  109893. typedef struct{
  109894. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  109895. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  109896. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  109897. vorbis_info_residue *);
  109898. void (*free_info) (vorbis_info_residue *);
  109899. void (*free_look) (vorbis_look_residue *);
  109900. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  109901. float **,int *,int);
  109902. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  109903. vorbis_look_residue *,
  109904. float **,float **,int *,int,long **);
  109905. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  109906. float **,int *,int);
  109907. } vorbis_func_residue;
  109908. typedef struct vorbis_info_residue0{
  109909. /* block-partitioned VQ coded straight residue */
  109910. long begin;
  109911. long end;
  109912. /* first stage (lossless partitioning) */
  109913. int grouping; /* group n vectors per partition */
  109914. int partitions; /* possible codebooks for a partition */
  109915. int groupbook; /* huffbook for partitioning */
  109916. int secondstages[64]; /* expanded out to pointers in lookup */
  109917. int booklist[256]; /* list of second stage books */
  109918. float classmetric1[64];
  109919. float classmetric2[64];
  109920. } vorbis_info_residue0;
  109921. /* Mapping backend generic *****************************************/
  109922. typedef struct{
  109923. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  109924. oggpack_buffer *);
  109925. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  109926. void (*free_info) (vorbis_info_mapping *);
  109927. int (*forward) (struct vorbis_block *vb);
  109928. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  109929. } vorbis_func_mapping;
  109930. typedef struct vorbis_info_mapping0{
  109931. int submaps; /* <= 16 */
  109932. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  109933. int floorsubmap[16]; /* [mux] submap to floors */
  109934. int residuesubmap[16]; /* [mux] submap to residue */
  109935. int coupling_steps;
  109936. int coupling_mag[256];
  109937. int coupling_ang[256];
  109938. } vorbis_info_mapping0;
  109939. #endif
  109940. /*** End of inlined file: backends.h ***/
  109941. #ifndef EHMER_MAX
  109942. #define EHMER_MAX 56
  109943. #endif
  109944. /* psychoacoustic setup ********************************************/
  109945. #define P_BANDS 17 /* 62Hz to 16kHz */
  109946. #define P_LEVELS 8 /* 30dB to 100dB */
  109947. #define P_LEVEL_0 30. /* 30 dB */
  109948. #define P_NOISECURVES 3
  109949. #define NOISE_COMPAND_LEVELS 40
  109950. typedef struct vorbis_info_psy{
  109951. int blockflag;
  109952. float ath_adjatt;
  109953. float ath_maxatt;
  109954. float tone_masteratt[P_NOISECURVES];
  109955. float tone_centerboost;
  109956. float tone_decay;
  109957. float tone_abs_limit;
  109958. float toneatt[P_BANDS];
  109959. int noisemaskp;
  109960. float noisemaxsupp;
  109961. float noisewindowlo;
  109962. float noisewindowhi;
  109963. int noisewindowlomin;
  109964. int noisewindowhimin;
  109965. int noisewindowfixed;
  109966. float noiseoff[P_NOISECURVES][P_BANDS];
  109967. float noisecompand[NOISE_COMPAND_LEVELS];
  109968. float max_curve_dB;
  109969. int normal_channel_p;
  109970. int normal_point_p;
  109971. int normal_start;
  109972. int normal_partition;
  109973. double normal_thresh;
  109974. } vorbis_info_psy;
  109975. typedef struct{
  109976. int eighth_octave_lines;
  109977. /* for block long/short tuning; encode only */
  109978. float preecho_thresh[VE_BANDS];
  109979. float postecho_thresh[VE_BANDS];
  109980. float stretch_penalty;
  109981. float preecho_minenergy;
  109982. float ampmax_att_per_sec;
  109983. /* channel coupling config */
  109984. int coupling_pkHz[PACKETBLOBS];
  109985. int coupling_pointlimit[2][PACKETBLOBS];
  109986. int coupling_prepointamp[PACKETBLOBS];
  109987. int coupling_postpointamp[PACKETBLOBS];
  109988. int sliding_lowpass[2][PACKETBLOBS];
  109989. } vorbis_info_psy_global;
  109990. typedef struct {
  109991. float ampmax;
  109992. int channels;
  109993. vorbis_info_psy_global *gi;
  109994. int coupling_pointlimit[2][P_NOISECURVES];
  109995. } vorbis_look_psy_global;
  109996. typedef struct {
  109997. int n;
  109998. struct vorbis_info_psy *vi;
  109999. float ***tonecurves;
  110000. float **noiseoffset;
  110001. float *ath;
  110002. long *octave; /* in n.ocshift format */
  110003. long *bark;
  110004. long firstoc;
  110005. long shiftoc;
  110006. int eighth_octave_lines; /* power of two, please */
  110007. int total_octave_lines;
  110008. long rate; /* cache it */
  110009. float m_val; /* Masking compensation value */
  110010. } vorbis_look_psy;
  110011. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110012. vorbis_info_psy_global *gi,int n,long rate);
  110013. extern void _vp_psy_clear(vorbis_look_psy *p);
  110014. extern void *_vi_psy_dup(void *source);
  110015. extern void _vi_psy_free(vorbis_info_psy *i);
  110016. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  110017. extern void _vp_remove_floor(vorbis_look_psy *p,
  110018. float *mdct,
  110019. int *icodedflr,
  110020. float *residue,
  110021. int sliding_lowpass);
  110022. extern void _vp_noisemask(vorbis_look_psy *p,
  110023. float *logmdct,
  110024. float *logmask);
  110025. extern void _vp_tonemask(vorbis_look_psy *p,
  110026. float *logfft,
  110027. float *logmask,
  110028. float global_specmax,
  110029. float local_specmax);
  110030. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110031. float *noise,
  110032. float *tone,
  110033. int offset_select,
  110034. float *logmask,
  110035. float *mdct,
  110036. float *logmdct);
  110037. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110038. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110039. vorbis_info_psy_global *g,
  110040. vorbis_look_psy *p,
  110041. vorbis_info_mapping0 *vi,
  110042. float **mdct);
  110043. extern void _vp_couple(int blobno,
  110044. vorbis_info_psy_global *g,
  110045. vorbis_look_psy *p,
  110046. vorbis_info_mapping0 *vi,
  110047. float **res,
  110048. float **mag_memo,
  110049. int **mag_sort,
  110050. int **ifloor,
  110051. int *nonzero,
  110052. int sliding_lowpass);
  110053. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110054. float *in,float *out,int *sortedindex);
  110055. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110056. float *magnitudes,int *sortedindex);
  110057. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110058. vorbis_look_psy *p,
  110059. vorbis_info_mapping0 *vi,
  110060. float **mags);
  110061. extern void hf_reduction(vorbis_info_psy_global *g,
  110062. vorbis_look_psy *p,
  110063. vorbis_info_mapping0 *vi,
  110064. float **mdct);
  110065. #endif
  110066. /*** End of inlined file: psy.h ***/
  110067. /*** Start of inlined file: bitrate.h ***/
  110068. #ifndef _V_BITRATE_H_
  110069. #define _V_BITRATE_H_
  110070. /*** Start of inlined file: os.h ***/
  110071. #ifndef _OS_H
  110072. #define _OS_H
  110073. /********************************************************************
  110074. * *
  110075. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110076. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110077. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110078. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110079. * *
  110080. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110081. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110082. * *
  110083. ********************************************************************
  110084. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110085. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110086. ********************************************************************/
  110087. #ifdef HAVE_CONFIG_H
  110088. #include "config.h"
  110089. #endif
  110090. #include <math.h>
  110091. /*** Start of inlined file: misc.h ***/
  110092. #ifndef _V_RANDOM_H_
  110093. #define _V_RANDOM_H_
  110094. extern int analysis_noisy;
  110095. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110096. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110097. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110098. ogg_int64_t off);
  110099. #ifdef DEBUG_MALLOC
  110100. #define _VDBG_GRAPHFILE "malloc.m"
  110101. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110102. extern void _VDBG_free(void *ptr,char *file,long line);
  110103. #ifndef MISC_C
  110104. #undef _ogg_malloc
  110105. #undef _ogg_calloc
  110106. #undef _ogg_realloc
  110107. #undef _ogg_free
  110108. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110109. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110110. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110111. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110112. #endif
  110113. #endif
  110114. #endif
  110115. /*** End of inlined file: misc.h ***/
  110116. #ifndef _V_IFDEFJAIL_H_
  110117. # define _V_IFDEFJAIL_H_
  110118. # ifdef __GNUC__
  110119. # define STIN static __inline__
  110120. # elif _WIN32
  110121. # define STIN static __inline
  110122. # else
  110123. # define STIN static
  110124. # endif
  110125. #ifdef DJGPP
  110126. # define rint(x) (floor((x)+0.5f))
  110127. #endif
  110128. #ifndef M_PI
  110129. # define M_PI (3.1415926536f)
  110130. #endif
  110131. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110132. # include <malloc.h>
  110133. # define rint(x) (floor((x)+0.5f))
  110134. # define NO_FLOAT_MATH_LIB
  110135. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110136. #endif
  110137. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110138. void *_alloca(size_t size);
  110139. # define alloca _alloca
  110140. #endif
  110141. #ifndef FAST_HYPOT
  110142. # define FAST_HYPOT hypot
  110143. #endif
  110144. #endif
  110145. #ifdef HAVE_ALLOCA_H
  110146. # include <alloca.h>
  110147. #endif
  110148. #ifdef USE_MEMORY_H
  110149. # include <memory.h>
  110150. #endif
  110151. #ifndef min
  110152. # define min(x,y) ((x)>(y)?(y):(x))
  110153. #endif
  110154. #ifndef max
  110155. # define max(x,y) ((x)<(y)?(y):(x))
  110156. #endif
  110157. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110158. # define VORBIS_FPU_CONTROL
  110159. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110160. Because of encapsulation constraints (GCC can't see inside the asm
  110161. block and so we end up doing stupid things like a store/load that
  110162. is collectively a noop), we do it this way */
  110163. /* we must set up the fpu before this works!! */
  110164. typedef ogg_int16_t vorbis_fpu_control;
  110165. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110166. ogg_int16_t ret;
  110167. ogg_int16_t temp;
  110168. __asm__ __volatile__("fnstcw %0\n\t"
  110169. "movw %0,%%dx\n\t"
  110170. "orw $62463,%%dx\n\t"
  110171. "movw %%dx,%1\n\t"
  110172. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110173. *fpu=ret;
  110174. }
  110175. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110176. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110177. }
  110178. /* assumes the FPU is in round mode! */
  110179. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110180. we get extra fst/fld to
  110181. truncate precision */
  110182. int i;
  110183. __asm__("fistl %0": "=m"(i) : "t"(f));
  110184. return(i);
  110185. }
  110186. #endif
  110187. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110188. # define VORBIS_FPU_CONTROL
  110189. typedef ogg_int16_t vorbis_fpu_control;
  110190. static __inline int vorbis_ftoi(double f){
  110191. int i;
  110192. __asm{
  110193. fld f
  110194. fistp i
  110195. }
  110196. return i;
  110197. }
  110198. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110199. }
  110200. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110201. }
  110202. #endif
  110203. #ifndef VORBIS_FPU_CONTROL
  110204. typedef int vorbis_fpu_control;
  110205. static int vorbis_ftoi(double f){
  110206. return (int)(f+.5);
  110207. }
  110208. /* We don't have special code for this compiler/arch, so do it the slow way */
  110209. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110210. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110211. #endif
  110212. #endif /* _OS_H */
  110213. /*** End of inlined file: os.h ***/
  110214. /* encode side bitrate tracking */
  110215. typedef struct bitrate_manager_state {
  110216. int managed;
  110217. long avg_reservoir;
  110218. long minmax_reservoir;
  110219. long avg_bitsper;
  110220. long min_bitsper;
  110221. long max_bitsper;
  110222. long short_per_long;
  110223. double avgfloat;
  110224. vorbis_block *vb;
  110225. int choice;
  110226. } bitrate_manager_state;
  110227. typedef struct bitrate_manager_info{
  110228. long avg_rate;
  110229. long min_rate;
  110230. long max_rate;
  110231. long reservoir_bits;
  110232. double reservoir_bias;
  110233. double slew_damp;
  110234. } bitrate_manager_info;
  110235. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110236. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110237. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110238. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110239. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110240. #endif
  110241. /*** End of inlined file: bitrate.h ***/
  110242. static int ilog(unsigned int v){
  110243. int ret=0;
  110244. while(v){
  110245. ret++;
  110246. v>>=1;
  110247. }
  110248. return(ret);
  110249. }
  110250. static int ilog2(unsigned int v){
  110251. int ret=0;
  110252. if(v)--v;
  110253. while(v){
  110254. ret++;
  110255. v>>=1;
  110256. }
  110257. return(ret);
  110258. }
  110259. typedef struct private_state {
  110260. /* local lookup storage */
  110261. envelope_lookup *ve; /* envelope lookup */
  110262. int window[2];
  110263. vorbis_look_transform **transform[2]; /* block, type */
  110264. drft_lookup fft_look[2];
  110265. int modebits;
  110266. vorbis_look_floor **flr;
  110267. vorbis_look_residue **residue;
  110268. vorbis_look_psy *psy;
  110269. vorbis_look_psy_global *psy_g_look;
  110270. /* local storage, only used on the encoding side. This way the
  110271. application does not need to worry about freeing some packets'
  110272. memory and not others'; packet storage is always tracked.
  110273. Cleared next call to a _dsp_ function */
  110274. unsigned char *header;
  110275. unsigned char *header1;
  110276. unsigned char *header2;
  110277. bitrate_manager_state bms;
  110278. ogg_int64_t sample_count;
  110279. } private_state;
  110280. /* codec_setup_info contains all the setup information specific to the
  110281. specific compression/decompression mode in progress (eg,
  110282. psychoacoustic settings, channel setup, options, codebook
  110283. etc).
  110284. *********************************************************************/
  110285. /*** Start of inlined file: highlevel.h ***/
  110286. typedef struct highlevel_byblocktype {
  110287. double tone_mask_setting;
  110288. double tone_peaklimit_setting;
  110289. double noise_bias_setting;
  110290. double noise_compand_setting;
  110291. } highlevel_byblocktype;
  110292. typedef struct highlevel_encode_setup {
  110293. void *setup;
  110294. int set_in_stone;
  110295. double base_setting;
  110296. double long_setting;
  110297. double short_setting;
  110298. double impulse_noisetune;
  110299. int managed;
  110300. long bitrate_min;
  110301. long bitrate_av;
  110302. double bitrate_av_damp;
  110303. long bitrate_max;
  110304. long bitrate_reservoir;
  110305. double bitrate_reservoir_bias;
  110306. int impulse_block_p;
  110307. int noise_normalize_p;
  110308. double stereo_point_setting;
  110309. double lowpass_kHz;
  110310. double ath_floating_dB;
  110311. double ath_absolute_dB;
  110312. double amplitude_track_dBpersec;
  110313. double trigger_setting;
  110314. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110315. } highlevel_encode_setup;
  110316. /*** End of inlined file: highlevel.h ***/
  110317. typedef struct codec_setup_info {
  110318. /* Vorbis supports only short and long blocks, but allows the
  110319. encoder to choose the sizes */
  110320. long blocksizes[2];
  110321. /* modes are the primary means of supporting on-the-fly different
  110322. blocksizes, different channel mappings (LR or M/A),
  110323. different residue backends, etc. Each mode consists of a
  110324. blocksize flag and a mapping (along with the mapping setup */
  110325. int modes;
  110326. int maps;
  110327. int floors;
  110328. int residues;
  110329. int books;
  110330. int psys; /* encode only */
  110331. vorbis_info_mode *mode_param[64];
  110332. int map_type[64];
  110333. vorbis_info_mapping *map_param[64];
  110334. int floor_type[64];
  110335. vorbis_info_floor *floor_param[64];
  110336. int residue_type[64];
  110337. vorbis_info_residue *residue_param[64];
  110338. static_codebook *book_param[256];
  110339. codebook *fullbooks;
  110340. vorbis_info_psy *psy_param[4]; /* encode only */
  110341. vorbis_info_psy_global psy_g_param;
  110342. bitrate_manager_info bi;
  110343. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110344. highly redundant structure, but
  110345. improves clarity of program flow. */
  110346. int halfrate_flag; /* painless downsample for decode */
  110347. } codec_setup_info;
  110348. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110349. extern void _vp_global_free(vorbis_look_psy_global *look);
  110350. #endif
  110351. /*** End of inlined file: codec_internal.h ***/
  110352. /*** Start of inlined file: registry.h ***/
  110353. #ifndef _V_REG_H_
  110354. #define _V_REG_H_
  110355. #define VI_TRANSFORMB 1
  110356. #define VI_WINDOWB 1
  110357. #define VI_TIMEB 1
  110358. #define VI_FLOORB 2
  110359. #define VI_RESB 3
  110360. #define VI_MAPB 1
  110361. extern vorbis_func_floor *_floor_P[];
  110362. extern vorbis_func_residue *_residue_P[];
  110363. extern vorbis_func_mapping *_mapping_P[];
  110364. #endif
  110365. /*** End of inlined file: registry.h ***/
  110366. /*** Start of inlined file: scales.h ***/
  110367. #ifndef _V_SCALES_H_
  110368. #define _V_SCALES_H_
  110369. #include <math.h>
  110370. /* 20log10(x) */
  110371. #define VORBIS_IEEE_FLOAT32 1
  110372. #ifdef VORBIS_IEEE_FLOAT32
  110373. static float unitnorm(float x){
  110374. union {
  110375. ogg_uint32_t i;
  110376. float f;
  110377. } ix;
  110378. ix.f = x;
  110379. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110380. return ix.f;
  110381. }
  110382. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110383. static float todB(const float *x){
  110384. union {
  110385. ogg_uint32_t i;
  110386. float f;
  110387. } ix;
  110388. ix.f = *x;
  110389. ix.i = ix.i&0x7fffffff;
  110390. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110391. }
  110392. #define todB_nn(x) todB(x)
  110393. #else
  110394. static float unitnorm(float x){
  110395. if(x<0)return(-1.f);
  110396. return(1.f);
  110397. }
  110398. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110399. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110400. #endif
  110401. #define fromdB(x) (exp((x)*.11512925f))
  110402. /* The bark scale equations are approximations, since the original
  110403. table was somewhat hand rolled. The below are chosen to have the
  110404. best possible fit to the rolled tables, thus their somewhat odd
  110405. appearance (these are more accurate and over a longer range than
  110406. the oft-quoted bark equations found in the texts I have). The
  110407. approximations are valid from 0 - 30kHz (nyquist) or so.
  110408. all f in Hz, z in Bark */
  110409. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110410. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110411. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110412. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110413. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110414. 0.0 */
  110415. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110416. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110417. #endif
  110418. /*** End of inlined file: scales.h ***/
  110419. int analysis_noisy=1;
  110420. /* decides between modes, dispatches to the appropriate mapping. */
  110421. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110422. int ret,i;
  110423. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110424. vb->glue_bits=0;
  110425. vb->time_bits=0;
  110426. vb->floor_bits=0;
  110427. vb->res_bits=0;
  110428. /* first things first. Make sure encode is ready */
  110429. for(i=0;i<PACKETBLOBS;i++)
  110430. oggpack_reset(vbi->packetblob[i]);
  110431. /* we only have one mapping type (0), and we let the mapping code
  110432. itself figure out what soft mode to use. This allows easier
  110433. bitrate management */
  110434. if((ret=_mapping_P[0]->forward(vb)))
  110435. return(ret);
  110436. if(op){
  110437. if(vorbis_bitrate_managed(vb))
  110438. /* The app is using a bitmanaged mode... but not using the
  110439. bitrate management interface. */
  110440. return(OV_EINVAL);
  110441. op->packet=oggpack_get_buffer(&vb->opb);
  110442. op->bytes=oggpack_bytes(&vb->opb);
  110443. op->b_o_s=0;
  110444. op->e_o_s=vb->eofflag;
  110445. op->granulepos=vb->granulepos;
  110446. op->packetno=vb->sequence; /* for sake of completeness */
  110447. }
  110448. return(0);
  110449. }
  110450. /* there was no great place to put this.... */
  110451. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110452. int j;
  110453. FILE *of;
  110454. char buffer[80];
  110455. /* if(i==5870){*/
  110456. sprintf(buffer,"%s_%d.m",base,i);
  110457. of=fopen(buffer,"w");
  110458. if(!of)perror("failed to open data dump file");
  110459. for(j=0;j<n;j++){
  110460. if(bark){
  110461. float b=toBARK((4000.f*j/n)+.25);
  110462. fprintf(of,"%f ",b);
  110463. }else
  110464. if(off!=0)
  110465. fprintf(of,"%f ",(double)(j+off)/8000.);
  110466. else
  110467. fprintf(of,"%f ",(double)j);
  110468. if(dB){
  110469. float val;
  110470. if(v[j]==0.)
  110471. val=-140.;
  110472. else
  110473. val=todB(v+j);
  110474. fprintf(of,"%f\n",val);
  110475. }else{
  110476. fprintf(of,"%f\n",v[j]);
  110477. }
  110478. }
  110479. fclose(of);
  110480. /* } */
  110481. }
  110482. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110483. ogg_int64_t off){
  110484. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110485. }
  110486. #endif
  110487. /*** End of inlined file: analysis.c ***/
  110488. /*** Start of inlined file: bitrate.c ***/
  110489. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110490. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110491. // tasks..
  110492. #if JUCE_MSVC
  110493. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110494. #endif
  110495. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110496. #if JUCE_USE_OGGVORBIS
  110497. #include <stdlib.h>
  110498. #include <string.h>
  110499. #include <math.h>
  110500. /* compute bitrate tracking setup */
  110501. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  110502. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110503. bitrate_manager_info *bi=&ci->bi;
  110504. memset(bm,0,sizeof(*bm));
  110505. if(bi && (bi->reservoir_bits>0)){
  110506. long ratesamples=vi->rate;
  110507. int halfsamples=ci->blocksizes[0]>>1;
  110508. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  110509. bm->managed=1;
  110510. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  110511. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  110512. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  110513. bm->avgfloat=PACKETBLOBS/2;
  110514. /* not a necessary fix, but one that leads to a more balanced
  110515. typical initialization */
  110516. {
  110517. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110518. bm->minmax_reservoir=desired_fill;
  110519. bm->avg_reservoir=desired_fill;
  110520. }
  110521. }
  110522. }
  110523. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  110524. memset(bm,0,sizeof(*bm));
  110525. return;
  110526. }
  110527. int vorbis_bitrate_managed(vorbis_block *vb){
  110528. vorbis_dsp_state *vd=vb->vd;
  110529. private_state *b=(private_state*)vd->backend_state;
  110530. bitrate_manager_state *bm=&b->bms;
  110531. if(bm && bm->managed)return(1);
  110532. return(0);
  110533. }
  110534. /* finish taking in the block we just processed */
  110535. int vorbis_bitrate_addblock(vorbis_block *vb){
  110536. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110537. vorbis_dsp_state *vd=vb->vd;
  110538. private_state *b=(private_state*)vd->backend_state;
  110539. bitrate_manager_state *bm=&b->bms;
  110540. vorbis_info *vi=vd->vi;
  110541. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110542. bitrate_manager_info *bi=&ci->bi;
  110543. int choice=rint(bm->avgfloat);
  110544. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110545. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  110546. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  110547. int samples=ci->blocksizes[vb->W]>>1;
  110548. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110549. if(!bm->managed){
  110550. /* not a bitrate managed stream, but for API simplicity, we'll
  110551. buffer the packet to keep the code path clean */
  110552. if(bm->vb)return(-1); /* one has been submitted without
  110553. being claimed */
  110554. bm->vb=vb;
  110555. return(0);
  110556. }
  110557. bm->vb=vb;
  110558. /* look ahead for avg floater */
  110559. if(bm->avg_bitsper>0){
  110560. double slew=0.;
  110561. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110562. double slewlimit= 15./bi->slew_damp;
  110563. /* choosing a new floater:
  110564. if we're over target, we slew down
  110565. if we're under target, we slew up
  110566. choose slew as follows: look through packetblobs of this frame
  110567. and set slew as the first in the appropriate direction that
  110568. gives us the slew we want. This may mean no slew if delta is
  110569. already favorable.
  110570. Then limit slew to slew max */
  110571. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110572. while(choice>0 && this_bits>avg_target_bits &&
  110573. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110574. choice--;
  110575. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110576. }
  110577. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110578. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  110579. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110580. choice++;
  110581. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110582. }
  110583. }
  110584. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  110585. if(slew<-slewlimit)slew=-slewlimit;
  110586. if(slew>slewlimit)slew=slewlimit;
  110587. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  110588. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110589. }
  110590. /* enforce min(if used) on the current floater (if used) */
  110591. if(bm->min_bitsper>0){
  110592. /* do we need to force the bitrate up? */
  110593. if(this_bits<min_target_bits){
  110594. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  110595. choice++;
  110596. if(choice>=PACKETBLOBS)break;
  110597. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110598. }
  110599. }
  110600. }
  110601. /* enforce max (if used) on the current floater (if used) */
  110602. if(bm->max_bitsper>0){
  110603. /* do we need to force the bitrate down? */
  110604. if(this_bits>max_target_bits){
  110605. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  110606. choice--;
  110607. if(choice<0)break;
  110608. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110609. }
  110610. }
  110611. }
  110612. /* Choice of packetblobs now made based on floater, and min/max
  110613. requirements. Now boundary check extreme choices */
  110614. if(choice<0){
  110615. /* choosing a smaller packetblob is insufficient to trim bitrate.
  110616. frame will need to be truncated */
  110617. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  110618. bm->choice=choice=0;
  110619. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  110620. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  110621. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110622. }
  110623. }else{
  110624. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  110625. if(choice>=PACKETBLOBS)
  110626. choice=PACKETBLOBS-1;
  110627. bm->choice=choice;
  110628. /* prop up bitrate according to demand. pad this frame out with zeroes */
  110629. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  110630. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  110631. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110632. }
  110633. /* now we have the final packet and the final packet size. Update statistics */
  110634. /* min and max reservoir */
  110635. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  110636. if(max_target_bits>0 && this_bits>max_target_bits){
  110637. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110638. }else if(min_target_bits>0 && this_bits<min_target_bits){
  110639. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110640. }else{
  110641. /* inbetween; we want to take reservoir toward but not past desired_fill */
  110642. if(bm->minmax_reservoir>desired_fill){
  110643. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  110644. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110645. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  110646. }else{
  110647. bm->minmax_reservoir=desired_fill;
  110648. }
  110649. }else{
  110650. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  110651. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110652. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  110653. }else{
  110654. bm->minmax_reservoir=desired_fill;
  110655. }
  110656. }
  110657. }
  110658. }
  110659. /* avg reservoir */
  110660. if(bm->avg_bitsper>0){
  110661. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110662. bm->avg_reservoir+=this_bits-avg_target_bits;
  110663. }
  110664. return(0);
  110665. }
  110666. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  110667. private_state *b=(private_state*)vd->backend_state;
  110668. bitrate_manager_state *bm=&b->bms;
  110669. vorbis_block *vb=bm->vb;
  110670. int choice=PACKETBLOBS/2;
  110671. if(!vb)return 0;
  110672. if(op){
  110673. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110674. if(vorbis_bitrate_managed(vb))
  110675. choice=bm->choice;
  110676. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  110677. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  110678. op->b_o_s=0;
  110679. op->e_o_s=vb->eofflag;
  110680. op->granulepos=vb->granulepos;
  110681. op->packetno=vb->sequence; /* for sake of completeness */
  110682. }
  110683. bm->vb=0;
  110684. return(1);
  110685. }
  110686. #endif
  110687. /*** End of inlined file: bitrate.c ***/
  110688. /*** Start of inlined file: block.c ***/
  110689. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110690. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110691. // tasks..
  110692. #if JUCE_MSVC
  110693. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110694. #endif
  110695. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110696. #if JUCE_USE_OGGVORBIS
  110697. #include <stdio.h>
  110698. #include <stdlib.h>
  110699. #include <string.h>
  110700. /*** Start of inlined file: window.h ***/
  110701. #ifndef _V_WINDOW_
  110702. #define _V_WINDOW_
  110703. extern float *_vorbis_window_get(int n);
  110704. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  110705. int lW,int W,int nW);
  110706. #endif
  110707. /*** End of inlined file: window.h ***/
  110708. /*** Start of inlined file: lpc.h ***/
  110709. #ifndef _V_LPC_H_
  110710. #define _V_LPC_H_
  110711. /* simple linear scale LPC code */
  110712. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  110713. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  110714. float *data,long n);
  110715. #endif
  110716. /*** End of inlined file: lpc.h ***/
  110717. /* pcm accumulator examples (not exhaustive):
  110718. <-------------- lW ---------------->
  110719. <--------------- W ---------------->
  110720. : .....|..... _______________ |
  110721. : .''' | '''_--- | |\ |
  110722. :.....''' |_____--- '''......| | \_______|
  110723. :.................|__________________|_______|__|______|
  110724. |<------ Sl ------>| > Sr < |endW
  110725. |beginSl |endSl | |endSr
  110726. |beginW |endlW |beginSr
  110727. |< lW >|
  110728. <--------------- W ---------------->
  110729. | | .. ______________ |
  110730. | | ' `/ | ---_ |
  110731. |___.'___/`. | ---_____|
  110732. |_______|__|_______|_________________|
  110733. | >|Sl|< |<------ Sr ----->|endW
  110734. | | |endSl |beginSr |endSr
  110735. |beginW | |endlW
  110736. mult[0] |beginSl mult[n]
  110737. <-------------- lW ----------------->
  110738. |<--W-->|
  110739. : .............. ___ | |
  110740. : .''' |`/ \ | |
  110741. :.....''' |/`....\|...|
  110742. :.........................|___|___|___|
  110743. |Sl |Sr |endW
  110744. | | |endSr
  110745. | |beginSr
  110746. | |endSl
  110747. |beginSl
  110748. |beginW
  110749. */
  110750. /* block abstraction setup *********************************************/
  110751. #ifndef WORD_ALIGN
  110752. #define WORD_ALIGN 8
  110753. #endif
  110754. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  110755. int i;
  110756. memset(vb,0,sizeof(*vb));
  110757. vb->vd=v;
  110758. vb->localalloc=0;
  110759. vb->localstore=NULL;
  110760. if(v->analysisp){
  110761. vorbis_block_internal *vbi=(vorbis_block_internal*)
  110762. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  110763. vbi->ampmax=-9999;
  110764. for(i=0;i<PACKETBLOBS;i++){
  110765. if(i==PACKETBLOBS/2){
  110766. vbi->packetblob[i]=&vb->opb;
  110767. }else{
  110768. vbi->packetblob[i]=
  110769. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  110770. }
  110771. oggpack_writeinit(vbi->packetblob[i]);
  110772. }
  110773. }
  110774. return(0);
  110775. }
  110776. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  110777. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  110778. if(bytes+vb->localtop>vb->localalloc){
  110779. /* can't just _ogg_realloc... there are outstanding pointers */
  110780. if(vb->localstore){
  110781. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  110782. vb->totaluse+=vb->localtop;
  110783. link->next=vb->reap;
  110784. link->ptr=vb->localstore;
  110785. vb->reap=link;
  110786. }
  110787. /* highly conservative */
  110788. vb->localalloc=bytes;
  110789. vb->localstore=_ogg_malloc(vb->localalloc);
  110790. vb->localtop=0;
  110791. }
  110792. {
  110793. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  110794. vb->localtop+=bytes;
  110795. return ret;
  110796. }
  110797. }
  110798. /* reap the chain, pull the ripcord */
  110799. void _vorbis_block_ripcord(vorbis_block *vb){
  110800. /* reap the chain */
  110801. struct alloc_chain *reap=vb->reap;
  110802. while(reap){
  110803. struct alloc_chain *next=reap->next;
  110804. _ogg_free(reap->ptr);
  110805. memset(reap,0,sizeof(*reap));
  110806. _ogg_free(reap);
  110807. reap=next;
  110808. }
  110809. /* consolidate storage */
  110810. if(vb->totaluse){
  110811. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  110812. vb->localalloc+=vb->totaluse;
  110813. vb->totaluse=0;
  110814. }
  110815. /* pull the ripcord */
  110816. vb->localtop=0;
  110817. vb->reap=NULL;
  110818. }
  110819. int vorbis_block_clear(vorbis_block *vb){
  110820. int i;
  110821. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110822. _vorbis_block_ripcord(vb);
  110823. if(vb->localstore)_ogg_free(vb->localstore);
  110824. if(vbi){
  110825. for(i=0;i<PACKETBLOBS;i++){
  110826. oggpack_writeclear(vbi->packetblob[i]);
  110827. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  110828. }
  110829. _ogg_free(vbi);
  110830. }
  110831. memset(vb,0,sizeof(*vb));
  110832. return(0);
  110833. }
  110834. /* Analysis side code, but directly related to blocking. Thus it's
  110835. here and not in analysis.c (which is for analysis transforms only).
  110836. The init is here because some of it is shared */
  110837. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  110838. int i;
  110839. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110840. private_state *b=NULL;
  110841. int hs;
  110842. if(ci==NULL) return 1;
  110843. hs=ci->halfrate_flag;
  110844. memset(v,0,sizeof(*v));
  110845. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  110846. v->vi=vi;
  110847. b->modebits=ilog2(ci->modes);
  110848. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  110849. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  110850. /* MDCT is tranform 0 */
  110851. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110852. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110853. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  110854. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  110855. /* Vorbis I uses only window type 0 */
  110856. b->window[0]=ilog2(ci->blocksizes[0])-6;
  110857. b->window[1]=ilog2(ci->blocksizes[1])-6;
  110858. if(encp){ /* encode/decode differ here */
  110859. /* analysis always needs an fft */
  110860. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  110861. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  110862. /* finish the codebooks */
  110863. if(!ci->fullbooks){
  110864. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110865. for(i=0;i<ci->books;i++)
  110866. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  110867. }
  110868. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  110869. for(i=0;i<ci->psys;i++){
  110870. _vp_psy_init(b->psy+i,
  110871. ci->psy_param[i],
  110872. &ci->psy_g_param,
  110873. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  110874. vi->rate);
  110875. }
  110876. v->analysisp=1;
  110877. }else{
  110878. /* finish the codebooks */
  110879. if(!ci->fullbooks){
  110880. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110881. for(i=0;i<ci->books;i++){
  110882. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  110883. /* decode codebooks are now standalone after init */
  110884. vorbis_staticbook_destroy(ci->book_param[i]);
  110885. ci->book_param[i]=NULL;
  110886. }
  110887. }
  110888. }
  110889. /* initialize the storage vectors. blocksize[1] is small for encode,
  110890. but the correct size for decode */
  110891. v->pcm_storage=ci->blocksizes[1];
  110892. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  110893. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  110894. {
  110895. int i;
  110896. for(i=0;i<vi->channels;i++)
  110897. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  110898. }
  110899. /* all 1 (large block) or 0 (small block) */
  110900. /* explicitly set for the sake of clarity */
  110901. v->lW=0; /* previous window size */
  110902. v->W=0; /* current window size */
  110903. /* all vector indexes */
  110904. v->centerW=ci->blocksizes[1]/2;
  110905. v->pcm_current=v->centerW;
  110906. /* initialize all the backend lookups */
  110907. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  110908. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  110909. for(i=0;i<ci->floors;i++)
  110910. b->flr[i]=_floor_P[ci->floor_type[i]]->
  110911. look(v,ci->floor_param[i]);
  110912. for(i=0;i<ci->residues;i++)
  110913. b->residue[i]=_residue_P[ci->residue_type[i]]->
  110914. look(v,ci->residue_param[i]);
  110915. return 0;
  110916. }
  110917. /* arbitrary settings and spec-mandated numbers get filled in here */
  110918. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  110919. private_state *b=NULL;
  110920. if(_vds_shared_init(v,vi,1))return 1;
  110921. b=(private_state*)v->backend_state;
  110922. b->psy_g_look=_vp_global_look(vi);
  110923. /* Initialize the envelope state storage */
  110924. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  110925. _ve_envelope_init(b->ve,vi);
  110926. vorbis_bitrate_init(vi,&b->bms);
  110927. /* compressed audio packets start after the headers
  110928. with sequence number 3 */
  110929. v->sequence=3;
  110930. return(0);
  110931. }
  110932. void vorbis_dsp_clear(vorbis_dsp_state *v){
  110933. int i;
  110934. if(v){
  110935. vorbis_info *vi=v->vi;
  110936. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  110937. private_state *b=(private_state*)v->backend_state;
  110938. if(b){
  110939. if(b->ve){
  110940. _ve_envelope_clear(b->ve);
  110941. _ogg_free(b->ve);
  110942. }
  110943. if(b->transform[0]){
  110944. mdct_clear((mdct_lookup*) b->transform[0][0]);
  110945. _ogg_free(b->transform[0][0]);
  110946. _ogg_free(b->transform[0]);
  110947. }
  110948. if(b->transform[1]){
  110949. mdct_clear((mdct_lookup*) b->transform[1][0]);
  110950. _ogg_free(b->transform[1][0]);
  110951. _ogg_free(b->transform[1]);
  110952. }
  110953. if(b->flr){
  110954. for(i=0;i<ci->floors;i++)
  110955. _floor_P[ci->floor_type[i]]->
  110956. free_look(b->flr[i]);
  110957. _ogg_free(b->flr);
  110958. }
  110959. if(b->residue){
  110960. for(i=0;i<ci->residues;i++)
  110961. _residue_P[ci->residue_type[i]]->
  110962. free_look(b->residue[i]);
  110963. _ogg_free(b->residue);
  110964. }
  110965. if(b->psy){
  110966. for(i=0;i<ci->psys;i++)
  110967. _vp_psy_clear(b->psy+i);
  110968. _ogg_free(b->psy);
  110969. }
  110970. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  110971. vorbis_bitrate_clear(&b->bms);
  110972. drft_clear(&b->fft_look[0]);
  110973. drft_clear(&b->fft_look[1]);
  110974. }
  110975. if(v->pcm){
  110976. for(i=0;i<vi->channels;i++)
  110977. if(v->pcm[i])_ogg_free(v->pcm[i]);
  110978. _ogg_free(v->pcm);
  110979. if(v->pcmret)_ogg_free(v->pcmret);
  110980. }
  110981. if(b){
  110982. /* free header, header1, header2 */
  110983. if(b->header)_ogg_free(b->header);
  110984. if(b->header1)_ogg_free(b->header1);
  110985. if(b->header2)_ogg_free(b->header2);
  110986. _ogg_free(b);
  110987. }
  110988. memset(v,0,sizeof(*v));
  110989. }
  110990. }
  110991. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  110992. int i;
  110993. vorbis_info *vi=v->vi;
  110994. private_state *b=(private_state*)v->backend_state;
  110995. /* free header, header1, header2 */
  110996. if(b->header)_ogg_free(b->header);b->header=NULL;
  110997. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  110998. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  110999. /* Do we have enough storage space for the requested buffer? If not,
  111000. expand the PCM (and envelope) storage */
  111001. if(v->pcm_current+vals>=v->pcm_storage){
  111002. v->pcm_storage=v->pcm_current+vals*2;
  111003. for(i=0;i<vi->channels;i++){
  111004. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  111005. }
  111006. }
  111007. for(i=0;i<vi->channels;i++)
  111008. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  111009. return(v->pcmret);
  111010. }
  111011. static void _preextrapolate_helper(vorbis_dsp_state *v){
  111012. int i;
  111013. int order=32;
  111014. float *lpc=(float*)alloca(order*sizeof(*lpc));
  111015. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  111016. long j;
  111017. v->preextrapolate=1;
  111018. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111019. for(i=0;i<v->vi->channels;i++){
  111020. /* need to run the extrapolation in reverse! */
  111021. for(j=0;j<v->pcm_current;j++)
  111022. work[j]=v->pcm[i][v->pcm_current-j-1];
  111023. /* prime as above */
  111024. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111025. /* run the predictor filter */
  111026. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111027. order,
  111028. work+v->pcm_current-v->centerW,
  111029. v->centerW);
  111030. for(j=0;j<v->pcm_current;j++)
  111031. v->pcm[i][v->pcm_current-j-1]=work[j];
  111032. }
  111033. }
  111034. }
  111035. /* call with val<=0 to set eof */
  111036. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111037. vorbis_info *vi=v->vi;
  111038. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111039. if(vals<=0){
  111040. int order=32;
  111041. int i;
  111042. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111043. /* if it wasn't done earlier (very short sample) */
  111044. if(!v->preextrapolate)
  111045. _preextrapolate_helper(v);
  111046. /* We're encoding the end of the stream. Just make sure we have
  111047. [at least] a few full blocks of zeroes at the end. */
  111048. /* actually, we don't want zeroes; that could drop a large
  111049. amplitude off a cliff, creating spread spectrum noise that will
  111050. suck to encode. Extrapolate for the sake of cleanliness. */
  111051. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111052. v->eofflag=v->pcm_current;
  111053. v->pcm_current+=ci->blocksizes[1]*3;
  111054. for(i=0;i<vi->channels;i++){
  111055. if(v->eofflag>order*2){
  111056. /* extrapolate with LPC to fill in */
  111057. long n;
  111058. /* make a predictor filter */
  111059. n=v->eofflag;
  111060. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111061. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111062. /* run the predictor filter */
  111063. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111064. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111065. }else{
  111066. /* not enough data to extrapolate (unlikely to happen due to
  111067. guarding the overlap, but bulletproof in case that
  111068. assumtion goes away). zeroes will do. */
  111069. memset(v->pcm[i]+v->eofflag,0,
  111070. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111071. }
  111072. }
  111073. }else{
  111074. if(v->pcm_current+vals>v->pcm_storage)
  111075. return(OV_EINVAL);
  111076. v->pcm_current+=vals;
  111077. /* we may want to reverse extrapolate the beginning of a stream
  111078. too... in case we're beginning on a cliff! */
  111079. /* clumsy, but simple. It only runs once, so simple is good. */
  111080. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111081. _preextrapolate_helper(v);
  111082. }
  111083. return(0);
  111084. }
  111085. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111086. the next block on which to continue analysis */
  111087. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111088. int i;
  111089. vorbis_info *vi=v->vi;
  111090. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111091. private_state *b=(private_state*)v->backend_state;
  111092. vorbis_look_psy_global *g=b->psy_g_look;
  111093. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111094. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111095. /* check to see if we're started... */
  111096. if(!v->preextrapolate)return(0);
  111097. /* check to see if we're done... */
  111098. if(v->eofflag==-1)return(0);
  111099. /* By our invariant, we have lW, W and centerW set. Search for
  111100. the next boundary so we can determine nW (the next window size)
  111101. which lets us compute the shape of the current block's window */
  111102. /* we do an envelope search even on a single blocksize; we may still
  111103. be throwing more bits at impulses, and envelope search handles
  111104. marking impulses too. */
  111105. {
  111106. long bp=_ve_envelope_search(v);
  111107. if(bp==-1){
  111108. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111109. full long block */
  111110. v->nW=0;
  111111. }else{
  111112. if(ci->blocksizes[0]==ci->blocksizes[1])
  111113. v->nW=0;
  111114. else
  111115. v->nW=bp;
  111116. }
  111117. }
  111118. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111119. {
  111120. /* center of next block + next block maximum right side. */
  111121. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111122. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111123. although this check is
  111124. less strict that the
  111125. _ve_envelope_search,
  111126. the search is not run
  111127. if we only use one
  111128. block size */
  111129. }
  111130. /* fill in the block. Note that for a short window, lW and nW are *short*
  111131. regardless of actual settings in the stream */
  111132. _vorbis_block_ripcord(vb);
  111133. vb->lW=v->lW;
  111134. vb->W=v->W;
  111135. vb->nW=v->nW;
  111136. if(v->W){
  111137. if(!v->lW || !v->nW){
  111138. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111139. /*fprintf(stderr,"-");*/
  111140. }else{
  111141. vbi->blocktype=BLOCKTYPE_LONG;
  111142. /*fprintf(stderr,"_");*/
  111143. }
  111144. }else{
  111145. if(_ve_envelope_mark(v)){
  111146. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111147. /*fprintf(stderr,"|");*/
  111148. }else{
  111149. vbi->blocktype=BLOCKTYPE_PADDING;
  111150. /*fprintf(stderr,".");*/
  111151. }
  111152. }
  111153. vb->vd=v;
  111154. vb->sequence=v->sequence++;
  111155. vb->granulepos=v->granulepos;
  111156. vb->pcmend=ci->blocksizes[v->W];
  111157. /* copy the vectors; this uses the local storage in vb */
  111158. /* this tracks 'strongest peak' for later psychoacoustics */
  111159. /* moved to the global psy state; clean this mess up */
  111160. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111161. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111162. vbi->ampmax=g->ampmax;
  111163. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111164. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111165. for(i=0;i<vi->channels;i++){
  111166. vbi->pcmdelay[i]=
  111167. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111168. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111169. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111170. /* before we added the delay
  111171. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111172. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111173. */
  111174. }
  111175. /* handle eof detection: eof==0 means that we've not yet received EOF
  111176. eof>0 marks the last 'real' sample in pcm[]
  111177. eof<0 'no more to do'; doesn't get here */
  111178. if(v->eofflag){
  111179. if(v->centerW>=v->eofflag){
  111180. v->eofflag=-1;
  111181. vb->eofflag=1;
  111182. return(1);
  111183. }
  111184. }
  111185. /* advance storage vectors and clean up */
  111186. {
  111187. int new_centerNext=ci->blocksizes[1]/2;
  111188. int movementW=centerNext-new_centerNext;
  111189. if(movementW>0){
  111190. _ve_envelope_shift(b->ve,movementW);
  111191. v->pcm_current-=movementW;
  111192. for(i=0;i<vi->channels;i++)
  111193. memmove(v->pcm[i],v->pcm[i]+movementW,
  111194. v->pcm_current*sizeof(*v->pcm[i]));
  111195. v->lW=v->W;
  111196. v->W=v->nW;
  111197. v->centerW=new_centerNext;
  111198. if(v->eofflag){
  111199. v->eofflag-=movementW;
  111200. if(v->eofflag<=0)v->eofflag=-1;
  111201. /* do not add padding to end of stream! */
  111202. if(v->centerW>=v->eofflag){
  111203. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111204. }else{
  111205. v->granulepos+=movementW;
  111206. }
  111207. }else{
  111208. v->granulepos+=movementW;
  111209. }
  111210. }
  111211. }
  111212. /* done */
  111213. return(1);
  111214. }
  111215. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111216. vorbis_info *vi=v->vi;
  111217. codec_setup_info *ci;
  111218. int hs;
  111219. if(!v->backend_state)return -1;
  111220. if(!vi)return -1;
  111221. ci=(codec_setup_info*) vi->codec_setup;
  111222. if(!ci)return -1;
  111223. hs=ci->halfrate_flag;
  111224. v->centerW=ci->blocksizes[1]>>(hs+1);
  111225. v->pcm_current=v->centerW>>hs;
  111226. v->pcm_returned=-1;
  111227. v->granulepos=-1;
  111228. v->sequence=-1;
  111229. v->eofflag=0;
  111230. ((private_state *)(v->backend_state))->sample_count=-1;
  111231. return(0);
  111232. }
  111233. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111234. if(_vds_shared_init(v,vi,0)) return 1;
  111235. vorbis_synthesis_restart(v);
  111236. return 0;
  111237. }
  111238. /* Unlike in analysis, the window is only partially applied for each
  111239. block. The time domain envelope is not yet handled at the point of
  111240. calling (as it relies on the previous block). */
  111241. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111242. vorbis_info *vi=v->vi;
  111243. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111244. private_state *b=(private_state*)v->backend_state;
  111245. int hs=ci->halfrate_flag;
  111246. int i,j;
  111247. if(!vb)return(OV_EINVAL);
  111248. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111249. v->lW=v->W;
  111250. v->W=vb->W;
  111251. v->nW=-1;
  111252. if((v->sequence==-1)||
  111253. (v->sequence+1 != vb->sequence)){
  111254. v->granulepos=-1; /* out of sequence; lose count */
  111255. b->sample_count=-1;
  111256. }
  111257. v->sequence=vb->sequence;
  111258. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111259. was called on block */
  111260. int n=ci->blocksizes[v->W]>>(hs+1);
  111261. int n0=ci->blocksizes[0]>>(hs+1);
  111262. int n1=ci->blocksizes[1]>>(hs+1);
  111263. int thisCenter;
  111264. int prevCenter;
  111265. v->glue_bits+=vb->glue_bits;
  111266. v->time_bits+=vb->time_bits;
  111267. v->floor_bits+=vb->floor_bits;
  111268. v->res_bits+=vb->res_bits;
  111269. if(v->centerW){
  111270. thisCenter=n1;
  111271. prevCenter=0;
  111272. }else{
  111273. thisCenter=0;
  111274. prevCenter=n1;
  111275. }
  111276. /* v->pcm is now used like a two-stage double buffer. We don't want
  111277. to have to constantly shift *or* adjust memory usage. Don't
  111278. accept a new block until the old is shifted out */
  111279. for(j=0;j<vi->channels;j++){
  111280. /* the overlap/add section */
  111281. if(v->lW){
  111282. if(v->W){
  111283. /* large/large */
  111284. float *w=_vorbis_window_get(b->window[1]-hs);
  111285. float *pcm=v->pcm[j]+prevCenter;
  111286. float *p=vb->pcm[j];
  111287. for(i=0;i<n1;i++)
  111288. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111289. }else{
  111290. /* large/small */
  111291. float *w=_vorbis_window_get(b->window[0]-hs);
  111292. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111293. float *p=vb->pcm[j];
  111294. for(i=0;i<n0;i++)
  111295. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111296. }
  111297. }else{
  111298. if(v->W){
  111299. /* small/large */
  111300. float *w=_vorbis_window_get(b->window[0]-hs);
  111301. float *pcm=v->pcm[j]+prevCenter;
  111302. float *p=vb->pcm[j]+n1/2-n0/2;
  111303. for(i=0;i<n0;i++)
  111304. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111305. for(;i<n1/2+n0/2;i++)
  111306. pcm[i]=p[i];
  111307. }else{
  111308. /* small/small */
  111309. float *w=_vorbis_window_get(b->window[0]-hs);
  111310. float *pcm=v->pcm[j]+prevCenter;
  111311. float *p=vb->pcm[j];
  111312. for(i=0;i<n0;i++)
  111313. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111314. }
  111315. }
  111316. /* the copy section */
  111317. {
  111318. float *pcm=v->pcm[j]+thisCenter;
  111319. float *p=vb->pcm[j]+n;
  111320. for(i=0;i<n;i++)
  111321. pcm[i]=p[i];
  111322. }
  111323. }
  111324. if(v->centerW)
  111325. v->centerW=0;
  111326. else
  111327. v->centerW=n1;
  111328. /* deal with initial packet state; we do this using the explicit
  111329. pcm_returned==-1 flag otherwise we're sensitive to first block
  111330. being short or long */
  111331. if(v->pcm_returned==-1){
  111332. v->pcm_returned=thisCenter;
  111333. v->pcm_current=thisCenter;
  111334. }else{
  111335. v->pcm_returned=prevCenter;
  111336. v->pcm_current=prevCenter+
  111337. ((ci->blocksizes[v->lW]/4+
  111338. ci->blocksizes[v->W]/4)>>hs);
  111339. }
  111340. }
  111341. /* track the frame number... This is for convenience, but also
  111342. making sure our last packet doesn't end with added padding. If
  111343. the last packet is partial, the number of samples we'll have to
  111344. return will be past the vb->granulepos.
  111345. This is not foolproof! It will be confused if we begin
  111346. decoding at the last page after a seek or hole. In that case,
  111347. we don't have a starting point to judge where the last frame
  111348. is. For this reason, vorbisfile will always try to make sure
  111349. it reads the last two marked pages in proper sequence */
  111350. if(b->sample_count==-1){
  111351. b->sample_count=0;
  111352. }else{
  111353. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111354. }
  111355. if(v->granulepos==-1){
  111356. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111357. v->granulepos=vb->granulepos;
  111358. /* is this a short page? */
  111359. if(b->sample_count>v->granulepos){
  111360. /* corner case; if this is both the first and last audio page,
  111361. then spec says the end is cut, not beginning */
  111362. if(vb->eofflag){
  111363. /* trim the end */
  111364. /* no preceeding granulepos; assume we started at zero (we'd
  111365. have to in a short single-page stream) */
  111366. /* granulepos could be -1 due to a seek, but that would result
  111367. in a long count, not short count */
  111368. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111369. }else{
  111370. /* trim the beginning */
  111371. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111372. if(v->pcm_returned>v->pcm_current)
  111373. v->pcm_returned=v->pcm_current;
  111374. }
  111375. }
  111376. }
  111377. }else{
  111378. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111379. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111380. if(v->granulepos>vb->granulepos){
  111381. long extra=v->granulepos-vb->granulepos;
  111382. if(extra)
  111383. if(vb->eofflag){
  111384. /* partial last frame. Strip the extra samples off */
  111385. v->pcm_current-=extra>>hs;
  111386. } /* else {Shouldn't happen *unless* the bitstream is out of
  111387. spec. Either way, believe the bitstream } */
  111388. } /* else {Shouldn't happen *unless* the bitstream is out of
  111389. spec. Either way, believe the bitstream } */
  111390. v->granulepos=vb->granulepos;
  111391. }
  111392. }
  111393. /* Update, cleanup */
  111394. if(vb->eofflag)v->eofflag=1;
  111395. return(0);
  111396. }
  111397. /* pcm==NULL indicates we just want the pending samples, no more */
  111398. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111399. vorbis_info *vi=v->vi;
  111400. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111401. if(pcm){
  111402. int i;
  111403. for(i=0;i<vi->channels;i++)
  111404. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111405. *pcm=v->pcmret;
  111406. }
  111407. return(v->pcm_current-v->pcm_returned);
  111408. }
  111409. return(0);
  111410. }
  111411. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111412. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111413. v->pcm_returned+=n;
  111414. return(0);
  111415. }
  111416. /* intended for use with a specific vorbisfile feature; we want access
  111417. to the [usually synthetic/postextrapolated] buffer and lapping at
  111418. the end of a decode cycle, specifically, a half-short-block worth.
  111419. This funtion works like pcmout above, except it will also expose
  111420. this implicit buffer data not normally decoded. */
  111421. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111422. vorbis_info *vi=v->vi;
  111423. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111424. int hs=ci->halfrate_flag;
  111425. int n=ci->blocksizes[v->W]>>(hs+1);
  111426. int n0=ci->blocksizes[0]>>(hs+1);
  111427. int n1=ci->blocksizes[1]>>(hs+1);
  111428. int i,j;
  111429. if(v->pcm_returned<0)return 0;
  111430. /* our returned data ends at pcm_returned; because the synthesis pcm
  111431. buffer is a two-fragment ring, that means our data block may be
  111432. fragmented by buffering, wrapping or a short block not filling
  111433. out a buffer. To simplify things, we unfragment if it's at all
  111434. possibly needed. Otherwise, we'd need to call lapout more than
  111435. once as well as hold additional dsp state. Opt for
  111436. simplicity. */
  111437. /* centerW was advanced by blockin; it would be the center of the
  111438. *next* block */
  111439. if(v->centerW==n1){
  111440. /* the data buffer wraps; swap the halves */
  111441. /* slow, sure, small */
  111442. for(j=0;j<vi->channels;j++){
  111443. float *p=v->pcm[j];
  111444. for(i=0;i<n1;i++){
  111445. float temp=p[i];
  111446. p[i]=p[i+n1];
  111447. p[i+n1]=temp;
  111448. }
  111449. }
  111450. v->pcm_current-=n1;
  111451. v->pcm_returned-=n1;
  111452. v->centerW=0;
  111453. }
  111454. /* solidify buffer into contiguous space */
  111455. if((v->lW^v->W)==1){
  111456. /* long/short or short/long */
  111457. for(j=0;j<vi->channels;j++){
  111458. float *s=v->pcm[j];
  111459. float *d=v->pcm[j]+(n1-n0)/2;
  111460. for(i=(n1+n0)/2-1;i>=0;--i)
  111461. d[i]=s[i];
  111462. }
  111463. v->pcm_returned+=(n1-n0)/2;
  111464. v->pcm_current+=(n1-n0)/2;
  111465. }else{
  111466. if(v->lW==0){
  111467. /* short/short */
  111468. for(j=0;j<vi->channels;j++){
  111469. float *s=v->pcm[j];
  111470. float *d=v->pcm[j]+n1-n0;
  111471. for(i=n0-1;i>=0;--i)
  111472. d[i]=s[i];
  111473. }
  111474. v->pcm_returned+=n1-n0;
  111475. v->pcm_current+=n1-n0;
  111476. }
  111477. }
  111478. if(pcm){
  111479. int i;
  111480. for(i=0;i<vi->channels;i++)
  111481. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111482. *pcm=v->pcmret;
  111483. }
  111484. return(n1+n-v->pcm_returned);
  111485. }
  111486. float *vorbis_window(vorbis_dsp_state *v,int W){
  111487. vorbis_info *vi=v->vi;
  111488. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111489. int hs=ci->halfrate_flag;
  111490. private_state *b=(private_state*)v->backend_state;
  111491. if(b->window[W]-1<0)return NULL;
  111492. return _vorbis_window_get(b->window[W]-hs);
  111493. }
  111494. #endif
  111495. /*** End of inlined file: block.c ***/
  111496. /*** Start of inlined file: codebook.c ***/
  111497. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111498. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111499. // tasks..
  111500. #if JUCE_MSVC
  111501. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111502. #endif
  111503. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111504. #if JUCE_USE_OGGVORBIS
  111505. #include <stdlib.h>
  111506. #include <string.h>
  111507. #include <math.h>
  111508. /* packs the given codebook into the bitstream **************************/
  111509. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  111510. long i,j;
  111511. int ordered=0;
  111512. /* first the basic parameters */
  111513. oggpack_write(opb,0x564342,24);
  111514. oggpack_write(opb,c->dim,16);
  111515. oggpack_write(opb,c->entries,24);
  111516. /* pack the codewords. There are two packings; length ordered and
  111517. length random. Decide between the two now. */
  111518. for(i=1;i<c->entries;i++)
  111519. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  111520. if(i==c->entries)ordered=1;
  111521. if(ordered){
  111522. /* length ordered. We only need to say how many codewords of
  111523. each length. The actual codewords are generated
  111524. deterministically */
  111525. long count=0;
  111526. oggpack_write(opb,1,1); /* ordered */
  111527. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  111528. for(i=1;i<c->entries;i++){
  111529. long thisx=c->lengthlist[i];
  111530. long last=c->lengthlist[i-1];
  111531. if(thisx>last){
  111532. for(j=last;j<thisx;j++){
  111533. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111534. count=i;
  111535. }
  111536. }
  111537. }
  111538. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111539. }else{
  111540. /* length random. Again, we don't code the codeword itself, just
  111541. the length. This time, though, we have to encode each length */
  111542. oggpack_write(opb,0,1); /* unordered */
  111543. /* algortihmic mapping has use for 'unused entries', which we tag
  111544. here. The algorithmic mapping happens as usual, but the unused
  111545. entry has no codeword. */
  111546. for(i=0;i<c->entries;i++)
  111547. if(c->lengthlist[i]==0)break;
  111548. if(i==c->entries){
  111549. oggpack_write(opb,0,1); /* no unused entries */
  111550. for(i=0;i<c->entries;i++)
  111551. oggpack_write(opb,c->lengthlist[i]-1,5);
  111552. }else{
  111553. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  111554. for(i=0;i<c->entries;i++){
  111555. if(c->lengthlist[i]==0){
  111556. oggpack_write(opb,0,1);
  111557. }else{
  111558. oggpack_write(opb,1,1);
  111559. oggpack_write(opb,c->lengthlist[i]-1,5);
  111560. }
  111561. }
  111562. }
  111563. }
  111564. /* is the entry number the desired return value, or do we have a
  111565. mapping? If we have a mapping, what type? */
  111566. oggpack_write(opb,c->maptype,4);
  111567. switch(c->maptype){
  111568. case 0:
  111569. /* no mapping */
  111570. break;
  111571. case 1:case 2:
  111572. /* implicitly populated value mapping */
  111573. /* explicitly populated value mapping */
  111574. if(!c->quantlist){
  111575. /* no quantlist? error */
  111576. return(-1);
  111577. }
  111578. /* values that define the dequantization */
  111579. oggpack_write(opb,c->q_min,32);
  111580. oggpack_write(opb,c->q_delta,32);
  111581. oggpack_write(opb,c->q_quant-1,4);
  111582. oggpack_write(opb,c->q_sequencep,1);
  111583. {
  111584. int quantvals;
  111585. switch(c->maptype){
  111586. case 1:
  111587. /* a single column of (c->entries/c->dim) quantized values for
  111588. building a full value list algorithmically (square lattice) */
  111589. quantvals=_book_maptype1_quantvals(c);
  111590. break;
  111591. case 2:
  111592. /* every value (c->entries*c->dim total) specified explicitly */
  111593. quantvals=c->entries*c->dim;
  111594. break;
  111595. default: /* NOT_REACHABLE */
  111596. quantvals=-1;
  111597. }
  111598. /* quantized values */
  111599. for(i=0;i<quantvals;i++)
  111600. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  111601. }
  111602. break;
  111603. default:
  111604. /* error case; we don't have any other map types now */
  111605. return(-1);
  111606. }
  111607. return(0);
  111608. }
  111609. /* unpacks a codebook from the packet buffer into the codebook struct,
  111610. readies the codebook auxiliary structures for decode *************/
  111611. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  111612. long i,j;
  111613. memset(s,0,sizeof(*s));
  111614. s->allocedp=1;
  111615. /* make sure alignment is correct */
  111616. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  111617. /* first the basic parameters */
  111618. s->dim=oggpack_read(opb,16);
  111619. s->entries=oggpack_read(opb,24);
  111620. if(s->entries==-1)goto _eofout;
  111621. /* codeword ordering.... length ordered or unordered? */
  111622. switch((int)oggpack_read(opb,1)){
  111623. case 0:
  111624. /* unordered */
  111625. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111626. /* allocated but unused entries? */
  111627. if(oggpack_read(opb,1)){
  111628. /* yes, unused entries */
  111629. for(i=0;i<s->entries;i++){
  111630. if(oggpack_read(opb,1)){
  111631. long num=oggpack_read(opb,5);
  111632. if(num==-1)goto _eofout;
  111633. s->lengthlist[i]=num+1;
  111634. }else
  111635. s->lengthlist[i]=0;
  111636. }
  111637. }else{
  111638. /* all entries used; no tagging */
  111639. for(i=0;i<s->entries;i++){
  111640. long num=oggpack_read(opb,5);
  111641. if(num==-1)goto _eofout;
  111642. s->lengthlist[i]=num+1;
  111643. }
  111644. }
  111645. break;
  111646. case 1:
  111647. /* ordered */
  111648. {
  111649. long length=oggpack_read(opb,5)+1;
  111650. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111651. for(i=0;i<s->entries;){
  111652. long num=oggpack_read(opb,_ilog(s->entries-i));
  111653. if(num==-1)goto _eofout;
  111654. for(j=0;j<num && i<s->entries;j++,i++)
  111655. s->lengthlist[i]=length;
  111656. length++;
  111657. }
  111658. }
  111659. break;
  111660. default:
  111661. /* EOF */
  111662. return(-1);
  111663. }
  111664. /* Do we have a mapping to unpack? */
  111665. switch((s->maptype=oggpack_read(opb,4))){
  111666. case 0:
  111667. /* no mapping */
  111668. break;
  111669. case 1: case 2:
  111670. /* implicitly populated value mapping */
  111671. /* explicitly populated value mapping */
  111672. s->q_min=oggpack_read(opb,32);
  111673. s->q_delta=oggpack_read(opb,32);
  111674. s->q_quant=oggpack_read(opb,4)+1;
  111675. s->q_sequencep=oggpack_read(opb,1);
  111676. {
  111677. int quantvals=0;
  111678. switch(s->maptype){
  111679. case 1:
  111680. quantvals=_book_maptype1_quantvals(s);
  111681. break;
  111682. case 2:
  111683. quantvals=s->entries*s->dim;
  111684. break;
  111685. }
  111686. /* quantized values */
  111687. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  111688. for(i=0;i<quantvals;i++)
  111689. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  111690. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  111691. }
  111692. break;
  111693. default:
  111694. goto _errout;
  111695. }
  111696. /* all set */
  111697. return(0);
  111698. _errout:
  111699. _eofout:
  111700. vorbis_staticbook_clear(s);
  111701. return(-1);
  111702. }
  111703. /* returns the number of bits ************************************************/
  111704. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  111705. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  111706. return(book->c->lengthlist[a]);
  111707. }
  111708. /* One the encode side, our vector writers are each designed for a
  111709. specific purpose, and the encoder is not flexible without modification:
  111710. The LSP vector coder uses a single stage nearest-match with no
  111711. interleave, so no step and no error return. This is specced by floor0
  111712. and doesn't change.
  111713. Residue0 encoding interleaves, uses multiple stages, and each stage
  111714. peels of a specific amount of resolution from a lattice (thus we want
  111715. to match by threshold, not nearest match). Residue doesn't *have* to
  111716. be encoded that way, but to change it, one will need to add more
  111717. infrastructure on the encode side (decode side is specced and simpler) */
  111718. /* floor0 LSP (single stage, non interleaved, nearest match) */
  111719. /* returns entry number and *modifies a* to the quantization value *****/
  111720. int vorbis_book_errorv(codebook *book,float *a){
  111721. int dim=book->dim,k;
  111722. int best=_best(book,a,1);
  111723. for(k=0;k<dim;k++)
  111724. a[k]=(book->valuelist+best*dim)[k];
  111725. return(best);
  111726. }
  111727. /* returns the number of bits and *modifies a* to the quantization value *****/
  111728. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  111729. int k,dim=book->dim;
  111730. for(k=0;k<dim;k++)
  111731. a[k]=(book->valuelist+best*dim)[k];
  111732. return(vorbis_book_encode(book,best,b));
  111733. }
  111734. /* the 'eliminate the decode tree' optimization actually requires the
  111735. codewords to be MSb first, not LSb. This is an annoying inelegancy
  111736. (and one of the first places where carefully thought out design
  111737. turned out to be wrong; Vorbis II and future Ogg codecs should go
  111738. to an MSb bitpacker), but not actually the huge hit it appears to
  111739. be. The first-stage decode table catches most words so that
  111740. bitreverse is not in the main execution path. */
  111741. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  111742. int read=book->dec_maxlength;
  111743. long lo,hi;
  111744. long lok = oggpack_look(b,book->dec_firsttablen);
  111745. if (lok >= 0) {
  111746. long entry = book->dec_firsttable[lok];
  111747. if(entry&0x80000000UL){
  111748. lo=(entry>>15)&0x7fff;
  111749. hi=book->used_entries-(entry&0x7fff);
  111750. }else{
  111751. oggpack_adv(b, book->dec_codelengths[entry-1]);
  111752. return(entry-1);
  111753. }
  111754. }else{
  111755. lo=0;
  111756. hi=book->used_entries;
  111757. }
  111758. lok = oggpack_look(b, read);
  111759. while(lok<0 && read>1)
  111760. lok = oggpack_look(b, --read);
  111761. if(lok<0)return -1;
  111762. /* bisect search for the codeword in the ordered list */
  111763. {
  111764. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  111765. while(hi-lo>1){
  111766. long p=(hi-lo)>>1;
  111767. long test=book->codelist[lo+p]>testword;
  111768. lo+=p&(test-1);
  111769. hi-=p&(-test);
  111770. }
  111771. if(book->dec_codelengths[lo]<=read){
  111772. oggpack_adv(b, book->dec_codelengths[lo]);
  111773. return(lo);
  111774. }
  111775. }
  111776. oggpack_adv(b, read);
  111777. return(-1);
  111778. }
  111779. /* Decode side is specced and easier, because we don't need to find
  111780. matches using different criteria; we simply read and map. There are
  111781. two things we need to do 'depending':
  111782. We may need to support interleave. We don't really, but it's
  111783. convenient to do it here rather than rebuild the vector later.
  111784. Cascades may be additive or multiplicitive; this is not inherent in
  111785. the codebook, but set in the code using the codebook. Like
  111786. interleaving, it's easiest to do it here.
  111787. addmul==0 -> declarative (set the value)
  111788. addmul==1 -> additive
  111789. addmul==2 -> multiplicitive */
  111790. /* returns the [original, not compacted] entry number or -1 on eof *********/
  111791. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  111792. long packed_entry=decode_packed_entry_number(book,b);
  111793. if(packed_entry>=0)
  111794. return(book->dec_index[packed_entry]);
  111795. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  111796. return(packed_entry);
  111797. }
  111798. /* returns 0 on OK or -1 on eof *************************************/
  111799. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111800. int step=n/book->dim;
  111801. long *entry = (long*)alloca(sizeof(*entry)*step);
  111802. float **t = (float**)alloca(sizeof(*t)*step);
  111803. int i,j,o;
  111804. for (i = 0; i < step; i++) {
  111805. entry[i]=decode_packed_entry_number(book,b);
  111806. if(entry[i]==-1)return(-1);
  111807. t[i] = book->valuelist+entry[i]*book->dim;
  111808. }
  111809. for(i=0,o=0;i<book->dim;i++,o+=step)
  111810. for (j=0;j<step;j++)
  111811. a[o+j]+=t[j][i];
  111812. return(0);
  111813. }
  111814. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111815. int i,j,entry;
  111816. float *t;
  111817. if(book->dim>8){
  111818. for(i=0;i<n;){
  111819. entry = decode_packed_entry_number(book,b);
  111820. if(entry==-1)return(-1);
  111821. t = book->valuelist+entry*book->dim;
  111822. for (j=0;j<book->dim;)
  111823. a[i++]+=t[j++];
  111824. }
  111825. }else{
  111826. for(i=0;i<n;){
  111827. entry = decode_packed_entry_number(book,b);
  111828. if(entry==-1)return(-1);
  111829. t = book->valuelist+entry*book->dim;
  111830. j=0;
  111831. switch((int)book->dim){
  111832. case 8:
  111833. a[i++]+=t[j++];
  111834. case 7:
  111835. a[i++]+=t[j++];
  111836. case 6:
  111837. a[i++]+=t[j++];
  111838. case 5:
  111839. a[i++]+=t[j++];
  111840. case 4:
  111841. a[i++]+=t[j++];
  111842. case 3:
  111843. a[i++]+=t[j++];
  111844. case 2:
  111845. a[i++]+=t[j++];
  111846. case 1:
  111847. a[i++]+=t[j++];
  111848. case 0:
  111849. break;
  111850. }
  111851. }
  111852. }
  111853. return(0);
  111854. }
  111855. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  111856. int i,j,entry;
  111857. float *t;
  111858. for(i=0;i<n;){
  111859. entry = decode_packed_entry_number(book,b);
  111860. if(entry==-1)return(-1);
  111861. t = book->valuelist+entry*book->dim;
  111862. for (j=0;j<book->dim;)
  111863. a[i++]=t[j++];
  111864. }
  111865. return(0);
  111866. }
  111867. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  111868. oggpack_buffer *b,int n){
  111869. long i,j,entry;
  111870. int chptr=0;
  111871. for(i=offset/ch;i<(offset+n)/ch;){
  111872. entry = decode_packed_entry_number(book,b);
  111873. if(entry==-1)return(-1);
  111874. {
  111875. const float *t = book->valuelist+entry*book->dim;
  111876. for (j=0;j<book->dim;j++){
  111877. a[chptr++][i]+=t[j];
  111878. if(chptr==ch){
  111879. chptr=0;
  111880. i++;
  111881. }
  111882. }
  111883. }
  111884. }
  111885. return(0);
  111886. }
  111887. #ifdef _V_SELFTEST
  111888. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  111889. number of vectors through (keeping track of the quantized values),
  111890. and decode using the unpacked book. quantized version of in should
  111891. exactly equal out */
  111892. #include <stdio.h>
  111893. #include "vorbis/book/lsp20_0.vqh"
  111894. #include "vorbis/book/res0a_13.vqh"
  111895. #define TESTSIZE 40
  111896. float test1[TESTSIZE]={
  111897. 0.105939f,
  111898. 0.215373f,
  111899. 0.429117f,
  111900. 0.587974f,
  111901. 0.181173f,
  111902. 0.296583f,
  111903. 0.515707f,
  111904. 0.715261f,
  111905. 0.162327f,
  111906. 0.263834f,
  111907. 0.342876f,
  111908. 0.406025f,
  111909. 0.103571f,
  111910. 0.223561f,
  111911. 0.368513f,
  111912. 0.540313f,
  111913. 0.136672f,
  111914. 0.395882f,
  111915. 0.587183f,
  111916. 0.652476f,
  111917. 0.114338f,
  111918. 0.417300f,
  111919. 0.525486f,
  111920. 0.698679f,
  111921. 0.147492f,
  111922. 0.324481f,
  111923. 0.643089f,
  111924. 0.757582f,
  111925. 0.139556f,
  111926. 0.215795f,
  111927. 0.324559f,
  111928. 0.399387f,
  111929. 0.120236f,
  111930. 0.267420f,
  111931. 0.446940f,
  111932. 0.608760f,
  111933. 0.115587f,
  111934. 0.287234f,
  111935. 0.571081f,
  111936. 0.708603f,
  111937. };
  111938. float test3[TESTSIZE]={
  111939. 0,1,-2,3,4,-5,6,7,8,9,
  111940. 8,-2,7,-1,4,6,8,3,1,-9,
  111941. 10,11,12,13,14,15,26,17,18,19,
  111942. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  111943. static_codebook *testlist[]={&_vq_book_lsp20_0,
  111944. &_vq_book_res0a_13,NULL};
  111945. float *testvec[]={test1,test3};
  111946. int main(){
  111947. oggpack_buffer write;
  111948. oggpack_buffer read;
  111949. long ptr=0,i;
  111950. oggpack_writeinit(&write);
  111951. fprintf(stderr,"Testing codebook abstraction...:\n");
  111952. while(testlist[ptr]){
  111953. codebook c;
  111954. static_codebook s;
  111955. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  111956. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  111957. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  111958. memset(iv,0,sizeof(*iv)*TESTSIZE);
  111959. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  111960. /* pack the codebook, write the testvector */
  111961. oggpack_reset(&write);
  111962. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  111963. we can write */
  111964. vorbis_staticbook_pack(testlist[ptr],&write);
  111965. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  111966. for(i=0;i<TESTSIZE;i+=c.dim){
  111967. int best=_best(&c,qv+i,1);
  111968. vorbis_book_encodev(&c,best,qv+i,&write);
  111969. }
  111970. vorbis_book_clear(&c);
  111971. fprintf(stderr,"OK.\n");
  111972. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  111973. /* transfer the write data to a read buffer and unpack/read */
  111974. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  111975. if(vorbis_staticbook_unpack(&read,&s)){
  111976. fprintf(stderr,"Error unpacking codebook.\n");
  111977. exit(1);
  111978. }
  111979. if(vorbis_book_init_decode(&c,&s)){
  111980. fprintf(stderr,"Error initializing codebook.\n");
  111981. exit(1);
  111982. }
  111983. for(i=0;i<TESTSIZE;i+=c.dim)
  111984. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  111985. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  111986. exit(1);
  111987. }
  111988. for(i=0;i<TESTSIZE;i++)
  111989. if(fabs(qv[i]-iv[i])>.000001){
  111990. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  111991. iv[i],qv[i],i);
  111992. exit(1);
  111993. }
  111994. fprintf(stderr,"OK\n");
  111995. ptr++;
  111996. }
  111997. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  111998. exit(0);
  111999. }
  112000. #endif
  112001. #endif
  112002. /*** End of inlined file: codebook.c ***/
  112003. /*** Start of inlined file: envelope.c ***/
  112004. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112005. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112006. // tasks..
  112007. #if JUCE_MSVC
  112008. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112009. #endif
  112010. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112011. #if JUCE_USE_OGGVORBIS
  112012. #include <stdlib.h>
  112013. #include <string.h>
  112014. #include <stdio.h>
  112015. #include <math.h>
  112016. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  112017. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112018. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112019. int ch=vi->channels;
  112020. int i,j;
  112021. int n=e->winlength=128;
  112022. e->searchstep=64; /* not random */
  112023. e->minenergy=gi->preecho_minenergy;
  112024. e->ch=ch;
  112025. e->storage=128;
  112026. e->cursor=ci->blocksizes[1]/2;
  112027. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112028. mdct_init(&e->mdct,n);
  112029. for(i=0;i<n;i++){
  112030. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112031. e->mdct_win[i]*=e->mdct_win[i];
  112032. }
  112033. /* magic follows */
  112034. e->band[0].begin=2; e->band[0].end=4;
  112035. e->band[1].begin=4; e->band[1].end=5;
  112036. e->band[2].begin=6; e->band[2].end=6;
  112037. e->band[3].begin=9; e->band[3].end=8;
  112038. e->band[4].begin=13; e->band[4].end=8;
  112039. e->band[5].begin=17; e->band[5].end=8;
  112040. e->band[6].begin=22; e->band[6].end=8;
  112041. for(j=0;j<VE_BANDS;j++){
  112042. n=e->band[j].end;
  112043. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112044. for(i=0;i<n;i++){
  112045. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112046. e->band[j].total+=e->band[j].window[i];
  112047. }
  112048. e->band[j].total=1./e->band[j].total;
  112049. }
  112050. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112051. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112052. }
  112053. void _ve_envelope_clear(envelope_lookup *e){
  112054. int i;
  112055. mdct_clear(&e->mdct);
  112056. for(i=0;i<VE_BANDS;i++)
  112057. _ogg_free(e->band[i].window);
  112058. _ogg_free(e->mdct_win);
  112059. _ogg_free(e->filter);
  112060. _ogg_free(e->mark);
  112061. memset(e,0,sizeof(*e));
  112062. }
  112063. /* fairly straight threshhold-by-band based until we find something
  112064. that works better and isn't patented. */
  112065. static int _ve_amp(envelope_lookup *ve,
  112066. vorbis_info_psy_global *gi,
  112067. float *data,
  112068. envelope_band *bands,
  112069. envelope_filter_state *filters,
  112070. long pos){
  112071. long n=ve->winlength;
  112072. int ret=0;
  112073. long i,j;
  112074. float decay;
  112075. /* we want to have a 'minimum bar' for energy, else we're just
  112076. basing blocks on quantization noise that outweighs the signal
  112077. itself (for low power signals) */
  112078. float minV=ve->minenergy;
  112079. float *vec=(float*) alloca(n*sizeof(*vec));
  112080. /* stretch is used to gradually lengthen the number of windows
  112081. considered prevoius-to-potential-trigger */
  112082. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112083. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112084. if(penalty<0.f)penalty=0.f;
  112085. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112086. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112087. totalshift+pos*ve->searchstep);*/
  112088. /* window and transform */
  112089. for(i=0;i<n;i++)
  112090. vec[i]=data[i]*ve->mdct_win[i];
  112091. mdct_forward(&ve->mdct,vec,vec);
  112092. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112093. /* near-DC spreading function; this has nothing to do with
  112094. psychoacoustics, just sidelobe leakage and window size */
  112095. {
  112096. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112097. int ptr=filters->nearptr;
  112098. /* the accumulation is regularly refreshed from scratch to avoid
  112099. floating point creep */
  112100. if(ptr==0){
  112101. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112102. filters->nearDC_partialacc=temp;
  112103. }else{
  112104. decay=filters->nearDC_acc+=temp;
  112105. filters->nearDC_partialacc+=temp;
  112106. }
  112107. filters->nearDC_acc-=filters->nearDC[ptr];
  112108. filters->nearDC[ptr]=temp;
  112109. decay*=(1./(VE_NEARDC+1));
  112110. filters->nearptr++;
  112111. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112112. decay=todB(&decay)*.5-15.f;
  112113. }
  112114. /* perform spreading and limiting, also smooth the spectrum. yes,
  112115. the MDCT results in all real coefficients, but it still *behaves*
  112116. like real/imaginary pairs */
  112117. for(i=0;i<n/2;i+=2){
  112118. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112119. val=todB(&val)*.5f;
  112120. if(val<decay)val=decay;
  112121. if(val<minV)val=minV;
  112122. vec[i>>1]=val;
  112123. decay-=8.;
  112124. }
  112125. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112126. /* perform preecho/postecho triggering by band */
  112127. for(j=0;j<VE_BANDS;j++){
  112128. float acc=0.;
  112129. float valmax,valmin;
  112130. /* accumulate amplitude */
  112131. for(i=0;i<bands[j].end;i++)
  112132. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112133. acc*=bands[j].total;
  112134. /* convert amplitude to delta */
  112135. {
  112136. int p,thisx=filters[j].ampptr;
  112137. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112138. p=thisx;
  112139. p--;
  112140. if(p<0)p+=VE_AMP;
  112141. postmax=max(acc,filters[j].ampbuf[p]);
  112142. postmin=min(acc,filters[j].ampbuf[p]);
  112143. for(i=0;i<stretch;i++){
  112144. p--;
  112145. if(p<0)p+=VE_AMP;
  112146. premax=max(premax,filters[j].ampbuf[p]);
  112147. premin=min(premin,filters[j].ampbuf[p]);
  112148. }
  112149. valmin=postmin-premin;
  112150. valmax=postmax-premax;
  112151. /*filters[j].markers[pos]=valmax;*/
  112152. filters[j].ampbuf[thisx]=acc;
  112153. filters[j].ampptr++;
  112154. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112155. }
  112156. /* look at min/max, decide trigger */
  112157. if(valmax>gi->preecho_thresh[j]+penalty){
  112158. ret|=1;
  112159. ret|=4;
  112160. }
  112161. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112162. }
  112163. return(ret);
  112164. }
  112165. #if 0
  112166. static int seq=0;
  112167. static ogg_int64_t totalshift=-1024;
  112168. #endif
  112169. long _ve_envelope_search(vorbis_dsp_state *v){
  112170. vorbis_info *vi=v->vi;
  112171. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112172. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112173. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112174. long i,j;
  112175. int first=ve->current/ve->searchstep;
  112176. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112177. if(first<0)first=0;
  112178. /* make sure we have enough storage to match the PCM */
  112179. if(last+VE_WIN+VE_POST>ve->storage){
  112180. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112181. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112182. }
  112183. for(j=first;j<last;j++){
  112184. int ret=0;
  112185. ve->stretch++;
  112186. if(ve->stretch>VE_MAXSTRETCH*2)
  112187. ve->stretch=VE_MAXSTRETCH*2;
  112188. for(i=0;i<ve->ch;i++){
  112189. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112190. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112191. }
  112192. ve->mark[j+VE_POST]=0;
  112193. if(ret&1){
  112194. ve->mark[j]=1;
  112195. ve->mark[j+1]=1;
  112196. }
  112197. if(ret&2){
  112198. ve->mark[j]=1;
  112199. if(j>0)ve->mark[j-1]=1;
  112200. }
  112201. if(ret&4)ve->stretch=-1;
  112202. }
  112203. ve->current=last*ve->searchstep;
  112204. {
  112205. long centerW=v->centerW;
  112206. long testW=
  112207. centerW+
  112208. ci->blocksizes[v->W]/4+
  112209. ci->blocksizes[1]/2+
  112210. ci->blocksizes[0]/4;
  112211. j=ve->cursor;
  112212. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112213. working back one window */
  112214. if(j>=testW)return(1);
  112215. ve->cursor=j;
  112216. if(ve->mark[j/ve->searchstep]){
  112217. if(j>centerW){
  112218. #if 0
  112219. if(j>ve->curmark){
  112220. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112221. int l,m;
  112222. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112223. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112224. seq,
  112225. (totalshift+ve->cursor)/44100.,
  112226. (totalshift+j)/44100.);
  112227. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112228. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112229. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112230. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112231. for(m=0;m<VE_BANDS;m++){
  112232. char buf[80];
  112233. sprintf(buf,"delL%d",m);
  112234. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112235. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112236. }
  112237. for(m=0;m<VE_BANDS;m++){
  112238. char buf[80];
  112239. sprintf(buf,"delR%d",m);
  112240. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112241. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112242. }
  112243. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112244. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112245. seq++;
  112246. }
  112247. #endif
  112248. ve->curmark=j;
  112249. if(j>=testW)return(1);
  112250. return(0);
  112251. }
  112252. }
  112253. j+=ve->searchstep;
  112254. }
  112255. }
  112256. return(-1);
  112257. }
  112258. int _ve_envelope_mark(vorbis_dsp_state *v){
  112259. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112260. vorbis_info *vi=v->vi;
  112261. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112262. long centerW=v->centerW;
  112263. long beginW=centerW-ci->blocksizes[v->W]/4;
  112264. long endW=centerW+ci->blocksizes[v->W]/4;
  112265. if(v->W){
  112266. beginW-=ci->blocksizes[v->lW]/4;
  112267. endW+=ci->blocksizes[v->nW]/4;
  112268. }else{
  112269. beginW-=ci->blocksizes[0]/4;
  112270. endW+=ci->blocksizes[0]/4;
  112271. }
  112272. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112273. {
  112274. long first=beginW/ve->searchstep;
  112275. long last=endW/ve->searchstep;
  112276. long i;
  112277. for(i=first;i<last;i++)
  112278. if(ve->mark[i])return(1);
  112279. }
  112280. return(0);
  112281. }
  112282. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112283. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112284. ahead of ve->current */
  112285. int smallshift=shift/e->searchstep;
  112286. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112287. #if 0
  112288. for(i=0;i<VE_BANDS*e->ch;i++)
  112289. memmove(e->filter[i].markers,
  112290. e->filter[i].markers+smallshift,
  112291. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112292. totalshift+=shift;
  112293. #endif
  112294. e->current-=shift;
  112295. if(e->curmark>=0)
  112296. e->curmark-=shift;
  112297. e->cursor-=shift;
  112298. }
  112299. #endif
  112300. /*** End of inlined file: envelope.c ***/
  112301. /*** Start of inlined file: floor0.c ***/
  112302. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112303. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112304. // tasks..
  112305. #if JUCE_MSVC
  112306. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112307. #endif
  112308. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112309. #if JUCE_USE_OGGVORBIS
  112310. #include <stdlib.h>
  112311. #include <string.h>
  112312. #include <math.h>
  112313. /*** Start of inlined file: lsp.h ***/
  112314. #ifndef _V_LSP_H_
  112315. #define _V_LSP_H_
  112316. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112317. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112318. float *lsp,int m,
  112319. float amp,float ampoffset);
  112320. #endif
  112321. /*** End of inlined file: lsp.h ***/
  112322. #include <stdio.h>
  112323. typedef struct {
  112324. int ln;
  112325. int m;
  112326. int **linearmap;
  112327. int n[2];
  112328. vorbis_info_floor0 *vi;
  112329. long bits;
  112330. long frames;
  112331. } vorbis_look_floor0;
  112332. /***********************************************/
  112333. static void floor0_free_info(vorbis_info_floor *i){
  112334. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112335. if(info){
  112336. memset(info,0,sizeof(*info));
  112337. _ogg_free(info);
  112338. }
  112339. }
  112340. static void floor0_free_look(vorbis_look_floor *i){
  112341. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112342. if(look){
  112343. if(look->linearmap){
  112344. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112345. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112346. _ogg_free(look->linearmap);
  112347. }
  112348. memset(look,0,sizeof(*look));
  112349. _ogg_free(look);
  112350. }
  112351. }
  112352. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112353. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112354. int j;
  112355. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112356. info->order=oggpack_read(opb,8);
  112357. info->rate=oggpack_read(opb,16);
  112358. info->barkmap=oggpack_read(opb,16);
  112359. info->ampbits=oggpack_read(opb,6);
  112360. info->ampdB=oggpack_read(opb,8);
  112361. info->numbooks=oggpack_read(opb,4)+1;
  112362. if(info->order<1)goto err_out;
  112363. if(info->rate<1)goto err_out;
  112364. if(info->barkmap<1)goto err_out;
  112365. if(info->numbooks<1)goto err_out;
  112366. for(j=0;j<info->numbooks;j++){
  112367. info->books[j]=oggpack_read(opb,8);
  112368. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112369. }
  112370. return(info);
  112371. err_out:
  112372. floor0_free_info(info);
  112373. return(NULL);
  112374. }
  112375. /* initialize Bark scale and normalization lookups. We could do this
  112376. with static tables, but Vorbis allows a number of possible
  112377. combinations, so it's best to do it computationally.
  112378. The below is authoritative in terms of defining scale mapping.
  112379. Note that the scale depends on the sampling rate as well as the
  112380. linear block and mapping sizes */
  112381. static void floor0_map_lazy_init(vorbis_block *vb,
  112382. vorbis_info_floor *infoX,
  112383. vorbis_look_floor0 *look){
  112384. if(!look->linearmap[vb->W]){
  112385. vorbis_dsp_state *vd=vb->vd;
  112386. vorbis_info *vi=vd->vi;
  112387. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112388. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112389. int W=vb->W;
  112390. int n=ci->blocksizes[W]/2,j;
  112391. /* we choose a scaling constant so that:
  112392. floor(bark(rate/2-1)*C)=mapped-1
  112393. floor(bark(rate/2)*C)=mapped */
  112394. float scale=look->ln/toBARK(info->rate/2.f);
  112395. /* the mapping from a linear scale to a smaller bark scale is
  112396. straightforward. We do *not* make sure that the linear mapping
  112397. does not skip bark-scale bins; the decoder simply skips them and
  112398. the encoder may do what it wishes in filling them. They're
  112399. necessary in some mapping combinations to keep the scale spacing
  112400. accurate */
  112401. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112402. for(j=0;j<n;j++){
  112403. int val=floor( toBARK((info->rate/2.f)/n*j)
  112404. *scale); /* bark numbers represent band edges */
  112405. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112406. look->linearmap[W][j]=val;
  112407. }
  112408. look->linearmap[W][j]=-1;
  112409. look->n[W]=n;
  112410. }
  112411. }
  112412. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112413. vorbis_info_floor *i){
  112414. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112415. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112416. look->m=info->order;
  112417. look->ln=info->barkmap;
  112418. look->vi=info;
  112419. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112420. return look;
  112421. }
  112422. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112423. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112424. vorbis_info_floor0 *info=look->vi;
  112425. int j,k;
  112426. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112427. if(ampraw>0){ /* also handles the -1 out of data case */
  112428. long maxval=(1<<info->ampbits)-1;
  112429. float amp=(float)ampraw/maxval*info->ampdB;
  112430. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112431. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112432. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112433. codebook *b=ci->fullbooks+info->books[booknum];
  112434. float last=0.f;
  112435. /* the additional b->dim is a guard against any possible stack
  112436. smash; b->dim is provably more than we can overflow the
  112437. vector */
  112438. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112439. for(j=0;j<look->m;j+=b->dim)
  112440. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112441. for(j=0;j<look->m;){
  112442. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112443. last=lsp[j-1];
  112444. }
  112445. lsp[look->m]=amp;
  112446. return(lsp);
  112447. }
  112448. }
  112449. eop:
  112450. return(NULL);
  112451. }
  112452. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112453. void *memo,float *out){
  112454. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112455. vorbis_info_floor0 *info=look->vi;
  112456. floor0_map_lazy_init(vb,info,look);
  112457. if(memo){
  112458. float *lsp=(float *)memo;
  112459. float amp=lsp[look->m];
  112460. /* take the coefficients back to a spectral envelope curve */
  112461. vorbis_lsp_to_curve(out,
  112462. look->linearmap[vb->W],
  112463. look->n[vb->W],
  112464. look->ln,
  112465. lsp,look->m,amp,(float)info->ampdB);
  112466. return(1);
  112467. }
  112468. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112469. return(0);
  112470. }
  112471. /* export hooks */
  112472. vorbis_func_floor floor0_exportbundle={
  112473. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112474. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112475. };
  112476. #endif
  112477. /*** End of inlined file: floor0.c ***/
  112478. /*** Start of inlined file: floor1.c ***/
  112479. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112480. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112481. // tasks..
  112482. #if JUCE_MSVC
  112483. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112484. #endif
  112485. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112486. #if JUCE_USE_OGGVORBIS
  112487. #include <stdlib.h>
  112488. #include <string.h>
  112489. #include <math.h>
  112490. #include <stdio.h>
  112491. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112492. typedef struct {
  112493. int sorted_index[VIF_POSIT+2];
  112494. int forward_index[VIF_POSIT+2];
  112495. int reverse_index[VIF_POSIT+2];
  112496. int hineighbor[VIF_POSIT];
  112497. int loneighbor[VIF_POSIT];
  112498. int posts;
  112499. int n;
  112500. int quant_q;
  112501. vorbis_info_floor1 *vi;
  112502. long phrasebits;
  112503. long postbits;
  112504. long frames;
  112505. } vorbis_look_floor1;
  112506. typedef struct lsfit_acc{
  112507. long x0;
  112508. long x1;
  112509. long xa;
  112510. long ya;
  112511. long x2a;
  112512. long y2a;
  112513. long xya;
  112514. long an;
  112515. } lsfit_acc;
  112516. /***********************************************/
  112517. static void floor1_free_info(vorbis_info_floor *i){
  112518. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112519. if(info){
  112520. memset(info,0,sizeof(*info));
  112521. _ogg_free(info);
  112522. }
  112523. }
  112524. static void floor1_free_look(vorbis_look_floor *i){
  112525. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  112526. if(look){
  112527. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  112528. (float)look->phrasebits/look->frames,
  112529. (float)look->postbits/look->frames,
  112530. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112531. memset(look,0,sizeof(*look));
  112532. _ogg_free(look);
  112533. }
  112534. }
  112535. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  112536. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112537. int j,k;
  112538. int count=0;
  112539. int rangebits;
  112540. int maxposit=info->postlist[1];
  112541. int maxclass=-1;
  112542. /* save out partitions */
  112543. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  112544. for(j=0;j<info->partitions;j++){
  112545. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  112546. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112547. }
  112548. /* save out partition classes */
  112549. for(j=0;j<maxclass+1;j++){
  112550. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  112551. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  112552. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  112553. for(k=0;k<(1<<info->class_subs[j]);k++)
  112554. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  112555. }
  112556. /* save out the post list */
  112557. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  112558. oggpack_write(opb,ilog2(maxposit),4);
  112559. rangebits=ilog2(maxposit);
  112560. for(j=0,k=0;j<info->partitions;j++){
  112561. count+=info->class_dim[info->partitionclass[j]];
  112562. for(;k<count;k++)
  112563. oggpack_write(opb,info->postlist[k+2],rangebits);
  112564. }
  112565. }
  112566. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112567. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112568. int j,k,count=0,maxclass=-1,rangebits;
  112569. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  112570. /* read partitions */
  112571. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  112572. for(j=0;j<info->partitions;j++){
  112573. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  112574. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112575. }
  112576. /* read partition classes */
  112577. for(j=0;j<maxclass+1;j++){
  112578. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  112579. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  112580. if(info->class_subs[j]<0)
  112581. goto err_out;
  112582. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  112583. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  112584. goto err_out;
  112585. for(k=0;k<(1<<info->class_subs[j]);k++){
  112586. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  112587. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  112588. goto err_out;
  112589. }
  112590. }
  112591. /* read the post list */
  112592. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  112593. rangebits=oggpack_read(opb,4);
  112594. for(j=0,k=0;j<info->partitions;j++){
  112595. count+=info->class_dim[info->partitionclass[j]];
  112596. for(;k<count;k++){
  112597. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  112598. if(t<0 || t>=(1<<rangebits))
  112599. goto err_out;
  112600. }
  112601. }
  112602. info->postlist[0]=0;
  112603. info->postlist[1]=1<<rangebits;
  112604. return(info);
  112605. err_out:
  112606. floor1_free_info(info);
  112607. return(NULL);
  112608. }
  112609. static int JUCE_CDECL icomp(const void *a,const void *b){
  112610. return(**(int **)a-**(int **)b);
  112611. }
  112612. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  112613. vorbis_info_floor *in){
  112614. int *sortpointer[VIF_POSIT+2];
  112615. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  112616. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  112617. int i,j,n=0;
  112618. look->vi=info;
  112619. look->n=info->postlist[1];
  112620. /* we drop each position value in-between already decoded values,
  112621. and use linear interpolation to predict each new value past the
  112622. edges. The positions are read in the order of the position
  112623. list... we precompute the bounding positions in the lookup. Of
  112624. course, the neighbors can change (if a position is declined), but
  112625. this is an initial mapping */
  112626. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  112627. n+=2;
  112628. look->posts=n;
  112629. /* also store a sorted position index */
  112630. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  112631. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  112632. /* points from sort order back to range number */
  112633. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  112634. /* points from range order to sorted position */
  112635. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  112636. /* we actually need the post values too */
  112637. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  112638. /* quantize values to multiplier spec */
  112639. switch(info->mult){
  112640. case 1: /* 1024 -> 256 */
  112641. look->quant_q=256;
  112642. break;
  112643. case 2: /* 1024 -> 128 */
  112644. look->quant_q=128;
  112645. break;
  112646. case 3: /* 1024 -> 86 */
  112647. look->quant_q=86;
  112648. break;
  112649. case 4: /* 1024 -> 64 */
  112650. look->quant_q=64;
  112651. break;
  112652. }
  112653. /* discover our neighbors for decode where we don't use fit flags
  112654. (that would push the neighbors outward) */
  112655. for(i=0;i<n-2;i++){
  112656. int lo=0;
  112657. int hi=1;
  112658. int lx=0;
  112659. int hx=look->n;
  112660. int currentx=info->postlist[i+2];
  112661. for(j=0;j<i+2;j++){
  112662. int x=info->postlist[j];
  112663. if(x>lx && x<currentx){
  112664. lo=j;
  112665. lx=x;
  112666. }
  112667. if(x<hx && x>currentx){
  112668. hi=j;
  112669. hx=x;
  112670. }
  112671. }
  112672. look->loneighbor[i]=lo;
  112673. look->hineighbor[i]=hi;
  112674. }
  112675. return(look);
  112676. }
  112677. static int render_point(int x0,int x1,int y0,int y1,int x){
  112678. y0&=0x7fff; /* mask off flag */
  112679. y1&=0x7fff;
  112680. {
  112681. int dy=y1-y0;
  112682. int adx=x1-x0;
  112683. int ady=abs(dy);
  112684. int err=ady*(x-x0);
  112685. int off=err/adx;
  112686. if(dy<0)return(y0-off);
  112687. return(y0+off);
  112688. }
  112689. }
  112690. static int vorbis_dBquant(const float *x){
  112691. int i= *x*7.3142857f+1023.5f;
  112692. if(i>1023)return(1023);
  112693. if(i<0)return(0);
  112694. return i;
  112695. }
  112696. static float FLOOR1_fromdB_LOOKUP[256]={
  112697. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  112698. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  112699. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  112700. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  112701. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  112702. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  112703. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  112704. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  112705. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  112706. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  112707. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  112708. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  112709. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  112710. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  112711. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  112712. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  112713. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  112714. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  112715. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  112716. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  112717. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  112718. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  112719. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  112720. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  112721. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  112722. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  112723. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  112724. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  112725. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  112726. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  112727. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  112728. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  112729. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  112730. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  112731. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  112732. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  112733. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  112734. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  112735. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  112736. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  112737. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  112738. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  112739. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  112740. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  112741. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  112742. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  112743. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  112744. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  112745. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  112746. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  112747. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  112748. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  112749. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  112750. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  112751. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  112752. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  112753. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  112754. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  112755. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  112756. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  112757. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  112758. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  112759. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  112760. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  112761. };
  112762. static void render_line(int x0,int x1,int y0,int y1,float *d){
  112763. int dy=y1-y0;
  112764. int adx=x1-x0;
  112765. int ady=abs(dy);
  112766. int base=dy/adx;
  112767. int sy=(dy<0?base-1:base+1);
  112768. int x=x0;
  112769. int y=y0;
  112770. int err=0;
  112771. ady-=abs(base*adx);
  112772. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112773. while(++x<x1){
  112774. err=err+ady;
  112775. if(err>=adx){
  112776. err-=adx;
  112777. y+=sy;
  112778. }else{
  112779. y+=base;
  112780. }
  112781. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112782. }
  112783. }
  112784. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  112785. int dy=y1-y0;
  112786. int adx=x1-x0;
  112787. int ady=abs(dy);
  112788. int base=dy/adx;
  112789. int sy=(dy<0?base-1:base+1);
  112790. int x=x0;
  112791. int y=y0;
  112792. int err=0;
  112793. ady-=abs(base*adx);
  112794. d[x]=y;
  112795. while(++x<x1){
  112796. err=err+ady;
  112797. if(err>=adx){
  112798. err-=adx;
  112799. y+=sy;
  112800. }else{
  112801. y+=base;
  112802. }
  112803. d[x]=y;
  112804. }
  112805. }
  112806. /* the floor has already been filtered to only include relevant sections */
  112807. static int accumulate_fit(const float *flr,const float *mdct,
  112808. int x0, int x1,lsfit_acc *a,
  112809. int n,vorbis_info_floor1 *info){
  112810. long i;
  112811. 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;
  112812. memset(a,0,sizeof(*a));
  112813. a->x0=x0;
  112814. a->x1=x1;
  112815. if(x1>=n)x1=n-1;
  112816. for(i=x0;i<=x1;i++){
  112817. int quantized=vorbis_dBquant(flr+i);
  112818. if(quantized){
  112819. if(mdct[i]+info->twofitatten>=flr[i]){
  112820. xa += i;
  112821. ya += quantized;
  112822. x2a += i*i;
  112823. y2a += quantized*quantized;
  112824. xya += i*quantized;
  112825. na++;
  112826. }else{
  112827. xb += i;
  112828. yb += quantized;
  112829. x2b += i*i;
  112830. y2b += quantized*quantized;
  112831. xyb += i*quantized;
  112832. nb++;
  112833. }
  112834. }
  112835. }
  112836. xb+=xa;
  112837. yb+=ya;
  112838. x2b+=x2a;
  112839. y2b+=y2a;
  112840. xyb+=xya;
  112841. nb+=na;
  112842. /* weight toward the actually used frequencies if we meet the threshhold */
  112843. {
  112844. int weight=nb*info->twofitweight/(na+1);
  112845. a->xa=xa*weight+xb;
  112846. a->ya=ya*weight+yb;
  112847. a->x2a=x2a*weight+x2b;
  112848. a->y2a=y2a*weight+y2b;
  112849. a->xya=xya*weight+xyb;
  112850. a->an=na*weight+nb;
  112851. }
  112852. return(na);
  112853. }
  112854. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  112855. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  112856. long x0=a[0].x0;
  112857. long x1=a[fits-1].x1;
  112858. for(i=0;i<fits;i++){
  112859. x+=a[i].xa;
  112860. y+=a[i].ya;
  112861. x2+=a[i].x2a;
  112862. y2+=a[i].y2a;
  112863. xy+=a[i].xya;
  112864. an+=a[i].an;
  112865. }
  112866. if(*y0>=0){
  112867. x+= x0;
  112868. y+= *y0;
  112869. x2+= x0 * x0;
  112870. y2+= *y0 * *y0;
  112871. xy+= *y0 * x0;
  112872. an++;
  112873. }
  112874. if(*y1>=0){
  112875. x+= x1;
  112876. y+= *y1;
  112877. x2+= x1 * x1;
  112878. y2+= *y1 * *y1;
  112879. xy+= *y1 * x1;
  112880. an++;
  112881. }
  112882. if(an){
  112883. /* need 64 bit multiplies, which C doesn't give portably as int */
  112884. double fx=x;
  112885. double fy=y;
  112886. double fx2=x2;
  112887. double fxy=xy;
  112888. double denom=1./(an*fx2-fx*fx);
  112889. double a=(fy*fx2-fxy*fx)*denom;
  112890. double b=(an*fxy-fx*fy)*denom;
  112891. *y0=rint(a+b*x0);
  112892. *y1=rint(a+b*x1);
  112893. /* limit to our range! */
  112894. if(*y0>1023)*y0=1023;
  112895. if(*y1>1023)*y1=1023;
  112896. if(*y0<0)*y0=0;
  112897. if(*y1<0)*y1=0;
  112898. }else{
  112899. *y0=0;
  112900. *y1=0;
  112901. }
  112902. }
  112903. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  112904. long y=0;
  112905. int i;
  112906. for(i=0;i<fits && y==0;i++)
  112907. y+=a[i].ya;
  112908. *y0=*y1=y;
  112909. }*/
  112910. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  112911. const float *mdct,
  112912. vorbis_info_floor1 *info){
  112913. int dy=y1-y0;
  112914. int adx=x1-x0;
  112915. int ady=abs(dy);
  112916. int base=dy/adx;
  112917. int sy=(dy<0?base-1:base+1);
  112918. int x=x0;
  112919. int y=y0;
  112920. int err=0;
  112921. int val=vorbis_dBquant(mask+x);
  112922. int mse=0;
  112923. int n=0;
  112924. ady-=abs(base*adx);
  112925. mse=(y-val);
  112926. mse*=mse;
  112927. n++;
  112928. if(mdct[x]+info->twofitatten>=mask[x]){
  112929. if(y+info->maxover<val)return(1);
  112930. if(y-info->maxunder>val)return(1);
  112931. }
  112932. while(++x<x1){
  112933. err=err+ady;
  112934. if(err>=adx){
  112935. err-=adx;
  112936. y+=sy;
  112937. }else{
  112938. y+=base;
  112939. }
  112940. val=vorbis_dBquant(mask+x);
  112941. mse+=((y-val)*(y-val));
  112942. n++;
  112943. if(mdct[x]+info->twofitatten>=mask[x]){
  112944. if(val){
  112945. if(y+info->maxover<val)return(1);
  112946. if(y-info->maxunder>val)return(1);
  112947. }
  112948. }
  112949. }
  112950. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  112951. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  112952. if(mse/n>info->maxerr)return(1);
  112953. return(0);
  112954. }
  112955. static int post_Y(int *A,int *B,int pos){
  112956. if(A[pos]<0)
  112957. return B[pos];
  112958. if(B[pos]<0)
  112959. return A[pos];
  112960. return (A[pos]+B[pos])>>1;
  112961. }
  112962. int *floor1_fit(vorbis_block *vb,void *look_,
  112963. const float *logmdct, /* in */
  112964. const float *logmask){
  112965. long i,j;
  112966. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  112967. vorbis_info_floor1 *info=look->vi;
  112968. long n=look->n;
  112969. long posts=look->posts;
  112970. long nonzero=0;
  112971. lsfit_acc fits[VIF_POSIT+1];
  112972. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  112973. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  112974. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  112975. int hineighbor[VIF_POSIT+2];
  112976. int *output=NULL;
  112977. int memo[VIF_POSIT+2];
  112978. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  112979. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  112980. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  112981. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  112982. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  112983. /* quantize the relevant floor points and collect them into line fit
  112984. structures (one per minimal division) at the same time */
  112985. if(posts==0){
  112986. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  112987. }else{
  112988. for(i=0;i<posts-1;i++)
  112989. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  112990. look->sorted_index[i+1],fits+i,
  112991. n,info);
  112992. }
  112993. if(nonzero){
  112994. /* start by fitting the implicit base case.... */
  112995. int y0=-200;
  112996. int y1=-200;
  112997. fit_line(fits,posts-1,&y0,&y1);
  112998. fit_valueA[0]=y0;
  112999. fit_valueB[0]=y0;
  113000. fit_valueB[1]=y1;
  113001. fit_valueA[1]=y1;
  113002. /* Non degenerate case */
  113003. /* start progressive splitting. This is a greedy, non-optimal
  113004. algorithm, but simple and close enough to the best
  113005. answer. */
  113006. for(i=2;i<posts;i++){
  113007. int sortpos=look->reverse_index[i];
  113008. int ln=loneighbor[sortpos];
  113009. int hn=hineighbor[sortpos];
  113010. /* eliminate repeat searches of a particular range with a memo */
  113011. if(memo[ln]!=hn){
  113012. /* haven't performed this error search yet */
  113013. int lsortpos=look->reverse_index[ln];
  113014. int hsortpos=look->reverse_index[hn];
  113015. memo[ln]=hn;
  113016. {
  113017. /* A note: we want to bound/minimize *local*, not global, error */
  113018. int lx=info->postlist[ln];
  113019. int hx=info->postlist[hn];
  113020. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113021. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113022. if(ly==-1 || hy==-1){
  113023. exit(1);
  113024. }
  113025. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113026. /* outside error bounds/begin search area. Split it. */
  113027. int ly0=-200;
  113028. int ly1=-200;
  113029. int hy0=-200;
  113030. int hy1=-200;
  113031. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113032. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113033. /* store new edge values */
  113034. fit_valueB[ln]=ly0;
  113035. if(ln==0)fit_valueA[ln]=ly0;
  113036. fit_valueA[i]=ly1;
  113037. fit_valueB[i]=hy0;
  113038. fit_valueA[hn]=hy1;
  113039. if(hn==1)fit_valueB[hn]=hy1;
  113040. if(ly1>=0 || hy0>=0){
  113041. /* store new neighbor values */
  113042. for(j=sortpos-1;j>=0;j--)
  113043. if(hineighbor[j]==hn)
  113044. hineighbor[j]=i;
  113045. else
  113046. break;
  113047. for(j=sortpos+1;j<posts;j++)
  113048. if(loneighbor[j]==ln)
  113049. loneighbor[j]=i;
  113050. else
  113051. break;
  113052. }
  113053. }else{
  113054. fit_valueA[i]=-200;
  113055. fit_valueB[i]=-200;
  113056. }
  113057. }
  113058. }
  113059. }
  113060. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113061. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113062. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113063. /* fill in posts marked as not using a fit; we will zero
  113064. back out to 'unused' when encoding them so long as curve
  113065. interpolation doesn't force them into use */
  113066. for(i=2;i<posts;i++){
  113067. int ln=look->loneighbor[i-2];
  113068. int hn=look->hineighbor[i-2];
  113069. int x0=info->postlist[ln];
  113070. int x1=info->postlist[hn];
  113071. int y0=output[ln];
  113072. int y1=output[hn];
  113073. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113074. int vx=post_Y(fit_valueA,fit_valueB,i);
  113075. if(vx>=0 && predicted!=vx){
  113076. output[i]=vx;
  113077. }else{
  113078. output[i]= predicted|0x8000;
  113079. }
  113080. }
  113081. }
  113082. return(output);
  113083. }
  113084. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113085. int *A,int *B,
  113086. int del){
  113087. long i;
  113088. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113089. long posts=look->posts;
  113090. int *output=NULL;
  113091. if(A && B){
  113092. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113093. for(i=0;i<posts;i++){
  113094. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113095. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113096. }
  113097. }
  113098. return(output);
  113099. }
  113100. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113101. void*look_,
  113102. int *post,int *ilogmask){
  113103. long i,j;
  113104. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113105. vorbis_info_floor1 *info=look->vi;
  113106. long posts=look->posts;
  113107. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113108. int out[VIF_POSIT+2];
  113109. static_codebook **sbooks=ci->book_param;
  113110. codebook *books=ci->fullbooks;
  113111. static long seq=0;
  113112. /* quantize values to multiplier spec */
  113113. if(post){
  113114. for(i=0;i<posts;i++){
  113115. int val=post[i]&0x7fff;
  113116. switch(info->mult){
  113117. case 1: /* 1024 -> 256 */
  113118. val>>=2;
  113119. break;
  113120. case 2: /* 1024 -> 128 */
  113121. val>>=3;
  113122. break;
  113123. case 3: /* 1024 -> 86 */
  113124. val/=12;
  113125. break;
  113126. case 4: /* 1024 -> 64 */
  113127. val>>=4;
  113128. break;
  113129. }
  113130. post[i]=val | (post[i]&0x8000);
  113131. }
  113132. out[0]=post[0];
  113133. out[1]=post[1];
  113134. /* find prediction values for each post and subtract them */
  113135. for(i=2;i<posts;i++){
  113136. int ln=look->loneighbor[i-2];
  113137. int hn=look->hineighbor[i-2];
  113138. int x0=info->postlist[ln];
  113139. int x1=info->postlist[hn];
  113140. int y0=post[ln];
  113141. int y1=post[hn];
  113142. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113143. if((post[i]&0x8000) || (predicted==post[i])){
  113144. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113145. in interpolation */
  113146. out[i]=0;
  113147. }else{
  113148. int headroom=(look->quant_q-predicted<predicted?
  113149. look->quant_q-predicted:predicted);
  113150. int val=post[i]-predicted;
  113151. /* at this point the 'deviation' value is in the range +/- max
  113152. range, but the real, unique range can always be mapped to
  113153. only [0-maxrange). So we want to wrap the deviation into
  113154. this limited range, but do it in the way that least screws
  113155. an essentially gaussian probability distribution. */
  113156. if(val<0)
  113157. if(val<-headroom)
  113158. val=headroom-val-1;
  113159. else
  113160. val=-1-(val<<1);
  113161. else
  113162. if(val>=headroom)
  113163. val= val+headroom;
  113164. else
  113165. val<<=1;
  113166. out[i]=val;
  113167. post[ln]&=0x7fff;
  113168. post[hn]&=0x7fff;
  113169. }
  113170. }
  113171. /* we have everything we need. pack it out */
  113172. /* mark nontrivial floor */
  113173. oggpack_write(opb,1,1);
  113174. /* beginning/end post */
  113175. look->frames++;
  113176. look->postbits+=ilog(look->quant_q-1)*2;
  113177. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113178. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113179. /* partition by partition */
  113180. for(i=0,j=2;i<info->partitions;i++){
  113181. int classx=info->partitionclass[i];
  113182. int cdim=info->class_dim[classx];
  113183. int csubbits=info->class_subs[classx];
  113184. int csub=1<<csubbits;
  113185. int bookas[8]={0,0,0,0,0,0,0,0};
  113186. int cval=0;
  113187. int cshift=0;
  113188. int k,l;
  113189. /* generate the partition's first stage cascade value */
  113190. if(csubbits){
  113191. int maxval[8];
  113192. for(k=0;k<csub;k++){
  113193. int booknum=info->class_subbook[classx][k];
  113194. if(booknum<0){
  113195. maxval[k]=1;
  113196. }else{
  113197. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113198. }
  113199. }
  113200. for(k=0;k<cdim;k++){
  113201. for(l=0;l<csub;l++){
  113202. int val=out[j+k];
  113203. if(val<maxval[l]){
  113204. bookas[k]=l;
  113205. break;
  113206. }
  113207. }
  113208. cval|= bookas[k]<<cshift;
  113209. cshift+=csubbits;
  113210. }
  113211. /* write it */
  113212. look->phrasebits+=
  113213. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113214. #ifdef TRAIN_FLOOR1
  113215. {
  113216. FILE *of;
  113217. char buffer[80];
  113218. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113219. vb->pcmend/2,posts-2,class);
  113220. of=fopen(buffer,"a");
  113221. fprintf(of,"%d\n",cval);
  113222. fclose(of);
  113223. }
  113224. #endif
  113225. }
  113226. /* write post values */
  113227. for(k=0;k<cdim;k++){
  113228. int book=info->class_subbook[classx][bookas[k]];
  113229. if(book>=0){
  113230. /* hack to allow training with 'bad' books */
  113231. if(out[j+k]<(books+book)->entries)
  113232. look->postbits+=vorbis_book_encode(books+book,
  113233. out[j+k],opb);
  113234. /*else
  113235. fprintf(stderr,"+!");*/
  113236. #ifdef TRAIN_FLOOR1
  113237. {
  113238. FILE *of;
  113239. char buffer[80];
  113240. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113241. vb->pcmend/2,posts-2,class,bookas[k]);
  113242. of=fopen(buffer,"a");
  113243. fprintf(of,"%d\n",out[j+k]);
  113244. fclose(of);
  113245. }
  113246. #endif
  113247. }
  113248. }
  113249. j+=cdim;
  113250. }
  113251. {
  113252. /* generate quantized floor equivalent to what we'd unpack in decode */
  113253. /* render the lines */
  113254. int hx=0;
  113255. int lx=0;
  113256. int ly=post[0]*info->mult;
  113257. for(j=1;j<look->posts;j++){
  113258. int current=look->forward_index[j];
  113259. int hy=post[current]&0x7fff;
  113260. if(hy==post[current]){
  113261. hy*=info->mult;
  113262. hx=info->postlist[current];
  113263. render_line0(lx,hx,ly,hy,ilogmask);
  113264. lx=hx;
  113265. ly=hy;
  113266. }
  113267. }
  113268. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113269. seq++;
  113270. return(1);
  113271. }
  113272. }else{
  113273. oggpack_write(opb,0,1);
  113274. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113275. seq++;
  113276. return(0);
  113277. }
  113278. }
  113279. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113280. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113281. vorbis_info_floor1 *info=look->vi;
  113282. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113283. int i,j,k;
  113284. codebook *books=ci->fullbooks;
  113285. /* unpack wrapped/predicted values from stream */
  113286. if(oggpack_read(&vb->opb,1)==1){
  113287. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113288. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113289. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113290. /* partition by partition */
  113291. for(i=0,j=2;i<info->partitions;i++){
  113292. int classx=info->partitionclass[i];
  113293. int cdim=info->class_dim[classx];
  113294. int csubbits=info->class_subs[classx];
  113295. int csub=1<<csubbits;
  113296. int cval=0;
  113297. /* decode the partition's first stage cascade value */
  113298. if(csubbits){
  113299. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113300. if(cval==-1)goto eop;
  113301. }
  113302. for(k=0;k<cdim;k++){
  113303. int book=info->class_subbook[classx][cval&(csub-1)];
  113304. cval>>=csubbits;
  113305. if(book>=0){
  113306. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113307. goto eop;
  113308. }else{
  113309. fit_value[j+k]=0;
  113310. }
  113311. }
  113312. j+=cdim;
  113313. }
  113314. /* unwrap positive values and reconsitute via linear interpolation */
  113315. for(i=2;i<look->posts;i++){
  113316. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113317. info->postlist[look->hineighbor[i-2]],
  113318. fit_value[look->loneighbor[i-2]],
  113319. fit_value[look->hineighbor[i-2]],
  113320. info->postlist[i]);
  113321. int hiroom=look->quant_q-predicted;
  113322. int loroom=predicted;
  113323. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113324. int val=fit_value[i];
  113325. if(val){
  113326. if(val>=room){
  113327. if(hiroom>loroom){
  113328. val = val-loroom;
  113329. }else{
  113330. val = -1-(val-hiroom);
  113331. }
  113332. }else{
  113333. if(val&1){
  113334. val= -((val+1)>>1);
  113335. }else{
  113336. val>>=1;
  113337. }
  113338. }
  113339. fit_value[i]=val+predicted;
  113340. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113341. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113342. }else{
  113343. fit_value[i]=predicted|0x8000;
  113344. }
  113345. }
  113346. return(fit_value);
  113347. }
  113348. eop:
  113349. return(NULL);
  113350. }
  113351. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113352. float *out){
  113353. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113354. vorbis_info_floor1 *info=look->vi;
  113355. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113356. int n=ci->blocksizes[vb->W]/2;
  113357. int j;
  113358. if(memo){
  113359. /* render the lines */
  113360. int *fit_value=(int *)memo;
  113361. int hx=0;
  113362. int lx=0;
  113363. int ly=fit_value[0]*info->mult;
  113364. for(j=1;j<look->posts;j++){
  113365. int current=look->forward_index[j];
  113366. int hy=fit_value[current]&0x7fff;
  113367. if(hy==fit_value[current]){
  113368. hy*=info->mult;
  113369. hx=info->postlist[current];
  113370. render_line(lx,hx,ly,hy,out);
  113371. lx=hx;
  113372. ly=hy;
  113373. }
  113374. }
  113375. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113376. return(1);
  113377. }
  113378. memset(out,0,sizeof(*out)*n);
  113379. return(0);
  113380. }
  113381. /* export hooks */
  113382. vorbis_func_floor floor1_exportbundle={
  113383. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113384. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113385. };
  113386. #endif
  113387. /*** End of inlined file: floor1.c ***/
  113388. /*** Start of inlined file: info.c ***/
  113389. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113390. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113391. // tasks..
  113392. #if JUCE_MSVC
  113393. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113394. #endif
  113395. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113396. #if JUCE_USE_OGGVORBIS
  113397. /* general handling of the header and the vorbis_info structure (and
  113398. substructures) */
  113399. #include <stdlib.h>
  113400. #include <string.h>
  113401. #include <ctype.h>
  113402. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113403. while(bytes--){
  113404. oggpack_write(o,*s++,8);
  113405. }
  113406. }
  113407. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113408. while(bytes--){
  113409. *buf++=oggpack_read(o,8);
  113410. }
  113411. }
  113412. void vorbis_comment_init(vorbis_comment *vc){
  113413. memset(vc,0,sizeof(*vc));
  113414. }
  113415. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113416. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113417. (vc->comments+2)*sizeof(*vc->user_comments));
  113418. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113419. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113420. vc->comment_lengths[vc->comments]=strlen(comment);
  113421. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113422. strcpy(vc->user_comments[vc->comments], comment);
  113423. vc->comments++;
  113424. vc->user_comments[vc->comments]=NULL;
  113425. }
  113426. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113427. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113428. strcpy(comment, tag);
  113429. strcat(comment, "=");
  113430. strcat(comment, contents);
  113431. vorbis_comment_add(vc, comment);
  113432. }
  113433. /* This is more or less the same as strncasecmp - but that doesn't exist
  113434. * everywhere, and this is a fairly trivial function, so we include it */
  113435. static int tagcompare(const char *s1, const char *s2, int n){
  113436. int c=0;
  113437. while(c < n){
  113438. if(toupper(s1[c]) != toupper(s2[c]))
  113439. return !0;
  113440. c++;
  113441. }
  113442. return 0;
  113443. }
  113444. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113445. long i;
  113446. int found = 0;
  113447. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113448. char *fulltag = (char*)alloca(taglen+ 1);
  113449. strcpy(fulltag, tag);
  113450. strcat(fulltag, "=");
  113451. for(i=0;i<vc->comments;i++){
  113452. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113453. if(count == found)
  113454. /* We return a pointer to the data, not a copy */
  113455. return vc->user_comments[i] + taglen;
  113456. else
  113457. found++;
  113458. }
  113459. }
  113460. return NULL; /* didn't find anything */
  113461. }
  113462. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113463. int i,count=0;
  113464. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113465. char *fulltag = (char*)alloca(taglen+1);
  113466. strcpy(fulltag,tag);
  113467. strcat(fulltag, "=");
  113468. for(i=0;i<vc->comments;i++){
  113469. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113470. count++;
  113471. }
  113472. return count;
  113473. }
  113474. void vorbis_comment_clear(vorbis_comment *vc){
  113475. if(vc){
  113476. long i;
  113477. for(i=0;i<vc->comments;i++)
  113478. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113479. if(vc->user_comments)_ogg_free(vc->user_comments);
  113480. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113481. if(vc->vendor)_ogg_free(vc->vendor);
  113482. }
  113483. memset(vc,0,sizeof(*vc));
  113484. }
  113485. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113486. They may be equal, but short will never ge greater than long */
  113487. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113488. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113489. return ci ? ci->blocksizes[zo] : -1;
  113490. }
  113491. /* used by synthesis, which has a full, alloced vi */
  113492. void vorbis_info_init(vorbis_info *vi){
  113493. memset(vi,0,sizeof(*vi));
  113494. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  113495. }
  113496. void vorbis_info_clear(vorbis_info *vi){
  113497. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113498. int i;
  113499. if(ci){
  113500. for(i=0;i<ci->modes;i++)
  113501. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  113502. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  113503. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  113504. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  113505. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  113506. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  113507. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  113508. for(i=0;i<ci->books;i++){
  113509. if(ci->book_param[i]){
  113510. /* knows if the book was not alloced */
  113511. vorbis_staticbook_destroy(ci->book_param[i]);
  113512. }
  113513. if(ci->fullbooks)
  113514. vorbis_book_clear(ci->fullbooks+i);
  113515. }
  113516. if(ci->fullbooks)
  113517. _ogg_free(ci->fullbooks);
  113518. for(i=0;i<ci->psys;i++)
  113519. _vi_psy_free(ci->psy_param[i]);
  113520. _ogg_free(ci);
  113521. }
  113522. memset(vi,0,sizeof(*vi));
  113523. }
  113524. /* Header packing/unpacking ********************************************/
  113525. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  113526. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113527. if(!ci)return(OV_EFAULT);
  113528. vi->version=oggpack_read(opb,32);
  113529. if(vi->version!=0)return(OV_EVERSION);
  113530. vi->channels=oggpack_read(opb,8);
  113531. vi->rate=oggpack_read(opb,32);
  113532. vi->bitrate_upper=oggpack_read(opb,32);
  113533. vi->bitrate_nominal=oggpack_read(opb,32);
  113534. vi->bitrate_lower=oggpack_read(opb,32);
  113535. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  113536. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  113537. if(vi->rate<1)goto err_out;
  113538. if(vi->channels<1)goto err_out;
  113539. if(ci->blocksizes[0]<8)goto err_out;
  113540. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  113541. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113542. return(0);
  113543. err_out:
  113544. vorbis_info_clear(vi);
  113545. return(OV_EBADHEADER);
  113546. }
  113547. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  113548. int i;
  113549. int vendorlen=oggpack_read(opb,32);
  113550. if(vendorlen<0)goto err_out;
  113551. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  113552. _v_readstring(opb,vc->vendor,vendorlen);
  113553. vc->comments=oggpack_read(opb,32);
  113554. if(vc->comments<0)goto err_out;
  113555. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  113556. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  113557. for(i=0;i<vc->comments;i++){
  113558. int len=oggpack_read(opb,32);
  113559. if(len<0)goto err_out;
  113560. vc->comment_lengths[i]=len;
  113561. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  113562. _v_readstring(opb,vc->user_comments[i],len);
  113563. }
  113564. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113565. return(0);
  113566. err_out:
  113567. vorbis_comment_clear(vc);
  113568. return(OV_EBADHEADER);
  113569. }
  113570. /* all of the real encoding details are here. The modes, books,
  113571. everything */
  113572. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  113573. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113574. int i;
  113575. if(!ci)return(OV_EFAULT);
  113576. /* codebooks */
  113577. ci->books=oggpack_read(opb,8)+1;
  113578. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  113579. for(i=0;i<ci->books;i++){
  113580. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  113581. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  113582. }
  113583. /* time backend settings; hooks are unused */
  113584. {
  113585. int times=oggpack_read(opb,6)+1;
  113586. for(i=0;i<times;i++){
  113587. int test=oggpack_read(opb,16);
  113588. if(test<0 || test>=VI_TIMEB)goto err_out;
  113589. }
  113590. }
  113591. /* floor backend settings */
  113592. ci->floors=oggpack_read(opb,6)+1;
  113593. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  113594. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  113595. for(i=0;i<ci->floors;i++){
  113596. ci->floor_type[i]=oggpack_read(opb,16);
  113597. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  113598. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  113599. if(!ci->floor_param[i])goto err_out;
  113600. }
  113601. /* residue backend settings */
  113602. ci->residues=oggpack_read(opb,6)+1;
  113603. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  113604. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  113605. for(i=0;i<ci->residues;i++){
  113606. ci->residue_type[i]=oggpack_read(opb,16);
  113607. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  113608. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  113609. if(!ci->residue_param[i])goto err_out;
  113610. }
  113611. /* map backend settings */
  113612. ci->maps=oggpack_read(opb,6)+1;
  113613. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  113614. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  113615. for(i=0;i<ci->maps;i++){
  113616. ci->map_type[i]=oggpack_read(opb,16);
  113617. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  113618. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  113619. if(!ci->map_param[i])goto err_out;
  113620. }
  113621. /* mode settings */
  113622. ci->modes=oggpack_read(opb,6)+1;
  113623. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  113624. for(i=0;i<ci->modes;i++){
  113625. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  113626. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  113627. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  113628. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  113629. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  113630. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  113631. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  113632. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  113633. }
  113634. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  113635. return(0);
  113636. err_out:
  113637. vorbis_info_clear(vi);
  113638. return(OV_EBADHEADER);
  113639. }
  113640. /* The Vorbis header is in three packets; the initial small packet in
  113641. the first page that identifies basic parameters, a second packet
  113642. with bitstream comments and a third packet that holds the
  113643. codebook. */
  113644. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  113645. oggpack_buffer opb;
  113646. if(op){
  113647. oggpack_readinit(&opb,op->packet,op->bytes);
  113648. /* Which of the three types of header is this? */
  113649. /* Also verify header-ness, vorbis */
  113650. {
  113651. char buffer[6];
  113652. int packtype=oggpack_read(&opb,8);
  113653. memset(buffer,0,6);
  113654. _v_readstring(&opb,buffer,6);
  113655. if(memcmp(buffer,"vorbis",6)){
  113656. /* not a vorbis header */
  113657. return(OV_ENOTVORBIS);
  113658. }
  113659. switch(packtype){
  113660. case 0x01: /* least significant *bit* is read first */
  113661. if(!op->b_o_s){
  113662. /* Not the initial packet */
  113663. return(OV_EBADHEADER);
  113664. }
  113665. if(vi->rate!=0){
  113666. /* previously initialized info header */
  113667. return(OV_EBADHEADER);
  113668. }
  113669. return(_vorbis_unpack_info(vi,&opb));
  113670. case 0x03: /* least significant *bit* is read first */
  113671. if(vi->rate==0){
  113672. /* um... we didn't get the initial header */
  113673. return(OV_EBADHEADER);
  113674. }
  113675. return(_vorbis_unpack_comment(vc,&opb));
  113676. case 0x05: /* least significant *bit* is read first */
  113677. if(vi->rate==0 || vc->vendor==NULL){
  113678. /* um... we didn;t get the initial header or comments yet */
  113679. return(OV_EBADHEADER);
  113680. }
  113681. return(_vorbis_unpack_books(vi,&opb));
  113682. default:
  113683. /* Not a valid vorbis header type */
  113684. return(OV_EBADHEADER);
  113685. break;
  113686. }
  113687. }
  113688. }
  113689. return(OV_EBADHEADER);
  113690. }
  113691. /* pack side **********************************************************/
  113692. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  113693. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113694. if(!ci)return(OV_EFAULT);
  113695. /* preamble */
  113696. oggpack_write(opb,0x01,8);
  113697. _v_writestring(opb,"vorbis", 6);
  113698. /* basic information about the stream */
  113699. oggpack_write(opb,0x00,32);
  113700. oggpack_write(opb,vi->channels,8);
  113701. oggpack_write(opb,vi->rate,32);
  113702. oggpack_write(opb,vi->bitrate_upper,32);
  113703. oggpack_write(opb,vi->bitrate_nominal,32);
  113704. oggpack_write(opb,vi->bitrate_lower,32);
  113705. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  113706. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  113707. oggpack_write(opb,1,1);
  113708. return(0);
  113709. }
  113710. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  113711. char temp[]="Xiph.Org libVorbis I 20050304";
  113712. int bytes = strlen(temp);
  113713. /* preamble */
  113714. oggpack_write(opb,0x03,8);
  113715. _v_writestring(opb,"vorbis", 6);
  113716. /* vendor */
  113717. oggpack_write(opb,bytes,32);
  113718. _v_writestring(opb,temp, bytes);
  113719. /* comments */
  113720. oggpack_write(opb,vc->comments,32);
  113721. if(vc->comments){
  113722. int i;
  113723. for(i=0;i<vc->comments;i++){
  113724. if(vc->user_comments[i]){
  113725. oggpack_write(opb,vc->comment_lengths[i],32);
  113726. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  113727. }else{
  113728. oggpack_write(opb,0,32);
  113729. }
  113730. }
  113731. }
  113732. oggpack_write(opb,1,1);
  113733. return(0);
  113734. }
  113735. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  113736. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113737. int i;
  113738. if(!ci)return(OV_EFAULT);
  113739. oggpack_write(opb,0x05,8);
  113740. _v_writestring(opb,"vorbis", 6);
  113741. /* books */
  113742. oggpack_write(opb,ci->books-1,8);
  113743. for(i=0;i<ci->books;i++)
  113744. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  113745. /* times; hook placeholders */
  113746. oggpack_write(opb,0,6);
  113747. oggpack_write(opb,0,16);
  113748. /* floors */
  113749. oggpack_write(opb,ci->floors-1,6);
  113750. for(i=0;i<ci->floors;i++){
  113751. oggpack_write(opb,ci->floor_type[i],16);
  113752. if(_floor_P[ci->floor_type[i]]->pack)
  113753. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  113754. else
  113755. goto err_out;
  113756. }
  113757. /* residues */
  113758. oggpack_write(opb,ci->residues-1,6);
  113759. for(i=0;i<ci->residues;i++){
  113760. oggpack_write(opb,ci->residue_type[i],16);
  113761. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  113762. }
  113763. /* maps */
  113764. oggpack_write(opb,ci->maps-1,6);
  113765. for(i=0;i<ci->maps;i++){
  113766. oggpack_write(opb,ci->map_type[i],16);
  113767. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  113768. }
  113769. /* modes */
  113770. oggpack_write(opb,ci->modes-1,6);
  113771. for(i=0;i<ci->modes;i++){
  113772. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  113773. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  113774. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  113775. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  113776. }
  113777. oggpack_write(opb,1,1);
  113778. return(0);
  113779. err_out:
  113780. return(-1);
  113781. }
  113782. int vorbis_commentheader_out(vorbis_comment *vc,
  113783. ogg_packet *op){
  113784. oggpack_buffer opb;
  113785. oggpack_writeinit(&opb);
  113786. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  113787. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113788. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  113789. op->bytes=oggpack_bytes(&opb);
  113790. op->b_o_s=0;
  113791. op->e_o_s=0;
  113792. op->granulepos=0;
  113793. op->packetno=1;
  113794. return 0;
  113795. }
  113796. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  113797. vorbis_comment *vc,
  113798. ogg_packet *op,
  113799. ogg_packet *op_comm,
  113800. ogg_packet *op_code){
  113801. int ret=OV_EIMPL;
  113802. vorbis_info *vi=v->vi;
  113803. oggpack_buffer opb;
  113804. private_state *b=(private_state*)v->backend_state;
  113805. if(!b){
  113806. ret=OV_EFAULT;
  113807. goto err_out;
  113808. }
  113809. /* first header packet **********************************************/
  113810. oggpack_writeinit(&opb);
  113811. if(_vorbis_pack_info(&opb,vi))goto err_out;
  113812. /* build the packet */
  113813. if(b->header)_ogg_free(b->header);
  113814. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113815. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  113816. op->packet=b->header;
  113817. op->bytes=oggpack_bytes(&opb);
  113818. op->b_o_s=1;
  113819. op->e_o_s=0;
  113820. op->granulepos=0;
  113821. op->packetno=0;
  113822. /* second header packet (comments) **********************************/
  113823. oggpack_reset(&opb);
  113824. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  113825. if(b->header1)_ogg_free(b->header1);
  113826. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113827. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  113828. op_comm->packet=b->header1;
  113829. op_comm->bytes=oggpack_bytes(&opb);
  113830. op_comm->b_o_s=0;
  113831. op_comm->e_o_s=0;
  113832. op_comm->granulepos=0;
  113833. op_comm->packetno=1;
  113834. /* third header packet (modes/codebooks) ****************************/
  113835. oggpack_reset(&opb);
  113836. if(_vorbis_pack_books(&opb,vi))goto err_out;
  113837. if(b->header2)_ogg_free(b->header2);
  113838. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113839. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  113840. op_code->packet=b->header2;
  113841. op_code->bytes=oggpack_bytes(&opb);
  113842. op_code->b_o_s=0;
  113843. op_code->e_o_s=0;
  113844. op_code->granulepos=0;
  113845. op_code->packetno=2;
  113846. oggpack_writeclear(&opb);
  113847. return(0);
  113848. err_out:
  113849. oggpack_writeclear(&opb);
  113850. memset(op,0,sizeof(*op));
  113851. memset(op_comm,0,sizeof(*op_comm));
  113852. memset(op_code,0,sizeof(*op_code));
  113853. if(b->header)_ogg_free(b->header);
  113854. if(b->header1)_ogg_free(b->header1);
  113855. if(b->header2)_ogg_free(b->header2);
  113856. b->header=NULL;
  113857. b->header1=NULL;
  113858. b->header2=NULL;
  113859. return(ret);
  113860. }
  113861. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  113862. if(granulepos>=0)
  113863. return((double)granulepos/v->vi->rate);
  113864. return(-1);
  113865. }
  113866. #endif
  113867. /*** End of inlined file: info.c ***/
  113868. /*** Start of inlined file: lpc.c ***/
  113869. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  113870. are derived from code written by Jutta Degener and Carsten Bormann;
  113871. thus we include their copyright below. The entirety of this file
  113872. is freely redistributable on the condition that both of these
  113873. copyright notices are preserved without modification. */
  113874. /* Preserved Copyright: *********************************************/
  113875. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  113876. Technische Universita"t Berlin
  113877. Any use of this software is permitted provided that this notice is not
  113878. removed and that neither the authors nor the Technische Universita"t
  113879. Berlin are deemed to have made any representations as to the
  113880. suitability of this software for any purpose nor are held responsible
  113881. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  113882. THIS SOFTWARE.
  113883. As a matter of courtesy, the authors request to be informed about uses
  113884. this software has found, about bugs in this software, and about any
  113885. improvements that may be of general interest.
  113886. Berlin, 28.11.1994
  113887. Jutta Degener
  113888. Carsten Bormann
  113889. *********************************************************************/
  113890. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113891. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113892. // tasks..
  113893. #if JUCE_MSVC
  113894. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113895. #endif
  113896. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113897. #if JUCE_USE_OGGVORBIS
  113898. #include <stdlib.h>
  113899. #include <string.h>
  113900. #include <math.h>
  113901. /* Autocorrelation LPC coeff generation algorithm invented by
  113902. N. Levinson in 1947, modified by J. Durbin in 1959. */
  113903. /* Input : n elements of time doamin data
  113904. Output: m lpc coefficients, excitation energy */
  113905. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  113906. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  113907. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  113908. double error;
  113909. int i,j;
  113910. /* autocorrelation, p+1 lag coefficients */
  113911. j=m+1;
  113912. while(j--){
  113913. double d=0; /* double needed for accumulator depth */
  113914. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  113915. aut[j]=d;
  113916. }
  113917. /* Generate lpc coefficients from autocorr values */
  113918. error=aut[0];
  113919. for(i=0;i<m;i++){
  113920. double r= -aut[i+1];
  113921. if(error==0){
  113922. memset(lpci,0,m*sizeof(*lpci));
  113923. return 0;
  113924. }
  113925. /* Sum up this iteration's reflection coefficient; note that in
  113926. Vorbis we don't save it. If anyone wants to recycle this code
  113927. and needs reflection coefficients, save the results of 'r' from
  113928. each iteration. */
  113929. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  113930. r/=error;
  113931. /* Update LPC coefficients and total error */
  113932. lpc[i]=r;
  113933. for(j=0;j<i/2;j++){
  113934. double tmp=lpc[j];
  113935. lpc[j]+=r*lpc[i-1-j];
  113936. lpc[i-1-j]+=r*tmp;
  113937. }
  113938. if(i%2)lpc[j]+=lpc[j]*r;
  113939. error*=1.f-r*r;
  113940. }
  113941. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  113942. /* we need the error value to know how big an impulse to hit the
  113943. filter with later */
  113944. return error;
  113945. }
  113946. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  113947. float *data,long n){
  113948. /* in: coeff[0...m-1] LPC coefficients
  113949. prime[0...m-1] initial values (allocated size of n+m-1)
  113950. out: data[0...n-1] data samples */
  113951. long i,j,o,p;
  113952. float y;
  113953. float *work=(float*)alloca(sizeof(*work)*(m+n));
  113954. if(!prime)
  113955. for(i=0;i<m;i++)
  113956. work[i]=0.f;
  113957. else
  113958. for(i=0;i<m;i++)
  113959. work[i]=prime[i];
  113960. for(i=0;i<n;i++){
  113961. y=0;
  113962. o=i;
  113963. p=m;
  113964. for(j=0;j<m;j++)
  113965. y-=work[o++]*coeff[--p];
  113966. data[i]=work[o]=y;
  113967. }
  113968. }
  113969. #endif
  113970. /*** End of inlined file: lpc.c ***/
  113971. /*** Start of inlined file: lsp.c ***/
  113972. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  113973. an iterative root polisher (CACM algorithm 283). It *is* possible
  113974. to confuse this algorithm into not converging; that should only
  113975. happen with absurdly closely spaced roots (very sharp peaks in the
  113976. LPC f response) which in turn should be impossible in our use of
  113977. the code. If this *does* happen anyway, it's a bug in the floor
  113978. finder; find the cause of the confusion (probably a single bin
  113979. spike or accidental near-float-limit resolution problems) and
  113980. correct it. */
  113981. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113982. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113983. // tasks..
  113984. #if JUCE_MSVC
  113985. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113986. #endif
  113987. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113988. #if JUCE_USE_OGGVORBIS
  113989. #include <math.h>
  113990. #include <string.h>
  113991. #include <stdlib.h>
  113992. /*** Start of inlined file: lookup.h ***/
  113993. #ifndef _V_LOOKUP_H_
  113994. #ifdef FLOAT_LOOKUP
  113995. extern float vorbis_coslook(float a);
  113996. extern float vorbis_invsqlook(float a);
  113997. extern float vorbis_invsq2explook(int a);
  113998. extern float vorbis_fromdBlook(float a);
  113999. #endif
  114000. #ifdef INT_LOOKUP
  114001. extern long vorbis_invsqlook_i(long a,long e);
  114002. extern long vorbis_coslook_i(long a);
  114003. extern float vorbis_fromdBlook_i(long a);
  114004. #endif
  114005. #endif
  114006. /*** End of inlined file: lookup.h ***/
  114007. /* three possible LSP to f curve functions; the exact computation
  114008. (float), a lookup based float implementation, and an integer
  114009. implementation. The float lookup is likely the optimal choice on
  114010. any machine with an FPU. The integer implementation is *not* fixed
  114011. point (due to the need for a large dynamic range and thus a
  114012. seperately tracked exponent) and thus much more complex than the
  114013. relatively simple float implementations. It's mostly for future
  114014. work on a fully fixed point implementation for processors like the
  114015. ARM family. */
  114016. /* undefine both for the 'old' but more precise implementation */
  114017. #define FLOAT_LOOKUP
  114018. #undef INT_LOOKUP
  114019. #ifdef FLOAT_LOOKUP
  114020. /*** Start of inlined file: lookup.c ***/
  114021. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114022. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114023. // tasks..
  114024. #if JUCE_MSVC
  114025. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114026. #endif
  114027. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114028. #if JUCE_USE_OGGVORBIS
  114029. #include <math.h>
  114030. /*** Start of inlined file: lookup.h ***/
  114031. #ifndef _V_LOOKUP_H_
  114032. #ifdef FLOAT_LOOKUP
  114033. extern float vorbis_coslook(float a);
  114034. extern float vorbis_invsqlook(float a);
  114035. extern float vorbis_invsq2explook(int a);
  114036. extern float vorbis_fromdBlook(float a);
  114037. #endif
  114038. #ifdef INT_LOOKUP
  114039. extern long vorbis_invsqlook_i(long a,long e);
  114040. extern long vorbis_coslook_i(long a);
  114041. extern float vorbis_fromdBlook_i(long a);
  114042. #endif
  114043. #endif
  114044. /*** End of inlined file: lookup.h ***/
  114045. /*** Start of inlined file: lookup_data.h ***/
  114046. #ifndef _V_LOOKUP_DATA_H_
  114047. #ifdef FLOAT_LOOKUP
  114048. #define COS_LOOKUP_SZ 128
  114049. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114050. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114051. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114052. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114053. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114054. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114055. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114056. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114057. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114058. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114059. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114060. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114061. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114062. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114063. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114064. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114065. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114066. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114067. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114068. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114069. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114070. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114071. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114072. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114073. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114074. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114075. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114076. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114077. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114078. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114079. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114080. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114081. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114082. -1.0000000000000f,
  114083. };
  114084. #define INVSQ_LOOKUP_SZ 32
  114085. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114086. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114087. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114088. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114089. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114090. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114091. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114092. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114093. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114094. 1.000000000000f,
  114095. };
  114096. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114097. #define INVSQ2EXP_LOOKUP_MAX 32
  114098. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114099. INVSQ2EXP_LOOKUP_MIN+1]={
  114100. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114101. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114102. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114103. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114104. 256.f, 181.019336f, 128.f, 90.50966799f,
  114105. 64.f, 45.254834f, 32.f, 22.627417f,
  114106. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114107. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114108. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114109. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114110. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114111. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114112. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114113. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114114. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114115. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114116. 1.525878906e-05f,
  114117. };
  114118. #endif
  114119. #define FROMdB_LOOKUP_SZ 35
  114120. #define FROMdB2_LOOKUP_SZ 32
  114121. #define FROMdB_SHIFT 5
  114122. #define FROMdB2_SHIFT 3
  114123. #define FROMdB2_MASK 31
  114124. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114125. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114126. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114127. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114128. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114129. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114130. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114131. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114132. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114133. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114134. };
  114135. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114136. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114137. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114138. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114139. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114140. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114141. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114142. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114143. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114144. };
  114145. #ifdef INT_LOOKUP
  114146. #define INVSQ_LOOKUP_I_SHIFT 10
  114147. #define INVSQ_LOOKUP_I_MASK 1023
  114148. static long INVSQ_LOOKUP_I[64+1]={
  114149. 92682l, 91966l, 91267l, 90583l,
  114150. 89915l, 89261l, 88621l, 87995l,
  114151. 87381l, 86781l, 86192l, 85616l,
  114152. 85051l, 84497l, 83953l, 83420l,
  114153. 82897l, 82384l, 81880l, 81385l,
  114154. 80899l, 80422l, 79953l, 79492l,
  114155. 79039l, 78594l, 78156l, 77726l,
  114156. 77302l, 76885l, 76475l, 76072l,
  114157. 75674l, 75283l, 74898l, 74519l,
  114158. 74146l, 73778l, 73415l, 73058l,
  114159. 72706l, 72359l, 72016l, 71679l,
  114160. 71347l, 71019l, 70695l, 70376l,
  114161. 70061l, 69750l, 69444l, 69141l,
  114162. 68842l, 68548l, 68256l, 67969l,
  114163. 67685l, 67405l, 67128l, 66855l,
  114164. 66585l, 66318l, 66054l, 65794l,
  114165. 65536l,
  114166. };
  114167. #define COS_LOOKUP_I_SHIFT 9
  114168. #define COS_LOOKUP_I_MASK 511
  114169. #define COS_LOOKUP_I_SZ 128
  114170. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114171. 16384l, 16379l, 16364l, 16340l,
  114172. 16305l, 16261l, 16207l, 16143l,
  114173. 16069l, 15986l, 15893l, 15791l,
  114174. 15679l, 15557l, 15426l, 15286l,
  114175. 15137l, 14978l, 14811l, 14635l,
  114176. 14449l, 14256l, 14053l, 13842l,
  114177. 13623l, 13395l, 13160l, 12916l,
  114178. 12665l, 12406l, 12140l, 11866l,
  114179. 11585l, 11297l, 11003l, 10702l,
  114180. 10394l, 10080l, 9760l, 9434l,
  114181. 9102l, 8765l, 8423l, 8076l,
  114182. 7723l, 7366l, 7005l, 6639l,
  114183. 6270l, 5897l, 5520l, 5139l,
  114184. 4756l, 4370l, 3981l, 3590l,
  114185. 3196l, 2801l, 2404l, 2006l,
  114186. 1606l, 1205l, 804l, 402l,
  114187. 0l, -401l, -803l, -1204l,
  114188. -1605l, -2005l, -2403l, -2800l,
  114189. -3195l, -3589l, -3980l, -4369l,
  114190. -4755l, -5138l, -5519l, -5896l,
  114191. -6269l, -6638l, -7004l, -7365l,
  114192. -7722l, -8075l, -8422l, -8764l,
  114193. -9101l, -9433l, -9759l, -10079l,
  114194. -10393l, -10701l, -11002l, -11296l,
  114195. -11584l, -11865l, -12139l, -12405l,
  114196. -12664l, -12915l, -13159l, -13394l,
  114197. -13622l, -13841l, -14052l, -14255l,
  114198. -14448l, -14634l, -14810l, -14977l,
  114199. -15136l, -15285l, -15425l, -15556l,
  114200. -15678l, -15790l, -15892l, -15985l,
  114201. -16068l, -16142l, -16206l, -16260l,
  114202. -16304l, -16339l, -16363l, -16378l,
  114203. -16383l,
  114204. };
  114205. #endif
  114206. #endif
  114207. /*** End of inlined file: lookup_data.h ***/
  114208. #ifdef FLOAT_LOOKUP
  114209. /* interpolated lookup based cos function, domain 0 to PI only */
  114210. float vorbis_coslook(float a){
  114211. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114212. int i=vorbis_ftoi(d-.5);
  114213. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114214. }
  114215. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114216. float vorbis_invsqlook(float a){
  114217. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114218. int i=vorbis_ftoi(d-.5f);
  114219. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114220. }
  114221. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114222. float vorbis_invsq2explook(int a){
  114223. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114224. }
  114225. #include <stdio.h>
  114226. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114227. float vorbis_fromdBlook(float a){
  114228. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114229. return (i<0)?1.f:
  114230. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114231. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114232. }
  114233. #endif
  114234. #ifdef INT_LOOKUP
  114235. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114236. 16.16 format
  114237. returns in m.8 format */
  114238. long vorbis_invsqlook_i(long a,long e){
  114239. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114240. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114241. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114242. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114243. d)>>16); /* result 1.16 */
  114244. e+=32;
  114245. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114246. e=(e>>1)-8;
  114247. return(val>>e);
  114248. }
  114249. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114250. /* a is in n.12 format */
  114251. float vorbis_fromdBlook_i(long a){
  114252. int i=(-a)>>(12-FROMdB2_SHIFT);
  114253. return (i<0)?1.f:
  114254. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114255. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114256. }
  114257. /* interpolated lookup based cos function, domain 0 to PI only */
  114258. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114259. long vorbis_coslook_i(long a){
  114260. int i=a>>COS_LOOKUP_I_SHIFT;
  114261. int d=a&COS_LOOKUP_I_MASK;
  114262. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114263. COS_LOOKUP_I_SHIFT);
  114264. }
  114265. #endif
  114266. #endif
  114267. /*** End of inlined file: lookup.c ***/
  114268. /* catch this in the build system; we #include for
  114269. compilers (like gcc) that can't inline across
  114270. modules */
  114271. /* side effect: changes *lsp to cosines of lsp */
  114272. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114273. float amp,float ampoffset){
  114274. int i;
  114275. float wdel=M_PI/ln;
  114276. vorbis_fpu_control fpu;
  114277. (void) fpu; // to avoid an unused variable warning
  114278. vorbis_fpu_setround(&fpu);
  114279. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114280. i=0;
  114281. while(i<n){
  114282. int k=map[i];
  114283. int qexp;
  114284. float p=.7071067812f;
  114285. float q=.7071067812f;
  114286. float w=vorbis_coslook(wdel*k);
  114287. float *ftmp=lsp;
  114288. int c=m>>1;
  114289. do{
  114290. q*=ftmp[0]-w;
  114291. p*=ftmp[1]-w;
  114292. ftmp+=2;
  114293. }while(--c);
  114294. if(m&1){
  114295. /* odd order filter; slightly assymetric */
  114296. /* the last coefficient */
  114297. q*=ftmp[0]-w;
  114298. q*=q;
  114299. p*=p*(1.f-w*w);
  114300. }else{
  114301. /* even order filter; still symmetric */
  114302. q*=q*(1.f+w);
  114303. p*=p*(1.f-w);
  114304. }
  114305. q=frexp(p+q,&qexp);
  114306. q=vorbis_fromdBlook(amp*
  114307. vorbis_invsqlook(q)*
  114308. vorbis_invsq2explook(qexp+m)-
  114309. ampoffset);
  114310. do{
  114311. curve[i++]*=q;
  114312. }while(map[i]==k);
  114313. }
  114314. vorbis_fpu_restore(fpu);
  114315. }
  114316. #else
  114317. #ifdef INT_LOOKUP
  114318. /*** Start of inlined file: lookup.c ***/
  114319. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114320. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114321. // tasks..
  114322. #if JUCE_MSVC
  114323. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114324. #endif
  114325. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114326. #if JUCE_USE_OGGVORBIS
  114327. #include <math.h>
  114328. /*** Start of inlined file: lookup.h ***/
  114329. #ifndef _V_LOOKUP_H_
  114330. #ifdef FLOAT_LOOKUP
  114331. extern float vorbis_coslook(float a);
  114332. extern float vorbis_invsqlook(float a);
  114333. extern float vorbis_invsq2explook(int a);
  114334. extern float vorbis_fromdBlook(float a);
  114335. #endif
  114336. #ifdef INT_LOOKUP
  114337. extern long vorbis_invsqlook_i(long a,long e);
  114338. extern long vorbis_coslook_i(long a);
  114339. extern float vorbis_fromdBlook_i(long a);
  114340. #endif
  114341. #endif
  114342. /*** End of inlined file: lookup.h ***/
  114343. /*** Start of inlined file: lookup_data.h ***/
  114344. #ifndef _V_LOOKUP_DATA_H_
  114345. #ifdef FLOAT_LOOKUP
  114346. #define COS_LOOKUP_SZ 128
  114347. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114348. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114349. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114350. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114351. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114352. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114353. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114354. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114355. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114356. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114357. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114358. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114359. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114360. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114361. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114362. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114363. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114364. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114365. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114366. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114367. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114368. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114369. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114370. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114371. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114372. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114373. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114374. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114375. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114376. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114377. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114378. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114379. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114380. -1.0000000000000f,
  114381. };
  114382. #define INVSQ_LOOKUP_SZ 32
  114383. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114384. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114385. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114386. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114387. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114388. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114389. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114390. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114391. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114392. 1.000000000000f,
  114393. };
  114394. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114395. #define INVSQ2EXP_LOOKUP_MAX 32
  114396. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114397. INVSQ2EXP_LOOKUP_MIN+1]={
  114398. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114399. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114400. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114401. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114402. 256.f, 181.019336f, 128.f, 90.50966799f,
  114403. 64.f, 45.254834f, 32.f, 22.627417f,
  114404. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114405. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114406. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114407. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114408. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114409. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114410. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114411. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114412. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114413. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114414. 1.525878906e-05f,
  114415. };
  114416. #endif
  114417. #define FROMdB_LOOKUP_SZ 35
  114418. #define FROMdB2_LOOKUP_SZ 32
  114419. #define FROMdB_SHIFT 5
  114420. #define FROMdB2_SHIFT 3
  114421. #define FROMdB2_MASK 31
  114422. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114423. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114424. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114425. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114426. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114427. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114428. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114429. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114430. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114431. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114432. };
  114433. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114434. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114435. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114436. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114437. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114438. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114439. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114440. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114441. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114442. };
  114443. #ifdef INT_LOOKUP
  114444. #define INVSQ_LOOKUP_I_SHIFT 10
  114445. #define INVSQ_LOOKUP_I_MASK 1023
  114446. static long INVSQ_LOOKUP_I[64+1]={
  114447. 92682l, 91966l, 91267l, 90583l,
  114448. 89915l, 89261l, 88621l, 87995l,
  114449. 87381l, 86781l, 86192l, 85616l,
  114450. 85051l, 84497l, 83953l, 83420l,
  114451. 82897l, 82384l, 81880l, 81385l,
  114452. 80899l, 80422l, 79953l, 79492l,
  114453. 79039l, 78594l, 78156l, 77726l,
  114454. 77302l, 76885l, 76475l, 76072l,
  114455. 75674l, 75283l, 74898l, 74519l,
  114456. 74146l, 73778l, 73415l, 73058l,
  114457. 72706l, 72359l, 72016l, 71679l,
  114458. 71347l, 71019l, 70695l, 70376l,
  114459. 70061l, 69750l, 69444l, 69141l,
  114460. 68842l, 68548l, 68256l, 67969l,
  114461. 67685l, 67405l, 67128l, 66855l,
  114462. 66585l, 66318l, 66054l, 65794l,
  114463. 65536l,
  114464. };
  114465. #define COS_LOOKUP_I_SHIFT 9
  114466. #define COS_LOOKUP_I_MASK 511
  114467. #define COS_LOOKUP_I_SZ 128
  114468. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114469. 16384l, 16379l, 16364l, 16340l,
  114470. 16305l, 16261l, 16207l, 16143l,
  114471. 16069l, 15986l, 15893l, 15791l,
  114472. 15679l, 15557l, 15426l, 15286l,
  114473. 15137l, 14978l, 14811l, 14635l,
  114474. 14449l, 14256l, 14053l, 13842l,
  114475. 13623l, 13395l, 13160l, 12916l,
  114476. 12665l, 12406l, 12140l, 11866l,
  114477. 11585l, 11297l, 11003l, 10702l,
  114478. 10394l, 10080l, 9760l, 9434l,
  114479. 9102l, 8765l, 8423l, 8076l,
  114480. 7723l, 7366l, 7005l, 6639l,
  114481. 6270l, 5897l, 5520l, 5139l,
  114482. 4756l, 4370l, 3981l, 3590l,
  114483. 3196l, 2801l, 2404l, 2006l,
  114484. 1606l, 1205l, 804l, 402l,
  114485. 0l, -401l, -803l, -1204l,
  114486. -1605l, -2005l, -2403l, -2800l,
  114487. -3195l, -3589l, -3980l, -4369l,
  114488. -4755l, -5138l, -5519l, -5896l,
  114489. -6269l, -6638l, -7004l, -7365l,
  114490. -7722l, -8075l, -8422l, -8764l,
  114491. -9101l, -9433l, -9759l, -10079l,
  114492. -10393l, -10701l, -11002l, -11296l,
  114493. -11584l, -11865l, -12139l, -12405l,
  114494. -12664l, -12915l, -13159l, -13394l,
  114495. -13622l, -13841l, -14052l, -14255l,
  114496. -14448l, -14634l, -14810l, -14977l,
  114497. -15136l, -15285l, -15425l, -15556l,
  114498. -15678l, -15790l, -15892l, -15985l,
  114499. -16068l, -16142l, -16206l, -16260l,
  114500. -16304l, -16339l, -16363l, -16378l,
  114501. -16383l,
  114502. };
  114503. #endif
  114504. #endif
  114505. /*** End of inlined file: lookup_data.h ***/
  114506. #ifdef FLOAT_LOOKUP
  114507. /* interpolated lookup based cos function, domain 0 to PI only */
  114508. float vorbis_coslook(float a){
  114509. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114510. int i=vorbis_ftoi(d-.5);
  114511. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114512. }
  114513. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114514. float vorbis_invsqlook(float a){
  114515. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114516. int i=vorbis_ftoi(d-.5f);
  114517. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114518. }
  114519. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114520. float vorbis_invsq2explook(int a){
  114521. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114522. }
  114523. #include <stdio.h>
  114524. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114525. float vorbis_fromdBlook(float a){
  114526. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114527. return (i<0)?1.f:
  114528. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114529. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114530. }
  114531. #endif
  114532. #ifdef INT_LOOKUP
  114533. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114534. 16.16 format
  114535. returns in m.8 format */
  114536. long vorbis_invsqlook_i(long a,long e){
  114537. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114538. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114539. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114540. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114541. d)>>16); /* result 1.16 */
  114542. e+=32;
  114543. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114544. e=(e>>1)-8;
  114545. return(val>>e);
  114546. }
  114547. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114548. /* a is in n.12 format */
  114549. float vorbis_fromdBlook_i(long a){
  114550. int i=(-a)>>(12-FROMdB2_SHIFT);
  114551. return (i<0)?1.f:
  114552. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114553. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114554. }
  114555. /* interpolated lookup based cos function, domain 0 to PI only */
  114556. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114557. long vorbis_coslook_i(long a){
  114558. int i=a>>COS_LOOKUP_I_SHIFT;
  114559. int d=a&COS_LOOKUP_I_MASK;
  114560. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114561. COS_LOOKUP_I_SHIFT);
  114562. }
  114563. #endif
  114564. #endif
  114565. /*** End of inlined file: lookup.c ***/
  114566. /* catch this in the build system; we #include for
  114567. compilers (like gcc) that can't inline across
  114568. modules */
  114569. static int MLOOP_1[64]={
  114570. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  114571. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  114572. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114573. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114574. };
  114575. static int MLOOP_2[64]={
  114576. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114577. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114578. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114579. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114580. };
  114581. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114582. /* side effect: changes *lsp to cosines of lsp */
  114583. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114584. float amp,float ampoffset){
  114585. /* 0 <= m < 256 */
  114586. /* set up for using all int later */
  114587. int i;
  114588. int ampoffseti=rint(ampoffset*4096.f);
  114589. int ampi=rint(amp*16.f);
  114590. long *ilsp=alloca(m*sizeof(*ilsp));
  114591. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114592. i=0;
  114593. while(i<n){
  114594. int j,k=map[i];
  114595. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114596. unsigned long qi=46341;
  114597. int qexp=0,shift;
  114598. long wi=vorbis_coslook_i(k*65536/ln);
  114599. qi*=labs(ilsp[0]-wi);
  114600. pi*=labs(ilsp[1]-wi);
  114601. for(j=3;j<m;j+=2){
  114602. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114603. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114604. shift=MLOOP_3[(pi|qi)>>16];
  114605. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114606. pi=(pi>>shift)*labs(ilsp[j]-wi);
  114607. qexp+=shift;
  114608. }
  114609. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114610. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114611. shift=MLOOP_3[(pi|qi)>>16];
  114612. /* pi,qi normalized collectively, both tracked using qexp */
  114613. if(m&1){
  114614. /* odd order filter; slightly assymetric */
  114615. /* the last coefficient */
  114616. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114617. pi=(pi>>shift)<<14;
  114618. qexp+=shift;
  114619. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114620. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114621. shift=MLOOP_3[(pi|qi)>>16];
  114622. pi>>=shift;
  114623. qi>>=shift;
  114624. qexp+=shift-14*((m+1)>>1);
  114625. pi=((pi*pi)>>16);
  114626. qi=((qi*qi)>>16);
  114627. qexp=qexp*2+m;
  114628. pi*=(1<<14)-((wi*wi)>>14);
  114629. qi+=pi>>14;
  114630. }else{
  114631. /* even order filter; still symmetric */
  114632. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  114633. worth tracking step by step */
  114634. pi>>=shift;
  114635. qi>>=shift;
  114636. qexp+=shift-7*m;
  114637. pi=((pi*pi)>>16);
  114638. qi=((qi*qi)>>16);
  114639. qexp=qexp*2+m;
  114640. pi*=(1<<14)-wi;
  114641. qi*=(1<<14)+wi;
  114642. qi=(qi+pi)>>14;
  114643. }
  114644. /* we've let the normalization drift because it wasn't important;
  114645. however, for the lookup, things must be normalized again. We
  114646. need at most one right shift or a number of left shifts */
  114647. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  114648. qi>>=1; qexp++;
  114649. }else
  114650. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  114651. qi<<=1; qexp--;
  114652. }
  114653. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  114654. vorbis_invsqlook_i(qi,qexp)-
  114655. /* m.8, m+n<=8 */
  114656. ampoffseti); /* 8.12[0] */
  114657. curve[i]*=amp;
  114658. while(map[++i]==k)curve[i]*=amp;
  114659. }
  114660. }
  114661. #else
  114662. /* old, nonoptimized but simple version for any poor sap who needs to
  114663. figure out what the hell this code does, or wants the other
  114664. fraction of a dB precision */
  114665. /* side effect: changes *lsp to cosines of lsp */
  114666. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114667. float amp,float ampoffset){
  114668. int i;
  114669. float wdel=M_PI/ln;
  114670. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  114671. i=0;
  114672. while(i<n){
  114673. int j,k=map[i];
  114674. float p=.5f;
  114675. float q=.5f;
  114676. float w=2.f*cos(wdel*k);
  114677. for(j=1;j<m;j+=2){
  114678. q *= w-lsp[j-1];
  114679. p *= w-lsp[j];
  114680. }
  114681. if(j==m){
  114682. /* odd order filter; slightly assymetric */
  114683. /* the last coefficient */
  114684. q*=w-lsp[j-1];
  114685. p*=p*(4.f-w*w);
  114686. q*=q;
  114687. }else{
  114688. /* even order filter; still symmetric */
  114689. p*=p*(2.f-w);
  114690. q*=q*(2.f+w);
  114691. }
  114692. q=fromdB(amp/sqrt(p+q)-ampoffset);
  114693. curve[i]*=q;
  114694. while(map[++i]==k)curve[i]*=q;
  114695. }
  114696. }
  114697. #endif
  114698. #endif
  114699. static void cheby(float *g, int ord) {
  114700. int i, j;
  114701. g[0] *= .5f;
  114702. for(i=2; i<= ord; i++) {
  114703. for(j=ord; j >= i; j--) {
  114704. g[j-2] -= g[j];
  114705. g[j] += g[j];
  114706. }
  114707. }
  114708. }
  114709. static int JUCE_CDECL comp(const void *a,const void *b){
  114710. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  114711. }
  114712. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  114713. but there are root sets for which it gets into limit cycles
  114714. (exacerbated by zero suppression) and fails. We can't afford to
  114715. fail, even if the failure is 1 in 100,000,000, so we now use
  114716. Laguerre and later polish with Newton-Raphson (which can then
  114717. afford to fail) */
  114718. #define EPSILON 10e-7
  114719. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  114720. int i,m;
  114721. double lastdelta=0.f;
  114722. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  114723. for(i=0;i<=ord;i++)defl[i]=a[i];
  114724. for(m=ord;m>0;m--){
  114725. double newx=0.f,delta;
  114726. /* iterate a root */
  114727. while(1){
  114728. double p=defl[m],pp=0.f,ppp=0.f,denom;
  114729. /* eval the polynomial and its first two derivatives */
  114730. for(i=m;i>0;i--){
  114731. ppp = newx*ppp + pp;
  114732. pp = newx*pp + p;
  114733. p = newx*p + defl[i-1];
  114734. }
  114735. /* Laguerre's method */
  114736. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  114737. if(denom<0)
  114738. return(-1); /* complex root! The LPC generator handed us a bad filter */
  114739. if(pp>0){
  114740. denom = pp + sqrt(denom);
  114741. if(denom<EPSILON)denom=EPSILON;
  114742. }else{
  114743. denom = pp - sqrt(denom);
  114744. if(denom>-(EPSILON))denom=-(EPSILON);
  114745. }
  114746. delta = m*p/denom;
  114747. newx -= delta;
  114748. if(delta<0.f)delta*=-1;
  114749. if(fabs(delta/newx)<10e-12)break;
  114750. lastdelta=delta;
  114751. }
  114752. r[m-1]=newx;
  114753. /* forward deflation */
  114754. for(i=m;i>0;i--)
  114755. defl[i-1]+=newx*defl[i];
  114756. defl++;
  114757. }
  114758. return(0);
  114759. }
  114760. /* for spit-and-polish only */
  114761. static int Newton_Raphson(float *a,int ord,float *r){
  114762. int i, k, count=0;
  114763. double error=1.f;
  114764. double *root=(double*)alloca(ord*sizeof(*root));
  114765. for(i=0; i<ord;i++) root[i] = r[i];
  114766. while(error>1e-20){
  114767. error=0;
  114768. for(i=0; i<ord; i++) { /* Update each point. */
  114769. double pp=0.,delta;
  114770. double rooti=root[i];
  114771. double p=a[ord];
  114772. for(k=ord-1; k>= 0; k--) {
  114773. pp= pp* rooti + p;
  114774. p = p * rooti + a[k];
  114775. }
  114776. delta = p/pp;
  114777. root[i] -= delta;
  114778. error+= delta*delta;
  114779. }
  114780. if(count>40)return(-1);
  114781. count++;
  114782. }
  114783. /* Replaced the original bubble sort with a real sort. With your
  114784. help, we can eliminate the bubble sort in our lifetime. --Monty */
  114785. for(i=0; i<ord;i++) r[i] = root[i];
  114786. return(0);
  114787. }
  114788. /* Convert lpc coefficients to lsp coefficients */
  114789. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  114790. int order2=(m+1)>>1;
  114791. int g1_order,g2_order;
  114792. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  114793. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  114794. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  114795. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  114796. int i;
  114797. /* even and odd are slightly different base cases */
  114798. g1_order=(m+1)>>1;
  114799. g2_order=(m) >>1;
  114800. /* Compute the lengths of the x polynomials. */
  114801. /* Compute the first half of K & R F1 & F2 polynomials. */
  114802. /* Compute half of the symmetric and antisymmetric polynomials. */
  114803. /* Remove the roots at +1 and -1. */
  114804. g1[g1_order] = 1.f;
  114805. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  114806. g2[g2_order] = 1.f;
  114807. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  114808. if(g1_order>g2_order){
  114809. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  114810. }else{
  114811. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  114812. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  114813. }
  114814. /* Convert into polynomials in cos(alpha) */
  114815. cheby(g1,g1_order);
  114816. cheby(g2,g2_order);
  114817. /* Find the roots of the 2 even polynomials.*/
  114818. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  114819. Laguerre_With_Deflation(g2,g2_order,g2r))
  114820. return(-1);
  114821. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  114822. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  114823. qsort(g1r,g1_order,sizeof(*g1r),comp);
  114824. qsort(g2r,g2_order,sizeof(*g2r),comp);
  114825. for(i=0;i<g1_order;i++)
  114826. lsp[i*2] = acos(g1r[i]);
  114827. for(i=0;i<g2_order;i++)
  114828. lsp[i*2+1] = acos(g2r[i]);
  114829. return(0);
  114830. }
  114831. #endif
  114832. /*** End of inlined file: lsp.c ***/
  114833. /*** Start of inlined file: mapping0.c ***/
  114834. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114835. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114836. // tasks..
  114837. #if JUCE_MSVC
  114838. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114839. #endif
  114840. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114841. #if JUCE_USE_OGGVORBIS
  114842. #include <stdlib.h>
  114843. #include <stdio.h>
  114844. #include <string.h>
  114845. #include <math.h>
  114846. /* simplistic, wasteful way of doing this (unique lookup for each
  114847. mode/submapping); there should be a central repository for
  114848. identical lookups. That will require minor work, so I'm putting it
  114849. off as low priority.
  114850. Why a lookup for each backend in a given mode? Because the
  114851. blocksize is set by the mode, and low backend lookups may require
  114852. parameters from other areas of the mode/mapping */
  114853. static void mapping0_free_info(vorbis_info_mapping *i){
  114854. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  114855. if(info){
  114856. memset(info,0,sizeof(*info));
  114857. _ogg_free(info);
  114858. }
  114859. }
  114860. static int ilog3(unsigned int v){
  114861. int ret=0;
  114862. if(v)--v;
  114863. while(v){
  114864. ret++;
  114865. v>>=1;
  114866. }
  114867. return(ret);
  114868. }
  114869. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  114870. oggpack_buffer *opb){
  114871. int i;
  114872. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  114873. /* another 'we meant to do it this way' hack... up to beta 4, we
  114874. packed 4 binary zeros here to signify one submapping in use. We
  114875. now redefine that to mean four bitflags that indicate use of
  114876. deeper features; bit0:submappings, bit1:coupling,
  114877. bit2,3:reserved. This is backward compatable with all actual uses
  114878. of the beta code. */
  114879. if(info->submaps>1){
  114880. oggpack_write(opb,1,1);
  114881. oggpack_write(opb,info->submaps-1,4);
  114882. }else
  114883. oggpack_write(opb,0,1);
  114884. if(info->coupling_steps>0){
  114885. oggpack_write(opb,1,1);
  114886. oggpack_write(opb,info->coupling_steps-1,8);
  114887. for(i=0;i<info->coupling_steps;i++){
  114888. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  114889. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  114890. }
  114891. }else
  114892. oggpack_write(opb,0,1);
  114893. oggpack_write(opb,0,2); /* 2,3:reserved */
  114894. /* we don't write the channel submappings if we only have one... */
  114895. if(info->submaps>1){
  114896. for(i=0;i<vi->channels;i++)
  114897. oggpack_write(opb,info->chmuxlist[i],4);
  114898. }
  114899. for(i=0;i<info->submaps;i++){
  114900. oggpack_write(opb,0,8); /* time submap unused */
  114901. oggpack_write(opb,info->floorsubmap[i],8);
  114902. oggpack_write(opb,info->residuesubmap[i],8);
  114903. }
  114904. }
  114905. /* also responsible for range checking */
  114906. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  114907. int i;
  114908. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  114909. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114910. memset(info,0,sizeof(*info));
  114911. if(oggpack_read(opb,1))
  114912. info->submaps=oggpack_read(opb,4)+1;
  114913. else
  114914. info->submaps=1;
  114915. if(oggpack_read(opb,1)){
  114916. info->coupling_steps=oggpack_read(opb,8)+1;
  114917. for(i=0;i<info->coupling_steps;i++){
  114918. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  114919. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  114920. if(testM<0 ||
  114921. testA<0 ||
  114922. testM==testA ||
  114923. testM>=vi->channels ||
  114924. testA>=vi->channels) goto err_out;
  114925. }
  114926. }
  114927. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  114928. if(info->submaps>1){
  114929. for(i=0;i<vi->channels;i++){
  114930. info->chmuxlist[i]=oggpack_read(opb,4);
  114931. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  114932. }
  114933. }
  114934. for(i=0;i<info->submaps;i++){
  114935. oggpack_read(opb,8); /* time submap unused */
  114936. info->floorsubmap[i]=oggpack_read(opb,8);
  114937. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  114938. info->residuesubmap[i]=oggpack_read(opb,8);
  114939. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  114940. }
  114941. return info;
  114942. err_out:
  114943. mapping0_free_info(info);
  114944. return(NULL);
  114945. }
  114946. #if 0
  114947. static long seq=0;
  114948. static ogg_int64_t total=0;
  114949. static float FLOOR1_fromdB_LOOKUP[256]={
  114950. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  114951. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  114952. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  114953. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  114954. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  114955. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  114956. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  114957. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  114958. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  114959. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  114960. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  114961. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  114962. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  114963. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  114964. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  114965. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  114966. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  114967. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  114968. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  114969. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  114970. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  114971. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  114972. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  114973. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  114974. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  114975. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  114976. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  114977. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  114978. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  114979. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  114980. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  114981. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  114982. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  114983. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  114984. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  114985. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  114986. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  114987. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  114988. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  114989. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  114990. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  114991. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  114992. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  114993. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  114994. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  114995. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  114996. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  114997. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  114998. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  114999. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  115000. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  115001. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  115002. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  115003. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  115004. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  115005. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  115006. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  115007. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  115008. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  115009. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  115010. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  115011. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  115012. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  115013. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  115014. };
  115015. #endif
  115016. extern int *floor1_fit(vorbis_block *vb,void *look,
  115017. const float *logmdct, /* in */
  115018. const float *logmask);
  115019. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115020. int *A,int *B,
  115021. int del);
  115022. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115023. void*look,
  115024. int *post,int *ilogmask);
  115025. static int mapping0_forward(vorbis_block *vb){
  115026. vorbis_dsp_state *vd=vb->vd;
  115027. vorbis_info *vi=vd->vi;
  115028. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115029. private_state *b=(private_state*)vb->vd->backend_state;
  115030. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115031. int n=vb->pcmend;
  115032. int i,j,k;
  115033. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115034. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115035. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115036. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115037. float global_ampmax=vbi->ampmax;
  115038. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115039. int blocktype=vbi->blocktype;
  115040. int modenumber=vb->W;
  115041. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115042. vorbis_look_psy *psy_look=
  115043. b->psy+blocktype+(vb->W?2:0);
  115044. vb->mode=modenumber;
  115045. for(i=0;i<vi->channels;i++){
  115046. float scale=4.f/n;
  115047. float scale_dB;
  115048. float *pcm =vb->pcm[i];
  115049. float *logfft =pcm;
  115050. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115051. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115052. todB estimation used on IEEE 754
  115053. compliant machines had a bug that
  115054. returned dB values about a third
  115055. of a decibel too high. The bug
  115056. was harmless because tunings
  115057. implicitly took that into
  115058. account. However, fixing the bug
  115059. in the estimator requires
  115060. changing all the tunings as well.
  115061. For now, it's easier to sync
  115062. things back up here, and
  115063. recalibrate the tunings in the
  115064. next major model upgrade. */
  115065. #if 0
  115066. if(vi->channels==2)
  115067. if(i==0)
  115068. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115069. else
  115070. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115071. #endif
  115072. /* window the PCM data */
  115073. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115074. #if 0
  115075. if(vi->channels==2)
  115076. if(i==0)
  115077. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115078. else
  115079. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115080. #endif
  115081. /* transform the PCM data */
  115082. /* only MDCT right now.... */
  115083. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115084. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115085. drft_forward(&b->fft_look[vb->W],pcm);
  115086. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115087. original todB estimation used on
  115088. IEEE 754 compliant machines had a
  115089. bug that returned dB values about
  115090. a third of a decibel too high.
  115091. The bug was harmless because
  115092. tunings implicitly took that into
  115093. account. However, fixing the bug
  115094. in the estimator requires
  115095. changing all the tunings as well.
  115096. For now, it's easier to sync
  115097. things back up here, and
  115098. recalibrate the tunings in the
  115099. next major model upgrade. */
  115100. local_ampmax[i]=logfft[0];
  115101. for(j=1;j<n-1;j+=2){
  115102. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115103. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115104. .345 is a hack; the original todB
  115105. estimation used on IEEE 754
  115106. compliant machines had a bug that
  115107. returned dB values about a third
  115108. of a decibel too high. The bug
  115109. was harmless because tunings
  115110. implicitly took that into
  115111. account. However, fixing the bug
  115112. in the estimator requires
  115113. changing all the tunings as well.
  115114. For now, it's easier to sync
  115115. things back up here, and
  115116. recalibrate the tunings in the
  115117. next major model upgrade. */
  115118. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115119. }
  115120. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115121. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115122. #if 0
  115123. if(vi->channels==2){
  115124. if(i==0){
  115125. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115126. }else{
  115127. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115128. }
  115129. }
  115130. #endif
  115131. }
  115132. {
  115133. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115134. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115135. for(i=0;i<vi->channels;i++){
  115136. /* the encoder setup assumes that all the modes used by any
  115137. specific bitrate tweaking use the same floor */
  115138. int submap=info->chmuxlist[i];
  115139. /* the following makes things clearer to *me* anyway */
  115140. float *mdct =gmdct[i];
  115141. float *logfft =vb->pcm[i];
  115142. float *logmdct =logfft+n/2;
  115143. float *logmask =logfft;
  115144. vb->mode=modenumber;
  115145. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115146. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115147. for(j=0;j<n/2;j++)
  115148. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115149. todB estimation used on IEEE 754
  115150. compliant machines had a bug that
  115151. returned dB values about a third
  115152. of a decibel too high. The bug
  115153. was harmless because tunings
  115154. implicitly took that into
  115155. account. However, fixing the bug
  115156. in the estimator requires
  115157. changing all the tunings as well.
  115158. For now, it's easier to sync
  115159. things back up here, and
  115160. recalibrate the tunings in the
  115161. next major model upgrade. */
  115162. #if 0
  115163. if(vi->channels==2){
  115164. if(i==0)
  115165. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115166. else
  115167. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115168. }else{
  115169. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115170. }
  115171. #endif
  115172. /* first step; noise masking. Not only does 'noise masking'
  115173. give us curves from which we can decide how much resolution
  115174. to give noise parts of the spectrum, it also implicitly hands
  115175. us a tonality estimate (the larger the value in the
  115176. 'noise_depth' vector, the more tonal that area is) */
  115177. _vp_noisemask(psy_look,
  115178. logmdct,
  115179. noise); /* noise does not have by-frequency offset
  115180. bias applied yet */
  115181. #if 0
  115182. if(vi->channels==2){
  115183. if(i==0)
  115184. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115185. else
  115186. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115187. }
  115188. #endif
  115189. /* second step: 'all the other crap'; all the stuff that isn't
  115190. computed/fit for bitrate management goes in the second psy
  115191. vector. This includes tone masking, peak limiting and ATH */
  115192. _vp_tonemask(psy_look,
  115193. logfft,
  115194. tone,
  115195. global_ampmax,
  115196. local_ampmax[i]);
  115197. #if 0
  115198. if(vi->channels==2){
  115199. if(i==0)
  115200. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115201. else
  115202. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115203. }
  115204. #endif
  115205. /* third step; we offset the noise vectors, overlay tone
  115206. masking. We then do a floor1-specific line fit. If we're
  115207. performing bitrate management, the line fit is performed
  115208. multiple times for up/down tweakage on demand. */
  115209. #if 0
  115210. {
  115211. float aotuv[psy_look->n];
  115212. #endif
  115213. _vp_offset_and_mix(psy_look,
  115214. noise,
  115215. tone,
  115216. 1,
  115217. logmask,
  115218. mdct,
  115219. logmdct);
  115220. #if 0
  115221. if(vi->channels==2){
  115222. if(i==0)
  115223. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115224. else
  115225. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115226. }
  115227. }
  115228. #endif
  115229. #if 0
  115230. if(vi->channels==2){
  115231. if(i==0)
  115232. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115233. else
  115234. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115235. }
  115236. #endif
  115237. /* this algorithm is hardwired to floor 1 for now; abort out if
  115238. we're *not* floor1. This won't happen unless someone has
  115239. broken the encode setup lib. Guard it anyway. */
  115240. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115241. floor_posts[i][PACKETBLOBS/2]=
  115242. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115243. logmdct,
  115244. logmask);
  115245. /* are we managing bitrate? If so, perform two more fits for
  115246. later rate tweaking (fits represent hi/lo) */
  115247. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115248. /* higher rate by way of lower noise curve */
  115249. _vp_offset_and_mix(psy_look,
  115250. noise,
  115251. tone,
  115252. 2,
  115253. logmask,
  115254. mdct,
  115255. logmdct);
  115256. #if 0
  115257. if(vi->channels==2){
  115258. if(i==0)
  115259. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115260. else
  115261. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115262. }
  115263. #endif
  115264. floor_posts[i][PACKETBLOBS-1]=
  115265. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115266. logmdct,
  115267. logmask);
  115268. /* lower rate by way of higher noise curve */
  115269. _vp_offset_and_mix(psy_look,
  115270. noise,
  115271. tone,
  115272. 0,
  115273. logmask,
  115274. mdct,
  115275. logmdct);
  115276. #if 0
  115277. if(vi->channels==2)
  115278. if(i==0)
  115279. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115280. else
  115281. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115282. #endif
  115283. floor_posts[i][0]=
  115284. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115285. logmdct,
  115286. logmask);
  115287. /* we also interpolate a range of intermediate curves for
  115288. intermediate rates */
  115289. for(k=1;k<PACKETBLOBS/2;k++)
  115290. floor_posts[i][k]=
  115291. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115292. floor_posts[i][0],
  115293. floor_posts[i][PACKETBLOBS/2],
  115294. k*65536/(PACKETBLOBS/2));
  115295. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115296. floor_posts[i][k]=
  115297. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115298. floor_posts[i][PACKETBLOBS/2],
  115299. floor_posts[i][PACKETBLOBS-1],
  115300. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115301. }
  115302. }
  115303. }
  115304. vbi->ampmax=global_ampmax;
  115305. /*
  115306. the next phases are performed once for vbr-only and PACKETBLOB
  115307. times for bitrate managed modes.
  115308. 1) encode actual mode being used
  115309. 2) encode the floor for each channel, compute coded mask curve/res
  115310. 3) normalize and couple.
  115311. 4) encode residue
  115312. 5) save packet bytes to the packetblob vector
  115313. */
  115314. /* iterate over the many masking curve fits we've created */
  115315. {
  115316. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115317. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115318. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115319. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115320. float **mag_memo;
  115321. int **mag_sort;
  115322. if(info->coupling_steps){
  115323. mag_memo=_vp_quantize_couple_memo(vb,
  115324. &ci->psy_g_param,
  115325. psy_look,
  115326. info,
  115327. gmdct);
  115328. mag_sort=_vp_quantize_couple_sort(vb,
  115329. psy_look,
  115330. info,
  115331. mag_memo);
  115332. hf_reduction(&ci->psy_g_param,
  115333. psy_look,
  115334. info,
  115335. mag_memo);
  115336. }
  115337. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115338. if(psy_look->vi->normal_channel_p){
  115339. for(i=0;i<vi->channels;i++){
  115340. float *mdct =gmdct[i];
  115341. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115342. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115343. }
  115344. }
  115345. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115346. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115347. k++){
  115348. oggpack_buffer *opb=vbi->packetblob[k];
  115349. /* start out our new packet blob with packet type and mode */
  115350. /* Encode the packet type */
  115351. oggpack_write(opb,0,1);
  115352. /* Encode the modenumber */
  115353. /* Encode frame mode, pre,post windowsize, then dispatch */
  115354. oggpack_write(opb,modenumber,b->modebits);
  115355. if(vb->W){
  115356. oggpack_write(opb,vb->lW,1);
  115357. oggpack_write(opb,vb->nW,1);
  115358. }
  115359. /* encode floor, compute masking curve, sep out residue */
  115360. for(i=0;i<vi->channels;i++){
  115361. int submap=info->chmuxlist[i];
  115362. float *mdct =gmdct[i];
  115363. float *res =vb->pcm[i];
  115364. int *ilogmask=ilogmaskch[i]=
  115365. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115366. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115367. floor_posts[i][k],
  115368. ilogmask);
  115369. #if 0
  115370. {
  115371. char buf[80];
  115372. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115373. float work[n/2];
  115374. for(j=0;j<n/2;j++)
  115375. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115376. _analysis_output(buf,seq,work,n/2,1,1,0);
  115377. }
  115378. #endif
  115379. _vp_remove_floor(psy_look,
  115380. mdct,
  115381. ilogmask,
  115382. res,
  115383. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115384. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115385. #if 0
  115386. {
  115387. char buf[80];
  115388. float work[n/2];
  115389. for(j=0;j<n/2;j++)
  115390. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115391. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115392. _analysis_output(buf,seq,work,n/2,1,1,0);
  115393. }
  115394. #endif
  115395. }
  115396. /* our iteration is now based on masking curve, not prequant and
  115397. coupling. Only one prequant/coupling step */
  115398. /* quantize/couple */
  115399. /* incomplete implementation that assumes the tree is all depth
  115400. one, or no tree at all */
  115401. if(info->coupling_steps){
  115402. _vp_couple(k,
  115403. &ci->psy_g_param,
  115404. psy_look,
  115405. info,
  115406. vb->pcm,
  115407. mag_memo,
  115408. mag_sort,
  115409. ilogmaskch,
  115410. nonzero,
  115411. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115412. }
  115413. /* classify and encode by submap */
  115414. for(i=0;i<info->submaps;i++){
  115415. int ch_in_bundle=0;
  115416. long **classifications;
  115417. int resnum=info->residuesubmap[i];
  115418. for(j=0;j<vi->channels;j++){
  115419. if(info->chmuxlist[j]==i){
  115420. zerobundle[ch_in_bundle]=0;
  115421. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115422. res_bundle[ch_in_bundle]=vb->pcm[j];
  115423. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115424. }
  115425. }
  115426. classifications=_residue_P[ci->residue_type[resnum]]->
  115427. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115428. _residue_P[ci->residue_type[resnum]]->
  115429. forward(opb,vb,b->residue[resnum],
  115430. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115431. }
  115432. /* ok, done encoding. Next protopacket. */
  115433. }
  115434. }
  115435. #if 0
  115436. seq++;
  115437. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115438. #endif
  115439. return(0);
  115440. }
  115441. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115442. vorbis_dsp_state *vd=vb->vd;
  115443. vorbis_info *vi=vd->vi;
  115444. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115445. private_state *b=(private_state*)vd->backend_state;
  115446. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115447. int i,j;
  115448. long n=vb->pcmend=ci->blocksizes[vb->W];
  115449. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115450. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115451. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115452. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115453. /* recover the spectral envelope; store it in the PCM vector for now */
  115454. for(i=0;i<vi->channels;i++){
  115455. int submap=info->chmuxlist[i];
  115456. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115457. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115458. if(floormemo[i])
  115459. nonzero[i]=1;
  115460. else
  115461. nonzero[i]=0;
  115462. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115463. }
  115464. /* channel coupling can 'dirty' the nonzero listing */
  115465. for(i=0;i<info->coupling_steps;i++){
  115466. if(nonzero[info->coupling_mag[i]] ||
  115467. nonzero[info->coupling_ang[i]]){
  115468. nonzero[info->coupling_mag[i]]=1;
  115469. nonzero[info->coupling_ang[i]]=1;
  115470. }
  115471. }
  115472. /* recover the residue into our working vectors */
  115473. for(i=0;i<info->submaps;i++){
  115474. int ch_in_bundle=0;
  115475. for(j=0;j<vi->channels;j++){
  115476. if(info->chmuxlist[j]==i){
  115477. if(nonzero[j])
  115478. zerobundle[ch_in_bundle]=1;
  115479. else
  115480. zerobundle[ch_in_bundle]=0;
  115481. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115482. }
  115483. }
  115484. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115485. inverse(vb,b->residue[info->residuesubmap[i]],
  115486. pcmbundle,zerobundle,ch_in_bundle);
  115487. }
  115488. /* channel coupling */
  115489. for(i=info->coupling_steps-1;i>=0;i--){
  115490. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115491. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115492. for(j=0;j<n/2;j++){
  115493. float mag=pcmM[j];
  115494. float ang=pcmA[j];
  115495. if(mag>0)
  115496. if(ang>0){
  115497. pcmM[j]=mag;
  115498. pcmA[j]=mag-ang;
  115499. }else{
  115500. pcmA[j]=mag;
  115501. pcmM[j]=mag+ang;
  115502. }
  115503. else
  115504. if(ang>0){
  115505. pcmM[j]=mag;
  115506. pcmA[j]=mag+ang;
  115507. }else{
  115508. pcmA[j]=mag;
  115509. pcmM[j]=mag-ang;
  115510. }
  115511. }
  115512. }
  115513. /* compute and apply spectral envelope */
  115514. for(i=0;i<vi->channels;i++){
  115515. float *pcm=vb->pcm[i];
  115516. int submap=info->chmuxlist[i];
  115517. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115518. inverse2(vb,b->flr[info->floorsubmap[submap]],
  115519. floormemo[i],pcm);
  115520. }
  115521. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  115522. /* only MDCT right now.... */
  115523. for(i=0;i<vi->channels;i++){
  115524. float *pcm=vb->pcm[i];
  115525. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  115526. }
  115527. /* all done! */
  115528. return(0);
  115529. }
  115530. /* export hooks */
  115531. vorbis_func_mapping mapping0_exportbundle={
  115532. &mapping0_pack,
  115533. &mapping0_unpack,
  115534. &mapping0_free_info,
  115535. &mapping0_forward,
  115536. &mapping0_inverse
  115537. };
  115538. #endif
  115539. /*** End of inlined file: mapping0.c ***/
  115540. /*** Start of inlined file: mdct.c ***/
  115541. /* this can also be run as an integer transform by uncommenting a
  115542. define in mdct.h; the integerization is a first pass and although
  115543. it's likely stable for Vorbis, the dynamic range is constrained and
  115544. roundoff isn't done (so it's noisy). Consider it functional, but
  115545. only a starting point. There's no point on a machine with an FPU */
  115546. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115547. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115548. // tasks..
  115549. #if JUCE_MSVC
  115550. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115551. #endif
  115552. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115553. #if JUCE_USE_OGGVORBIS
  115554. #include <stdio.h>
  115555. #include <stdlib.h>
  115556. #include <string.h>
  115557. #include <math.h>
  115558. /* build lookups for trig functions; also pre-figure scaling and
  115559. some window function algebra. */
  115560. void mdct_init(mdct_lookup *lookup,int n){
  115561. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  115562. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  115563. int i;
  115564. int n2=n>>1;
  115565. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  115566. lookup->n=n;
  115567. lookup->trig=T;
  115568. lookup->bitrev=bitrev;
  115569. /* trig lookups... */
  115570. for(i=0;i<n/4;i++){
  115571. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  115572. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  115573. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115574. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115575. }
  115576. for(i=0;i<n/8;i++){
  115577. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115578. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115579. }
  115580. /* bitreverse lookup... */
  115581. {
  115582. int mask=(1<<(log2n-1))-1,i,j;
  115583. int msb=1<<(log2n-2);
  115584. for(i=0;i<n/8;i++){
  115585. int acc=0;
  115586. for(j=0;msb>>j;j++)
  115587. if((msb>>j)&i)acc|=1<<j;
  115588. bitrev[i*2]=((~acc)&mask)-1;
  115589. bitrev[i*2+1]=acc;
  115590. }
  115591. }
  115592. lookup->scale=FLOAT_CONV(4.f/n);
  115593. }
  115594. /* 8 point butterfly (in place, 4 register) */
  115595. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115596. REG_TYPE r0 = x[6] + x[2];
  115597. REG_TYPE r1 = x[6] - x[2];
  115598. REG_TYPE r2 = x[4] + x[0];
  115599. REG_TYPE r3 = x[4] - x[0];
  115600. x[6] = r0 + r2;
  115601. x[4] = r0 - r2;
  115602. r0 = x[5] - x[1];
  115603. r2 = x[7] - x[3];
  115604. x[0] = r1 + r0;
  115605. x[2] = r1 - r0;
  115606. r0 = x[5] + x[1];
  115607. r1 = x[7] + x[3];
  115608. x[3] = r2 + r3;
  115609. x[1] = r2 - r3;
  115610. x[7] = r1 + r0;
  115611. x[5] = r1 - r0;
  115612. }
  115613. /* 16 point butterfly (in place, 4 register) */
  115614. STIN void mdct_butterfly_16(DATA_TYPE *x){
  115615. REG_TYPE r0 = x[1] - x[9];
  115616. REG_TYPE r1 = x[0] - x[8];
  115617. x[8] += x[0];
  115618. x[9] += x[1];
  115619. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  115620. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  115621. r0 = x[3] - x[11];
  115622. r1 = x[10] - x[2];
  115623. x[10] += x[2];
  115624. x[11] += x[3];
  115625. x[2] = r0;
  115626. x[3] = r1;
  115627. r0 = x[12] - x[4];
  115628. r1 = x[13] - x[5];
  115629. x[12] += x[4];
  115630. x[13] += x[5];
  115631. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  115632. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  115633. r0 = x[14] - x[6];
  115634. r1 = x[15] - x[7];
  115635. x[14] += x[6];
  115636. x[15] += x[7];
  115637. x[6] = r0;
  115638. x[7] = r1;
  115639. mdct_butterfly_8(x);
  115640. mdct_butterfly_8(x+8);
  115641. }
  115642. /* 32 point butterfly (in place, 4 register) */
  115643. STIN void mdct_butterfly_32(DATA_TYPE *x){
  115644. REG_TYPE r0 = x[30] - x[14];
  115645. REG_TYPE r1 = x[31] - x[15];
  115646. x[30] += x[14];
  115647. x[31] += x[15];
  115648. x[14] = r0;
  115649. x[15] = r1;
  115650. r0 = x[28] - x[12];
  115651. r1 = x[29] - x[13];
  115652. x[28] += x[12];
  115653. x[29] += x[13];
  115654. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  115655. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  115656. r0 = x[26] - x[10];
  115657. r1 = x[27] - x[11];
  115658. x[26] += x[10];
  115659. x[27] += x[11];
  115660. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  115661. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  115662. r0 = x[24] - x[8];
  115663. r1 = x[25] - x[9];
  115664. x[24] += x[8];
  115665. x[25] += x[9];
  115666. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  115667. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115668. r0 = x[22] - x[6];
  115669. r1 = x[7] - x[23];
  115670. x[22] += x[6];
  115671. x[23] += x[7];
  115672. x[6] = r1;
  115673. x[7] = r0;
  115674. r0 = x[4] - x[20];
  115675. r1 = x[5] - x[21];
  115676. x[20] += x[4];
  115677. x[21] += x[5];
  115678. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  115679. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  115680. r0 = x[2] - x[18];
  115681. r1 = x[3] - x[19];
  115682. x[18] += x[2];
  115683. x[19] += x[3];
  115684. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  115685. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  115686. r0 = x[0] - x[16];
  115687. r1 = x[1] - x[17];
  115688. x[16] += x[0];
  115689. x[17] += x[1];
  115690. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115691. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  115692. mdct_butterfly_16(x);
  115693. mdct_butterfly_16(x+16);
  115694. }
  115695. /* N point first stage butterfly (in place, 2 register) */
  115696. STIN void mdct_butterfly_first(DATA_TYPE *T,
  115697. DATA_TYPE *x,
  115698. int points){
  115699. DATA_TYPE *x1 = x + points - 8;
  115700. DATA_TYPE *x2 = x + (points>>1) - 8;
  115701. REG_TYPE r0;
  115702. REG_TYPE r1;
  115703. do{
  115704. r0 = x1[6] - x2[6];
  115705. r1 = x1[7] - x2[7];
  115706. x1[6] += x2[6];
  115707. x1[7] += x2[7];
  115708. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115709. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115710. r0 = x1[4] - x2[4];
  115711. r1 = x1[5] - x2[5];
  115712. x1[4] += x2[4];
  115713. x1[5] += x2[5];
  115714. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  115715. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  115716. r0 = x1[2] - x2[2];
  115717. r1 = x1[3] - x2[3];
  115718. x1[2] += x2[2];
  115719. x1[3] += x2[3];
  115720. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  115721. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  115722. r0 = x1[0] - x2[0];
  115723. r1 = x1[1] - x2[1];
  115724. x1[0] += x2[0];
  115725. x1[1] += x2[1];
  115726. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  115727. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  115728. x1-=8;
  115729. x2-=8;
  115730. T+=16;
  115731. }while(x2>=x);
  115732. }
  115733. /* N/stage point generic N stage butterfly (in place, 2 register) */
  115734. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  115735. DATA_TYPE *x,
  115736. int points,
  115737. int trigint){
  115738. DATA_TYPE *x1 = x + points - 8;
  115739. DATA_TYPE *x2 = x + (points>>1) - 8;
  115740. REG_TYPE r0;
  115741. REG_TYPE r1;
  115742. do{
  115743. r0 = x1[6] - x2[6];
  115744. r1 = x1[7] - x2[7];
  115745. x1[6] += x2[6];
  115746. x1[7] += x2[7];
  115747. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115748. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115749. T+=trigint;
  115750. r0 = x1[4] - x2[4];
  115751. r1 = x1[5] - x2[5];
  115752. x1[4] += x2[4];
  115753. x1[5] += x2[5];
  115754. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115755. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115756. T+=trigint;
  115757. r0 = x1[2] - x2[2];
  115758. r1 = x1[3] - x2[3];
  115759. x1[2] += x2[2];
  115760. x1[3] += x2[3];
  115761. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115762. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115763. T+=trigint;
  115764. r0 = x1[0] - x2[0];
  115765. r1 = x1[1] - x2[1];
  115766. x1[0] += x2[0];
  115767. x1[1] += x2[1];
  115768. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115769. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115770. T+=trigint;
  115771. x1-=8;
  115772. x2-=8;
  115773. }while(x2>=x);
  115774. }
  115775. STIN void mdct_butterflies(mdct_lookup *init,
  115776. DATA_TYPE *x,
  115777. int points){
  115778. DATA_TYPE *T=init->trig;
  115779. int stages=init->log2n-5;
  115780. int i,j;
  115781. if(--stages>0){
  115782. mdct_butterfly_first(T,x,points);
  115783. }
  115784. for(i=1;--stages>0;i++){
  115785. for(j=0;j<(1<<i);j++)
  115786. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  115787. }
  115788. for(j=0;j<points;j+=32)
  115789. mdct_butterfly_32(x+j);
  115790. }
  115791. void mdct_clear(mdct_lookup *l){
  115792. if(l){
  115793. if(l->trig)_ogg_free(l->trig);
  115794. if(l->bitrev)_ogg_free(l->bitrev);
  115795. memset(l,0,sizeof(*l));
  115796. }
  115797. }
  115798. STIN void mdct_bitreverse(mdct_lookup *init,
  115799. DATA_TYPE *x){
  115800. int n = init->n;
  115801. int *bit = init->bitrev;
  115802. DATA_TYPE *w0 = x;
  115803. DATA_TYPE *w1 = x = w0+(n>>1);
  115804. DATA_TYPE *T = init->trig+n;
  115805. do{
  115806. DATA_TYPE *x0 = x+bit[0];
  115807. DATA_TYPE *x1 = x+bit[1];
  115808. REG_TYPE r0 = x0[1] - x1[1];
  115809. REG_TYPE r1 = x0[0] + x1[0];
  115810. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  115811. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  115812. w1 -= 4;
  115813. r0 = HALVE(x0[1] + x1[1]);
  115814. r1 = HALVE(x0[0] - x1[0]);
  115815. w0[0] = r0 + r2;
  115816. w1[2] = r0 - r2;
  115817. w0[1] = r1 + r3;
  115818. w1[3] = r3 - r1;
  115819. x0 = x+bit[2];
  115820. x1 = x+bit[3];
  115821. r0 = x0[1] - x1[1];
  115822. r1 = x0[0] + x1[0];
  115823. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  115824. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  115825. r0 = HALVE(x0[1] + x1[1]);
  115826. r1 = HALVE(x0[0] - x1[0]);
  115827. w0[2] = r0 + r2;
  115828. w1[0] = r0 - r2;
  115829. w0[3] = r1 + r3;
  115830. w1[1] = r3 - r1;
  115831. T += 4;
  115832. bit += 4;
  115833. w0 += 4;
  115834. }while(w0<w1);
  115835. }
  115836. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115837. int n=init->n;
  115838. int n2=n>>1;
  115839. int n4=n>>2;
  115840. /* rotate */
  115841. DATA_TYPE *iX = in+n2-7;
  115842. DATA_TYPE *oX = out+n2+n4;
  115843. DATA_TYPE *T = init->trig+n4;
  115844. do{
  115845. oX -= 4;
  115846. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  115847. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  115848. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  115849. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  115850. iX -= 8;
  115851. T += 4;
  115852. }while(iX>=in);
  115853. iX = in+n2-8;
  115854. oX = out+n2+n4;
  115855. T = init->trig+n4;
  115856. do{
  115857. T -= 4;
  115858. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  115859. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  115860. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  115861. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  115862. iX -= 8;
  115863. oX += 4;
  115864. }while(iX>=in);
  115865. mdct_butterflies(init,out+n2,n2);
  115866. mdct_bitreverse(init,out);
  115867. /* roatate + window */
  115868. {
  115869. DATA_TYPE *oX1=out+n2+n4;
  115870. DATA_TYPE *oX2=out+n2+n4;
  115871. DATA_TYPE *iX =out;
  115872. T =init->trig+n2;
  115873. do{
  115874. oX1-=4;
  115875. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  115876. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  115877. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  115878. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  115879. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  115880. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  115881. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  115882. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  115883. oX2+=4;
  115884. iX += 8;
  115885. T += 8;
  115886. }while(iX<oX1);
  115887. iX=out+n2+n4;
  115888. oX1=out+n4;
  115889. oX2=oX1;
  115890. do{
  115891. oX1-=4;
  115892. iX-=4;
  115893. oX2[0] = -(oX1[3] = iX[3]);
  115894. oX2[1] = -(oX1[2] = iX[2]);
  115895. oX2[2] = -(oX1[1] = iX[1]);
  115896. oX2[3] = -(oX1[0] = iX[0]);
  115897. oX2+=4;
  115898. }while(oX2<iX);
  115899. iX=out+n2+n4;
  115900. oX1=out+n2+n4;
  115901. oX2=out+n2;
  115902. do{
  115903. oX1-=4;
  115904. oX1[0]= iX[3];
  115905. oX1[1]= iX[2];
  115906. oX1[2]= iX[1];
  115907. oX1[3]= iX[0];
  115908. iX+=4;
  115909. }while(oX1>oX2);
  115910. }
  115911. }
  115912. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115913. int n=init->n;
  115914. int n2=n>>1;
  115915. int n4=n>>2;
  115916. int n8=n>>3;
  115917. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  115918. DATA_TYPE *w2=w+n2;
  115919. /* rotate */
  115920. /* window + rotate + step 1 */
  115921. REG_TYPE r0;
  115922. REG_TYPE r1;
  115923. DATA_TYPE *x0=in+n2+n4;
  115924. DATA_TYPE *x1=x0+1;
  115925. DATA_TYPE *T=init->trig+n2;
  115926. int i=0;
  115927. for(i=0;i<n8;i+=2){
  115928. x0 -=4;
  115929. T-=2;
  115930. r0= x0[2] + x1[0];
  115931. r1= x0[0] + x1[2];
  115932. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115933. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115934. x1 +=4;
  115935. }
  115936. x1=in+1;
  115937. for(;i<n2-n8;i+=2){
  115938. T-=2;
  115939. x0 -=4;
  115940. r0= x0[2] - x1[0];
  115941. r1= x0[0] - x1[2];
  115942. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115943. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115944. x1 +=4;
  115945. }
  115946. x0=in+n;
  115947. for(;i<n2;i+=2){
  115948. T-=2;
  115949. x0 -=4;
  115950. r0= -x0[2] - x1[0];
  115951. r1= -x0[0] - x1[2];
  115952. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115953. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115954. x1 +=4;
  115955. }
  115956. mdct_butterflies(init,w+n2,n2);
  115957. mdct_bitreverse(init,w);
  115958. /* roatate + window */
  115959. T=init->trig+n2;
  115960. x0=out+n2;
  115961. for(i=0;i<n4;i++){
  115962. x0--;
  115963. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  115964. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  115965. w+=2;
  115966. T+=2;
  115967. }
  115968. }
  115969. #endif
  115970. /*** End of inlined file: mdct.c ***/
  115971. /*** Start of inlined file: psy.c ***/
  115972. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115973. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115974. // tasks..
  115975. #if JUCE_MSVC
  115976. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115977. #endif
  115978. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115979. #if JUCE_USE_OGGVORBIS
  115980. #include <stdlib.h>
  115981. #include <math.h>
  115982. #include <string.h>
  115983. /*** Start of inlined file: masking.h ***/
  115984. #ifndef _V_MASKING_H_
  115985. #define _V_MASKING_H_
  115986. /* more detailed ATH; the bass if flat to save stressing the floor
  115987. overly for only a bin or two of savings. */
  115988. #define MAX_ATH 88
  115989. static float ATH[]={
  115990. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  115991. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  115992. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  115993. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  115994. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  115995. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  115996. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  115997. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  115998. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  115999. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  116000. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  116001. };
  116002. /* The tone masking curves from Ehmer's and Fielder's papers have been
  116003. replaced by an empirically collected data set. The previously
  116004. published values were, far too often, simply on crack. */
  116005. #define EHMER_OFFSET 16
  116006. #define EHMER_MAX 56
  116007. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116008. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116009. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116010. for collection of these curves) */
  116011. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116012. /* 62.5 Hz */
  116013. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116014. -60, -60, -60, -60, -62, -62, -65, -73,
  116015. -69, -68, -68, -67, -70, -70, -72, -74,
  116016. -75, -79, -79, -80, -83, -88, -93, -100,
  116017. -110, -999, -999, -999, -999, -999, -999, -999,
  116018. -999, -999, -999, -999, -999, -999, -999, -999,
  116019. -999, -999, -999, -999, -999, -999, -999, -999},
  116020. { -48, -48, -48, -48, -48, -48, -48, -48,
  116021. -48, -48, -48, -48, -48, -53, -61, -66,
  116022. -66, -68, -67, -70, -76, -76, -72, -73,
  116023. -75, -76, -78, -79, -83, -88, -93, -100,
  116024. -110, -999, -999, -999, -999, -999, -999, -999,
  116025. -999, -999, -999, -999, -999, -999, -999, -999,
  116026. -999, -999, -999, -999, -999, -999, -999, -999},
  116027. { -37, -37, -37, -37, -37, -37, -37, -37,
  116028. -38, -40, -42, -46, -48, -53, -55, -62,
  116029. -65, -58, -56, -56, -61, -60, -65, -67,
  116030. -69, -71, -77, -77, -78, -80, -82, -84,
  116031. -88, -93, -98, -106, -112, -999, -999, -999,
  116032. -999, -999, -999, -999, -999, -999, -999, -999,
  116033. -999, -999, -999, -999, -999, -999, -999, -999},
  116034. { -25, -25, -25, -25, -25, -25, -25, -25,
  116035. -25, -26, -27, -29, -32, -38, -48, -52,
  116036. -52, -50, -48, -48, -51, -52, -54, -60,
  116037. -67, -67, -66, -68, -69, -73, -73, -76,
  116038. -80, -81, -81, -85, -85, -86, -88, -93,
  116039. -100, -110, -999, -999, -999, -999, -999, -999,
  116040. -999, -999, -999, -999, -999, -999, -999, -999},
  116041. { -16, -16, -16, -16, -16, -16, -16, -16,
  116042. -17, -19, -20, -22, -26, -28, -31, -40,
  116043. -47, -39, -39, -40, -42, -43, -47, -51,
  116044. -57, -52, -55, -55, -60, -58, -62, -63,
  116045. -70, -67, -69, -72, -73, -77, -80, -82,
  116046. -83, -87, -90, -94, -98, -104, -115, -999,
  116047. -999, -999, -999, -999, -999, -999, -999, -999},
  116048. { -8, -8, -8, -8, -8, -8, -8, -8,
  116049. -8, -8, -10, -11, -15, -19, -25, -30,
  116050. -34, -31, -30, -31, -29, -32, -35, -42,
  116051. -48, -42, -44, -46, -50, -50, -51, -52,
  116052. -59, -54, -55, -55, -58, -62, -63, -66,
  116053. -72, -73, -76, -75, -78, -80, -80, -81,
  116054. -84, -88, -90, -94, -98, -101, -106, -110}},
  116055. /* 88Hz */
  116056. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116057. -66, -66, -66, -66, -66, -67, -67, -67,
  116058. -76, -72, -71, -74, -76, -76, -75, -78,
  116059. -79, -79, -81, -83, -86, -89, -93, -97,
  116060. -100, -105, -110, -999, -999, -999, -999, -999,
  116061. -999, -999, -999, -999, -999, -999, -999, -999,
  116062. -999, -999, -999, -999, -999, -999, -999, -999},
  116063. { -47, -47, -47, -47, -47, -47, -47, -47,
  116064. -47, -47, -47, -48, -51, -55, -59, -66,
  116065. -66, -66, -67, -66, -68, -69, -70, -74,
  116066. -79, -77, -77, -78, -80, -81, -82, -84,
  116067. -86, -88, -91, -95, -100, -108, -116, -999,
  116068. -999, -999, -999, -999, -999, -999, -999, -999,
  116069. -999, -999, -999, -999, -999, -999, -999, -999},
  116070. { -36, -36, -36, -36, -36, -36, -36, -36,
  116071. -36, -37, -37, -41, -44, -48, -51, -58,
  116072. -62, -60, -57, -59, -59, -60, -63, -65,
  116073. -72, -71, -70, -72, -74, -77, -76, -78,
  116074. -81, -81, -80, -83, -86, -91, -96, -100,
  116075. -105, -110, -999, -999, -999, -999, -999, -999,
  116076. -999, -999, -999, -999, -999, -999, -999, -999},
  116077. { -28, -28, -28, -28, -28, -28, -28, -28,
  116078. -28, -30, -32, -32, -33, -35, -41, -49,
  116079. -50, -49, -47, -48, -48, -52, -51, -57,
  116080. -65, -61, -59, -61, -64, -69, -70, -74,
  116081. -77, -77, -78, -81, -84, -85, -87, -90,
  116082. -92, -96, -100, -107, -112, -999, -999, -999,
  116083. -999, -999, -999, -999, -999, -999, -999, -999},
  116084. { -19, -19, -19, -19, -19, -19, -19, -19,
  116085. -20, -21, -23, -27, -30, -35, -36, -41,
  116086. -46, -44, -42, -40, -41, -41, -43, -48,
  116087. -55, -53, -52, -53, -56, -59, -58, -60,
  116088. -67, -66, -69, -71, -72, -75, -79, -81,
  116089. -84, -87, -90, -93, -97, -101, -107, -114,
  116090. -999, -999, -999, -999, -999, -999, -999, -999},
  116091. { -9, -9, -9, -9, -9, -9, -9, -9,
  116092. -11, -12, -12, -15, -16, -20, -23, -30,
  116093. -37, -34, -33, -34, -31, -32, -32, -38,
  116094. -47, -44, -41, -40, -47, -49, -46, -46,
  116095. -58, -50, -50, -54, -58, -62, -64, -67,
  116096. -67, -70, -72, -76, -79, -83, -87, -91,
  116097. -96, -100, -104, -110, -999, -999, -999, -999}},
  116098. /* 125 Hz */
  116099. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116100. -62, -62, -63, -64, -66, -67, -66, -68,
  116101. -75, -72, -76, -75, -76, -78, -79, -82,
  116102. -84, -85, -90, -94, -101, -110, -999, -999,
  116103. -999, -999, -999, -999, -999, -999, -999, -999,
  116104. -999, -999, -999, -999, -999, -999, -999, -999,
  116105. -999, -999, -999, -999, -999, -999, -999, -999},
  116106. { -59, -59, -59, -59, -59, -59, -59, -59,
  116107. -59, -59, -59, -60, -60, -61, -63, -66,
  116108. -71, -68, -70, -70, -71, -72, -72, -75,
  116109. -81, -78, -79, -82, -83, -86, -90, -97,
  116110. -103, -113, -999, -999, -999, -999, -999, -999,
  116111. -999, -999, -999, -999, -999, -999, -999, -999,
  116112. -999, -999, -999, -999, -999, -999, -999, -999},
  116113. { -53, -53, -53, -53, -53, -53, -53, -53,
  116114. -53, -54, -55, -57, -56, -57, -55, -61,
  116115. -65, -60, -60, -62, -63, -63, -66, -68,
  116116. -74, -73, -75, -75, -78, -80, -80, -82,
  116117. -85, -90, -96, -101, -108, -999, -999, -999,
  116118. -999, -999, -999, -999, -999, -999, -999, -999,
  116119. -999, -999, -999, -999, -999, -999, -999, -999},
  116120. { -46, -46, -46, -46, -46, -46, -46, -46,
  116121. -46, -46, -47, -47, -47, -47, -48, -51,
  116122. -57, -51, -49, -50, -51, -53, -54, -59,
  116123. -66, -60, -62, -67, -67, -70, -72, -75,
  116124. -76, -78, -81, -85, -88, -94, -97, -104,
  116125. -112, -999, -999, -999, -999, -999, -999, -999,
  116126. -999, -999, -999, -999, -999, -999, -999, -999},
  116127. { -36, -36, -36, -36, -36, -36, -36, -36,
  116128. -39, -41, -42, -42, -39, -38, -41, -43,
  116129. -52, -44, -40, -39, -37, -37, -40, -47,
  116130. -54, -50, -48, -50, -55, -61, -59, -62,
  116131. -66, -66, -66, -69, -69, -73, -74, -74,
  116132. -75, -77, -79, -82, -87, -91, -95, -100,
  116133. -108, -115, -999, -999, -999, -999, -999, -999},
  116134. { -28, -26, -24, -22, -20, -20, -23, -29,
  116135. -30, -31, -28, -27, -28, -28, -28, -35,
  116136. -40, -33, -32, -29, -30, -30, -30, -37,
  116137. -45, -41, -37, -38, -45, -47, -47, -48,
  116138. -53, -49, -48, -50, -49, -49, -51, -52,
  116139. -58, -56, -57, -56, -60, -61, -62, -70,
  116140. -72, -74, -78, -83, -88, -93, -100, -106}},
  116141. /* 177 Hz */
  116142. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116143. -999, -110, -105, -100, -95, -91, -87, -83,
  116144. -80, -78, -76, -78, -78, -81, -83, -85,
  116145. -86, -85, -86, -87, -90, -97, -107, -999,
  116146. -999, -999, -999, -999, -999, -999, -999, -999,
  116147. -999, -999, -999, -999, -999, -999, -999, -999,
  116148. -999, -999, -999, -999, -999, -999, -999, -999},
  116149. {-999, -999, -999, -110, -105, -100, -95, -90,
  116150. -85, -81, -77, -73, -70, -67, -67, -68,
  116151. -75, -73, -70, -69, -70, -72, -75, -79,
  116152. -84, -83, -84, -86, -88, -89, -89, -93,
  116153. -98, -105, -112, -999, -999, -999, -999, -999,
  116154. -999, -999, -999, -999, -999, -999, -999, -999,
  116155. -999, -999, -999, -999, -999, -999, -999, -999},
  116156. {-105, -100, -95, -90, -85, -80, -76, -71,
  116157. -68, -68, -65, -63, -63, -62, -62, -64,
  116158. -65, -64, -61, -62, -63, -64, -66, -68,
  116159. -73, -73, -74, -75, -76, -81, -83, -85,
  116160. -88, -89, -92, -95, -100, -108, -999, -999,
  116161. -999, -999, -999, -999, -999, -999, -999, -999,
  116162. -999, -999, -999, -999, -999, -999, -999, -999},
  116163. { -80, -75, -71, -68, -65, -63, -62, -61,
  116164. -61, -61, -61, -59, -56, -57, -53, -50,
  116165. -58, -52, -50, -50, -52, -53, -54, -58,
  116166. -67, -63, -67, -68, -72, -75, -78, -80,
  116167. -81, -81, -82, -85, -89, -90, -93, -97,
  116168. -101, -107, -114, -999, -999, -999, -999, -999,
  116169. -999, -999, -999, -999, -999, -999, -999, -999},
  116170. { -65, -61, -59, -57, -56, -55, -55, -56,
  116171. -56, -57, -55, -53, -52, -47, -44, -44,
  116172. -50, -44, -41, -39, -39, -42, -40, -46,
  116173. -51, -49, -50, -53, -54, -63, -60, -61,
  116174. -62, -66, -66, -66, -70, -73, -74, -75,
  116175. -76, -75, -79, -85, -89, -91, -96, -102,
  116176. -110, -999, -999, -999, -999, -999, -999, -999},
  116177. { -52, -50, -49, -49, -48, -48, -48, -49,
  116178. -50, -50, -49, -46, -43, -39, -35, -33,
  116179. -38, -36, -32, -29, -32, -32, -32, -35,
  116180. -44, -39, -38, -38, -46, -50, -45, -46,
  116181. -53, -50, -50, -50, -54, -54, -53, -53,
  116182. -56, -57, -59, -66, -70, -72, -74, -79,
  116183. -83, -85, -90, -97, -114, -999, -999, -999}},
  116184. /* 250 Hz */
  116185. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116186. -100, -95, -90, -86, -80, -75, -75, -79,
  116187. -80, -79, -80, -81, -82, -88, -95, -103,
  116188. -110, -999, -999, -999, -999, -999, -999, -999,
  116189. -999, -999, -999, -999, -999, -999, -999, -999,
  116190. -999, -999, -999, -999, -999, -999, -999, -999,
  116191. -999, -999, -999, -999, -999, -999, -999, -999},
  116192. {-999, -999, -999, -999, -108, -103, -98, -93,
  116193. -88, -83, -79, -78, -75, -71, -67, -68,
  116194. -73, -73, -72, -73, -75, -77, -80, -82,
  116195. -88, -93, -100, -107, -114, -999, -999, -999,
  116196. -999, -999, -999, -999, -999, -999, -999, -999,
  116197. -999, -999, -999, -999, -999, -999, -999, -999,
  116198. -999, -999, -999, -999, -999, -999, -999, -999},
  116199. {-999, -999, -999, -110, -105, -101, -96, -90,
  116200. -86, -81, -77, -73, -69, -66, -61, -62,
  116201. -66, -64, -62, -65, -66, -70, -72, -76,
  116202. -81, -80, -84, -90, -95, -102, -110, -999,
  116203. -999, -999, -999, -999, -999, -999, -999, -999,
  116204. -999, -999, -999, -999, -999, -999, -999, -999,
  116205. -999, -999, -999, -999, -999, -999, -999, -999},
  116206. {-999, -999, -999, -107, -103, -97, -92, -88,
  116207. -83, -79, -74, -70, -66, -59, -53, -58,
  116208. -62, -55, -54, -54, -54, -58, -61, -62,
  116209. -72, -70, -72, -75, -78, -80, -81, -80,
  116210. -83, -83, -88, -93, -100, -107, -115, -999,
  116211. -999, -999, -999, -999, -999, -999, -999, -999,
  116212. -999, -999, -999, -999, -999, -999, -999, -999},
  116213. {-999, -999, -999, -105, -100, -95, -90, -85,
  116214. -80, -75, -70, -66, -62, -56, -48, -44,
  116215. -48, -46, -46, -43, -46, -48, -48, -51,
  116216. -58, -58, -59, -60, -62, -62, -61, -61,
  116217. -65, -64, -65, -68, -70, -74, -75, -78,
  116218. -81, -86, -95, -110, -999, -999, -999, -999,
  116219. -999, -999, -999, -999, -999, -999, -999, -999},
  116220. {-999, -999, -105, -100, -95, -90, -85, -80,
  116221. -75, -70, -65, -61, -55, -49, -39, -33,
  116222. -40, -35, -32, -38, -40, -33, -35, -37,
  116223. -46, -41, -45, -44, -46, -42, -45, -46,
  116224. -52, -50, -50, -50, -54, -54, -55, -57,
  116225. -62, -64, -66, -68, -70, -76, -81, -90,
  116226. -100, -110, -999, -999, -999, -999, -999, -999}},
  116227. /* 354 hz */
  116228. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116229. -105, -98, -90, -85, -82, -83, -80, -78,
  116230. -84, -79, -80, -83, -87, -89, -91, -93,
  116231. -99, -106, -117, -999, -999, -999, -999, -999,
  116232. -999, -999, -999, -999, -999, -999, -999, -999,
  116233. -999, -999, -999, -999, -999, -999, -999, -999,
  116234. -999, -999, -999, -999, -999, -999, -999, -999},
  116235. {-999, -999, -999, -999, -999, -999, -999, -999,
  116236. -105, -98, -90, -85, -80, -75, -70, -68,
  116237. -74, -72, -74, -77, -80, -82, -85, -87,
  116238. -92, -89, -91, -95, -100, -106, -112, -999,
  116239. -999, -999, -999, -999, -999, -999, -999, -999,
  116240. -999, -999, -999, -999, -999, -999, -999, -999,
  116241. -999, -999, -999, -999, -999, -999, -999, -999},
  116242. {-999, -999, -999, -999, -999, -999, -999, -999,
  116243. -105, -98, -90, -83, -75, -71, -63, -64,
  116244. -67, -62, -64, -67, -70, -73, -77, -81,
  116245. -84, -83, -85, -89, -90, -93, -98, -104,
  116246. -109, -114, -999, -999, -999, -999, -999, -999,
  116247. -999, -999, -999, -999, -999, -999, -999, -999,
  116248. -999, -999, -999, -999, -999, -999, -999, -999},
  116249. {-999, -999, -999, -999, -999, -999, -999, -999,
  116250. -103, -96, -88, -81, -75, -68, -58, -54,
  116251. -56, -54, -56, -56, -58, -60, -63, -66,
  116252. -74, -69, -72, -72, -75, -74, -77, -81,
  116253. -81, -82, -84, -87, -93, -96, -99, -104,
  116254. -110, -999, -999, -999, -999, -999, -999, -999,
  116255. -999, -999, -999, -999, -999, -999, -999, -999},
  116256. {-999, -999, -999, -999, -999, -108, -102, -96,
  116257. -91, -85, -80, -74, -68, -60, -51, -46,
  116258. -48, -46, -43, -45, -47, -47, -49, -48,
  116259. -56, -53, -55, -58, -57, -63, -58, -60,
  116260. -66, -64, -67, -70, -70, -74, -77, -84,
  116261. -86, -89, -91, -93, -94, -101, -109, -118,
  116262. -999, -999, -999, -999, -999, -999, -999, -999},
  116263. {-999, -999, -999, -108, -103, -98, -93, -88,
  116264. -83, -78, -73, -68, -60, -53, -44, -35,
  116265. -38, -38, -34, -34, -36, -40, -41, -44,
  116266. -51, -45, -46, -47, -46, -54, -50, -49,
  116267. -50, -50, -50, -51, -54, -57, -58, -60,
  116268. -66, -66, -66, -64, -65, -68, -77, -82,
  116269. -87, -95, -110, -999, -999, -999, -999, -999}},
  116270. /* 500 Hz */
  116271. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116272. -107, -102, -97, -92, -87, -83, -78, -75,
  116273. -82, -79, -83, -85, -89, -92, -95, -98,
  116274. -101, -105, -109, -113, -999, -999, -999, -999,
  116275. -999, -999, -999, -999, -999, -999, -999, -999,
  116276. -999, -999, -999, -999, -999, -999, -999, -999,
  116277. -999, -999, -999, -999, -999, -999, -999, -999},
  116278. {-999, -999, -999, -999, -999, -999, -999, -106,
  116279. -100, -95, -90, -86, -81, -78, -74, -69,
  116280. -74, -74, -76, -79, -83, -84, -86, -89,
  116281. -92, -97, -93, -100, -103, -107, -110, -999,
  116282. -999, -999, -999, -999, -999, -999, -999, -999,
  116283. -999, -999, -999, -999, -999, -999, -999, -999,
  116284. -999, -999, -999, -999, -999, -999, -999, -999},
  116285. {-999, -999, -999, -999, -999, -999, -106, -100,
  116286. -95, -90, -87, -83, -80, -75, -69, -60,
  116287. -66, -66, -68, -70, -74, -78, -79, -81,
  116288. -81, -83, -84, -87, -93, -96, -99, -103,
  116289. -107, -110, -999, -999, -999, -999, -999, -999,
  116290. -999, -999, -999, -999, -999, -999, -999, -999,
  116291. -999, -999, -999, -999, -999, -999, -999, -999},
  116292. {-999, -999, -999, -999, -999, -108, -103, -98,
  116293. -93, -89, -85, -82, -78, -71, -62, -55,
  116294. -58, -58, -54, -54, -55, -59, -61, -62,
  116295. -70, -66, -66, -67, -70, -72, -75, -78,
  116296. -84, -84, -84, -88, -91, -90, -95, -98,
  116297. -102, -103, -106, -110, -999, -999, -999, -999,
  116298. -999, -999, -999, -999, -999, -999, -999, -999},
  116299. {-999, -999, -999, -999, -108, -103, -98, -94,
  116300. -90, -87, -82, -79, -73, -67, -58, -47,
  116301. -50, -45, -41, -45, -48, -44, -44, -49,
  116302. -54, -51, -48, -47, -49, -50, -51, -57,
  116303. -58, -60, -63, -69, -70, -69, -71, -74,
  116304. -78, -82, -90, -95, -101, -105, -110, -999,
  116305. -999, -999, -999, -999, -999, -999, -999, -999},
  116306. {-999, -999, -999, -105, -101, -97, -93, -90,
  116307. -85, -80, -77, -72, -65, -56, -48, -37,
  116308. -40, -36, -34, -40, -50, -47, -38, -41,
  116309. -47, -38, -35, -39, -38, -43, -40, -45,
  116310. -50, -45, -44, -47, -50, -55, -48, -48,
  116311. -52, -66, -70, -76, -82, -90, -97, -105,
  116312. -110, -999, -999, -999, -999, -999, -999, -999}},
  116313. /* 707 Hz */
  116314. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116315. -999, -108, -103, -98, -93, -86, -79, -76,
  116316. -83, -81, -85, -87, -89, -93, -98, -102,
  116317. -107, -112, -999, -999, -999, -999, -999, -999,
  116318. -999, -999, -999, -999, -999, -999, -999, -999,
  116319. -999, -999, -999, -999, -999, -999, -999, -999,
  116320. -999, -999, -999, -999, -999, -999, -999, -999},
  116321. {-999, -999, -999, -999, -999, -999, -999, -999,
  116322. -999, -108, -103, -98, -93, -86, -79, -71,
  116323. -77, -74, -77, -79, -81, -84, -85, -90,
  116324. -92, -93, -92, -98, -101, -108, -112, -999,
  116325. -999, -999, -999, -999, -999, -999, -999, -999,
  116326. -999, -999, -999, -999, -999, -999, -999, -999,
  116327. -999, -999, -999, -999, -999, -999, -999, -999},
  116328. {-999, -999, -999, -999, -999, -999, -999, -999,
  116329. -108, -103, -98, -93, -87, -78, -68, -65,
  116330. -66, -62, -65, -67, -70, -73, -75, -78,
  116331. -82, -82, -83, -84, -91, -93, -98, -102,
  116332. -106, -110, -999, -999, -999, -999, -999, -999,
  116333. -999, -999, -999, -999, -999, -999, -999, -999,
  116334. -999, -999, -999, -999, -999, -999, -999, -999},
  116335. {-999, -999, -999, -999, -999, -999, -999, -999,
  116336. -105, -100, -95, -90, -82, -74, -62, -57,
  116337. -58, -56, -51, -52, -52, -54, -54, -58,
  116338. -66, -59, -60, -63, -66, -69, -73, -79,
  116339. -83, -84, -80, -81, -81, -82, -88, -92,
  116340. -98, -105, -113, -999, -999, -999, -999, -999,
  116341. -999, -999, -999, -999, -999, -999, -999, -999},
  116342. {-999, -999, -999, -999, -999, -999, -999, -107,
  116343. -102, -97, -92, -84, -79, -69, -57, -47,
  116344. -52, -47, -44, -45, -50, -52, -42, -42,
  116345. -53, -43, -43, -48, -51, -56, -55, -52,
  116346. -57, -59, -61, -62, -67, -71, -78, -83,
  116347. -86, -94, -98, -103, -110, -999, -999, -999,
  116348. -999, -999, -999, -999, -999, -999, -999, -999},
  116349. {-999, -999, -999, -999, -999, -999, -105, -100,
  116350. -95, -90, -84, -78, -70, -61, -51, -41,
  116351. -40, -38, -40, -46, -52, -51, -41, -40,
  116352. -46, -40, -38, -38, -41, -46, -41, -46,
  116353. -47, -43, -43, -45, -41, -45, -56, -67,
  116354. -68, -83, -87, -90, -95, -102, -107, -113,
  116355. -999, -999, -999, -999, -999, -999, -999, -999}},
  116356. /* 1000 Hz */
  116357. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116358. -999, -109, -105, -101, -96, -91, -84, -77,
  116359. -82, -82, -85, -89, -94, -100, -106, -110,
  116360. -999, -999, -999, -999, -999, -999, -999, -999,
  116361. -999, -999, -999, -999, -999, -999, -999, -999,
  116362. -999, -999, -999, -999, -999, -999, -999, -999,
  116363. -999, -999, -999, -999, -999, -999, -999, -999},
  116364. {-999, -999, -999, -999, -999, -999, -999, -999,
  116365. -999, -106, -103, -98, -92, -85, -80, -71,
  116366. -75, -72, -76, -80, -84, -86, -89, -93,
  116367. -100, -107, -113, -999, -999, -999, -999, -999,
  116368. -999, -999, -999, -999, -999, -999, -999, -999,
  116369. -999, -999, -999, -999, -999, -999, -999, -999,
  116370. -999, -999, -999, -999, -999, -999, -999, -999},
  116371. {-999, -999, -999, -999, -999, -999, -999, -107,
  116372. -104, -101, -97, -92, -88, -84, -80, -64,
  116373. -66, -63, -64, -66, -69, -73, -77, -83,
  116374. -83, -86, -91, -98, -104, -111, -999, -999,
  116375. -999, -999, -999, -999, -999, -999, -999, -999,
  116376. -999, -999, -999, -999, -999, -999, -999, -999,
  116377. -999, -999, -999, -999, -999, -999, -999, -999},
  116378. {-999, -999, -999, -999, -999, -999, -999, -107,
  116379. -104, -101, -97, -92, -90, -84, -74, -57,
  116380. -58, -52, -55, -54, -50, -52, -50, -52,
  116381. -63, -62, -69, -76, -77, -78, -78, -79,
  116382. -82, -88, -94, -100, -106, -111, -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, -106, -102,
  116386. -98, -95, -90, -85, -83, -78, -70, -50,
  116387. -50, -41, -44, -49, -47, -50, -50, -44,
  116388. -55, -46, -47, -48, -48, -54, -49, -49,
  116389. -58, -62, -71, -81, -87, -92, -97, -102,
  116390. -108, -114, -999, -999, -999, -999, -999, -999,
  116391. -999, -999, -999, -999, -999, -999, -999, -999},
  116392. {-999, -999, -999, -999, -999, -999, -106, -102,
  116393. -98, -95, -90, -85, -83, -78, -70, -45,
  116394. -43, -41, -47, -50, -51, -50, -49, -45,
  116395. -47, -41, -44, -41, -39, -43, -38, -37,
  116396. -40, -41, -44, -50, -58, -65, -73, -79,
  116397. -85, -92, -97, -101, -105, -109, -113, -999,
  116398. -999, -999, -999, -999, -999, -999, -999, -999}},
  116399. /* 1414 Hz */
  116400. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116401. -999, -999, -999, -107, -100, -95, -87, -81,
  116402. -85, -83, -88, -93, -100, -107, -114, -999,
  116403. -999, -999, -999, -999, -999, -999, -999, -999,
  116404. -999, -999, -999, -999, -999, -999, -999, -999,
  116405. -999, -999, -999, -999, -999, -999, -999, -999,
  116406. -999, -999, -999, -999, -999, -999, -999, -999},
  116407. {-999, -999, -999, -999, -999, -999, -999, -999,
  116408. -999, -999, -107, -101, -95, -88, -83, -76,
  116409. -73, -72, -79, -84, -90, -95, -100, -105,
  116410. -110, -115, -999, -999, -999, -999, -999, -999,
  116411. -999, -999, -999, -999, -999, -999, -999, -999,
  116412. -999, -999, -999, -999, -999, -999, -999, -999,
  116413. -999, -999, -999, -999, -999, -999, -999, -999},
  116414. {-999, -999, -999, -999, -999, -999, -999, -999,
  116415. -999, -999, -104, -98, -92, -87, -81, -70,
  116416. -65, -62, -67, -71, -74, -80, -85, -91,
  116417. -95, -99, -103, -108, -111, -114, -999, -999,
  116418. -999, -999, -999, -999, -999, -999, -999, -999,
  116419. -999, -999, -999, -999, -999, -999, -999, -999,
  116420. -999, -999, -999, -999, -999, -999, -999, -999},
  116421. {-999, -999, -999, -999, -999, -999, -999, -999,
  116422. -999, -999, -103, -97, -90, -85, -76, -60,
  116423. -56, -54, -60, -62, -61, -56, -63, -65,
  116424. -73, -74, -77, -75, -78, -81, -86, -87,
  116425. -88, -91, -94, -98, -103, -110, -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, -105,
  116429. -100, -97, -92, -86, -81, -79, -70, -57,
  116430. -51, -47, -51, -58, -60, -56, -53, -50,
  116431. -58, -52, -50, -50, -53, -55, -64, -69,
  116432. -71, -85, -82, -78, -81, -85, -95, -102,
  116433. -112, -999, -999, -999, -999, -999, -999, -999,
  116434. -999, -999, -999, -999, -999, -999, -999, -999},
  116435. {-999, -999, -999, -999, -999, -999, -999, -105,
  116436. -100, -97, -92, -85, -83, -79, -72, -49,
  116437. -40, -43, -43, -54, -56, -51, -50, -40,
  116438. -43, -38, -36, -35, -37, -38, -37, -44,
  116439. -54, -60, -57, -60, -70, -75, -84, -92,
  116440. -103, -112, -999, -999, -999, -999, -999, -999,
  116441. -999, -999, -999, -999, -999, -999, -999, -999}},
  116442. /* 2000 Hz */
  116443. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116444. -999, -999, -999, -110, -102, -95, -89, -82,
  116445. -83, -84, -90, -92, -99, -107, -113, -999,
  116446. -999, -999, -999, -999, -999, -999, -999, -999,
  116447. -999, -999, -999, -999, -999, -999, -999, -999,
  116448. -999, -999, -999, -999, -999, -999, -999, -999,
  116449. -999, -999, -999, -999, -999, -999, -999, -999},
  116450. {-999, -999, -999, -999, -999, -999, -999, -999,
  116451. -999, -999, -107, -101, -95, -89, -83, -72,
  116452. -74, -78, -85, -88, -88, -90, -92, -98,
  116453. -105, -111, -999, -999, -999, -999, -999, -999,
  116454. -999, -999, -999, -999, -999, -999, -999, -999,
  116455. -999, -999, -999, -999, -999, -999, -999, -999,
  116456. -999, -999, -999, -999, -999, -999, -999, -999},
  116457. {-999, -999, -999, -999, -999, -999, -999, -999,
  116458. -999, -109, -103, -97, -93, -87, -81, -70,
  116459. -70, -67, -75, -73, -76, -79, -81, -83,
  116460. -88, -89, -97, -103, -110, -999, -999, -999,
  116461. -999, -999, -999, -999, -999, -999, -999, -999,
  116462. -999, -999, -999, -999, -999, -999, -999, -999,
  116463. -999, -999, -999, -999, -999, -999, -999, -999},
  116464. {-999, -999, -999, -999, -999, -999, -999, -999,
  116465. -999, -107, -100, -94, -88, -83, -75, -63,
  116466. -59, -59, -63, -66, -60, -62, -67, -67,
  116467. -77, -76, -81, -88, -86, -92, -96, -102,
  116468. -109, -116, -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, -105, -98, -92, -86, -81, -73, -56,
  116473. -52, -47, -55, -60, -58, -52, -51, -45,
  116474. -49, -50, -53, -54, -61, -71, -70, -69,
  116475. -78, -79, -87, -90, -96, -104, -112, -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, -999,
  116479. -999, -103, -96, -90, -86, -78, -70, -51,
  116480. -42, -47, -48, -55, -54, -54, -53, -42,
  116481. -35, -28, -33, -38, -37, -44, -47, -49,
  116482. -54, -63, -68, -78, -82, -89, -94, -99,
  116483. -104, -109, -114, -999, -999, -999, -999, -999,
  116484. -999, -999, -999, -999, -999, -999, -999, -999}},
  116485. /* 2828 Hz */
  116486. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116487. -999, -999, -999, -999, -110, -100, -90, -79,
  116488. -85, -81, -82, -82, -89, -94, -99, -103,
  116489. -109, -115, -999, -999, -999, -999, -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, -999, -999},
  116493. {-999, -999, -999, -999, -999, -999, -999, -999,
  116494. -999, -999, -999, -999, -105, -97, -85, -72,
  116495. -74, -70, -70, -70, -76, -85, -91, -93,
  116496. -97, -103, -109, -115, -999, -999, -999, -999,
  116497. -999, -999, -999, -999, -999, -999, -999, -999,
  116498. -999, -999, -999, -999, -999, -999, -999, -999,
  116499. -999, -999, -999, -999, -999, -999, -999, -999},
  116500. {-999, -999, -999, -999, -999, -999, -999, -999,
  116501. -999, -999, -999, -999, -112, -93, -81, -68,
  116502. -62, -60, -60, -57, -63, -70, -77, -82,
  116503. -90, -93, -98, -104, -109, -113, -999, -999,
  116504. -999, -999, -999, -999, -999, -999, -999, -999,
  116505. -999, -999, -999, -999, -999, -999, -999, -999,
  116506. -999, -999, -999, -999, -999, -999, -999, -999},
  116507. {-999, -999, -999, -999, -999, -999, -999, -999,
  116508. -999, -999, -999, -113, -100, -93, -84, -63,
  116509. -58, -48, -53, -54, -52, -52, -57, -64,
  116510. -66, -76, -83, -81, -85, -85, -90, -95,
  116511. -98, -101, -103, -106, -108, -111, -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, -999, -105, -95, -86, -74, -53,
  116516. -50, -38, -43, -49, -43, -42, -39, -39,
  116517. -46, -52, -57, -56, -72, -69, -74, -81,
  116518. -87, -92, -94, -97, -99, -102, -105, -108,
  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, -108, -99, -90, -76, -66, -45,
  116523. -43, -41, -44, -47, -43, -47, -40, -30,
  116524. -31, -31, -39, -33, -40, -41, -43, -53,
  116525. -59, -70, -73, -77, -79, -82, -84, -87,
  116526. -999, -999, -999, -999, -999, -999, -999, -999,
  116527. -999, -999, -999, -999, -999, -999, -999, -999}},
  116528. /* 4000 Hz */
  116529. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116530. -999, -999, -999, -999, -999, -110, -91, -76,
  116531. -75, -85, -93, -98, -104, -110, -999, -999,
  116532. -999, -999, -999, -999, -999, -999, -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, -999},
  116536. {-999, -999, -999, -999, -999, -999, -999, -999,
  116537. -999, -999, -999, -999, -999, -110, -91, -70,
  116538. -70, -75, -86, -89, -94, -98, -101, -106,
  116539. -110, -999, -999, -999, -999, -999, -999, -999,
  116540. -999, -999, -999, -999, -999, -999, -999, -999,
  116541. -999, -999, -999, -999, -999, -999, -999, -999,
  116542. -999, -999, -999, -999, -999, -999, -999, -999},
  116543. {-999, -999, -999, -999, -999, -999, -999, -999,
  116544. -999, -999, -999, -999, -110, -95, -80, -60,
  116545. -65, -64, -74, -83, -88, -91, -95, -99,
  116546. -103, -107, -110, -999, -999, -999, -999, -999,
  116547. -999, -999, -999, -999, -999, -999, -999, -999,
  116548. -999, -999, -999, -999, -999, -999, -999, -999,
  116549. -999, -999, -999, -999, -999, -999, -999, -999},
  116550. {-999, -999, -999, -999, -999, -999, -999, -999,
  116551. -999, -999, -999, -999, -110, -95, -80, -58,
  116552. -55, -49, -66, -68, -71, -78, -78, -80,
  116553. -88, -85, -89, -97, -100, -105, -110, -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, -999, -999, -110, -95, -80, -53,
  116559. -52, -41, -59, -59, -49, -58, -56, -63,
  116560. -86, -79, -90, -93, -98, -103, -107, -112,
  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, -999, -999, -110, -97, -91, -73, -45,
  116566. -40, -33, -53, -61, -49, -54, -50, -50,
  116567. -60, -52, -67, -74, -81, -92, -96, -100,
  116568. -105, -110, -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. /* 5657 Hz */
  116572. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116573. -999, -999, -999, -113, -106, -99, -92, -77,
  116574. -80, -88, -97, -106, -115, -999, -999, -999,
  116575. -999, -999, -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, -999, -999, -999, -999, -999, -999, -999,
  116580. -999, -999, -116, -109, -102, -95, -89, -74,
  116581. -72, -88, -87, -95, -102, -109, -116, -999,
  116582. -999, -999, -999, -999, -999, -999, -999, -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, -999, -999, -999, -999, -999, -999, -999,
  116587. -999, -999, -116, -109, -102, -95, -89, -75,
  116588. -66, -74, -77, -78, -86, -87, -90, -96,
  116589. -105, -115, -999, -999, -999, -999, -999, -999,
  116590. -999, -999, -999, -999, -999, -999, -999, -999,
  116591. -999, -999, -999, -999, -999, -999, -999, -999,
  116592. -999, -999, -999, -999, -999, -999, -999, -999},
  116593. {-999, -999, -999, -999, -999, -999, -999, -999,
  116594. -999, -999, -115, -108, -101, -94, -88, -66,
  116595. -56, -61, -70, -65, -78, -72, -83, -84,
  116596. -93, -98, -105, -110, -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, -110, -105, -95, -89, -82, -57,
  116602. -52, -52, -59, -56, -59, -58, -69, -67,
  116603. -88, -82, -82, -89, -94, -100, -108, -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, -110, -101, -96, -90, -83, -77, -54,
  116609. -43, -38, -50, -48, -52, -48, -42, -42,
  116610. -51, -52, -53, -59, -65, -71, -78, -85,
  116611. -95, -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. /* 8000 Hz */
  116615. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116616. -999, -999, -999, -999, -120, -105, -86, -68,
  116617. -78, -79, -90, -100, -110, -999, -999, -999,
  116618. -999, -999, -999, -999, -999, -999, -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, -999, -999, -999, -999, -999,
  116623. -999, -999, -999, -999, -120, -105, -86, -66,
  116624. -73, -77, -88, -96, -105, -115, -999, -999,
  116625. -999, -999, -999, -999, -999, -999, -999, -999,
  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, -999, -999, -999, -999, -999, -999,
  116630. -999, -999, -999, -120, -105, -92, -80, -61,
  116631. -64, -68, -80, -87, -92, -100, -110, -999,
  116632. -999, -999, -999, -999, -999, -999, -999, -999,
  116633. -999, -999, -999, -999, -999, -999, -999, -999,
  116634. -999, -999, -999, -999, -999, -999, -999, -999,
  116635. -999, -999, -999, -999, -999, -999, -999, -999},
  116636. {-999, -999, -999, -999, -999, -999, -999, -999,
  116637. -999, -999, -999, -120, -104, -91, -79, -52,
  116638. -60, -54, -64, -69, -77, -80, -82, -84,
  116639. -85, -87, -88, -90, -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, -118, -100, -87, -77, -49,
  116645. -50, -44, -58, -61, -61, -67, -65, -62,
  116646. -62, -62, -65, -68, -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, -115, -98, -84, -62, -49,
  116652. -44, -38, -46, -49, -49, -46, -39, -37,
  116653. -39, -40, -42, -43, -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. /* 11314 Hz */
  116658. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116659. -999, -999, -999, -999, -999, -110, -88, -74,
  116660. -77, -82, -82, -85, -90, -94, -99, -104,
  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, -999, -999, -999, -999,
  116666. -999, -999, -999, -999, -999, -110, -88, -66,
  116667. -70, -81, -80, -81, -84, -88, -91, -93,
  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, -999, -999, -999, -999, -999,
  116673. -999, -999, -999, -999, -999, -110, -88, -61,
  116674. -63, -70, -71, -74, -77, -80, -83, -85,
  116675. -999, -999, -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. -999, -999, -999, -999, -999, -999, -999, -999},
  116679. {-999, -999, -999, -999, -999, -999, -999, -999,
  116680. -999, -999, -999, -999, -999, -110, -86, -62,
  116681. -63, -62, -62, -58, -52, -50, -50, -52,
  116682. -54, -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, -999, -999, -118, -108, -84, -53,
  116688. -50, -50, -50, -55, -47, -45, -40, -40,
  116689. -40, -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, -999, -999, -118, -100, -73, -43,
  116695. -37, -42, -43, -53, -38, -37, -35, -35,
  116696. -38, -999, -999, -999, -999, -999, -999, -999,
  116697. -999, -999, -999, -999, -999, -999, -999, -999,
  116698. -999, -999, -999, -999, -999, -999, -999, -999,
  116699. -999, -999, -999, -999, -999, -999, -999, -999}},
  116700. /* 16000 Hz */
  116701. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116702. -999, -999, -999, -110, -100, -91, -84, -74,
  116703. -80, -80, -80, -80, -80, -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, -999, -999, -999, -999, -999, -999,
  116709. -999, -999, -999, -110, -100, -91, -84, -74,
  116710. -68, -68, -68, -68, -68, -999, -999, -999,
  116711. -999, -999, -999, -999, -999, -999, -999, -999,
  116712. -999, -999, -999, -999, -999, -999, -999, -999,
  116713. -999, -999, -999, -999, -999, -999, -999, -999,
  116714. -999, -999, -999, -999, -999, -999, -999, -999},
  116715. {-999, -999, -999, -999, -999, -999, -999, -999,
  116716. -999, -999, -999, -110, -100, -86, -78, -70,
  116717. -60, -45, -30, -21, -999, -999, -999, -999,
  116718. -999, -999, -999, -999, -999, -999, -999, -999,
  116719. -999, -999, -999, -999, -999, -999, -999, -999,
  116720. -999, -999, -999, -999, -999, -999, -999, -999,
  116721. -999, -999, -999, -999, -999, -999, -999, -999},
  116722. {-999, -999, -999, -999, -999, -999, -999, -999,
  116723. -999, -999, -999, -110, -100, -87, -78, -67,
  116724. -48, -38, -29, -21, -999, -999, -999, -999,
  116725. -999, -999, -999, -999, -999, -999, -999, -999,
  116726. -999, -999, -999, -999, -999, -999, -999, -999,
  116727. -999, -999, -999, -999, -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, -110, -100, -86, -69, -56,
  116731. -45, -35, -33, -29, -999, -999, -999, -999,
  116732. -999, -999, -999, -999, -999, -999, -999, -999,
  116733. -999, -999, -999, -999, -999, -999, -999, -999,
  116734. -999, -999, -999, -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, -110, -100, -83, -71, -48,
  116738. -27, -38, -37, -34, -999, -999, -999, -999,
  116739. -999, -999, -999, -999, -999, -999, -999, -999,
  116740. -999, -999, -999, -999, -999, -999, -999, -999,
  116741. -999, -999, -999, -999, -999, -999, -999, -999,
  116742. -999, -999, -999, -999, -999, -999, -999, -999}}
  116743. };
  116744. #endif
  116745. /*** End of inlined file: masking.h ***/
  116746. #define NEGINF -9999.f
  116747. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  116748. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  116749. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  116750. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116751. vorbis_info_psy_global *gi=&ci->psy_g_param;
  116752. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  116753. look->channels=vi->channels;
  116754. look->ampmax=-9999.;
  116755. look->gi=gi;
  116756. return(look);
  116757. }
  116758. void _vp_global_free(vorbis_look_psy_global *look){
  116759. if(look){
  116760. memset(look,0,sizeof(*look));
  116761. _ogg_free(look);
  116762. }
  116763. }
  116764. void _vi_gpsy_free(vorbis_info_psy_global *i){
  116765. if(i){
  116766. memset(i,0,sizeof(*i));
  116767. _ogg_free(i);
  116768. }
  116769. }
  116770. void _vi_psy_free(vorbis_info_psy *i){
  116771. if(i){
  116772. memset(i,0,sizeof(*i));
  116773. _ogg_free(i);
  116774. }
  116775. }
  116776. static void min_curve(float *c,
  116777. float *c2){
  116778. int i;
  116779. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  116780. }
  116781. static void max_curve(float *c,
  116782. float *c2){
  116783. int i;
  116784. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  116785. }
  116786. static void attenuate_curve(float *c,float att){
  116787. int i;
  116788. for(i=0;i<EHMER_MAX;i++)
  116789. c[i]+=att;
  116790. }
  116791. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  116792. float center_boost, float center_decay_rate){
  116793. int i,j,k,m;
  116794. float ath[EHMER_MAX];
  116795. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  116796. float athc[P_LEVELS][EHMER_MAX];
  116797. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  116798. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  116799. memset(workc,0,sizeof(workc));
  116800. for(i=0;i<P_BANDS;i++){
  116801. /* we add back in the ATH to avoid low level curves falling off to
  116802. -infinity and unnecessarily cutting off high level curves in the
  116803. curve limiting (last step). */
  116804. /* A half-band's settings must be valid over the whole band, and
  116805. it's better to mask too little than too much */
  116806. int ath_offset=i*4;
  116807. for(j=0;j<EHMER_MAX;j++){
  116808. float min=999.;
  116809. for(k=0;k<4;k++)
  116810. if(j+k+ath_offset<MAX_ATH){
  116811. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  116812. }else{
  116813. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  116814. }
  116815. ath[j]=min;
  116816. }
  116817. /* copy curves into working space, replicate the 50dB curve to 30
  116818. and 40, replicate the 100dB curve to 110 */
  116819. for(j=0;j<6;j++)
  116820. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  116821. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116822. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116823. /* apply centered curve boost/decay */
  116824. for(j=0;j<P_LEVELS;j++){
  116825. for(k=0;k<EHMER_MAX;k++){
  116826. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  116827. if(adj<0. && center_boost>0)adj=0.;
  116828. if(adj>0. && center_boost<0)adj=0.;
  116829. workc[i][j][k]+=adj;
  116830. }
  116831. }
  116832. /* normalize curves so the driving amplitude is 0dB */
  116833. /* make temp curves with the ATH overlayed */
  116834. for(j=0;j<P_LEVELS;j++){
  116835. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  116836. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  116837. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  116838. max_curve(athc[j],workc[i][j]);
  116839. }
  116840. /* Now limit the louder curves.
  116841. the idea is this: We don't know what the playback attenuation
  116842. will be; 0dB SL moves every time the user twiddles the volume
  116843. knob. So that means we have to use a single 'most pessimal' curve
  116844. for all masking amplitudes, right? Wrong. The *loudest* sound
  116845. can be in (we assume) a range of ...+100dB] SL. However, sounds
  116846. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  116847. etc... */
  116848. for(j=1;j<P_LEVELS;j++){
  116849. min_curve(athc[j],athc[j-1]);
  116850. min_curve(workc[i][j],athc[j]);
  116851. }
  116852. }
  116853. for(i=0;i<P_BANDS;i++){
  116854. int hi_curve,lo_curve,bin;
  116855. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  116856. /* low frequency curves are measured with greater resolution than
  116857. the MDCT/FFT will actually give us; we want the curve applied
  116858. to the tone data to be pessimistic and thus apply the minimum
  116859. masking possible for a given bin. That means that a single bin
  116860. could span more than one octave and that the curve will be a
  116861. composite of multiple octaves. It also may mean that a single
  116862. bin may span > an eighth of an octave and that the eighth
  116863. octave values may also be composited. */
  116864. /* which octave curves will we be compositing? */
  116865. bin=floor(fromOC(i*.5)/binHz);
  116866. lo_curve= ceil(toOC(bin*binHz+1)*2);
  116867. hi_curve= floor(toOC((bin+1)*binHz)*2);
  116868. if(lo_curve>i)lo_curve=i;
  116869. if(lo_curve<0)lo_curve=0;
  116870. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  116871. for(m=0;m<P_LEVELS;m++){
  116872. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  116873. for(j=0;j<n;j++)brute_buffer[j]=999.;
  116874. /* render the curve into bins, then pull values back into curve.
  116875. The point is that any inherent subsampling aliasing results in
  116876. a safe minimum */
  116877. for(k=lo_curve;k<=hi_curve;k++){
  116878. int l=0;
  116879. for(j=0;j<EHMER_MAX;j++){
  116880. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  116881. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  116882. if(lo_bin<0)lo_bin=0;
  116883. if(lo_bin>n)lo_bin=n;
  116884. if(lo_bin<l)l=lo_bin;
  116885. if(hi_bin<0)hi_bin=0;
  116886. if(hi_bin>n)hi_bin=n;
  116887. for(;l<hi_bin && l<n;l++)
  116888. if(brute_buffer[l]>workc[k][m][j])
  116889. brute_buffer[l]=workc[k][m][j];
  116890. }
  116891. for(;l<n;l++)
  116892. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116893. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116894. }
  116895. /* be equally paranoid about being valid up to next half ocatve */
  116896. if(i+1<P_BANDS){
  116897. int l=0;
  116898. k=i+1;
  116899. for(j=0;j<EHMER_MAX;j++){
  116900. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  116901. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  116902. if(lo_bin<0)lo_bin=0;
  116903. if(lo_bin>n)lo_bin=n;
  116904. if(lo_bin<l)l=lo_bin;
  116905. if(hi_bin<0)hi_bin=0;
  116906. if(hi_bin>n)hi_bin=n;
  116907. for(;l<hi_bin && l<n;l++)
  116908. if(brute_buffer[l]>workc[k][m][j])
  116909. brute_buffer[l]=workc[k][m][j];
  116910. }
  116911. for(;l<n;l++)
  116912. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116913. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116914. }
  116915. for(j=0;j<EHMER_MAX;j++){
  116916. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  116917. if(bin<0){
  116918. ret[i][m][j+2]=-999.;
  116919. }else{
  116920. if(bin>=n){
  116921. ret[i][m][j+2]=-999.;
  116922. }else{
  116923. ret[i][m][j+2]=brute_buffer[bin];
  116924. }
  116925. }
  116926. }
  116927. /* add fenceposts */
  116928. for(j=0;j<EHMER_OFFSET;j++)
  116929. if(ret[i][m][j+2]>-200.f)break;
  116930. ret[i][m][0]=j;
  116931. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  116932. if(ret[i][m][j+2]>-200.f)
  116933. break;
  116934. ret[i][m][1]=j;
  116935. }
  116936. }
  116937. return(ret);
  116938. }
  116939. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  116940. vorbis_info_psy_global *gi,int n,long rate){
  116941. long i,j,lo=-99,hi=1;
  116942. long maxoc;
  116943. memset(p,0,sizeof(*p));
  116944. p->eighth_octave_lines=gi->eighth_octave_lines;
  116945. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  116946. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  116947. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  116948. p->total_octave_lines=maxoc-p->firstoc+1;
  116949. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  116950. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  116951. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  116952. p->vi=vi;
  116953. p->n=n;
  116954. p->rate=rate;
  116955. /* AoTuV HF weighting */
  116956. p->m_val = 1.;
  116957. if(rate < 26000) p->m_val = 0;
  116958. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  116959. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  116960. /* set up the lookups for a given blocksize and sample rate */
  116961. for(i=0,j=0;i<MAX_ATH-1;i++){
  116962. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  116963. float base=ATH[i];
  116964. if(j<endpos){
  116965. float delta=(ATH[i+1]-base)/(endpos-j);
  116966. for(;j<endpos && j<n;j++){
  116967. p->ath[j]=base+100.;
  116968. base+=delta;
  116969. }
  116970. }
  116971. }
  116972. for(i=0;i<n;i++){
  116973. float bark=toBARK(rate/(2*n)*i);
  116974. for(;lo+vi->noisewindowlomin<i &&
  116975. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  116976. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  116977. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  116978. p->bark[i]=((lo-1)<<16)+(hi-1);
  116979. }
  116980. for(i=0;i<n;i++)
  116981. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  116982. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  116983. vi->tone_centerboost,vi->tone_decay);
  116984. /* set up rolling noise median */
  116985. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  116986. for(i=0;i<P_NOISECURVES;i++)
  116987. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  116988. for(i=0;i<n;i++){
  116989. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  116990. int inthalfoc;
  116991. float del;
  116992. if(halfoc<0)halfoc=0;
  116993. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  116994. inthalfoc=(int)halfoc;
  116995. del=halfoc-inthalfoc;
  116996. for(j=0;j<P_NOISECURVES;j++)
  116997. p->noiseoffset[j][i]=
  116998. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  116999. p->vi->noiseoff[j][inthalfoc+1]*del;
  117000. }
  117001. #if 0
  117002. {
  117003. static int ls=0;
  117004. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  117005. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  117006. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117007. }
  117008. #endif
  117009. }
  117010. void _vp_psy_clear(vorbis_look_psy *p){
  117011. int i,j;
  117012. if(p){
  117013. if(p->ath)_ogg_free(p->ath);
  117014. if(p->octave)_ogg_free(p->octave);
  117015. if(p->bark)_ogg_free(p->bark);
  117016. if(p->tonecurves){
  117017. for(i=0;i<P_BANDS;i++){
  117018. for(j=0;j<P_LEVELS;j++){
  117019. _ogg_free(p->tonecurves[i][j]);
  117020. }
  117021. _ogg_free(p->tonecurves[i]);
  117022. }
  117023. _ogg_free(p->tonecurves);
  117024. }
  117025. if(p->noiseoffset){
  117026. for(i=0;i<P_NOISECURVES;i++){
  117027. _ogg_free(p->noiseoffset[i]);
  117028. }
  117029. _ogg_free(p->noiseoffset);
  117030. }
  117031. memset(p,0,sizeof(*p));
  117032. }
  117033. }
  117034. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117035. static void seed_curve(float *seed,
  117036. const float **curves,
  117037. float amp,
  117038. int oc, int n,
  117039. int linesper,float dBoffset){
  117040. int i,post1;
  117041. int seedptr;
  117042. const float *posts,*curve;
  117043. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117044. choice=max(choice,0);
  117045. choice=min(choice,P_LEVELS-1);
  117046. posts=curves[choice];
  117047. curve=posts+2;
  117048. post1=(int)posts[1];
  117049. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117050. for(i=posts[0];i<post1;i++){
  117051. if(seedptr>0){
  117052. float lin=amp+curve[i];
  117053. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117054. }
  117055. seedptr+=linesper;
  117056. if(seedptr>=n)break;
  117057. }
  117058. }
  117059. static void seed_loop(vorbis_look_psy *p,
  117060. const float ***curves,
  117061. const float *f,
  117062. const float *flr,
  117063. float *seed,
  117064. float specmax){
  117065. vorbis_info_psy *vi=p->vi;
  117066. long n=p->n,i;
  117067. float dBoffset=vi->max_curve_dB-specmax;
  117068. /* prime the working vector with peak values */
  117069. for(i=0;i<n;i++){
  117070. float max=f[i];
  117071. long oc=p->octave[i];
  117072. while(i+1<n && p->octave[i+1]==oc){
  117073. i++;
  117074. if(f[i]>max)max=f[i];
  117075. }
  117076. if(max+6.f>flr[i]){
  117077. oc=oc>>p->shiftoc;
  117078. if(oc>=P_BANDS)oc=P_BANDS-1;
  117079. if(oc<0)oc=0;
  117080. seed_curve(seed,
  117081. curves[oc],
  117082. max,
  117083. p->octave[i]-p->firstoc,
  117084. p->total_octave_lines,
  117085. p->eighth_octave_lines,
  117086. dBoffset);
  117087. }
  117088. }
  117089. }
  117090. static void seed_chase(float *seeds, int linesper, long n){
  117091. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117092. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117093. long stack=0;
  117094. long pos=0;
  117095. long i;
  117096. for(i=0;i<n;i++){
  117097. if(stack<2){
  117098. posstack[stack]=i;
  117099. ampstack[stack++]=seeds[i];
  117100. }else{
  117101. while(1){
  117102. if(seeds[i]<ampstack[stack-1]){
  117103. posstack[stack]=i;
  117104. ampstack[stack++]=seeds[i];
  117105. break;
  117106. }else{
  117107. if(i<posstack[stack-1]+linesper){
  117108. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117109. i<posstack[stack-2]+linesper){
  117110. /* we completely overlap, making stack-1 irrelevant. pop it */
  117111. stack--;
  117112. continue;
  117113. }
  117114. }
  117115. posstack[stack]=i;
  117116. ampstack[stack++]=seeds[i];
  117117. break;
  117118. }
  117119. }
  117120. }
  117121. }
  117122. /* the stack now contains only the positions that are relevant. Scan
  117123. 'em straight through */
  117124. for(i=0;i<stack;i++){
  117125. long endpos;
  117126. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117127. endpos=posstack[i+1];
  117128. }else{
  117129. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117130. discarded in short frames */
  117131. }
  117132. if(endpos>n)endpos=n;
  117133. for(;pos<endpos;pos++)
  117134. seeds[pos]=ampstack[i];
  117135. }
  117136. /* there. Linear time. I now remember this was on a problem set I
  117137. had in Grad Skool... I didn't solve it at the time ;-) */
  117138. }
  117139. /* bleaugh, this is more complicated than it needs to be */
  117140. #include<stdio.h>
  117141. static void max_seeds(vorbis_look_psy *p,
  117142. float *seed,
  117143. float *flr){
  117144. long n=p->total_octave_lines;
  117145. int linesper=p->eighth_octave_lines;
  117146. long linpos=0;
  117147. long pos;
  117148. seed_chase(seed,linesper,n); /* for masking */
  117149. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117150. while(linpos+1<p->n){
  117151. float minV=seed[pos];
  117152. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117153. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117154. while(pos+1<=end){
  117155. pos++;
  117156. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117157. minV=seed[pos];
  117158. }
  117159. end=pos+p->firstoc;
  117160. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117161. if(flr[linpos]<minV)flr[linpos]=minV;
  117162. }
  117163. {
  117164. float minV=seed[p->total_octave_lines-1];
  117165. for(;linpos<p->n;linpos++)
  117166. if(flr[linpos]<minV)flr[linpos]=minV;
  117167. }
  117168. }
  117169. static void bark_noise_hybridmp(int n,const long *b,
  117170. const float *f,
  117171. float *noise,
  117172. const float offset,
  117173. const int fixed){
  117174. float *N=(float*) alloca(n*sizeof(*N));
  117175. float *X=(float*) alloca(n*sizeof(*N));
  117176. float *XX=(float*) alloca(n*sizeof(*N));
  117177. float *Y=(float*) alloca(n*sizeof(*N));
  117178. float *XY=(float*) alloca(n*sizeof(*N));
  117179. float tN, tX, tXX, tY, tXY;
  117180. int i;
  117181. int lo, hi;
  117182. float R, A, B, D;
  117183. float w, x, y;
  117184. tN = tX = tXX = tY = tXY = 0.f;
  117185. y = f[0] + offset;
  117186. if (y < 1.f) y = 1.f;
  117187. w = y * y * .5;
  117188. tN += w;
  117189. tX += w;
  117190. tY += w * y;
  117191. N[0] = tN;
  117192. X[0] = tX;
  117193. XX[0] = tXX;
  117194. Y[0] = tY;
  117195. XY[0] = tXY;
  117196. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117197. y = f[i] + offset;
  117198. if (y < 1.f) y = 1.f;
  117199. w = y * y;
  117200. tN += w;
  117201. tX += w * x;
  117202. tXX += w * x * x;
  117203. tY += w * y;
  117204. tXY += w * x * y;
  117205. N[i] = tN;
  117206. X[i] = tX;
  117207. XX[i] = tXX;
  117208. Y[i] = tY;
  117209. XY[i] = tXY;
  117210. }
  117211. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117212. lo = b[i] >> 16;
  117213. if( lo>=0 ) break;
  117214. hi = b[i] & 0xffff;
  117215. tN = N[hi] + N[-lo];
  117216. tX = X[hi] - X[-lo];
  117217. tXX = XX[hi] + XX[-lo];
  117218. tY = Y[hi] + Y[-lo];
  117219. tXY = XY[hi] - XY[-lo];
  117220. A = tY * tXX - tX * tXY;
  117221. B = tN * tXY - tX * tY;
  117222. D = tN * tXX - tX * tX;
  117223. R = (A + x * B) / D;
  117224. if (R < 0.f)
  117225. R = 0.f;
  117226. noise[i] = R - offset;
  117227. }
  117228. for ( ;; i++, x += 1.f) {
  117229. lo = b[i] >> 16;
  117230. hi = b[i] & 0xffff;
  117231. if(hi>=n)break;
  117232. tN = N[hi] - N[lo];
  117233. tX = X[hi] - X[lo];
  117234. tXX = XX[hi] - XX[lo];
  117235. tY = Y[hi] - Y[lo];
  117236. tXY = XY[hi] - XY[lo];
  117237. A = tY * tXX - tX * tXY;
  117238. B = tN * tXY - tX * tY;
  117239. D = tN * tXX - tX * tX;
  117240. R = (A + x * B) / D;
  117241. if (R < 0.f) R = 0.f;
  117242. noise[i] = R - offset;
  117243. }
  117244. for ( ; i < n; i++, x += 1.f) {
  117245. R = (A + x * B) / D;
  117246. if (R < 0.f) R = 0.f;
  117247. noise[i] = R - offset;
  117248. }
  117249. if (fixed <= 0) return;
  117250. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117251. hi = i + fixed / 2;
  117252. lo = hi - fixed;
  117253. if(lo>=0)break;
  117254. tN = N[hi] + N[-lo];
  117255. tX = X[hi] - X[-lo];
  117256. tXX = XX[hi] + XX[-lo];
  117257. tY = Y[hi] + Y[-lo];
  117258. tXY = XY[hi] - XY[-lo];
  117259. A = tY * tXX - tX * tXY;
  117260. B = tN * tXY - tX * tY;
  117261. D = tN * tXX - tX * tX;
  117262. R = (A + x * B) / D;
  117263. if (R - offset < noise[i]) noise[i] = R - offset;
  117264. }
  117265. for ( ;; i++, x += 1.f) {
  117266. hi = i + fixed / 2;
  117267. lo = hi - fixed;
  117268. if(hi>=n)break;
  117269. tN = N[hi] - N[lo];
  117270. tX = X[hi] - X[lo];
  117271. tXX = XX[hi] - XX[lo];
  117272. tY = Y[hi] - Y[lo];
  117273. tXY = XY[hi] - XY[lo];
  117274. A = tY * tXX - tX * tXY;
  117275. B = tN * tXY - tX * tY;
  117276. D = tN * tXX - tX * tX;
  117277. R = (A + x * B) / D;
  117278. if (R - offset < noise[i]) noise[i] = R - offset;
  117279. }
  117280. for ( ; i < n; i++, x += 1.f) {
  117281. R = (A + x * B) / D;
  117282. if (R - offset < noise[i]) noise[i] = R - offset;
  117283. }
  117284. }
  117285. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117286. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117287. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117288. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117289. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117290. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117291. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117292. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117293. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117294. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117295. 973377.F, 913981.F, 858210.F, 805842.F,
  117296. 756669.F, 710497.F, 667142.F, 626433.F,
  117297. 588208.F, 552316.F, 518613.F, 486967.F,
  117298. 457252.F, 429351.F, 403152.F, 378551.F,
  117299. 355452.F, 333762.F, 313396.F, 294273.F,
  117300. 276316.F, 259455.F, 243623.F, 228757.F,
  117301. 214798.F, 201691.F, 189384.F, 177828.F,
  117302. 166977.F, 156788.F, 147221.F, 138237.F,
  117303. 129802.F, 121881.F, 114444.F, 107461.F,
  117304. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117305. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117306. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117307. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117308. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117309. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117310. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117311. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117312. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117313. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117314. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117315. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117316. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117317. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117318. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117319. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117320. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117321. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117322. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117323. 842.910F, 791.475F, 743.179F, 697.830F,
  117324. 655.249F, 615.265F, 577.722F, 542.469F,
  117325. 509.367F, 478.286F, 449.101F, 421.696F,
  117326. 395.964F, 371.803F, 349.115F, 327.812F,
  117327. 307.809F, 289.026F, 271.390F, 254.830F,
  117328. 239.280F, 224.679F, 210.969F, 198.096F,
  117329. 186.008F, 174.658F, 164.000F, 153.993F,
  117330. 144.596F, 135.773F, 127.488F, 119.708F,
  117331. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117332. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117333. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117334. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117335. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117336. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117337. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117338. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117339. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117340. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117341. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117342. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117343. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117344. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117345. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117346. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117347. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117348. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117349. 1.20790F, 1.13419F, 1.06499F, 1.F
  117350. };
  117351. void _vp_remove_floor(vorbis_look_psy *p,
  117352. float *mdct,
  117353. int *codedflr,
  117354. float *residue,
  117355. int sliding_lowpass){
  117356. int i,n=p->n;
  117357. if(sliding_lowpass>n)sliding_lowpass=n;
  117358. for(i=0;i<sliding_lowpass;i++){
  117359. residue[i]=
  117360. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117361. }
  117362. for(;i<n;i++)
  117363. residue[i]=0.;
  117364. }
  117365. void _vp_noisemask(vorbis_look_psy *p,
  117366. float *logmdct,
  117367. float *logmask){
  117368. int i,n=p->n;
  117369. float *work=(float*) alloca(n*sizeof(*work));
  117370. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117371. 140.,-1);
  117372. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117373. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117374. p->vi->noisewindowfixed);
  117375. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117376. #if 0
  117377. {
  117378. static int seq=0;
  117379. float work2[n];
  117380. for(i=0;i<n;i++){
  117381. work2[i]=logmask[i]+work[i];
  117382. }
  117383. if(seq&1)
  117384. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117385. else
  117386. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117387. if(seq&1)
  117388. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117389. else
  117390. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117391. seq++;
  117392. }
  117393. #endif
  117394. for(i=0;i<n;i++){
  117395. int dB=logmask[i]+.5;
  117396. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117397. if(dB<0)dB=0;
  117398. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117399. }
  117400. }
  117401. void _vp_tonemask(vorbis_look_psy *p,
  117402. float *logfft,
  117403. float *logmask,
  117404. float global_specmax,
  117405. float local_specmax){
  117406. int i,n=p->n;
  117407. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117408. float att=local_specmax+p->vi->ath_adjatt;
  117409. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117410. /* set the ATH (floating below localmax, not global max by a
  117411. specified att) */
  117412. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117413. for(i=0;i<n;i++)
  117414. logmask[i]=p->ath[i]+att;
  117415. /* tone masking */
  117416. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117417. max_seeds(p,seed,logmask);
  117418. }
  117419. void _vp_offset_and_mix(vorbis_look_psy *p,
  117420. float *noise,
  117421. float *tone,
  117422. int offset_select,
  117423. float *logmask,
  117424. float *mdct,
  117425. float *logmdct){
  117426. int i,n=p->n;
  117427. float de, coeffi, cx;/* AoTuV */
  117428. float toneatt=p->vi->tone_masteratt[offset_select];
  117429. cx = p->m_val;
  117430. for(i=0;i<n;i++){
  117431. float val= noise[i]+p->noiseoffset[offset_select][i];
  117432. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117433. logmask[i]=max(val,tone[i]+toneatt);
  117434. /* AoTuV */
  117435. /** @ M1 **
  117436. The following codes improve a noise problem.
  117437. A fundamental idea uses the value of masking and carries out
  117438. the relative compensation of the MDCT.
  117439. However, this code is not perfect and all noise problems cannot be solved.
  117440. by Aoyumi @ 2004/04/18
  117441. */
  117442. if(offset_select == 1) {
  117443. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117444. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117445. if(val > coeffi){
  117446. /* mdct value is > -17.2 dB below floor */
  117447. de = 1.0-((val-coeffi)*0.005*cx);
  117448. /* pro-rated attenuation:
  117449. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117450. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117451. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117452. etc... */
  117453. if(de < 0) de = 0.0001;
  117454. }else
  117455. /* mdct value is <= -17.2 dB below floor */
  117456. de = 1.0-((val-coeffi)*0.0003*cx);
  117457. /* pro-rated attenuation:
  117458. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117459. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117460. etc... */
  117461. mdct[i] *= de;
  117462. }
  117463. }
  117464. }
  117465. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117466. vorbis_info *vi=vd->vi;
  117467. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117468. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117469. int n=ci->blocksizes[vd->W]/2;
  117470. float secs=(float)n/vi->rate;
  117471. amp+=secs*gi->ampmax_att_per_sec;
  117472. if(amp<-9999)amp=-9999;
  117473. return(amp);
  117474. }
  117475. static void couple_lossless(float A, float B,
  117476. float *qA, float *qB){
  117477. int test1=fabs(*qA)>fabs(*qB);
  117478. test1-= fabs(*qA)<fabs(*qB);
  117479. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117480. if(test1==1){
  117481. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117482. }else{
  117483. float temp=*qB;
  117484. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117485. *qA=temp;
  117486. }
  117487. if(*qB>fabs(*qA)*1.9999f){
  117488. *qB= -fabs(*qA)*2.f;
  117489. *qA= -*qA;
  117490. }
  117491. }
  117492. static float hypot_lookup[32]={
  117493. -0.009935, -0.011245, -0.012726, -0.014397,
  117494. -0.016282, -0.018407, -0.020800, -0.023494,
  117495. -0.026522, -0.029923, -0.033737, -0.038010,
  117496. -0.042787, -0.048121, -0.054064, -0.060671,
  117497. -0.068000, -0.076109, -0.085054, -0.094892,
  117498. -0.105675, -0.117451, -0.130260, -0.144134,
  117499. -0.159093, -0.175146, -0.192286, -0.210490,
  117500. -0.229718, -0.249913, -0.271001, -0.292893};
  117501. static void precomputed_couple_point(float premag,
  117502. int floorA,int floorB,
  117503. float *mag, float *ang){
  117504. int test=(floorA>floorB)-1;
  117505. int offset=31-abs(floorA-floorB);
  117506. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  117507. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  117508. *mag=premag*floormag;
  117509. *ang=0.f;
  117510. }
  117511. /* just like below, this is currently set up to only do
  117512. single-step-depth coupling. Otherwise, we'd have to do more
  117513. copying (which will be inevitable later) */
  117514. /* doing the real circular magnitude calculation is audibly superior
  117515. to (A+B)/sqrt(2) */
  117516. static float dipole_hypot(float a, float b){
  117517. if(a>0.){
  117518. if(b>0.)return sqrt(a*a+b*b);
  117519. if(a>-b)return sqrt(a*a-b*b);
  117520. return -sqrt(b*b-a*a);
  117521. }
  117522. if(b<0.)return -sqrt(a*a+b*b);
  117523. if(-a>b)return -sqrt(a*a-b*b);
  117524. return sqrt(b*b-a*a);
  117525. }
  117526. static float round_hypot(float a, float b){
  117527. if(a>0.){
  117528. if(b>0.)return sqrt(a*a+b*b);
  117529. if(a>-b)return sqrt(a*a+b*b);
  117530. return -sqrt(b*b+a*a);
  117531. }
  117532. if(b<0.)return -sqrt(a*a+b*b);
  117533. if(-a>b)return -sqrt(a*a+b*b);
  117534. return sqrt(b*b+a*a);
  117535. }
  117536. /* revert to round hypot for now */
  117537. float **_vp_quantize_couple_memo(vorbis_block *vb,
  117538. vorbis_info_psy_global *g,
  117539. vorbis_look_psy *p,
  117540. vorbis_info_mapping0 *vi,
  117541. float **mdct){
  117542. int i,j,n=p->n;
  117543. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117544. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117545. for(i=0;i<vi->coupling_steps;i++){
  117546. float *mdctM=mdct[vi->coupling_mag[i]];
  117547. float *mdctA=mdct[vi->coupling_ang[i]];
  117548. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117549. for(j=0;j<limit;j++)
  117550. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  117551. for(;j<n;j++)
  117552. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  117553. }
  117554. return(ret);
  117555. }
  117556. /* this is for per-channel noise normalization */
  117557. static int JUCE_CDECL apsort(const void *a, const void *b){
  117558. float f1=fabs(**(float**)a);
  117559. float f2=fabs(**(float**)b);
  117560. return (f1<f2)-(f1>f2);
  117561. }
  117562. int **_vp_quantize_couple_sort(vorbis_block *vb,
  117563. vorbis_look_psy *p,
  117564. vorbis_info_mapping0 *vi,
  117565. float **mags){
  117566. if(p->vi->normal_point_p){
  117567. int i,j,k,n=p->n;
  117568. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117569. int partition=p->vi->normal_partition;
  117570. float **work=(float**) alloca(sizeof(*work)*partition);
  117571. for(i=0;i<vi->coupling_steps;i++){
  117572. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117573. for(j=0;j<n;j+=partition){
  117574. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117575. qsort(work,partition,sizeof(*work),apsort);
  117576. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117577. }
  117578. }
  117579. return(ret);
  117580. }
  117581. return(NULL);
  117582. }
  117583. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117584. float *magnitudes,int *sortedindex){
  117585. int i,j,n=p->n;
  117586. vorbis_info_psy *vi=p->vi;
  117587. int partition=vi->normal_partition;
  117588. float **work=(float**) alloca(sizeof(*work)*partition);
  117589. int start=vi->normal_start;
  117590. for(j=start;j<n;j+=partition){
  117591. if(j+partition>n)partition=n-j;
  117592. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117593. qsort(work,partition,sizeof(*work),apsort);
  117594. for(i=0;i<partition;i++){
  117595. sortedindex[i+j-start]=work[i]-magnitudes;
  117596. }
  117597. }
  117598. }
  117599. void _vp_noise_normalize(vorbis_look_psy *p,
  117600. float *in,float *out,int *sortedindex){
  117601. int flag=0,i,j=0,n=p->n;
  117602. vorbis_info_psy *vi=p->vi;
  117603. int partition=vi->normal_partition;
  117604. int start=vi->normal_start;
  117605. if(start>n)start=n;
  117606. if(vi->normal_channel_p){
  117607. for(;j<start;j++)
  117608. out[j]=rint(in[j]);
  117609. for(;j+partition<=n;j+=partition){
  117610. float acc=0.;
  117611. int k;
  117612. for(i=j;i<j+partition;i++)
  117613. acc+=in[i]*in[i];
  117614. for(i=0;i<partition;i++){
  117615. k=sortedindex[i+j-start];
  117616. if(in[k]*in[k]>=.25f){
  117617. out[k]=rint(in[k]);
  117618. acc-=in[k]*in[k];
  117619. flag=1;
  117620. }else{
  117621. if(acc<vi->normal_thresh)break;
  117622. out[k]=unitnorm(in[k]);
  117623. acc-=1.;
  117624. }
  117625. }
  117626. for(;i<partition;i++){
  117627. k=sortedindex[i+j-start];
  117628. out[k]=0.;
  117629. }
  117630. }
  117631. }
  117632. for(;j<n;j++)
  117633. out[j]=rint(in[j]);
  117634. }
  117635. void _vp_couple(int blobno,
  117636. vorbis_info_psy_global *g,
  117637. vorbis_look_psy *p,
  117638. vorbis_info_mapping0 *vi,
  117639. float **res,
  117640. float **mag_memo,
  117641. int **mag_sort,
  117642. int **ifloor,
  117643. int *nonzero,
  117644. int sliding_lowpass){
  117645. int i,j,k,n=p->n;
  117646. /* perform any requested channel coupling */
  117647. /* point stereo can only be used in a first stage (in this encoder)
  117648. because of the dependency on floor lookups */
  117649. for(i=0;i<vi->coupling_steps;i++){
  117650. /* once we're doing multistage coupling in which a channel goes
  117651. through more than one coupling step, the floor vector
  117652. magnitudes will also have to be recalculated an propogated
  117653. along with PCM. Right now, we're not (that will wait until 5.1
  117654. most likely), so the code isn't here yet. The memory management
  117655. here is all assuming single depth couplings anyway. */
  117656. /* make sure coupling a zero and a nonzero channel results in two
  117657. nonzero channels. */
  117658. if(nonzero[vi->coupling_mag[i]] ||
  117659. nonzero[vi->coupling_ang[i]]){
  117660. float *rM=res[vi->coupling_mag[i]];
  117661. float *rA=res[vi->coupling_ang[i]];
  117662. float *qM=rM+n;
  117663. float *qA=rA+n;
  117664. int *floorM=ifloor[vi->coupling_mag[i]];
  117665. int *floorA=ifloor[vi->coupling_ang[i]];
  117666. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  117667. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  117668. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  117669. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  117670. int pointlimit=limit;
  117671. nonzero[vi->coupling_mag[i]]=1;
  117672. nonzero[vi->coupling_ang[i]]=1;
  117673. /* The threshold of a stereo is changed with the size of n */
  117674. if(n > 1000)
  117675. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  117676. for(j=0;j<p->n;j+=partition){
  117677. float acc=0.f;
  117678. for(k=0;k<partition;k++){
  117679. int l=k+j;
  117680. if(l<sliding_lowpass){
  117681. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  117682. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  117683. precomputed_couple_point(mag_memo[i][l],
  117684. floorM[l],floorA[l],
  117685. qM+l,qA+l);
  117686. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  117687. }else{
  117688. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  117689. }
  117690. }else{
  117691. qM[l]=0.;
  117692. qA[l]=0.;
  117693. }
  117694. }
  117695. if(p->vi->normal_point_p){
  117696. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  117697. int l=mag_sort[i][j+k];
  117698. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  117699. qM[l]=unitnorm(qM[l]);
  117700. acc-=1.f;
  117701. }
  117702. }
  117703. }
  117704. }
  117705. }
  117706. }
  117707. }
  117708. /* AoTuV */
  117709. /** @ M2 **
  117710. The boost problem by the combination of noise normalization and point stereo is eased.
  117711. However, this is a temporary patch.
  117712. by Aoyumi @ 2004/04/18
  117713. */
  117714. void hf_reduction(vorbis_info_psy_global *g,
  117715. vorbis_look_psy *p,
  117716. vorbis_info_mapping0 *vi,
  117717. float **mdct){
  117718. int i,j,n=p->n, de=0.3*p->m_val;
  117719. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117720. for(i=0; i<vi->coupling_steps; i++){
  117721. /* for(j=start; j<limit; j++){} // ???*/
  117722. for(j=limit; j<n; j++)
  117723. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  117724. }
  117725. }
  117726. #endif
  117727. /*** End of inlined file: psy.c ***/
  117728. /*** Start of inlined file: registry.c ***/
  117729. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117730. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117731. // tasks..
  117732. #if JUCE_MSVC
  117733. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117734. #endif
  117735. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117736. #if JUCE_USE_OGGVORBIS
  117737. /* seems like major overkill now; the backend numbers will grow into
  117738. the infrastructure soon enough */
  117739. extern vorbis_func_floor floor0_exportbundle;
  117740. extern vorbis_func_floor floor1_exportbundle;
  117741. extern vorbis_func_residue residue0_exportbundle;
  117742. extern vorbis_func_residue residue1_exportbundle;
  117743. extern vorbis_func_residue residue2_exportbundle;
  117744. extern vorbis_func_mapping mapping0_exportbundle;
  117745. vorbis_func_floor *_floor_P[]={
  117746. &floor0_exportbundle,
  117747. &floor1_exportbundle,
  117748. };
  117749. vorbis_func_residue *_residue_P[]={
  117750. &residue0_exportbundle,
  117751. &residue1_exportbundle,
  117752. &residue2_exportbundle,
  117753. };
  117754. vorbis_func_mapping *_mapping_P[]={
  117755. &mapping0_exportbundle,
  117756. };
  117757. #endif
  117758. /*** End of inlined file: registry.c ***/
  117759. /*** Start of inlined file: res0.c ***/
  117760. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  117761. encode/decode loops are coded for clarity and performance is not
  117762. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  117763. it's slow. */
  117764. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117765. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117766. // tasks..
  117767. #if JUCE_MSVC
  117768. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117769. #endif
  117770. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117771. #if JUCE_USE_OGGVORBIS
  117772. #include <stdlib.h>
  117773. #include <string.h>
  117774. #include <math.h>
  117775. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117776. #include <stdio.h>
  117777. #endif
  117778. typedef struct {
  117779. vorbis_info_residue0 *info;
  117780. int parts;
  117781. int stages;
  117782. codebook *fullbooks;
  117783. codebook *phrasebook;
  117784. codebook ***partbooks;
  117785. int partvals;
  117786. int **decodemap;
  117787. long postbits;
  117788. long phrasebits;
  117789. long frames;
  117790. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  117791. int train_seq;
  117792. long *training_data[8][64];
  117793. float training_max[8][64];
  117794. float training_min[8][64];
  117795. float tmin;
  117796. float tmax;
  117797. #endif
  117798. } vorbis_look_residue0;
  117799. void res0_free_info(vorbis_info_residue *i){
  117800. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  117801. if(info){
  117802. memset(info,0,sizeof(*info));
  117803. _ogg_free(info);
  117804. }
  117805. }
  117806. void res0_free_look(vorbis_look_residue *i){
  117807. int j;
  117808. if(i){
  117809. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  117810. #ifdef TRAIN_RES
  117811. {
  117812. int j,k,l;
  117813. for(j=0;j<look->parts;j++){
  117814. /*fprintf(stderr,"partition %d: ",j);*/
  117815. for(k=0;k<8;k++)
  117816. if(look->training_data[k][j]){
  117817. char buffer[80];
  117818. FILE *of;
  117819. codebook *statebook=look->partbooks[j][k];
  117820. /* long and short into the same bucket by current convention */
  117821. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  117822. of=fopen(buffer,"a");
  117823. for(l=0;l<statebook->entries;l++)
  117824. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  117825. fclose(of);
  117826. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  117827. look->training_min[k][j],look->training_max[k][j]);*/
  117828. _ogg_free(look->training_data[k][j]);
  117829. look->training_data[k][j]=NULL;
  117830. }
  117831. /*fprintf(stderr,"\n");*/
  117832. }
  117833. }
  117834. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  117835. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  117836. (float)look->phrasebits/look->frames,
  117837. (float)look->postbits/look->frames,
  117838. (float)(look->postbits+look->phrasebits)/look->frames);*/
  117839. #endif
  117840. /*vorbis_info_residue0 *info=look->info;
  117841. fprintf(stderr,
  117842. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  117843. "(%g/frame) \n",look->frames,look->phrasebits,
  117844. look->resbitsflat,
  117845. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  117846. for(j=0;j<look->parts;j++){
  117847. long acc=0;
  117848. fprintf(stderr,"\t[%d] == ",j);
  117849. for(k=0;k<look->stages;k++)
  117850. if((info->secondstages[j]>>k)&1){
  117851. fprintf(stderr,"%ld,",look->resbits[j][k]);
  117852. acc+=look->resbits[j][k];
  117853. }
  117854. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  117855. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  117856. }
  117857. fprintf(stderr,"\n");*/
  117858. for(j=0;j<look->parts;j++)
  117859. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  117860. _ogg_free(look->partbooks);
  117861. for(j=0;j<look->partvals;j++)
  117862. _ogg_free(look->decodemap[j]);
  117863. _ogg_free(look->decodemap);
  117864. memset(look,0,sizeof(*look));
  117865. _ogg_free(look);
  117866. }
  117867. }
  117868. static int icount(unsigned int v){
  117869. int ret=0;
  117870. while(v){
  117871. ret+=v&1;
  117872. v>>=1;
  117873. }
  117874. return(ret);
  117875. }
  117876. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  117877. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117878. int j,acc=0;
  117879. oggpack_write(opb,info->begin,24);
  117880. oggpack_write(opb,info->end,24);
  117881. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  117882. code with a partitioned book */
  117883. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  117884. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  117885. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  117886. bitmask of one indicates this partition class has bits to write
  117887. this pass */
  117888. for(j=0;j<info->partitions;j++){
  117889. if(ilog(info->secondstages[j])>3){
  117890. /* yes, this is a minor hack due to not thinking ahead */
  117891. oggpack_write(opb,info->secondstages[j],3);
  117892. oggpack_write(opb,1,1);
  117893. oggpack_write(opb,info->secondstages[j]>>3,5);
  117894. }else
  117895. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  117896. acc+=icount(info->secondstages[j]);
  117897. }
  117898. for(j=0;j<acc;j++)
  117899. oggpack_write(opb,info->booklist[j],8);
  117900. }
  117901. /* vorbis_info is for range checking */
  117902. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  117903. int j,acc=0;
  117904. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  117905. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  117906. info->begin=oggpack_read(opb,24);
  117907. info->end=oggpack_read(opb,24);
  117908. info->grouping=oggpack_read(opb,24)+1;
  117909. info->partitions=oggpack_read(opb,6)+1;
  117910. info->groupbook=oggpack_read(opb,8);
  117911. for(j=0;j<info->partitions;j++){
  117912. int cascade=oggpack_read(opb,3);
  117913. if(oggpack_read(opb,1))
  117914. cascade|=(oggpack_read(opb,5)<<3);
  117915. info->secondstages[j]=cascade;
  117916. acc+=icount(cascade);
  117917. }
  117918. for(j=0;j<acc;j++)
  117919. info->booklist[j]=oggpack_read(opb,8);
  117920. if(info->groupbook>=ci->books)goto errout;
  117921. for(j=0;j<acc;j++)
  117922. if(info->booklist[j]>=ci->books)goto errout;
  117923. return(info);
  117924. errout:
  117925. res0_free_info(info);
  117926. return(NULL);
  117927. }
  117928. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  117929. vorbis_info_residue *vr){
  117930. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117931. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  117932. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  117933. int j,k,acc=0;
  117934. int dim;
  117935. int maxstage=0;
  117936. look->info=info;
  117937. look->parts=info->partitions;
  117938. look->fullbooks=ci->fullbooks;
  117939. look->phrasebook=ci->fullbooks+info->groupbook;
  117940. dim=look->phrasebook->dim;
  117941. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  117942. for(j=0;j<look->parts;j++){
  117943. int stages=ilog(info->secondstages[j]);
  117944. if(stages){
  117945. if(stages>maxstage)maxstage=stages;
  117946. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  117947. for(k=0;k<stages;k++)
  117948. if(info->secondstages[j]&(1<<k)){
  117949. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  117950. #ifdef TRAIN_RES
  117951. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  117952. sizeof(***look->training_data));
  117953. #endif
  117954. }
  117955. }
  117956. }
  117957. look->partvals=rint(pow((float)look->parts,(float)dim));
  117958. look->stages=maxstage;
  117959. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  117960. for(j=0;j<look->partvals;j++){
  117961. long val=j;
  117962. long mult=look->partvals/look->parts;
  117963. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  117964. for(k=0;k<dim;k++){
  117965. long deco=val/mult;
  117966. val-=deco*mult;
  117967. mult/=look->parts;
  117968. look->decodemap[j][k]=deco;
  117969. }
  117970. }
  117971. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117972. {
  117973. static int train_seq=0;
  117974. look->train_seq=train_seq++;
  117975. }
  117976. #endif
  117977. return(look);
  117978. }
  117979. /* break an abstraction and copy some code for performance purposes */
  117980. static int local_book_besterror(codebook *book,float *a){
  117981. int dim=book->dim,i,k,o;
  117982. int best=0;
  117983. encode_aux_threshmatch *tt=book->c->thresh_tree;
  117984. /* find the quant val of each scalar */
  117985. for(k=0,o=dim;k<dim;++k){
  117986. float val=a[--o];
  117987. i=tt->threshvals>>1;
  117988. if(val<tt->quantthresh[i]){
  117989. if(val<tt->quantthresh[i-1]){
  117990. for(--i;i>0;--i)
  117991. if(val>=tt->quantthresh[i-1])
  117992. break;
  117993. }
  117994. }else{
  117995. for(++i;i<tt->threshvals-1;++i)
  117996. if(val<tt->quantthresh[i])break;
  117997. }
  117998. best=(best*tt->quantvals)+tt->quantmap[i];
  117999. }
  118000. /* regular lattices are easy :-) */
  118001. if(book->c->lengthlist[best]<=0){
  118002. const static_codebook *c=book->c;
  118003. int i,j;
  118004. float bestf=0.f;
  118005. float *e=book->valuelist;
  118006. best=-1;
  118007. for(i=0;i<book->entries;i++){
  118008. if(c->lengthlist[i]>0){
  118009. float thisx=0.f;
  118010. for(j=0;j<dim;j++){
  118011. float val=(e[j]-a[j]);
  118012. thisx+=val*val;
  118013. }
  118014. if(best==-1 || thisx<bestf){
  118015. bestf=thisx;
  118016. best=i;
  118017. }
  118018. }
  118019. e+=dim;
  118020. }
  118021. }
  118022. {
  118023. float *ptr=book->valuelist+best*dim;
  118024. for(i=0;i<dim;i++)
  118025. *a++ -= *ptr++;
  118026. }
  118027. return(best);
  118028. }
  118029. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118030. codebook *book,long *acc){
  118031. int i,bits=0;
  118032. int dim=book->dim;
  118033. int step=n/dim;
  118034. for(i=0;i<step;i++){
  118035. int entry=local_book_besterror(book,vec+i*dim);
  118036. #ifdef TRAIN_RES
  118037. acc[entry]++;
  118038. #endif
  118039. bits+=vorbis_book_encode(book,entry,opb);
  118040. }
  118041. return(bits);
  118042. }
  118043. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118044. float **in,int ch){
  118045. long i,j,k;
  118046. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118047. vorbis_info_residue0 *info=look->info;
  118048. /* move all this setup out later */
  118049. int samples_per_partition=info->grouping;
  118050. int possible_partitions=info->partitions;
  118051. int n=info->end-info->begin;
  118052. int partvals=n/samples_per_partition;
  118053. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118054. float scale=100./samples_per_partition;
  118055. /* we find the partition type for each partition of each
  118056. channel. We'll go back and do the interleaved encoding in a
  118057. bit. For now, clarity */
  118058. for(i=0;i<ch;i++){
  118059. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118060. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118061. }
  118062. for(i=0;i<partvals;i++){
  118063. int offset=i*samples_per_partition+info->begin;
  118064. for(j=0;j<ch;j++){
  118065. float max=0.;
  118066. float ent=0.;
  118067. for(k=0;k<samples_per_partition;k++){
  118068. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118069. ent+=fabs(rint(in[j][offset+k]));
  118070. }
  118071. ent*=scale;
  118072. for(k=0;k<possible_partitions-1;k++)
  118073. if(max<=info->classmetric1[k] &&
  118074. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118075. break;
  118076. partword[j][i]=k;
  118077. }
  118078. }
  118079. #ifdef TRAIN_RESAUX
  118080. {
  118081. FILE *of;
  118082. char buffer[80];
  118083. for(i=0;i<ch;i++){
  118084. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118085. of=fopen(buffer,"a");
  118086. for(j=0;j<partvals;j++)
  118087. fprintf(of,"%ld, ",partword[i][j]);
  118088. fprintf(of,"\n");
  118089. fclose(of);
  118090. }
  118091. }
  118092. #endif
  118093. look->frames++;
  118094. return(partword);
  118095. }
  118096. /* designed for stereo or other modes where the partition size is an
  118097. integer multiple of the number of channels encoded in the current
  118098. submap */
  118099. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118100. int ch){
  118101. long i,j,k,l;
  118102. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118103. vorbis_info_residue0 *info=look->info;
  118104. /* move all this setup out later */
  118105. int samples_per_partition=info->grouping;
  118106. int possible_partitions=info->partitions;
  118107. int n=info->end-info->begin;
  118108. int partvals=n/samples_per_partition;
  118109. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118110. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118111. FILE *of;
  118112. char buffer[80];
  118113. #endif
  118114. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118115. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118116. for(i=0,l=info->begin/ch;i<partvals;i++){
  118117. float magmax=0.f;
  118118. float angmax=0.f;
  118119. for(j=0;j<samples_per_partition;j+=ch){
  118120. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118121. for(k=1;k<ch;k++)
  118122. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118123. l++;
  118124. }
  118125. for(j=0;j<possible_partitions-1;j++)
  118126. if(magmax<=info->classmetric1[j] &&
  118127. angmax<=info->classmetric2[j])
  118128. break;
  118129. partword[0][i]=j;
  118130. }
  118131. #ifdef TRAIN_RESAUX
  118132. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118133. of=fopen(buffer,"a");
  118134. for(i=0;i<partvals;i++)
  118135. fprintf(of,"%ld, ",partword[0][i]);
  118136. fprintf(of,"\n");
  118137. fclose(of);
  118138. #endif
  118139. look->frames++;
  118140. return(partword);
  118141. }
  118142. static int _01forward(oggpack_buffer *opb,
  118143. vorbis_block *vb,vorbis_look_residue *vl,
  118144. float **in,int ch,
  118145. long **partword,
  118146. int (*encode)(oggpack_buffer *,float *,int,
  118147. codebook *,long *)){
  118148. long i,j,k,s;
  118149. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118150. vorbis_info_residue0 *info=look->info;
  118151. /* move all this setup out later */
  118152. int samples_per_partition=info->grouping;
  118153. int possible_partitions=info->partitions;
  118154. int partitions_per_word=look->phrasebook->dim;
  118155. int n=info->end-info->begin;
  118156. int partvals=n/samples_per_partition;
  118157. long resbits[128];
  118158. long resvals[128];
  118159. #ifdef TRAIN_RES
  118160. for(i=0;i<ch;i++)
  118161. for(j=info->begin;j<info->end;j++){
  118162. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118163. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118164. }
  118165. #endif
  118166. memset(resbits,0,sizeof(resbits));
  118167. memset(resvals,0,sizeof(resvals));
  118168. /* we code the partition words for each channel, then the residual
  118169. words for a partition per channel until we've written all the
  118170. residual words for that partition word. Then write the next
  118171. partition channel words... */
  118172. for(s=0;s<look->stages;s++){
  118173. for(i=0;i<partvals;){
  118174. /* first we encode a partition codeword for each channel */
  118175. if(s==0){
  118176. for(j=0;j<ch;j++){
  118177. long val=partword[j][i];
  118178. for(k=1;k<partitions_per_word;k++){
  118179. val*=possible_partitions;
  118180. if(i+k<partvals)
  118181. val+=partword[j][i+k];
  118182. }
  118183. /* training hack */
  118184. if(val<look->phrasebook->entries)
  118185. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118186. #if 0 /*def TRAIN_RES*/
  118187. else
  118188. fprintf(stderr,"!");
  118189. #endif
  118190. }
  118191. }
  118192. /* now we encode interleaved residual values for the partitions */
  118193. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118194. long offset=i*samples_per_partition+info->begin;
  118195. for(j=0;j<ch;j++){
  118196. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118197. if(info->secondstages[partword[j][i]]&(1<<s)){
  118198. codebook *statebook=look->partbooks[partword[j][i]][s];
  118199. if(statebook){
  118200. int ret;
  118201. long *accumulator=NULL;
  118202. #ifdef TRAIN_RES
  118203. accumulator=look->training_data[s][partword[j][i]];
  118204. {
  118205. int l;
  118206. float *samples=in[j]+offset;
  118207. for(l=0;l<samples_per_partition;l++){
  118208. if(samples[l]<look->training_min[s][partword[j][i]])
  118209. look->training_min[s][partword[j][i]]=samples[l];
  118210. if(samples[l]>look->training_max[s][partword[j][i]])
  118211. look->training_max[s][partword[j][i]]=samples[l];
  118212. }
  118213. }
  118214. #endif
  118215. ret=encode(opb,in[j]+offset,samples_per_partition,
  118216. statebook,accumulator);
  118217. look->postbits+=ret;
  118218. resbits[partword[j][i]]+=ret;
  118219. }
  118220. }
  118221. }
  118222. }
  118223. }
  118224. }
  118225. /*{
  118226. long total=0;
  118227. long totalbits=0;
  118228. fprintf(stderr,"%d :: ",vb->mode);
  118229. for(k=0;k<possible_partitions;k++){
  118230. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118231. total+=resvals[k];
  118232. totalbits+=resbits[k];
  118233. }
  118234. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118235. }*/
  118236. return(0);
  118237. }
  118238. /* a truncated packet here just means 'stop working'; it's not an error */
  118239. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118240. float **in,int ch,
  118241. long (*decodepart)(codebook *, float *,
  118242. oggpack_buffer *,int)){
  118243. long i,j,k,l,s;
  118244. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118245. vorbis_info_residue0 *info=look->info;
  118246. /* move all this setup out later */
  118247. int samples_per_partition=info->grouping;
  118248. int partitions_per_word=look->phrasebook->dim;
  118249. int n=info->end-info->begin;
  118250. int partvals=n/samples_per_partition;
  118251. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118252. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118253. for(j=0;j<ch;j++)
  118254. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118255. for(s=0;s<look->stages;s++){
  118256. /* each loop decodes on partition codeword containing
  118257. partitions_pre_word partitions */
  118258. for(i=0,l=0;i<partvals;l++){
  118259. if(s==0){
  118260. /* fetch the partition word for each channel */
  118261. for(j=0;j<ch;j++){
  118262. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118263. if(temp==-1)goto eopbreak;
  118264. partword[j][l]=look->decodemap[temp];
  118265. if(partword[j][l]==NULL)goto errout;
  118266. }
  118267. }
  118268. /* now we decode residual values for the partitions */
  118269. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118270. for(j=0;j<ch;j++){
  118271. long offset=info->begin+i*samples_per_partition;
  118272. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118273. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118274. if(stagebook){
  118275. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118276. samples_per_partition)==-1)goto eopbreak;
  118277. }
  118278. }
  118279. }
  118280. }
  118281. }
  118282. errout:
  118283. eopbreak:
  118284. return(0);
  118285. }
  118286. #if 0
  118287. /* residue 0 and 1 are just slight variants of one another. 0 is
  118288. interleaved, 1 is not */
  118289. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118290. float **in,int *nonzero,int ch){
  118291. /* we encode only the nonzero parts of a bundle */
  118292. int i,used=0;
  118293. for(i=0;i<ch;i++)
  118294. if(nonzero[i])
  118295. in[used++]=in[i];
  118296. if(used)
  118297. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118298. return(_01class(vb,vl,in,used));
  118299. else
  118300. return(0);
  118301. }
  118302. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118303. float **in,float **out,int *nonzero,int ch,
  118304. long **partword){
  118305. /* we encode only the nonzero parts of a bundle */
  118306. int i,j,used=0,n=vb->pcmend/2;
  118307. for(i=0;i<ch;i++)
  118308. if(nonzero[i]){
  118309. if(out)
  118310. for(j=0;j<n;j++)
  118311. out[i][j]+=in[i][j];
  118312. in[used++]=in[i];
  118313. }
  118314. if(used){
  118315. int ret=_01forward(vb,vl,in,used,partword,
  118316. _interleaved_encodepart);
  118317. if(out){
  118318. used=0;
  118319. for(i=0;i<ch;i++)
  118320. if(nonzero[i]){
  118321. for(j=0;j<n;j++)
  118322. out[i][j]-=in[used][j];
  118323. used++;
  118324. }
  118325. }
  118326. return(ret);
  118327. }else{
  118328. return(0);
  118329. }
  118330. }
  118331. #endif
  118332. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118333. float **in,int *nonzero,int ch){
  118334. int i,used=0;
  118335. for(i=0;i<ch;i++)
  118336. if(nonzero[i])
  118337. in[used++]=in[i];
  118338. if(used)
  118339. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118340. else
  118341. return(0);
  118342. }
  118343. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118344. float **in,float **out,int *nonzero,int ch,
  118345. long **partword){
  118346. int i,j,used=0,n=vb->pcmend/2;
  118347. for(i=0;i<ch;i++)
  118348. if(nonzero[i]){
  118349. if(out)
  118350. for(j=0;j<n;j++)
  118351. out[i][j]+=in[i][j];
  118352. in[used++]=in[i];
  118353. }
  118354. if(used){
  118355. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118356. if(out){
  118357. used=0;
  118358. for(i=0;i<ch;i++)
  118359. if(nonzero[i]){
  118360. for(j=0;j<n;j++)
  118361. out[i][j]-=in[used][j];
  118362. used++;
  118363. }
  118364. }
  118365. return(ret);
  118366. }else{
  118367. return(0);
  118368. }
  118369. }
  118370. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118371. float **in,int *nonzero,int ch){
  118372. int i,used=0;
  118373. for(i=0;i<ch;i++)
  118374. if(nonzero[i])
  118375. in[used++]=in[i];
  118376. if(used)
  118377. return(_01class(vb,vl,in,used));
  118378. else
  118379. return(0);
  118380. }
  118381. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118382. float **in,int *nonzero,int ch){
  118383. int i,used=0;
  118384. for(i=0;i<ch;i++)
  118385. if(nonzero[i])
  118386. in[used++]=in[i];
  118387. if(used)
  118388. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118389. else
  118390. return(0);
  118391. }
  118392. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118393. float **in,int *nonzero,int ch){
  118394. int i,used=0;
  118395. for(i=0;i<ch;i++)
  118396. if(nonzero[i])used++;
  118397. if(used)
  118398. return(_2class(vb,vl,in,ch));
  118399. else
  118400. return(0);
  118401. }
  118402. /* res2 is slightly more different; all the channels are interleaved
  118403. into a single vector and encoded. */
  118404. int res2_forward(oggpack_buffer *opb,
  118405. vorbis_block *vb,vorbis_look_residue *vl,
  118406. float **in,float **out,int *nonzero,int ch,
  118407. long **partword){
  118408. long i,j,k,n=vb->pcmend/2,used=0;
  118409. /* don't duplicate the code; use a working vector hack for now and
  118410. reshape ourselves into a single channel res1 */
  118411. /* ugly; reallocs for each coupling pass :-( */
  118412. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118413. for(i=0;i<ch;i++){
  118414. float *pcm=in[i];
  118415. if(nonzero[i])used++;
  118416. for(j=0,k=i;j<n;j++,k+=ch)
  118417. work[k]=pcm[j];
  118418. }
  118419. if(used){
  118420. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118421. /* update the sofar vector */
  118422. if(out){
  118423. for(i=0;i<ch;i++){
  118424. float *pcm=in[i];
  118425. float *sofar=out[i];
  118426. for(j=0,k=i;j<n;j++,k+=ch)
  118427. sofar[j]+=pcm[j]-work[k];
  118428. }
  118429. }
  118430. return(ret);
  118431. }else{
  118432. return(0);
  118433. }
  118434. }
  118435. /* duplicate code here as speed is somewhat more important */
  118436. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118437. float **in,int *nonzero,int ch){
  118438. long i,k,l,s;
  118439. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118440. vorbis_info_residue0 *info=look->info;
  118441. /* move all this setup out later */
  118442. int samples_per_partition=info->grouping;
  118443. int partitions_per_word=look->phrasebook->dim;
  118444. int n=info->end-info->begin;
  118445. int partvals=n/samples_per_partition;
  118446. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118447. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118448. for(i=0;i<ch;i++)if(nonzero[i])break;
  118449. if(i==ch)return(0); /* no nonzero vectors */
  118450. for(s=0;s<look->stages;s++){
  118451. for(i=0,l=0;i<partvals;l++){
  118452. if(s==0){
  118453. /* fetch the partition word */
  118454. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118455. if(temp==-1)goto eopbreak;
  118456. partword[l]=look->decodemap[temp];
  118457. if(partword[l]==NULL)goto errout;
  118458. }
  118459. /* now we decode residual values for the partitions */
  118460. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118461. if(info->secondstages[partword[l][k]]&(1<<s)){
  118462. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118463. if(stagebook){
  118464. if(vorbis_book_decodevv_add(stagebook,in,
  118465. i*samples_per_partition+info->begin,ch,
  118466. &vb->opb,samples_per_partition)==-1)
  118467. goto eopbreak;
  118468. }
  118469. }
  118470. }
  118471. }
  118472. errout:
  118473. eopbreak:
  118474. return(0);
  118475. }
  118476. vorbis_func_residue residue0_exportbundle={
  118477. NULL,
  118478. &res0_unpack,
  118479. &res0_look,
  118480. &res0_free_info,
  118481. &res0_free_look,
  118482. NULL,
  118483. NULL,
  118484. &res0_inverse
  118485. };
  118486. vorbis_func_residue residue1_exportbundle={
  118487. &res0_pack,
  118488. &res0_unpack,
  118489. &res0_look,
  118490. &res0_free_info,
  118491. &res0_free_look,
  118492. &res1_class,
  118493. &res1_forward,
  118494. &res1_inverse
  118495. };
  118496. vorbis_func_residue residue2_exportbundle={
  118497. &res0_pack,
  118498. &res0_unpack,
  118499. &res0_look,
  118500. &res0_free_info,
  118501. &res0_free_look,
  118502. &res2_class,
  118503. &res2_forward,
  118504. &res2_inverse
  118505. };
  118506. #endif
  118507. /*** End of inlined file: res0.c ***/
  118508. /*** Start of inlined file: sharedbook.c ***/
  118509. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118510. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118511. // tasks..
  118512. #if JUCE_MSVC
  118513. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118514. #endif
  118515. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118516. #if JUCE_USE_OGGVORBIS
  118517. #include <stdlib.h>
  118518. #include <math.h>
  118519. #include <string.h>
  118520. /**** pack/unpack helpers ******************************************/
  118521. int _ilog(unsigned int v){
  118522. int ret=0;
  118523. while(v){
  118524. ret++;
  118525. v>>=1;
  118526. }
  118527. return(ret);
  118528. }
  118529. /* 32 bit float (not IEEE; nonnormalized mantissa +
  118530. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  118531. Why not IEEE? It's just not that important here. */
  118532. #define VQ_FEXP 10
  118533. #define VQ_FMAN 21
  118534. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  118535. /* doesn't currently guard under/overflow */
  118536. long _float32_pack(float val){
  118537. int sign=0;
  118538. long exp;
  118539. long mant;
  118540. if(val<0){
  118541. sign=0x80000000;
  118542. val= -val;
  118543. }
  118544. exp= floor(log(val)/log(2.f));
  118545. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  118546. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  118547. return(sign|exp|mant);
  118548. }
  118549. float _float32_unpack(long val){
  118550. double mant=val&0x1fffff;
  118551. int sign=val&0x80000000;
  118552. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  118553. if(sign)mant= -mant;
  118554. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  118555. }
  118556. /* given a list of word lengths, generate a list of codewords. Works
  118557. for length ordered or unordered, always assigns the lowest valued
  118558. codewords first. Extended to handle unused entries (length 0) */
  118559. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  118560. long i,j,count=0;
  118561. ogg_uint32_t marker[33];
  118562. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  118563. memset(marker,0,sizeof(marker));
  118564. for(i=0;i<n;i++){
  118565. long length=l[i];
  118566. if(length>0){
  118567. ogg_uint32_t entry=marker[length];
  118568. /* when we claim a node for an entry, we also claim the nodes
  118569. below it (pruning off the imagined tree that may have dangled
  118570. from it) as well as blocking the use of any nodes directly
  118571. above for leaves */
  118572. /* update ourself */
  118573. if(length<32 && (entry>>length)){
  118574. /* error condition; the lengths must specify an overpopulated tree */
  118575. _ogg_free(r);
  118576. return(NULL);
  118577. }
  118578. r[count++]=entry;
  118579. /* Look to see if the next shorter marker points to the node
  118580. above. if so, update it and repeat. */
  118581. {
  118582. for(j=length;j>0;j--){
  118583. if(marker[j]&1){
  118584. /* have to jump branches */
  118585. if(j==1)
  118586. marker[1]++;
  118587. else
  118588. marker[j]=marker[j-1]<<1;
  118589. break; /* invariant says next upper marker would already
  118590. have been moved if it was on the same path */
  118591. }
  118592. marker[j]++;
  118593. }
  118594. }
  118595. /* prune the tree; the implicit invariant says all the longer
  118596. markers were dangling from our just-taken node. Dangle them
  118597. from our *new* node. */
  118598. for(j=length+1;j<33;j++)
  118599. if((marker[j]>>1) == entry){
  118600. entry=marker[j];
  118601. marker[j]=marker[j-1]<<1;
  118602. }else
  118603. break;
  118604. }else
  118605. if(sparsecount==0)count++;
  118606. }
  118607. /* bitreverse the words because our bitwise packer/unpacker is LSb
  118608. endian */
  118609. for(i=0,count=0;i<n;i++){
  118610. ogg_uint32_t temp=0;
  118611. for(j=0;j<l[i];j++){
  118612. temp<<=1;
  118613. temp|=(r[count]>>j)&1;
  118614. }
  118615. if(sparsecount){
  118616. if(l[i])
  118617. r[count++]=temp;
  118618. }else
  118619. r[count++]=temp;
  118620. }
  118621. return(r);
  118622. }
  118623. /* there might be a straightforward one-line way to do the below
  118624. that's portable and totally safe against roundoff, but I haven't
  118625. thought of it. Therefore, we opt on the side of caution */
  118626. long _book_maptype1_quantvals(const static_codebook *b){
  118627. long vals=floor(pow((float)b->entries,1.f/b->dim));
  118628. /* the above *should* be reliable, but we'll not assume that FP is
  118629. ever reliable when bitstream sync is at stake; verify via integer
  118630. means that vals really is the greatest value of dim for which
  118631. vals^b->bim <= b->entries */
  118632. /* treat the above as an initial guess */
  118633. while(1){
  118634. long acc=1;
  118635. long acc1=1;
  118636. int i;
  118637. for(i=0;i<b->dim;i++){
  118638. acc*=vals;
  118639. acc1*=vals+1;
  118640. }
  118641. if(acc<=b->entries && acc1>b->entries){
  118642. return(vals);
  118643. }else{
  118644. if(acc>b->entries){
  118645. vals--;
  118646. }else{
  118647. vals++;
  118648. }
  118649. }
  118650. }
  118651. }
  118652. /* unpack the quantized list of values for encode/decode ***********/
  118653. /* we need to deal with two map types: in map type 1, the values are
  118654. generated algorithmically (each column of the vector counts through
  118655. the values in the quant vector). in map type 2, all the values came
  118656. in in an explicit list. Both value lists must be unpacked */
  118657. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  118658. long j,k,count=0;
  118659. if(b->maptype==1 || b->maptype==2){
  118660. int quantvals;
  118661. float mindel=_float32_unpack(b->q_min);
  118662. float delta=_float32_unpack(b->q_delta);
  118663. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  118664. /* maptype 1 and 2 both use a quantized value vector, but
  118665. different sizes */
  118666. switch(b->maptype){
  118667. case 1:
  118668. /* most of the time, entries%dimensions == 0, but we need to be
  118669. well defined. We define that the possible vales at each
  118670. scalar is values == entries/dim. If entries%dim != 0, we'll
  118671. have 'too few' values (values*dim<entries), which means that
  118672. we'll have 'left over' entries; left over entries use zeroed
  118673. values (and are wasted). So don't generate codebooks like
  118674. that */
  118675. quantvals=_book_maptype1_quantvals(b);
  118676. for(j=0;j<b->entries;j++){
  118677. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118678. float last=0.f;
  118679. int indexdiv=1;
  118680. for(k=0;k<b->dim;k++){
  118681. int index= (j/indexdiv)%quantvals;
  118682. float val=b->quantlist[index];
  118683. val=fabs(val)*delta+mindel+last;
  118684. if(b->q_sequencep)last=val;
  118685. if(sparsemap)
  118686. r[sparsemap[count]*b->dim+k]=val;
  118687. else
  118688. r[count*b->dim+k]=val;
  118689. indexdiv*=quantvals;
  118690. }
  118691. count++;
  118692. }
  118693. }
  118694. break;
  118695. case 2:
  118696. for(j=0;j<b->entries;j++){
  118697. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118698. float last=0.f;
  118699. for(k=0;k<b->dim;k++){
  118700. float val=b->quantlist[j*b->dim+k];
  118701. val=fabs(val)*delta+mindel+last;
  118702. if(b->q_sequencep)last=val;
  118703. if(sparsemap)
  118704. r[sparsemap[count]*b->dim+k]=val;
  118705. else
  118706. r[count*b->dim+k]=val;
  118707. }
  118708. count++;
  118709. }
  118710. }
  118711. break;
  118712. }
  118713. return(r);
  118714. }
  118715. return(NULL);
  118716. }
  118717. void vorbis_staticbook_clear(static_codebook *b){
  118718. if(b->allocedp){
  118719. if(b->quantlist)_ogg_free(b->quantlist);
  118720. if(b->lengthlist)_ogg_free(b->lengthlist);
  118721. if(b->nearest_tree){
  118722. _ogg_free(b->nearest_tree->ptr0);
  118723. _ogg_free(b->nearest_tree->ptr1);
  118724. _ogg_free(b->nearest_tree->p);
  118725. _ogg_free(b->nearest_tree->q);
  118726. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  118727. _ogg_free(b->nearest_tree);
  118728. }
  118729. if(b->thresh_tree){
  118730. _ogg_free(b->thresh_tree->quantthresh);
  118731. _ogg_free(b->thresh_tree->quantmap);
  118732. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  118733. _ogg_free(b->thresh_tree);
  118734. }
  118735. memset(b,0,sizeof(*b));
  118736. }
  118737. }
  118738. void vorbis_staticbook_destroy(static_codebook *b){
  118739. if(b->allocedp){
  118740. vorbis_staticbook_clear(b);
  118741. _ogg_free(b);
  118742. }
  118743. }
  118744. void vorbis_book_clear(codebook *b){
  118745. /* static book is not cleared; we're likely called on the lookup and
  118746. the static codebook belongs to the info struct */
  118747. if(b->valuelist)_ogg_free(b->valuelist);
  118748. if(b->codelist)_ogg_free(b->codelist);
  118749. if(b->dec_index)_ogg_free(b->dec_index);
  118750. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  118751. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  118752. memset(b,0,sizeof(*b));
  118753. }
  118754. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  118755. memset(c,0,sizeof(*c));
  118756. c->c=s;
  118757. c->entries=s->entries;
  118758. c->used_entries=s->entries;
  118759. c->dim=s->dim;
  118760. c->codelist=_make_words(s->lengthlist,s->entries,0);
  118761. c->valuelist=_book_unquantize(s,s->entries,NULL);
  118762. return(0);
  118763. }
  118764. static int JUCE_CDECL sort32a(const void *a,const void *b){
  118765. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  118766. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  118767. }
  118768. /* decode codebook arrangement is more heavily optimized than encode */
  118769. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  118770. int i,j,n=0,tabn;
  118771. int *sortindex;
  118772. memset(c,0,sizeof(*c));
  118773. /* count actually used entries */
  118774. for(i=0;i<s->entries;i++)
  118775. if(s->lengthlist[i]>0)
  118776. n++;
  118777. c->entries=s->entries;
  118778. c->used_entries=n;
  118779. c->dim=s->dim;
  118780. /* two different remappings go on here.
  118781. First, we collapse the likely sparse codebook down only to
  118782. actually represented values/words. This collapsing needs to be
  118783. indexed as map-valueless books are used to encode original entry
  118784. positions as integers.
  118785. Second, we reorder all vectors, including the entry index above,
  118786. by sorted bitreversed codeword to allow treeless decode. */
  118787. {
  118788. /* perform sort */
  118789. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  118790. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  118791. if(codes==NULL)goto err_out;
  118792. for(i=0;i<n;i++){
  118793. codes[i]=ogg_bitreverse(codes[i]);
  118794. codep[i]=codes+i;
  118795. }
  118796. qsort(codep,n,sizeof(*codep),sort32a);
  118797. sortindex=(int*)alloca(n*sizeof(*sortindex));
  118798. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  118799. /* the index is a reverse index */
  118800. for(i=0;i<n;i++){
  118801. int position=codep[i]-codes;
  118802. sortindex[position]=i;
  118803. }
  118804. for(i=0;i<n;i++)
  118805. c->codelist[sortindex[i]]=codes[i];
  118806. _ogg_free(codes);
  118807. }
  118808. c->valuelist=_book_unquantize(s,n,sortindex);
  118809. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  118810. for(n=0,i=0;i<s->entries;i++)
  118811. if(s->lengthlist[i]>0)
  118812. c->dec_index[sortindex[n++]]=i;
  118813. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  118814. for(n=0,i=0;i<s->entries;i++)
  118815. if(s->lengthlist[i]>0)
  118816. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  118817. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  118818. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  118819. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  118820. tabn=1<<c->dec_firsttablen;
  118821. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  118822. c->dec_maxlength=0;
  118823. for(i=0;i<n;i++){
  118824. if(c->dec_maxlength<c->dec_codelengths[i])
  118825. c->dec_maxlength=c->dec_codelengths[i];
  118826. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  118827. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  118828. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  118829. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  118830. }
  118831. }
  118832. /* now fill in 'unused' entries in the firsttable with hi/lo search
  118833. hints for the non-direct-hits */
  118834. {
  118835. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  118836. long lo=0,hi=0;
  118837. for(i=0;i<tabn;i++){
  118838. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  118839. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  118840. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  118841. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  118842. /* we only actually have 15 bits per hint to play with here.
  118843. In order to overflow gracefully (nothing breaks, efficiency
  118844. just drops), encode as the difference from the extremes. */
  118845. {
  118846. unsigned long loval=lo;
  118847. unsigned long hival=n-hi;
  118848. if(loval>0x7fff)loval=0x7fff;
  118849. if(hival>0x7fff)hival=0x7fff;
  118850. c->dec_firsttable[ogg_bitreverse(word)]=
  118851. 0x80000000UL | (loval<<15) | hival;
  118852. }
  118853. }
  118854. }
  118855. }
  118856. return(0);
  118857. err_out:
  118858. vorbis_book_clear(c);
  118859. return(-1);
  118860. }
  118861. static float _dist(int el,float *ref, float *b,int step){
  118862. int i;
  118863. float acc=0.f;
  118864. for(i=0;i<el;i++){
  118865. float val=(ref[i]-b[i*step]);
  118866. acc+=val*val;
  118867. }
  118868. return(acc);
  118869. }
  118870. int _best(codebook *book, float *a, int step){
  118871. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118872. #if 0
  118873. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  118874. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  118875. #endif
  118876. int dim=book->dim;
  118877. int k,o;
  118878. /*int savebest=-1;
  118879. float saverr;*/
  118880. /* do we have a threshhold encode hint? */
  118881. if(tt){
  118882. int index=0,i;
  118883. /* find the quant val of each scalar */
  118884. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118885. i=tt->threshvals>>1;
  118886. if(a[o]<tt->quantthresh[i]){
  118887. for(;i>0;i--)
  118888. if(a[o]>=tt->quantthresh[i-1])
  118889. break;
  118890. }else{
  118891. for(i++;i<tt->threshvals-1;i++)
  118892. if(a[o]<tt->quantthresh[i])break;
  118893. }
  118894. index=(index*tt->quantvals)+tt->quantmap[i];
  118895. }
  118896. /* regular lattices are easy :-) */
  118897. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  118898. use a decision tree after all
  118899. and fall through*/
  118900. return(index);
  118901. }
  118902. #if 0
  118903. /* do we have a pigeonhole encode hint? */
  118904. if(pt){
  118905. const static_codebook *c=book->c;
  118906. int i,besti=-1;
  118907. float best=0.f;
  118908. int entry=0;
  118909. /* dealing with sequentialness is a pain in the ass */
  118910. if(c->q_sequencep){
  118911. int pv;
  118912. long mul=1;
  118913. float qlast=0;
  118914. for(k=0,o=0;k<dim;k++,o+=step){
  118915. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  118916. if(pv<0 || pv>=pt->mapentries)break;
  118917. entry+=pt->pigeonmap[pv]*mul;
  118918. mul*=pt->quantvals;
  118919. qlast+=pv*pt->del+pt->min;
  118920. }
  118921. }else{
  118922. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118923. int pv=(int)((a[o]-pt->min)/pt->del);
  118924. if(pv<0 || pv>=pt->mapentries)break;
  118925. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  118926. }
  118927. }
  118928. /* must be within the pigeonholable range; if we quant outside (or
  118929. in an entry that we define no list for), brute force it */
  118930. if(k==dim && pt->fitlength[entry]){
  118931. /* search the abbreviated list */
  118932. long *list=pt->fitlist+pt->fitmap[entry];
  118933. for(i=0;i<pt->fitlength[entry];i++){
  118934. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  118935. if(besti==-1 || this<best){
  118936. best=this;
  118937. besti=list[i];
  118938. }
  118939. }
  118940. return(besti);
  118941. }
  118942. }
  118943. if(nt){
  118944. /* optimized using the decision tree */
  118945. while(1){
  118946. float c=0.f;
  118947. float *p=book->valuelist+nt->p[ptr];
  118948. float *q=book->valuelist+nt->q[ptr];
  118949. for(k=0,o=0;k<dim;k++,o+=step)
  118950. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  118951. if(c>0.f) /* in A */
  118952. ptr= -nt->ptr0[ptr];
  118953. else /* in B */
  118954. ptr= -nt->ptr1[ptr];
  118955. if(ptr<=0)break;
  118956. }
  118957. return(-ptr);
  118958. }
  118959. #endif
  118960. /* brute force it! */
  118961. {
  118962. const static_codebook *c=book->c;
  118963. int i,besti=-1;
  118964. float best=0.f;
  118965. float *e=book->valuelist;
  118966. for(i=0;i<book->entries;i++){
  118967. if(c->lengthlist[i]>0){
  118968. float thisx=_dist(dim,e,a,step);
  118969. if(besti==-1 || thisx<best){
  118970. best=thisx;
  118971. besti=i;
  118972. }
  118973. }
  118974. e+=dim;
  118975. }
  118976. /*if(savebest!=-1 && savebest!=besti){
  118977. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  118978. "original:");
  118979. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  118980. fprintf(stderr,"\n"
  118981. "pigeonhole (entry %d, err %g):",savebest,saverr);
  118982. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118983. (book->valuelist+savebest*dim)[i]);
  118984. fprintf(stderr,"\n"
  118985. "bruteforce (entry %d, err %g):",besti,best);
  118986. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118987. (book->valuelist+besti*dim)[i]);
  118988. fprintf(stderr,"\n");
  118989. }*/
  118990. return(besti);
  118991. }
  118992. }
  118993. long vorbis_book_codeword(codebook *book,int entry){
  118994. if(book->c) /* only use with encode; decode optimizations are
  118995. allowed to break this */
  118996. return book->codelist[entry];
  118997. return -1;
  118998. }
  118999. long vorbis_book_codelen(codebook *book,int entry){
  119000. if(book->c) /* only use with encode; decode optimizations are
  119001. allowed to break this */
  119002. return book->c->lengthlist[entry];
  119003. return -1;
  119004. }
  119005. #ifdef _V_SELFTEST
  119006. /* Unit tests of the dequantizer; this stuff will be OK
  119007. cross-platform, I simply want to be sure that special mapping cases
  119008. actually work properly; a bug could go unnoticed for a while */
  119009. #include <stdio.h>
  119010. /* cases:
  119011. no mapping
  119012. full, explicit mapping
  119013. algorithmic mapping
  119014. nonsequential
  119015. sequential
  119016. */
  119017. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119018. static long partial_quantlist1[]={0,7,2};
  119019. /* no mapping */
  119020. static_codebook test1={
  119021. 4,16,
  119022. NULL,
  119023. 0,
  119024. 0,0,0,0,
  119025. NULL,
  119026. NULL,NULL
  119027. };
  119028. static float *test1_result=NULL;
  119029. /* linear, full mapping, nonsequential */
  119030. static_codebook test2={
  119031. 4,3,
  119032. NULL,
  119033. 2,
  119034. -533200896,1611661312,4,0,
  119035. full_quantlist1,
  119036. NULL,NULL
  119037. };
  119038. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119039. /* linear, full mapping, sequential */
  119040. static_codebook test3={
  119041. 4,3,
  119042. NULL,
  119043. 2,
  119044. -533200896,1611661312,4,1,
  119045. full_quantlist1,
  119046. NULL,NULL
  119047. };
  119048. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119049. /* linear, algorithmic mapping, nonsequential */
  119050. static_codebook test4={
  119051. 3,27,
  119052. NULL,
  119053. 1,
  119054. -533200896,1611661312,4,0,
  119055. partial_quantlist1,
  119056. NULL,NULL
  119057. };
  119058. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119059. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119060. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119061. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119062. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119063. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119064. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119065. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119066. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119067. /* linear, algorithmic mapping, sequential */
  119068. static_codebook test5={
  119069. 3,27,
  119070. NULL,
  119071. 1,
  119072. -533200896,1611661312,4,1,
  119073. partial_quantlist1,
  119074. NULL,NULL
  119075. };
  119076. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119077. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119078. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119079. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119080. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119081. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119082. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119083. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119084. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119085. void run_test(static_codebook *b,float *comp){
  119086. float *out=_book_unquantize(b,b->entries,NULL);
  119087. int i;
  119088. if(comp){
  119089. if(!out){
  119090. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119091. exit(1);
  119092. }
  119093. for(i=0;i<b->entries*b->dim;i++)
  119094. if(fabs(out[i]-comp[i])>.0001){
  119095. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119096. "position %d, %g != %g\n",i,out[i],comp[i]);
  119097. exit(1);
  119098. }
  119099. }else{
  119100. if(out){
  119101. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119102. " correct result should have been NULL\n");
  119103. exit(1);
  119104. }
  119105. }
  119106. }
  119107. int main(){
  119108. /* run the nine dequant tests, and compare to the hand-rolled results */
  119109. fprintf(stderr,"Dequant test 1... ");
  119110. run_test(&test1,test1_result);
  119111. fprintf(stderr,"OK\nDequant test 2... ");
  119112. run_test(&test2,test2_result);
  119113. fprintf(stderr,"OK\nDequant test 3... ");
  119114. run_test(&test3,test3_result);
  119115. fprintf(stderr,"OK\nDequant test 4... ");
  119116. run_test(&test4,test4_result);
  119117. fprintf(stderr,"OK\nDequant test 5... ");
  119118. run_test(&test5,test5_result);
  119119. fprintf(stderr,"OK\n\n");
  119120. return(0);
  119121. }
  119122. #endif
  119123. #endif
  119124. /*** End of inlined file: sharedbook.c ***/
  119125. /*** Start of inlined file: smallft.c ***/
  119126. /* FFT implementation from OggSquish, minus cosine transforms,
  119127. * minus all but radix 2/4 case. In Vorbis we only need this
  119128. * cut-down version.
  119129. *
  119130. * To do more than just power-of-two sized vectors, see the full
  119131. * version I wrote for NetLib.
  119132. *
  119133. * Note that the packing is a little strange; rather than the FFT r/i
  119134. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119135. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119136. * FORTRAN version
  119137. */
  119138. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119139. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119140. // tasks..
  119141. #if JUCE_MSVC
  119142. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119143. #endif
  119144. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119145. #if JUCE_USE_OGGVORBIS
  119146. #include <stdlib.h>
  119147. #include <string.h>
  119148. #include <math.h>
  119149. static void drfti1(int n, float *wa, int *ifac){
  119150. static int ntryh[4] = { 4,2,3,5 };
  119151. static float tpi = 6.28318530717958648f;
  119152. float arg,argh,argld,fi;
  119153. int ntry=0,i,j=-1;
  119154. int k1, l1, l2, ib;
  119155. int ld, ii, ip, is, nq, nr;
  119156. int ido, ipm, nfm1;
  119157. int nl=n;
  119158. int nf=0;
  119159. L101:
  119160. j++;
  119161. if (j < 4)
  119162. ntry=ntryh[j];
  119163. else
  119164. ntry+=2;
  119165. L104:
  119166. nq=nl/ntry;
  119167. nr=nl-ntry*nq;
  119168. if (nr!=0) goto L101;
  119169. nf++;
  119170. ifac[nf+1]=ntry;
  119171. nl=nq;
  119172. if(ntry!=2)goto L107;
  119173. if(nf==1)goto L107;
  119174. for (i=1;i<nf;i++){
  119175. ib=nf-i+1;
  119176. ifac[ib+1]=ifac[ib];
  119177. }
  119178. ifac[2] = 2;
  119179. L107:
  119180. if(nl!=1)goto L104;
  119181. ifac[0]=n;
  119182. ifac[1]=nf;
  119183. argh=tpi/n;
  119184. is=0;
  119185. nfm1=nf-1;
  119186. l1=1;
  119187. if(nfm1==0)return;
  119188. for (k1=0;k1<nfm1;k1++){
  119189. ip=ifac[k1+2];
  119190. ld=0;
  119191. l2=l1*ip;
  119192. ido=n/l2;
  119193. ipm=ip-1;
  119194. for (j=0;j<ipm;j++){
  119195. ld+=l1;
  119196. i=is;
  119197. argld=(float)ld*argh;
  119198. fi=0.f;
  119199. for (ii=2;ii<ido;ii+=2){
  119200. fi+=1.f;
  119201. arg=fi*argld;
  119202. wa[i++]=cos(arg);
  119203. wa[i++]=sin(arg);
  119204. }
  119205. is+=ido;
  119206. }
  119207. l1=l2;
  119208. }
  119209. }
  119210. static void fdrffti(int n, float *wsave, int *ifac){
  119211. if (n == 1) return;
  119212. drfti1(n, wsave+n, ifac);
  119213. }
  119214. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119215. int i,k;
  119216. float ti2,tr2;
  119217. int t0,t1,t2,t3,t4,t5,t6;
  119218. t1=0;
  119219. t0=(t2=l1*ido);
  119220. t3=ido<<1;
  119221. for(k=0;k<l1;k++){
  119222. ch[t1<<1]=cc[t1]+cc[t2];
  119223. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119224. t1+=ido;
  119225. t2+=ido;
  119226. }
  119227. if(ido<2)return;
  119228. if(ido==2)goto L105;
  119229. t1=0;
  119230. t2=t0;
  119231. for(k=0;k<l1;k++){
  119232. t3=t2;
  119233. t4=(t1<<1)+(ido<<1);
  119234. t5=t1;
  119235. t6=t1+t1;
  119236. for(i=2;i<ido;i+=2){
  119237. t3+=2;
  119238. t4-=2;
  119239. t5+=2;
  119240. t6+=2;
  119241. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119242. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119243. ch[t6]=cc[t5]+ti2;
  119244. ch[t4]=ti2-cc[t5];
  119245. ch[t6-1]=cc[t5-1]+tr2;
  119246. ch[t4-1]=cc[t5-1]-tr2;
  119247. }
  119248. t1+=ido;
  119249. t2+=ido;
  119250. }
  119251. if(ido%2==1)return;
  119252. L105:
  119253. t3=(t2=(t1=ido)-1);
  119254. t2+=t0;
  119255. for(k=0;k<l1;k++){
  119256. ch[t1]=-cc[t2];
  119257. ch[t1-1]=cc[t3];
  119258. t1+=ido<<1;
  119259. t2+=ido;
  119260. t3+=ido;
  119261. }
  119262. }
  119263. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119264. float *wa2,float *wa3){
  119265. static float hsqt2 = .70710678118654752f;
  119266. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119267. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119268. t0=l1*ido;
  119269. t1=t0;
  119270. t4=t1<<1;
  119271. t2=t1+(t1<<1);
  119272. t3=0;
  119273. for(k=0;k<l1;k++){
  119274. tr1=cc[t1]+cc[t2];
  119275. tr2=cc[t3]+cc[t4];
  119276. ch[t5=t3<<2]=tr1+tr2;
  119277. ch[(ido<<2)+t5-1]=tr2-tr1;
  119278. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119279. ch[t5]=cc[t2]-cc[t1];
  119280. t1+=ido;
  119281. t2+=ido;
  119282. t3+=ido;
  119283. t4+=ido;
  119284. }
  119285. if(ido<2)return;
  119286. if(ido==2)goto L105;
  119287. t1=0;
  119288. for(k=0;k<l1;k++){
  119289. t2=t1;
  119290. t4=t1<<2;
  119291. t5=(t6=ido<<1)+t4;
  119292. for(i=2;i<ido;i+=2){
  119293. t3=(t2+=2);
  119294. t4+=2;
  119295. t5-=2;
  119296. t3+=t0;
  119297. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119298. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119299. t3+=t0;
  119300. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119301. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119302. t3+=t0;
  119303. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119304. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119305. tr1=cr2+cr4;
  119306. tr4=cr4-cr2;
  119307. ti1=ci2+ci4;
  119308. ti4=ci2-ci4;
  119309. ti2=cc[t2]+ci3;
  119310. ti3=cc[t2]-ci3;
  119311. tr2=cc[t2-1]+cr3;
  119312. tr3=cc[t2-1]-cr3;
  119313. ch[t4-1]=tr1+tr2;
  119314. ch[t4]=ti1+ti2;
  119315. ch[t5-1]=tr3-ti4;
  119316. ch[t5]=tr4-ti3;
  119317. ch[t4+t6-1]=ti4+tr3;
  119318. ch[t4+t6]=tr4+ti3;
  119319. ch[t5+t6-1]=tr2-tr1;
  119320. ch[t5+t6]=ti1-ti2;
  119321. }
  119322. t1+=ido;
  119323. }
  119324. if(ido&1)return;
  119325. L105:
  119326. t2=(t1=t0+ido-1)+(t0<<1);
  119327. t3=ido<<2;
  119328. t4=ido;
  119329. t5=ido<<1;
  119330. t6=ido;
  119331. for(k=0;k<l1;k++){
  119332. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119333. tr1=hsqt2*(cc[t1]-cc[t2]);
  119334. ch[t4-1]=tr1+cc[t6-1];
  119335. ch[t4+t5-1]=cc[t6-1]-tr1;
  119336. ch[t4]=ti1-cc[t1+t0];
  119337. ch[t4+t5]=ti1+cc[t1+t0];
  119338. t1+=ido;
  119339. t2+=ido;
  119340. t4+=t3;
  119341. t6+=ido;
  119342. }
  119343. }
  119344. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119345. float *c2,float *ch,float *ch2,float *wa){
  119346. static float tpi=6.283185307179586f;
  119347. int idij,ipph,i,j,k,l,ic,ik,is;
  119348. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119349. float dc2,ai1,ai2,ar1,ar2,ds2;
  119350. int nbd;
  119351. float dcp,arg,dsp,ar1h,ar2h;
  119352. int idp2,ipp2;
  119353. arg=tpi/(float)ip;
  119354. dcp=cos(arg);
  119355. dsp=sin(arg);
  119356. ipph=(ip+1)>>1;
  119357. ipp2=ip;
  119358. idp2=ido;
  119359. nbd=(ido-1)>>1;
  119360. t0=l1*ido;
  119361. t10=ip*ido;
  119362. if(ido==1)goto L119;
  119363. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119364. t1=0;
  119365. for(j=1;j<ip;j++){
  119366. t1+=t0;
  119367. t2=t1;
  119368. for(k=0;k<l1;k++){
  119369. ch[t2]=c1[t2];
  119370. t2+=ido;
  119371. }
  119372. }
  119373. is=-ido;
  119374. t1=0;
  119375. if(nbd>l1){
  119376. for(j=1;j<ip;j++){
  119377. t1+=t0;
  119378. is+=ido;
  119379. t2= -ido+t1;
  119380. for(k=0;k<l1;k++){
  119381. idij=is-1;
  119382. t2+=ido;
  119383. t3=t2;
  119384. for(i=2;i<ido;i+=2){
  119385. idij+=2;
  119386. t3+=2;
  119387. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119388. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119389. }
  119390. }
  119391. }
  119392. }else{
  119393. for(j=1;j<ip;j++){
  119394. is+=ido;
  119395. idij=is-1;
  119396. t1+=t0;
  119397. t2=t1;
  119398. for(i=2;i<ido;i+=2){
  119399. idij+=2;
  119400. t2+=2;
  119401. t3=t2;
  119402. for(k=0;k<l1;k++){
  119403. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119404. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119405. t3+=ido;
  119406. }
  119407. }
  119408. }
  119409. }
  119410. t1=0;
  119411. t2=ipp2*t0;
  119412. if(nbd<l1){
  119413. for(j=1;j<ipph;j++){
  119414. t1+=t0;
  119415. t2-=t0;
  119416. t3=t1;
  119417. t4=t2;
  119418. for(i=2;i<ido;i+=2){
  119419. t3+=2;
  119420. t4+=2;
  119421. t5=t3-ido;
  119422. t6=t4-ido;
  119423. for(k=0;k<l1;k++){
  119424. t5+=ido;
  119425. t6+=ido;
  119426. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119427. c1[t6-1]=ch[t5]-ch[t6];
  119428. c1[t5]=ch[t5]+ch[t6];
  119429. c1[t6]=ch[t6-1]-ch[t5-1];
  119430. }
  119431. }
  119432. }
  119433. }else{
  119434. for(j=1;j<ipph;j++){
  119435. t1+=t0;
  119436. t2-=t0;
  119437. t3=t1;
  119438. t4=t2;
  119439. for(k=0;k<l1;k++){
  119440. t5=t3;
  119441. t6=t4;
  119442. for(i=2;i<ido;i+=2){
  119443. t5+=2;
  119444. t6+=2;
  119445. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119446. c1[t6-1]=ch[t5]-ch[t6];
  119447. c1[t5]=ch[t5]+ch[t6];
  119448. c1[t6]=ch[t6-1]-ch[t5-1];
  119449. }
  119450. t3+=ido;
  119451. t4+=ido;
  119452. }
  119453. }
  119454. }
  119455. L119:
  119456. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119457. t1=0;
  119458. t2=ipp2*idl1;
  119459. for(j=1;j<ipph;j++){
  119460. t1+=t0;
  119461. t2-=t0;
  119462. t3=t1-ido;
  119463. t4=t2-ido;
  119464. for(k=0;k<l1;k++){
  119465. t3+=ido;
  119466. t4+=ido;
  119467. c1[t3]=ch[t3]+ch[t4];
  119468. c1[t4]=ch[t4]-ch[t3];
  119469. }
  119470. }
  119471. ar1=1.f;
  119472. ai1=0.f;
  119473. t1=0;
  119474. t2=ipp2*idl1;
  119475. t3=(ip-1)*idl1;
  119476. for(l=1;l<ipph;l++){
  119477. t1+=idl1;
  119478. t2-=idl1;
  119479. ar1h=dcp*ar1-dsp*ai1;
  119480. ai1=dcp*ai1+dsp*ar1;
  119481. ar1=ar1h;
  119482. t4=t1;
  119483. t5=t2;
  119484. t6=t3;
  119485. t7=idl1;
  119486. for(ik=0;ik<idl1;ik++){
  119487. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119488. ch2[t5++]=ai1*c2[t6++];
  119489. }
  119490. dc2=ar1;
  119491. ds2=ai1;
  119492. ar2=ar1;
  119493. ai2=ai1;
  119494. t4=idl1;
  119495. t5=(ipp2-1)*idl1;
  119496. for(j=2;j<ipph;j++){
  119497. t4+=idl1;
  119498. t5-=idl1;
  119499. ar2h=dc2*ar2-ds2*ai2;
  119500. ai2=dc2*ai2+ds2*ar2;
  119501. ar2=ar2h;
  119502. t6=t1;
  119503. t7=t2;
  119504. t8=t4;
  119505. t9=t5;
  119506. for(ik=0;ik<idl1;ik++){
  119507. ch2[t6++]+=ar2*c2[t8++];
  119508. ch2[t7++]+=ai2*c2[t9++];
  119509. }
  119510. }
  119511. }
  119512. t1=0;
  119513. for(j=1;j<ipph;j++){
  119514. t1+=idl1;
  119515. t2=t1;
  119516. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  119517. }
  119518. if(ido<l1)goto L132;
  119519. t1=0;
  119520. t2=0;
  119521. for(k=0;k<l1;k++){
  119522. t3=t1;
  119523. t4=t2;
  119524. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  119525. t1+=ido;
  119526. t2+=t10;
  119527. }
  119528. goto L135;
  119529. L132:
  119530. for(i=0;i<ido;i++){
  119531. t1=i;
  119532. t2=i;
  119533. for(k=0;k<l1;k++){
  119534. cc[t2]=ch[t1];
  119535. t1+=ido;
  119536. t2+=t10;
  119537. }
  119538. }
  119539. L135:
  119540. t1=0;
  119541. t2=ido<<1;
  119542. t3=0;
  119543. t4=ipp2*t0;
  119544. for(j=1;j<ipph;j++){
  119545. t1+=t2;
  119546. t3+=t0;
  119547. t4-=t0;
  119548. t5=t1;
  119549. t6=t3;
  119550. t7=t4;
  119551. for(k=0;k<l1;k++){
  119552. cc[t5-1]=ch[t6];
  119553. cc[t5]=ch[t7];
  119554. t5+=t10;
  119555. t6+=ido;
  119556. t7+=ido;
  119557. }
  119558. }
  119559. if(ido==1)return;
  119560. if(nbd<l1)goto L141;
  119561. t1=-ido;
  119562. t3=0;
  119563. t4=0;
  119564. t5=ipp2*t0;
  119565. for(j=1;j<ipph;j++){
  119566. t1+=t2;
  119567. t3+=t2;
  119568. t4+=t0;
  119569. t5-=t0;
  119570. t6=t1;
  119571. t7=t3;
  119572. t8=t4;
  119573. t9=t5;
  119574. for(k=0;k<l1;k++){
  119575. for(i=2;i<ido;i+=2){
  119576. ic=idp2-i;
  119577. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  119578. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  119579. cc[i+t7]=ch[i+t8]+ch[i+t9];
  119580. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  119581. }
  119582. t6+=t10;
  119583. t7+=t10;
  119584. t8+=ido;
  119585. t9+=ido;
  119586. }
  119587. }
  119588. return;
  119589. L141:
  119590. t1=-ido;
  119591. t3=0;
  119592. t4=0;
  119593. t5=ipp2*t0;
  119594. for(j=1;j<ipph;j++){
  119595. t1+=t2;
  119596. t3+=t2;
  119597. t4+=t0;
  119598. t5-=t0;
  119599. for(i=2;i<ido;i+=2){
  119600. t6=idp2+t1-i;
  119601. t7=i+t3;
  119602. t8=i+t4;
  119603. t9=i+t5;
  119604. for(k=0;k<l1;k++){
  119605. cc[t7-1]=ch[t8-1]+ch[t9-1];
  119606. cc[t6-1]=ch[t8-1]-ch[t9-1];
  119607. cc[t7]=ch[t8]+ch[t9];
  119608. cc[t6]=ch[t9]-ch[t8];
  119609. t6+=t10;
  119610. t7+=t10;
  119611. t8+=ido;
  119612. t9+=ido;
  119613. }
  119614. }
  119615. }
  119616. }
  119617. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  119618. int i,k1,l1,l2;
  119619. int na,kh,nf;
  119620. int ip,iw,ido,idl1,ix2,ix3;
  119621. nf=ifac[1];
  119622. na=1;
  119623. l2=n;
  119624. iw=n;
  119625. for(k1=0;k1<nf;k1++){
  119626. kh=nf-k1;
  119627. ip=ifac[kh+1];
  119628. l1=l2/ip;
  119629. ido=n/l2;
  119630. idl1=ido*l1;
  119631. iw-=(ip-1)*ido;
  119632. na=1-na;
  119633. if(ip!=4)goto L102;
  119634. ix2=iw+ido;
  119635. ix3=ix2+ido;
  119636. if(na!=0)
  119637. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119638. else
  119639. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119640. goto L110;
  119641. L102:
  119642. if(ip!=2)goto L104;
  119643. if(na!=0)goto L103;
  119644. dradf2(ido,l1,c,ch,wa+iw-1);
  119645. goto L110;
  119646. L103:
  119647. dradf2(ido,l1,ch,c,wa+iw-1);
  119648. goto L110;
  119649. L104:
  119650. if(ido==1)na=1-na;
  119651. if(na!=0)goto L109;
  119652. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119653. na=1;
  119654. goto L110;
  119655. L109:
  119656. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119657. na=0;
  119658. L110:
  119659. l2=l1;
  119660. }
  119661. if(na==1)return;
  119662. for(i=0;i<n;i++)c[i]=ch[i];
  119663. }
  119664. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  119665. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119666. float ti2,tr2;
  119667. t0=l1*ido;
  119668. t1=0;
  119669. t2=0;
  119670. t3=(ido<<1)-1;
  119671. for(k=0;k<l1;k++){
  119672. ch[t1]=cc[t2]+cc[t3+t2];
  119673. ch[t1+t0]=cc[t2]-cc[t3+t2];
  119674. t2=(t1+=ido)<<1;
  119675. }
  119676. if(ido<2)return;
  119677. if(ido==2)goto L105;
  119678. t1=0;
  119679. t2=0;
  119680. for(k=0;k<l1;k++){
  119681. t3=t1;
  119682. t5=(t4=t2)+(ido<<1);
  119683. t6=t0+t1;
  119684. for(i=2;i<ido;i+=2){
  119685. t3+=2;
  119686. t4+=2;
  119687. t5-=2;
  119688. t6+=2;
  119689. ch[t3-1]=cc[t4-1]+cc[t5-1];
  119690. tr2=cc[t4-1]-cc[t5-1];
  119691. ch[t3]=cc[t4]-cc[t5];
  119692. ti2=cc[t4]+cc[t5];
  119693. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  119694. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  119695. }
  119696. t2=(t1+=ido)<<1;
  119697. }
  119698. if(ido%2==1)return;
  119699. L105:
  119700. t1=ido-1;
  119701. t2=ido-1;
  119702. for(k=0;k<l1;k++){
  119703. ch[t1]=cc[t2]+cc[t2];
  119704. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  119705. t1+=ido;
  119706. t2+=ido<<1;
  119707. }
  119708. }
  119709. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  119710. float *wa2){
  119711. static float taur = -.5f;
  119712. static float taui = .8660254037844386f;
  119713. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119714. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  119715. t0=l1*ido;
  119716. t1=0;
  119717. t2=t0<<1;
  119718. t3=ido<<1;
  119719. t4=ido+(ido<<1);
  119720. t5=0;
  119721. for(k=0;k<l1;k++){
  119722. tr2=cc[t3-1]+cc[t3-1];
  119723. cr2=cc[t5]+(taur*tr2);
  119724. ch[t1]=cc[t5]+tr2;
  119725. ci3=taui*(cc[t3]+cc[t3]);
  119726. ch[t1+t0]=cr2-ci3;
  119727. ch[t1+t2]=cr2+ci3;
  119728. t1+=ido;
  119729. t3+=t4;
  119730. t5+=t4;
  119731. }
  119732. if(ido==1)return;
  119733. t1=0;
  119734. t3=ido<<1;
  119735. for(k=0;k<l1;k++){
  119736. t7=t1+(t1<<1);
  119737. t6=(t5=t7+t3);
  119738. t8=t1;
  119739. t10=(t9=t1+t0)+t0;
  119740. for(i=2;i<ido;i+=2){
  119741. t5+=2;
  119742. t6-=2;
  119743. t7+=2;
  119744. t8+=2;
  119745. t9+=2;
  119746. t10+=2;
  119747. tr2=cc[t5-1]+cc[t6-1];
  119748. cr2=cc[t7-1]+(taur*tr2);
  119749. ch[t8-1]=cc[t7-1]+tr2;
  119750. ti2=cc[t5]-cc[t6];
  119751. ci2=cc[t7]+(taur*ti2);
  119752. ch[t8]=cc[t7]+ti2;
  119753. cr3=taui*(cc[t5-1]-cc[t6-1]);
  119754. ci3=taui*(cc[t5]+cc[t6]);
  119755. dr2=cr2-ci3;
  119756. dr3=cr2+ci3;
  119757. di2=ci2+cr3;
  119758. di3=ci2-cr3;
  119759. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  119760. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  119761. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  119762. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  119763. }
  119764. t1+=ido;
  119765. }
  119766. }
  119767. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  119768. float *wa2,float *wa3){
  119769. static float sqrt2=1.414213562373095f;
  119770. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  119771. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119772. t0=l1*ido;
  119773. t1=0;
  119774. t2=ido<<2;
  119775. t3=0;
  119776. t6=ido<<1;
  119777. for(k=0;k<l1;k++){
  119778. t4=t3+t6;
  119779. t5=t1;
  119780. tr3=cc[t4-1]+cc[t4-1];
  119781. tr4=cc[t4]+cc[t4];
  119782. tr1=cc[t3]-cc[(t4+=t6)-1];
  119783. tr2=cc[t3]+cc[t4-1];
  119784. ch[t5]=tr2+tr3;
  119785. ch[t5+=t0]=tr1-tr4;
  119786. ch[t5+=t0]=tr2-tr3;
  119787. ch[t5+=t0]=tr1+tr4;
  119788. t1+=ido;
  119789. t3+=t2;
  119790. }
  119791. if(ido<2)return;
  119792. if(ido==2)goto L105;
  119793. t1=0;
  119794. for(k=0;k<l1;k++){
  119795. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  119796. t7=t1;
  119797. for(i=2;i<ido;i+=2){
  119798. t2+=2;
  119799. t3+=2;
  119800. t4-=2;
  119801. t5-=2;
  119802. t7+=2;
  119803. ti1=cc[t2]+cc[t5];
  119804. ti2=cc[t2]-cc[t5];
  119805. ti3=cc[t3]-cc[t4];
  119806. tr4=cc[t3]+cc[t4];
  119807. tr1=cc[t2-1]-cc[t5-1];
  119808. tr2=cc[t2-1]+cc[t5-1];
  119809. ti4=cc[t3-1]-cc[t4-1];
  119810. tr3=cc[t3-1]+cc[t4-1];
  119811. ch[t7-1]=tr2+tr3;
  119812. cr3=tr2-tr3;
  119813. ch[t7]=ti2+ti3;
  119814. ci3=ti2-ti3;
  119815. cr2=tr1-tr4;
  119816. cr4=tr1+tr4;
  119817. ci2=ti1+ti4;
  119818. ci4=ti1-ti4;
  119819. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  119820. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  119821. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  119822. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  119823. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  119824. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  119825. }
  119826. t1+=ido;
  119827. }
  119828. if(ido%2 == 1)return;
  119829. L105:
  119830. t1=ido;
  119831. t2=ido<<2;
  119832. t3=ido-1;
  119833. t4=ido+(ido<<1);
  119834. for(k=0;k<l1;k++){
  119835. t5=t3;
  119836. ti1=cc[t1]+cc[t4];
  119837. ti2=cc[t4]-cc[t1];
  119838. tr1=cc[t1-1]-cc[t4-1];
  119839. tr2=cc[t1-1]+cc[t4-1];
  119840. ch[t5]=tr2+tr2;
  119841. ch[t5+=t0]=sqrt2*(tr1-ti1);
  119842. ch[t5+=t0]=ti2+ti2;
  119843. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  119844. t3+=ido;
  119845. t1+=t2;
  119846. t4+=t2;
  119847. }
  119848. }
  119849. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119850. float *c2,float *ch,float *ch2,float *wa){
  119851. static float tpi=6.283185307179586f;
  119852. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  119853. t11,t12;
  119854. float dc2,ai1,ai2,ar1,ar2,ds2;
  119855. int nbd;
  119856. float dcp,arg,dsp,ar1h,ar2h;
  119857. int ipp2;
  119858. t10=ip*ido;
  119859. t0=l1*ido;
  119860. arg=tpi/(float)ip;
  119861. dcp=cos(arg);
  119862. dsp=sin(arg);
  119863. nbd=(ido-1)>>1;
  119864. ipp2=ip;
  119865. ipph=(ip+1)>>1;
  119866. if(ido<l1)goto L103;
  119867. t1=0;
  119868. t2=0;
  119869. for(k=0;k<l1;k++){
  119870. t3=t1;
  119871. t4=t2;
  119872. for(i=0;i<ido;i++){
  119873. ch[t3]=cc[t4];
  119874. t3++;
  119875. t4++;
  119876. }
  119877. t1+=ido;
  119878. t2+=t10;
  119879. }
  119880. goto L106;
  119881. L103:
  119882. t1=0;
  119883. for(i=0;i<ido;i++){
  119884. t2=t1;
  119885. t3=t1;
  119886. for(k=0;k<l1;k++){
  119887. ch[t2]=cc[t3];
  119888. t2+=ido;
  119889. t3+=t10;
  119890. }
  119891. t1++;
  119892. }
  119893. L106:
  119894. t1=0;
  119895. t2=ipp2*t0;
  119896. t7=(t5=ido<<1);
  119897. for(j=1;j<ipph;j++){
  119898. t1+=t0;
  119899. t2-=t0;
  119900. t3=t1;
  119901. t4=t2;
  119902. t6=t5;
  119903. for(k=0;k<l1;k++){
  119904. ch[t3]=cc[t6-1]+cc[t6-1];
  119905. ch[t4]=cc[t6]+cc[t6];
  119906. t3+=ido;
  119907. t4+=ido;
  119908. t6+=t10;
  119909. }
  119910. t5+=t7;
  119911. }
  119912. if (ido == 1)goto L116;
  119913. if(nbd<l1)goto L112;
  119914. t1=0;
  119915. t2=ipp2*t0;
  119916. t7=0;
  119917. for(j=1;j<ipph;j++){
  119918. t1+=t0;
  119919. t2-=t0;
  119920. t3=t1;
  119921. t4=t2;
  119922. t7+=(ido<<1);
  119923. t8=t7;
  119924. for(k=0;k<l1;k++){
  119925. t5=t3;
  119926. t6=t4;
  119927. t9=t8;
  119928. t11=t8;
  119929. for(i=2;i<ido;i+=2){
  119930. t5+=2;
  119931. t6+=2;
  119932. t9+=2;
  119933. t11-=2;
  119934. ch[t5-1]=cc[t9-1]+cc[t11-1];
  119935. ch[t6-1]=cc[t9-1]-cc[t11-1];
  119936. ch[t5]=cc[t9]-cc[t11];
  119937. ch[t6]=cc[t9]+cc[t11];
  119938. }
  119939. t3+=ido;
  119940. t4+=ido;
  119941. t8+=t10;
  119942. }
  119943. }
  119944. goto L116;
  119945. L112:
  119946. t1=0;
  119947. t2=ipp2*t0;
  119948. t7=0;
  119949. for(j=1;j<ipph;j++){
  119950. t1+=t0;
  119951. t2-=t0;
  119952. t3=t1;
  119953. t4=t2;
  119954. t7+=(ido<<1);
  119955. t8=t7;
  119956. t9=t7;
  119957. for(i=2;i<ido;i+=2){
  119958. t3+=2;
  119959. t4+=2;
  119960. t8+=2;
  119961. t9-=2;
  119962. t5=t3;
  119963. t6=t4;
  119964. t11=t8;
  119965. t12=t9;
  119966. for(k=0;k<l1;k++){
  119967. ch[t5-1]=cc[t11-1]+cc[t12-1];
  119968. ch[t6-1]=cc[t11-1]-cc[t12-1];
  119969. ch[t5]=cc[t11]-cc[t12];
  119970. ch[t6]=cc[t11]+cc[t12];
  119971. t5+=ido;
  119972. t6+=ido;
  119973. t11+=t10;
  119974. t12+=t10;
  119975. }
  119976. }
  119977. }
  119978. L116:
  119979. ar1=1.f;
  119980. ai1=0.f;
  119981. t1=0;
  119982. t9=(t2=ipp2*idl1);
  119983. t3=(ip-1)*idl1;
  119984. for(l=1;l<ipph;l++){
  119985. t1+=idl1;
  119986. t2-=idl1;
  119987. ar1h=dcp*ar1-dsp*ai1;
  119988. ai1=dcp*ai1+dsp*ar1;
  119989. ar1=ar1h;
  119990. t4=t1;
  119991. t5=t2;
  119992. t6=0;
  119993. t7=idl1;
  119994. t8=t3;
  119995. for(ik=0;ik<idl1;ik++){
  119996. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  119997. c2[t5++]=ai1*ch2[t8++];
  119998. }
  119999. dc2=ar1;
  120000. ds2=ai1;
  120001. ar2=ar1;
  120002. ai2=ai1;
  120003. t6=idl1;
  120004. t7=t9-idl1;
  120005. for(j=2;j<ipph;j++){
  120006. t6+=idl1;
  120007. t7-=idl1;
  120008. ar2h=dc2*ar2-ds2*ai2;
  120009. ai2=dc2*ai2+ds2*ar2;
  120010. ar2=ar2h;
  120011. t4=t1;
  120012. t5=t2;
  120013. t11=t6;
  120014. t12=t7;
  120015. for(ik=0;ik<idl1;ik++){
  120016. c2[t4++]+=ar2*ch2[t11++];
  120017. c2[t5++]+=ai2*ch2[t12++];
  120018. }
  120019. }
  120020. }
  120021. t1=0;
  120022. for(j=1;j<ipph;j++){
  120023. t1+=idl1;
  120024. t2=t1;
  120025. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120026. }
  120027. t1=0;
  120028. t2=ipp2*t0;
  120029. for(j=1;j<ipph;j++){
  120030. t1+=t0;
  120031. t2-=t0;
  120032. t3=t1;
  120033. t4=t2;
  120034. for(k=0;k<l1;k++){
  120035. ch[t3]=c1[t3]-c1[t4];
  120036. ch[t4]=c1[t3]+c1[t4];
  120037. t3+=ido;
  120038. t4+=ido;
  120039. }
  120040. }
  120041. if(ido==1)goto L132;
  120042. if(nbd<l1)goto L128;
  120043. t1=0;
  120044. t2=ipp2*t0;
  120045. for(j=1;j<ipph;j++){
  120046. t1+=t0;
  120047. t2-=t0;
  120048. t3=t1;
  120049. t4=t2;
  120050. for(k=0;k<l1;k++){
  120051. t5=t3;
  120052. t6=t4;
  120053. for(i=2;i<ido;i+=2){
  120054. t5+=2;
  120055. t6+=2;
  120056. ch[t5-1]=c1[t5-1]-c1[t6];
  120057. ch[t6-1]=c1[t5-1]+c1[t6];
  120058. ch[t5]=c1[t5]+c1[t6-1];
  120059. ch[t6]=c1[t5]-c1[t6-1];
  120060. }
  120061. t3+=ido;
  120062. t4+=ido;
  120063. }
  120064. }
  120065. goto L132;
  120066. L128:
  120067. t1=0;
  120068. t2=ipp2*t0;
  120069. for(j=1;j<ipph;j++){
  120070. t1+=t0;
  120071. t2-=t0;
  120072. t3=t1;
  120073. t4=t2;
  120074. for(i=2;i<ido;i+=2){
  120075. t3+=2;
  120076. t4+=2;
  120077. t5=t3;
  120078. t6=t4;
  120079. for(k=0;k<l1;k++){
  120080. ch[t5-1]=c1[t5-1]-c1[t6];
  120081. ch[t6-1]=c1[t5-1]+c1[t6];
  120082. ch[t5]=c1[t5]+c1[t6-1];
  120083. ch[t6]=c1[t5]-c1[t6-1];
  120084. t5+=ido;
  120085. t6+=ido;
  120086. }
  120087. }
  120088. }
  120089. L132:
  120090. if(ido==1)return;
  120091. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120092. t1=0;
  120093. for(j=1;j<ip;j++){
  120094. t2=(t1+=t0);
  120095. for(k=0;k<l1;k++){
  120096. c1[t2]=ch[t2];
  120097. t2+=ido;
  120098. }
  120099. }
  120100. if(nbd>l1)goto L139;
  120101. is= -ido-1;
  120102. t1=0;
  120103. for(j=1;j<ip;j++){
  120104. is+=ido;
  120105. t1+=t0;
  120106. idij=is;
  120107. t2=t1;
  120108. for(i=2;i<ido;i+=2){
  120109. t2+=2;
  120110. idij+=2;
  120111. t3=t2;
  120112. for(k=0;k<l1;k++){
  120113. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120114. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120115. t3+=ido;
  120116. }
  120117. }
  120118. }
  120119. return;
  120120. L139:
  120121. is= -ido-1;
  120122. t1=0;
  120123. for(j=1;j<ip;j++){
  120124. is+=ido;
  120125. t1+=t0;
  120126. t2=t1;
  120127. for(k=0;k<l1;k++){
  120128. idij=is;
  120129. t3=t2;
  120130. for(i=2;i<ido;i+=2){
  120131. idij+=2;
  120132. t3+=2;
  120133. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120134. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120135. }
  120136. t2+=ido;
  120137. }
  120138. }
  120139. }
  120140. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120141. int i,k1,l1,l2;
  120142. int na;
  120143. int nf,ip,iw,ix2,ix3,ido,idl1;
  120144. nf=ifac[1];
  120145. na=0;
  120146. l1=1;
  120147. iw=1;
  120148. for(k1=0;k1<nf;k1++){
  120149. ip=ifac[k1 + 2];
  120150. l2=ip*l1;
  120151. ido=n/l2;
  120152. idl1=ido*l1;
  120153. if(ip!=4)goto L103;
  120154. ix2=iw+ido;
  120155. ix3=ix2+ido;
  120156. if(na!=0)
  120157. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120158. else
  120159. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120160. na=1-na;
  120161. goto L115;
  120162. L103:
  120163. if(ip!=2)goto L106;
  120164. if(na!=0)
  120165. dradb2(ido,l1,ch,c,wa+iw-1);
  120166. else
  120167. dradb2(ido,l1,c,ch,wa+iw-1);
  120168. na=1-na;
  120169. goto L115;
  120170. L106:
  120171. if(ip!=3)goto L109;
  120172. ix2=iw+ido;
  120173. if(na!=0)
  120174. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120175. else
  120176. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120177. na=1-na;
  120178. goto L115;
  120179. L109:
  120180. /* The radix five case can be translated later..... */
  120181. /* if(ip!=5)goto L112;
  120182. ix2=iw+ido;
  120183. ix3=ix2+ido;
  120184. ix4=ix3+ido;
  120185. if(na!=0)
  120186. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120187. else
  120188. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120189. na=1-na;
  120190. goto L115;
  120191. L112:*/
  120192. if(na!=0)
  120193. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120194. else
  120195. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120196. if(ido==1)na=1-na;
  120197. L115:
  120198. l1=l2;
  120199. iw+=(ip-1)*ido;
  120200. }
  120201. if(na==0)return;
  120202. for(i=0;i<n;i++)c[i]=ch[i];
  120203. }
  120204. void drft_forward(drft_lookup *l,float *data){
  120205. if(l->n==1)return;
  120206. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120207. }
  120208. void drft_backward(drft_lookup *l,float *data){
  120209. if (l->n==1)return;
  120210. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120211. }
  120212. void drft_init(drft_lookup *l,int n){
  120213. l->n=n;
  120214. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120215. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120216. fdrffti(n, l->trigcache, l->splitcache);
  120217. }
  120218. void drft_clear(drft_lookup *l){
  120219. if(l){
  120220. if(l->trigcache)_ogg_free(l->trigcache);
  120221. if(l->splitcache)_ogg_free(l->splitcache);
  120222. memset(l,0,sizeof(*l));
  120223. }
  120224. }
  120225. #endif
  120226. /*** End of inlined file: smallft.c ***/
  120227. /*** Start of inlined file: synthesis.c ***/
  120228. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120229. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120230. // tasks..
  120231. #if JUCE_MSVC
  120232. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120233. #endif
  120234. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120235. #if JUCE_USE_OGGVORBIS
  120236. #include <stdio.h>
  120237. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120238. vorbis_dsp_state *vd=vb->vd;
  120239. private_state *b=(private_state*)vd->backend_state;
  120240. vorbis_info *vi=vd->vi;
  120241. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120242. oggpack_buffer *opb=&vb->opb;
  120243. int type,mode,i;
  120244. /* first things first. Make sure decode is ready */
  120245. _vorbis_block_ripcord(vb);
  120246. oggpack_readinit(opb,op->packet,op->bytes);
  120247. /* Check the packet type */
  120248. if(oggpack_read(opb,1)!=0){
  120249. /* Oops. This is not an audio data packet */
  120250. return(OV_ENOTAUDIO);
  120251. }
  120252. /* read our mode and pre/post windowsize */
  120253. mode=oggpack_read(opb,b->modebits);
  120254. if(mode==-1)return(OV_EBADPACKET);
  120255. vb->mode=mode;
  120256. vb->W=ci->mode_param[mode]->blockflag;
  120257. if(vb->W){
  120258. /* this doesn;t get mapped through mode selection as it's used
  120259. only for window selection */
  120260. vb->lW=oggpack_read(opb,1);
  120261. vb->nW=oggpack_read(opb,1);
  120262. if(vb->nW==-1) return(OV_EBADPACKET);
  120263. }else{
  120264. vb->lW=0;
  120265. vb->nW=0;
  120266. }
  120267. /* more setup */
  120268. vb->granulepos=op->granulepos;
  120269. vb->sequence=op->packetno;
  120270. vb->eofflag=op->e_o_s;
  120271. /* alloc pcm passback storage */
  120272. vb->pcmend=ci->blocksizes[vb->W];
  120273. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120274. for(i=0;i<vi->channels;i++)
  120275. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120276. /* unpack_header enforces range checking */
  120277. type=ci->map_type[ci->mode_param[mode]->mapping];
  120278. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120279. mapping]));
  120280. }
  120281. /* used to track pcm position without actually performing decode.
  120282. Useful for sequential 'fast forward' */
  120283. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120284. vorbis_dsp_state *vd=vb->vd;
  120285. private_state *b=(private_state*)vd->backend_state;
  120286. vorbis_info *vi=vd->vi;
  120287. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120288. oggpack_buffer *opb=&vb->opb;
  120289. int mode;
  120290. /* first things first. Make sure decode is ready */
  120291. _vorbis_block_ripcord(vb);
  120292. oggpack_readinit(opb,op->packet,op->bytes);
  120293. /* Check the packet type */
  120294. if(oggpack_read(opb,1)!=0){
  120295. /* Oops. This is not an audio data packet */
  120296. return(OV_ENOTAUDIO);
  120297. }
  120298. /* read our mode and pre/post windowsize */
  120299. mode=oggpack_read(opb,b->modebits);
  120300. if(mode==-1)return(OV_EBADPACKET);
  120301. vb->mode=mode;
  120302. vb->W=ci->mode_param[mode]->blockflag;
  120303. if(vb->W){
  120304. vb->lW=oggpack_read(opb,1);
  120305. vb->nW=oggpack_read(opb,1);
  120306. if(vb->nW==-1) return(OV_EBADPACKET);
  120307. }else{
  120308. vb->lW=0;
  120309. vb->nW=0;
  120310. }
  120311. /* more setup */
  120312. vb->granulepos=op->granulepos;
  120313. vb->sequence=op->packetno;
  120314. vb->eofflag=op->e_o_s;
  120315. /* no pcm */
  120316. vb->pcmend=0;
  120317. vb->pcm=NULL;
  120318. return(0);
  120319. }
  120320. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120321. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120322. oggpack_buffer opb;
  120323. int mode;
  120324. oggpack_readinit(&opb,op->packet,op->bytes);
  120325. /* Check the packet type */
  120326. if(oggpack_read(&opb,1)!=0){
  120327. /* Oops. This is not an audio data packet */
  120328. return(OV_ENOTAUDIO);
  120329. }
  120330. {
  120331. int modebits=0;
  120332. int v=ci->modes;
  120333. while(v>1){
  120334. modebits++;
  120335. v>>=1;
  120336. }
  120337. /* read our mode and pre/post windowsize */
  120338. mode=oggpack_read(&opb,modebits);
  120339. }
  120340. if(mode==-1)return(OV_EBADPACKET);
  120341. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120342. }
  120343. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120344. /* set / clear half-sample-rate mode */
  120345. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120346. /* right now, our MDCT can't handle < 64 sample windows. */
  120347. if(ci->blocksizes[0]<=64 && flag)return -1;
  120348. ci->halfrate_flag=(flag?1:0);
  120349. return 0;
  120350. }
  120351. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120352. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120353. return ci->halfrate_flag;
  120354. }
  120355. #endif
  120356. /*** End of inlined file: synthesis.c ***/
  120357. /*** Start of inlined file: vorbisenc.c ***/
  120358. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120359. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120360. // tasks..
  120361. #if JUCE_MSVC
  120362. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120363. #endif
  120364. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120365. #if JUCE_USE_OGGVORBIS
  120366. #include <stdlib.h>
  120367. #include <string.h>
  120368. #include <math.h>
  120369. /* careful with this; it's using static array sizing to make managing
  120370. all the modes a little less annoying. If we use a residue backend
  120371. with > 12 partition types, or a different division of iteration,
  120372. this needs to be updated. */
  120373. typedef struct {
  120374. static_codebook *books[12][3];
  120375. } static_bookblock;
  120376. typedef struct {
  120377. int res_type;
  120378. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120379. vorbis_info_residue0 *res;
  120380. static_codebook *book_aux;
  120381. static_codebook *book_aux_managed;
  120382. static_bookblock *books_base;
  120383. static_bookblock *books_base_managed;
  120384. } vorbis_residue_template;
  120385. typedef struct {
  120386. vorbis_info_mapping0 *map;
  120387. vorbis_residue_template *res;
  120388. } vorbis_mapping_template;
  120389. typedef struct vp_adjblock{
  120390. int block[P_BANDS];
  120391. } vp_adjblock;
  120392. typedef struct {
  120393. int data[NOISE_COMPAND_LEVELS];
  120394. } compandblock;
  120395. /* high level configuration information for setting things up
  120396. step-by-step with the detailed vorbis_encode_ctl interface.
  120397. There's a fair amount of redundancy such that interactive setup
  120398. does not directly deal with any vorbis_info or codec_setup_info
  120399. initialization; it's all stored (until full init) in this highlevel
  120400. setup, then flushed out to the real codec setup structs later. */
  120401. typedef struct {
  120402. int att[P_NOISECURVES];
  120403. float boost;
  120404. float decay;
  120405. } att3;
  120406. typedef struct { int data[P_NOISECURVES]; } adj3;
  120407. typedef struct {
  120408. int pre[PACKETBLOBS];
  120409. int post[PACKETBLOBS];
  120410. float kHz[PACKETBLOBS];
  120411. float lowpasskHz[PACKETBLOBS];
  120412. } adj_stereo;
  120413. typedef struct {
  120414. int lo;
  120415. int hi;
  120416. int fixed;
  120417. } noiseguard;
  120418. typedef struct {
  120419. int data[P_NOISECURVES][17];
  120420. } noise3;
  120421. typedef struct {
  120422. int mappings;
  120423. double *rate_mapping;
  120424. double *quality_mapping;
  120425. int coupling_restriction;
  120426. long samplerate_min_restriction;
  120427. long samplerate_max_restriction;
  120428. int *blocksize_short;
  120429. int *blocksize_long;
  120430. att3 *psy_tone_masteratt;
  120431. int *psy_tone_0dB;
  120432. int *psy_tone_dBsuppress;
  120433. vp_adjblock *psy_tone_adj_impulse;
  120434. vp_adjblock *psy_tone_adj_long;
  120435. vp_adjblock *psy_tone_adj_other;
  120436. noiseguard *psy_noiseguards;
  120437. noise3 *psy_noise_bias_impulse;
  120438. noise3 *psy_noise_bias_padding;
  120439. noise3 *psy_noise_bias_trans;
  120440. noise3 *psy_noise_bias_long;
  120441. int *psy_noise_dBsuppress;
  120442. compandblock *psy_noise_compand;
  120443. double *psy_noise_compand_short_mapping;
  120444. double *psy_noise_compand_long_mapping;
  120445. int *psy_noise_normal_start[2];
  120446. int *psy_noise_normal_partition[2];
  120447. double *psy_noise_normal_thresh;
  120448. int *psy_ath_float;
  120449. int *psy_ath_abs;
  120450. double *psy_lowpass;
  120451. vorbis_info_psy_global *global_params;
  120452. double *global_mapping;
  120453. adj_stereo *stereo_modes;
  120454. static_codebook ***floor_books;
  120455. vorbis_info_floor1 *floor_params;
  120456. int *floor_short_mapping;
  120457. int *floor_long_mapping;
  120458. vorbis_mapping_template *maps;
  120459. } ve_setup_data_template;
  120460. /* a few static coder conventions */
  120461. static vorbis_info_mode _mode_template[2]={
  120462. {0,0,0,0},
  120463. {1,0,0,1}
  120464. };
  120465. static vorbis_info_mapping0 _map_nominal[2]={
  120466. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120467. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120468. };
  120469. /*** Start of inlined file: setup_44.h ***/
  120470. /*** Start of inlined file: floor_all.h ***/
  120471. /*** Start of inlined file: floor_books.h ***/
  120472. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120473. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120474. };
  120475. static static_codebook _huff_book_line_256x7_0sub1 = {
  120476. 1, 9,
  120477. _huff_lengthlist_line_256x7_0sub1,
  120478. 0, 0, 0, 0, 0,
  120479. NULL,
  120480. NULL,
  120481. NULL,
  120482. NULL,
  120483. 0
  120484. };
  120485. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120487. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120488. };
  120489. static static_codebook _huff_book_line_256x7_0sub2 = {
  120490. 1, 25,
  120491. _huff_lengthlist_line_256x7_0sub2,
  120492. 0, 0, 0, 0, 0,
  120493. NULL,
  120494. NULL,
  120495. NULL,
  120496. NULL,
  120497. 0
  120498. };
  120499. static long _huff_lengthlist_line_256x7_0sub3[] = {
  120500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  120502. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  120503. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  120504. };
  120505. static static_codebook _huff_book_line_256x7_0sub3 = {
  120506. 1, 64,
  120507. _huff_lengthlist_line_256x7_0sub3,
  120508. 0, 0, 0, 0, 0,
  120509. NULL,
  120510. NULL,
  120511. NULL,
  120512. NULL,
  120513. 0
  120514. };
  120515. static long _huff_lengthlist_line_256x7_1sub1[] = {
  120516. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  120517. };
  120518. static static_codebook _huff_book_line_256x7_1sub1 = {
  120519. 1, 9,
  120520. _huff_lengthlist_line_256x7_1sub1,
  120521. 0, 0, 0, 0, 0,
  120522. NULL,
  120523. NULL,
  120524. NULL,
  120525. NULL,
  120526. 0
  120527. };
  120528. static long _huff_lengthlist_line_256x7_1sub2[] = {
  120529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  120530. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  120531. };
  120532. static static_codebook _huff_book_line_256x7_1sub2 = {
  120533. 1, 25,
  120534. _huff_lengthlist_line_256x7_1sub2,
  120535. 0, 0, 0, 0, 0,
  120536. NULL,
  120537. NULL,
  120538. NULL,
  120539. NULL,
  120540. 0
  120541. };
  120542. static long _huff_lengthlist_line_256x7_1sub3[] = {
  120543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  120545. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120546. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  120547. };
  120548. static static_codebook _huff_book_line_256x7_1sub3 = {
  120549. 1, 64,
  120550. _huff_lengthlist_line_256x7_1sub3,
  120551. 0, 0, 0, 0, 0,
  120552. NULL,
  120553. NULL,
  120554. NULL,
  120555. NULL,
  120556. 0
  120557. };
  120558. static long _huff_lengthlist_line_256x7_class0[] = {
  120559. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  120560. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  120561. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  120562. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  120563. };
  120564. static static_codebook _huff_book_line_256x7_class0 = {
  120565. 1, 64,
  120566. _huff_lengthlist_line_256x7_class0,
  120567. 0, 0, 0, 0, 0,
  120568. NULL,
  120569. NULL,
  120570. NULL,
  120571. NULL,
  120572. 0
  120573. };
  120574. static long _huff_lengthlist_line_256x7_class1[] = {
  120575. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  120576. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  120577. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  120578. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  120579. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  120580. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  120581. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  120582. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  120583. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  120584. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  120585. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  120586. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  120587. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120588. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120589. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  120590. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  120591. };
  120592. static static_codebook _huff_book_line_256x7_class1 = {
  120593. 1, 256,
  120594. _huff_lengthlist_line_256x7_class1,
  120595. 0, 0, 0, 0, 0,
  120596. NULL,
  120597. NULL,
  120598. NULL,
  120599. NULL,
  120600. 0
  120601. };
  120602. static long _huff_lengthlist_line_512x17_0sub0[] = {
  120603. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  120604. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  120605. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  120606. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  120607. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  120608. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  120609. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  120610. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120611. };
  120612. static static_codebook _huff_book_line_512x17_0sub0 = {
  120613. 1, 128,
  120614. _huff_lengthlist_line_512x17_0sub0,
  120615. 0, 0, 0, 0, 0,
  120616. NULL,
  120617. NULL,
  120618. NULL,
  120619. NULL,
  120620. 0
  120621. };
  120622. static long _huff_lengthlist_line_512x17_1sub0[] = {
  120623. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120624. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  120625. };
  120626. static static_codebook _huff_book_line_512x17_1sub0 = {
  120627. 1, 32,
  120628. _huff_lengthlist_line_512x17_1sub0,
  120629. 0, 0, 0, 0, 0,
  120630. NULL,
  120631. NULL,
  120632. NULL,
  120633. NULL,
  120634. 0
  120635. };
  120636. static long _huff_lengthlist_line_512x17_1sub1[] = {
  120637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120639. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  120640. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  120641. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  120642. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  120643. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  120644. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120645. };
  120646. static static_codebook _huff_book_line_512x17_1sub1 = {
  120647. 1, 128,
  120648. _huff_lengthlist_line_512x17_1sub1,
  120649. 0, 0, 0, 0, 0,
  120650. NULL,
  120651. NULL,
  120652. NULL,
  120653. NULL,
  120654. 0
  120655. };
  120656. static long _huff_lengthlist_line_512x17_2sub1[] = {
  120657. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  120658. 5, 3,
  120659. };
  120660. static static_codebook _huff_book_line_512x17_2sub1 = {
  120661. 1, 18,
  120662. _huff_lengthlist_line_512x17_2sub1,
  120663. 0, 0, 0, 0, 0,
  120664. NULL,
  120665. NULL,
  120666. NULL,
  120667. NULL,
  120668. 0
  120669. };
  120670. static long _huff_lengthlist_line_512x17_2sub2[] = {
  120671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120672. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  120673. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  120674. 9, 8,
  120675. };
  120676. static static_codebook _huff_book_line_512x17_2sub2 = {
  120677. 1, 50,
  120678. _huff_lengthlist_line_512x17_2sub2,
  120679. 0, 0, 0, 0, 0,
  120680. NULL,
  120681. NULL,
  120682. NULL,
  120683. NULL,
  120684. 0
  120685. };
  120686. static long _huff_lengthlist_line_512x17_2sub3[] = {
  120687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120690. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  120691. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  120692. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120693. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120694. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120695. };
  120696. static static_codebook _huff_book_line_512x17_2sub3 = {
  120697. 1, 128,
  120698. _huff_lengthlist_line_512x17_2sub3,
  120699. 0, 0, 0, 0, 0,
  120700. NULL,
  120701. NULL,
  120702. NULL,
  120703. NULL,
  120704. 0
  120705. };
  120706. static long _huff_lengthlist_line_512x17_3sub1[] = {
  120707. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  120708. 5, 5,
  120709. };
  120710. static static_codebook _huff_book_line_512x17_3sub1 = {
  120711. 1, 18,
  120712. _huff_lengthlist_line_512x17_3sub1,
  120713. 0, 0, 0, 0, 0,
  120714. NULL,
  120715. NULL,
  120716. NULL,
  120717. NULL,
  120718. 0
  120719. };
  120720. static long _huff_lengthlist_line_512x17_3sub2[] = {
  120721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120722. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  120723. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  120724. 11,14,
  120725. };
  120726. static static_codebook _huff_book_line_512x17_3sub2 = {
  120727. 1, 50,
  120728. _huff_lengthlist_line_512x17_3sub2,
  120729. 0, 0, 0, 0, 0,
  120730. NULL,
  120731. NULL,
  120732. NULL,
  120733. NULL,
  120734. 0
  120735. };
  120736. static long _huff_lengthlist_line_512x17_3sub3[] = {
  120737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120740. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  120741. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120742. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120743. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120744. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120745. };
  120746. static static_codebook _huff_book_line_512x17_3sub3 = {
  120747. 1, 128,
  120748. _huff_lengthlist_line_512x17_3sub3,
  120749. 0, 0, 0, 0, 0,
  120750. NULL,
  120751. NULL,
  120752. NULL,
  120753. NULL,
  120754. 0
  120755. };
  120756. static long _huff_lengthlist_line_512x17_class1[] = {
  120757. 1, 2, 3, 6, 5, 4, 7, 7,
  120758. };
  120759. static static_codebook _huff_book_line_512x17_class1 = {
  120760. 1, 8,
  120761. _huff_lengthlist_line_512x17_class1,
  120762. 0, 0, 0, 0, 0,
  120763. NULL,
  120764. NULL,
  120765. NULL,
  120766. NULL,
  120767. 0
  120768. };
  120769. static long _huff_lengthlist_line_512x17_class2[] = {
  120770. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  120771. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  120772. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  120773. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  120774. };
  120775. static static_codebook _huff_book_line_512x17_class2 = {
  120776. 1, 64,
  120777. _huff_lengthlist_line_512x17_class2,
  120778. 0, 0, 0, 0, 0,
  120779. NULL,
  120780. NULL,
  120781. NULL,
  120782. NULL,
  120783. 0
  120784. };
  120785. static long _huff_lengthlist_line_512x17_class3[] = {
  120786. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  120787. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  120788. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  120789. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  120790. };
  120791. static static_codebook _huff_book_line_512x17_class3 = {
  120792. 1, 64,
  120793. _huff_lengthlist_line_512x17_class3,
  120794. 0, 0, 0, 0, 0,
  120795. NULL,
  120796. NULL,
  120797. NULL,
  120798. NULL,
  120799. 0
  120800. };
  120801. static long _huff_lengthlist_line_128x4_class0[] = {
  120802. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  120803. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  120804. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  120805. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  120806. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  120807. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  120808. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  120809. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  120810. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  120811. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  120812. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  120813. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  120814. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  120815. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  120816. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  120817. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  120818. };
  120819. static static_codebook _huff_book_line_128x4_class0 = {
  120820. 1, 256,
  120821. _huff_lengthlist_line_128x4_class0,
  120822. 0, 0, 0, 0, 0,
  120823. NULL,
  120824. NULL,
  120825. NULL,
  120826. NULL,
  120827. 0
  120828. };
  120829. static long _huff_lengthlist_line_128x4_0sub0[] = {
  120830. 2, 2, 2, 2,
  120831. };
  120832. static static_codebook _huff_book_line_128x4_0sub0 = {
  120833. 1, 4,
  120834. _huff_lengthlist_line_128x4_0sub0,
  120835. 0, 0, 0, 0, 0,
  120836. NULL,
  120837. NULL,
  120838. NULL,
  120839. NULL,
  120840. 0
  120841. };
  120842. static long _huff_lengthlist_line_128x4_0sub1[] = {
  120843. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  120844. };
  120845. static static_codebook _huff_book_line_128x4_0sub1 = {
  120846. 1, 10,
  120847. _huff_lengthlist_line_128x4_0sub1,
  120848. 0, 0, 0, 0, 0,
  120849. NULL,
  120850. NULL,
  120851. NULL,
  120852. NULL,
  120853. 0
  120854. };
  120855. static long _huff_lengthlist_line_128x4_0sub2[] = {
  120856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  120857. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  120858. };
  120859. static static_codebook _huff_book_line_128x4_0sub2 = {
  120860. 1, 25,
  120861. _huff_lengthlist_line_128x4_0sub2,
  120862. 0, 0, 0, 0, 0,
  120863. NULL,
  120864. NULL,
  120865. NULL,
  120866. NULL,
  120867. 0
  120868. };
  120869. static long _huff_lengthlist_line_128x4_0sub3[] = {
  120870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  120872. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  120873. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  120874. };
  120875. static static_codebook _huff_book_line_128x4_0sub3 = {
  120876. 1, 64,
  120877. _huff_lengthlist_line_128x4_0sub3,
  120878. 0, 0, 0, 0, 0,
  120879. NULL,
  120880. NULL,
  120881. NULL,
  120882. NULL,
  120883. 0
  120884. };
  120885. static long _huff_lengthlist_line_256x4_class0[] = {
  120886. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  120887. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  120888. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  120889. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  120890. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  120891. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  120892. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  120893. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  120894. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  120895. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  120896. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  120897. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  120898. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  120899. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  120900. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  120901. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  120902. };
  120903. static static_codebook _huff_book_line_256x4_class0 = {
  120904. 1, 256,
  120905. _huff_lengthlist_line_256x4_class0,
  120906. 0, 0, 0, 0, 0,
  120907. NULL,
  120908. NULL,
  120909. NULL,
  120910. NULL,
  120911. 0
  120912. };
  120913. static long _huff_lengthlist_line_256x4_0sub0[] = {
  120914. 2, 2, 2, 2,
  120915. };
  120916. static static_codebook _huff_book_line_256x4_0sub0 = {
  120917. 1, 4,
  120918. _huff_lengthlist_line_256x4_0sub0,
  120919. 0, 0, 0, 0, 0,
  120920. NULL,
  120921. NULL,
  120922. NULL,
  120923. NULL,
  120924. 0
  120925. };
  120926. static long _huff_lengthlist_line_256x4_0sub1[] = {
  120927. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  120928. };
  120929. static static_codebook _huff_book_line_256x4_0sub1 = {
  120930. 1, 10,
  120931. _huff_lengthlist_line_256x4_0sub1,
  120932. 0, 0, 0, 0, 0,
  120933. NULL,
  120934. NULL,
  120935. NULL,
  120936. NULL,
  120937. 0
  120938. };
  120939. static long _huff_lengthlist_line_256x4_0sub2[] = {
  120940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  120941. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  120942. };
  120943. static static_codebook _huff_book_line_256x4_0sub2 = {
  120944. 1, 25,
  120945. _huff_lengthlist_line_256x4_0sub2,
  120946. 0, 0, 0, 0, 0,
  120947. NULL,
  120948. NULL,
  120949. NULL,
  120950. NULL,
  120951. 0
  120952. };
  120953. static long _huff_lengthlist_line_256x4_0sub3[] = {
  120954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  120956. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  120957. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  120958. };
  120959. static static_codebook _huff_book_line_256x4_0sub3 = {
  120960. 1, 64,
  120961. _huff_lengthlist_line_256x4_0sub3,
  120962. 0, 0, 0, 0, 0,
  120963. NULL,
  120964. NULL,
  120965. NULL,
  120966. NULL,
  120967. 0
  120968. };
  120969. static long _huff_lengthlist_line_128x7_class0[] = {
  120970. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  120971. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  120972. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  120973. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  120974. };
  120975. static static_codebook _huff_book_line_128x7_class0 = {
  120976. 1, 64,
  120977. _huff_lengthlist_line_128x7_class0,
  120978. 0, 0, 0, 0, 0,
  120979. NULL,
  120980. NULL,
  120981. NULL,
  120982. NULL,
  120983. 0
  120984. };
  120985. static long _huff_lengthlist_line_128x7_class1[] = {
  120986. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  120987. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  120988. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  120989. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  120990. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  120991. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  120992. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  120993. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  120994. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  120995. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  120996. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  120997. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  120998. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  120999. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  121000. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  121001. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  121002. };
  121003. static static_codebook _huff_book_line_128x7_class1 = {
  121004. 1, 256,
  121005. _huff_lengthlist_line_128x7_class1,
  121006. 0, 0, 0, 0, 0,
  121007. NULL,
  121008. NULL,
  121009. NULL,
  121010. NULL,
  121011. 0
  121012. };
  121013. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121014. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  121015. };
  121016. static static_codebook _huff_book_line_128x7_0sub1 = {
  121017. 1, 9,
  121018. _huff_lengthlist_line_128x7_0sub1,
  121019. 0, 0, 0, 0, 0,
  121020. NULL,
  121021. NULL,
  121022. NULL,
  121023. NULL,
  121024. 0
  121025. };
  121026. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121028. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121029. };
  121030. static static_codebook _huff_book_line_128x7_0sub2 = {
  121031. 1, 25,
  121032. _huff_lengthlist_line_128x7_0sub2,
  121033. 0, 0, 0, 0, 0,
  121034. NULL,
  121035. NULL,
  121036. NULL,
  121037. NULL,
  121038. 0
  121039. };
  121040. static long _huff_lengthlist_line_128x7_0sub3[] = {
  121041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  121043. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121044. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121045. };
  121046. static static_codebook _huff_book_line_128x7_0sub3 = {
  121047. 1, 64,
  121048. _huff_lengthlist_line_128x7_0sub3,
  121049. 0, 0, 0, 0, 0,
  121050. NULL,
  121051. NULL,
  121052. NULL,
  121053. NULL,
  121054. 0
  121055. };
  121056. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121057. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121058. };
  121059. static static_codebook _huff_book_line_128x7_1sub1 = {
  121060. 1, 9,
  121061. _huff_lengthlist_line_128x7_1sub1,
  121062. 0, 0, 0, 0, 0,
  121063. NULL,
  121064. NULL,
  121065. NULL,
  121066. NULL,
  121067. 0
  121068. };
  121069. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121071. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121072. };
  121073. static static_codebook _huff_book_line_128x7_1sub2 = {
  121074. 1, 25,
  121075. _huff_lengthlist_line_128x7_1sub2,
  121076. 0, 0, 0, 0, 0,
  121077. NULL,
  121078. NULL,
  121079. NULL,
  121080. NULL,
  121081. 0
  121082. };
  121083. static long _huff_lengthlist_line_128x7_1sub3[] = {
  121084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  121086. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121087. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121088. };
  121089. static static_codebook _huff_book_line_128x7_1sub3 = {
  121090. 1, 64,
  121091. _huff_lengthlist_line_128x7_1sub3,
  121092. 0, 0, 0, 0, 0,
  121093. NULL,
  121094. NULL,
  121095. NULL,
  121096. NULL,
  121097. 0
  121098. };
  121099. static long _huff_lengthlist_line_128x11_class1[] = {
  121100. 1, 6, 3, 7, 2, 4, 5, 7,
  121101. };
  121102. static static_codebook _huff_book_line_128x11_class1 = {
  121103. 1, 8,
  121104. _huff_lengthlist_line_128x11_class1,
  121105. 0, 0, 0, 0, 0,
  121106. NULL,
  121107. NULL,
  121108. NULL,
  121109. NULL,
  121110. 0
  121111. };
  121112. static long _huff_lengthlist_line_128x11_class2[] = {
  121113. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121114. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121115. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121116. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121117. };
  121118. static static_codebook _huff_book_line_128x11_class2 = {
  121119. 1, 64,
  121120. _huff_lengthlist_line_128x11_class2,
  121121. 0, 0, 0, 0, 0,
  121122. NULL,
  121123. NULL,
  121124. NULL,
  121125. NULL,
  121126. 0
  121127. };
  121128. static long _huff_lengthlist_line_128x11_class3[] = {
  121129. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121130. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121131. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121132. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121133. };
  121134. static static_codebook _huff_book_line_128x11_class3 = {
  121135. 1, 64,
  121136. _huff_lengthlist_line_128x11_class3,
  121137. 0, 0, 0, 0, 0,
  121138. NULL,
  121139. NULL,
  121140. NULL,
  121141. NULL,
  121142. 0
  121143. };
  121144. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121145. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121146. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121147. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121148. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121149. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121150. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121151. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121152. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121153. };
  121154. static static_codebook _huff_book_line_128x11_0sub0 = {
  121155. 1, 128,
  121156. _huff_lengthlist_line_128x11_0sub0,
  121157. 0, 0, 0, 0, 0,
  121158. NULL,
  121159. NULL,
  121160. NULL,
  121161. NULL,
  121162. 0
  121163. };
  121164. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121165. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121166. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121167. };
  121168. static static_codebook _huff_book_line_128x11_1sub0 = {
  121169. 1, 32,
  121170. _huff_lengthlist_line_128x11_1sub0,
  121171. 0, 0, 0, 0, 0,
  121172. NULL,
  121173. NULL,
  121174. NULL,
  121175. NULL,
  121176. 0
  121177. };
  121178. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121181. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121182. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121183. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121184. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121185. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121186. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121187. };
  121188. static static_codebook _huff_book_line_128x11_1sub1 = {
  121189. 1, 128,
  121190. _huff_lengthlist_line_128x11_1sub1,
  121191. 0, 0, 0, 0, 0,
  121192. NULL,
  121193. NULL,
  121194. NULL,
  121195. NULL,
  121196. 0
  121197. };
  121198. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121199. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121200. 5, 5,
  121201. };
  121202. static static_codebook _huff_book_line_128x11_2sub1 = {
  121203. 1, 18,
  121204. _huff_lengthlist_line_128x11_2sub1,
  121205. 0, 0, 0, 0, 0,
  121206. NULL,
  121207. NULL,
  121208. NULL,
  121209. NULL,
  121210. 0
  121211. };
  121212. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121214. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121215. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121216. 8,11,
  121217. };
  121218. static static_codebook _huff_book_line_128x11_2sub2 = {
  121219. 1, 50,
  121220. _huff_lengthlist_line_128x11_2sub2,
  121221. 0, 0, 0, 0, 0,
  121222. NULL,
  121223. NULL,
  121224. NULL,
  121225. NULL,
  121226. 0
  121227. };
  121228. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121232. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121233. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121234. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121235. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121236. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121237. };
  121238. static static_codebook _huff_book_line_128x11_2sub3 = {
  121239. 1, 128,
  121240. _huff_lengthlist_line_128x11_2sub3,
  121241. 0, 0, 0, 0, 0,
  121242. NULL,
  121243. NULL,
  121244. NULL,
  121245. NULL,
  121246. 0
  121247. };
  121248. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121249. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121250. 5, 4,
  121251. };
  121252. static static_codebook _huff_book_line_128x11_3sub1 = {
  121253. 1, 18,
  121254. _huff_lengthlist_line_128x11_3sub1,
  121255. 0, 0, 0, 0, 0,
  121256. NULL,
  121257. NULL,
  121258. NULL,
  121259. NULL,
  121260. 0
  121261. };
  121262. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121264. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121265. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121266. 12, 6,
  121267. };
  121268. static static_codebook _huff_book_line_128x11_3sub2 = {
  121269. 1, 50,
  121270. _huff_lengthlist_line_128x11_3sub2,
  121271. 0, 0, 0, 0, 0,
  121272. NULL,
  121273. NULL,
  121274. NULL,
  121275. NULL,
  121276. 0
  121277. };
  121278. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121282. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121283. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121284. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121285. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121286. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121287. };
  121288. static static_codebook _huff_book_line_128x11_3sub3 = {
  121289. 1, 128,
  121290. _huff_lengthlist_line_128x11_3sub3,
  121291. 0, 0, 0, 0, 0,
  121292. NULL,
  121293. NULL,
  121294. NULL,
  121295. NULL,
  121296. 0
  121297. };
  121298. static long _huff_lengthlist_line_128x17_class1[] = {
  121299. 1, 3, 4, 7, 2, 5, 6, 7,
  121300. };
  121301. static static_codebook _huff_book_line_128x17_class1 = {
  121302. 1, 8,
  121303. _huff_lengthlist_line_128x17_class1,
  121304. 0, 0, 0, 0, 0,
  121305. NULL,
  121306. NULL,
  121307. NULL,
  121308. NULL,
  121309. 0
  121310. };
  121311. static long _huff_lengthlist_line_128x17_class2[] = {
  121312. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121313. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121314. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121315. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121316. };
  121317. static static_codebook _huff_book_line_128x17_class2 = {
  121318. 1, 64,
  121319. _huff_lengthlist_line_128x17_class2,
  121320. 0, 0, 0, 0, 0,
  121321. NULL,
  121322. NULL,
  121323. NULL,
  121324. NULL,
  121325. 0
  121326. };
  121327. static long _huff_lengthlist_line_128x17_class3[] = {
  121328. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121329. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121330. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121331. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121332. };
  121333. static static_codebook _huff_book_line_128x17_class3 = {
  121334. 1, 64,
  121335. _huff_lengthlist_line_128x17_class3,
  121336. 0, 0, 0, 0, 0,
  121337. NULL,
  121338. NULL,
  121339. NULL,
  121340. NULL,
  121341. 0
  121342. };
  121343. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121344. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121345. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121346. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121347. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121348. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121349. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121350. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121351. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121352. };
  121353. static static_codebook _huff_book_line_128x17_0sub0 = {
  121354. 1, 128,
  121355. _huff_lengthlist_line_128x17_0sub0,
  121356. 0, 0, 0, 0, 0,
  121357. NULL,
  121358. NULL,
  121359. NULL,
  121360. NULL,
  121361. 0
  121362. };
  121363. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121364. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121365. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121366. };
  121367. static static_codebook _huff_book_line_128x17_1sub0 = {
  121368. 1, 32,
  121369. _huff_lengthlist_line_128x17_1sub0,
  121370. 0, 0, 0, 0, 0,
  121371. NULL,
  121372. NULL,
  121373. NULL,
  121374. NULL,
  121375. 0
  121376. };
  121377. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121380. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121381. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121382. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121383. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121384. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121385. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121386. };
  121387. static static_codebook _huff_book_line_128x17_1sub1 = {
  121388. 1, 128,
  121389. _huff_lengthlist_line_128x17_1sub1,
  121390. 0, 0, 0, 0, 0,
  121391. NULL,
  121392. NULL,
  121393. NULL,
  121394. NULL,
  121395. 0
  121396. };
  121397. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121398. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121399. 9, 4,
  121400. };
  121401. static static_codebook _huff_book_line_128x17_2sub1 = {
  121402. 1, 18,
  121403. _huff_lengthlist_line_128x17_2sub1,
  121404. 0, 0, 0, 0, 0,
  121405. NULL,
  121406. NULL,
  121407. NULL,
  121408. NULL,
  121409. 0
  121410. };
  121411. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121413. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121414. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121415. 13,13,
  121416. };
  121417. static static_codebook _huff_book_line_128x17_2sub2 = {
  121418. 1, 50,
  121419. _huff_lengthlist_line_128x17_2sub2,
  121420. 0, 0, 0, 0, 0,
  121421. NULL,
  121422. NULL,
  121423. NULL,
  121424. NULL,
  121425. 0
  121426. };
  121427. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121431. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121432. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121433. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121434. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121435. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121436. };
  121437. static static_codebook _huff_book_line_128x17_2sub3 = {
  121438. 1, 128,
  121439. _huff_lengthlist_line_128x17_2sub3,
  121440. 0, 0, 0, 0, 0,
  121441. NULL,
  121442. NULL,
  121443. NULL,
  121444. NULL,
  121445. 0
  121446. };
  121447. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121448. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121449. 6, 4,
  121450. };
  121451. static static_codebook _huff_book_line_128x17_3sub1 = {
  121452. 1, 18,
  121453. _huff_lengthlist_line_128x17_3sub1,
  121454. 0, 0, 0, 0, 0,
  121455. NULL,
  121456. NULL,
  121457. NULL,
  121458. NULL,
  121459. 0
  121460. };
  121461. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121463. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121464. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121465. 10, 8,
  121466. };
  121467. static static_codebook _huff_book_line_128x17_3sub2 = {
  121468. 1, 50,
  121469. _huff_lengthlist_line_128x17_3sub2,
  121470. 0, 0, 0, 0, 0,
  121471. NULL,
  121472. NULL,
  121473. NULL,
  121474. NULL,
  121475. 0
  121476. };
  121477. static long _huff_lengthlist_line_128x17_3sub3[] = {
  121478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121481. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121482. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121483. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121484. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121485. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121486. };
  121487. static static_codebook _huff_book_line_128x17_3sub3 = {
  121488. 1, 128,
  121489. _huff_lengthlist_line_128x17_3sub3,
  121490. 0, 0, 0, 0, 0,
  121491. NULL,
  121492. NULL,
  121493. NULL,
  121494. NULL,
  121495. 0
  121496. };
  121497. static long _huff_lengthlist_line_1024x27_class1[] = {
  121498. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  121499. };
  121500. static static_codebook _huff_book_line_1024x27_class1 = {
  121501. 1, 16,
  121502. _huff_lengthlist_line_1024x27_class1,
  121503. 0, 0, 0, 0, 0,
  121504. NULL,
  121505. NULL,
  121506. NULL,
  121507. NULL,
  121508. 0
  121509. };
  121510. static long _huff_lengthlist_line_1024x27_class2[] = {
  121511. 1, 4, 2, 6, 3, 7, 5, 7,
  121512. };
  121513. static static_codebook _huff_book_line_1024x27_class2 = {
  121514. 1, 8,
  121515. _huff_lengthlist_line_1024x27_class2,
  121516. 0, 0, 0, 0, 0,
  121517. NULL,
  121518. NULL,
  121519. NULL,
  121520. NULL,
  121521. 0
  121522. };
  121523. static long _huff_lengthlist_line_1024x27_class3[] = {
  121524. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  121525. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  121526. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  121527. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  121528. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  121529. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  121530. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  121531. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  121532. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  121533. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  121534. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  121535. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121536. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  121537. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  121538. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  121539. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121540. };
  121541. static static_codebook _huff_book_line_1024x27_class3 = {
  121542. 1, 256,
  121543. _huff_lengthlist_line_1024x27_class3,
  121544. 0, 0, 0, 0, 0,
  121545. NULL,
  121546. NULL,
  121547. NULL,
  121548. NULL,
  121549. 0
  121550. };
  121551. static long _huff_lengthlist_line_1024x27_class4[] = {
  121552. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  121553. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  121554. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  121555. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  121556. };
  121557. static static_codebook _huff_book_line_1024x27_class4 = {
  121558. 1, 64,
  121559. _huff_lengthlist_line_1024x27_class4,
  121560. 0, 0, 0, 0, 0,
  121561. NULL,
  121562. NULL,
  121563. NULL,
  121564. NULL,
  121565. 0
  121566. };
  121567. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  121568. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121569. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  121570. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  121571. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  121572. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  121573. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  121574. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  121575. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  121576. };
  121577. static static_codebook _huff_book_line_1024x27_0sub0 = {
  121578. 1, 128,
  121579. _huff_lengthlist_line_1024x27_0sub0,
  121580. 0, 0, 0, 0, 0,
  121581. NULL,
  121582. NULL,
  121583. NULL,
  121584. NULL,
  121585. 0
  121586. };
  121587. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  121588. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  121589. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  121590. };
  121591. static static_codebook _huff_book_line_1024x27_1sub0 = {
  121592. 1, 32,
  121593. _huff_lengthlist_line_1024x27_1sub0,
  121594. 0, 0, 0, 0, 0,
  121595. NULL,
  121596. NULL,
  121597. NULL,
  121598. NULL,
  121599. 0
  121600. };
  121601. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  121602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121604. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  121605. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  121606. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  121607. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  121608. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  121609. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  121610. };
  121611. static static_codebook _huff_book_line_1024x27_1sub1 = {
  121612. 1, 128,
  121613. _huff_lengthlist_line_1024x27_1sub1,
  121614. 0, 0, 0, 0, 0,
  121615. NULL,
  121616. NULL,
  121617. NULL,
  121618. NULL,
  121619. 0
  121620. };
  121621. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  121622. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121623. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  121624. };
  121625. static static_codebook _huff_book_line_1024x27_2sub0 = {
  121626. 1, 32,
  121627. _huff_lengthlist_line_1024x27_2sub0,
  121628. 0, 0, 0, 0, 0,
  121629. NULL,
  121630. NULL,
  121631. NULL,
  121632. NULL,
  121633. 0
  121634. };
  121635. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  121636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121638. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  121639. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  121640. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  121641. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  121642. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  121643. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  121644. };
  121645. static static_codebook _huff_book_line_1024x27_2sub1 = {
  121646. 1, 128,
  121647. _huff_lengthlist_line_1024x27_2sub1,
  121648. 0, 0, 0, 0, 0,
  121649. NULL,
  121650. NULL,
  121651. NULL,
  121652. NULL,
  121653. 0
  121654. };
  121655. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  121656. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  121657. 5, 5,
  121658. };
  121659. static static_codebook _huff_book_line_1024x27_3sub1 = {
  121660. 1, 18,
  121661. _huff_lengthlist_line_1024x27_3sub1,
  121662. 0, 0, 0, 0, 0,
  121663. NULL,
  121664. NULL,
  121665. NULL,
  121666. NULL,
  121667. 0
  121668. };
  121669. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  121670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121671. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  121672. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  121673. 9,11,
  121674. };
  121675. static static_codebook _huff_book_line_1024x27_3sub2 = {
  121676. 1, 50,
  121677. _huff_lengthlist_line_1024x27_3sub2,
  121678. 0, 0, 0, 0, 0,
  121679. NULL,
  121680. NULL,
  121681. NULL,
  121682. NULL,
  121683. 0
  121684. };
  121685. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  121686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121689. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  121690. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  121691. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121692. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121693. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121694. };
  121695. static static_codebook _huff_book_line_1024x27_3sub3 = {
  121696. 1, 128,
  121697. _huff_lengthlist_line_1024x27_3sub3,
  121698. 0, 0, 0, 0, 0,
  121699. NULL,
  121700. NULL,
  121701. NULL,
  121702. NULL,
  121703. 0
  121704. };
  121705. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  121706. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  121707. 5, 4,
  121708. };
  121709. static static_codebook _huff_book_line_1024x27_4sub1 = {
  121710. 1, 18,
  121711. _huff_lengthlist_line_1024x27_4sub1,
  121712. 0, 0, 0, 0, 0,
  121713. NULL,
  121714. NULL,
  121715. NULL,
  121716. NULL,
  121717. 0
  121718. };
  121719. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  121720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121721. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  121722. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  121723. 9,12,
  121724. };
  121725. static static_codebook _huff_book_line_1024x27_4sub2 = {
  121726. 1, 50,
  121727. _huff_lengthlist_line_1024x27_4sub2,
  121728. 0, 0, 0, 0, 0,
  121729. NULL,
  121730. NULL,
  121731. NULL,
  121732. NULL,
  121733. 0
  121734. };
  121735. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  121736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121739. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  121740. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  121741. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121742. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121743. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  121744. };
  121745. static static_codebook _huff_book_line_1024x27_4sub3 = {
  121746. 1, 128,
  121747. _huff_lengthlist_line_1024x27_4sub3,
  121748. 0, 0, 0, 0, 0,
  121749. NULL,
  121750. NULL,
  121751. NULL,
  121752. NULL,
  121753. 0
  121754. };
  121755. static long _huff_lengthlist_line_2048x27_class1[] = {
  121756. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  121757. };
  121758. static static_codebook _huff_book_line_2048x27_class1 = {
  121759. 1, 16,
  121760. _huff_lengthlist_line_2048x27_class1,
  121761. 0, 0, 0, 0, 0,
  121762. NULL,
  121763. NULL,
  121764. NULL,
  121765. NULL,
  121766. 0
  121767. };
  121768. static long _huff_lengthlist_line_2048x27_class2[] = {
  121769. 1, 2, 3, 6, 4, 7, 5, 7,
  121770. };
  121771. static static_codebook _huff_book_line_2048x27_class2 = {
  121772. 1, 8,
  121773. _huff_lengthlist_line_2048x27_class2,
  121774. 0, 0, 0, 0, 0,
  121775. NULL,
  121776. NULL,
  121777. NULL,
  121778. NULL,
  121779. 0
  121780. };
  121781. static long _huff_lengthlist_line_2048x27_class3[] = {
  121782. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  121783. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  121784. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  121785. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  121786. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  121787. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  121788. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  121789. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  121790. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  121791. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  121792. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  121793. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121794. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  121795. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  121796. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121797. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121798. };
  121799. static static_codebook _huff_book_line_2048x27_class3 = {
  121800. 1, 256,
  121801. _huff_lengthlist_line_2048x27_class3,
  121802. 0, 0, 0, 0, 0,
  121803. NULL,
  121804. NULL,
  121805. NULL,
  121806. NULL,
  121807. 0
  121808. };
  121809. static long _huff_lengthlist_line_2048x27_class4[] = {
  121810. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  121811. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  121812. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  121813. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  121814. };
  121815. static static_codebook _huff_book_line_2048x27_class4 = {
  121816. 1, 64,
  121817. _huff_lengthlist_line_2048x27_class4,
  121818. 0, 0, 0, 0, 0,
  121819. NULL,
  121820. NULL,
  121821. NULL,
  121822. NULL,
  121823. 0
  121824. };
  121825. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  121826. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121827. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  121828. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  121829. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  121830. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  121831. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  121832. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  121833. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  121834. };
  121835. static static_codebook _huff_book_line_2048x27_0sub0 = {
  121836. 1, 128,
  121837. _huff_lengthlist_line_2048x27_0sub0,
  121838. 0, 0, 0, 0, 0,
  121839. NULL,
  121840. NULL,
  121841. NULL,
  121842. NULL,
  121843. 0
  121844. };
  121845. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  121846. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121847. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  121848. };
  121849. static static_codebook _huff_book_line_2048x27_1sub0 = {
  121850. 1, 32,
  121851. _huff_lengthlist_line_2048x27_1sub0,
  121852. 0, 0, 0, 0, 0,
  121853. NULL,
  121854. NULL,
  121855. NULL,
  121856. NULL,
  121857. 0
  121858. };
  121859. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  121860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121862. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  121863. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  121864. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  121865. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  121866. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  121867. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  121868. };
  121869. static static_codebook _huff_book_line_2048x27_1sub1 = {
  121870. 1, 128,
  121871. _huff_lengthlist_line_2048x27_1sub1,
  121872. 0, 0, 0, 0, 0,
  121873. NULL,
  121874. NULL,
  121875. NULL,
  121876. NULL,
  121877. 0
  121878. };
  121879. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  121880. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121881. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  121882. };
  121883. static static_codebook _huff_book_line_2048x27_2sub0 = {
  121884. 1, 32,
  121885. _huff_lengthlist_line_2048x27_2sub0,
  121886. 0, 0, 0, 0, 0,
  121887. NULL,
  121888. NULL,
  121889. NULL,
  121890. NULL,
  121891. 0
  121892. };
  121893. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  121894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121896. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  121897. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  121898. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  121899. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  121900. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  121901. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121902. };
  121903. static static_codebook _huff_book_line_2048x27_2sub1 = {
  121904. 1, 128,
  121905. _huff_lengthlist_line_2048x27_2sub1,
  121906. 0, 0, 0, 0, 0,
  121907. NULL,
  121908. NULL,
  121909. NULL,
  121910. NULL,
  121911. 0
  121912. };
  121913. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  121914. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  121915. 5, 5,
  121916. };
  121917. static static_codebook _huff_book_line_2048x27_3sub1 = {
  121918. 1, 18,
  121919. _huff_lengthlist_line_2048x27_3sub1,
  121920. 0, 0, 0, 0, 0,
  121921. NULL,
  121922. NULL,
  121923. NULL,
  121924. NULL,
  121925. 0
  121926. };
  121927. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  121928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121929. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  121930. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  121931. 10,12,
  121932. };
  121933. static static_codebook _huff_book_line_2048x27_3sub2 = {
  121934. 1, 50,
  121935. _huff_lengthlist_line_2048x27_3sub2,
  121936. 0, 0, 0, 0, 0,
  121937. NULL,
  121938. NULL,
  121939. NULL,
  121940. NULL,
  121941. 0
  121942. };
  121943. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  121944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121947. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  121948. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121949. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121950. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121951. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121952. };
  121953. static static_codebook _huff_book_line_2048x27_3sub3 = {
  121954. 1, 128,
  121955. _huff_lengthlist_line_2048x27_3sub3,
  121956. 0, 0, 0, 0, 0,
  121957. NULL,
  121958. NULL,
  121959. NULL,
  121960. NULL,
  121961. 0
  121962. };
  121963. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  121964. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  121965. 4, 5,
  121966. };
  121967. static static_codebook _huff_book_line_2048x27_4sub1 = {
  121968. 1, 18,
  121969. _huff_lengthlist_line_2048x27_4sub1,
  121970. 0, 0, 0, 0, 0,
  121971. NULL,
  121972. NULL,
  121973. NULL,
  121974. NULL,
  121975. 0
  121976. };
  121977. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  121978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121979. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  121980. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  121981. 10,10,
  121982. };
  121983. static static_codebook _huff_book_line_2048x27_4sub2 = {
  121984. 1, 50,
  121985. _huff_lengthlist_line_2048x27_4sub2,
  121986. 0, 0, 0, 0, 0,
  121987. NULL,
  121988. NULL,
  121989. NULL,
  121990. NULL,
  121991. 0
  121992. };
  121993. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  121994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121997. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  121998. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  121999. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122000. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122001. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122002. };
  122003. static static_codebook _huff_book_line_2048x27_4sub3 = {
  122004. 1, 128,
  122005. _huff_lengthlist_line_2048x27_4sub3,
  122006. 0, 0, 0, 0, 0,
  122007. NULL,
  122008. NULL,
  122009. NULL,
  122010. NULL,
  122011. 0
  122012. };
  122013. static long _huff_lengthlist_line_256x4low_class0[] = {
  122014. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  122015. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  122016. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  122017. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  122018. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122019. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122020. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122021. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122022. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122023. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122024. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122025. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122026. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122027. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122028. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122029. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122030. };
  122031. static static_codebook _huff_book_line_256x4low_class0 = {
  122032. 1, 256,
  122033. _huff_lengthlist_line_256x4low_class0,
  122034. 0, 0, 0, 0, 0,
  122035. NULL,
  122036. NULL,
  122037. NULL,
  122038. NULL,
  122039. 0
  122040. };
  122041. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122042. 1, 3, 2, 3,
  122043. };
  122044. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122045. 1, 4,
  122046. _huff_lengthlist_line_256x4low_0sub0,
  122047. 0, 0, 0, 0, 0,
  122048. NULL,
  122049. NULL,
  122050. NULL,
  122051. NULL,
  122052. 0
  122053. };
  122054. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122055. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122056. };
  122057. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122058. 1, 10,
  122059. _huff_lengthlist_line_256x4low_0sub1,
  122060. 0, 0, 0, 0, 0,
  122061. NULL,
  122062. NULL,
  122063. NULL,
  122064. NULL,
  122065. 0
  122066. };
  122067. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122069. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122070. };
  122071. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122072. 1, 25,
  122073. _huff_lengthlist_line_256x4low_0sub2,
  122074. 0, 0, 0, 0, 0,
  122075. NULL,
  122076. NULL,
  122077. NULL,
  122078. NULL,
  122079. 0
  122080. };
  122081. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  122082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  122084. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122085. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122086. };
  122087. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122088. 1, 64,
  122089. _huff_lengthlist_line_256x4low_0sub3,
  122090. 0, 0, 0, 0, 0,
  122091. NULL,
  122092. NULL,
  122093. NULL,
  122094. NULL,
  122095. 0
  122096. };
  122097. /*** End of inlined file: floor_books.h ***/
  122098. static static_codebook *_floor_128x4_books[]={
  122099. &_huff_book_line_128x4_class0,
  122100. &_huff_book_line_128x4_0sub0,
  122101. &_huff_book_line_128x4_0sub1,
  122102. &_huff_book_line_128x4_0sub2,
  122103. &_huff_book_line_128x4_0sub3,
  122104. };
  122105. static static_codebook *_floor_256x4_books[]={
  122106. &_huff_book_line_256x4_class0,
  122107. &_huff_book_line_256x4_0sub0,
  122108. &_huff_book_line_256x4_0sub1,
  122109. &_huff_book_line_256x4_0sub2,
  122110. &_huff_book_line_256x4_0sub3,
  122111. };
  122112. static static_codebook *_floor_128x7_books[]={
  122113. &_huff_book_line_128x7_class0,
  122114. &_huff_book_line_128x7_class1,
  122115. &_huff_book_line_128x7_0sub1,
  122116. &_huff_book_line_128x7_0sub2,
  122117. &_huff_book_line_128x7_0sub3,
  122118. &_huff_book_line_128x7_1sub1,
  122119. &_huff_book_line_128x7_1sub2,
  122120. &_huff_book_line_128x7_1sub3,
  122121. };
  122122. static static_codebook *_floor_256x7_books[]={
  122123. &_huff_book_line_256x7_class0,
  122124. &_huff_book_line_256x7_class1,
  122125. &_huff_book_line_256x7_0sub1,
  122126. &_huff_book_line_256x7_0sub2,
  122127. &_huff_book_line_256x7_0sub3,
  122128. &_huff_book_line_256x7_1sub1,
  122129. &_huff_book_line_256x7_1sub2,
  122130. &_huff_book_line_256x7_1sub3,
  122131. };
  122132. static static_codebook *_floor_128x11_books[]={
  122133. &_huff_book_line_128x11_class1,
  122134. &_huff_book_line_128x11_class2,
  122135. &_huff_book_line_128x11_class3,
  122136. &_huff_book_line_128x11_0sub0,
  122137. &_huff_book_line_128x11_1sub0,
  122138. &_huff_book_line_128x11_1sub1,
  122139. &_huff_book_line_128x11_2sub1,
  122140. &_huff_book_line_128x11_2sub2,
  122141. &_huff_book_line_128x11_2sub3,
  122142. &_huff_book_line_128x11_3sub1,
  122143. &_huff_book_line_128x11_3sub2,
  122144. &_huff_book_line_128x11_3sub3,
  122145. };
  122146. static static_codebook *_floor_128x17_books[]={
  122147. &_huff_book_line_128x17_class1,
  122148. &_huff_book_line_128x17_class2,
  122149. &_huff_book_line_128x17_class3,
  122150. &_huff_book_line_128x17_0sub0,
  122151. &_huff_book_line_128x17_1sub0,
  122152. &_huff_book_line_128x17_1sub1,
  122153. &_huff_book_line_128x17_2sub1,
  122154. &_huff_book_line_128x17_2sub2,
  122155. &_huff_book_line_128x17_2sub3,
  122156. &_huff_book_line_128x17_3sub1,
  122157. &_huff_book_line_128x17_3sub2,
  122158. &_huff_book_line_128x17_3sub3,
  122159. };
  122160. static static_codebook *_floor_256x4low_books[]={
  122161. &_huff_book_line_256x4low_class0,
  122162. &_huff_book_line_256x4low_0sub0,
  122163. &_huff_book_line_256x4low_0sub1,
  122164. &_huff_book_line_256x4low_0sub2,
  122165. &_huff_book_line_256x4low_0sub3,
  122166. };
  122167. static static_codebook *_floor_1024x27_books[]={
  122168. &_huff_book_line_1024x27_class1,
  122169. &_huff_book_line_1024x27_class2,
  122170. &_huff_book_line_1024x27_class3,
  122171. &_huff_book_line_1024x27_class4,
  122172. &_huff_book_line_1024x27_0sub0,
  122173. &_huff_book_line_1024x27_1sub0,
  122174. &_huff_book_line_1024x27_1sub1,
  122175. &_huff_book_line_1024x27_2sub0,
  122176. &_huff_book_line_1024x27_2sub1,
  122177. &_huff_book_line_1024x27_3sub1,
  122178. &_huff_book_line_1024x27_3sub2,
  122179. &_huff_book_line_1024x27_3sub3,
  122180. &_huff_book_line_1024x27_4sub1,
  122181. &_huff_book_line_1024x27_4sub2,
  122182. &_huff_book_line_1024x27_4sub3,
  122183. };
  122184. static static_codebook *_floor_2048x27_books[]={
  122185. &_huff_book_line_2048x27_class1,
  122186. &_huff_book_line_2048x27_class2,
  122187. &_huff_book_line_2048x27_class3,
  122188. &_huff_book_line_2048x27_class4,
  122189. &_huff_book_line_2048x27_0sub0,
  122190. &_huff_book_line_2048x27_1sub0,
  122191. &_huff_book_line_2048x27_1sub1,
  122192. &_huff_book_line_2048x27_2sub0,
  122193. &_huff_book_line_2048x27_2sub1,
  122194. &_huff_book_line_2048x27_3sub1,
  122195. &_huff_book_line_2048x27_3sub2,
  122196. &_huff_book_line_2048x27_3sub3,
  122197. &_huff_book_line_2048x27_4sub1,
  122198. &_huff_book_line_2048x27_4sub2,
  122199. &_huff_book_line_2048x27_4sub3,
  122200. };
  122201. static static_codebook *_floor_512x17_books[]={
  122202. &_huff_book_line_512x17_class1,
  122203. &_huff_book_line_512x17_class2,
  122204. &_huff_book_line_512x17_class3,
  122205. &_huff_book_line_512x17_0sub0,
  122206. &_huff_book_line_512x17_1sub0,
  122207. &_huff_book_line_512x17_1sub1,
  122208. &_huff_book_line_512x17_2sub1,
  122209. &_huff_book_line_512x17_2sub2,
  122210. &_huff_book_line_512x17_2sub3,
  122211. &_huff_book_line_512x17_3sub1,
  122212. &_huff_book_line_512x17_3sub2,
  122213. &_huff_book_line_512x17_3sub3,
  122214. };
  122215. static static_codebook **_floor_books[10]={
  122216. _floor_128x4_books,
  122217. _floor_256x4_books,
  122218. _floor_128x7_books,
  122219. _floor_256x7_books,
  122220. _floor_128x11_books,
  122221. _floor_128x17_books,
  122222. _floor_256x4low_books,
  122223. _floor_1024x27_books,
  122224. _floor_2048x27_books,
  122225. _floor_512x17_books,
  122226. };
  122227. static vorbis_info_floor1 _floor[10]={
  122228. /* 128 x 4 */
  122229. {
  122230. 1,{0},{4},{2},{0},
  122231. {{1,2,3,4}},
  122232. 4,{0,128, 33,8,16,70},
  122233. 60,30,500, 1.,18., -1
  122234. },
  122235. /* 256 x 4 */
  122236. {
  122237. 1,{0},{4},{2},{0},
  122238. {{1,2,3,4}},
  122239. 4,{0,256, 66,16,32,140},
  122240. 60,30,500, 1.,18., -1
  122241. },
  122242. /* 128 x 7 */
  122243. {
  122244. 2,{0,1},{3,4},{2,2},{0,1},
  122245. {{-1,2,3,4},{-1,5,6,7}},
  122246. 4,{0,128, 14,4,58, 2,8,28,90},
  122247. 60,30,500, 1.,18., -1
  122248. },
  122249. /* 256 x 7 */
  122250. {
  122251. 2,{0,1},{3,4},{2,2},{0,1},
  122252. {{-1,2,3,4},{-1,5,6,7}},
  122253. 4,{0,256, 28,8,116, 4,16,56,180},
  122254. 60,30,500, 1.,18., -1
  122255. },
  122256. /* 128 x 11 */
  122257. {
  122258. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122259. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122260. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122261. 60,30,500, 1,18., -1
  122262. },
  122263. /* 128 x 17 */
  122264. {
  122265. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122266. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122267. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122268. 60,30,500, 1,18., -1
  122269. },
  122270. /* 256 x 4 (low bitrate version) */
  122271. {
  122272. 1,{0},{4},{2},{0},
  122273. {{1,2,3,4}},
  122274. 4,{0,256, 66,16,32,140},
  122275. 60,30,500, 1.,18., -1
  122276. },
  122277. /* 1024 x 27 */
  122278. {
  122279. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122280. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122281. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122282. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122283. 60,30,500, 3,18., -1 /* lowpass */
  122284. },
  122285. /* 2048 x 27 */
  122286. {
  122287. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122288. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122289. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122290. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122291. 60,30,500, 3,18., -1 /* lowpass */
  122292. },
  122293. /* 512 x 17 */
  122294. {
  122295. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122296. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122297. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122298. 7,23,39, 55,79,110, 156,232,360},
  122299. 60,30,500, 1,18., -1 /* lowpass! */
  122300. },
  122301. };
  122302. /*** End of inlined file: floor_all.h ***/
  122303. /*** Start of inlined file: residue_44.h ***/
  122304. /*** Start of inlined file: res_books_stereo.h ***/
  122305. static long _vq_quantlist__16c0_s_p1_0[] = {
  122306. 1,
  122307. 0,
  122308. 2,
  122309. };
  122310. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122311. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122312. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122316. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122317. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122321. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122322. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122357. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  122362. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  122367. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122402. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122403. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122407. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122408. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  122409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122412. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122413. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  122414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122419. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122424. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122429. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  122464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  122469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  122474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122511. 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122515. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  122722. };
  122723. static float _vq_quantthresh__16c0_s_p1_0[] = {
  122724. -0.5, 0.5,
  122725. };
  122726. static long _vq_quantmap__16c0_s_p1_0[] = {
  122727. 1, 0, 2,
  122728. };
  122729. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  122730. _vq_quantthresh__16c0_s_p1_0,
  122731. _vq_quantmap__16c0_s_p1_0,
  122732. 3,
  122733. 3
  122734. };
  122735. static static_codebook _16c0_s_p1_0 = {
  122736. 8, 6561,
  122737. _vq_lengthlist__16c0_s_p1_0,
  122738. 1, -535822336, 1611661312, 2, 0,
  122739. _vq_quantlist__16c0_s_p1_0,
  122740. NULL,
  122741. &_vq_auxt__16c0_s_p1_0,
  122742. NULL,
  122743. 0
  122744. };
  122745. static long _vq_quantlist__16c0_s_p2_0[] = {
  122746. 2,
  122747. 1,
  122748. 3,
  122749. 0,
  122750. 4,
  122751. };
  122752. static long _vq_lengthlist__16c0_s_p2_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,
  122793. };
  122794. static float _vq_quantthresh__16c0_s_p2_0[] = {
  122795. -1.5, -0.5, 0.5, 1.5,
  122796. };
  122797. static long _vq_quantmap__16c0_s_p2_0[] = {
  122798. 3, 1, 0, 2, 4,
  122799. };
  122800. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  122801. _vq_quantthresh__16c0_s_p2_0,
  122802. _vq_quantmap__16c0_s_p2_0,
  122803. 5,
  122804. 5
  122805. };
  122806. static static_codebook _16c0_s_p2_0 = {
  122807. 4, 625,
  122808. _vq_lengthlist__16c0_s_p2_0,
  122809. 1, -533725184, 1611661312, 3, 0,
  122810. _vq_quantlist__16c0_s_p2_0,
  122811. NULL,
  122812. &_vq_auxt__16c0_s_p2_0,
  122813. NULL,
  122814. 0
  122815. };
  122816. static long _vq_quantlist__16c0_s_p3_0[] = {
  122817. 2,
  122818. 1,
  122819. 3,
  122820. 0,
  122821. 4,
  122822. };
  122823. static long _vq_lengthlist__16c0_s_p3_0[] = {
  122824. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  122826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122827. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  122829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122830. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  122831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122863. 0,
  122864. };
  122865. static float _vq_quantthresh__16c0_s_p3_0[] = {
  122866. -1.5, -0.5, 0.5, 1.5,
  122867. };
  122868. static long _vq_quantmap__16c0_s_p3_0[] = {
  122869. 3, 1, 0, 2, 4,
  122870. };
  122871. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  122872. _vq_quantthresh__16c0_s_p3_0,
  122873. _vq_quantmap__16c0_s_p3_0,
  122874. 5,
  122875. 5
  122876. };
  122877. static static_codebook _16c0_s_p3_0 = {
  122878. 4, 625,
  122879. _vq_lengthlist__16c0_s_p3_0,
  122880. 1, -533725184, 1611661312, 3, 0,
  122881. _vq_quantlist__16c0_s_p3_0,
  122882. NULL,
  122883. &_vq_auxt__16c0_s_p3_0,
  122884. NULL,
  122885. 0
  122886. };
  122887. static long _vq_quantlist__16c0_s_p4_0[] = {
  122888. 4,
  122889. 3,
  122890. 5,
  122891. 2,
  122892. 6,
  122893. 1,
  122894. 7,
  122895. 0,
  122896. 8,
  122897. };
  122898. static long _vq_lengthlist__16c0_s_p4_0[] = {
  122899. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  122900. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  122901. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122902. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  122903. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122904. 0,
  122905. };
  122906. static float _vq_quantthresh__16c0_s_p4_0[] = {
  122907. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122908. };
  122909. static long _vq_quantmap__16c0_s_p4_0[] = {
  122910. 7, 5, 3, 1, 0, 2, 4, 6,
  122911. 8,
  122912. };
  122913. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  122914. _vq_quantthresh__16c0_s_p4_0,
  122915. _vq_quantmap__16c0_s_p4_0,
  122916. 9,
  122917. 9
  122918. };
  122919. static static_codebook _16c0_s_p4_0 = {
  122920. 2, 81,
  122921. _vq_lengthlist__16c0_s_p4_0,
  122922. 1, -531628032, 1611661312, 4, 0,
  122923. _vq_quantlist__16c0_s_p4_0,
  122924. NULL,
  122925. &_vq_auxt__16c0_s_p4_0,
  122926. NULL,
  122927. 0
  122928. };
  122929. static long _vq_quantlist__16c0_s_p5_0[] = {
  122930. 4,
  122931. 3,
  122932. 5,
  122933. 2,
  122934. 6,
  122935. 1,
  122936. 7,
  122937. 0,
  122938. 8,
  122939. };
  122940. static long _vq_lengthlist__16c0_s_p5_0[] = {
  122941. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  122942. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  122943. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  122944. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  122945. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  122946. 10,
  122947. };
  122948. static float _vq_quantthresh__16c0_s_p5_0[] = {
  122949. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122950. };
  122951. static long _vq_quantmap__16c0_s_p5_0[] = {
  122952. 7, 5, 3, 1, 0, 2, 4, 6,
  122953. 8,
  122954. };
  122955. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  122956. _vq_quantthresh__16c0_s_p5_0,
  122957. _vq_quantmap__16c0_s_p5_0,
  122958. 9,
  122959. 9
  122960. };
  122961. static static_codebook _16c0_s_p5_0 = {
  122962. 2, 81,
  122963. _vq_lengthlist__16c0_s_p5_0,
  122964. 1, -531628032, 1611661312, 4, 0,
  122965. _vq_quantlist__16c0_s_p5_0,
  122966. NULL,
  122967. &_vq_auxt__16c0_s_p5_0,
  122968. NULL,
  122969. 0
  122970. };
  122971. static long _vq_quantlist__16c0_s_p6_0[] = {
  122972. 8,
  122973. 7,
  122974. 9,
  122975. 6,
  122976. 10,
  122977. 5,
  122978. 11,
  122979. 4,
  122980. 12,
  122981. 3,
  122982. 13,
  122983. 2,
  122984. 14,
  122985. 1,
  122986. 15,
  122987. 0,
  122988. 16,
  122989. };
  122990. static long _vq_lengthlist__16c0_s_p6_0[] = {
  122991. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  122992. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  122993. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  122994. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  122995. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  122996. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  122997. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  122998. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  122999. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  123000. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123001. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  123002. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  123003. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  123004. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  123005. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  123006. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123007. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123008. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123009. 14,
  123010. };
  123011. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123012. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123013. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123014. };
  123015. static long _vq_quantmap__16c0_s_p6_0[] = {
  123016. 15, 13, 11, 9, 7, 5, 3, 1,
  123017. 0, 2, 4, 6, 8, 10, 12, 14,
  123018. 16,
  123019. };
  123020. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123021. _vq_quantthresh__16c0_s_p6_0,
  123022. _vq_quantmap__16c0_s_p6_0,
  123023. 17,
  123024. 17
  123025. };
  123026. static static_codebook _16c0_s_p6_0 = {
  123027. 2, 289,
  123028. _vq_lengthlist__16c0_s_p6_0,
  123029. 1, -529530880, 1611661312, 5, 0,
  123030. _vq_quantlist__16c0_s_p6_0,
  123031. NULL,
  123032. &_vq_auxt__16c0_s_p6_0,
  123033. NULL,
  123034. 0
  123035. };
  123036. static long _vq_quantlist__16c0_s_p7_0[] = {
  123037. 1,
  123038. 0,
  123039. 2,
  123040. };
  123041. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123042. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123043. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123044. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123045. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123046. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123047. 13,
  123048. };
  123049. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123050. -5.5, 5.5,
  123051. };
  123052. static long _vq_quantmap__16c0_s_p7_0[] = {
  123053. 1, 0, 2,
  123054. };
  123055. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123056. _vq_quantthresh__16c0_s_p7_0,
  123057. _vq_quantmap__16c0_s_p7_0,
  123058. 3,
  123059. 3
  123060. };
  123061. static static_codebook _16c0_s_p7_0 = {
  123062. 4, 81,
  123063. _vq_lengthlist__16c0_s_p7_0,
  123064. 1, -529137664, 1618345984, 2, 0,
  123065. _vq_quantlist__16c0_s_p7_0,
  123066. NULL,
  123067. &_vq_auxt__16c0_s_p7_0,
  123068. NULL,
  123069. 0
  123070. };
  123071. static long _vq_quantlist__16c0_s_p7_1[] = {
  123072. 5,
  123073. 4,
  123074. 6,
  123075. 3,
  123076. 7,
  123077. 2,
  123078. 8,
  123079. 1,
  123080. 9,
  123081. 0,
  123082. 10,
  123083. };
  123084. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123085. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123086. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123087. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123088. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123089. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123090. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123091. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123092. 11,11,11, 9, 9, 9, 9,10,10,
  123093. };
  123094. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123095. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123096. 3.5, 4.5,
  123097. };
  123098. static long _vq_quantmap__16c0_s_p7_1[] = {
  123099. 9, 7, 5, 3, 1, 0, 2, 4,
  123100. 6, 8, 10,
  123101. };
  123102. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123103. _vq_quantthresh__16c0_s_p7_1,
  123104. _vq_quantmap__16c0_s_p7_1,
  123105. 11,
  123106. 11
  123107. };
  123108. static static_codebook _16c0_s_p7_1 = {
  123109. 2, 121,
  123110. _vq_lengthlist__16c0_s_p7_1,
  123111. 1, -531365888, 1611661312, 4, 0,
  123112. _vq_quantlist__16c0_s_p7_1,
  123113. NULL,
  123114. &_vq_auxt__16c0_s_p7_1,
  123115. NULL,
  123116. 0
  123117. };
  123118. static long _vq_quantlist__16c0_s_p8_0[] = {
  123119. 6,
  123120. 5,
  123121. 7,
  123122. 4,
  123123. 8,
  123124. 3,
  123125. 9,
  123126. 2,
  123127. 10,
  123128. 1,
  123129. 11,
  123130. 0,
  123131. 12,
  123132. };
  123133. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123134. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123135. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123136. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123137. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123138. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123139. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123140. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123141. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123142. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123143. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123144. 0,12,13,13,12,13,14,14,14,
  123145. };
  123146. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123147. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123148. 12.5, 17.5, 22.5, 27.5,
  123149. };
  123150. static long _vq_quantmap__16c0_s_p8_0[] = {
  123151. 11, 9, 7, 5, 3, 1, 0, 2,
  123152. 4, 6, 8, 10, 12,
  123153. };
  123154. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123155. _vq_quantthresh__16c0_s_p8_0,
  123156. _vq_quantmap__16c0_s_p8_0,
  123157. 13,
  123158. 13
  123159. };
  123160. static static_codebook _16c0_s_p8_0 = {
  123161. 2, 169,
  123162. _vq_lengthlist__16c0_s_p8_0,
  123163. 1, -526516224, 1616117760, 4, 0,
  123164. _vq_quantlist__16c0_s_p8_0,
  123165. NULL,
  123166. &_vq_auxt__16c0_s_p8_0,
  123167. NULL,
  123168. 0
  123169. };
  123170. static long _vq_quantlist__16c0_s_p8_1[] = {
  123171. 2,
  123172. 1,
  123173. 3,
  123174. 0,
  123175. 4,
  123176. };
  123177. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123178. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123179. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123180. };
  123181. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123182. -1.5, -0.5, 0.5, 1.5,
  123183. };
  123184. static long _vq_quantmap__16c0_s_p8_1[] = {
  123185. 3, 1, 0, 2, 4,
  123186. };
  123187. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123188. _vq_quantthresh__16c0_s_p8_1,
  123189. _vq_quantmap__16c0_s_p8_1,
  123190. 5,
  123191. 5
  123192. };
  123193. static static_codebook _16c0_s_p8_1 = {
  123194. 2, 25,
  123195. _vq_lengthlist__16c0_s_p8_1,
  123196. 1, -533725184, 1611661312, 3, 0,
  123197. _vq_quantlist__16c0_s_p8_1,
  123198. NULL,
  123199. &_vq_auxt__16c0_s_p8_1,
  123200. NULL,
  123201. 0
  123202. };
  123203. static long _vq_quantlist__16c0_s_p9_0[] = {
  123204. 1,
  123205. 0,
  123206. 2,
  123207. };
  123208. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123209. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123210. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123211. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123212. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123213. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123214. 7,
  123215. };
  123216. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123217. -157.5, 157.5,
  123218. };
  123219. static long _vq_quantmap__16c0_s_p9_0[] = {
  123220. 1, 0, 2,
  123221. };
  123222. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123223. _vq_quantthresh__16c0_s_p9_0,
  123224. _vq_quantmap__16c0_s_p9_0,
  123225. 3,
  123226. 3
  123227. };
  123228. static static_codebook _16c0_s_p9_0 = {
  123229. 4, 81,
  123230. _vq_lengthlist__16c0_s_p9_0,
  123231. 1, -518803456, 1628680192, 2, 0,
  123232. _vq_quantlist__16c0_s_p9_0,
  123233. NULL,
  123234. &_vq_auxt__16c0_s_p9_0,
  123235. NULL,
  123236. 0
  123237. };
  123238. static long _vq_quantlist__16c0_s_p9_1[] = {
  123239. 7,
  123240. 6,
  123241. 8,
  123242. 5,
  123243. 9,
  123244. 4,
  123245. 10,
  123246. 3,
  123247. 11,
  123248. 2,
  123249. 12,
  123250. 1,
  123251. 13,
  123252. 0,
  123253. 14,
  123254. };
  123255. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123256. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123257. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123258. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123259. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123260. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123261. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123262. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123263. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123264. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123265. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123266. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123267. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123268. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123269. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123270. 10,
  123271. };
  123272. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123273. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123274. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123275. };
  123276. static long _vq_quantmap__16c0_s_p9_1[] = {
  123277. 13, 11, 9, 7, 5, 3, 1, 0,
  123278. 2, 4, 6, 8, 10, 12, 14,
  123279. };
  123280. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123281. _vq_quantthresh__16c0_s_p9_1,
  123282. _vq_quantmap__16c0_s_p9_1,
  123283. 15,
  123284. 15
  123285. };
  123286. static static_codebook _16c0_s_p9_1 = {
  123287. 2, 225,
  123288. _vq_lengthlist__16c0_s_p9_1,
  123289. 1, -520986624, 1620377600, 4, 0,
  123290. _vq_quantlist__16c0_s_p9_1,
  123291. NULL,
  123292. &_vq_auxt__16c0_s_p9_1,
  123293. NULL,
  123294. 0
  123295. };
  123296. static long _vq_quantlist__16c0_s_p9_2[] = {
  123297. 10,
  123298. 9,
  123299. 11,
  123300. 8,
  123301. 12,
  123302. 7,
  123303. 13,
  123304. 6,
  123305. 14,
  123306. 5,
  123307. 15,
  123308. 4,
  123309. 16,
  123310. 3,
  123311. 17,
  123312. 2,
  123313. 18,
  123314. 1,
  123315. 19,
  123316. 0,
  123317. 20,
  123318. };
  123319. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123320. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123321. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123322. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123323. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123324. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123325. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123326. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123327. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123328. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123329. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123330. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123331. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123332. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123333. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123334. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123335. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123336. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123337. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123338. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123339. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123340. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123341. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123342. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123343. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123344. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123345. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123346. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123347. 10,11,10,10,11, 9,10,10,10,
  123348. };
  123349. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123350. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123351. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123352. 6.5, 7.5, 8.5, 9.5,
  123353. };
  123354. static long _vq_quantmap__16c0_s_p9_2[] = {
  123355. 19, 17, 15, 13, 11, 9, 7, 5,
  123356. 3, 1, 0, 2, 4, 6, 8, 10,
  123357. 12, 14, 16, 18, 20,
  123358. };
  123359. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123360. _vq_quantthresh__16c0_s_p9_2,
  123361. _vq_quantmap__16c0_s_p9_2,
  123362. 21,
  123363. 21
  123364. };
  123365. static static_codebook _16c0_s_p9_2 = {
  123366. 2, 441,
  123367. _vq_lengthlist__16c0_s_p9_2,
  123368. 1, -529268736, 1611661312, 5, 0,
  123369. _vq_quantlist__16c0_s_p9_2,
  123370. NULL,
  123371. &_vq_auxt__16c0_s_p9_2,
  123372. NULL,
  123373. 0
  123374. };
  123375. static long _huff_lengthlist__16c0_s_single[] = {
  123376. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123377. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123378. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123379. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123380. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123381. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123382. 16,16,18,18,
  123383. };
  123384. static static_codebook _huff_book__16c0_s_single = {
  123385. 2, 100,
  123386. _huff_lengthlist__16c0_s_single,
  123387. 0, 0, 0, 0, 0,
  123388. NULL,
  123389. NULL,
  123390. NULL,
  123391. NULL,
  123392. 0
  123393. };
  123394. static long _huff_lengthlist__16c1_s_long[] = {
  123395. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123396. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123397. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123398. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123399. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123400. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123401. 12,11,11,13,
  123402. };
  123403. static static_codebook _huff_book__16c1_s_long = {
  123404. 2, 100,
  123405. _huff_lengthlist__16c1_s_long,
  123406. 0, 0, 0, 0, 0,
  123407. NULL,
  123408. NULL,
  123409. NULL,
  123410. NULL,
  123411. 0
  123412. };
  123413. static long _vq_quantlist__16c1_s_p1_0[] = {
  123414. 1,
  123415. 0,
  123416. 2,
  123417. };
  123418. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123419. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123420. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123424. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123425. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123429. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123430. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  123465. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123470. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123475. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123510. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123511. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123515. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123516. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  123517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123520. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123521. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  123522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123527. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123532. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123537. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  123572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  123577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  123582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123618. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123623. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  123830. };
  123831. static float _vq_quantthresh__16c1_s_p1_0[] = {
  123832. -0.5, 0.5,
  123833. };
  123834. static long _vq_quantmap__16c1_s_p1_0[] = {
  123835. 1, 0, 2,
  123836. };
  123837. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  123838. _vq_quantthresh__16c1_s_p1_0,
  123839. _vq_quantmap__16c1_s_p1_0,
  123840. 3,
  123841. 3
  123842. };
  123843. static static_codebook _16c1_s_p1_0 = {
  123844. 8, 6561,
  123845. _vq_lengthlist__16c1_s_p1_0,
  123846. 1, -535822336, 1611661312, 2, 0,
  123847. _vq_quantlist__16c1_s_p1_0,
  123848. NULL,
  123849. &_vq_auxt__16c1_s_p1_0,
  123850. NULL,
  123851. 0
  123852. };
  123853. static long _vq_quantlist__16c1_s_p2_0[] = {
  123854. 2,
  123855. 1,
  123856. 3,
  123857. 0,
  123858. 4,
  123859. };
  123860. static long _vq_lengthlist__16c1_s_p2_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,
  123901. };
  123902. static float _vq_quantthresh__16c1_s_p2_0[] = {
  123903. -1.5, -0.5, 0.5, 1.5,
  123904. };
  123905. static long _vq_quantmap__16c1_s_p2_0[] = {
  123906. 3, 1, 0, 2, 4,
  123907. };
  123908. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  123909. _vq_quantthresh__16c1_s_p2_0,
  123910. _vq_quantmap__16c1_s_p2_0,
  123911. 5,
  123912. 5
  123913. };
  123914. static static_codebook _16c1_s_p2_0 = {
  123915. 4, 625,
  123916. _vq_lengthlist__16c1_s_p2_0,
  123917. 1, -533725184, 1611661312, 3, 0,
  123918. _vq_quantlist__16c1_s_p2_0,
  123919. NULL,
  123920. &_vq_auxt__16c1_s_p2_0,
  123921. NULL,
  123922. 0
  123923. };
  123924. static long _vq_quantlist__16c1_s_p3_0[] = {
  123925. 2,
  123926. 1,
  123927. 3,
  123928. 0,
  123929. 4,
  123930. };
  123931. static long _vq_lengthlist__16c1_s_p3_0[] = {
  123932. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  123934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123935. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  123937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123938. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123971. 0,
  123972. };
  123973. static float _vq_quantthresh__16c1_s_p3_0[] = {
  123974. -1.5, -0.5, 0.5, 1.5,
  123975. };
  123976. static long _vq_quantmap__16c1_s_p3_0[] = {
  123977. 3, 1, 0, 2, 4,
  123978. };
  123979. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  123980. _vq_quantthresh__16c1_s_p3_0,
  123981. _vq_quantmap__16c1_s_p3_0,
  123982. 5,
  123983. 5
  123984. };
  123985. static static_codebook _16c1_s_p3_0 = {
  123986. 4, 625,
  123987. _vq_lengthlist__16c1_s_p3_0,
  123988. 1, -533725184, 1611661312, 3, 0,
  123989. _vq_quantlist__16c1_s_p3_0,
  123990. NULL,
  123991. &_vq_auxt__16c1_s_p3_0,
  123992. NULL,
  123993. 0
  123994. };
  123995. static long _vq_quantlist__16c1_s_p4_0[] = {
  123996. 4,
  123997. 3,
  123998. 5,
  123999. 2,
  124000. 6,
  124001. 1,
  124002. 7,
  124003. 0,
  124004. 8,
  124005. };
  124006. static long _vq_lengthlist__16c1_s_p4_0[] = {
  124007. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124008. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124009. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124010. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124011. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124012. 0,
  124013. };
  124014. static float _vq_quantthresh__16c1_s_p4_0[] = {
  124015. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124016. };
  124017. static long _vq_quantmap__16c1_s_p4_0[] = {
  124018. 7, 5, 3, 1, 0, 2, 4, 6,
  124019. 8,
  124020. };
  124021. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124022. _vq_quantthresh__16c1_s_p4_0,
  124023. _vq_quantmap__16c1_s_p4_0,
  124024. 9,
  124025. 9
  124026. };
  124027. static static_codebook _16c1_s_p4_0 = {
  124028. 2, 81,
  124029. _vq_lengthlist__16c1_s_p4_0,
  124030. 1, -531628032, 1611661312, 4, 0,
  124031. _vq_quantlist__16c1_s_p4_0,
  124032. NULL,
  124033. &_vq_auxt__16c1_s_p4_0,
  124034. NULL,
  124035. 0
  124036. };
  124037. static long _vq_quantlist__16c1_s_p5_0[] = {
  124038. 4,
  124039. 3,
  124040. 5,
  124041. 2,
  124042. 6,
  124043. 1,
  124044. 7,
  124045. 0,
  124046. 8,
  124047. };
  124048. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124049. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124050. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124051. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124052. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124053. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124054. 10,
  124055. };
  124056. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124057. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124058. };
  124059. static long _vq_quantmap__16c1_s_p5_0[] = {
  124060. 7, 5, 3, 1, 0, 2, 4, 6,
  124061. 8,
  124062. };
  124063. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124064. _vq_quantthresh__16c1_s_p5_0,
  124065. _vq_quantmap__16c1_s_p5_0,
  124066. 9,
  124067. 9
  124068. };
  124069. static static_codebook _16c1_s_p5_0 = {
  124070. 2, 81,
  124071. _vq_lengthlist__16c1_s_p5_0,
  124072. 1, -531628032, 1611661312, 4, 0,
  124073. _vq_quantlist__16c1_s_p5_0,
  124074. NULL,
  124075. &_vq_auxt__16c1_s_p5_0,
  124076. NULL,
  124077. 0
  124078. };
  124079. static long _vq_quantlist__16c1_s_p6_0[] = {
  124080. 8,
  124081. 7,
  124082. 9,
  124083. 6,
  124084. 10,
  124085. 5,
  124086. 11,
  124087. 4,
  124088. 12,
  124089. 3,
  124090. 13,
  124091. 2,
  124092. 14,
  124093. 1,
  124094. 15,
  124095. 0,
  124096. 16,
  124097. };
  124098. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124099. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124100. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124101. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124102. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124103. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124104. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124105. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124106. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124107. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124108. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124109. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124110. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124111. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124112. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124113. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124114. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124115. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124116. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124117. 14,
  124118. };
  124119. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124120. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124121. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124122. };
  124123. static long _vq_quantmap__16c1_s_p6_0[] = {
  124124. 15, 13, 11, 9, 7, 5, 3, 1,
  124125. 0, 2, 4, 6, 8, 10, 12, 14,
  124126. 16,
  124127. };
  124128. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124129. _vq_quantthresh__16c1_s_p6_0,
  124130. _vq_quantmap__16c1_s_p6_0,
  124131. 17,
  124132. 17
  124133. };
  124134. static static_codebook _16c1_s_p6_0 = {
  124135. 2, 289,
  124136. _vq_lengthlist__16c1_s_p6_0,
  124137. 1, -529530880, 1611661312, 5, 0,
  124138. _vq_quantlist__16c1_s_p6_0,
  124139. NULL,
  124140. &_vq_auxt__16c1_s_p6_0,
  124141. NULL,
  124142. 0
  124143. };
  124144. static long _vq_quantlist__16c1_s_p7_0[] = {
  124145. 1,
  124146. 0,
  124147. 2,
  124148. };
  124149. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124150. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124151. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124152. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124153. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124154. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124155. 11,
  124156. };
  124157. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124158. -5.5, 5.5,
  124159. };
  124160. static long _vq_quantmap__16c1_s_p7_0[] = {
  124161. 1, 0, 2,
  124162. };
  124163. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124164. _vq_quantthresh__16c1_s_p7_0,
  124165. _vq_quantmap__16c1_s_p7_0,
  124166. 3,
  124167. 3
  124168. };
  124169. static static_codebook _16c1_s_p7_0 = {
  124170. 4, 81,
  124171. _vq_lengthlist__16c1_s_p7_0,
  124172. 1, -529137664, 1618345984, 2, 0,
  124173. _vq_quantlist__16c1_s_p7_0,
  124174. NULL,
  124175. &_vq_auxt__16c1_s_p7_0,
  124176. NULL,
  124177. 0
  124178. };
  124179. static long _vq_quantlist__16c1_s_p7_1[] = {
  124180. 5,
  124181. 4,
  124182. 6,
  124183. 3,
  124184. 7,
  124185. 2,
  124186. 8,
  124187. 1,
  124188. 9,
  124189. 0,
  124190. 10,
  124191. };
  124192. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124193. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124194. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124195. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124196. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124197. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124198. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124199. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124200. 10,10,10, 8, 8, 8, 8, 9, 9,
  124201. };
  124202. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124203. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124204. 3.5, 4.5,
  124205. };
  124206. static long _vq_quantmap__16c1_s_p7_1[] = {
  124207. 9, 7, 5, 3, 1, 0, 2, 4,
  124208. 6, 8, 10,
  124209. };
  124210. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124211. _vq_quantthresh__16c1_s_p7_1,
  124212. _vq_quantmap__16c1_s_p7_1,
  124213. 11,
  124214. 11
  124215. };
  124216. static static_codebook _16c1_s_p7_1 = {
  124217. 2, 121,
  124218. _vq_lengthlist__16c1_s_p7_1,
  124219. 1, -531365888, 1611661312, 4, 0,
  124220. _vq_quantlist__16c1_s_p7_1,
  124221. NULL,
  124222. &_vq_auxt__16c1_s_p7_1,
  124223. NULL,
  124224. 0
  124225. };
  124226. static long _vq_quantlist__16c1_s_p8_0[] = {
  124227. 6,
  124228. 5,
  124229. 7,
  124230. 4,
  124231. 8,
  124232. 3,
  124233. 9,
  124234. 2,
  124235. 10,
  124236. 1,
  124237. 11,
  124238. 0,
  124239. 12,
  124240. };
  124241. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124242. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124243. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124244. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124245. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124246. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124247. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124248. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124249. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124250. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124251. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124252. 0,12,12,12,12,13,13,14,15,
  124253. };
  124254. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124255. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124256. 12.5, 17.5, 22.5, 27.5,
  124257. };
  124258. static long _vq_quantmap__16c1_s_p8_0[] = {
  124259. 11, 9, 7, 5, 3, 1, 0, 2,
  124260. 4, 6, 8, 10, 12,
  124261. };
  124262. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124263. _vq_quantthresh__16c1_s_p8_0,
  124264. _vq_quantmap__16c1_s_p8_0,
  124265. 13,
  124266. 13
  124267. };
  124268. static static_codebook _16c1_s_p8_0 = {
  124269. 2, 169,
  124270. _vq_lengthlist__16c1_s_p8_0,
  124271. 1, -526516224, 1616117760, 4, 0,
  124272. _vq_quantlist__16c1_s_p8_0,
  124273. NULL,
  124274. &_vq_auxt__16c1_s_p8_0,
  124275. NULL,
  124276. 0
  124277. };
  124278. static long _vq_quantlist__16c1_s_p8_1[] = {
  124279. 2,
  124280. 1,
  124281. 3,
  124282. 0,
  124283. 4,
  124284. };
  124285. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124286. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124287. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124288. };
  124289. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124290. -1.5, -0.5, 0.5, 1.5,
  124291. };
  124292. static long _vq_quantmap__16c1_s_p8_1[] = {
  124293. 3, 1, 0, 2, 4,
  124294. };
  124295. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124296. _vq_quantthresh__16c1_s_p8_1,
  124297. _vq_quantmap__16c1_s_p8_1,
  124298. 5,
  124299. 5
  124300. };
  124301. static static_codebook _16c1_s_p8_1 = {
  124302. 2, 25,
  124303. _vq_lengthlist__16c1_s_p8_1,
  124304. 1, -533725184, 1611661312, 3, 0,
  124305. _vq_quantlist__16c1_s_p8_1,
  124306. NULL,
  124307. &_vq_auxt__16c1_s_p8_1,
  124308. NULL,
  124309. 0
  124310. };
  124311. static long _vq_quantlist__16c1_s_p9_0[] = {
  124312. 6,
  124313. 5,
  124314. 7,
  124315. 4,
  124316. 8,
  124317. 3,
  124318. 9,
  124319. 2,
  124320. 10,
  124321. 1,
  124322. 11,
  124323. 0,
  124324. 12,
  124325. };
  124326. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124327. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124328. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124329. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124330. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124331. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124332. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124333. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124334. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124335. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124336. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124337. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124338. };
  124339. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124340. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124341. 787.5, 1102.5, 1417.5, 1732.5,
  124342. };
  124343. static long _vq_quantmap__16c1_s_p9_0[] = {
  124344. 11, 9, 7, 5, 3, 1, 0, 2,
  124345. 4, 6, 8, 10, 12,
  124346. };
  124347. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124348. _vq_quantthresh__16c1_s_p9_0,
  124349. _vq_quantmap__16c1_s_p9_0,
  124350. 13,
  124351. 13
  124352. };
  124353. static static_codebook _16c1_s_p9_0 = {
  124354. 2, 169,
  124355. _vq_lengthlist__16c1_s_p9_0,
  124356. 1, -513964032, 1628680192, 4, 0,
  124357. _vq_quantlist__16c1_s_p9_0,
  124358. NULL,
  124359. &_vq_auxt__16c1_s_p9_0,
  124360. NULL,
  124361. 0
  124362. };
  124363. static long _vq_quantlist__16c1_s_p9_1[] = {
  124364. 7,
  124365. 6,
  124366. 8,
  124367. 5,
  124368. 9,
  124369. 4,
  124370. 10,
  124371. 3,
  124372. 11,
  124373. 2,
  124374. 12,
  124375. 1,
  124376. 13,
  124377. 0,
  124378. 14,
  124379. };
  124380. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124381. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124382. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124383. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124384. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124385. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124386. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124387. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124388. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124389. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124390. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124391. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124392. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124393. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124394. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124395. 13,
  124396. };
  124397. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124398. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124399. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124400. };
  124401. static long _vq_quantmap__16c1_s_p9_1[] = {
  124402. 13, 11, 9, 7, 5, 3, 1, 0,
  124403. 2, 4, 6, 8, 10, 12, 14,
  124404. };
  124405. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124406. _vq_quantthresh__16c1_s_p9_1,
  124407. _vq_quantmap__16c1_s_p9_1,
  124408. 15,
  124409. 15
  124410. };
  124411. static static_codebook _16c1_s_p9_1 = {
  124412. 2, 225,
  124413. _vq_lengthlist__16c1_s_p9_1,
  124414. 1, -520986624, 1620377600, 4, 0,
  124415. _vq_quantlist__16c1_s_p9_1,
  124416. NULL,
  124417. &_vq_auxt__16c1_s_p9_1,
  124418. NULL,
  124419. 0
  124420. };
  124421. static long _vq_quantlist__16c1_s_p9_2[] = {
  124422. 10,
  124423. 9,
  124424. 11,
  124425. 8,
  124426. 12,
  124427. 7,
  124428. 13,
  124429. 6,
  124430. 14,
  124431. 5,
  124432. 15,
  124433. 4,
  124434. 16,
  124435. 3,
  124436. 17,
  124437. 2,
  124438. 18,
  124439. 1,
  124440. 19,
  124441. 0,
  124442. 20,
  124443. };
  124444. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124445. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124446. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124447. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124448. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124449. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124450. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124451. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124452. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124453. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124454. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124455. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124456. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124457. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124458. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124459. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124460. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124461. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124462. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124463. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124464. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124465. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124466. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124467. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124468. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124469. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124470. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124471. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124472. 11,11,11,11,12,11,11,12,11,
  124473. };
  124474. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124475. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124476. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124477. 6.5, 7.5, 8.5, 9.5,
  124478. };
  124479. static long _vq_quantmap__16c1_s_p9_2[] = {
  124480. 19, 17, 15, 13, 11, 9, 7, 5,
  124481. 3, 1, 0, 2, 4, 6, 8, 10,
  124482. 12, 14, 16, 18, 20,
  124483. };
  124484. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124485. _vq_quantthresh__16c1_s_p9_2,
  124486. _vq_quantmap__16c1_s_p9_2,
  124487. 21,
  124488. 21
  124489. };
  124490. static static_codebook _16c1_s_p9_2 = {
  124491. 2, 441,
  124492. _vq_lengthlist__16c1_s_p9_2,
  124493. 1, -529268736, 1611661312, 5, 0,
  124494. _vq_quantlist__16c1_s_p9_2,
  124495. NULL,
  124496. &_vq_auxt__16c1_s_p9_2,
  124497. NULL,
  124498. 0
  124499. };
  124500. static long _huff_lengthlist__16c1_s_short[] = {
  124501. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  124502. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  124503. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  124504. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  124505. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  124506. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  124507. 9, 9,10,13,
  124508. };
  124509. static static_codebook _huff_book__16c1_s_short = {
  124510. 2, 100,
  124511. _huff_lengthlist__16c1_s_short,
  124512. 0, 0, 0, 0, 0,
  124513. NULL,
  124514. NULL,
  124515. NULL,
  124516. NULL,
  124517. 0
  124518. };
  124519. static long _huff_lengthlist__16c2_s_long[] = {
  124520. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  124521. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  124522. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  124523. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  124524. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  124525. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  124526. 14,14,16,18,
  124527. };
  124528. static static_codebook _huff_book__16c2_s_long = {
  124529. 2, 100,
  124530. _huff_lengthlist__16c2_s_long,
  124531. 0, 0, 0, 0, 0,
  124532. NULL,
  124533. NULL,
  124534. NULL,
  124535. NULL,
  124536. 0
  124537. };
  124538. static long _vq_quantlist__16c2_s_p1_0[] = {
  124539. 1,
  124540. 0,
  124541. 2,
  124542. };
  124543. static long _vq_lengthlist__16c2_s_p1_0[] = {
  124544. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  124545. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124549. 0,
  124550. };
  124551. static float _vq_quantthresh__16c2_s_p1_0[] = {
  124552. -0.5, 0.5,
  124553. };
  124554. static long _vq_quantmap__16c2_s_p1_0[] = {
  124555. 1, 0, 2,
  124556. };
  124557. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  124558. _vq_quantthresh__16c2_s_p1_0,
  124559. _vq_quantmap__16c2_s_p1_0,
  124560. 3,
  124561. 3
  124562. };
  124563. static static_codebook _16c2_s_p1_0 = {
  124564. 4, 81,
  124565. _vq_lengthlist__16c2_s_p1_0,
  124566. 1, -535822336, 1611661312, 2, 0,
  124567. _vq_quantlist__16c2_s_p1_0,
  124568. NULL,
  124569. &_vq_auxt__16c2_s_p1_0,
  124570. NULL,
  124571. 0
  124572. };
  124573. static long _vq_quantlist__16c2_s_p2_0[] = {
  124574. 2,
  124575. 1,
  124576. 3,
  124577. 0,
  124578. 4,
  124579. };
  124580. static long _vq_lengthlist__16c2_s_p2_0[] = {
  124581. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  124582. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  124583. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  124584. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  124585. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  124586. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  124587. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  124588. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  124589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124593. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  124594. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  124595. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  124596. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  124597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124601. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  124602. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  124603. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  124604. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124609. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  124610. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  124611. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  124612. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  124617. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  124618. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  124619. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  124620. 13,
  124621. };
  124622. static float _vq_quantthresh__16c2_s_p2_0[] = {
  124623. -1.5, -0.5, 0.5, 1.5,
  124624. };
  124625. static long _vq_quantmap__16c2_s_p2_0[] = {
  124626. 3, 1, 0, 2, 4,
  124627. };
  124628. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  124629. _vq_quantthresh__16c2_s_p2_0,
  124630. _vq_quantmap__16c2_s_p2_0,
  124631. 5,
  124632. 5
  124633. };
  124634. static static_codebook _16c2_s_p2_0 = {
  124635. 4, 625,
  124636. _vq_lengthlist__16c2_s_p2_0,
  124637. 1, -533725184, 1611661312, 3, 0,
  124638. _vq_quantlist__16c2_s_p2_0,
  124639. NULL,
  124640. &_vq_auxt__16c2_s_p2_0,
  124641. NULL,
  124642. 0
  124643. };
  124644. static long _vq_quantlist__16c2_s_p3_0[] = {
  124645. 4,
  124646. 3,
  124647. 5,
  124648. 2,
  124649. 6,
  124650. 1,
  124651. 7,
  124652. 0,
  124653. 8,
  124654. };
  124655. static long _vq_lengthlist__16c2_s_p3_0[] = {
  124656. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  124657. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  124658. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124659. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  124660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124661. 0,
  124662. };
  124663. static float _vq_quantthresh__16c2_s_p3_0[] = {
  124664. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124665. };
  124666. static long _vq_quantmap__16c2_s_p3_0[] = {
  124667. 7, 5, 3, 1, 0, 2, 4, 6,
  124668. 8,
  124669. };
  124670. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  124671. _vq_quantthresh__16c2_s_p3_0,
  124672. _vq_quantmap__16c2_s_p3_0,
  124673. 9,
  124674. 9
  124675. };
  124676. static static_codebook _16c2_s_p3_0 = {
  124677. 2, 81,
  124678. _vq_lengthlist__16c2_s_p3_0,
  124679. 1, -531628032, 1611661312, 4, 0,
  124680. _vq_quantlist__16c2_s_p3_0,
  124681. NULL,
  124682. &_vq_auxt__16c2_s_p3_0,
  124683. NULL,
  124684. 0
  124685. };
  124686. static long _vq_quantlist__16c2_s_p4_0[] = {
  124687. 8,
  124688. 7,
  124689. 9,
  124690. 6,
  124691. 10,
  124692. 5,
  124693. 11,
  124694. 4,
  124695. 12,
  124696. 3,
  124697. 13,
  124698. 2,
  124699. 14,
  124700. 1,
  124701. 15,
  124702. 0,
  124703. 16,
  124704. };
  124705. static long _vq_lengthlist__16c2_s_p4_0[] = {
  124706. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  124707. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  124708. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  124709. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  124710. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  124711. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  124712. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  124713. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  124714. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  124715. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  124716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124719. 0, 0, 0, 0, 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, 0,
  124724. 0,
  124725. };
  124726. static float _vq_quantthresh__16c2_s_p4_0[] = {
  124727. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124728. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124729. };
  124730. static long _vq_quantmap__16c2_s_p4_0[] = {
  124731. 15, 13, 11, 9, 7, 5, 3, 1,
  124732. 0, 2, 4, 6, 8, 10, 12, 14,
  124733. 16,
  124734. };
  124735. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  124736. _vq_quantthresh__16c2_s_p4_0,
  124737. _vq_quantmap__16c2_s_p4_0,
  124738. 17,
  124739. 17
  124740. };
  124741. static static_codebook _16c2_s_p4_0 = {
  124742. 2, 289,
  124743. _vq_lengthlist__16c2_s_p4_0,
  124744. 1, -529530880, 1611661312, 5, 0,
  124745. _vq_quantlist__16c2_s_p4_0,
  124746. NULL,
  124747. &_vq_auxt__16c2_s_p4_0,
  124748. NULL,
  124749. 0
  124750. };
  124751. static long _vq_quantlist__16c2_s_p5_0[] = {
  124752. 1,
  124753. 0,
  124754. 2,
  124755. };
  124756. static long _vq_lengthlist__16c2_s_p5_0[] = {
  124757. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  124758. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  124759. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  124760. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  124761. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  124762. 12,
  124763. };
  124764. static float _vq_quantthresh__16c2_s_p5_0[] = {
  124765. -5.5, 5.5,
  124766. };
  124767. static long _vq_quantmap__16c2_s_p5_0[] = {
  124768. 1, 0, 2,
  124769. };
  124770. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  124771. _vq_quantthresh__16c2_s_p5_0,
  124772. _vq_quantmap__16c2_s_p5_0,
  124773. 3,
  124774. 3
  124775. };
  124776. static static_codebook _16c2_s_p5_0 = {
  124777. 4, 81,
  124778. _vq_lengthlist__16c2_s_p5_0,
  124779. 1, -529137664, 1618345984, 2, 0,
  124780. _vq_quantlist__16c2_s_p5_0,
  124781. NULL,
  124782. &_vq_auxt__16c2_s_p5_0,
  124783. NULL,
  124784. 0
  124785. };
  124786. static long _vq_quantlist__16c2_s_p5_1[] = {
  124787. 5,
  124788. 4,
  124789. 6,
  124790. 3,
  124791. 7,
  124792. 2,
  124793. 8,
  124794. 1,
  124795. 9,
  124796. 0,
  124797. 10,
  124798. };
  124799. static long _vq_lengthlist__16c2_s_p5_1[] = {
  124800. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  124801. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  124802. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  124803. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  124804. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  124805. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  124806. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  124807. 11,11,11, 7, 7, 8, 8, 8, 8,
  124808. };
  124809. static float _vq_quantthresh__16c2_s_p5_1[] = {
  124810. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124811. 3.5, 4.5,
  124812. };
  124813. static long _vq_quantmap__16c2_s_p5_1[] = {
  124814. 9, 7, 5, 3, 1, 0, 2, 4,
  124815. 6, 8, 10,
  124816. };
  124817. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  124818. _vq_quantthresh__16c2_s_p5_1,
  124819. _vq_quantmap__16c2_s_p5_1,
  124820. 11,
  124821. 11
  124822. };
  124823. static static_codebook _16c2_s_p5_1 = {
  124824. 2, 121,
  124825. _vq_lengthlist__16c2_s_p5_1,
  124826. 1, -531365888, 1611661312, 4, 0,
  124827. _vq_quantlist__16c2_s_p5_1,
  124828. NULL,
  124829. &_vq_auxt__16c2_s_p5_1,
  124830. NULL,
  124831. 0
  124832. };
  124833. static long _vq_quantlist__16c2_s_p6_0[] = {
  124834. 6,
  124835. 5,
  124836. 7,
  124837. 4,
  124838. 8,
  124839. 3,
  124840. 9,
  124841. 2,
  124842. 10,
  124843. 1,
  124844. 11,
  124845. 0,
  124846. 12,
  124847. };
  124848. static long _vq_lengthlist__16c2_s_p6_0[] = {
  124849. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124850. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  124851. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  124852. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  124853. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  124854. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  124855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124859. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124860. };
  124861. static float _vq_quantthresh__16c2_s_p6_0[] = {
  124862. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124863. 12.5, 17.5, 22.5, 27.5,
  124864. };
  124865. static long _vq_quantmap__16c2_s_p6_0[] = {
  124866. 11, 9, 7, 5, 3, 1, 0, 2,
  124867. 4, 6, 8, 10, 12,
  124868. };
  124869. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  124870. _vq_quantthresh__16c2_s_p6_0,
  124871. _vq_quantmap__16c2_s_p6_0,
  124872. 13,
  124873. 13
  124874. };
  124875. static static_codebook _16c2_s_p6_0 = {
  124876. 2, 169,
  124877. _vq_lengthlist__16c2_s_p6_0,
  124878. 1, -526516224, 1616117760, 4, 0,
  124879. _vq_quantlist__16c2_s_p6_0,
  124880. NULL,
  124881. &_vq_auxt__16c2_s_p6_0,
  124882. NULL,
  124883. 0
  124884. };
  124885. static long _vq_quantlist__16c2_s_p6_1[] = {
  124886. 2,
  124887. 1,
  124888. 3,
  124889. 0,
  124890. 4,
  124891. };
  124892. static long _vq_lengthlist__16c2_s_p6_1[] = {
  124893. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124894. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124895. };
  124896. static float _vq_quantthresh__16c2_s_p6_1[] = {
  124897. -1.5, -0.5, 0.5, 1.5,
  124898. };
  124899. static long _vq_quantmap__16c2_s_p6_1[] = {
  124900. 3, 1, 0, 2, 4,
  124901. };
  124902. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  124903. _vq_quantthresh__16c2_s_p6_1,
  124904. _vq_quantmap__16c2_s_p6_1,
  124905. 5,
  124906. 5
  124907. };
  124908. static static_codebook _16c2_s_p6_1 = {
  124909. 2, 25,
  124910. _vq_lengthlist__16c2_s_p6_1,
  124911. 1, -533725184, 1611661312, 3, 0,
  124912. _vq_quantlist__16c2_s_p6_1,
  124913. NULL,
  124914. &_vq_auxt__16c2_s_p6_1,
  124915. NULL,
  124916. 0
  124917. };
  124918. static long _vq_quantlist__16c2_s_p7_0[] = {
  124919. 6,
  124920. 5,
  124921. 7,
  124922. 4,
  124923. 8,
  124924. 3,
  124925. 9,
  124926. 2,
  124927. 10,
  124928. 1,
  124929. 11,
  124930. 0,
  124931. 12,
  124932. };
  124933. static long _vq_lengthlist__16c2_s_p7_0[] = {
  124934. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124935. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  124936. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  124937. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  124938. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  124939. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  124940. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  124941. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  124942. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  124943. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  124944. 18,13,14,13,13,14,13,15,14,
  124945. };
  124946. static float _vq_quantthresh__16c2_s_p7_0[] = {
  124947. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  124948. 27.5, 38.5, 49.5, 60.5,
  124949. };
  124950. static long _vq_quantmap__16c2_s_p7_0[] = {
  124951. 11, 9, 7, 5, 3, 1, 0, 2,
  124952. 4, 6, 8, 10, 12,
  124953. };
  124954. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  124955. _vq_quantthresh__16c2_s_p7_0,
  124956. _vq_quantmap__16c2_s_p7_0,
  124957. 13,
  124958. 13
  124959. };
  124960. static static_codebook _16c2_s_p7_0 = {
  124961. 2, 169,
  124962. _vq_lengthlist__16c2_s_p7_0,
  124963. 1, -523206656, 1618345984, 4, 0,
  124964. _vq_quantlist__16c2_s_p7_0,
  124965. NULL,
  124966. &_vq_auxt__16c2_s_p7_0,
  124967. NULL,
  124968. 0
  124969. };
  124970. static long _vq_quantlist__16c2_s_p7_1[] = {
  124971. 5,
  124972. 4,
  124973. 6,
  124974. 3,
  124975. 7,
  124976. 2,
  124977. 8,
  124978. 1,
  124979. 9,
  124980. 0,
  124981. 10,
  124982. };
  124983. static long _vq_lengthlist__16c2_s_p7_1[] = {
  124984. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  124985. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  124986. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  124987. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124988. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  124989. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  124990. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  124991. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124992. };
  124993. static float _vq_quantthresh__16c2_s_p7_1[] = {
  124994. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124995. 3.5, 4.5,
  124996. };
  124997. static long _vq_quantmap__16c2_s_p7_1[] = {
  124998. 9, 7, 5, 3, 1, 0, 2, 4,
  124999. 6, 8, 10,
  125000. };
  125001. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  125002. _vq_quantthresh__16c2_s_p7_1,
  125003. _vq_quantmap__16c2_s_p7_1,
  125004. 11,
  125005. 11
  125006. };
  125007. static static_codebook _16c2_s_p7_1 = {
  125008. 2, 121,
  125009. _vq_lengthlist__16c2_s_p7_1,
  125010. 1, -531365888, 1611661312, 4, 0,
  125011. _vq_quantlist__16c2_s_p7_1,
  125012. NULL,
  125013. &_vq_auxt__16c2_s_p7_1,
  125014. NULL,
  125015. 0
  125016. };
  125017. static long _vq_quantlist__16c2_s_p8_0[] = {
  125018. 7,
  125019. 6,
  125020. 8,
  125021. 5,
  125022. 9,
  125023. 4,
  125024. 10,
  125025. 3,
  125026. 11,
  125027. 2,
  125028. 12,
  125029. 1,
  125030. 13,
  125031. 0,
  125032. 14,
  125033. };
  125034. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125035. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125036. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125037. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125038. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125039. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125040. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125041. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125042. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125043. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125044. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125045. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125046. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125047. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125048. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125049. 13,
  125050. };
  125051. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125052. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125053. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125054. };
  125055. static long _vq_quantmap__16c2_s_p8_0[] = {
  125056. 13, 11, 9, 7, 5, 3, 1, 0,
  125057. 2, 4, 6, 8, 10, 12, 14,
  125058. };
  125059. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125060. _vq_quantthresh__16c2_s_p8_0,
  125061. _vq_quantmap__16c2_s_p8_0,
  125062. 15,
  125063. 15
  125064. };
  125065. static static_codebook _16c2_s_p8_0 = {
  125066. 2, 225,
  125067. _vq_lengthlist__16c2_s_p8_0,
  125068. 1, -520986624, 1620377600, 4, 0,
  125069. _vq_quantlist__16c2_s_p8_0,
  125070. NULL,
  125071. &_vq_auxt__16c2_s_p8_0,
  125072. NULL,
  125073. 0
  125074. };
  125075. static long _vq_quantlist__16c2_s_p8_1[] = {
  125076. 10,
  125077. 9,
  125078. 11,
  125079. 8,
  125080. 12,
  125081. 7,
  125082. 13,
  125083. 6,
  125084. 14,
  125085. 5,
  125086. 15,
  125087. 4,
  125088. 16,
  125089. 3,
  125090. 17,
  125091. 2,
  125092. 18,
  125093. 1,
  125094. 19,
  125095. 0,
  125096. 20,
  125097. };
  125098. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125099. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125100. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125101. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125102. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125103. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125104. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125105. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125106. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125107. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125108. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125109. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125110. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125111. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125112. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125113. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125114. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125115. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125116. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125117. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125118. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125119. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125120. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125121. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125122. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125123. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125124. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125125. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125126. 10,11,10,10,10,10,10,10,10,
  125127. };
  125128. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125129. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125130. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125131. 6.5, 7.5, 8.5, 9.5,
  125132. };
  125133. static long _vq_quantmap__16c2_s_p8_1[] = {
  125134. 19, 17, 15, 13, 11, 9, 7, 5,
  125135. 3, 1, 0, 2, 4, 6, 8, 10,
  125136. 12, 14, 16, 18, 20,
  125137. };
  125138. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125139. _vq_quantthresh__16c2_s_p8_1,
  125140. _vq_quantmap__16c2_s_p8_1,
  125141. 21,
  125142. 21
  125143. };
  125144. static static_codebook _16c2_s_p8_1 = {
  125145. 2, 441,
  125146. _vq_lengthlist__16c2_s_p8_1,
  125147. 1, -529268736, 1611661312, 5, 0,
  125148. _vq_quantlist__16c2_s_p8_1,
  125149. NULL,
  125150. &_vq_auxt__16c2_s_p8_1,
  125151. NULL,
  125152. 0
  125153. };
  125154. static long _vq_quantlist__16c2_s_p9_0[] = {
  125155. 6,
  125156. 5,
  125157. 7,
  125158. 4,
  125159. 8,
  125160. 3,
  125161. 9,
  125162. 2,
  125163. 10,
  125164. 1,
  125165. 11,
  125166. 0,
  125167. 12,
  125168. };
  125169. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125170. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125171. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125172. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125173. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125174. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125175. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125176. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125177. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125178. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125179. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125180. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125181. };
  125182. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125183. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125184. 2327.5, 3258.5, 4189.5, 5120.5,
  125185. };
  125186. static long _vq_quantmap__16c2_s_p9_0[] = {
  125187. 11, 9, 7, 5, 3, 1, 0, 2,
  125188. 4, 6, 8, 10, 12,
  125189. };
  125190. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125191. _vq_quantthresh__16c2_s_p9_0,
  125192. _vq_quantmap__16c2_s_p9_0,
  125193. 13,
  125194. 13
  125195. };
  125196. static static_codebook _16c2_s_p9_0 = {
  125197. 2, 169,
  125198. _vq_lengthlist__16c2_s_p9_0,
  125199. 1, -510275072, 1631393792, 4, 0,
  125200. _vq_quantlist__16c2_s_p9_0,
  125201. NULL,
  125202. &_vq_auxt__16c2_s_p9_0,
  125203. NULL,
  125204. 0
  125205. };
  125206. static long _vq_quantlist__16c2_s_p9_1[] = {
  125207. 8,
  125208. 7,
  125209. 9,
  125210. 6,
  125211. 10,
  125212. 5,
  125213. 11,
  125214. 4,
  125215. 12,
  125216. 3,
  125217. 13,
  125218. 2,
  125219. 14,
  125220. 1,
  125221. 15,
  125222. 0,
  125223. 16,
  125224. };
  125225. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125226. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125227. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125228. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125229. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125230. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125231. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125232. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125233. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125234. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125235. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125236. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125237. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125238. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125239. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125240. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125241. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125242. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125243. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125244. 10,
  125245. };
  125246. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125247. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125248. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125249. };
  125250. static long _vq_quantmap__16c2_s_p9_1[] = {
  125251. 15, 13, 11, 9, 7, 5, 3, 1,
  125252. 0, 2, 4, 6, 8, 10, 12, 14,
  125253. 16,
  125254. };
  125255. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125256. _vq_quantthresh__16c2_s_p9_1,
  125257. _vq_quantmap__16c2_s_p9_1,
  125258. 17,
  125259. 17
  125260. };
  125261. static static_codebook _16c2_s_p9_1 = {
  125262. 2, 289,
  125263. _vq_lengthlist__16c2_s_p9_1,
  125264. 1, -518488064, 1622704128, 5, 0,
  125265. _vq_quantlist__16c2_s_p9_1,
  125266. NULL,
  125267. &_vq_auxt__16c2_s_p9_1,
  125268. NULL,
  125269. 0
  125270. };
  125271. static long _vq_quantlist__16c2_s_p9_2[] = {
  125272. 13,
  125273. 12,
  125274. 14,
  125275. 11,
  125276. 15,
  125277. 10,
  125278. 16,
  125279. 9,
  125280. 17,
  125281. 8,
  125282. 18,
  125283. 7,
  125284. 19,
  125285. 6,
  125286. 20,
  125287. 5,
  125288. 21,
  125289. 4,
  125290. 22,
  125291. 3,
  125292. 23,
  125293. 2,
  125294. 24,
  125295. 1,
  125296. 25,
  125297. 0,
  125298. 26,
  125299. };
  125300. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125301. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125302. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125303. };
  125304. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125305. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125306. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125307. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125308. 11.5, 12.5,
  125309. };
  125310. static long _vq_quantmap__16c2_s_p9_2[] = {
  125311. 25, 23, 21, 19, 17, 15, 13, 11,
  125312. 9, 7, 5, 3, 1, 0, 2, 4,
  125313. 6, 8, 10, 12, 14, 16, 18, 20,
  125314. 22, 24, 26,
  125315. };
  125316. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125317. _vq_quantthresh__16c2_s_p9_2,
  125318. _vq_quantmap__16c2_s_p9_2,
  125319. 27,
  125320. 27
  125321. };
  125322. static static_codebook _16c2_s_p9_2 = {
  125323. 1, 27,
  125324. _vq_lengthlist__16c2_s_p9_2,
  125325. 1, -528875520, 1611661312, 5, 0,
  125326. _vq_quantlist__16c2_s_p9_2,
  125327. NULL,
  125328. &_vq_auxt__16c2_s_p9_2,
  125329. NULL,
  125330. 0
  125331. };
  125332. static long _huff_lengthlist__16c2_s_short[] = {
  125333. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125334. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125335. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125336. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125337. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125338. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125339. 15,12,14,14,
  125340. };
  125341. static static_codebook _huff_book__16c2_s_short = {
  125342. 2, 100,
  125343. _huff_lengthlist__16c2_s_short,
  125344. 0, 0, 0, 0, 0,
  125345. NULL,
  125346. NULL,
  125347. NULL,
  125348. NULL,
  125349. 0
  125350. };
  125351. static long _vq_quantlist__8c0_s_p1_0[] = {
  125352. 1,
  125353. 0,
  125354. 2,
  125355. };
  125356. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125357. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125358. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125362. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125363. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125367. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125368. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  125403. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  125408. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  125413. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125448. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125449. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125453. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125454. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  125455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125458. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125459. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125465. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125470. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125475. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  125510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  125515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  125520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125556. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125561. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  125768. };
  125769. static float _vq_quantthresh__8c0_s_p1_0[] = {
  125770. -0.5, 0.5,
  125771. };
  125772. static long _vq_quantmap__8c0_s_p1_0[] = {
  125773. 1, 0, 2,
  125774. };
  125775. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  125776. _vq_quantthresh__8c0_s_p1_0,
  125777. _vq_quantmap__8c0_s_p1_0,
  125778. 3,
  125779. 3
  125780. };
  125781. static static_codebook _8c0_s_p1_0 = {
  125782. 8, 6561,
  125783. _vq_lengthlist__8c0_s_p1_0,
  125784. 1, -535822336, 1611661312, 2, 0,
  125785. _vq_quantlist__8c0_s_p1_0,
  125786. NULL,
  125787. &_vq_auxt__8c0_s_p1_0,
  125788. NULL,
  125789. 0
  125790. };
  125791. static long _vq_quantlist__8c0_s_p2_0[] = {
  125792. 2,
  125793. 1,
  125794. 3,
  125795. 0,
  125796. 4,
  125797. };
  125798. static long _vq_lengthlist__8c0_s_p2_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,
  125839. };
  125840. static float _vq_quantthresh__8c0_s_p2_0[] = {
  125841. -1.5, -0.5, 0.5, 1.5,
  125842. };
  125843. static long _vq_quantmap__8c0_s_p2_0[] = {
  125844. 3, 1, 0, 2, 4,
  125845. };
  125846. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  125847. _vq_quantthresh__8c0_s_p2_0,
  125848. _vq_quantmap__8c0_s_p2_0,
  125849. 5,
  125850. 5
  125851. };
  125852. static static_codebook _8c0_s_p2_0 = {
  125853. 4, 625,
  125854. _vq_lengthlist__8c0_s_p2_0,
  125855. 1, -533725184, 1611661312, 3, 0,
  125856. _vq_quantlist__8c0_s_p2_0,
  125857. NULL,
  125858. &_vq_auxt__8c0_s_p2_0,
  125859. NULL,
  125860. 0
  125861. };
  125862. static long _vq_quantlist__8c0_s_p3_0[] = {
  125863. 2,
  125864. 1,
  125865. 3,
  125866. 0,
  125867. 4,
  125868. };
  125869. static long _vq_lengthlist__8c0_s_p3_0[] = {
  125870. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  125872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125873. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  125875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125876. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  125877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125909. 0,
  125910. };
  125911. static float _vq_quantthresh__8c0_s_p3_0[] = {
  125912. -1.5, -0.5, 0.5, 1.5,
  125913. };
  125914. static long _vq_quantmap__8c0_s_p3_0[] = {
  125915. 3, 1, 0, 2, 4,
  125916. };
  125917. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  125918. _vq_quantthresh__8c0_s_p3_0,
  125919. _vq_quantmap__8c0_s_p3_0,
  125920. 5,
  125921. 5
  125922. };
  125923. static static_codebook _8c0_s_p3_0 = {
  125924. 4, 625,
  125925. _vq_lengthlist__8c0_s_p3_0,
  125926. 1, -533725184, 1611661312, 3, 0,
  125927. _vq_quantlist__8c0_s_p3_0,
  125928. NULL,
  125929. &_vq_auxt__8c0_s_p3_0,
  125930. NULL,
  125931. 0
  125932. };
  125933. static long _vq_quantlist__8c0_s_p4_0[] = {
  125934. 4,
  125935. 3,
  125936. 5,
  125937. 2,
  125938. 6,
  125939. 1,
  125940. 7,
  125941. 0,
  125942. 8,
  125943. };
  125944. static long _vq_lengthlist__8c0_s_p4_0[] = {
  125945. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  125946. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  125947. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  125948. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  125949. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125950. 0,
  125951. };
  125952. static float _vq_quantthresh__8c0_s_p4_0[] = {
  125953. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125954. };
  125955. static long _vq_quantmap__8c0_s_p4_0[] = {
  125956. 7, 5, 3, 1, 0, 2, 4, 6,
  125957. 8,
  125958. };
  125959. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  125960. _vq_quantthresh__8c0_s_p4_0,
  125961. _vq_quantmap__8c0_s_p4_0,
  125962. 9,
  125963. 9
  125964. };
  125965. static static_codebook _8c0_s_p4_0 = {
  125966. 2, 81,
  125967. _vq_lengthlist__8c0_s_p4_0,
  125968. 1, -531628032, 1611661312, 4, 0,
  125969. _vq_quantlist__8c0_s_p4_0,
  125970. NULL,
  125971. &_vq_auxt__8c0_s_p4_0,
  125972. NULL,
  125973. 0
  125974. };
  125975. static long _vq_quantlist__8c0_s_p5_0[] = {
  125976. 4,
  125977. 3,
  125978. 5,
  125979. 2,
  125980. 6,
  125981. 1,
  125982. 7,
  125983. 0,
  125984. 8,
  125985. };
  125986. static long _vq_lengthlist__8c0_s_p5_0[] = {
  125987. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  125988. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  125989. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  125990. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  125991. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  125992. 10,
  125993. };
  125994. static float _vq_quantthresh__8c0_s_p5_0[] = {
  125995. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125996. };
  125997. static long _vq_quantmap__8c0_s_p5_0[] = {
  125998. 7, 5, 3, 1, 0, 2, 4, 6,
  125999. 8,
  126000. };
  126001. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  126002. _vq_quantthresh__8c0_s_p5_0,
  126003. _vq_quantmap__8c0_s_p5_0,
  126004. 9,
  126005. 9
  126006. };
  126007. static static_codebook _8c0_s_p5_0 = {
  126008. 2, 81,
  126009. _vq_lengthlist__8c0_s_p5_0,
  126010. 1, -531628032, 1611661312, 4, 0,
  126011. _vq_quantlist__8c0_s_p5_0,
  126012. NULL,
  126013. &_vq_auxt__8c0_s_p5_0,
  126014. NULL,
  126015. 0
  126016. };
  126017. static long _vq_quantlist__8c0_s_p6_0[] = {
  126018. 8,
  126019. 7,
  126020. 9,
  126021. 6,
  126022. 10,
  126023. 5,
  126024. 11,
  126025. 4,
  126026. 12,
  126027. 3,
  126028. 13,
  126029. 2,
  126030. 14,
  126031. 1,
  126032. 15,
  126033. 0,
  126034. 16,
  126035. };
  126036. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126037. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126038. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126039. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126040. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126041. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126042. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126043. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126044. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126045. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126046. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126047. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126048. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126049. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126050. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126051. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126052. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126053. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126054. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126055. 14,
  126056. };
  126057. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126058. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126059. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126060. };
  126061. static long _vq_quantmap__8c0_s_p6_0[] = {
  126062. 15, 13, 11, 9, 7, 5, 3, 1,
  126063. 0, 2, 4, 6, 8, 10, 12, 14,
  126064. 16,
  126065. };
  126066. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126067. _vq_quantthresh__8c0_s_p6_0,
  126068. _vq_quantmap__8c0_s_p6_0,
  126069. 17,
  126070. 17
  126071. };
  126072. static static_codebook _8c0_s_p6_0 = {
  126073. 2, 289,
  126074. _vq_lengthlist__8c0_s_p6_0,
  126075. 1, -529530880, 1611661312, 5, 0,
  126076. _vq_quantlist__8c0_s_p6_0,
  126077. NULL,
  126078. &_vq_auxt__8c0_s_p6_0,
  126079. NULL,
  126080. 0
  126081. };
  126082. static long _vq_quantlist__8c0_s_p7_0[] = {
  126083. 1,
  126084. 0,
  126085. 2,
  126086. };
  126087. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126088. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126089. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126090. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126091. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126092. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126093. 10,
  126094. };
  126095. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126096. -5.5, 5.5,
  126097. };
  126098. static long _vq_quantmap__8c0_s_p7_0[] = {
  126099. 1, 0, 2,
  126100. };
  126101. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126102. _vq_quantthresh__8c0_s_p7_0,
  126103. _vq_quantmap__8c0_s_p7_0,
  126104. 3,
  126105. 3
  126106. };
  126107. static static_codebook _8c0_s_p7_0 = {
  126108. 4, 81,
  126109. _vq_lengthlist__8c0_s_p7_0,
  126110. 1, -529137664, 1618345984, 2, 0,
  126111. _vq_quantlist__8c0_s_p7_0,
  126112. NULL,
  126113. &_vq_auxt__8c0_s_p7_0,
  126114. NULL,
  126115. 0
  126116. };
  126117. static long _vq_quantlist__8c0_s_p7_1[] = {
  126118. 5,
  126119. 4,
  126120. 6,
  126121. 3,
  126122. 7,
  126123. 2,
  126124. 8,
  126125. 1,
  126126. 9,
  126127. 0,
  126128. 10,
  126129. };
  126130. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126131. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126132. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126133. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126134. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126135. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126136. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126137. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126138. 10,10,10, 9, 9, 9,10,10,10,
  126139. };
  126140. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126141. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126142. 3.5, 4.5,
  126143. };
  126144. static long _vq_quantmap__8c0_s_p7_1[] = {
  126145. 9, 7, 5, 3, 1, 0, 2, 4,
  126146. 6, 8, 10,
  126147. };
  126148. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126149. _vq_quantthresh__8c0_s_p7_1,
  126150. _vq_quantmap__8c0_s_p7_1,
  126151. 11,
  126152. 11
  126153. };
  126154. static static_codebook _8c0_s_p7_1 = {
  126155. 2, 121,
  126156. _vq_lengthlist__8c0_s_p7_1,
  126157. 1, -531365888, 1611661312, 4, 0,
  126158. _vq_quantlist__8c0_s_p7_1,
  126159. NULL,
  126160. &_vq_auxt__8c0_s_p7_1,
  126161. NULL,
  126162. 0
  126163. };
  126164. static long _vq_quantlist__8c0_s_p8_0[] = {
  126165. 6,
  126166. 5,
  126167. 7,
  126168. 4,
  126169. 8,
  126170. 3,
  126171. 9,
  126172. 2,
  126173. 10,
  126174. 1,
  126175. 11,
  126176. 0,
  126177. 12,
  126178. };
  126179. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126180. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126181. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126182. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126183. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126184. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126185. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126186. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126187. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126188. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126189. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126190. 0, 0,13,13,11,13,13,11,12,
  126191. };
  126192. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126193. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126194. 12.5, 17.5, 22.5, 27.5,
  126195. };
  126196. static long _vq_quantmap__8c0_s_p8_0[] = {
  126197. 11, 9, 7, 5, 3, 1, 0, 2,
  126198. 4, 6, 8, 10, 12,
  126199. };
  126200. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126201. _vq_quantthresh__8c0_s_p8_0,
  126202. _vq_quantmap__8c0_s_p8_0,
  126203. 13,
  126204. 13
  126205. };
  126206. static static_codebook _8c0_s_p8_0 = {
  126207. 2, 169,
  126208. _vq_lengthlist__8c0_s_p8_0,
  126209. 1, -526516224, 1616117760, 4, 0,
  126210. _vq_quantlist__8c0_s_p8_0,
  126211. NULL,
  126212. &_vq_auxt__8c0_s_p8_0,
  126213. NULL,
  126214. 0
  126215. };
  126216. static long _vq_quantlist__8c0_s_p8_1[] = {
  126217. 2,
  126218. 1,
  126219. 3,
  126220. 0,
  126221. 4,
  126222. };
  126223. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126224. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126225. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126226. };
  126227. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126228. -1.5, -0.5, 0.5, 1.5,
  126229. };
  126230. static long _vq_quantmap__8c0_s_p8_1[] = {
  126231. 3, 1, 0, 2, 4,
  126232. };
  126233. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126234. _vq_quantthresh__8c0_s_p8_1,
  126235. _vq_quantmap__8c0_s_p8_1,
  126236. 5,
  126237. 5
  126238. };
  126239. static static_codebook _8c0_s_p8_1 = {
  126240. 2, 25,
  126241. _vq_lengthlist__8c0_s_p8_1,
  126242. 1, -533725184, 1611661312, 3, 0,
  126243. _vq_quantlist__8c0_s_p8_1,
  126244. NULL,
  126245. &_vq_auxt__8c0_s_p8_1,
  126246. NULL,
  126247. 0
  126248. };
  126249. static long _vq_quantlist__8c0_s_p9_0[] = {
  126250. 1,
  126251. 0,
  126252. 2,
  126253. };
  126254. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126255. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126256. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126257. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126258. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126259. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126260. 7,
  126261. };
  126262. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126263. -157.5, 157.5,
  126264. };
  126265. static long _vq_quantmap__8c0_s_p9_0[] = {
  126266. 1, 0, 2,
  126267. };
  126268. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126269. _vq_quantthresh__8c0_s_p9_0,
  126270. _vq_quantmap__8c0_s_p9_0,
  126271. 3,
  126272. 3
  126273. };
  126274. static static_codebook _8c0_s_p9_0 = {
  126275. 4, 81,
  126276. _vq_lengthlist__8c0_s_p9_0,
  126277. 1, -518803456, 1628680192, 2, 0,
  126278. _vq_quantlist__8c0_s_p9_0,
  126279. NULL,
  126280. &_vq_auxt__8c0_s_p9_0,
  126281. NULL,
  126282. 0
  126283. };
  126284. static long _vq_quantlist__8c0_s_p9_1[] = {
  126285. 7,
  126286. 6,
  126287. 8,
  126288. 5,
  126289. 9,
  126290. 4,
  126291. 10,
  126292. 3,
  126293. 11,
  126294. 2,
  126295. 12,
  126296. 1,
  126297. 13,
  126298. 0,
  126299. 14,
  126300. };
  126301. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126302. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126303. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126304. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126305. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126306. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126307. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126308. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126309. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126310. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126311. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126312. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126313. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126314. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126315. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126316. 11,
  126317. };
  126318. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126319. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126320. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126321. };
  126322. static long _vq_quantmap__8c0_s_p9_1[] = {
  126323. 13, 11, 9, 7, 5, 3, 1, 0,
  126324. 2, 4, 6, 8, 10, 12, 14,
  126325. };
  126326. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126327. _vq_quantthresh__8c0_s_p9_1,
  126328. _vq_quantmap__8c0_s_p9_1,
  126329. 15,
  126330. 15
  126331. };
  126332. static static_codebook _8c0_s_p9_1 = {
  126333. 2, 225,
  126334. _vq_lengthlist__8c0_s_p9_1,
  126335. 1, -520986624, 1620377600, 4, 0,
  126336. _vq_quantlist__8c0_s_p9_1,
  126337. NULL,
  126338. &_vq_auxt__8c0_s_p9_1,
  126339. NULL,
  126340. 0
  126341. };
  126342. static long _vq_quantlist__8c0_s_p9_2[] = {
  126343. 10,
  126344. 9,
  126345. 11,
  126346. 8,
  126347. 12,
  126348. 7,
  126349. 13,
  126350. 6,
  126351. 14,
  126352. 5,
  126353. 15,
  126354. 4,
  126355. 16,
  126356. 3,
  126357. 17,
  126358. 2,
  126359. 18,
  126360. 1,
  126361. 19,
  126362. 0,
  126363. 20,
  126364. };
  126365. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126366. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126367. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126368. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126369. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126370. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126371. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126372. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126373. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126374. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126375. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126376. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126377. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126378. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126379. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126380. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126381. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126382. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126383. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126384. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126385. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126386. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126387. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126388. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126389. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126390. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126391. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126392. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126393. 10,11, 9,11,10, 9,10, 9,10,
  126394. };
  126395. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126396. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126397. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126398. 6.5, 7.5, 8.5, 9.5,
  126399. };
  126400. static long _vq_quantmap__8c0_s_p9_2[] = {
  126401. 19, 17, 15, 13, 11, 9, 7, 5,
  126402. 3, 1, 0, 2, 4, 6, 8, 10,
  126403. 12, 14, 16, 18, 20,
  126404. };
  126405. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126406. _vq_quantthresh__8c0_s_p9_2,
  126407. _vq_quantmap__8c0_s_p9_2,
  126408. 21,
  126409. 21
  126410. };
  126411. static static_codebook _8c0_s_p9_2 = {
  126412. 2, 441,
  126413. _vq_lengthlist__8c0_s_p9_2,
  126414. 1, -529268736, 1611661312, 5, 0,
  126415. _vq_quantlist__8c0_s_p9_2,
  126416. NULL,
  126417. &_vq_auxt__8c0_s_p9_2,
  126418. NULL,
  126419. 0
  126420. };
  126421. static long _huff_lengthlist__8c0_s_single[] = {
  126422. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126423. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126424. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126425. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126426. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126427. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126428. 17,16,17,17,
  126429. };
  126430. static static_codebook _huff_book__8c0_s_single = {
  126431. 2, 100,
  126432. _huff_lengthlist__8c0_s_single,
  126433. 0, 0, 0, 0, 0,
  126434. NULL,
  126435. NULL,
  126436. NULL,
  126437. NULL,
  126438. 0
  126439. };
  126440. static long _vq_quantlist__8c1_s_p1_0[] = {
  126441. 1,
  126442. 0,
  126443. 2,
  126444. };
  126445. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126446. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126447. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126451. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126452. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126456. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126457. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  126492. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126497. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126502. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126537. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126538. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126542. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126543. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  126544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126547. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126548. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  126549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126554. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126559. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126564. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  126599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  126604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  126609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126645. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126650. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  126857. };
  126858. static float _vq_quantthresh__8c1_s_p1_0[] = {
  126859. -0.5, 0.5,
  126860. };
  126861. static long _vq_quantmap__8c1_s_p1_0[] = {
  126862. 1, 0, 2,
  126863. };
  126864. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  126865. _vq_quantthresh__8c1_s_p1_0,
  126866. _vq_quantmap__8c1_s_p1_0,
  126867. 3,
  126868. 3
  126869. };
  126870. static static_codebook _8c1_s_p1_0 = {
  126871. 8, 6561,
  126872. _vq_lengthlist__8c1_s_p1_0,
  126873. 1, -535822336, 1611661312, 2, 0,
  126874. _vq_quantlist__8c1_s_p1_0,
  126875. NULL,
  126876. &_vq_auxt__8c1_s_p1_0,
  126877. NULL,
  126878. 0
  126879. };
  126880. static long _vq_quantlist__8c1_s_p2_0[] = {
  126881. 2,
  126882. 1,
  126883. 3,
  126884. 0,
  126885. 4,
  126886. };
  126887. static long _vq_lengthlist__8c1_s_p2_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,
  126928. };
  126929. static float _vq_quantthresh__8c1_s_p2_0[] = {
  126930. -1.5, -0.5, 0.5, 1.5,
  126931. };
  126932. static long _vq_quantmap__8c1_s_p2_0[] = {
  126933. 3, 1, 0, 2, 4,
  126934. };
  126935. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  126936. _vq_quantthresh__8c1_s_p2_0,
  126937. _vq_quantmap__8c1_s_p2_0,
  126938. 5,
  126939. 5
  126940. };
  126941. static static_codebook _8c1_s_p2_0 = {
  126942. 4, 625,
  126943. _vq_lengthlist__8c1_s_p2_0,
  126944. 1, -533725184, 1611661312, 3, 0,
  126945. _vq_quantlist__8c1_s_p2_0,
  126946. NULL,
  126947. &_vq_auxt__8c1_s_p2_0,
  126948. NULL,
  126949. 0
  126950. };
  126951. static long _vq_quantlist__8c1_s_p3_0[] = {
  126952. 2,
  126953. 1,
  126954. 3,
  126955. 0,
  126956. 4,
  126957. };
  126958. static long _vq_lengthlist__8c1_s_p3_0[] = {
  126959. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  126961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126962. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  126964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126965. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126998. 0,
  126999. };
  127000. static float _vq_quantthresh__8c1_s_p3_0[] = {
  127001. -1.5, -0.5, 0.5, 1.5,
  127002. };
  127003. static long _vq_quantmap__8c1_s_p3_0[] = {
  127004. 3, 1, 0, 2, 4,
  127005. };
  127006. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127007. _vq_quantthresh__8c1_s_p3_0,
  127008. _vq_quantmap__8c1_s_p3_0,
  127009. 5,
  127010. 5
  127011. };
  127012. static static_codebook _8c1_s_p3_0 = {
  127013. 4, 625,
  127014. _vq_lengthlist__8c1_s_p3_0,
  127015. 1, -533725184, 1611661312, 3, 0,
  127016. _vq_quantlist__8c1_s_p3_0,
  127017. NULL,
  127018. &_vq_auxt__8c1_s_p3_0,
  127019. NULL,
  127020. 0
  127021. };
  127022. static long _vq_quantlist__8c1_s_p4_0[] = {
  127023. 4,
  127024. 3,
  127025. 5,
  127026. 2,
  127027. 6,
  127028. 1,
  127029. 7,
  127030. 0,
  127031. 8,
  127032. };
  127033. static long _vq_lengthlist__8c1_s_p4_0[] = {
  127034. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127035. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127036. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127037. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127038. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127039. 0,
  127040. };
  127041. static float _vq_quantthresh__8c1_s_p4_0[] = {
  127042. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127043. };
  127044. static long _vq_quantmap__8c1_s_p4_0[] = {
  127045. 7, 5, 3, 1, 0, 2, 4, 6,
  127046. 8,
  127047. };
  127048. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127049. _vq_quantthresh__8c1_s_p4_0,
  127050. _vq_quantmap__8c1_s_p4_0,
  127051. 9,
  127052. 9
  127053. };
  127054. static static_codebook _8c1_s_p4_0 = {
  127055. 2, 81,
  127056. _vq_lengthlist__8c1_s_p4_0,
  127057. 1, -531628032, 1611661312, 4, 0,
  127058. _vq_quantlist__8c1_s_p4_0,
  127059. NULL,
  127060. &_vq_auxt__8c1_s_p4_0,
  127061. NULL,
  127062. 0
  127063. };
  127064. static long _vq_quantlist__8c1_s_p5_0[] = {
  127065. 4,
  127066. 3,
  127067. 5,
  127068. 2,
  127069. 6,
  127070. 1,
  127071. 7,
  127072. 0,
  127073. 8,
  127074. };
  127075. static long _vq_lengthlist__8c1_s_p5_0[] = {
  127076. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127077. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127078. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127079. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127080. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127081. 10,
  127082. };
  127083. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127084. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127085. };
  127086. static long _vq_quantmap__8c1_s_p5_0[] = {
  127087. 7, 5, 3, 1, 0, 2, 4, 6,
  127088. 8,
  127089. };
  127090. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127091. _vq_quantthresh__8c1_s_p5_0,
  127092. _vq_quantmap__8c1_s_p5_0,
  127093. 9,
  127094. 9
  127095. };
  127096. static static_codebook _8c1_s_p5_0 = {
  127097. 2, 81,
  127098. _vq_lengthlist__8c1_s_p5_0,
  127099. 1, -531628032, 1611661312, 4, 0,
  127100. _vq_quantlist__8c1_s_p5_0,
  127101. NULL,
  127102. &_vq_auxt__8c1_s_p5_0,
  127103. NULL,
  127104. 0
  127105. };
  127106. static long _vq_quantlist__8c1_s_p6_0[] = {
  127107. 8,
  127108. 7,
  127109. 9,
  127110. 6,
  127111. 10,
  127112. 5,
  127113. 11,
  127114. 4,
  127115. 12,
  127116. 3,
  127117. 13,
  127118. 2,
  127119. 14,
  127120. 1,
  127121. 15,
  127122. 0,
  127123. 16,
  127124. };
  127125. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127126. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127127. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127128. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127129. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127130. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127131. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127132. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127133. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127134. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127135. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127136. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127137. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127138. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127139. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127140. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127141. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127142. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127143. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127144. 14,
  127145. };
  127146. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127147. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127148. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127149. };
  127150. static long _vq_quantmap__8c1_s_p6_0[] = {
  127151. 15, 13, 11, 9, 7, 5, 3, 1,
  127152. 0, 2, 4, 6, 8, 10, 12, 14,
  127153. 16,
  127154. };
  127155. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127156. _vq_quantthresh__8c1_s_p6_0,
  127157. _vq_quantmap__8c1_s_p6_0,
  127158. 17,
  127159. 17
  127160. };
  127161. static static_codebook _8c1_s_p6_0 = {
  127162. 2, 289,
  127163. _vq_lengthlist__8c1_s_p6_0,
  127164. 1, -529530880, 1611661312, 5, 0,
  127165. _vq_quantlist__8c1_s_p6_0,
  127166. NULL,
  127167. &_vq_auxt__8c1_s_p6_0,
  127168. NULL,
  127169. 0
  127170. };
  127171. static long _vq_quantlist__8c1_s_p7_0[] = {
  127172. 1,
  127173. 0,
  127174. 2,
  127175. };
  127176. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127177. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127178. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127179. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127180. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127181. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127182. 9,
  127183. };
  127184. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127185. -5.5, 5.5,
  127186. };
  127187. static long _vq_quantmap__8c1_s_p7_0[] = {
  127188. 1, 0, 2,
  127189. };
  127190. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127191. _vq_quantthresh__8c1_s_p7_0,
  127192. _vq_quantmap__8c1_s_p7_0,
  127193. 3,
  127194. 3
  127195. };
  127196. static static_codebook _8c1_s_p7_0 = {
  127197. 4, 81,
  127198. _vq_lengthlist__8c1_s_p7_0,
  127199. 1, -529137664, 1618345984, 2, 0,
  127200. _vq_quantlist__8c1_s_p7_0,
  127201. NULL,
  127202. &_vq_auxt__8c1_s_p7_0,
  127203. NULL,
  127204. 0
  127205. };
  127206. static long _vq_quantlist__8c1_s_p7_1[] = {
  127207. 5,
  127208. 4,
  127209. 6,
  127210. 3,
  127211. 7,
  127212. 2,
  127213. 8,
  127214. 1,
  127215. 9,
  127216. 0,
  127217. 10,
  127218. };
  127219. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127220. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127221. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127222. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127223. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127224. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127225. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127226. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127227. 10,10,10, 8, 8, 8, 8, 8, 8,
  127228. };
  127229. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127230. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127231. 3.5, 4.5,
  127232. };
  127233. static long _vq_quantmap__8c1_s_p7_1[] = {
  127234. 9, 7, 5, 3, 1, 0, 2, 4,
  127235. 6, 8, 10,
  127236. };
  127237. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127238. _vq_quantthresh__8c1_s_p7_1,
  127239. _vq_quantmap__8c1_s_p7_1,
  127240. 11,
  127241. 11
  127242. };
  127243. static static_codebook _8c1_s_p7_1 = {
  127244. 2, 121,
  127245. _vq_lengthlist__8c1_s_p7_1,
  127246. 1, -531365888, 1611661312, 4, 0,
  127247. _vq_quantlist__8c1_s_p7_1,
  127248. NULL,
  127249. &_vq_auxt__8c1_s_p7_1,
  127250. NULL,
  127251. 0
  127252. };
  127253. static long _vq_quantlist__8c1_s_p8_0[] = {
  127254. 6,
  127255. 5,
  127256. 7,
  127257. 4,
  127258. 8,
  127259. 3,
  127260. 9,
  127261. 2,
  127262. 10,
  127263. 1,
  127264. 11,
  127265. 0,
  127266. 12,
  127267. };
  127268. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127269. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127270. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127271. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127272. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127273. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127274. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127275. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127276. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127277. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127278. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127279. 0,12,12,11,10,12,11,13,12,
  127280. };
  127281. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127282. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127283. 12.5, 17.5, 22.5, 27.5,
  127284. };
  127285. static long _vq_quantmap__8c1_s_p8_0[] = {
  127286. 11, 9, 7, 5, 3, 1, 0, 2,
  127287. 4, 6, 8, 10, 12,
  127288. };
  127289. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127290. _vq_quantthresh__8c1_s_p8_0,
  127291. _vq_quantmap__8c1_s_p8_0,
  127292. 13,
  127293. 13
  127294. };
  127295. static static_codebook _8c1_s_p8_0 = {
  127296. 2, 169,
  127297. _vq_lengthlist__8c1_s_p8_0,
  127298. 1, -526516224, 1616117760, 4, 0,
  127299. _vq_quantlist__8c1_s_p8_0,
  127300. NULL,
  127301. &_vq_auxt__8c1_s_p8_0,
  127302. NULL,
  127303. 0
  127304. };
  127305. static long _vq_quantlist__8c1_s_p8_1[] = {
  127306. 2,
  127307. 1,
  127308. 3,
  127309. 0,
  127310. 4,
  127311. };
  127312. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127313. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127314. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127315. };
  127316. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127317. -1.5, -0.5, 0.5, 1.5,
  127318. };
  127319. static long _vq_quantmap__8c1_s_p8_1[] = {
  127320. 3, 1, 0, 2, 4,
  127321. };
  127322. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127323. _vq_quantthresh__8c1_s_p8_1,
  127324. _vq_quantmap__8c1_s_p8_1,
  127325. 5,
  127326. 5
  127327. };
  127328. static static_codebook _8c1_s_p8_1 = {
  127329. 2, 25,
  127330. _vq_lengthlist__8c1_s_p8_1,
  127331. 1, -533725184, 1611661312, 3, 0,
  127332. _vq_quantlist__8c1_s_p8_1,
  127333. NULL,
  127334. &_vq_auxt__8c1_s_p8_1,
  127335. NULL,
  127336. 0
  127337. };
  127338. static long _vq_quantlist__8c1_s_p9_0[] = {
  127339. 6,
  127340. 5,
  127341. 7,
  127342. 4,
  127343. 8,
  127344. 3,
  127345. 9,
  127346. 2,
  127347. 10,
  127348. 1,
  127349. 11,
  127350. 0,
  127351. 12,
  127352. };
  127353. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127354. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127355. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127356. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127357. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127358. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127359. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127360. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127361. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127362. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127363. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127364. 10,10,10,10,10, 9, 9, 9, 9,
  127365. };
  127366. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127367. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127368. 787.5, 1102.5, 1417.5, 1732.5,
  127369. };
  127370. static long _vq_quantmap__8c1_s_p9_0[] = {
  127371. 11, 9, 7, 5, 3, 1, 0, 2,
  127372. 4, 6, 8, 10, 12,
  127373. };
  127374. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127375. _vq_quantthresh__8c1_s_p9_0,
  127376. _vq_quantmap__8c1_s_p9_0,
  127377. 13,
  127378. 13
  127379. };
  127380. static static_codebook _8c1_s_p9_0 = {
  127381. 2, 169,
  127382. _vq_lengthlist__8c1_s_p9_0,
  127383. 1, -513964032, 1628680192, 4, 0,
  127384. _vq_quantlist__8c1_s_p9_0,
  127385. NULL,
  127386. &_vq_auxt__8c1_s_p9_0,
  127387. NULL,
  127388. 0
  127389. };
  127390. static long _vq_quantlist__8c1_s_p9_1[] = {
  127391. 7,
  127392. 6,
  127393. 8,
  127394. 5,
  127395. 9,
  127396. 4,
  127397. 10,
  127398. 3,
  127399. 11,
  127400. 2,
  127401. 12,
  127402. 1,
  127403. 13,
  127404. 0,
  127405. 14,
  127406. };
  127407. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127408. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127409. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127410. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127411. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127412. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127413. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127414. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127415. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127416. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127417. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127418. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127419. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127420. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127421. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127422. 15,
  127423. };
  127424. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127425. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127426. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127427. };
  127428. static long _vq_quantmap__8c1_s_p9_1[] = {
  127429. 13, 11, 9, 7, 5, 3, 1, 0,
  127430. 2, 4, 6, 8, 10, 12, 14,
  127431. };
  127432. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127433. _vq_quantthresh__8c1_s_p9_1,
  127434. _vq_quantmap__8c1_s_p9_1,
  127435. 15,
  127436. 15
  127437. };
  127438. static static_codebook _8c1_s_p9_1 = {
  127439. 2, 225,
  127440. _vq_lengthlist__8c1_s_p9_1,
  127441. 1, -520986624, 1620377600, 4, 0,
  127442. _vq_quantlist__8c1_s_p9_1,
  127443. NULL,
  127444. &_vq_auxt__8c1_s_p9_1,
  127445. NULL,
  127446. 0
  127447. };
  127448. static long _vq_quantlist__8c1_s_p9_2[] = {
  127449. 10,
  127450. 9,
  127451. 11,
  127452. 8,
  127453. 12,
  127454. 7,
  127455. 13,
  127456. 6,
  127457. 14,
  127458. 5,
  127459. 15,
  127460. 4,
  127461. 16,
  127462. 3,
  127463. 17,
  127464. 2,
  127465. 18,
  127466. 1,
  127467. 19,
  127468. 0,
  127469. 20,
  127470. };
  127471. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127472. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127473. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127474. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127475. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127476. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127477. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127478. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127479. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127480. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127481. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127482. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127483. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127484. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127485. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127486. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127487. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127488. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127489. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127490. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127491. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127492. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127493. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  127494. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  127495. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127496. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  127497. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  127498. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  127499. 10,10,10,10,10,10,10,10,10,
  127500. };
  127501. static float _vq_quantthresh__8c1_s_p9_2[] = {
  127502. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127503. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127504. 6.5, 7.5, 8.5, 9.5,
  127505. };
  127506. static long _vq_quantmap__8c1_s_p9_2[] = {
  127507. 19, 17, 15, 13, 11, 9, 7, 5,
  127508. 3, 1, 0, 2, 4, 6, 8, 10,
  127509. 12, 14, 16, 18, 20,
  127510. };
  127511. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  127512. _vq_quantthresh__8c1_s_p9_2,
  127513. _vq_quantmap__8c1_s_p9_2,
  127514. 21,
  127515. 21
  127516. };
  127517. static static_codebook _8c1_s_p9_2 = {
  127518. 2, 441,
  127519. _vq_lengthlist__8c1_s_p9_2,
  127520. 1, -529268736, 1611661312, 5, 0,
  127521. _vq_quantlist__8c1_s_p9_2,
  127522. NULL,
  127523. &_vq_auxt__8c1_s_p9_2,
  127524. NULL,
  127525. 0
  127526. };
  127527. static long _huff_lengthlist__8c1_s_single[] = {
  127528. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  127529. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  127530. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  127531. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  127532. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  127533. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  127534. 9, 7, 7, 8,
  127535. };
  127536. static static_codebook _huff_book__8c1_s_single = {
  127537. 2, 100,
  127538. _huff_lengthlist__8c1_s_single,
  127539. 0, 0, 0, 0, 0,
  127540. NULL,
  127541. NULL,
  127542. NULL,
  127543. NULL,
  127544. 0
  127545. };
  127546. static long _huff_lengthlist__44c2_s_long[] = {
  127547. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  127548. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  127549. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  127550. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  127551. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  127552. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  127553. 10, 8, 8, 9,
  127554. };
  127555. static static_codebook _huff_book__44c2_s_long = {
  127556. 2, 100,
  127557. _huff_lengthlist__44c2_s_long,
  127558. 0, 0, 0, 0, 0,
  127559. NULL,
  127560. NULL,
  127561. NULL,
  127562. NULL,
  127563. 0
  127564. };
  127565. static long _vq_quantlist__44c2_s_p1_0[] = {
  127566. 1,
  127567. 0,
  127568. 2,
  127569. };
  127570. static long _vq_lengthlist__44c2_s_p1_0[] = {
  127571. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127572. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127576. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127577. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127581. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127582. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  127617. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127622. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  127627. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127662. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127663. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127667. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127668. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  127669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127672. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127673. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127679. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127684. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127689. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  127724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  127729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  127734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127770. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127775. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  127982. };
  127983. static float _vq_quantthresh__44c2_s_p1_0[] = {
  127984. -0.5, 0.5,
  127985. };
  127986. static long _vq_quantmap__44c2_s_p1_0[] = {
  127987. 1, 0, 2,
  127988. };
  127989. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  127990. _vq_quantthresh__44c2_s_p1_0,
  127991. _vq_quantmap__44c2_s_p1_0,
  127992. 3,
  127993. 3
  127994. };
  127995. static static_codebook _44c2_s_p1_0 = {
  127996. 8, 6561,
  127997. _vq_lengthlist__44c2_s_p1_0,
  127998. 1, -535822336, 1611661312, 2, 0,
  127999. _vq_quantlist__44c2_s_p1_0,
  128000. NULL,
  128001. &_vq_auxt__44c2_s_p1_0,
  128002. NULL,
  128003. 0
  128004. };
  128005. static long _vq_quantlist__44c2_s_p2_0[] = {
  128006. 2,
  128007. 1,
  128008. 3,
  128009. 0,
  128010. 4,
  128011. };
  128012. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128013. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128014. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128015. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  128016. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  128017. 0, 0, 9, 9, 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, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128023. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128024. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128025. 12, 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, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128031. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128032. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 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. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128039. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128040. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 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,
  128053. };
  128054. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128055. -1.5, -0.5, 0.5, 1.5,
  128056. };
  128057. static long _vq_quantmap__44c2_s_p2_0[] = {
  128058. 3, 1, 0, 2, 4,
  128059. };
  128060. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128061. _vq_quantthresh__44c2_s_p2_0,
  128062. _vq_quantmap__44c2_s_p2_0,
  128063. 5,
  128064. 5
  128065. };
  128066. static static_codebook _44c2_s_p2_0 = {
  128067. 4, 625,
  128068. _vq_lengthlist__44c2_s_p2_0,
  128069. 1, -533725184, 1611661312, 3, 0,
  128070. _vq_quantlist__44c2_s_p2_0,
  128071. NULL,
  128072. &_vq_auxt__44c2_s_p2_0,
  128073. NULL,
  128074. 0
  128075. };
  128076. static long _vq_quantlist__44c2_s_p3_0[] = {
  128077. 2,
  128078. 1,
  128079. 3,
  128080. 0,
  128081. 4,
  128082. };
  128083. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128084. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128087. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128090. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128123. 0,
  128124. };
  128125. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128126. -1.5, -0.5, 0.5, 1.5,
  128127. };
  128128. static long _vq_quantmap__44c2_s_p3_0[] = {
  128129. 3, 1, 0, 2, 4,
  128130. };
  128131. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128132. _vq_quantthresh__44c2_s_p3_0,
  128133. _vq_quantmap__44c2_s_p3_0,
  128134. 5,
  128135. 5
  128136. };
  128137. static static_codebook _44c2_s_p3_0 = {
  128138. 4, 625,
  128139. _vq_lengthlist__44c2_s_p3_0,
  128140. 1, -533725184, 1611661312, 3, 0,
  128141. _vq_quantlist__44c2_s_p3_0,
  128142. NULL,
  128143. &_vq_auxt__44c2_s_p3_0,
  128144. NULL,
  128145. 0
  128146. };
  128147. static long _vq_quantlist__44c2_s_p4_0[] = {
  128148. 4,
  128149. 3,
  128150. 5,
  128151. 2,
  128152. 6,
  128153. 1,
  128154. 7,
  128155. 0,
  128156. 8,
  128157. };
  128158. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128159. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128160. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128161. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128162. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128163. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128164. 0,
  128165. };
  128166. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128167. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128168. };
  128169. static long _vq_quantmap__44c2_s_p4_0[] = {
  128170. 7, 5, 3, 1, 0, 2, 4, 6,
  128171. 8,
  128172. };
  128173. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128174. _vq_quantthresh__44c2_s_p4_0,
  128175. _vq_quantmap__44c2_s_p4_0,
  128176. 9,
  128177. 9
  128178. };
  128179. static static_codebook _44c2_s_p4_0 = {
  128180. 2, 81,
  128181. _vq_lengthlist__44c2_s_p4_0,
  128182. 1, -531628032, 1611661312, 4, 0,
  128183. _vq_quantlist__44c2_s_p4_0,
  128184. NULL,
  128185. &_vq_auxt__44c2_s_p4_0,
  128186. NULL,
  128187. 0
  128188. };
  128189. static long _vq_quantlist__44c2_s_p5_0[] = {
  128190. 4,
  128191. 3,
  128192. 5,
  128193. 2,
  128194. 6,
  128195. 1,
  128196. 7,
  128197. 0,
  128198. 8,
  128199. };
  128200. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128201. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128202. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128203. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128204. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128205. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128206. 11,
  128207. };
  128208. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128209. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128210. };
  128211. static long _vq_quantmap__44c2_s_p5_0[] = {
  128212. 7, 5, 3, 1, 0, 2, 4, 6,
  128213. 8,
  128214. };
  128215. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128216. _vq_quantthresh__44c2_s_p5_0,
  128217. _vq_quantmap__44c2_s_p5_0,
  128218. 9,
  128219. 9
  128220. };
  128221. static static_codebook _44c2_s_p5_0 = {
  128222. 2, 81,
  128223. _vq_lengthlist__44c2_s_p5_0,
  128224. 1, -531628032, 1611661312, 4, 0,
  128225. _vq_quantlist__44c2_s_p5_0,
  128226. NULL,
  128227. &_vq_auxt__44c2_s_p5_0,
  128228. NULL,
  128229. 0
  128230. };
  128231. static long _vq_quantlist__44c2_s_p6_0[] = {
  128232. 8,
  128233. 7,
  128234. 9,
  128235. 6,
  128236. 10,
  128237. 5,
  128238. 11,
  128239. 4,
  128240. 12,
  128241. 3,
  128242. 13,
  128243. 2,
  128244. 14,
  128245. 1,
  128246. 15,
  128247. 0,
  128248. 16,
  128249. };
  128250. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128251. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128252. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128253. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128254. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128255. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128256. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128257. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128258. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128259. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128260. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128261. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128262. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128263. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128264. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128265. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128266. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128267. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128268. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128269. 14,
  128270. };
  128271. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128272. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128273. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128274. };
  128275. static long _vq_quantmap__44c2_s_p6_0[] = {
  128276. 15, 13, 11, 9, 7, 5, 3, 1,
  128277. 0, 2, 4, 6, 8, 10, 12, 14,
  128278. 16,
  128279. };
  128280. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128281. _vq_quantthresh__44c2_s_p6_0,
  128282. _vq_quantmap__44c2_s_p6_0,
  128283. 17,
  128284. 17
  128285. };
  128286. static static_codebook _44c2_s_p6_0 = {
  128287. 2, 289,
  128288. _vq_lengthlist__44c2_s_p6_0,
  128289. 1, -529530880, 1611661312, 5, 0,
  128290. _vq_quantlist__44c2_s_p6_0,
  128291. NULL,
  128292. &_vq_auxt__44c2_s_p6_0,
  128293. NULL,
  128294. 0
  128295. };
  128296. static long _vq_quantlist__44c2_s_p7_0[] = {
  128297. 1,
  128298. 0,
  128299. 2,
  128300. };
  128301. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128302. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128303. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128304. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128305. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128306. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128307. 11,
  128308. };
  128309. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128310. -5.5, 5.5,
  128311. };
  128312. static long _vq_quantmap__44c2_s_p7_0[] = {
  128313. 1, 0, 2,
  128314. };
  128315. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128316. _vq_quantthresh__44c2_s_p7_0,
  128317. _vq_quantmap__44c2_s_p7_0,
  128318. 3,
  128319. 3
  128320. };
  128321. static static_codebook _44c2_s_p7_0 = {
  128322. 4, 81,
  128323. _vq_lengthlist__44c2_s_p7_0,
  128324. 1, -529137664, 1618345984, 2, 0,
  128325. _vq_quantlist__44c2_s_p7_0,
  128326. NULL,
  128327. &_vq_auxt__44c2_s_p7_0,
  128328. NULL,
  128329. 0
  128330. };
  128331. static long _vq_quantlist__44c2_s_p7_1[] = {
  128332. 5,
  128333. 4,
  128334. 6,
  128335. 3,
  128336. 7,
  128337. 2,
  128338. 8,
  128339. 1,
  128340. 9,
  128341. 0,
  128342. 10,
  128343. };
  128344. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128345. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128346. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128347. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128348. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128349. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128350. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128351. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128352. 10,10,10, 8, 8, 8, 8, 8, 8,
  128353. };
  128354. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128355. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128356. 3.5, 4.5,
  128357. };
  128358. static long _vq_quantmap__44c2_s_p7_1[] = {
  128359. 9, 7, 5, 3, 1, 0, 2, 4,
  128360. 6, 8, 10,
  128361. };
  128362. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128363. _vq_quantthresh__44c2_s_p7_1,
  128364. _vq_quantmap__44c2_s_p7_1,
  128365. 11,
  128366. 11
  128367. };
  128368. static static_codebook _44c2_s_p7_1 = {
  128369. 2, 121,
  128370. _vq_lengthlist__44c2_s_p7_1,
  128371. 1, -531365888, 1611661312, 4, 0,
  128372. _vq_quantlist__44c2_s_p7_1,
  128373. NULL,
  128374. &_vq_auxt__44c2_s_p7_1,
  128375. NULL,
  128376. 0
  128377. };
  128378. static long _vq_quantlist__44c2_s_p8_0[] = {
  128379. 6,
  128380. 5,
  128381. 7,
  128382. 4,
  128383. 8,
  128384. 3,
  128385. 9,
  128386. 2,
  128387. 10,
  128388. 1,
  128389. 11,
  128390. 0,
  128391. 12,
  128392. };
  128393. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128394. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128395. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128396. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128397. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128398. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128399. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128400. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128401. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128402. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128403. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128404. 0,12,12,12,12,13,12,14,14,
  128405. };
  128406. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128407. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128408. 12.5, 17.5, 22.5, 27.5,
  128409. };
  128410. static long _vq_quantmap__44c2_s_p8_0[] = {
  128411. 11, 9, 7, 5, 3, 1, 0, 2,
  128412. 4, 6, 8, 10, 12,
  128413. };
  128414. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128415. _vq_quantthresh__44c2_s_p8_0,
  128416. _vq_quantmap__44c2_s_p8_0,
  128417. 13,
  128418. 13
  128419. };
  128420. static static_codebook _44c2_s_p8_0 = {
  128421. 2, 169,
  128422. _vq_lengthlist__44c2_s_p8_0,
  128423. 1, -526516224, 1616117760, 4, 0,
  128424. _vq_quantlist__44c2_s_p8_0,
  128425. NULL,
  128426. &_vq_auxt__44c2_s_p8_0,
  128427. NULL,
  128428. 0
  128429. };
  128430. static long _vq_quantlist__44c2_s_p8_1[] = {
  128431. 2,
  128432. 1,
  128433. 3,
  128434. 0,
  128435. 4,
  128436. };
  128437. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128438. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128439. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128440. };
  128441. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128442. -1.5, -0.5, 0.5, 1.5,
  128443. };
  128444. static long _vq_quantmap__44c2_s_p8_1[] = {
  128445. 3, 1, 0, 2, 4,
  128446. };
  128447. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128448. _vq_quantthresh__44c2_s_p8_1,
  128449. _vq_quantmap__44c2_s_p8_1,
  128450. 5,
  128451. 5
  128452. };
  128453. static static_codebook _44c2_s_p8_1 = {
  128454. 2, 25,
  128455. _vq_lengthlist__44c2_s_p8_1,
  128456. 1, -533725184, 1611661312, 3, 0,
  128457. _vq_quantlist__44c2_s_p8_1,
  128458. NULL,
  128459. &_vq_auxt__44c2_s_p8_1,
  128460. NULL,
  128461. 0
  128462. };
  128463. static long _vq_quantlist__44c2_s_p9_0[] = {
  128464. 6,
  128465. 5,
  128466. 7,
  128467. 4,
  128468. 8,
  128469. 3,
  128470. 9,
  128471. 2,
  128472. 10,
  128473. 1,
  128474. 11,
  128475. 0,
  128476. 12,
  128477. };
  128478. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128479. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128480. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128481. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128482. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128483. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128484. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128485. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128486. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128487. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128488. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128489. 11,11,11,11,11,11,11,11,11,
  128490. };
  128491. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128492. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  128493. 552.5, 773.5, 994.5, 1215.5,
  128494. };
  128495. static long _vq_quantmap__44c2_s_p9_0[] = {
  128496. 11, 9, 7, 5, 3, 1, 0, 2,
  128497. 4, 6, 8, 10, 12,
  128498. };
  128499. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  128500. _vq_quantthresh__44c2_s_p9_0,
  128501. _vq_quantmap__44c2_s_p9_0,
  128502. 13,
  128503. 13
  128504. };
  128505. static static_codebook _44c2_s_p9_0 = {
  128506. 2, 169,
  128507. _vq_lengthlist__44c2_s_p9_0,
  128508. 1, -514541568, 1627103232, 4, 0,
  128509. _vq_quantlist__44c2_s_p9_0,
  128510. NULL,
  128511. &_vq_auxt__44c2_s_p9_0,
  128512. NULL,
  128513. 0
  128514. };
  128515. static long _vq_quantlist__44c2_s_p9_1[] = {
  128516. 6,
  128517. 5,
  128518. 7,
  128519. 4,
  128520. 8,
  128521. 3,
  128522. 9,
  128523. 2,
  128524. 10,
  128525. 1,
  128526. 11,
  128527. 0,
  128528. 12,
  128529. };
  128530. static long _vq_lengthlist__44c2_s_p9_1[] = {
  128531. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  128532. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  128533. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  128534. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  128535. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  128536. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  128537. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  128538. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  128539. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  128540. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  128541. 17,13,12,12,10,13,11,14,14,
  128542. };
  128543. static float _vq_quantthresh__44c2_s_p9_1[] = {
  128544. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  128545. 42.5, 59.5, 76.5, 93.5,
  128546. };
  128547. static long _vq_quantmap__44c2_s_p9_1[] = {
  128548. 11, 9, 7, 5, 3, 1, 0, 2,
  128549. 4, 6, 8, 10, 12,
  128550. };
  128551. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  128552. _vq_quantthresh__44c2_s_p9_1,
  128553. _vq_quantmap__44c2_s_p9_1,
  128554. 13,
  128555. 13
  128556. };
  128557. static static_codebook _44c2_s_p9_1 = {
  128558. 2, 169,
  128559. _vq_lengthlist__44c2_s_p9_1,
  128560. 1, -522616832, 1620115456, 4, 0,
  128561. _vq_quantlist__44c2_s_p9_1,
  128562. NULL,
  128563. &_vq_auxt__44c2_s_p9_1,
  128564. NULL,
  128565. 0
  128566. };
  128567. static long _vq_quantlist__44c2_s_p9_2[] = {
  128568. 8,
  128569. 7,
  128570. 9,
  128571. 6,
  128572. 10,
  128573. 5,
  128574. 11,
  128575. 4,
  128576. 12,
  128577. 3,
  128578. 13,
  128579. 2,
  128580. 14,
  128581. 1,
  128582. 15,
  128583. 0,
  128584. 16,
  128585. };
  128586. static long _vq_lengthlist__44c2_s_p9_2[] = {
  128587. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128588. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128589. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  128590. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  128591. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  128592. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128593. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  128594. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  128595. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  128596. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  128597. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  128598. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  128599. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  128600. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  128601. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  128602. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128603. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  128604. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  128605. 10,
  128606. };
  128607. static float _vq_quantthresh__44c2_s_p9_2[] = {
  128608. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128609. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128610. };
  128611. static long _vq_quantmap__44c2_s_p9_2[] = {
  128612. 15, 13, 11, 9, 7, 5, 3, 1,
  128613. 0, 2, 4, 6, 8, 10, 12, 14,
  128614. 16,
  128615. };
  128616. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  128617. _vq_quantthresh__44c2_s_p9_2,
  128618. _vq_quantmap__44c2_s_p9_2,
  128619. 17,
  128620. 17
  128621. };
  128622. static static_codebook _44c2_s_p9_2 = {
  128623. 2, 289,
  128624. _vq_lengthlist__44c2_s_p9_2,
  128625. 1, -529530880, 1611661312, 5, 0,
  128626. _vq_quantlist__44c2_s_p9_2,
  128627. NULL,
  128628. &_vq_auxt__44c2_s_p9_2,
  128629. NULL,
  128630. 0
  128631. };
  128632. static long _huff_lengthlist__44c2_s_short[] = {
  128633. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  128634. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  128635. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  128636. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  128637. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  128638. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  128639. 6, 8, 9,12,
  128640. };
  128641. static static_codebook _huff_book__44c2_s_short = {
  128642. 2, 100,
  128643. _huff_lengthlist__44c2_s_short,
  128644. 0, 0, 0, 0, 0,
  128645. NULL,
  128646. NULL,
  128647. NULL,
  128648. NULL,
  128649. 0
  128650. };
  128651. static long _huff_lengthlist__44c3_s_long[] = {
  128652. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  128653. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  128654. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  128655. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  128656. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  128657. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  128658. 9, 8, 8, 8,
  128659. };
  128660. static static_codebook _huff_book__44c3_s_long = {
  128661. 2, 100,
  128662. _huff_lengthlist__44c3_s_long,
  128663. 0, 0, 0, 0, 0,
  128664. NULL,
  128665. NULL,
  128666. NULL,
  128667. NULL,
  128668. 0
  128669. };
  128670. static long _vq_quantlist__44c3_s_p1_0[] = {
  128671. 1,
  128672. 0,
  128673. 2,
  128674. };
  128675. static long _vq_lengthlist__44c3_s_p1_0[] = {
  128676. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128677. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128681. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128682. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128686. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128687. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  128722. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128727. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  128732. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128767. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128768. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128772. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128773. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  128774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128777. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128778. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  128779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128784. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128789. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128794. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  128829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  128834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  128839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128875. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128880. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  129087. };
  129088. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129089. -0.5, 0.5,
  129090. };
  129091. static long _vq_quantmap__44c3_s_p1_0[] = {
  129092. 1, 0, 2,
  129093. };
  129094. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129095. _vq_quantthresh__44c3_s_p1_0,
  129096. _vq_quantmap__44c3_s_p1_0,
  129097. 3,
  129098. 3
  129099. };
  129100. static static_codebook _44c3_s_p1_0 = {
  129101. 8, 6561,
  129102. _vq_lengthlist__44c3_s_p1_0,
  129103. 1, -535822336, 1611661312, 2, 0,
  129104. _vq_quantlist__44c3_s_p1_0,
  129105. NULL,
  129106. &_vq_auxt__44c3_s_p1_0,
  129107. NULL,
  129108. 0
  129109. };
  129110. static long _vq_quantlist__44c3_s_p2_0[] = {
  129111. 2,
  129112. 1,
  129113. 3,
  129114. 0,
  129115. 4,
  129116. };
  129117. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129118. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129119. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129120. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129121. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129122. 0, 0,10,10, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129128. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129129. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129130. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129136. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129137. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129144. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129145. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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,
  129158. };
  129159. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129160. -1.5, -0.5, 0.5, 1.5,
  129161. };
  129162. static long _vq_quantmap__44c3_s_p2_0[] = {
  129163. 3, 1, 0, 2, 4,
  129164. };
  129165. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129166. _vq_quantthresh__44c3_s_p2_0,
  129167. _vq_quantmap__44c3_s_p2_0,
  129168. 5,
  129169. 5
  129170. };
  129171. static static_codebook _44c3_s_p2_0 = {
  129172. 4, 625,
  129173. _vq_lengthlist__44c3_s_p2_0,
  129174. 1, -533725184, 1611661312, 3, 0,
  129175. _vq_quantlist__44c3_s_p2_0,
  129176. NULL,
  129177. &_vq_auxt__44c3_s_p2_0,
  129178. NULL,
  129179. 0
  129180. };
  129181. static long _vq_quantlist__44c3_s_p3_0[] = {
  129182. 2,
  129183. 1,
  129184. 3,
  129185. 0,
  129186. 4,
  129187. };
  129188. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129189. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129192. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129195. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129228. 0,
  129229. };
  129230. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129231. -1.5, -0.5, 0.5, 1.5,
  129232. };
  129233. static long _vq_quantmap__44c3_s_p3_0[] = {
  129234. 3, 1, 0, 2, 4,
  129235. };
  129236. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129237. _vq_quantthresh__44c3_s_p3_0,
  129238. _vq_quantmap__44c3_s_p3_0,
  129239. 5,
  129240. 5
  129241. };
  129242. static static_codebook _44c3_s_p3_0 = {
  129243. 4, 625,
  129244. _vq_lengthlist__44c3_s_p3_0,
  129245. 1, -533725184, 1611661312, 3, 0,
  129246. _vq_quantlist__44c3_s_p3_0,
  129247. NULL,
  129248. &_vq_auxt__44c3_s_p3_0,
  129249. NULL,
  129250. 0
  129251. };
  129252. static long _vq_quantlist__44c3_s_p4_0[] = {
  129253. 4,
  129254. 3,
  129255. 5,
  129256. 2,
  129257. 6,
  129258. 1,
  129259. 7,
  129260. 0,
  129261. 8,
  129262. };
  129263. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129264. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129265. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129266. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129267. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129268. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129269. 0,
  129270. };
  129271. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129272. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129273. };
  129274. static long _vq_quantmap__44c3_s_p4_0[] = {
  129275. 7, 5, 3, 1, 0, 2, 4, 6,
  129276. 8,
  129277. };
  129278. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129279. _vq_quantthresh__44c3_s_p4_0,
  129280. _vq_quantmap__44c3_s_p4_0,
  129281. 9,
  129282. 9
  129283. };
  129284. static static_codebook _44c3_s_p4_0 = {
  129285. 2, 81,
  129286. _vq_lengthlist__44c3_s_p4_0,
  129287. 1, -531628032, 1611661312, 4, 0,
  129288. _vq_quantlist__44c3_s_p4_0,
  129289. NULL,
  129290. &_vq_auxt__44c3_s_p4_0,
  129291. NULL,
  129292. 0
  129293. };
  129294. static long _vq_quantlist__44c3_s_p5_0[] = {
  129295. 4,
  129296. 3,
  129297. 5,
  129298. 2,
  129299. 6,
  129300. 1,
  129301. 7,
  129302. 0,
  129303. 8,
  129304. };
  129305. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129306. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129307. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129308. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129309. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129310. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129311. 11,
  129312. };
  129313. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129314. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129315. };
  129316. static long _vq_quantmap__44c3_s_p5_0[] = {
  129317. 7, 5, 3, 1, 0, 2, 4, 6,
  129318. 8,
  129319. };
  129320. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129321. _vq_quantthresh__44c3_s_p5_0,
  129322. _vq_quantmap__44c3_s_p5_0,
  129323. 9,
  129324. 9
  129325. };
  129326. static static_codebook _44c3_s_p5_0 = {
  129327. 2, 81,
  129328. _vq_lengthlist__44c3_s_p5_0,
  129329. 1, -531628032, 1611661312, 4, 0,
  129330. _vq_quantlist__44c3_s_p5_0,
  129331. NULL,
  129332. &_vq_auxt__44c3_s_p5_0,
  129333. NULL,
  129334. 0
  129335. };
  129336. static long _vq_quantlist__44c3_s_p6_0[] = {
  129337. 8,
  129338. 7,
  129339. 9,
  129340. 6,
  129341. 10,
  129342. 5,
  129343. 11,
  129344. 4,
  129345. 12,
  129346. 3,
  129347. 13,
  129348. 2,
  129349. 14,
  129350. 1,
  129351. 15,
  129352. 0,
  129353. 16,
  129354. };
  129355. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129356. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129357. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129358. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129359. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129360. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129361. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129362. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129363. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129364. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129365. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129366. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129367. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129368. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129369. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129370. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129371. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129372. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129373. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129374. 13,
  129375. };
  129376. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129377. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129378. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129379. };
  129380. static long _vq_quantmap__44c3_s_p6_0[] = {
  129381. 15, 13, 11, 9, 7, 5, 3, 1,
  129382. 0, 2, 4, 6, 8, 10, 12, 14,
  129383. 16,
  129384. };
  129385. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129386. _vq_quantthresh__44c3_s_p6_0,
  129387. _vq_quantmap__44c3_s_p6_0,
  129388. 17,
  129389. 17
  129390. };
  129391. static static_codebook _44c3_s_p6_0 = {
  129392. 2, 289,
  129393. _vq_lengthlist__44c3_s_p6_0,
  129394. 1, -529530880, 1611661312, 5, 0,
  129395. _vq_quantlist__44c3_s_p6_0,
  129396. NULL,
  129397. &_vq_auxt__44c3_s_p6_0,
  129398. NULL,
  129399. 0
  129400. };
  129401. static long _vq_quantlist__44c3_s_p7_0[] = {
  129402. 1,
  129403. 0,
  129404. 2,
  129405. };
  129406. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129407. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129408. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129409. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129410. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129411. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129412. 10,
  129413. };
  129414. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129415. -5.5, 5.5,
  129416. };
  129417. static long _vq_quantmap__44c3_s_p7_0[] = {
  129418. 1, 0, 2,
  129419. };
  129420. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129421. _vq_quantthresh__44c3_s_p7_0,
  129422. _vq_quantmap__44c3_s_p7_0,
  129423. 3,
  129424. 3
  129425. };
  129426. static static_codebook _44c3_s_p7_0 = {
  129427. 4, 81,
  129428. _vq_lengthlist__44c3_s_p7_0,
  129429. 1, -529137664, 1618345984, 2, 0,
  129430. _vq_quantlist__44c3_s_p7_0,
  129431. NULL,
  129432. &_vq_auxt__44c3_s_p7_0,
  129433. NULL,
  129434. 0
  129435. };
  129436. static long _vq_quantlist__44c3_s_p7_1[] = {
  129437. 5,
  129438. 4,
  129439. 6,
  129440. 3,
  129441. 7,
  129442. 2,
  129443. 8,
  129444. 1,
  129445. 9,
  129446. 0,
  129447. 10,
  129448. };
  129449. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129450. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129451. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129452. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129453. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129454. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129455. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129456. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129457. 10,10,10, 8, 8, 8, 8, 8, 8,
  129458. };
  129459. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129460. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129461. 3.5, 4.5,
  129462. };
  129463. static long _vq_quantmap__44c3_s_p7_1[] = {
  129464. 9, 7, 5, 3, 1, 0, 2, 4,
  129465. 6, 8, 10,
  129466. };
  129467. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129468. _vq_quantthresh__44c3_s_p7_1,
  129469. _vq_quantmap__44c3_s_p7_1,
  129470. 11,
  129471. 11
  129472. };
  129473. static static_codebook _44c3_s_p7_1 = {
  129474. 2, 121,
  129475. _vq_lengthlist__44c3_s_p7_1,
  129476. 1, -531365888, 1611661312, 4, 0,
  129477. _vq_quantlist__44c3_s_p7_1,
  129478. NULL,
  129479. &_vq_auxt__44c3_s_p7_1,
  129480. NULL,
  129481. 0
  129482. };
  129483. static long _vq_quantlist__44c3_s_p8_0[] = {
  129484. 6,
  129485. 5,
  129486. 7,
  129487. 4,
  129488. 8,
  129489. 3,
  129490. 9,
  129491. 2,
  129492. 10,
  129493. 1,
  129494. 11,
  129495. 0,
  129496. 12,
  129497. };
  129498. static long _vq_lengthlist__44c3_s_p8_0[] = {
  129499. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129500. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  129501. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129502. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129503. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  129504. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  129505. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  129506. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129507. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  129508. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  129509. 0,13,13,12,12,13,12,14,13,
  129510. };
  129511. static float _vq_quantthresh__44c3_s_p8_0[] = {
  129512. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129513. 12.5, 17.5, 22.5, 27.5,
  129514. };
  129515. static long _vq_quantmap__44c3_s_p8_0[] = {
  129516. 11, 9, 7, 5, 3, 1, 0, 2,
  129517. 4, 6, 8, 10, 12,
  129518. };
  129519. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  129520. _vq_quantthresh__44c3_s_p8_0,
  129521. _vq_quantmap__44c3_s_p8_0,
  129522. 13,
  129523. 13
  129524. };
  129525. static static_codebook _44c3_s_p8_0 = {
  129526. 2, 169,
  129527. _vq_lengthlist__44c3_s_p8_0,
  129528. 1, -526516224, 1616117760, 4, 0,
  129529. _vq_quantlist__44c3_s_p8_0,
  129530. NULL,
  129531. &_vq_auxt__44c3_s_p8_0,
  129532. NULL,
  129533. 0
  129534. };
  129535. static long _vq_quantlist__44c3_s_p8_1[] = {
  129536. 2,
  129537. 1,
  129538. 3,
  129539. 0,
  129540. 4,
  129541. };
  129542. static long _vq_lengthlist__44c3_s_p8_1[] = {
  129543. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  129544. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129545. };
  129546. static float _vq_quantthresh__44c3_s_p8_1[] = {
  129547. -1.5, -0.5, 0.5, 1.5,
  129548. };
  129549. static long _vq_quantmap__44c3_s_p8_1[] = {
  129550. 3, 1, 0, 2, 4,
  129551. };
  129552. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  129553. _vq_quantthresh__44c3_s_p8_1,
  129554. _vq_quantmap__44c3_s_p8_1,
  129555. 5,
  129556. 5
  129557. };
  129558. static static_codebook _44c3_s_p8_1 = {
  129559. 2, 25,
  129560. _vq_lengthlist__44c3_s_p8_1,
  129561. 1, -533725184, 1611661312, 3, 0,
  129562. _vq_quantlist__44c3_s_p8_1,
  129563. NULL,
  129564. &_vq_auxt__44c3_s_p8_1,
  129565. NULL,
  129566. 0
  129567. };
  129568. static long _vq_quantlist__44c3_s_p9_0[] = {
  129569. 6,
  129570. 5,
  129571. 7,
  129572. 4,
  129573. 8,
  129574. 3,
  129575. 9,
  129576. 2,
  129577. 10,
  129578. 1,
  129579. 11,
  129580. 0,
  129581. 12,
  129582. };
  129583. static long _vq_lengthlist__44c3_s_p9_0[] = {
  129584. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129585. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  129586. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129587. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  129588. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129589. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129590. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129591. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129592. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129593. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129594. 11,11,11,11,11,11,11,11,11,
  129595. };
  129596. static float _vq_quantthresh__44c3_s_p9_0[] = {
  129597. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  129598. 637.5, 892.5, 1147.5, 1402.5,
  129599. };
  129600. static long _vq_quantmap__44c3_s_p9_0[] = {
  129601. 11, 9, 7, 5, 3, 1, 0, 2,
  129602. 4, 6, 8, 10, 12,
  129603. };
  129604. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  129605. _vq_quantthresh__44c3_s_p9_0,
  129606. _vq_quantmap__44c3_s_p9_0,
  129607. 13,
  129608. 13
  129609. };
  129610. static static_codebook _44c3_s_p9_0 = {
  129611. 2, 169,
  129612. _vq_lengthlist__44c3_s_p9_0,
  129613. 1, -514332672, 1627381760, 4, 0,
  129614. _vq_quantlist__44c3_s_p9_0,
  129615. NULL,
  129616. &_vq_auxt__44c3_s_p9_0,
  129617. NULL,
  129618. 0
  129619. };
  129620. static long _vq_quantlist__44c3_s_p9_1[] = {
  129621. 7,
  129622. 6,
  129623. 8,
  129624. 5,
  129625. 9,
  129626. 4,
  129627. 10,
  129628. 3,
  129629. 11,
  129630. 2,
  129631. 12,
  129632. 1,
  129633. 13,
  129634. 0,
  129635. 14,
  129636. };
  129637. static long _vq_lengthlist__44c3_s_p9_1[] = {
  129638. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  129639. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  129640. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  129641. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  129642. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  129643. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  129644. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  129645. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  129646. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  129647. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  129648. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  129649. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  129650. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  129651. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  129652. 15,
  129653. };
  129654. static float _vq_quantthresh__44c3_s_p9_1[] = {
  129655. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  129656. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  129657. };
  129658. static long _vq_quantmap__44c3_s_p9_1[] = {
  129659. 13, 11, 9, 7, 5, 3, 1, 0,
  129660. 2, 4, 6, 8, 10, 12, 14,
  129661. };
  129662. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  129663. _vq_quantthresh__44c3_s_p9_1,
  129664. _vq_quantmap__44c3_s_p9_1,
  129665. 15,
  129666. 15
  129667. };
  129668. static static_codebook _44c3_s_p9_1 = {
  129669. 2, 225,
  129670. _vq_lengthlist__44c3_s_p9_1,
  129671. 1, -522338304, 1620115456, 4, 0,
  129672. _vq_quantlist__44c3_s_p9_1,
  129673. NULL,
  129674. &_vq_auxt__44c3_s_p9_1,
  129675. NULL,
  129676. 0
  129677. };
  129678. static long _vq_quantlist__44c3_s_p9_2[] = {
  129679. 8,
  129680. 7,
  129681. 9,
  129682. 6,
  129683. 10,
  129684. 5,
  129685. 11,
  129686. 4,
  129687. 12,
  129688. 3,
  129689. 13,
  129690. 2,
  129691. 14,
  129692. 1,
  129693. 15,
  129694. 0,
  129695. 16,
  129696. };
  129697. static long _vq_lengthlist__44c3_s_p9_2[] = {
  129698. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129699. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  129700. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  129701. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129702. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  129703. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129704. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  129705. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  129706. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  129707. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  129708. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  129709. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  129710. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  129711. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  129712. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  129713. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  129714. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  129715. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  129716. 10,
  129717. };
  129718. static float _vq_quantthresh__44c3_s_p9_2[] = {
  129719. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129720. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129721. };
  129722. static long _vq_quantmap__44c3_s_p9_2[] = {
  129723. 15, 13, 11, 9, 7, 5, 3, 1,
  129724. 0, 2, 4, 6, 8, 10, 12, 14,
  129725. 16,
  129726. };
  129727. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  129728. _vq_quantthresh__44c3_s_p9_2,
  129729. _vq_quantmap__44c3_s_p9_2,
  129730. 17,
  129731. 17
  129732. };
  129733. static static_codebook _44c3_s_p9_2 = {
  129734. 2, 289,
  129735. _vq_lengthlist__44c3_s_p9_2,
  129736. 1, -529530880, 1611661312, 5, 0,
  129737. _vq_quantlist__44c3_s_p9_2,
  129738. NULL,
  129739. &_vq_auxt__44c3_s_p9_2,
  129740. NULL,
  129741. 0
  129742. };
  129743. static long _huff_lengthlist__44c3_s_short[] = {
  129744. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  129745. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  129746. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  129747. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  129748. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  129749. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  129750. 6, 8, 9,11,
  129751. };
  129752. static static_codebook _huff_book__44c3_s_short = {
  129753. 2, 100,
  129754. _huff_lengthlist__44c3_s_short,
  129755. 0, 0, 0, 0, 0,
  129756. NULL,
  129757. NULL,
  129758. NULL,
  129759. NULL,
  129760. 0
  129761. };
  129762. static long _huff_lengthlist__44c4_s_long[] = {
  129763. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  129764. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  129765. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  129766. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  129767. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  129768. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  129769. 9, 8, 7, 7,
  129770. };
  129771. static static_codebook _huff_book__44c4_s_long = {
  129772. 2, 100,
  129773. _huff_lengthlist__44c4_s_long,
  129774. 0, 0, 0, 0, 0,
  129775. NULL,
  129776. NULL,
  129777. NULL,
  129778. NULL,
  129779. 0
  129780. };
  129781. static long _vq_quantlist__44c4_s_p1_0[] = {
  129782. 1,
  129783. 0,
  129784. 2,
  129785. };
  129786. static long _vq_lengthlist__44c4_s_p1_0[] = {
  129787. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129788. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129792. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129793. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129797. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129798. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129833. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129838. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  129843. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129878. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129879. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129883. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129884. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  129885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129888. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129889. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129895. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129900. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129905. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  129940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  129945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  129950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129986. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129991. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  130198. };
  130199. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130200. -0.5, 0.5,
  130201. };
  130202. static long _vq_quantmap__44c4_s_p1_0[] = {
  130203. 1, 0, 2,
  130204. };
  130205. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130206. _vq_quantthresh__44c4_s_p1_0,
  130207. _vq_quantmap__44c4_s_p1_0,
  130208. 3,
  130209. 3
  130210. };
  130211. static static_codebook _44c4_s_p1_0 = {
  130212. 8, 6561,
  130213. _vq_lengthlist__44c4_s_p1_0,
  130214. 1, -535822336, 1611661312, 2, 0,
  130215. _vq_quantlist__44c4_s_p1_0,
  130216. NULL,
  130217. &_vq_auxt__44c4_s_p1_0,
  130218. NULL,
  130219. 0
  130220. };
  130221. static long _vq_quantlist__44c4_s_p2_0[] = {
  130222. 2,
  130223. 1,
  130224. 3,
  130225. 0,
  130226. 4,
  130227. };
  130228. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130229. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130230. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130231. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130232. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130233. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130239. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130240. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130241. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130247. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130248. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130255. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130256. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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,
  130269. };
  130270. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130271. -1.5, -0.5, 0.5, 1.5,
  130272. };
  130273. static long _vq_quantmap__44c4_s_p2_0[] = {
  130274. 3, 1, 0, 2, 4,
  130275. };
  130276. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130277. _vq_quantthresh__44c4_s_p2_0,
  130278. _vq_quantmap__44c4_s_p2_0,
  130279. 5,
  130280. 5
  130281. };
  130282. static static_codebook _44c4_s_p2_0 = {
  130283. 4, 625,
  130284. _vq_lengthlist__44c4_s_p2_0,
  130285. 1, -533725184, 1611661312, 3, 0,
  130286. _vq_quantlist__44c4_s_p2_0,
  130287. NULL,
  130288. &_vq_auxt__44c4_s_p2_0,
  130289. NULL,
  130290. 0
  130291. };
  130292. static long _vq_quantlist__44c4_s_p3_0[] = {
  130293. 2,
  130294. 1,
  130295. 3,
  130296. 0,
  130297. 4,
  130298. };
  130299. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130300. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130303. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130306. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130339. 0,
  130340. };
  130341. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130342. -1.5, -0.5, 0.5, 1.5,
  130343. };
  130344. static long _vq_quantmap__44c4_s_p3_0[] = {
  130345. 3, 1, 0, 2, 4,
  130346. };
  130347. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130348. _vq_quantthresh__44c4_s_p3_0,
  130349. _vq_quantmap__44c4_s_p3_0,
  130350. 5,
  130351. 5
  130352. };
  130353. static static_codebook _44c4_s_p3_0 = {
  130354. 4, 625,
  130355. _vq_lengthlist__44c4_s_p3_0,
  130356. 1, -533725184, 1611661312, 3, 0,
  130357. _vq_quantlist__44c4_s_p3_0,
  130358. NULL,
  130359. &_vq_auxt__44c4_s_p3_0,
  130360. NULL,
  130361. 0
  130362. };
  130363. static long _vq_quantlist__44c4_s_p4_0[] = {
  130364. 4,
  130365. 3,
  130366. 5,
  130367. 2,
  130368. 6,
  130369. 1,
  130370. 7,
  130371. 0,
  130372. 8,
  130373. };
  130374. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130375. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130376. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130377. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130378. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130379. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130380. 0,
  130381. };
  130382. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130383. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130384. };
  130385. static long _vq_quantmap__44c4_s_p4_0[] = {
  130386. 7, 5, 3, 1, 0, 2, 4, 6,
  130387. 8,
  130388. };
  130389. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130390. _vq_quantthresh__44c4_s_p4_0,
  130391. _vq_quantmap__44c4_s_p4_0,
  130392. 9,
  130393. 9
  130394. };
  130395. static static_codebook _44c4_s_p4_0 = {
  130396. 2, 81,
  130397. _vq_lengthlist__44c4_s_p4_0,
  130398. 1, -531628032, 1611661312, 4, 0,
  130399. _vq_quantlist__44c4_s_p4_0,
  130400. NULL,
  130401. &_vq_auxt__44c4_s_p4_0,
  130402. NULL,
  130403. 0
  130404. };
  130405. static long _vq_quantlist__44c4_s_p5_0[] = {
  130406. 4,
  130407. 3,
  130408. 5,
  130409. 2,
  130410. 6,
  130411. 1,
  130412. 7,
  130413. 0,
  130414. 8,
  130415. };
  130416. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130417. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130418. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130419. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130420. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130421. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130422. 10,
  130423. };
  130424. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130425. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130426. };
  130427. static long _vq_quantmap__44c4_s_p5_0[] = {
  130428. 7, 5, 3, 1, 0, 2, 4, 6,
  130429. 8,
  130430. };
  130431. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130432. _vq_quantthresh__44c4_s_p5_0,
  130433. _vq_quantmap__44c4_s_p5_0,
  130434. 9,
  130435. 9
  130436. };
  130437. static static_codebook _44c4_s_p5_0 = {
  130438. 2, 81,
  130439. _vq_lengthlist__44c4_s_p5_0,
  130440. 1, -531628032, 1611661312, 4, 0,
  130441. _vq_quantlist__44c4_s_p5_0,
  130442. NULL,
  130443. &_vq_auxt__44c4_s_p5_0,
  130444. NULL,
  130445. 0
  130446. };
  130447. static long _vq_quantlist__44c4_s_p6_0[] = {
  130448. 8,
  130449. 7,
  130450. 9,
  130451. 6,
  130452. 10,
  130453. 5,
  130454. 11,
  130455. 4,
  130456. 12,
  130457. 3,
  130458. 13,
  130459. 2,
  130460. 14,
  130461. 1,
  130462. 15,
  130463. 0,
  130464. 16,
  130465. };
  130466. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130467. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130468. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130469. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130470. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130471. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130472. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130473. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130474. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130475. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130476. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130477. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130478. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130479. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130480. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130481. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130482. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130483. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130484. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130485. 13,
  130486. };
  130487. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130488. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130489. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130490. };
  130491. static long _vq_quantmap__44c4_s_p6_0[] = {
  130492. 15, 13, 11, 9, 7, 5, 3, 1,
  130493. 0, 2, 4, 6, 8, 10, 12, 14,
  130494. 16,
  130495. };
  130496. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  130497. _vq_quantthresh__44c4_s_p6_0,
  130498. _vq_quantmap__44c4_s_p6_0,
  130499. 17,
  130500. 17
  130501. };
  130502. static static_codebook _44c4_s_p6_0 = {
  130503. 2, 289,
  130504. _vq_lengthlist__44c4_s_p6_0,
  130505. 1, -529530880, 1611661312, 5, 0,
  130506. _vq_quantlist__44c4_s_p6_0,
  130507. NULL,
  130508. &_vq_auxt__44c4_s_p6_0,
  130509. NULL,
  130510. 0
  130511. };
  130512. static long _vq_quantlist__44c4_s_p7_0[] = {
  130513. 1,
  130514. 0,
  130515. 2,
  130516. };
  130517. static long _vq_lengthlist__44c4_s_p7_0[] = {
  130518. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130519. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130520. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130521. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130522. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130523. 10,
  130524. };
  130525. static float _vq_quantthresh__44c4_s_p7_0[] = {
  130526. -5.5, 5.5,
  130527. };
  130528. static long _vq_quantmap__44c4_s_p7_0[] = {
  130529. 1, 0, 2,
  130530. };
  130531. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  130532. _vq_quantthresh__44c4_s_p7_0,
  130533. _vq_quantmap__44c4_s_p7_0,
  130534. 3,
  130535. 3
  130536. };
  130537. static static_codebook _44c4_s_p7_0 = {
  130538. 4, 81,
  130539. _vq_lengthlist__44c4_s_p7_0,
  130540. 1, -529137664, 1618345984, 2, 0,
  130541. _vq_quantlist__44c4_s_p7_0,
  130542. NULL,
  130543. &_vq_auxt__44c4_s_p7_0,
  130544. NULL,
  130545. 0
  130546. };
  130547. static long _vq_quantlist__44c4_s_p7_1[] = {
  130548. 5,
  130549. 4,
  130550. 6,
  130551. 3,
  130552. 7,
  130553. 2,
  130554. 8,
  130555. 1,
  130556. 9,
  130557. 0,
  130558. 10,
  130559. };
  130560. static long _vq_lengthlist__44c4_s_p7_1[] = {
  130561. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  130562. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130563. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130564. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130565. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130566. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130567. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130568. 10,10,10, 8, 8, 8, 8, 9, 9,
  130569. };
  130570. static float _vq_quantthresh__44c4_s_p7_1[] = {
  130571. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130572. 3.5, 4.5,
  130573. };
  130574. static long _vq_quantmap__44c4_s_p7_1[] = {
  130575. 9, 7, 5, 3, 1, 0, 2, 4,
  130576. 6, 8, 10,
  130577. };
  130578. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  130579. _vq_quantthresh__44c4_s_p7_1,
  130580. _vq_quantmap__44c4_s_p7_1,
  130581. 11,
  130582. 11
  130583. };
  130584. static static_codebook _44c4_s_p7_1 = {
  130585. 2, 121,
  130586. _vq_lengthlist__44c4_s_p7_1,
  130587. 1, -531365888, 1611661312, 4, 0,
  130588. _vq_quantlist__44c4_s_p7_1,
  130589. NULL,
  130590. &_vq_auxt__44c4_s_p7_1,
  130591. NULL,
  130592. 0
  130593. };
  130594. static long _vq_quantlist__44c4_s_p8_0[] = {
  130595. 6,
  130596. 5,
  130597. 7,
  130598. 4,
  130599. 8,
  130600. 3,
  130601. 9,
  130602. 2,
  130603. 10,
  130604. 1,
  130605. 11,
  130606. 0,
  130607. 12,
  130608. };
  130609. static long _vq_lengthlist__44c4_s_p8_0[] = {
  130610. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130611. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130612. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130613. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130614. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  130615. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130616. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  130617. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130618. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  130619. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  130620. 0,13,12,12,12,12,12,13,13,
  130621. };
  130622. static float _vq_quantthresh__44c4_s_p8_0[] = {
  130623. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130624. 12.5, 17.5, 22.5, 27.5,
  130625. };
  130626. static long _vq_quantmap__44c4_s_p8_0[] = {
  130627. 11, 9, 7, 5, 3, 1, 0, 2,
  130628. 4, 6, 8, 10, 12,
  130629. };
  130630. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  130631. _vq_quantthresh__44c4_s_p8_0,
  130632. _vq_quantmap__44c4_s_p8_0,
  130633. 13,
  130634. 13
  130635. };
  130636. static static_codebook _44c4_s_p8_0 = {
  130637. 2, 169,
  130638. _vq_lengthlist__44c4_s_p8_0,
  130639. 1, -526516224, 1616117760, 4, 0,
  130640. _vq_quantlist__44c4_s_p8_0,
  130641. NULL,
  130642. &_vq_auxt__44c4_s_p8_0,
  130643. NULL,
  130644. 0
  130645. };
  130646. static long _vq_quantlist__44c4_s_p8_1[] = {
  130647. 2,
  130648. 1,
  130649. 3,
  130650. 0,
  130651. 4,
  130652. };
  130653. static long _vq_lengthlist__44c4_s_p8_1[] = {
  130654. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  130655. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130656. };
  130657. static float _vq_quantthresh__44c4_s_p8_1[] = {
  130658. -1.5, -0.5, 0.5, 1.5,
  130659. };
  130660. static long _vq_quantmap__44c4_s_p8_1[] = {
  130661. 3, 1, 0, 2, 4,
  130662. };
  130663. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  130664. _vq_quantthresh__44c4_s_p8_1,
  130665. _vq_quantmap__44c4_s_p8_1,
  130666. 5,
  130667. 5
  130668. };
  130669. static static_codebook _44c4_s_p8_1 = {
  130670. 2, 25,
  130671. _vq_lengthlist__44c4_s_p8_1,
  130672. 1, -533725184, 1611661312, 3, 0,
  130673. _vq_quantlist__44c4_s_p8_1,
  130674. NULL,
  130675. &_vq_auxt__44c4_s_p8_1,
  130676. NULL,
  130677. 0
  130678. };
  130679. static long _vq_quantlist__44c4_s_p9_0[] = {
  130680. 6,
  130681. 5,
  130682. 7,
  130683. 4,
  130684. 8,
  130685. 3,
  130686. 9,
  130687. 2,
  130688. 10,
  130689. 1,
  130690. 11,
  130691. 0,
  130692. 12,
  130693. };
  130694. static long _vq_lengthlist__44c4_s_p9_0[] = {
  130695. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  130696. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  130697. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130698. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130699. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130700. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130701. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130702. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130703. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130704. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130705. 12,12,12,12,12,12,12,12,12,
  130706. };
  130707. static float _vq_quantthresh__44c4_s_p9_0[] = {
  130708. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  130709. 787.5, 1102.5, 1417.5, 1732.5,
  130710. };
  130711. static long _vq_quantmap__44c4_s_p9_0[] = {
  130712. 11, 9, 7, 5, 3, 1, 0, 2,
  130713. 4, 6, 8, 10, 12,
  130714. };
  130715. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  130716. _vq_quantthresh__44c4_s_p9_0,
  130717. _vq_quantmap__44c4_s_p9_0,
  130718. 13,
  130719. 13
  130720. };
  130721. static static_codebook _44c4_s_p9_0 = {
  130722. 2, 169,
  130723. _vq_lengthlist__44c4_s_p9_0,
  130724. 1, -513964032, 1628680192, 4, 0,
  130725. _vq_quantlist__44c4_s_p9_0,
  130726. NULL,
  130727. &_vq_auxt__44c4_s_p9_0,
  130728. NULL,
  130729. 0
  130730. };
  130731. static long _vq_quantlist__44c4_s_p9_1[] = {
  130732. 7,
  130733. 6,
  130734. 8,
  130735. 5,
  130736. 9,
  130737. 4,
  130738. 10,
  130739. 3,
  130740. 11,
  130741. 2,
  130742. 12,
  130743. 1,
  130744. 13,
  130745. 0,
  130746. 14,
  130747. };
  130748. static long _vq_lengthlist__44c4_s_p9_1[] = {
  130749. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  130750. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  130751. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  130752. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  130753. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  130754. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  130755. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  130756. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  130757. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  130758. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  130759. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  130760. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  130761. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  130762. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  130763. 15,
  130764. };
  130765. static float _vq_quantthresh__44c4_s_p9_1[] = {
  130766. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130767. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130768. };
  130769. static long _vq_quantmap__44c4_s_p9_1[] = {
  130770. 13, 11, 9, 7, 5, 3, 1, 0,
  130771. 2, 4, 6, 8, 10, 12, 14,
  130772. };
  130773. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  130774. _vq_quantthresh__44c4_s_p9_1,
  130775. _vq_quantmap__44c4_s_p9_1,
  130776. 15,
  130777. 15
  130778. };
  130779. static static_codebook _44c4_s_p9_1 = {
  130780. 2, 225,
  130781. _vq_lengthlist__44c4_s_p9_1,
  130782. 1, -520986624, 1620377600, 4, 0,
  130783. _vq_quantlist__44c4_s_p9_1,
  130784. NULL,
  130785. &_vq_auxt__44c4_s_p9_1,
  130786. NULL,
  130787. 0
  130788. };
  130789. static long _vq_quantlist__44c4_s_p9_2[] = {
  130790. 10,
  130791. 9,
  130792. 11,
  130793. 8,
  130794. 12,
  130795. 7,
  130796. 13,
  130797. 6,
  130798. 14,
  130799. 5,
  130800. 15,
  130801. 4,
  130802. 16,
  130803. 3,
  130804. 17,
  130805. 2,
  130806. 18,
  130807. 1,
  130808. 19,
  130809. 0,
  130810. 20,
  130811. };
  130812. static long _vq_lengthlist__44c4_s_p9_2[] = {
  130813. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  130814. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130815. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  130816. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  130817. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130818. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  130819. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  130820. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  130821. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  130822. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  130823. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  130824. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  130825. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  130826. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  130827. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  130828. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  130829. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  130830. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  130831. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  130832. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  130833. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130834. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  130835. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  130836. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  130837. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  130838. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  130839. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  130840. 10,10,10,10,10,10,10,10,10,
  130841. };
  130842. static float _vq_quantthresh__44c4_s_p9_2[] = {
  130843. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130844. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130845. 6.5, 7.5, 8.5, 9.5,
  130846. };
  130847. static long _vq_quantmap__44c4_s_p9_2[] = {
  130848. 19, 17, 15, 13, 11, 9, 7, 5,
  130849. 3, 1, 0, 2, 4, 6, 8, 10,
  130850. 12, 14, 16, 18, 20,
  130851. };
  130852. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  130853. _vq_quantthresh__44c4_s_p9_2,
  130854. _vq_quantmap__44c4_s_p9_2,
  130855. 21,
  130856. 21
  130857. };
  130858. static static_codebook _44c4_s_p9_2 = {
  130859. 2, 441,
  130860. _vq_lengthlist__44c4_s_p9_2,
  130861. 1, -529268736, 1611661312, 5, 0,
  130862. _vq_quantlist__44c4_s_p9_2,
  130863. NULL,
  130864. &_vq_auxt__44c4_s_p9_2,
  130865. NULL,
  130866. 0
  130867. };
  130868. static long _huff_lengthlist__44c4_s_short[] = {
  130869. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  130870. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  130871. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  130872. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  130873. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  130874. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  130875. 7, 9,12,17,
  130876. };
  130877. static static_codebook _huff_book__44c4_s_short = {
  130878. 2, 100,
  130879. _huff_lengthlist__44c4_s_short,
  130880. 0, 0, 0, 0, 0,
  130881. NULL,
  130882. NULL,
  130883. NULL,
  130884. NULL,
  130885. 0
  130886. };
  130887. static long _huff_lengthlist__44c5_s_long[] = {
  130888. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  130889. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  130890. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  130891. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  130892. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  130893. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  130894. 9, 8, 7, 7,
  130895. };
  130896. static static_codebook _huff_book__44c5_s_long = {
  130897. 2, 100,
  130898. _huff_lengthlist__44c5_s_long,
  130899. 0, 0, 0, 0, 0,
  130900. NULL,
  130901. NULL,
  130902. NULL,
  130903. NULL,
  130904. 0
  130905. };
  130906. static long _vq_quantlist__44c5_s_p1_0[] = {
  130907. 1,
  130908. 0,
  130909. 2,
  130910. };
  130911. static long _vq_lengthlist__44c5_s_p1_0[] = {
  130912. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130913. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130917. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130918. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130922. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  130923. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130958. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130963. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  130964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130968. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  130969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131003. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131004. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131008. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131009. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  131010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131013. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131014. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  131015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131020. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131025. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131030. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  131065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  131070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  131075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131111. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131116. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  131323. };
  131324. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131325. -0.5, 0.5,
  131326. };
  131327. static long _vq_quantmap__44c5_s_p1_0[] = {
  131328. 1, 0, 2,
  131329. };
  131330. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131331. _vq_quantthresh__44c5_s_p1_0,
  131332. _vq_quantmap__44c5_s_p1_0,
  131333. 3,
  131334. 3
  131335. };
  131336. static static_codebook _44c5_s_p1_0 = {
  131337. 8, 6561,
  131338. _vq_lengthlist__44c5_s_p1_0,
  131339. 1, -535822336, 1611661312, 2, 0,
  131340. _vq_quantlist__44c5_s_p1_0,
  131341. NULL,
  131342. &_vq_auxt__44c5_s_p1_0,
  131343. NULL,
  131344. 0
  131345. };
  131346. static long _vq_quantlist__44c5_s_p2_0[] = {
  131347. 2,
  131348. 1,
  131349. 3,
  131350. 0,
  131351. 4,
  131352. };
  131353. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131354. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131355. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131356. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131357. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131358. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131364. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131365. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131366. 10, 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, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131372. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131373. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 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. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131380. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131381. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 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,
  131394. };
  131395. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131396. -1.5, -0.5, 0.5, 1.5,
  131397. };
  131398. static long _vq_quantmap__44c5_s_p2_0[] = {
  131399. 3, 1, 0, 2, 4,
  131400. };
  131401. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131402. _vq_quantthresh__44c5_s_p2_0,
  131403. _vq_quantmap__44c5_s_p2_0,
  131404. 5,
  131405. 5
  131406. };
  131407. static static_codebook _44c5_s_p2_0 = {
  131408. 4, 625,
  131409. _vq_lengthlist__44c5_s_p2_0,
  131410. 1, -533725184, 1611661312, 3, 0,
  131411. _vq_quantlist__44c5_s_p2_0,
  131412. NULL,
  131413. &_vq_auxt__44c5_s_p2_0,
  131414. NULL,
  131415. 0
  131416. };
  131417. static long _vq_quantlist__44c5_s_p3_0[] = {
  131418. 2,
  131419. 1,
  131420. 3,
  131421. 0,
  131422. 4,
  131423. };
  131424. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131425. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131428. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131431. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131464. 0,
  131465. };
  131466. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131467. -1.5, -0.5, 0.5, 1.5,
  131468. };
  131469. static long _vq_quantmap__44c5_s_p3_0[] = {
  131470. 3, 1, 0, 2, 4,
  131471. };
  131472. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131473. _vq_quantthresh__44c5_s_p3_0,
  131474. _vq_quantmap__44c5_s_p3_0,
  131475. 5,
  131476. 5
  131477. };
  131478. static static_codebook _44c5_s_p3_0 = {
  131479. 4, 625,
  131480. _vq_lengthlist__44c5_s_p3_0,
  131481. 1, -533725184, 1611661312, 3, 0,
  131482. _vq_quantlist__44c5_s_p3_0,
  131483. NULL,
  131484. &_vq_auxt__44c5_s_p3_0,
  131485. NULL,
  131486. 0
  131487. };
  131488. static long _vq_quantlist__44c5_s_p4_0[] = {
  131489. 4,
  131490. 3,
  131491. 5,
  131492. 2,
  131493. 6,
  131494. 1,
  131495. 7,
  131496. 0,
  131497. 8,
  131498. };
  131499. static long _vq_lengthlist__44c5_s_p4_0[] = {
  131500. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  131501. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  131502. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  131503. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  131504. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131505. 0,
  131506. };
  131507. static float _vq_quantthresh__44c5_s_p4_0[] = {
  131508. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131509. };
  131510. static long _vq_quantmap__44c5_s_p4_0[] = {
  131511. 7, 5, 3, 1, 0, 2, 4, 6,
  131512. 8,
  131513. };
  131514. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  131515. _vq_quantthresh__44c5_s_p4_0,
  131516. _vq_quantmap__44c5_s_p4_0,
  131517. 9,
  131518. 9
  131519. };
  131520. static static_codebook _44c5_s_p4_0 = {
  131521. 2, 81,
  131522. _vq_lengthlist__44c5_s_p4_0,
  131523. 1, -531628032, 1611661312, 4, 0,
  131524. _vq_quantlist__44c5_s_p4_0,
  131525. NULL,
  131526. &_vq_auxt__44c5_s_p4_0,
  131527. NULL,
  131528. 0
  131529. };
  131530. static long _vq_quantlist__44c5_s_p5_0[] = {
  131531. 4,
  131532. 3,
  131533. 5,
  131534. 2,
  131535. 6,
  131536. 1,
  131537. 7,
  131538. 0,
  131539. 8,
  131540. };
  131541. static long _vq_lengthlist__44c5_s_p5_0[] = {
  131542. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131543. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  131544. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  131545. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131546. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131547. 10,
  131548. };
  131549. static float _vq_quantthresh__44c5_s_p5_0[] = {
  131550. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131551. };
  131552. static long _vq_quantmap__44c5_s_p5_0[] = {
  131553. 7, 5, 3, 1, 0, 2, 4, 6,
  131554. 8,
  131555. };
  131556. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  131557. _vq_quantthresh__44c5_s_p5_0,
  131558. _vq_quantmap__44c5_s_p5_0,
  131559. 9,
  131560. 9
  131561. };
  131562. static static_codebook _44c5_s_p5_0 = {
  131563. 2, 81,
  131564. _vq_lengthlist__44c5_s_p5_0,
  131565. 1, -531628032, 1611661312, 4, 0,
  131566. _vq_quantlist__44c5_s_p5_0,
  131567. NULL,
  131568. &_vq_auxt__44c5_s_p5_0,
  131569. NULL,
  131570. 0
  131571. };
  131572. static long _vq_quantlist__44c5_s_p6_0[] = {
  131573. 8,
  131574. 7,
  131575. 9,
  131576. 6,
  131577. 10,
  131578. 5,
  131579. 11,
  131580. 4,
  131581. 12,
  131582. 3,
  131583. 13,
  131584. 2,
  131585. 14,
  131586. 1,
  131587. 15,
  131588. 0,
  131589. 16,
  131590. };
  131591. static long _vq_lengthlist__44c5_s_p6_0[] = {
  131592. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  131593. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131594. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131595. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131596. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131597. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131598. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  131599. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  131600. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131601. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131602. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  131603. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131604. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131605. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131606. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  131607. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131608. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  131609. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  131610. 13,
  131611. };
  131612. static float _vq_quantthresh__44c5_s_p6_0[] = {
  131613. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131614. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131615. };
  131616. static long _vq_quantmap__44c5_s_p6_0[] = {
  131617. 15, 13, 11, 9, 7, 5, 3, 1,
  131618. 0, 2, 4, 6, 8, 10, 12, 14,
  131619. 16,
  131620. };
  131621. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  131622. _vq_quantthresh__44c5_s_p6_0,
  131623. _vq_quantmap__44c5_s_p6_0,
  131624. 17,
  131625. 17
  131626. };
  131627. static static_codebook _44c5_s_p6_0 = {
  131628. 2, 289,
  131629. _vq_lengthlist__44c5_s_p6_0,
  131630. 1, -529530880, 1611661312, 5, 0,
  131631. _vq_quantlist__44c5_s_p6_0,
  131632. NULL,
  131633. &_vq_auxt__44c5_s_p6_0,
  131634. NULL,
  131635. 0
  131636. };
  131637. static long _vq_quantlist__44c5_s_p7_0[] = {
  131638. 1,
  131639. 0,
  131640. 2,
  131641. };
  131642. static long _vq_lengthlist__44c5_s_p7_0[] = {
  131643. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131644. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131645. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131646. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131647. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131648. 10,
  131649. };
  131650. static float _vq_quantthresh__44c5_s_p7_0[] = {
  131651. -5.5, 5.5,
  131652. };
  131653. static long _vq_quantmap__44c5_s_p7_0[] = {
  131654. 1, 0, 2,
  131655. };
  131656. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  131657. _vq_quantthresh__44c5_s_p7_0,
  131658. _vq_quantmap__44c5_s_p7_0,
  131659. 3,
  131660. 3
  131661. };
  131662. static static_codebook _44c5_s_p7_0 = {
  131663. 4, 81,
  131664. _vq_lengthlist__44c5_s_p7_0,
  131665. 1, -529137664, 1618345984, 2, 0,
  131666. _vq_quantlist__44c5_s_p7_0,
  131667. NULL,
  131668. &_vq_auxt__44c5_s_p7_0,
  131669. NULL,
  131670. 0
  131671. };
  131672. static long _vq_quantlist__44c5_s_p7_1[] = {
  131673. 5,
  131674. 4,
  131675. 6,
  131676. 3,
  131677. 7,
  131678. 2,
  131679. 8,
  131680. 1,
  131681. 9,
  131682. 0,
  131683. 10,
  131684. };
  131685. static long _vq_lengthlist__44c5_s_p7_1[] = {
  131686. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  131687. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131688. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131689. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  131690. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131691. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  131692. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131693. 10,10,10, 8, 8, 8, 8, 8, 8,
  131694. };
  131695. static float _vq_quantthresh__44c5_s_p7_1[] = {
  131696. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131697. 3.5, 4.5,
  131698. };
  131699. static long _vq_quantmap__44c5_s_p7_1[] = {
  131700. 9, 7, 5, 3, 1, 0, 2, 4,
  131701. 6, 8, 10,
  131702. };
  131703. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  131704. _vq_quantthresh__44c5_s_p7_1,
  131705. _vq_quantmap__44c5_s_p7_1,
  131706. 11,
  131707. 11
  131708. };
  131709. static static_codebook _44c5_s_p7_1 = {
  131710. 2, 121,
  131711. _vq_lengthlist__44c5_s_p7_1,
  131712. 1, -531365888, 1611661312, 4, 0,
  131713. _vq_quantlist__44c5_s_p7_1,
  131714. NULL,
  131715. &_vq_auxt__44c5_s_p7_1,
  131716. NULL,
  131717. 0
  131718. };
  131719. static long _vq_quantlist__44c5_s_p8_0[] = {
  131720. 6,
  131721. 5,
  131722. 7,
  131723. 4,
  131724. 8,
  131725. 3,
  131726. 9,
  131727. 2,
  131728. 10,
  131729. 1,
  131730. 11,
  131731. 0,
  131732. 12,
  131733. };
  131734. static long _vq_lengthlist__44c5_s_p8_0[] = {
  131735. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131736. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  131737. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131738. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131739. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  131740. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  131741. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  131742. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131743. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  131744. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131745. 0,12,12,12,12,12,12,13,13,
  131746. };
  131747. static float _vq_quantthresh__44c5_s_p8_0[] = {
  131748. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131749. 12.5, 17.5, 22.5, 27.5,
  131750. };
  131751. static long _vq_quantmap__44c5_s_p8_0[] = {
  131752. 11, 9, 7, 5, 3, 1, 0, 2,
  131753. 4, 6, 8, 10, 12,
  131754. };
  131755. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  131756. _vq_quantthresh__44c5_s_p8_0,
  131757. _vq_quantmap__44c5_s_p8_0,
  131758. 13,
  131759. 13
  131760. };
  131761. static static_codebook _44c5_s_p8_0 = {
  131762. 2, 169,
  131763. _vq_lengthlist__44c5_s_p8_0,
  131764. 1, -526516224, 1616117760, 4, 0,
  131765. _vq_quantlist__44c5_s_p8_0,
  131766. NULL,
  131767. &_vq_auxt__44c5_s_p8_0,
  131768. NULL,
  131769. 0
  131770. };
  131771. static long _vq_quantlist__44c5_s_p8_1[] = {
  131772. 2,
  131773. 1,
  131774. 3,
  131775. 0,
  131776. 4,
  131777. };
  131778. static long _vq_lengthlist__44c5_s_p8_1[] = {
  131779. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  131780. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131781. };
  131782. static float _vq_quantthresh__44c5_s_p8_1[] = {
  131783. -1.5, -0.5, 0.5, 1.5,
  131784. };
  131785. static long _vq_quantmap__44c5_s_p8_1[] = {
  131786. 3, 1, 0, 2, 4,
  131787. };
  131788. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  131789. _vq_quantthresh__44c5_s_p8_1,
  131790. _vq_quantmap__44c5_s_p8_1,
  131791. 5,
  131792. 5
  131793. };
  131794. static static_codebook _44c5_s_p8_1 = {
  131795. 2, 25,
  131796. _vq_lengthlist__44c5_s_p8_1,
  131797. 1, -533725184, 1611661312, 3, 0,
  131798. _vq_quantlist__44c5_s_p8_1,
  131799. NULL,
  131800. &_vq_auxt__44c5_s_p8_1,
  131801. NULL,
  131802. 0
  131803. };
  131804. static long _vq_quantlist__44c5_s_p9_0[] = {
  131805. 7,
  131806. 6,
  131807. 8,
  131808. 5,
  131809. 9,
  131810. 4,
  131811. 10,
  131812. 3,
  131813. 11,
  131814. 2,
  131815. 12,
  131816. 1,
  131817. 13,
  131818. 0,
  131819. 14,
  131820. };
  131821. static long _vq_lengthlist__44c5_s_p9_0[] = {
  131822. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  131823. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  131824. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131825. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131826. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131827. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131828. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131829. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131830. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131831. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131832. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131833. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131834. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131835. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  131836. 12,
  131837. };
  131838. static float _vq_quantthresh__44c5_s_p9_0[] = {
  131839. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  131840. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  131841. };
  131842. static long _vq_quantmap__44c5_s_p9_0[] = {
  131843. 13, 11, 9, 7, 5, 3, 1, 0,
  131844. 2, 4, 6, 8, 10, 12, 14,
  131845. };
  131846. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  131847. _vq_quantthresh__44c5_s_p9_0,
  131848. _vq_quantmap__44c5_s_p9_0,
  131849. 15,
  131850. 15
  131851. };
  131852. static static_codebook _44c5_s_p9_0 = {
  131853. 2, 225,
  131854. _vq_lengthlist__44c5_s_p9_0,
  131855. 1, -512522752, 1628852224, 4, 0,
  131856. _vq_quantlist__44c5_s_p9_0,
  131857. NULL,
  131858. &_vq_auxt__44c5_s_p9_0,
  131859. NULL,
  131860. 0
  131861. };
  131862. static long _vq_quantlist__44c5_s_p9_1[] = {
  131863. 8,
  131864. 7,
  131865. 9,
  131866. 6,
  131867. 10,
  131868. 5,
  131869. 11,
  131870. 4,
  131871. 12,
  131872. 3,
  131873. 13,
  131874. 2,
  131875. 14,
  131876. 1,
  131877. 15,
  131878. 0,
  131879. 16,
  131880. };
  131881. static long _vq_lengthlist__44c5_s_p9_1[] = {
  131882. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  131883. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  131884. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  131885. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  131886. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  131887. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  131888. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  131889. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  131890. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  131891. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  131892. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  131893. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  131894. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  131895. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  131896. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  131897. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  131898. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  131899. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  131900. 15,
  131901. };
  131902. static float _vq_quantthresh__44c5_s_p9_1[] = {
  131903. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  131904. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  131905. };
  131906. static long _vq_quantmap__44c5_s_p9_1[] = {
  131907. 15, 13, 11, 9, 7, 5, 3, 1,
  131908. 0, 2, 4, 6, 8, 10, 12, 14,
  131909. 16,
  131910. };
  131911. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  131912. _vq_quantthresh__44c5_s_p9_1,
  131913. _vq_quantmap__44c5_s_p9_1,
  131914. 17,
  131915. 17
  131916. };
  131917. static static_codebook _44c5_s_p9_1 = {
  131918. 2, 289,
  131919. _vq_lengthlist__44c5_s_p9_1,
  131920. 1, -520814592, 1620377600, 5, 0,
  131921. _vq_quantlist__44c5_s_p9_1,
  131922. NULL,
  131923. &_vq_auxt__44c5_s_p9_1,
  131924. NULL,
  131925. 0
  131926. };
  131927. static long _vq_quantlist__44c5_s_p9_2[] = {
  131928. 10,
  131929. 9,
  131930. 11,
  131931. 8,
  131932. 12,
  131933. 7,
  131934. 13,
  131935. 6,
  131936. 14,
  131937. 5,
  131938. 15,
  131939. 4,
  131940. 16,
  131941. 3,
  131942. 17,
  131943. 2,
  131944. 18,
  131945. 1,
  131946. 19,
  131947. 0,
  131948. 20,
  131949. };
  131950. static long _vq_lengthlist__44c5_s_p9_2[] = {
  131951. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131952. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  131953. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  131954. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  131955. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  131956. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  131957. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  131958. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  131959. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  131960. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131961. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131962. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  131963. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  131964. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  131965. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  131966. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  131967. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131968. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131969. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  131970. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  131971. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131972. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131973. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  131974. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  131975. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  131976. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131977. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  131978. 10,10,10,10,10,10,10,10,10,
  131979. };
  131980. static float _vq_quantthresh__44c5_s_p9_2[] = {
  131981. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131982. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131983. 6.5, 7.5, 8.5, 9.5,
  131984. };
  131985. static long _vq_quantmap__44c5_s_p9_2[] = {
  131986. 19, 17, 15, 13, 11, 9, 7, 5,
  131987. 3, 1, 0, 2, 4, 6, 8, 10,
  131988. 12, 14, 16, 18, 20,
  131989. };
  131990. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  131991. _vq_quantthresh__44c5_s_p9_2,
  131992. _vq_quantmap__44c5_s_p9_2,
  131993. 21,
  131994. 21
  131995. };
  131996. static static_codebook _44c5_s_p9_2 = {
  131997. 2, 441,
  131998. _vq_lengthlist__44c5_s_p9_2,
  131999. 1, -529268736, 1611661312, 5, 0,
  132000. _vq_quantlist__44c5_s_p9_2,
  132001. NULL,
  132002. &_vq_auxt__44c5_s_p9_2,
  132003. NULL,
  132004. 0
  132005. };
  132006. static long _huff_lengthlist__44c5_s_short[] = {
  132007. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132008. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132009. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132010. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132011. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132012. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132013. 6, 8,11,16,
  132014. };
  132015. static static_codebook _huff_book__44c5_s_short = {
  132016. 2, 100,
  132017. _huff_lengthlist__44c5_s_short,
  132018. 0, 0, 0, 0, 0,
  132019. NULL,
  132020. NULL,
  132021. NULL,
  132022. NULL,
  132023. 0
  132024. };
  132025. static long _huff_lengthlist__44c6_s_long[] = {
  132026. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132027. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132028. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132029. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132030. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132031. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132032. 11,10,10,12,
  132033. };
  132034. static static_codebook _huff_book__44c6_s_long = {
  132035. 2, 100,
  132036. _huff_lengthlist__44c6_s_long,
  132037. 0, 0, 0, 0, 0,
  132038. NULL,
  132039. NULL,
  132040. NULL,
  132041. NULL,
  132042. 0
  132043. };
  132044. static long _vq_quantlist__44c6_s_p1_0[] = {
  132045. 1,
  132046. 0,
  132047. 2,
  132048. };
  132049. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132050. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132051. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132052. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132053. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132054. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132055. 8,
  132056. };
  132057. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132058. -0.5, 0.5,
  132059. };
  132060. static long _vq_quantmap__44c6_s_p1_0[] = {
  132061. 1, 0, 2,
  132062. };
  132063. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132064. _vq_quantthresh__44c6_s_p1_0,
  132065. _vq_quantmap__44c6_s_p1_0,
  132066. 3,
  132067. 3
  132068. };
  132069. static static_codebook _44c6_s_p1_0 = {
  132070. 4, 81,
  132071. _vq_lengthlist__44c6_s_p1_0,
  132072. 1, -535822336, 1611661312, 2, 0,
  132073. _vq_quantlist__44c6_s_p1_0,
  132074. NULL,
  132075. &_vq_auxt__44c6_s_p1_0,
  132076. NULL,
  132077. 0
  132078. };
  132079. static long _vq_quantlist__44c6_s_p2_0[] = {
  132080. 2,
  132081. 1,
  132082. 3,
  132083. 0,
  132084. 4,
  132085. };
  132086. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132087. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132088. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132089. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132090. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132091. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132092. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132093. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132094. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132096. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132097. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132098. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132099. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132100. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132101. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132102. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132104. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132105. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132106. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132107. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132108. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132109. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132110. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132112. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132113. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132114. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132115. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132116. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132117. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132118. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132123. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132124. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132125. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132126. 13,
  132127. };
  132128. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132129. -1.5, -0.5, 0.5, 1.5,
  132130. };
  132131. static long _vq_quantmap__44c6_s_p2_0[] = {
  132132. 3, 1, 0, 2, 4,
  132133. };
  132134. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132135. _vq_quantthresh__44c6_s_p2_0,
  132136. _vq_quantmap__44c6_s_p2_0,
  132137. 5,
  132138. 5
  132139. };
  132140. static static_codebook _44c6_s_p2_0 = {
  132141. 4, 625,
  132142. _vq_lengthlist__44c6_s_p2_0,
  132143. 1, -533725184, 1611661312, 3, 0,
  132144. _vq_quantlist__44c6_s_p2_0,
  132145. NULL,
  132146. &_vq_auxt__44c6_s_p2_0,
  132147. NULL,
  132148. 0
  132149. };
  132150. static long _vq_quantlist__44c6_s_p3_0[] = {
  132151. 4,
  132152. 3,
  132153. 5,
  132154. 2,
  132155. 6,
  132156. 1,
  132157. 7,
  132158. 0,
  132159. 8,
  132160. };
  132161. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132162. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132163. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132164. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132165. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132167. 0,
  132168. };
  132169. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132170. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132171. };
  132172. static long _vq_quantmap__44c6_s_p3_0[] = {
  132173. 7, 5, 3, 1, 0, 2, 4, 6,
  132174. 8,
  132175. };
  132176. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132177. _vq_quantthresh__44c6_s_p3_0,
  132178. _vq_quantmap__44c6_s_p3_0,
  132179. 9,
  132180. 9
  132181. };
  132182. static static_codebook _44c6_s_p3_0 = {
  132183. 2, 81,
  132184. _vq_lengthlist__44c6_s_p3_0,
  132185. 1, -531628032, 1611661312, 4, 0,
  132186. _vq_quantlist__44c6_s_p3_0,
  132187. NULL,
  132188. &_vq_auxt__44c6_s_p3_0,
  132189. NULL,
  132190. 0
  132191. };
  132192. static long _vq_quantlist__44c6_s_p4_0[] = {
  132193. 8,
  132194. 7,
  132195. 9,
  132196. 6,
  132197. 10,
  132198. 5,
  132199. 11,
  132200. 4,
  132201. 12,
  132202. 3,
  132203. 13,
  132204. 2,
  132205. 14,
  132206. 1,
  132207. 15,
  132208. 0,
  132209. 16,
  132210. };
  132211. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132212. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132213. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132214. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132215. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132216. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132217. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132218. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132219. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132220. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132221. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132225. 0, 0, 0, 0, 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, 0,
  132230. 0,
  132231. };
  132232. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132233. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132234. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132235. };
  132236. static long _vq_quantmap__44c6_s_p4_0[] = {
  132237. 15, 13, 11, 9, 7, 5, 3, 1,
  132238. 0, 2, 4, 6, 8, 10, 12, 14,
  132239. 16,
  132240. };
  132241. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132242. _vq_quantthresh__44c6_s_p4_0,
  132243. _vq_quantmap__44c6_s_p4_0,
  132244. 17,
  132245. 17
  132246. };
  132247. static static_codebook _44c6_s_p4_0 = {
  132248. 2, 289,
  132249. _vq_lengthlist__44c6_s_p4_0,
  132250. 1, -529530880, 1611661312, 5, 0,
  132251. _vq_quantlist__44c6_s_p4_0,
  132252. NULL,
  132253. &_vq_auxt__44c6_s_p4_0,
  132254. NULL,
  132255. 0
  132256. };
  132257. static long _vq_quantlist__44c6_s_p5_0[] = {
  132258. 1,
  132259. 0,
  132260. 2,
  132261. };
  132262. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132263. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132264. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132265. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132266. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132267. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132268. 12,
  132269. };
  132270. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132271. -5.5, 5.5,
  132272. };
  132273. static long _vq_quantmap__44c6_s_p5_0[] = {
  132274. 1, 0, 2,
  132275. };
  132276. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132277. _vq_quantthresh__44c6_s_p5_0,
  132278. _vq_quantmap__44c6_s_p5_0,
  132279. 3,
  132280. 3
  132281. };
  132282. static static_codebook _44c6_s_p5_0 = {
  132283. 4, 81,
  132284. _vq_lengthlist__44c6_s_p5_0,
  132285. 1, -529137664, 1618345984, 2, 0,
  132286. _vq_quantlist__44c6_s_p5_0,
  132287. NULL,
  132288. &_vq_auxt__44c6_s_p5_0,
  132289. NULL,
  132290. 0
  132291. };
  132292. static long _vq_quantlist__44c6_s_p5_1[] = {
  132293. 5,
  132294. 4,
  132295. 6,
  132296. 3,
  132297. 7,
  132298. 2,
  132299. 8,
  132300. 1,
  132301. 9,
  132302. 0,
  132303. 10,
  132304. };
  132305. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132306. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132307. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132308. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132309. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132310. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132311. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132312. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132313. 11,10,10, 7, 7, 8, 8, 8, 8,
  132314. };
  132315. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132316. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132317. 3.5, 4.5,
  132318. };
  132319. static long _vq_quantmap__44c6_s_p5_1[] = {
  132320. 9, 7, 5, 3, 1, 0, 2, 4,
  132321. 6, 8, 10,
  132322. };
  132323. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132324. _vq_quantthresh__44c6_s_p5_1,
  132325. _vq_quantmap__44c6_s_p5_1,
  132326. 11,
  132327. 11
  132328. };
  132329. static static_codebook _44c6_s_p5_1 = {
  132330. 2, 121,
  132331. _vq_lengthlist__44c6_s_p5_1,
  132332. 1, -531365888, 1611661312, 4, 0,
  132333. _vq_quantlist__44c6_s_p5_1,
  132334. NULL,
  132335. &_vq_auxt__44c6_s_p5_1,
  132336. NULL,
  132337. 0
  132338. };
  132339. static long _vq_quantlist__44c6_s_p6_0[] = {
  132340. 6,
  132341. 5,
  132342. 7,
  132343. 4,
  132344. 8,
  132345. 3,
  132346. 9,
  132347. 2,
  132348. 10,
  132349. 1,
  132350. 11,
  132351. 0,
  132352. 12,
  132353. };
  132354. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132355. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132356. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132357. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132358. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132359. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132360. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132365. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132366. };
  132367. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132368. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132369. 12.5, 17.5, 22.5, 27.5,
  132370. };
  132371. static long _vq_quantmap__44c6_s_p6_0[] = {
  132372. 11, 9, 7, 5, 3, 1, 0, 2,
  132373. 4, 6, 8, 10, 12,
  132374. };
  132375. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132376. _vq_quantthresh__44c6_s_p6_0,
  132377. _vq_quantmap__44c6_s_p6_0,
  132378. 13,
  132379. 13
  132380. };
  132381. static static_codebook _44c6_s_p6_0 = {
  132382. 2, 169,
  132383. _vq_lengthlist__44c6_s_p6_0,
  132384. 1, -526516224, 1616117760, 4, 0,
  132385. _vq_quantlist__44c6_s_p6_0,
  132386. NULL,
  132387. &_vq_auxt__44c6_s_p6_0,
  132388. NULL,
  132389. 0
  132390. };
  132391. static long _vq_quantlist__44c6_s_p6_1[] = {
  132392. 2,
  132393. 1,
  132394. 3,
  132395. 0,
  132396. 4,
  132397. };
  132398. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132399. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132400. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132401. };
  132402. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132403. -1.5, -0.5, 0.5, 1.5,
  132404. };
  132405. static long _vq_quantmap__44c6_s_p6_1[] = {
  132406. 3, 1, 0, 2, 4,
  132407. };
  132408. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132409. _vq_quantthresh__44c6_s_p6_1,
  132410. _vq_quantmap__44c6_s_p6_1,
  132411. 5,
  132412. 5
  132413. };
  132414. static static_codebook _44c6_s_p6_1 = {
  132415. 2, 25,
  132416. _vq_lengthlist__44c6_s_p6_1,
  132417. 1, -533725184, 1611661312, 3, 0,
  132418. _vq_quantlist__44c6_s_p6_1,
  132419. NULL,
  132420. &_vq_auxt__44c6_s_p6_1,
  132421. NULL,
  132422. 0
  132423. };
  132424. static long _vq_quantlist__44c6_s_p7_0[] = {
  132425. 6,
  132426. 5,
  132427. 7,
  132428. 4,
  132429. 8,
  132430. 3,
  132431. 9,
  132432. 2,
  132433. 10,
  132434. 1,
  132435. 11,
  132436. 0,
  132437. 12,
  132438. };
  132439. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132440. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132441. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132442. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132443. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132444. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132445. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132446. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132447. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132448. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132449. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132450. 20,13,13,13,13,13,13,14,14,
  132451. };
  132452. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132453. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132454. 27.5, 38.5, 49.5, 60.5,
  132455. };
  132456. static long _vq_quantmap__44c6_s_p7_0[] = {
  132457. 11, 9, 7, 5, 3, 1, 0, 2,
  132458. 4, 6, 8, 10, 12,
  132459. };
  132460. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132461. _vq_quantthresh__44c6_s_p7_0,
  132462. _vq_quantmap__44c6_s_p7_0,
  132463. 13,
  132464. 13
  132465. };
  132466. static static_codebook _44c6_s_p7_0 = {
  132467. 2, 169,
  132468. _vq_lengthlist__44c6_s_p7_0,
  132469. 1, -523206656, 1618345984, 4, 0,
  132470. _vq_quantlist__44c6_s_p7_0,
  132471. NULL,
  132472. &_vq_auxt__44c6_s_p7_0,
  132473. NULL,
  132474. 0
  132475. };
  132476. static long _vq_quantlist__44c6_s_p7_1[] = {
  132477. 5,
  132478. 4,
  132479. 6,
  132480. 3,
  132481. 7,
  132482. 2,
  132483. 8,
  132484. 1,
  132485. 9,
  132486. 0,
  132487. 10,
  132488. };
  132489. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132490. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132491. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132492. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  132493. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  132494. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  132495. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  132496. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  132497. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  132498. };
  132499. static float _vq_quantthresh__44c6_s_p7_1[] = {
  132500. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132501. 3.5, 4.5,
  132502. };
  132503. static long _vq_quantmap__44c6_s_p7_1[] = {
  132504. 9, 7, 5, 3, 1, 0, 2, 4,
  132505. 6, 8, 10,
  132506. };
  132507. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  132508. _vq_quantthresh__44c6_s_p7_1,
  132509. _vq_quantmap__44c6_s_p7_1,
  132510. 11,
  132511. 11
  132512. };
  132513. static static_codebook _44c6_s_p7_1 = {
  132514. 2, 121,
  132515. _vq_lengthlist__44c6_s_p7_1,
  132516. 1, -531365888, 1611661312, 4, 0,
  132517. _vq_quantlist__44c6_s_p7_1,
  132518. NULL,
  132519. &_vq_auxt__44c6_s_p7_1,
  132520. NULL,
  132521. 0
  132522. };
  132523. static long _vq_quantlist__44c6_s_p8_0[] = {
  132524. 7,
  132525. 6,
  132526. 8,
  132527. 5,
  132528. 9,
  132529. 4,
  132530. 10,
  132531. 3,
  132532. 11,
  132533. 2,
  132534. 12,
  132535. 1,
  132536. 13,
  132537. 0,
  132538. 14,
  132539. };
  132540. static long _vq_lengthlist__44c6_s_p8_0[] = {
  132541. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  132542. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  132543. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  132544. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  132545. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  132546. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  132547. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  132548. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  132549. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  132550. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  132551. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  132552. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  132553. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  132554. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  132555. 14,
  132556. };
  132557. static float _vq_quantthresh__44c6_s_p8_0[] = {
  132558. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132559. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132560. };
  132561. static long _vq_quantmap__44c6_s_p8_0[] = {
  132562. 13, 11, 9, 7, 5, 3, 1, 0,
  132563. 2, 4, 6, 8, 10, 12, 14,
  132564. };
  132565. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  132566. _vq_quantthresh__44c6_s_p8_0,
  132567. _vq_quantmap__44c6_s_p8_0,
  132568. 15,
  132569. 15
  132570. };
  132571. static static_codebook _44c6_s_p8_0 = {
  132572. 2, 225,
  132573. _vq_lengthlist__44c6_s_p8_0,
  132574. 1, -520986624, 1620377600, 4, 0,
  132575. _vq_quantlist__44c6_s_p8_0,
  132576. NULL,
  132577. &_vq_auxt__44c6_s_p8_0,
  132578. NULL,
  132579. 0
  132580. };
  132581. static long _vq_quantlist__44c6_s_p8_1[] = {
  132582. 10,
  132583. 9,
  132584. 11,
  132585. 8,
  132586. 12,
  132587. 7,
  132588. 13,
  132589. 6,
  132590. 14,
  132591. 5,
  132592. 15,
  132593. 4,
  132594. 16,
  132595. 3,
  132596. 17,
  132597. 2,
  132598. 18,
  132599. 1,
  132600. 19,
  132601. 0,
  132602. 20,
  132603. };
  132604. static long _vq_lengthlist__44c6_s_p8_1[] = {
  132605. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  132606. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  132607. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132608. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132609. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132610. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  132611. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  132612. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  132613. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132614. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132615. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  132616. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  132617. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  132618. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  132619. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  132620. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  132621. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  132622. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  132623. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  132624. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  132625. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  132626. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132627. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132628. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132629. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  132630. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  132631. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  132632. 10,10,10,10,10,10,10,10,10,
  132633. };
  132634. static float _vq_quantthresh__44c6_s_p8_1[] = {
  132635. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132636. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132637. 6.5, 7.5, 8.5, 9.5,
  132638. };
  132639. static long _vq_quantmap__44c6_s_p8_1[] = {
  132640. 19, 17, 15, 13, 11, 9, 7, 5,
  132641. 3, 1, 0, 2, 4, 6, 8, 10,
  132642. 12, 14, 16, 18, 20,
  132643. };
  132644. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  132645. _vq_quantthresh__44c6_s_p8_1,
  132646. _vq_quantmap__44c6_s_p8_1,
  132647. 21,
  132648. 21
  132649. };
  132650. static static_codebook _44c6_s_p8_1 = {
  132651. 2, 441,
  132652. _vq_lengthlist__44c6_s_p8_1,
  132653. 1, -529268736, 1611661312, 5, 0,
  132654. _vq_quantlist__44c6_s_p8_1,
  132655. NULL,
  132656. &_vq_auxt__44c6_s_p8_1,
  132657. NULL,
  132658. 0
  132659. };
  132660. static long _vq_quantlist__44c6_s_p9_0[] = {
  132661. 6,
  132662. 5,
  132663. 7,
  132664. 4,
  132665. 8,
  132666. 3,
  132667. 9,
  132668. 2,
  132669. 10,
  132670. 1,
  132671. 11,
  132672. 0,
  132673. 12,
  132674. };
  132675. static long _vq_lengthlist__44c6_s_p9_0[] = {
  132676. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  132677. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  132678. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132679. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  132680. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132681. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132682. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132683. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132684. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132685. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132686. 10,10,10,10,10,10,10,10,10,
  132687. };
  132688. static float _vq_quantthresh__44c6_s_p9_0[] = {
  132689. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  132690. 1592.5, 2229.5, 2866.5, 3503.5,
  132691. };
  132692. static long _vq_quantmap__44c6_s_p9_0[] = {
  132693. 11, 9, 7, 5, 3, 1, 0, 2,
  132694. 4, 6, 8, 10, 12,
  132695. };
  132696. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  132697. _vq_quantthresh__44c6_s_p9_0,
  132698. _vq_quantmap__44c6_s_p9_0,
  132699. 13,
  132700. 13
  132701. };
  132702. static static_codebook _44c6_s_p9_0 = {
  132703. 2, 169,
  132704. _vq_lengthlist__44c6_s_p9_0,
  132705. 1, -511845376, 1630791680, 4, 0,
  132706. _vq_quantlist__44c6_s_p9_0,
  132707. NULL,
  132708. &_vq_auxt__44c6_s_p9_0,
  132709. NULL,
  132710. 0
  132711. };
  132712. static long _vq_quantlist__44c6_s_p9_1[] = {
  132713. 6,
  132714. 5,
  132715. 7,
  132716. 4,
  132717. 8,
  132718. 3,
  132719. 9,
  132720. 2,
  132721. 10,
  132722. 1,
  132723. 11,
  132724. 0,
  132725. 12,
  132726. };
  132727. static long _vq_lengthlist__44c6_s_p9_1[] = {
  132728. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  132729. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  132730. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  132731. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  132732. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  132733. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  132734. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  132735. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  132736. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  132737. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  132738. 15,12,10,11,11,13,11,12,13,
  132739. };
  132740. static float _vq_quantthresh__44c6_s_p9_1[] = {
  132741. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  132742. 122.5, 171.5, 220.5, 269.5,
  132743. };
  132744. static long _vq_quantmap__44c6_s_p9_1[] = {
  132745. 11, 9, 7, 5, 3, 1, 0, 2,
  132746. 4, 6, 8, 10, 12,
  132747. };
  132748. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  132749. _vq_quantthresh__44c6_s_p9_1,
  132750. _vq_quantmap__44c6_s_p9_1,
  132751. 13,
  132752. 13
  132753. };
  132754. static static_codebook _44c6_s_p9_1 = {
  132755. 2, 169,
  132756. _vq_lengthlist__44c6_s_p9_1,
  132757. 1, -518889472, 1622704128, 4, 0,
  132758. _vq_quantlist__44c6_s_p9_1,
  132759. NULL,
  132760. &_vq_auxt__44c6_s_p9_1,
  132761. NULL,
  132762. 0
  132763. };
  132764. static long _vq_quantlist__44c6_s_p9_2[] = {
  132765. 24,
  132766. 23,
  132767. 25,
  132768. 22,
  132769. 26,
  132770. 21,
  132771. 27,
  132772. 20,
  132773. 28,
  132774. 19,
  132775. 29,
  132776. 18,
  132777. 30,
  132778. 17,
  132779. 31,
  132780. 16,
  132781. 32,
  132782. 15,
  132783. 33,
  132784. 14,
  132785. 34,
  132786. 13,
  132787. 35,
  132788. 12,
  132789. 36,
  132790. 11,
  132791. 37,
  132792. 10,
  132793. 38,
  132794. 9,
  132795. 39,
  132796. 8,
  132797. 40,
  132798. 7,
  132799. 41,
  132800. 6,
  132801. 42,
  132802. 5,
  132803. 43,
  132804. 4,
  132805. 44,
  132806. 3,
  132807. 45,
  132808. 2,
  132809. 46,
  132810. 1,
  132811. 47,
  132812. 0,
  132813. 48,
  132814. };
  132815. static long _vq_lengthlist__44c6_s_p9_2[] = {
  132816. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  132817. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132818. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132819. 7,
  132820. };
  132821. static float _vq_quantthresh__44c6_s_p9_2[] = {
  132822. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  132823. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  132824. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132825. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132826. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  132827. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  132828. };
  132829. static long _vq_quantmap__44c6_s_p9_2[] = {
  132830. 47, 45, 43, 41, 39, 37, 35, 33,
  132831. 31, 29, 27, 25, 23, 21, 19, 17,
  132832. 15, 13, 11, 9, 7, 5, 3, 1,
  132833. 0, 2, 4, 6, 8, 10, 12, 14,
  132834. 16, 18, 20, 22, 24, 26, 28, 30,
  132835. 32, 34, 36, 38, 40, 42, 44, 46,
  132836. 48,
  132837. };
  132838. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  132839. _vq_quantthresh__44c6_s_p9_2,
  132840. _vq_quantmap__44c6_s_p9_2,
  132841. 49,
  132842. 49
  132843. };
  132844. static static_codebook _44c6_s_p9_2 = {
  132845. 1, 49,
  132846. _vq_lengthlist__44c6_s_p9_2,
  132847. 1, -526909440, 1611661312, 6, 0,
  132848. _vq_quantlist__44c6_s_p9_2,
  132849. NULL,
  132850. &_vq_auxt__44c6_s_p9_2,
  132851. NULL,
  132852. 0
  132853. };
  132854. static long _huff_lengthlist__44c6_s_short[] = {
  132855. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  132856. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  132857. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  132858. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  132859. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  132860. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  132861. 9,10,17,18,
  132862. };
  132863. static static_codebook _huff_book__44c6_s_short = {
  132864. 2, 100,
  132865. _huff_lengthlist__44c6_s_short,
  132866. 0, 0, 0, 0, 0,
  132867. NULL,
  132868. NULL,
  132869. NULL,
  132870. NULL,
  132871. 0
  132872. };
  132873. static long _huff_lengthlist__44c7_s_long[] = {
  132874. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  132875. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  132876. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  132877. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  132878. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  132879. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  132880. 11,10,10,12,
  132881. };
  132882. static static_codebook _huff_book__44c7_s_long = {
  132883. 2, 100,
  132884. _huff_lengthlist__44c7_s_long,
  132885. 0, 0, 0, 0, 0,
  132886. NULL,
  132887. NULL,
  132888. NULL,
  132889. NULL,
  132890. 0
  132891. };
  132892. static long _vq_quantlist__44c7_s_p1_0[] = {
  132893. 1,
  132894. 0,
  132895. 2,
  132896. };
  132897. static long _vq_lengthlist__44c7_s_p1_0[] = {
  132898. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132899. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132900. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132901. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132902. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  132903. 8,
  132904. };
  132905. static float _vq_quantthresh__44c7_s_p1_0[] = {
  132906. -0.5, 0.5,
  132907. };
  132908. static long _vq_quantmap__44c7_s_p1_0[] = {
  132909. 1, 0, 2,
  132910. };
  132911. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  132912. _vq_quantthresh__44c7_s_p1_0,
  132913. _vq_quantmap__44c7_s_p1_0,
  132914. 3,
  132915. 3
  132916. };
  132917. static static_codebook _44c7_s_p1_0 = {
  132918. 4, 81,
  132919. _vq_lengthlist__44c7_s_p1_0,
  132920. 1, -535822336, 1611661312, 2, 0,
  132921. _vq_quantlist__44c7_s_p1_0,
  132922. NULL,
  132923. &_vq_auxt__44c7_s_p1_0,
  132924. NULL,
  132925. 0
  132926. };
  132927. static long _vq_quantlist__44c7_s_p2_0[] = {
  132928. 2,
  132929. 1,
  132930. 3,
  132931. 0,
  132932. 4,
  132933. };
  132934. static long _vq_lengthlist__44c7_s_p2_0[] = {
  132935. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132936. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132937. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132938. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132939. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  132940. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132941. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  132942. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132944. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132945. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132946. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132947. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132948. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132949. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  132950. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132952. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132953. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  132954. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  132955. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  132956. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  132957. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132958. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132960. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  132961. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132962. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132963. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  132964. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132965. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  132966. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132971. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  132972. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  132973. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132974. 13,
  132975. };
  132976. static float _vq_quantthresh__44c7_s_p2_0[] = {
  132977. -1.5, -0.5, 0.5, 1.5,
  132978. };
  132979. static long _vq_quantmap__44c7_s_p2_0[] = {
  132980. 3, 1, 0, 2, 4,
  132981. };
  132982. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  132983. _vq_quantthresh__44c7_s_p2_0,
  132984. _vq_quantmap__44c7_s_p2_0,
  132985. 5,
  132986. 5
  132987. };
  132988. static static_codebook _44c7_s_p2_0 = {
  132989. 4, 625,
  132990. _vq_lengthlist__44c7_s_p2_0,
  132991. 1, -533725184, 1611661312, 3, 0,
  132992. _vq_quantlist__44c7_s_p2_0,
  132993. NULL,
  132994. &_vq_auxt__44c7_s_p2_0,
  132995. NULL,
  132996. 0
  132997. };
  132998. static long _vq_quantlist__44c7_s_p3_0[] = {
  132999. 4,
  133000. 3,
  133001. 5,
  133002. 2,
  133003. 6,
  133004. 1,
  133005. 7,
  133006. 0,
  133007. 8,
  133008. };
  133009. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133010. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133011. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133012. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133013. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133015. 0,
  133016. };
  133017. static float _vq_quantthresh__44c7_s_p3_0[] = {
  133018. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133019. };
  133020. static long _vq_quantmap__44c7_s_p3_0[] = {
  133021. 7, 5, 3, 1, 0, 2, 4, 6,
  133022. 8,
  133023. };
  133024. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133025. _vq_quantthresh__44c7_s_p3_0,
  133026. _vq_quantmap__44c7_s_p3_0,
  133027. 9,
  133028. 9
  133029. };
  133030. static static_codebook _44c7_s_p3_0 = {
  133031. 2, 81,
  133032. _vq_lengthlist__44c7_s_p3_0,
  133033. 1, -531628032, 1611661312, 4, 0,
  133034. _vq_quantlist__44c7_s_p3_0,
  133035. NULL,
  133036. &_vq_auxt__44c7_s_p3_0,
  133037. NULL,
  133038. 0
  133039. };
  133040. static long _vq_quantlist__44c7_s_p4_0[] = {
  133041. 8,
  133042. 7,
  133043. 9,
  133044. 6,
  133045. 10,
  133046. 5,
  133047. 11,
  133048. 4,
  133049. 12,
  133050. 3,
  133051. 13,
  133052. 2,
  133053. 14,
  133054. 1,
  133055. 15,
  133056. 0,
  133057. 16,
  133058. };
  133059. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133060. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133061. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133062. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133063. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133064. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133065. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133066. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133067. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133068. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133069. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133073. 0, 0, 0, 0, 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, 0,
  133078. 0,
  133079. };
  133080. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133081. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133082. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133083. };
  133084. static long _vq_quantmap__44c7_s_p4_0[] = {
  133085. 15, 13, 11, 9, 7, 5, 3, 1,
  133086. 0, 2, 4, 6, 8, 10, 12, 14,
  133087. 16,
  133088. };
  133089. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133090. _vq_quantthresh__44c7_s_p4_0,
  133091. _vq_quantmap__44c7_s_p4_0,
  133092. 17,
  133093. 17
  133094. };
  133095. static static_codebook _44c7_s_p4_0 = {
  133096. 2, 289,
  133097. _vq_lengthlist__44c7_s_p4_0,
  133098. 1, -529530880, 1611661312, 5, 0,
  133099. _vq_quantlist__44c7_s_p4_0,
  133100. NULL,
  133101. &_vq_auxt__44c7_s_p4_0,
  133102. NULL,
  133103. 0
  133104. };
  133105. static long _vq_quantlist__44c7_s_p5_0[] = {
  133106. 1,
  133107. 0,
  133108. 2,
  133109. };
  133110. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133111. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133112. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133113. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133114. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133115. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133116. 12,
  133117. };
  133118. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133119. -5.5, 5.5,
  133120. };
  133121. static long _vq_quantmap__44c7_s_p5_0[] = {
  133122. 1, 0, 2,
  133123. };
  133124. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133125. _vq_quantthresh__44c7_s_p5_0,
  133126. _vq_quantmap__44c7_s_p5_0,
  133127. 3,
  133128. 3
  133129. };
  133130. static static_codebook _44c7_s_p5_0 = {
  133131. 4, 81,
  133132. _vq_lengthlist__44c7_s_p5_0,
  133133. 1, -529137664, 1618345984, 2, 0,
  133134. _vq_quantlist__44c7_s_p5_0,
  133135. NULL,
  133136. &_vq_auxt__44c7_s_p5_0,
  133137. NULL,
  133138. 0
  133139. };
  133140. static long _vq_quantlist__44c7_s_p5_1[] = {
  133141. 5,
  133142. 4,
  133143. 6,
  133144. 3,
  133145. 7,
  133146. 2,
  133147. 8,
  133148. 1,
  133149. 9,
  133150. 0,
  133151. 10,
  133152. };
  133153. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133154. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133155. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133156. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133157. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133158. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133159. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133160. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133161. 11,11,11, 7, 7, 8, 8, 8, 8,
  133162. };
  133163. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133164. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133165. 3.5, 4.5,
  133166. };
  133167. static long _vq_quantmap__44c7_s_p5_1[] = {
  133168. 9, 7, 5, 3, 1, 0, 2, 4,
  133169. 6, 8, 10,
  133170. };
  133171. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133172. _vq_quantthresh__44c7_s_p5_1,
  133173. _vq_quantmap__44c7_s_p5_1,
  133174. 11,
  133175. 11
  133176. };
  133177. static static_codebook _44c7_s_p5_1 = {
  133178. 2, 121,
  133179. _vq_lengthlist__44c7_s_p5_1,
  133180. 1, -531365888, 1611661312, 4, 0,
  133181. _vq_quantlist__44c7_s_p5_1,
  133182. NULL,
  133183. &_vq_auxt__44c7_s_p5_1,
  133184. NULL,
  133185. 0
  133186. };
  133187. static long _vq_quantlist__44c7_s_p6_0[] = {
  133188. 6,
  133189. 5,
  133190. 7,
  133191. 4,
  133192. 8,
  133193. 3,
  133194. 9,
  133195. 2,
  133196. 10,
  133197. 1,
  133198. 11,
  133199. 0,
  133200. 12,
  133201. };
  133202. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133203. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133204. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133205. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133206. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133207. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133208. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133213. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133214. };
  133215. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133216. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133217. 12.5, 17.5, 22.5, 27.5,
  133218. };
  133219. static long _vq_quantmap__44c7_s_p6_0[] = {
  133220. 11, 9, 7, 5, 3, 1, 0, 2,
  133221. 4, 6, 8, 10, 12,
  133222. };
  133223. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133224. _vq_quantthresh__44c7_s_p6_0,
  133225. _vq_quantmap__44c7_s_p6_0,
  133226. 13,
  133227. 13
  133228. };
  133229. static static_codebook _44c7_s_p6_0 = {
  133230. 2, 169,
  133231. _vq_lengthlist__44c7_s_p6_0,
  133232. 1, -526516224, 1616117760, 4, 0,
  133233. _vq_quantlist__44c7_s_p6_0,
  133234. NULL,
  133235. &_vq_auxt__44c7_s_p6_0,
  133236. NULL,
  133237. 0
  133238. };
  133239. static long _vq_quantlist__44c7_s_p6_1[] = {
  133240. 2,
  133241. 1,
  133242. 3,
  133243. 0,
  133244. 4,
  133245. };
  133246. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133247. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133248. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133249. };
  133250. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133251. -1.5, -0.5, 0.5, 1.5,
  133252. };
  133253. static long _vq_quantmap__44c7_s_p6_1[] = {
  133254. 3, 1, 0, 2, 4,
  133255. };
  133256. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133257. _vq_quantthresh__44c7_s_p6_1,
  133258. _vq_quantmap__44c7_s_p6_1,
  133259. 5,
  133260. 5
  133261. };
  133262. static static_codebook _44c7_s_p6_1 = {
  133263. 2, 25,
  133264. _vq_lengthlist__44c7_s_p6_1,
  133265. 1, -533725184, 1611661312, 3, 0,
  133266. _vq_quantlist__44c7_s_p6_1,
  133267. NULL,
  133268. &_vq_auxt__44c7_s_p6_1,
  133269. NULL,
  133270. 0
  133271. };
  133272. static long _vq_quantlist__44c7_s_p7_0[] = {
  133273. 6,
  133274. 5,
  133275. 7,
  133276. 4,
  133277. 8,
  133278. 3,
  133279. 9,
  133280. 2,
  133281. 10,
  133282. 1,
  133283. 11,
  133284. 0,
  133285. 12,
  133286. };
  133287. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133288. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133289. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133290. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133291. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133292. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133293. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133294. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133295. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133296. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133297. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133298. 19,13,13,13,13,14,14,15,15,
  133299. };
  133300. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133301. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133302. 27.5, 38.5, 49.5, 60.5,
  133303. };
  133304. static long _vq_quantmap__44c7_s_p7_0[] = {
  133305. 11, 9, 7, 5, 3, 1, 0, 2,
  133306. 4, 6, 8, 10, 12,
  133307. };
  133308. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133309. _vq_quantthresh__44c7_s_p7_0,
  133310. _vq_quantmap__44c7_s_p7_0,
  133311. 13,
  133312. 13
  133313. };
  133314. static static_codebook _44c7_s_p7_0 = {
  133315. 2, 169,
  133316. _vq_lengthlist__44c7_s_p7_0,
  133317. 1, -523206656, 1618345984, 4, 0,
  133318. _vq_quantlist__44c7_s_p7_0,
  133319. NULL,
  133320. &_vq_auxt__44c7_s_p7_0,
  133321. NULL,
  133322. 0
  133323. };
  133324. static long _vq_quantlist__44c7_s_p7_1[] = {
  133325. 5,
  133326. 4,
  133327. 6,
  133328. 3,
  133329. 7,
  133330. 2,
  133331. 8,
  133332. 1,
  133333. 9,
  133334. 0,
  133335. 10,
  133336. };
  133337. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133338. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133339. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133340. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133341. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133342. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133343. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133344. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133345. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133346. };
  133347. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133348. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133349. 3.5, 4.5,
  133350. };
  133351. static long _vq_quantmap__44c7_s_p7_1[] = {
  133352. 9, 7, 5, 3, 1, 0, 2, 4,
  133353. 6, 8, 10,
  133354. };
  133355. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133356. _vq_quantthresh__44c7_s_p7_1,
  133357. _vq_quantmap__44c7_s_p7_1,
  133358. 11,
  133359. 11
  133360. };
  133361. static static_codebook _44c7_s_p7_1 = {
  133362. 2, 121,
  133363. _vq_lengthlist__44c7_s_p7_1,
  133364. 1, -531365888, 1611661312, 4, 0,
  133365. _vq_quantlist__44c7_s_p7_1,
  133366. NULL,
  133367. &_vq_auxt__44c7_s_p7_1,
  133368. NULL,
  133369. 0
  133370. };
  133371. static long _vq_quantlist__44c7_s_p8_0[] = {
  133372. 7,
  133373. 6,
  133374. 8,
  133375. 5,
  133376. 9,
  133377. 4,
  133378. 10,
  133379. 3,
  133380. 11,
  133381. 2,
  133382. 12,
  133383. 1,
  133384. 13,
  133385. 0,
  133386. 14,
  133387. };
  133388. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133389. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133390. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133391. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133392. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133393. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133394. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133395. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133396. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133397. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133398. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133399. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133400. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133401. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133402. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133403. 14,
  133404. };
  133405. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133406. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133407. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133408. };
  133409. static long _vq_quantmap__44c7_s_p8_0[] = {
  133410. 13, 11, 9, 7, 5, 3, 1, 0,
  133411. 2, 4, 6, 8, 10, 12, 14,
  133412. };
  133413. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133414. _vq_quantthresh__44c7_s_p8_0,
  133415. _vq_quantmap__44c7_s_p8_0,
  133416. 15,
  133417. 15
  133418. };
  133419. static static_codebook _44c7_s_p8_0 = {
  133420. 2, 225,
  133421. _vq_lengthlist__44c7_s_p8_0,
  133422. 1, -520986624, 1620377600, 4, 0,
  133423. _vq_quantlist__44c7_s_p8_0,
  133424. NULL,
  133425. &_vq_auxt__44c7_s_p8_0,
  133426. NULL,
  133427. 0
  133428. };
  133429. static long _vq_quantlist__44c7_s_p8_1[] = {
  133430. 10,
  133431. 9,
  133432. 11,
  133433. 8,
  133434. 12,
  133435. 7,
  133436. 13,
  133437. 6,
  133438. 14,
  133439. 5,
  133440. 15,
  133441. 4,
  133442. 16,
  133443. 3,
  133444. 17,
  133445. 2,
  133446. 18,
  133447. 1,
  133448. 19,
  133449. 0,
  133450. 20,
  133451. };
  133452. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133453. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133454. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133455. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133456. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133457. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133458. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133459. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133460. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133461. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133462. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133463. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133464. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133465. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133466. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133467. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133468. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133469. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133470. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133471. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133472. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133473. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133474. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133475. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133476. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133477. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133478. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133479. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133480. 10,10,10,10,10,10,10,10,10,
  133481. };
  133482. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133483. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133484. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133485. 6.5, 7.5, 8.5, 9.5,
  133486. };
  133487. static long _vq_quantmap__44c7_s_p8_1[] = {
  133488. 19, 17, 15, 13, 11, 9, 7, 5,
  133489. 3, 1, 0, 2, 4, 6, 8, 10,
  133490. 12, 14, 16, 18, 20,
  133491. };
  133492. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  133493. _vq_quantthresh__44c7_s_p8_1,
  133494. _vq_quantmap__44c7_s_p8_1,
  133495. 21,
  133496. 21
  133497. };
  133498. static static_codebook _44c7_s_p8_1 = {
  133499. 2, 441,
  133500. _vq_lengthlist__44c7_s_p8_1,
  133501. 1, -529268736, 1611661312, 5, 0,
  133502. _vq_quantlist__44c7_s_p8_1,
  133503. NULL,
  133504. &_vq_auxt__44c7_s_p8_1,
  133505. NULL,
  133506. 0
  133507. };
  133508. static long _vq_quantlist__44c7_s_p9_0[] = {
  133509. 6,
  133510. 5,
  133511. 7,
  133512. 4,
  133513. 8,
  133514. 3,
  133515. 9,
  133516. 2,
  133517. 10,
  133518. 1,
  133519. 11,
  133520. 0,
  133521. 12,
  133522. };
  133523. static long _vq_lengthlist__44c7_s_p9_0[] = {
  133524. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  133525. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  133526. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133527. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133528. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133529. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133530. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133531. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133532. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133533. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133534. 11,11,11,11,11,11,11,11,11,
  133535. };
  133536. static float _vq_quantthresh__44c7_s_p9_0[] = {
  133537. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133538. 1592.5, 2229.5, 2866.5, 3503.5,
  133539. };
  133540. static long _vq_quantmap__44c7_s_p9_0[] = {
  133541. 11, 9, 7, 5, 3, 1, 0, 2,
  133542. 4, 6, 8, 10, 12,
  133543. };
  133544. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  133545. _vq_quantthresh__44c7_s_p9_0,
  133546. _vq_quantmap__44c7_s_p9_0,
  133547. 13,
  133548. 13
  133549. };
  133550. static static_codebook _44c7_s_p9_0 = {
  133551. 2, 169,
  133552. _vq_lengthlist__44c7_s_p9_0,
  133553. 1, -511845376, 1630791680, 4, 0,
  133554. _vq_quantlist__44c7_s_p9_0,
  133555. NULL,
  133556. &_vq_auxt__44c7_s_p9_0,
  133557. NULL,
  133558. 0
  133559. };
  133560. static long _vq_quantlist__44c7_s_p9_1[] = {
  133561. 6,
  133562. 5,
  133563. 7,
  133564. 4,
  133565. 8,
  133566. 3,
  133567. 9,
  133568. 2,
  133569. 10,
  133570. 1,
  133571. 11,
  133572. 0,
  133573. 12,
  133574. };
  133575. static long _vq_lengthlist__44c7_s_p9_1[] = {
  133576. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133577. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  133578. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  133579. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  133580. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  133581. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  133582. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  133583. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  133584. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  133585. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  133586. 15,11,11,10,10,12,12,12,12,
  133587. };
  133588. static float _vq_quantthresh__44c7_s_p9_1[] = {
  133589. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133590. 122.5, 171.5, 220.5, 269.5,
  133591. };
  133592. static long _vq_quantmap__44c7_s_p9_1[] = {
  133593. 11, 9, 7, 5, 3, 1, 0, 2,
  133594. 4, 6, 8, 10, 12,
  133595. };
  133596. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  133597. _vq_quantthresh__44c7_s_p9_1,
  133598. _vq_quantmap__44c7_s_p9_1,
  133599. 13,
  133600. 13
  133601. };
  133602. static static_codebook _44c7_s_p9_1 = {
  133603. 2, 169,
  133604. _vq_lengthlist__44c7_s_p9_1,
  133605. 1, -518889472, 1622704128, 4, 0,
  133606. _vq_quantlist__44c7_s_p9_1,
  133607. NULL,
  133608. &_vq_auxt__44c7_s_p9_1,
  133609. NULL,
  133610. 0
  133611. };
  133612. static long _vq_quantlist__44c7_s_p9_2[] = {
  133613. 24,
  133614. 23,
  133615. 25,
  133616. 22,
  133617. 26,
  133618. 21,
  133619. 27,
  133620. 20,
  133621. 28,
  133622. 19,
  133623. 29,
  133624. 18,
  133625. 30,
  133626. 17,
  133627. 31,
  133628. 16,
  133629. 32,
  133630. 15,
  133631. 33,
  133632. 14,
  133633. 34,
  133634. 13,
  133635. 35,
  133636. 12,
  133637. 36,
  133638. 11,
  133639. 37,
  133640. 10,
  133641. 38,
  133642. 9,
  133643. 39,
  133644. 8,
  133645. 40,
  133646. 7,
  133647. 41,
  133648. 6,
  133649. 42,
  133650. 5,
  133651. 43,
  133652. 4,
  133653. 44,
  133654. 3,
  133655. 45,
  133656. 2,
  133657. 46,
  133658. 1,
  133659. 47,
  133660. 0,
  133661. 48,
  133662. };
  133663. static long _vq_lengthlist__44c7_s_p9_2[] = {
  133664. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133665. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133666. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133667. 7,
  133668. };
  133669. static float _vq_quantthresh__44c7_s_p9_2[] = {
  133670. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133671. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133672. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133673. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133674. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133675. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133676. };
  133677. static long _vq_quantmap__44c7_s_p9_2[] = {
  133678. 47, 45, 43, 41, 39, 37, 35, 33,
  133679. 31, 29, 27, 25, 23, 21, 19, 17,
  133680. 15, 13, 11, 9, 7, 5, 3, 1,
  133681. 0, 2, 4, 6, 8, 10, 12, 14,
  133682. 16, 18, 20, 22, 24, 26, 28, 30,
  133683. 32, 34, 36, 38, 40, 42, 44, 46,
  133684. 48,
  133685. };
  133686. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  133687. _vq_quantthresh__44c7_s_p9_2,
  133688. _vq_quantmap__44c7_s_p9_2,
  133689. 49,
  133690. 49
  133691. };
  133692. static static_codebook _44c7_s_p9_2 = {
  133693. 1, 49,
  133694. _vq_lengthlist__44c7_s_p9_2,
  133695. 1, -526909440, 1611661312, 6, 0,
  133696. _vq_quantlist__44c7_s_p9_2,
  133697. NULL,
  133698. &_vq_auxt__44c7_s_p9_2,
  133699. NULL,
  133700. 0
  133701. };
  133702. static long _huff_lengthlist__44c7_s_short[] = {
  133703. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  133704. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  133705. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  133706. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  133707. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  133708. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  133709. 10, 9,11,14,
  133710. };
  133711. static static_codebook _huff_book__44c7_s_short = {
  133712. 2, 100,
  133713. _huff_lengthlist__44c7_s_short,
  133714. 0, 0, 0, 0, 0,
  133715. NULL,
  133716. NULL,
  133717. NULL,
  133718. NULL,
  133719. 0
  133720. };
  133721. static long _huff_lengthlist__44c8_s_long[] = {
  133722. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  133723. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  133724. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  133725. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  133726. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  133727. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  133728. 11, 9, 9,10,
  133729. };
  133730. static static_codebook _huff_book__44c8_s_long = {
  133731. 2, 100,
  133732. _huff_lengthlist__44c8_s_long,
  133733. 0, 0, 0, 0, 0,
  133734. NULL,
  133735. NULL,
  133736. NULL,
  133737. NULL,
  133738. 0
  133739. };
  133740. static long _vq_quantlist__44c8_s_p1_0[] = {
  133741. 1,
  133742. 0,
  133743. 2,
  133744. };
  133745. static long _vq_lengthlist__44c8_s_p1_0[] = {
  133746. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  133747. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133748. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133749. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133750. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133751. 8,
  133752. };
  133753. static float _vq_quantthresh__44c8_s_p1_0[] = {
  133754. -0.5, 0.5,
  133755. };
  133756. static long _vq_quantmap__44c8_s_p1_0[] = {
  133757. 1, 0, 2,
  133758. };
  133759. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  133760. _vq_quantthresh__44c8_s_p1_0,
  133761. _vq_quantmap__44c8_s_p1_0,
  133762. 3,
  133763. 3
  133764. };
  133765. static static_codebook _44c8_s_p1_0 = {
  133766. 4, 81,
  133767. _vq_lengthlist__44c8_s_p1_0,
  133768. 1, -535822336, 1611661312, 2, 0,
  133769. _vq_quantlist__44c8_s_p1_0,
  133770. NULL,
  133771. &_vq_auxt__44c8_s_p1_0,
  133772. NULL,
  133773. 0
  133774. };
  133775. static long _vq_quantlist__44c8_s_p2_0[] = {
  133776. 2,
  133777. 1,
  133778. 3,
  133779. 0,
  133780. 4,
  133781. };
  133782. static long _vq_lengthlist__44c8_s_p2_0[] = {
  133783. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133784. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133785. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133786. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  133787. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133788. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  133789. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  133790. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133792. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133793. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  133794. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133795. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  133796. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  133797. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  133798. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  133799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133800. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  133801. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  133802. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  133803. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  133804. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  133805. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  133806. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133808. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133809. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  133810. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133811. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  133812. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  133813. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  133814. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133819. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  133820. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133821. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  133822. 13,
  133823. };
  133824. static float _vq_quantthresh__44c8_s_p2_0[] = {
  133825. -1.5, -0.5, 0.5, 1.5,
  133826. };
  133827. static long _vq_quantmap__44c8_s_p2_0[] = {
  133828. 3, 1, 0, 2, 4,
  133829. };
  133830. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  133831. _vq_quantthresh__44c8_s_p2_0,
  133832. _vq_quantmap__44c8_s_p2_0,
  133833. 5,
  133834. 5
  133835. };
  133836. static static_codebook _44c8_s_p2_0 = {
  133837. 4, 625,
  133838. _vq_lengthlist__44c8_s_p2_0,
  133839. 1, -533725184, 1611661312, 3, 0,
  133840. _vq_quantlist__44c8_s_p2_0,
  133841. NULL,
  133842. &_vq_auxt__44c8_s_p2_0,
  133843. NULL,
  133844. 0
  133845. };
  133846. static long _vq_quantlist__44c8_s_p3_0[] = {
  133847. 4,
  133848. 3,
  133849. 5,
  133850. 2,
  133851. 6,
  133852. 1,
  133853. 7,
  133854. 0,
  133855. 8,
  133856. };
  133857. static long _vq_lengthlist__44c8_s_p3_0[] = {
  133858. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133859. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133860. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133861. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133863. 0,
  133864. };
  133865. static float _vq_quantthresh__44c8_s_p3_0[] = {
  133866. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133867. };
  133868. static long _vq_quantmap__44c8_s_p3_0[] = {
  133869. 7, 5, 3, 1, 0, 2, 4, 6,
  133870. 8,
  133871. };
  133872. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  133873. _vq_quantthresh__44c8_s_p3_0,
  133874. _vq_quantmap__44c8_s_p3_0,
  133875. 9,
  133876. 9
  133877. };
  133878. static static_codebook _44c8_s_p3_0 = {
  133879. 2, 81,
  133880. _vq_lengthlist__44c8_s_p3_0,
  133881. 1, -531628032, 1611661312, 4, 0,
  133882. _vq_quantlist__44c8_s_p3_0,
  133883. NULL,
  133884. &_vq_auxt__44c8_s_p3_0,
  133885. NULL,
  133886. 0
  133887. };
  133888. static long _vq_quantlist__44c8_s_p4_0[] = {
  133889. 8,
  133890. 7,
  133891. 9,
  133892. 6,
  133893. 10,
  133894. 5,
  133895. 11,
  133896. 4,
  133897. 12,
  133898. 3,
  133899. 13,
  133900. 2,
  133901. 14,
  133902. 1,
  133903. 15,
  133904. 0,
  133905. 16,
  133906. };
  133907. static long _vq_lengthlist__44c8_s_p4_0[] = {
  133908. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133909. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  133910. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133911. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  133912. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  133913. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133914. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133915. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133916. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133917. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133921. 0, 0, 0, 0, 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, 0,
  133926. 0,
  133927. };
  133928. static float _vq_quantthresh__44c8_s_p4_0[] = {
  133929. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133930. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133931. };
  133932. static long _vq_quantmap__44c8_s_p4_0[] = {
  133933. 15, 13, 11, 9, 7, 5, 3, 1,
  133934. 0, 2, 4, 6, 8, 10, 12, 14,
  133935. 16,
  133936. };
  133937. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  133938. _vq_quantthresh__44c8_s_p4_0,
  133939. _vq_quantmap__44c8_s_p4_0,
  133940. 17,
  133941. 17
  133942. };
  133943. static static_codebook _44c8_s_p4_0 = {
  133944. 2, 289,
  133945. _vq_lengthlist__44c8_s_p4_0,
  133946. 1, -529530880, 1611661312, 5, 0,
  133947. _vq_quantlist__44c8_s_p4_0,
  133948. NULL,
  133949. &_vq_auxt__44c8_s_p4_0,
  133950. NULL,
  133951. 0
  133952. };
  133953. static long _vq_quantlist__44c8_s_p5_0[] = {
  133954. 1,
  133955. 0,
  133956. 2,
  133957. };
  133958. static long _vq_lengthlist__44c8_s_p5_0[] = {
  133959. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  133960. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133961. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133962. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  133963. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  133964. 12,
  133965. };
  133966. static float _vq_quantthresh__44c8_s_p5_0[] = {
  133967. -5.5, 5.5,
  133968. };
  133969. static long _vq_quantmap__44c8_s_p5_0[] = {
  133970. 1, 0, 2,
  133971. };
  133972. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  133973. _vq_quantthresh__44c8_s_p5_0,
  133974. _vq_quantmap__44c8_s_p5_0,
  133975. 3,
  133976. 3
  133977. };
  133978. static static_codebook _44c8_s_p5_0 = {
  133979. 4, 81,
  133980. _vq_lengthlist__44c8_s_p5_0,
  133981. 1, -529137664, 1618345984, 2, 0,
  133982. _vq_quantlist__44c8_s_p5_0,
  133983. NULL,
  133984. &_vq_auxt__44c8_s_p5_0,
  133985. NULL,
  133986. 0
  133987. };
  133988. static long _vq_quantlist__44c8_s_p5_1[] = {
  133989. 5,
  133990. 4,
  133991. 6,
  133992. 3,
  133993. 7,
  133994. 2,
  133995. 8,
  133996. 1,
  133997. 9,
  133998. 0,
  133999. 10,
  134000. };
  134001. static long _vq_lengthlist__44c8_s_p5_1[] = {
  134002. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  134003. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134004. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  134005. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  134006. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134007. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134008. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134009. 11,11,11, 7, 7, 7, 7, 8, 8,
  134010. };
  134011. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134012. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134013. 3.5, 4.5,
  134014. };
  134015. static long _vq_quantmap__44c8_s_p5_1[] = {
  134016. 9, 7, 5, 3, 1, 0, 2, 4,
  134017. 6, 8, 10,
  134018. };
  134019. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134020. _vq_quantthresh__44c8_s_p5_1,
  134021. _vq_quantmap__44c8_s_p5_1,
  134022. 11,
  134023. 11
  134024. };
  134025. static static_codebook _44c8_s_p5_1 = {
  134026. 2, 121,
  134027. _vq_lengthlist__44c8_s_p5_1,
  134028. 1, -531365888, 1611661312, 4, 0,
  134029. _vq_quantlist__44c8_s_p5_1,
  134030. NULL,
  134031. &_vq_auxt__44c8_s_p5_1,
  134032. NULL,
  134033. 0
  134034. };
  134035. static long _vq_quantlist__44c8_s_p6_0[] = {
  134036. 6,
  134037. 5,
  134038. 7,
  134039. 4,
  134040. 8,
  134041. 3,
  134042. 9,
  134043. 2,
  134044. 10,
  134045. 1,
  134046. 11,
  134047. 0,
  134048. 12,
  134049. };
  134050. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134051. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134052. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134053. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134054. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134055. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134056. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134061. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134062. };
  134063. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134064. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134065. 12.5, 17.5, 22.5, 27.5,
  134066. };
  134067. static long _vq_quantmap__44c8_s_p6_0[] = {
  134068. 11, 9, 7, 5, 3, 1, 0, 2,
  134069. 4, 6, 8, 10, 12,
  134070. };
  134071. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134072. _vq_quantthresh__44c8_s_p6_0,
  134073. _vq_quantmap__44c8_s_p6_0,
  134074. 13,
  134075. 13
  134076. };
  134077. static static_codebook _44c8_s_p6_0 = {
  134078. 2, 169,
  134079. _vq_lengthlist__44c8_s_p6_0,
  134080. 1, -526516224, 1616117760, 4, 0,
  134081. _vq_quantlist__44c8_s_p6_0,
  134082. NULL,
  134083. &_vq_auxt__44c8_s_p6_0,
  134084. NULL,
  134085. 0
  134086. };
  134087. static long _vq_quantlist__44c8_s_p6_1[] = {
  134088. 2,
  134089. 1,
  134090. 3,
  134091. 0,
  134092. 4,
  134093. };
  134094. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134095. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134096. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134097. };
  134098. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134099. -1.5, -0.5, 0.5, 1.5,
  134100. };
  134101. static long _vq_quantmap__44c8_s_p6_1[] = {
  134102. 3, 1, 0, 2, 4,
  134103. };
  134104. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134105. _vq_quantthresh__44c8_s_p6_1,
  134106. _vq_quantmap__44c8_s_p6_1,
  134107. 5,
  134108. 5
  134109. };
  134110. static static_codebook _44c8_s_p6_1 = {
  134111. 2, 25,
  134112. _vq_lengthlist__44c8_s_p6_1,
  134113. 1, -533725184, 1611661312, 3, 0,
  134114. _vq_quantlist__44c8_s_p6_1,
  134115. NULL,
  134116. &_vq_auxt__44c8_s_p6_1,
  134117. NULL,
  134118. 0
  134119. };
  134120. static long _vq_quantlist__44c8_s_p7_0[] = {
  134121. 6,
  134122. 5,
  134123. 7,
  134124. 4,
  134125. 8,
  134126. 3,
  134127. 9,
  134128. 2,
  134129. 10,
  134130. 1,
  134131. 11,
  134132. 0,
  134133. 12,
  134134. };
  134135. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134136. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134137. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134138. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134139. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134140. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134141. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134142. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134143. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134144. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134145. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134146. 20,13,13,13,13,14,13,15,15,
  134147. };
  134148. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134149. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134150. 27.5, 38.5, 49.5, 60.5,
  134151. };
  134152. static long _vq_quantmap__44c8_s_p7_0[] = {
  134153. 11, 9, 7, 5, 3, 1, 0, 2,
  134154. 4, 6, 8, 10, 12,
  134155. };
  134156. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134157. _vq_quantthresh__44c8_s_p7_0,
  134158. _vq_quantmap__44c8_s_p7_0,
  134159. 13,
  134160. 13
  134161. };
  134162. static static_codebook _44c8_s_p7_0 = {
  134163. 2, 169,
  134164. _vq_lengthlist__44c8_s_p7_0,
  134165. 1, -523206656, 1618345984, 4, 0,
  134166. _vq_quantlist__44c8_s_p7_0,
  134167. NULL,
  134168. &_vq_auxt__44c8_s_p7_0,
  134169. NULL,
  134170. 0
  134171. };
  134172. static long _vq_quantlist__44c8_s_p7_1[] = {
  134173. 5,
  134174. 4,
  134175. 6,
  134176. 3,
  134177. 7,
  134178. 2,
  134179. 8,
  134180. 1,
  134181. 9,
  134182. 0,
  134183. 10,
  134184. };
  134185. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134186. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134187. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134188. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134189. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134190. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134191. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134192. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134193. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134194. };
  134195. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134196. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134197. 3.5, 4.5,
  134198. };
  134199. static long _vq_quantmap__44c8_s_p7_1[] = {
  134200. 9, 7, 5, 3, 1, 0, 2, 4,
  134201. 6, 8, 10,
  134202. };
  134203. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134204. _vq_quantthresh__44c8_s_p7_1,
  134205. _vq_quantmap__44c8_s_p7_1,
  134206. 11,
  134207. 11
  134208. };
  134209. static static_codebook _44c8_s_p7_1 = {
  134210. 2, 121,
  134211. _vq_lengthlist__44c8_s_p7_1,
  134212. 1, -531365888, 1611661312, 4, 0,
  134213. _vq_quantlist__44c8_s_p7_1,
  134214. NULL,
  134215. &_vq_auxt__44c8_s_p7_1,
  134216. NULL,
  134217. 0
  134218. };
  134219. static long _vq_quantlist__44c8_s_p8_0[] = {
  134220. 7,
  134221. 6,
  134222. 8,
  134223. 5,
  134224. 9,
  134225. 4,
  134226. 10,
  134227. 3,
  134228. 11,
  134229. 2,
  134230. 12,
  134231. 1,
  134232. 13,
  134233. 0,
  134234. 14,
  134235. };
  134236. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134237. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134238. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134239. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134240. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134241. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134242. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134243. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134244. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134245. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134246. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134247. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134248. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134249. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134250. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134251. 15,
  134252. };
  134253. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134254. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134255. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134256. };
  134257. static long _vq_quantmap__44c8_s_p8_0[] = {
  134258. 13, 11, 9, 7, 5, 3, 1, 0,
  134259. 2, 4, 6, 8, 10, 12, 14,
  134260. };
  134261. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134262. _vq_quantthresh__44c8_s_p8_0,
  134263. _vq_quantmap__44c8_s_p8_0,
  134264. 15,
  134265. 15
  134266. };
  134267. static static_codebook _44c8_s_p8_0 = {
  134268. 2, 225,
  134269. _vq_lengthlist__44c8_s_p8_0,
  134270. 1, -520986624, 1620377600, 4, 0,
  134271. _vq_quantlist__44c8_s_p8_0,
  134272. NULL,
  134273. &_vq_auxt__44c8_s_p8_0,
  134274. NULL,
  134275. 0
  134276. };
  134277. static long _vq_quantlist__44c8_s_p8_1[] = {
  134278. 10,
  134279. 9,
  134280. 11,
  134281. 8,
  134282. 12,
  134283. 7,
  134284. 13,
  134285. 6,
  134286. 14,
  134287. 5,
  134288. 15,
  134289. 4,
  134290. 16,
  134291. 3,
  134292. 17,
  134293. 2,
  134294. 18,
  134295. 1,
  134296. 19,
  134297. 0,
  134298. 20,
  134299. };
  134300. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134301. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134302. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134303. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134304. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134305. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134306. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134307. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134308. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134309. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134310. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134311. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134312. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134313. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134314. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134315. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134316. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134317. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134318. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134319. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134320. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134321. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134322. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134323. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134324. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134325. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134326. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134327. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134328. 10, 9, 9,10,10, 9,10, 9, 9,
  134329. };
  134330. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134331. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134332. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134333. 6.5, 7.5, 8.5, 9.5,
  134334. };
  134335. static long _vq_quantmap__44c8_s_p8_1[] = {
  134336. 19, 17, 15, 13, 11, 9, 7, 5,
  134337. 3, 1, 0, 2, 4, 6, 8, 10,
  134338. 12, 14, 16, 18, 20,
  134339. };
  134340. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134341. _vq_quantthresh__44c8_s_p8_1,
  134342. _vq_quantmap__44c8_s_p8_1,
  134343. 21,
  134344. 21
  134345. };
  134346. static static_codebook _44c8_s_p8_1 = {
  134347. 2, 441,
  134348. _vq_lengthlist__44c8_s_p8_1,
  134349. 1, -529268736, 1611661312, 5, 0,
  134350. _vq_quantlist__44c8_s_p8_1,
  134351. NULL,
  134352. &_vq_auxt__44c8_s_p8_1,
  134353. NULL,
  134354. 0
  134355. };
  134356. static long _vq_quantlist__44c8_s_p9_0[] = {
  134357. 8,
  134358. 7,
  134359. 9,
  134360. 6,
  134361. 10,
  134362. 5,
  134363. 11,
  134364. 4,
  134365. 12,
  134366. 3,
  134367. 13,
  134368. 2,
  134369. 14,
  134370. 1,
  134371. 15,
  134372. 0,
  134373. 16,
  134374. };
  134375. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134376. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134377. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134378. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134379. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134380. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134381. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134382. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134383. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134384. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134385. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134386. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134387. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134388. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134389. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134390. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134391. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134392. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134393. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134394. 10,
  134395. };
  134396. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134397. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134398. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134399. };
  134400. static long _vq_quantmap__44c8_s_p9_0[] = {
  134401. 15, 13, 11, 9, 7, 5, 3, 1,
  134402. 0, 2, 4, 6, 8, 10, 12, 14,
  134403. 16,
  134404. };
  134405. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134406. _vq_quantthresh__44c8_s_p9_0,
  134407. _vq_quantmap__44c8_s_p9_0,
  134408. 17,
  134409. 17
  134410. };
  134411. static static_codebook _44c8_s_p9_0 = {
  134412. 2, 289,
  134413. _vq_lengthlist__44c8_s_p9_0,
  134414. 1, -509798400, 1631393792, 5, 0,
  134415. _vq_quantlist__44c8_s_p9_0,
  134416. NULL,
  134417. &_vq_auxt__44c8_s_p9_0,
  134418. NULL,
  134419. 0
  134420. };
  134421. static long _vq_quantlist__44c8_s_p9_1[] = {
  134422. 9,
  134423. 8,
  134424. 10,
  134425. 7,
  134426. 11,
  134427. 6,
  134428. 12,
  134429. 5,
  134430. 13,
  134431. 4,
  134432. 14,
  134433. 3,
  134434. 15,
  134435. 2,
  134436. 16,
  134437. 1,
  134438. 17,
  134439. 0,
  134440. 18,
  134441. };
  134442. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134443. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134444. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134445. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134446. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134447. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134448. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134449. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134450. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134451. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134452. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134453. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134454. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134455. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134456. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134457. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134458. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134459. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134460. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134461. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134462. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134463. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134464. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134465. 14,13,13,14,14,15,14,15,14,
  134466. };
  134467. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134468. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134469. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134470. 367.5, 416.5,
  134471. };
  134472. static long _vq_quantmap__44c8_s_p9_1[] = {
  134473. 17, 15, 13, 11, 9, 7, 5, 3,
  134474. 1, 0, 2, 4, 6, 8, 10, 12,
  134475. 14, 16, 18,
  134476. };
  134477. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134478. _vq_quantthresh__44c8_s_p9_1,
  134479. _vq_quantmap__44c8_s_p9_1,
  134480. 19,
  134481. 19
  134482. };
  134483. static static_codebook _44c8_s_p9_1 = {
  134484. 2, 361,
  134485. _vq_lengthlist__44c8_s_p9_1,
  134486. 1, -518287360, 1622704128, 5, 0,
  134487. _vq_quantlist__44c8_s_p9_1,
  134488. NULL,
  134489. &_vq_auxt__44c8_s_p9_1,
  134490. NULL,
  134491. 0
  134492. };
  134493. static long _vq_quantlist__44c8_s_p9_2[] = {
  134494. 24,
  134495. 23,
  134496. 25,
  134497. 22,
  134498. 26,
  134499. 21,
  134500. 27,
  134501. 20,
  134502. 28,
  134503. 19,
  134504. 29,
  134505. 18,
  134506. 30,
  134507. 17,
  134508. 31,
  134509. 16,
  134510. 32,
  134511. 15,
  134512. 33,
  134513. 14,
  134514. 34,
  134515. 13,
  134516. 35,
  134517. 12,
  134518. 36,
  134519. 11,
  134520. 37,
  134521. 10,
  134522. 38,
  134523. 9,
  134524. 39,
  134525. 8,
  134526. 40,
  134527. 7,
  134528. 41,
  134529. 6,
  134530. 42,
  134531. 5,
  134532. 43,
  134533. 4,
  134534. 44,
  134535. 3,
  134536. 45,
  134537. 2,
  134538. 46,
  134539. 1,
  134540. 47,
  134541. 0,
  134542. 48,
  134543. };
  134544. static long _vq_lengthlist__44c8_s_p9_2[] = {
  134545. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134546. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134547. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134548. 7,
  134549. };
  134550. static float _vq_quantthresh__44c8_s_p9_2[] = {
  134551. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134552. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134553. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134554. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134555. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134556. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134557. };
  134558. static long _vq_quantmap__44c8_s_p9_2[] = {
  134559. 47, 45, 43, 41, 39, 37, 35, 33,
  134560. 31, 29, 27, 25, 23, 21, 19, 17,
  134561. 15, 13, 11, 9, 7, 5, 3, 1,
  134562. 0, 2, 4, 6, 8, 10, 12, 14,
  134563. 16, 18, 20, 22, 24, 26, 28, 30,
  134564. 32, 34, 36, 38, 40, 42, 44, 46,
  134565. 48,
  134566. };
  134567. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  134568. _vq_quantthresh__44c8_s_p9_2,
  134569. _vq_quantmap__44c8_s_p9_2,
  134570. 49,
  134571. 49
  134572. };
  134573. static static_codebook _44c8_s_p9_2 = {
  134574. 1, 49,
  134575. _vq_lengthlist__44c8_s_p9_2,
  134576. 1, -526909440, 1611661312, 6, 0,
  134577. _vq_quantlist__44c8_s_p9_2,
  134578. NULL,
  134579. &_vq_auxt__44c8_s_p9_2,
  134580. NULL,
  134581. 0
  134582. };
  134583. static long _huff_lengthlist__44c8_s_short[] = {
  134584. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  134585. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  134586. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  134587. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  134588. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  134589. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  134590. 10, 9,11,14,
  134591. };
  134592. static static_codebook _huff_book__44c8_s_short = {
  134593. 2, 100,
  134594. _huff_lengthlist__44c8_s_short,
  134595. 0, 0, 0, 0, 0,
  134596. NULL,
  134597. NULL,
  134598. NULL,
  134599. NULL,
  134600. 0
  134601. };
  134602. static long _huff_lengthlist__44c9_s_long[] = {
  134603. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  134604. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  134605. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  134606. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  134607. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  134608. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  134609. 10, 9, 8, 9,
  134610. };
  134611. static static_codebook _huff_book__44c9_s_long = {
  134612. 2, 100,
  134613. _huff_lengthlist__44c9_s_long,
  134614. 0, 0, 0, 0, 0,
  134615. NULL,
  134616. NULL,
  134617. NULL,
  134618. NULL,
  134619. 0
  134620. };
  134621. static long _vq_quantlist__44c9_s_p1_0[] = {
  134622. 1,
  134623. 0,
  134624. 2,
  134625. };
  134626. static long _vq_lengthlist__44c9_s_p1_0[] = {
  134627. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  134628. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134629. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  134630. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134631. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  134632. 7,
  134633. };
  134634. static float _vq_quantthresh__44c9_s_p1_0[] = {
  134635. -0.5, 0.5,
  134636. };
  134637. static long _vq_quantmap__44c9_s_p1_0[] = {
  134638. 1, 0, 2,
  134639. };
  134640. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  134641. _vq_quantthresh__44c9_s_p1_0,
  134642. _vq_quantmap__44c9_s_p1_0,
  134643. 3,
  134644. 3
  134645. };
  134646. static static_codebook _44c9_s_p1_0 = {
  134647. 4, 81,
  134648. _vq_lengthlist__44c9_s_p1_0,
  134649. 1, -535822336, 1611661312, 2, 0,
  134650. _vq_quantlist__44c9_s_p1_0,
  134651. NULL,
  134652. &_vq_auxt__44c9_s_p1_0,
  134653. NULL,
  134654. 0
  134655. };
  134656. static long _vq_quantlist__44c9_s_p2_0[] = {
  134657. 2,
  134658. 1,
  134659. 3,
  134660. 0,
  134661. 4,
  134662. };
  134663. static long _vq_lengthlist__44c9_s_p2_0[] = {
  134664. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134665. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  134666. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  134667. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  134668. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  134669. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  134670. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  134671. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  134672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134673. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  134674. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  134675. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  134676. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  134677. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  134678. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  134679. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  134680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134681. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  134682. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  134683. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  134684. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  134685. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  134686. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  134687. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134689. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  134690. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  134691. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  134692. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  134693. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  134694. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  134695. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134700. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  134701. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  134702. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  134703. 12,
  134704. };
  134705. static float _vq_quantthresh__44c9_s_p2_0[] = {
  134706. -1.5, -0.5, 0.5, 1.5,
  134707. };
  134708. static long _vq_quantmap__44c9_s_p2_0[] = {
  134709. 3, 1, 0, 2, 4,
  134710. };
  134711. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  134712. _vq_quantthresh__44c9_s_p2_0,
  134713. _vq_quantmap__44c9_s_p2_0,
  134714. 5,
  134715. 5
  134716. };
  134717. static static_codebook _44c9_s_p2_0 = {
  134718. 4, 625,
  134719. _vq_lengthlist__44c9_s_p2_0,
  134720. 1, -533725184, 1611661312, 3, 0,
  134721. _vq_quantlist__44c9_s_p2_0,
  134722. NULL,
  134723. &_vq_auxt__44c9_s_p2_0,
  134724. NULL,
  134725. 0
  134726. };
  134727. static long _vq_quantlist__44c9_s_p3_0[] = {
  134728. 4,
  134729. 3,
  134730. 5,
  134731. 2,
  134732. 6,
  134733. 1,
  134734. 7,
  134735. 0,
  134736. 8,
  134737. };
  134738. static long _vq_lengthlist__44c9_s_p3_0[] = {
  134739. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  134740. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  134741. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  134742. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  134743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134744. 0,
  134745. };
  134746. static float _vq_quantthresh__44c9_s_p3_0[] = {
  134747. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134748. };
  134749. static long _vq_quantmap__44c9_s_p3_0[] = {
  134750. 7, 5, 3, 1, 0, 2, 4, 6,
  134751. 8,
  134752. };
  134753. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  134754. _vq_quantthresh__44c9_s_p3_0,
  134755. _vq_quantmap__44c9_s_p3_0,
  134756. 9,
  134757. 9
  134758. };
  134759. static static_codebook _44c9_s_p3_0 = {
  134760. 2, 81,
  134761. _vq_lengthlist__44c9_s_p3_0,
  134762. 1, -531628032, 1611661312, 4, 0,
  134763. _vq_quantlist__44c9_s_p3_0,
  134764. NULL,
  134765. &_vq_auxt__44c9_s_p3_0,
  134766. NULL,
  134767. 0
  134768. };
  134769. static long _vq_quantlist__44c9_s_p4_0[] = {
  134770. 8,
  134771. 7,
  134772. 9,
  134773. 6,
  134774. 10,
  134775. 5,
  134776. 11,
  134777. 4,
  134778. 12,
  134779. 3,
  134780. 13,
  134781. 2,
  134782. 14,
  134783. 1,
  134784. 15,
  134785. 0,
  134786. 16,
  134787. };
  134788. static long _vq_lengthlist__44c9_s_p4_0[] = {
  134789. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  134790. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  134791. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  134792. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  134793. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  134794. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  134795. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  134796. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134797. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134798. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  134799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134802. 0, 0, 0, 0, 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, 0,
  134807. 0,
  134808. };
  134809. static float _vq_quantthresh__44c9_s_p4_0[] = {
  134810. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134811. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134812. };
  134813. static long _vq_quantmap__44c9_s_p4_0[] = {
  134814. 15, 13, 11, 9, 7, 5, 3, 1,
  134815. 0, 2, 4, 6, 8, 10, 12, 14,
  134816. 16,
  134817. };
  134818. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  134819. _vq_quantthresh__44c9_s_p4_0,
  134820. _vq_quantmap__44c9_s_p4_0,
  134821. 17,
  134822. 17
  134823. };
  134824. static static_codebook _44c9_s_p4_0 = {
  134825. 2, 289,
  134826. _vq_lengthlist__44c9_s_p4_0,
  134827. 1, -529530880, 1611661312, 5, 0,
  134828. _vq_quantlist__44c9_s_p4_0,
  134829. NULL,
  134830. &_vq_auxt__44c9_s_p4_0,
  134831. NULL,
  134832. 0
  134833. };
  134834. static long _vq_quantlist__44c9_s_p5_0[] = {
  134835. 1,
  134836. 0,
  134837. 2,
  134838. };
  134839. static long _vq_lengthlist__44c9_s_p5_0[] = {
  134840. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  134841. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  134842. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  134843. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  134844. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  134845. 12,
  134846. };
  134847. static float _vq_quantthresh__44c9_s_p5_0[] = {
  134848. -5.5, 5.5,
  134849. };
  134850. static long _vq_quantmap__44c9_s_p5_0[] = {
  134851. 1, 0, 2,
  134852. };
  134853. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  134854. _vq_quantthresh__44c9_s_p5_0,
  134855. _vq_quantmap__44c9_s_p5_0,
  134856. 3,
  134857. 3
  134858. };
  134859. static static_codebook _44c9_s_p5_0 = {
  134860. 4, 81,
  134861. _vq_lengthlist__44c9_s_p5_0,
  134862. 1, -529137664, 1618345984, 2, 0,
  134863. _vq_quantlist__44c9_s_p5_0,
  134864. NULL,
  134865. &_vq_auxt__44c9_s_p5_0,
  134866. NULL,
  134867. 0
  134868. };
  134869. static long _vq_quantlist__44c9_s_p5_1[] = {
  134870. 5,
  134871. 4,
  134872. 6,
  134873. 3,
  134874. 7,
  134875. 2,
  134876. 8,
  134877. 1,
  134878. 9,
  134879. 0,
  134880. 10,
  134881. };
  134882. static long _vq_lengthlist__44c9_s_p5_1[] = {
  134883. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  134884. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  134885. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  134886. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  134887. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  134888. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  134889. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  134890. 11,11,11, 7, 7, 7, 7, 7, 7,
  134891. };
  134892. static float _vq_quantthresh__44c9_s_p5_1[] = {
  134893. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134894. 3.5, 4.5,
  134895. };
  134896. static long _vq_quantmap__44c9_s_p5_1[] = {
  134897. 9, 7, 5, 3, 1, 0, 2, 4,
  134898. 6, 8, 10,
  134899. };
  134900. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  134901. _vq_quantthresh__44c9_s_p5_1,
  134902. _vq_quantmap__44c9_s_p5_1,
  134903. 11,
  134904. 11
  134905. };
  134906. static static_codebook _44c9_s_p5_1 = {
  134907. 2, 121,
  134908. _vq_lengthlist__44c9_s_p5_1,
  134909. 1, -531365888, 1611661312, 4, 0,
  134910. _vq_quantlist__44c9_s_p5_1,
  134911. NULL,
  134912. &_vq_auxt__44c9_s_p5_1,
  134913. NULL,
  134914. 0
  134915. };
  134916. static long _vq_quantlist__44c9_s_p6_0[] = {
  134917. 6,
  134918. 5,
  134919. 7,
  134920. 4,
  134921. 8,
  134922. 3,
  134923. 9,
  134924. 2,
  134925. 10,
  134926. 1,
  134927. 11,
  134928. 0,
  134929. 12,
  134930. };
  134931. static long _vq_lengthlist__44c9_s_p6_0[] = {
  134932. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  134933. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  134934. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  134935. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134936. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  134937. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  134938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134942. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134943. };
  134944. static float _vq_quantthresh__44c9_s_p6_0[] = {
  134945. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134946. 12.5, 17.5, 22.5, 27.5,
  134947. };
  134948. static long _vq_quantmap__44c9_s_p6_0[] = {
  134949. 11, 9, 7, 5, 3, 1, 0, 2,
  134950. 4, 6, 8, 10, 12,
  134951. };
  134952. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  134953. _vq_quantthresh__44c9_s_p6_0,
  134954. _vq_quantmap__44c9_s_p6_0,
  134955. 13,
  134956. 13
  134957. };
  134958. static static_codebook _44c9_s_p6_0 = {
  134959. 2, 169,
  134960. _vq_lengthlist__44c9_s_p6_0,
  134961. 1, -526516224, 1616117760, 4, 0,
  134962. _vq_quantlist__44c9_s_p6_0,
  134963. NULL,
  134964. &_vq_auxt__44c9_s_p6_0,
  134965. NULL,
  134966. 0
  134967. };
  134968. static long _vq_quantlist__44c9_s_p6_1[] = {
  134969. 2,
  134970. 1,
  134971. 3,
  134972. 0,
  134973. 4,
  134974. };
  134975. static long _vq_lengthlist__44c9_s_p6_1[] = {
  134976. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  134977. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  134978. };
  134979. static float _vq_quantthresh__44c9_s_p6_1[] = {
  134980. -1.5, -0.5, 0.5, 1.5,
  134981. };
  134982. static long _vq_quantmap__44c9_s_p6_1[] = {
  134983. 3, 1, 0, 2, 4,
  134984. };
  134985. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  134986. _vq_quantthresh__44c9_s_p6_1,
  134987. _vq_quantmap__44c9_s_p6_1,
  134988. 5,
  134989. 5
  134990. };
  134991. static static_codebook _44c9_s_p6_1 = {
  134992. 2, 25,
  134993. _vq_lengthlist__44c9_s_p6_1,
  134994. 1, -533725184, 1611661312, 3, 0,
  134995. _vq_quantlist__44c9_s_p6_1,
  134996. NULL,
  134997. &_vq_auxt__44c9_s_p6_1,
  134998. NULL,
  134999. 0
  135000. };
  135001. static long _vq_quantlist__44c9_s_p7_0[] = {
  135002. 6,
  135003. 5,
  135004. 7,
  135005. 4,
  135006. 8,
  135007. 3,
  135008. 9,
  135009. 2,
  135010. 10,
  135011. 1,
  135012. 11,
  135013. 0,
  135014. 12,
  135015. };
  135016. static long _vq_lengthlist__44c9_s_p7_0[] = {
  135017. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  135018. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135019. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135020. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135021. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135022. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135023. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135024. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135025. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135026. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135027. 19,12,12,12,12,13,13,14,14,
  135028. };
  135029. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135030. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135031. 27.5, 38.5, 49.5, 60.5,
  135032. };
  135033. static long _vq_quantmap__44c9_s_p7_0[] = {
  135034. 11, 9, 7, 5, 3, 1, 0, 2,
  135035. 4, 6, 8, 10, 12,
  135036. };
  135037. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135038. _vq_quantthresh__44c9_s_p7_0,
  135039. _vq_quantmap__44c9_s_p7_0,
  135040. 13,
  135041. 13
  135042. };
  135043. static static_codebook _44c9_s_p7_0 = {
  135044. 2, 169,
  135045. _vq_lengthlist__44c9_s_p7_0,
  135046. 1, -523206656, 1618345984, 4, 0,
  135047. _vq_quantlist__44c9_s_p7_0,
  135048. NULL,
  135049. &_vq_auxt__44c9_s_p7_0,
  135050. NULL,
  135051. 0
  135052. };
  135053. static long _vq_quantlist__44c9_s_p7_1[] = {
  135054. 5,
  135055. 4,
  135056. 6,
  135057. 3,
  135058. 7,
  135059. 2,
  135060. 8,
  135061. 1,
  135062. 9,
  135063. 0,
  135064. 10,
  135065. };
  135066. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135067. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135068. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135069. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135070. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135071. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135072. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135073. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135074. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135075. };
  135076. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135077. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135078. 3.5, 4.5,
  135079. };
  135080. static long _vq_quantmap__44c9_s_p7_1[] = {
  135081. 9, 7, 5, 3, 1, 0, 2, 4,
  135082. 6, 8, 10,
  135083. };
  135084. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135085. _vq_quantthresh__44c9_s_p7_1,
  135086. _vq_quantmap__44c9_s_p7_1,
  135087. 11,
  135088. 11
  135089. };
  135090. static static_codebook _44c9_s_p7_1 = {
  135091. 2, 121,
  135092. _vq_lengthlist__44c9_s_p7_1,
  135093. 1, -531365888, 1611661312, 4, 0,
  135094. _vq_quantlist__44c9_s_p7_1,
  135095. NULL,
  135096. &_vq_auxt__44c9_s_p7_1,
  135097. NULL,
  135098. 0
  135099. };
  135100. static long _vq_quantlist__44c9_s_p8_0[] = {
  135101. 7,
  135102. 6,
  135103. 8,
  135104. 5,
  135105. 9,
  135106. 4,
  135107. 10,
  135108. 3,
  135109. 11,
  135110. 2,
  135111. 12,
  135112. 1,
  135113. 13,
  135114. 0,
  135115. 14,
  135116. };
  135117. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135118. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135119. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135120. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135121. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135122. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135123. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135124. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135125. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135126. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135127. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135128. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135129. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135130. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135131. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135132. 14,
  135133. };
  135134. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135135. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135136. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135137. };
  135138. static long _vq_quantmap__44c9_s_p8_0[] = {
  135139. 13, 11, 9, 7, 5, 3, 1, 0,
  135140. 2, 4, 6, 8, 10, 12, 14,
  135141. };
  135142. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135143. _vq_quantthresh__44c9_s_p8_0,
  135144. _vq_quantmap__44c9_s_p8_0,
  135145. 15,
  135146. 15
  135147. };
  135148. static static_codebook _44c9_s_p8_0 = {
  135149. 2, 225,
  135150. _vq_lengthlist__44c9_s_p8_0,
  135151. 1, -520986624, 1620377600, 4, 0,
  135152. _vq_quantlist__44c9_s_p8_0,
  135153. NULL,
  135154. &_vq_auxt__44c9_s_p8_0,
  135155. NULL,
  135156. 0
  135157. };
  135158. static long _vq_quantlist__44c9_s_p8_1[] = {
  135159. 10,
  135160. 9,
  135161. 11,
  135162. 8,
  135163. 12,
  135164. 7,
  135165. 13,
  135166. 6,
  135167. 14,
  135168. 5,
  135169. 15,
  135170. 4,
  135171. 16,
  135172. 3,
  135173. 17,
  135174. 2,
  135175. 18,
  135176. 1,
  135177. 19,
  135178. 0,
  135179. 20,
  135180. };
  135181. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135182. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135183. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135184. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135185. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135186. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135187. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135188. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135189. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135190. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135191. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135192. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135193. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135194. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135195. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135196. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135197. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135198. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135199. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135200. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135201. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135202. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135203. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135204. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135205. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135206. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135207. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135208. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135209. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135210. };
  135211. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135212. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135213. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135214. 6.5, 7.5, 8.5, 9.5,
  135215. };
  135216. static long _vq_quantmap__44c9_s_p8_1[] = {
  135217. 19, 17, 15, 13, 11, 9, 7, 5,
  135218. 3, 1, 0, 2, 4, 6, 8, 10,
  135219. 12, 14, 16, 18, 20,
  135220. };
  135221. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135222. _vq_quantthresh__44c9_s_p8_1,
  135223. _vq_quantmap__44c9_s_p8_1,
  135224. 21,
  135225. 21
  135226. };
  135227. static static_codebook _44c9_s_p8_1 = {
  135228. 2, 441,
  135229. _vq_lengthlist__44c9_s_p8_1,
  135230. 1, -529268736, 1611661312, 5, 0,
  135231. _vq_quantlist__44c9_s_p8_1,
  135232. NULL,
  135233. &_vq_auxt__44c9_s_p8_1,
  135234. NULL,
  135235. 0
  135236. };
  135237. static long _vq_quantlist__44c9_s_p9_0[] = {
  135238. 9,
  135239. 8,
  135240. 10,
  135241. 7,
  135242. 11,
  135243. 6,
  135244. 12,
  135245. 5,
  135246. 13,
  135247. 4,
  135248. 14,
  135249. 3,
  135250. 15,
  135251. 2,
  135252. 16,
  135253. 1,
  135254. 17,
  135255. 0,
  135256. 18,
  135257. };
  135258. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135259. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135260. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135261. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135262. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135263. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135264. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135265. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135266. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135267. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135268. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135269. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135270. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135271. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135272. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135273. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135274. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135275. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135276. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135277. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135278. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135279. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135280. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135281. 11,11,11,11,11,11,11,11,11,
  135282. };
  135283. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135284. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135285. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135286. 6982.5, 7913.5,
  135287. };
  135288. static long _vq_quantmap__44c9_s_p9_0[] = {
  135289. 17, 15, 13, 11, 9, 7, 5, 3,
  135290. 1, 0, 2, 4, 6, 8, 10, 12,
  135291. 14, 16, 18,
  135292. };
  135293. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135294. _vq_quantthresh__44c9_s_p9_0,
  135295. _vq_quantmap__44c9_s_p9_0,
  135296. 19,
  135297. 19
  135298. };
  135299. static static_codebook _44c9_s_p9_0 = {
  135300. 2, 361,
  135301. _vq_lengthlist__44c9_s_p9_0,
  135302. 1, -508535424, 1631393792, 5, 0,
  135303. _vq_quantlist__44c9_s_p9_0,
  135304. NULL,
  135305. &_vq_auxt__44c9_s_p9_0,
  135306. NULL,
  135307. 0
  135308. };
  135309. static long _vq_quantlist__44c9_s_p9_1[] = {
  135310. 9,
  135311. 8,
  135312. 10,
  135313. 7,
  135314. 11,
  135315. 6,
  135316. 12,
  135317. 5,
  135318. 13,
  135319. 4,
  135320. 14,
  135321. 3,
  135322. 15,
  135323. 2,
  135324. 16,
  135325. 1,
  135326. 17,
  135327. 0,
  135328. 18,
  135329. };
  135330. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135331. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135332. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135333. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135334. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135335. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135336. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135337. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135338. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135339. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135340. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135341. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135342. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135343. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135344. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135345. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135346. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135347. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135348. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135349. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135350. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135351. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135352. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135353. 13,13,13,14,13,14,15,15,15,
  135354. };
  135355. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135356. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135357. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135358. 367.5, 416.5,
  135359. };
  135360. static long _vq_quantmap__44c9_s_p9_1[] = {
  135361. 17, 15, 13, 11, 9, 7, 5, 3,
  135362. 1, 0, 2, 4, 6, 8, 10, 12,
  135363. 14, 16, 18,
  135364. };
  135365. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135366. _vq_quantthresh__44c9_s_p9_1,
  135367. _vq_quantmap__44c9_s_p9_1,
  135368. 19,
  135369. 19
  135370. };
  135371. static static_codebook _44c9_s_p9_1 = {
  135372. 2, 361,
  135373. _vq_lengthlist__44c9_s_p9_1,
  135374. 1, -518287360, 1622704128, 5, 0,
  135375. _vq_quantlist__44c9_s_p9_1,
  135376. NULL,
  135377. &_vq_auxt__44c9_s_p9_1,
  135378. NULL,
  135379. 0
  135380. };
  135381. static long _vq_quantlist__44c9_s_p9_2[] = {
  135382. 24,
  135383. 23,
  135384. 25,
  135385. 22,
  135386. 26,
  135387. 21,
  135388. 27,
  135389. 20,
  135390. 28,
  135391. 19,
  135392. 29,
  135393. 18,
  135394. 30,
  135395. 17,
  135396. 31,
  135397. 16,
  135398. 32,
  135399. 15,
  135400. 33,
  135401. 14,
  135402. 34,
  135403. 13,
  135404. 35,
  135405. 12,
  135406. 36,
  135407. 11,
  135408. 37,
  135409. 10,
  135410. 38,
  135411. 9,
  135412. 39,
  135413. 8,
  135414. 40,
  135415. 7,
  135416. 41,
  135417. 6,
  135418. 42,
  135419. 5,
  135420. 43,
  135421. 4,
  135422. 44,
  135423. 3,
  135424. 45,
  135425. 2,
  135426. 46,
  135427. 1,
  135428. 47,
  135429. 0,
  135430. 48,
  135431. };
  135432. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135433. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135434. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135435. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135436. 7,
  135437. };
  135438. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135439. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135440. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135441. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135442. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135443. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135444. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135445. };
  135446. static long _vq_quantmap__44c9_s_p9_2[] = {
  135447. 47, 45, 43, 41, 39, 37, 35, 33,
  135448. 31, 29, 27, 25, 23, 21, 19, 17,
  135449. 15, 13, 11, 9, 7, 5, 3, 1,
  135450. 0, 2, 4, 6, 8, 10, 12, 14,
  135451. 16, 18, 20, 22, 24, 26, 28, 30,
  135452. 32, 34, 36, 38, 40, 42, 44, 46,
  135453. 48,
  135454. };
  135455. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135456. _vq_quantthresh__44c9_s_p9_2,
  135457. _vq_quantmap__44c9_s_p9_2,
  135458. 49,
  135459. 49
  135460. };
  135461. static static_codebook _44c9_s_p9_2 = {
  135462. 1, 49,
  135463. _vq_lengthlist__44c9_s_p9_2,
  135464. 1, -526909440, 1611661312, 6, 0,
  135465. _vq_quantlist__44c9_s_p9_2,
  135466. NULL,
  135467. &_vq_auxt__44c9_s_p9_2,
  135468. NULL,
  135469. 0
  135470. };
  135471. static long _huff_lengthlist__44c9_s_short[] = {
  135472. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135473. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135474. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135475. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135476. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135477. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135478. 9, 8,10,13,
  135479. };
  135480. static static_codebook _huff_book__44c9_s_short = {
  135481. 2, 100,
  135482. _huff_lengthlist__44c9_s_short,
  135483. 0, 0, 0, 0, 0,
  135484. NULL,
  135485. NULL,
  135486. NULL,
  135487. NULL,
  135488. 0
  135489. };
  135490. static long _huff_lengthlist__44c0_s_long[] = {
  135491. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135492. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  135493. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  135494. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  135495. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  135496. 12,
  135497. };
  135498. static static_codebook _huff_book__44c0_s_long = {
  135499. 2, 81,
  135500. _huff_lengthlist__44c0_s_long,
  135501. 0, 0, 0, 0, 0,
  135502. NULL,
  135503. NULL,
  135504. NULL,
  135505. NULL,
  135506. 0
  135507. };
  135508. static long _vq_quantlist__44c0_s_p1_0[] = {
  135509. 1,
  135510. 0,
  135511. 2,
  135512. };
  135513. static long _vq_lengthlist__44c0_s_p1_0[] = {
  135514. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135515. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135519. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135520. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135524. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135525. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135560. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135565. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135570. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  135571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135605. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135606. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135610. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135611. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  135612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135615. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  135616. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  135617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135622. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135627. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135632. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  135667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  135672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  135677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135713. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135718. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  135925. };
  135926. static float _vq_quantthresh__44c0_s_p1_0[] = {
  135927. -0.5, 0.5,
  135928. };
  135929. static long _vq_quantmap__44c0_s_p1_0[] = {
  135930. 1, 0, 2,
  135931. };
  135932. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  135933. _vq_quantthresh__44c0_s_p1_0,
  135934. _vq_quantmap__44c0_s_p1_0,
  135935. 3,
  135936. 3
  135937. };
  135938. static static_codebook _44c0_s_p1_0 = {
  135939. 8, 6561,
  135940. _vq_lengthlist__44c0_s_p1_0,
  135941. 1, -535822336, 1611661312, 2, 0,
  135942. _vq_quantlist__44c0_s_p1_0,
  135943. NULL,
  135944. &_vq_auxt__44c0_s_p1_0,
  135945. NULL,
  135946. 0
  135947. };
  135948. static long _vq_quantlist__44c0_s_p2_0[] = {
  135949. 2,
  135950. 1,
  135951. 3,
  135952. 0,
  135953. 4,
  135954. };
  135955. static long _vq_lengthlist__44c0_s_p2_0[] = {
  135956. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  135958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135959. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  135961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135962. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  135996. };
  135997. static float _vq_quantthresh__44c0_s_p2_0[] = {
  135998. -1.5, -0.5, 0.5, 1.5,
  135999. };
  136000. static long _vq_quantmap__44c0_s_p2_0[] = {
  136001. 3, 1, 0, 2, 4,
  136002. };
  136003. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  136004. _vq_quantthresh__44c0_s_p2_0,
  136005. _vq_quantmap__44c0_s_p2_0,
  136006. 5,
  136007. 5
  136008. };
  136009. static static_codebook _44c0_s_p2_0 = {
  136010. 4, 625,
  136011. _vq_lengthlist__44c0_s_p2_0,
  136012. 1, -533725184, 1611661312, 3, 0,
  136013. _vq_quantlist__44c0_s_p2_0,
  136014. NULL,
  136015. &_vq_auxt__44c0_s_p2_0,
  136016. NULL,
  136017. 0
  136018. };
  136019. static long _vq_quantlist__44c0_s_p3_0[] = {
  136020. 4,
  136021. 3,
  136022. 5,
  136023. 2,
  136024. 6,
  136025. 1,
  136026. 7,
  136027. 0,
  136028. 8,
  136029. };
  136030. static long _vq_lengthlist__44c0_s_p3_0[] = {
  136031. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136032. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136033. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136034. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136035. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136036. 0,
  136037. };
  136038. static float _vq_quantthresh__44c0_s_p3_0[] = {
  136039. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136040. };
  136041. static long _vq_quantmap__44c0_s_p3_0[] = {
  136042. 7, 5, 3, 1, 0, 2, 4, 6,
  136043. 8,
  136044. };
  136045. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136046. _vq_quantthresh__44c0_s_p3_0,
  136047. _vq_quantmap__44c0_s_p3_0,
  136048. 9,
  136049. 9
  136050. };
  136051. static static_codebook _44c0_s_p3_0 = {
  136052. 2, 81,
  136053. _vq_lengthlist__44c0_s_p3_0,
  136054. 1, -531628032, 1611661312, 4, 0,
  136055. _vq_quantlist__44c0_s_p3_0,
  136056. NULL,
  136057. &_vq_auxt__44c0_s_p3_0,
  136058. NULL,
  136059. 0
  136060. };
  136061. static long _vq_quantlist__44c0_s_p4_0[] = {
  136062. 4,
  136063. 3,
  136064. 5,
  136065. 2,
  136066. 6,
  136067. 1,
  136068. 7,
  136069. 0,
  136070. 8,
  136071. };
  136072. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136073. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136074. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136075. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136076. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136077. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136078. 10,
  136079. };
  136080. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136081. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136082. };
  136083. static long _vq_quantmap__44c0_s_p4_0[] = {
  136084. 7, 5, 3, 1, 0, 2, 4, 6,
  136085. 8,
  136086. };
  136087. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136088. _vq_quantthresh__44c0_s_p4_0,
  136089. _vq_quantmap__44c0_s_p4_0,
  136090. 9,
  136091. 9
  136092. };
  136093. static static_codebook _44c0_s_p4_0 = {
  136094. 2, 81,
  136095. _vq_lengthlist__44c0_s_p4_0,
  136096. 1, -531628032, 1611661312, 4, 0,
  136097. _vq_quantlist__44c0_s_p4_0,
  136098. NULL,
  136099. &_vq_auxt__44c0_s_p4_0,
  136100. NULL,
  136101. 0
  136102. };
  136103. static long _vq_quantlist__44c0_s_p5_0[] = {
  136104. 8,
  136105. 7,
  136106. 9,
  136107. 6,
  136108. 10,
  136109. 5,
  136110. 11,
  136111. 4,
  136112. 12,
  136113. 3,
  136114. 13,
  136115. 2,
  136116. 14,
  136117. 1,
  136118. 15,
  136119. 0,
  136120. 16,
  136121. };
  136122. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136123. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136124. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136125. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136126. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136127. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136128. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136129. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136130. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136131. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136132. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136133. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136134. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136135. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136136. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136137. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136138. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136139. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136140. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136141. 14,
  136142. };
  136143. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136144. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136145. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136146. };
  136147. static long _vq_quantmap__44c0_s_p5_0[] = {
  136148. 15, 13, 11, 9, 7, 5, 3, 1,
  136149. 0, 2, 4, 6, 8, 10, 12, 14,
  136150. 16,
  136151. };
  136152. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136153. _vq_quantthresh__44c0_s_p5_0,
  136154. _vq_quantmap__44c0_s_p5_0,
  136155. 17,
  136156. 17
  136157. };
  136158. static static_codebook _44c0_s_p5_0 = {
  136159. 2, 289,
  136160. _vq_lengthlist__44c0_s_p5_0,
  136161. 1, -529530880, 1611661312, 5, 0,
  136162. _vq_quantlist__44c0_s_p5_0,
  136163. NULL,
  136164. &_vq_auxt__44c0_s_p5_0,
  136165. NULL,
  136166. 0
  136167. };
  136168. static long _vq_quantlist__44c0_s_p6_0[] = {
  136169. 1,
  136170. 0,
  136171. 2,
  136172. };
  136173. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136174. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136175. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136176. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136177. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136178. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136179. 10,
  136180. };
  136181. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136182. -5.5, 5.5,
  136183. };
  136184. static long _vq_quantmap__44c0_s_p6_0[] = {
  136185. 1, 0, 2,
  136186. };
  136187. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136188. _vq_quantthresh__44c0_s_p6_0,
  136189. _vq_quantmap__44c0_s_p6_0,
  136190. 3,
  136191. 3
  136192. };
  136193. static static_codebook _44c0_s_p6_0 = {
  136194. 4, 81,
  136195. _vq_lengthlist__44c0_s_p6_0,
  136196. 1, -529137664, 1618345984, 2, 0,
  136197. _vq_quantlist__44c0_s_p6_0,
  136198. NULL,
  136199. &_vq_auxt__44c0_s_p6_0,
  136200. NULL,
  136201. 0
  136202. };
  136203. static long _vq_quantlist__44c0_s_p6_1[] = {
  136204. 5,
  136205. 4,
  136206. 6,
  136207. 3,
  136208. 7,
  136209. 2,
  136210. 8,
  136211. 1,
  136212. 9,
  136213. 0,
  136214. 10,
  136215. };
  136216. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136217. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136218. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136219. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136220. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136221. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136222. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136223. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136224. 10,10,10, 8, 8, 8, 8, 8, 8,
  136225. };
  136226. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136227. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136228. 3.5, 4.5,
  136229. };
  136230. static long _vq_quantmap__44c0_s_p6_1[] = {
  136231. 9, 7, 5, 3, 1, 0, 2, 4,
  136232. 6, 8, 10,
  136233. };
  136234. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136235. _vq_quantthresh__44c0_s_p6_1,
  136236. _vq_quantmap__44c0_s_p6_1,
  136237. 11,
  136238. 11
  136239. };
  136240. static static_codebook _44c0_s_p6_1 = {
  136241. 2, 121,
  136242. _vq_lengthlist__44c0_s_p6_1,
  136243. 1, -531365888, 1611661312, 4, 0,
  136244. _vq_quantlist__44c0_s_p6_1,
  136245. NULL,
  136246. &_vq_auxt__44c0_s_p6_1,
  136247. NULL,
  136248. 0
  136249. };
  136250. static long _vq_quantlist__44c0_s_p7_0[] = {
  136251. 6,
  136252. 5,
  136253. 7,
  136254. 4,
  136255. 8,
  136256. 3,
  136257. 9,
  136258. 2,
  136259. 10,
  136260. 1,
  136261. 11,
  136262. 0,
  136263. 12,
  136264. };
  136265. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136266. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136267. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136268. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136269. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136270. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136271. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136272. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136273. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136274. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136275. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136276. 0,12,12,11,11,12,12,13,13,
  136277. };
  136278. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136279. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136280. 12.5, 17.5, 22.5, 27.5,
  136281. };
  136282. static long _vq_quantmap__44c0_s_p7_0[] = {
  136283. 11, 9, 7, 5, 3, 1, 0, 2,
  136284. 4, 6, 8, 10, 12,
  136285. };
  136286. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136287. _vq_quantthresh__44c0_s_p7_0,
  136288. _vq_quantmap__44c0_s_p7_0,
  136289. 13,
  136290. 13
  136291. };
  136292. static static_codebook _44c0_s_p7_0 = {
  136293. 2, 169,
  136294. _vq_lengthlist__44c0_s_p7_0,
  136295. 1, -526516224, 1616117760, 4, 0,
  136296. _vq_quantlist__44c0_s_p7_0,
  136297. NULL,
  136298. &_vq_auxt__44c0_s_p7_0,
  136299. NULL,
  136300. 0
  136301. };
  136302. static long _vq_quantlist__44c0_s_p7_1[] = {
  136303. 2,
  136304. 1,
  136305. 3,
  136306. 0,
  136307. 4,
  136308. };
  136309. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136310. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136311. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136312. };
  136313. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136314. -1.5, -0.5, 0.5, 1.5,
  136315. };
  136316. static long _vq_quantmap__44c0_s_p7_1[] = {
  136317. 3, 1, 0, 2, 4,
  136318. };
  136319. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136320. _vq_quantthresh__44c0_s_p7_1,
  136321. _vq_quantmap__44c0_s_p7_1,
  136322. 5,
  136323. 5
  136324. };
  136325. static static_codebook _44c0_s_p7_1 = {
  136326. 2, 25,
  136327. _vq_lengthlist__44c0_s_p7_1,
  136328. 1, -533725184, 1611661312, 3, 0,
  136329. _vq_quantlist__44c0_s_p7_1,
  136330. NULL,
  136331. &_vq_auxt__44c0_s_p7_1,
  136332. NULL,
  136333. 0
  136334. };
  136335. static long _vq_quantlist__44c0_s_p8_0[] = {
  136336. 2,
  136337. 1,
  136338. 3,
  136339. 0,
  136340. 4,
  136341. };
  136342. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136343. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136344. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136345. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136346. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136347. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136348. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136349. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136350. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136351. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136352. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136353. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136354. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136355. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136356. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136357. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136358. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136359. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136360. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136361. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136362. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136363. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136364. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136365. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136366. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136367. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136368. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136369. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136370. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136371. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136372. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136373. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136374. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136375. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136376. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136377. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136378. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136379. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136380. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136381. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136382. 11,
  136383. };
  136384. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136385. -331.5, -110.5, 110.5, 331.5,
  136386. };
  136387. static long _vq_quantmap__44c0_s_p8_0[] = {
  136388. 3, 1, 0, 2, 4,
  136389. };
  136390. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136391. _vq_quantthresh__44c0_s_p8_0,
  136392. _vq_quantmap__44c0_s_p8_0,
  136393. 5,
  136394. 5
  136395. };
  136396. static static_codebook _44c0_s_p8_0 = {
  136397. 4, 625,
  136398. _vq_lengthlist__44c0_s_p8_0,
  136399. 1, -518283264, 1627103232, 3, 0,
  136400. _vq_quantlist__44c0_s_p8_0,
  136401. NULL,
  136402. &_vq_auxt__44c0_s_p8_0,
  136403. NULL,
  136404. 0
  136405. };
  136406. static long _vq_quantlist__44c0_s_p8_1[] = {
  136407. 6,
  136408. 5,
  136409. 7,
  136410. 4,
  136411. 8,
  136412. 3,
  136413. 9,
  136414. 2,
  136415. 10,
  136416. 1,
  136417. 11,
  136418. 0,
  136419. 12,
  136420. };
  136421. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136422. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136423. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136424. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136425. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136426. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136427. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136428. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136429. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136430. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136431. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136432. 16,13,13,12,12,14,14,15,13,
  136433. };
  136434. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136435. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136436. 42.5, 59.5, 76.5, 93.5,
  136437. };
  136438. static long _vq_quantmap__44c0_s_p8_1[] = {
  136439. 11, 9, 7, 5, 3, 1, 0, 2,
  136440. 4, 6, 8, 10, 12,
  136441. };
  136442. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136443. _vq_quantthresh__44c0_s_p8_1,
  136444. _vq_quantmap__44c0_s_p8_1,
  136445. 13,
  136446. 13
  136447. };
  136448. static static_codebook _44c0_s_p8_1 = {
  136449. 2, 169,
  136450. _vq_lengthlist__44c0_s_p8_1,
  136451. 1, -522616832, 1620115456, 4, 0,
  136452. _vq_quantlist__44c0_s_p8_1,
  136453. NULL,
  136454. &_vq_auxt__44c0_s_p8_1,
  136455. NULL,
  136456. 0
  136457. };
  136458. static long _vq_quantlist__44c0_s_p8_2[] = {
  136459. 8,
  136460. 7,
  136461. 9,
  136462. 6,
  136463. 10,
  136464. 5,
  136465. 11,
  136466. 4,
  136467. 12,
  136468. 3,
  136469. 13,
  136470. 2,
  136471. 14,
  136472. 1,
  136473. 15,
  136474. 0,
  136475. 16,
  136476. };
  136477. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136478. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136479. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136480. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136481. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136482. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136483. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136484. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136485. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136486. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136487. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136488. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136489. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136490. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136491. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136492. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  136493. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  136494. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  136495. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  136496. 10,
  136497. };
  136498. static float _vq_quantthresh__44c0_s_p8_2[] = {
  136499. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136500. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136501. };
  136502. static long _vq_quantmap__44c0_s_p8_2[] = {
  136503. 15, 13, 11, 9, 7, 5, 3, 1,
  136504. 0, 2, 4, 6, 8, 10, 12, 14,
  136505. 16,
  136506. };
  136507. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  136508. _vq_quantthresh__44c0_s_p8_2,
  136509. _vq_quantmap__44c0_s_p8_2,
  136510. 17,
  136511. 17
  136512. };
  136513. static static_codebook _44c0_s_p8_2 = {
  136514. 2, 289,
  136515. _vq_lengthlist__44c0_s_p8_2,
  136516. 1, -529530880, 1611661312, 5, 0,
  136517. _vq_quantlist__44c0_s_p8_2,
  136518. NULL,
  136519. &_vq_auxt__44c0_s_p8_2,
  136520. NULL,
  136521. 0
  136522. };
  136523. static long _huff_lengthlist__44c0_s_short[] = {
  136524. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  136525. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  136526. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  136527. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  136528. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  136529. 12,
  136530. };
  136531. static static_codebook _huff_book__44c0_s_short = {
  136532. 2, 81,
  136533. _huff_lengthlist__44c0_s_short,
  136534. 0, 0, 0, 0, 0,
  136535. NULL,
  136536. NULL,
  136537. NULL,
  136538. NULL,
  136539. 0
  136540. };
  136541. static long _huff_lengthlist__44c0_sm_long[] = {
  136542. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  136543. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  136544. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  136545. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  136546. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  136547. 13,
  136548. };
  136549. static static_codebook _huff_book__44c0_sm_long = {
  136550. 2, 81,
  136551. _huff_lengthlist__44c0_sm_long,
  136552. 0, 0, 0, 0, 0,
  136553. NULL,
  136554. NULL,
  136555. NULL,
  136556. NULL,
  136557. 0
  136558. };
  136559. static long _vq_quantlist__44c0_sm_p1_0[] = {
  136560. 1,
  136561. 0,
  136562. 2,
  136563. };
  136564. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  136565. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136566. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136570. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136571. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136575. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136576. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  136611. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136616. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136621. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136656. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136657. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136661. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136662. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  136663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136666. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136667. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  136668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136673. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136678. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136683. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  136718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  136723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  136728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136764. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136769. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  136976. };
  136977. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  136978. -0.5, 0.5,
  136979. };
  136980. static long _vq_quantmap__44c0_sm_p1_0[] = {
  136981. 1, 0, 2,
  136982. };
  136983. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  136984. _vq_quantthresh__44c0_sm_p1_0,
  136985. _vq_quantmap__44c0_sm_p1_0,
  136986. 3,
  136987. 3
  136988. };
  136989. static static_codebook _44c0_sm_p1_0 = {
  136990. 8, 6561,
  136991. _vq_lengthlist__44c0_sm_p1_0,
  136992. 1, -535822336, 1611661312, 2, 0,
  136993. _vq_quantlist__44c0_sm_p1_0,
  136994. NULL,
  136995. &_vq_auxt__44c0_sm_p1_0,
  136996. NULL,
  136997. 0
  136998. };
  136999. static long _vq_quantlist__44c0_sm_p2_0[] = {
  137000. 2,
  137001. 1,
  137002. 3,
  137003. 0,
  137004. 4,
  137005. };
  137006. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137007. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137010. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137013. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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,
  137047. };
  137048. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137049. -1.5, -0.5, 0.5, 1.5,
  137050. };
  137051. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137052. 3, 1, 0, 2, 4,
  137053. };
  137054. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137055. _vq_quantthresh__44c0_sm_p2_0,
  137056. _vq_quantmap__44c0_sm_p2_0,
  137057. 5,
  137058. 5
  137059. };
  137060. static static_codebook _44c0_sm_p2_0 = {
  137061. 4, 625,
  137062. _vq_lengthlist__44c0_sm_p2_0,
  137063. 1, -533725184, 1611661312, 3, 0,
  137064. _vq_quantlist__44c0_sm_p2_0,
  137065. NULL,
  137066. &_vq_auxt__44c0_sm_p2_0,
  137067. NULL,
  137068. 0
  137069. };
  137070. static long _vq_quantlist__44c0_sm_p3_0[] = {
  137071. 4,
  137072. 3,
  137073. 5,
  137074. 2,
  137075. 6,
  137076. 1,
  137077. 7,
  137078. 0,
  137079. 8,
  137080. };
  137081. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137082. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137083. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137084. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137085. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137086. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137087. 0,
  137088. };
  137089. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137090. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137091. };
  137092. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137093. 7, 5, 3, 1, 0, 2, 4, 6,
  137094. 8,
  137095. };
  137096. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137097. _vq_quantthresh__44c0_sm_p3_0,
  137098. _vq_quantmap__44c0_sm_p3_0,
  137099. 9,
  137100. 9
  137101. };
  137102. static static_codebook _44c0_sm_p3_0 = {
  137103. 2, 81,
  137104. _vq_lengthlist__44c0_sm_p3_0,
  137105. 1, -531628032, 1611661312, 4, 0,
  137106. _vq_quantlist__44c0_sm_p3_0,
  137107. NULL,
  137108. &_vq_auxt__44c0_sm_p3_0,
  137109. NULL,
  137110. 0
  137111. };
  137112. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137113. 4,
  137114. 3,
  137115. 5,
  137116. 2,
  137117. 6,
  137118. 1,
  137119. 7,
  137120. 0,
  137121. 8,
  137122. };
  137123. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137124. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137125. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137126. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137127. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137128. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137129. 11,
  137130. };
  137131. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137132. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137133. };
  137134. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137135. 7, 5, 3, 1, 0, 2, 4, 6,
  137136. 8,
  137137. };
  137138. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137139. _vq_quantthresh__44c0_sm_p4_0,
  137140. _vq_quantmap__44c0_sm_p4_0,
  137141. 9,
  137142. 9
  137143. };
  137144. static static_codebook _44c0_sm_p4_0 = {
  137145. 2, 81,
  137146. _vq_lengthlist__44c0_sm_p4_0,
  137147. 1, -531628032, 1611661312, 4, 0,
  137148. _vq_quantlist__44c0_sm_p4_0,
  137149. NULL,
  137150. &_vq_auxt__44c0_sm_p4_0,
  137151. NULL,
  137152. 0
  137153. };
  137154. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137155. 8,
  137156. 7,
  137157. 9,
  137158. 6,
  137159. 10,
  137160. 5,
  137161. 11,
  137162. 4,
  137163. 12,
  137164. 3,
  137165. 13,
  137166. 2,
  137167. 14,
  137168. 1,
  137169. 15,
  137170. 0,
  137171. 16,
  137172. };
  137173. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137174. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137175. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137176. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137177. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137178. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137179. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137180. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137181. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137182. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137183. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137184. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137185. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137186. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137187. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137188. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137189. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137190. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137191. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137192. 14,
  137193. };
  137194. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137195. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137196. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137197. };
  137198. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137199. 15, 13, 11, 9, 7, 5, 3, 1,
  137200. 0, 2, 4, 6, 8, 10, 12, 14,
  137201. 16,
  137202. };
  137203. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137204. _vq_quantthresh__44c0_sm_p5_0,
  137205. _vq_quantmap__44c0_sm_p5_0,
  137206. 17,
  137207. 17
  137208. };
  137209. static static_codebook _44c0_sm_p5_0 = {
  137210. 2, 289,
  137211. _vq_lengthlist__44c0_sm_p5_0,
  137212. 1, -529530880, 1611661312, 5, 0,
  137213. _vq_quantlist__44c0_sm_p5_0,
  137214. NULL,
  137215. &_vq_auxt__44c0_sm_p5_0,
  137216. NULL,
  137217. 0
  137218. };
  137219. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137220. 1,
  137221. 0,
  137222. 2,
  137223. };
  137224. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137225. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137226. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137227. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137228. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137229. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137230. 11,
  137231. };
  137232. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137233. -5.5, 5.5,
  137234. };
  137235. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137236. 1, 0, 2,
  137237. };
  137238. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137239. _vq_quantthresh__44c0_sm_p6_0,
  137240. _vq_quantmap__44c0_sm_p6_0,
  137241. 3,
  137242. 3
  137243. };
  137244. static static_codebook _44c0_sm_p6_0 = {
  137245. 4, 81,
  137246. _vq_lengthlist__44c0_sm_p6_0,
  137247. 1, -529137664, 1618345984, 2, 0,
  137248. _vq_quantlist__44c0_sm_p6_0,
  137249. NULL,
  137250. &_vq_auxt__44c0_sm_p6_0,
  137251. NULL,
  137252. 0
  137253. };
  137254. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137255. 5,
  137256. 4,
  137257. 6,
  137258. 3,
  137259. 7,
  137260. 2,
  137261. 8,
  137262. 1,
  137263. 9,
  137264. 0,
  137265. 10,
  137266. };
  137267. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137268. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137269. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137270. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137271. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137272. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137273. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137274. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137275. 10,10,10, 8, 8, 8, 8, 8, 8,
  137276. };
  137277. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137278. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137279. 3.5, 4.5,
  137280. };
  137281. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137282. 9, 7, 5, 3, 1, 0, 2, 4,
  137283. 6, 8, 10,
  137284. };
  137285. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137286. _vq_quantthresh__44c0_sm_p6_1,
  137287. _vq_quantmap__44c0_sm_p6_1,
  137288. 11,
  137289. 11
  137290. };
  137291. static static_codebook _44c0_sm_p6_1 = {
  137292. 2, 121,
  137293. _vq_lengthlist__44c0_sm_p6_1,
  137294. 1, -531365888, 1611661312, 4, 0,
  137295. _vq_quantlist__44c0_sm_p6_1,
  137296. NULL,
  137297. &_vq_auxt__44c0_sm_p6_1,
  137298. NULL,
  137299. 0
  137300. };
  137301. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137302. 6,
  137303. 5,
  137304. 7,
  137305. 4,
  137306. 8,
  137307. 3,
  137308. 9,
  137309. 2,
  137310. 10,
  137311. 1,
  137312. 11,
  137313. 0,
  137314. 12,
  137315. };
  137316. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137317. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137318. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137319. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137320. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137321. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137322. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137323. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137324. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137325. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137326. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137327. 0,12,12,11,11,13,12,14,14,
  137328. };
  137329. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137330. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137331. 12.5, 17.5, 22.5, 27.5,
  137332. };
  137333. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137334. 11, 9, 7, 5, 3, 1, 0, 2,
  137335. 4, 6, 8, 10, 12,
  137336. };
  137337. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137338. _vq_quantthresh__44c0_sm_p7_0,
  137339. _vq_quantmap__44c0_sm_p7_0,
  137340. 13,
  137341. 13
  137342. };
  137343. static static_codebook _44c0_sm_p7_0 = {
  137344. 2, 169,
  137345. _vq_lengthlist__44c0_sm_p7_0,
  137346. 1, -526516224, 1616117760, 4, 0,
  137347. _vq_quantlist__44c0_sm_p7_0,
  137348. NULL,
  137349. &_vq_auxt__44c0_sm_p7_0,
  137350. NULL,
  137351. 0
  137352. };
  137353. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137354. 2,
  137355. 1,
  137356. 3,
  137357. 0,
  137358. 4,
  137359. };
  137360. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137361. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137362. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137363. };
  137364. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137365. -1.5, -0.5, 0.5, 1.5,
  137366. };
  137367. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137368. 3, 1, 0, 2, 4,
  137369. };
  137370. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137371. _vq_quantthresh__44c0_sm_p7_1,
  137372. _vq_quantmap__44c0_sm_p7_1,
  137373. 5,
  137374. 5
  137375. };
  137376. static static_codebook _44c0_sm_p7_1 = {
  137377. 2, 25,
  137378. _vq_lengthlist__44c0_sm_p7_1,
  137379. 1, -533725184, 1611661312, 3, 0,
  137380. _vq_quantlist__44c0_sm_p7_1,
  137381. NULL,
  137382. &_vq_auxt__44c0_sm_p7_1,
  137383. NULL,
  137384. 0
  137385. };
  137386. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137387. 4,
  137388. 3,
  137389. 5,
  137390. 2,
  137391. 6,
  137392. 1,
  137393. 7,
  137394. 0,
  137395. 8,
  137396. };
  137397. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137398. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137399. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137400. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137401. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137402. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137403. 12,
  137404. };
  137405. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137406. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137407. };
  137408. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137409. 7, 5, 3, 1, 0, 2, 4, 6,
  137410. 8,
  137411. };
  137412. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137413. _vq_quantthresh__44c0_sm_p8_0,
  137414. _vq_quantmap__44c0_sm_p8_0,
  137415. 9,
  137416. 9
  137417. };
  137418. static static_codebook _44c0_sm_p8_0 = {
  137419. 2, 81,
  137420. _vq_lengthlist__44c0_sm_p8_0,
  137421. 1, -516186112, 1627103232, 4, 0,
  137422. _vq_quantlist__44c0_sm_p8_0,
  137423. NULL,
  137424. &_vq_auxt__44c0_sm_p8_0,
  137425. NULL,
  137426. 0
  137427. };
  137428. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137429. 6,
  137430. 5,
  137431. 7,
  137432. 4,
  137433. 8,
  137434. 3,
  137435. 9,
  137436. 2,
  137437. 10,
  137438. 1,
  137439. 11,
  137440. 0,
  137441. 12,
  137442. };
  137443. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137444. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137445. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137446. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137447. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137448. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137449. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137450. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137451. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137452. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137453. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137454. 20,13,13,12,12,16,13,15,13,
  137455. };
  137456. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137457. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137458. 42.5, 59.5, 76.5, 93.5,
  137459. };
  137460. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137461. 11, 9, 7, 5, 3, 1, 0, 2,
  137462. 4, 6, 8, 10, 12,
  137463. };
  137464. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137465. _vq_quantthresh__44c0_sm_p8_1,
  137466. _vq_quantmap__44c0_sm_p8_1,
  137467. 13,
  137468. 13
  137469. };
  137470. static static_codebook _44c0_sm_p8_1 = {
  137471. 2, 169,
  137472. _vq_lengthlist__44c0_sm_p8_1,
  137473. 1, -522616832, 1620115456, 4, 0,
  137474. _vq_quantlist__44c0_sm_p8_1,
  137475. NULL,
  137476. &_vq_auxt__44c0_sm_p8_1,
  137477. NULL,
  137478. 0
  137479. };
  137480. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137481. 8,
  137482. 7,
  137483. 9,
  137484. 6,
  137485. 10,
  137486. 5,
  137487. 11,
  137488. 4,
  137489. 12,
  137490. 3,
  137491. 13,
  137492. 2,
  137493. 14,
  137494. 1,
  137495. 15,
  137496. 0,
  137497. 16,
  137498. };
  137499. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  137500. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137501. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137502. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137503. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137504. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137505. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137506. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137507. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  137508. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  137509. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  137510. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  137511. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137512. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  137513. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  137514. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137515. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137516. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137517. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137518. 9,
  137519. };
  137520. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  137521. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137522. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137523. };
  137524. static long _vq_quantmap__44c0_sm_p8_2[] = {
  137525. 15, 13, 11, 9, 7, 5, 3, 1,
  137526. 0, 2, 4, 6, 8, 10, 12, 14,
  137527. 16,
  137528. };
  137529. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  137530. _vq_quantthresh__44c0_sm_p8_2,
  137531. _vq_quantmap__44c0_sm_p8_2,
  137532. 17,
  137533. 17
  137534. };
  137535. static static_codebook _44c0_sm_p8_2 = {
  137536. 2, 289,
  137537. _vq_lengthlist__44c0_sm_p8_2,
  137538. 1, -529530880, 1611661312, 5, 0,
  137539. _vq_quantlist__44c0_sm_p8_2,
  137540. NULL,
  137541. &_vq_auxt__44c0_sm_p8_2,
  137542. NULL,
  137543. 0
  137544. };
  137545. static long _huff_lengthlist__44c0_sm_short[] = {
  137546. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  137547. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  137548. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  137549. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  137550. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  137551. 12,
  137552. };
  137553. static static_codebook _huff_book__44c0_sm_short = {
  137554. 2, 81,
  137555. _huff_lengthlist__44c0_sm_short,
  137556. 0, 0, 0, 0, 0,
  137557. NULL,
  137558. NULL,
  137559. NULL,
  137560. NULL,
  137561. 0
  137562. };
  137563. static long _huff_lengthlist__44c1_s_long[] = {
  137564. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  137565. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  137566. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  137567. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  137568. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  137569. 11,
  137570. };
  137571. static static_codebook _huff_book__44c1_s_long = {
  137572. 2, 81,
  137573. _huff_lengthlist__44c1_s_long,
  137574. 0, 0, 0, 0, 0,
  137575. NULL,
  137576. NULL,
  137577. NULL,
  137578. NULL,
  137579. 0
  137580. };
  137581. static long _vq_quantlist__44c1_s_p1_0[] = {
  137582. 1,
  137583. 0,
  137584. 2,
  137585. };
  137586. static long _vq_lengthlist__44c1_s_p1_0[] = {
  137587. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  137588. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137592. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137593. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137597. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137598. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  137633. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137638. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  137639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  137643. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137678. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137679. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137683. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  137684. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  137685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137688. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137689. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137695. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137700. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137705. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  137740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  137745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  137750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137786. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137791. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  137998. };
  137999. static float _vq_quantthresh__44c1_s_p1_0[] = {
  138000. -0.5, 0.5,
  138001. };
  138002. static long _vq_quantmap__44c1_s_p1_0[] = {
  138003. 1, 0, 2,
  138004. };
  138005. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  138006. _vq_quantthresh__44c1_s_p1_0,
  138007. _vq_quantmap__44c1_s_p1_0,
  138008. 3,
  138009. 3
  138010. };
  138011. static static_codebook _44c1_s_p1_0 = {
  138012. 8, 6561,
  138013. _vq_lengthlist__44c1_s_p1_0,
  138014. 1, -535822336, 1611661312, 2, 0,
  138015. _vq_quantlist__44c1_s_p1_0,
  138016. NULL,
  138017. &_vq_auxt__44c1_s_p1_0,
  138018. NULL,
  138019. 0
  138020. };
  138021. static long _vq_quantlist__44c1_s_p2_0[] = {
  138022. 2,
  138023. 1,
  138024. 3,
  138025. 0,
  138026. 4,
  138027. };
  138028. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138029. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138032. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138035. 0, 0, 0, 0, 6, 6, 6, 8, 8, 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,
  138069. };
  138070. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138071. -1.5, -0.5, 0.5, 1.5,
  138072. };
  138073. static long _vq_quantmap__44c1_s_p2_0[] = {
  138074. 3, 1, 0, 2, 4,
  138075. };
  138076. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138077. _vq_quantthresh__44c1_s_p2_0,
  138078. _vq_quantmap__44c1_s_p2_0,
  138079. 5,
  138080. 5
  138081. };
  138082. static static_codebook _44c1_s_p2_0 = {
  138083. 4, 625,
  138084. _vq_lengthlist__44c1_s_p2_0,
  138085. 1, -533725184, 1611661312, 3, 0,
  138086. _vq_quantlist__44c1_s_p2_0,
  138087. NULL,
  138088. &_vq_auxt__44c1_s_p2_0,
  138089. NULL,
  138090. 0
  138091. };
  138092. static long _vq_quantlist__44c1_s_p3_0[] = {
  138093. 4,
  138094. 3,
  138095. 5,
  138096. 2,
  138097. 6,
  138098. 1,
  138099. 7,
  138100. 0,
  138101. 8,
  138102. };
  138103. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138104. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138105. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138106. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138107. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138108. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138109. 0,
  138110. };
  138111. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138112. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138113. };
  138114. static long _vq_quantmap__44c1_s_p3_0[] = {
  138115. 7, 5, 3, 1, 0, 2, 4, 6,
  138116. 8,
  138117. };
  138118. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138119. _vq_quantthresh__44c1_s_p3_0,
  138120. _vq_quantmap__44c1_s_p3_0,
  138121. 9,
  138122. 9
  138123. };
  138124. static static_codebook _44c1_s_p3_0 = {
  138125. 2, 81,
  138126. _vq_lengthlist__44c1_s_p3_0,
  138127. 1, -531628032, 1611661312, 4, 0,
  138128. _vq_quantlist__44c1_s_p3_0,
  138129. NULL,
  138130. &_vq_auxt__44c1_s_p3_0,
  138131. NULL,
  138132. 0
  138133. };
  138134. static long _vq_quantlist__44c1_s_p4_0[] = {
  138135. 4,
  138136. 3,
  138137. 5,
  138138. 2,
  138139. 6,
  138140. 1,
  138141. 7,
  138142. 0,
  138143. 8,
  138144. };
  138145. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138146. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138147. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138148. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138149. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138150. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138151. 11,
  138152. };
  138153. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138154. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138155. };
  138156. static long _vq_quantmap__44c1_s_p4_0[] = {
  138157. 7, 5, 3, 1, 0, 2, 4, 6,
  138158. 8,
  138159. };
  138160. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138161. _vq_quantthresh__44c1_s_p4_0,
  138162. _vq_quantmap__44c1_s_p4_0,
  138163. 9,
  138164. 9
  138165. };
  138166. static static_codebook _44c1_s_p4_0 = {
  138167. 2, 81,
  138168. _vq_lengthlist__44c1_s_p4_0,
  138169. 1, -531628032, 1611661312, 4, 0,
  138170. _vq_quantlist__44c1_s_p4_0,
  138171. NULL,
  138172. &_vq_auxt__44c1_s_p4_0,
  138173. NULL,
  138174. 0
  138175. };
  138176. static long _vq_quantlist__44c1_s_p5_0[] = {
  138177. 8,
  138178. 7,
  138179. 9,
  138180. 6,
  138181. 10,
  138182. 5,
  138183. 11,
  138184. 4,
  138185. 12,
  138186. 3,
  138187. 13,
  138188. 2,
  138189. 14,
  138190. 1,
  138191. 15,
  138192. 0,
  138193. 16,
  138194. };
  138195. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138196. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138197. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138198. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138199. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138200. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138201. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138202. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138203. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138204. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138205. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138206. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138207. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138208. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138209. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138210. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138211. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138212. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138213. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138214. 14,
  138215. };
  138216. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138217. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138218. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138219. };
  138220. static long _vq_quantmap__44c1_s_p5_0[] = {
  138221. 15, 13, 11, 9, 7, 5, 3, 1,
  138222. 0, 2, 4, 6, 8, 10, 12, 14,
  138223. 16,
  138224. };
  138225. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138226. _vq_quantthresh__44c1_s_p5_0,
  138227. _vq_quantmap__44c1_s_p5_0,
  138228. 17,
  138229. 17
  138230. };
  138231. static static_codebook _44c1_s_p5_0 = {
  138232. 2, 289,
  138233. _vq_lengthlist__44c1_s_p5_0,
  138234. 1, -529530880, 1611661312, 5, 0,
  138235. _vq_quantlist__44c1_s_p5_0,
  138236. NULL,
  138237. &_vq_auxt__44c1_s_p5_0,
  138238. NULL,
  138239. 0
  138240. };
  138241. static long _vq_quantlist__44c1_s_p6_0[] = {
  138242. 1,
  138243. 0,
  138244. 2,
  138245. };
  138246. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138247. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138248. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138249. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138250. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138251. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138252. 11,
  138253. };
  138254. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138255. -5.5, 5.5,
  138256. };
  138257. static long _vq_quantmap__44c1_s_p6_0[] = {
  138258. 1, 0, 2,
  138259. };
  138260. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138261. _vq_quantthresh__44c1_s_p6_0,
  138262. _vq_quantmap__44c1_s_p6_0,
  138263. 3,
  138264. 3
  138265. };
  138266. static static_codebook _44c1_s_p6_0 = {
  138267. 4, 81,
  138268. _vq_lengthlist__44c1_s_p6_0,
  138269. 1, -529137664, 1618345984, 2, 0,
  138270. _vq_quantlist__44c1_s_p6_0,
  138271. NULL,
  138272. &_vq_auxt__44c1_s_p6_0,
  138273. NULL,
  138274. 0
  138275. };
  138276. static long _vq_quantlist__44c1_s_p6_1[] = {
  138277. 5,
  138278. 4,
  138279. 6,
  138280. 3,
  138281. 7,
  138282. 2,
  138283. 8,
  138284. 1,
  138285. 9,
  138286. 0,
  138287. 10,
  138288. };
  138289. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138290. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138291. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138292. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138293. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138294. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138295. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138296. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138297. 10,10,10, 8, 8, 8, 8, 8, 8,
  138298. };
  138299. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138300. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138301. 3.5, 4.5,
  138302. };
  138303. static long _vq_quantmap__44c1_s_p6_1[] = {
  138304. 9, 7, 5, 3, 1, 0, 2, 4,
  138305. 6, 8, 10,
  138306. };
  138307. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138308. _vq_quantthresh__44c1_s_p6_1,
  138309. _vq_quantmap__44c1_s_p6_1,
  138310. 11,
  138311. 11
  138312. };
  138313. static static_codebook _44c1_s_p6_1 = {
  138314. 2, 121,
  138315. _vq_lengthlist__44c1_s_p6_1,
  138316. 1, -531365888, 1611661312, 4, 0,
  138317. _vq_quantlist__44c1_s_p6_1,
  138318. NULL,
  138319. &_vq_auxt__44c1_s_p6_1,
  138320. NULL,
  138321. 0
  138322. };
  138323. static long _vq_quantlist__44c1_s_p7_0[] = {
  138324. 6,
  138325. 5,
  138326. 7,
  138327. 4,
  138328. 8,
  138329. 3,
  138330. 9,
  138331. 2,
  138332. 10,
  138333. 1,
  138334. 11,
  138335. 0,
  138336. 12,
  138337. };
  138338. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138339. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138340. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138341. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138342. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138343. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138344. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138345. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138346. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138347. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138348. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138349. 0,12,11,11,11,13,10,14,13,
  138350. };
  138351. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138352. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138353. 12.5, 17.5, 22.5, 27.5,
  138354. };
  138355. static long _vq_quantmap__44c1_s_p7_0[] = {
  138356. 11, 9, 7, 5, 3, 1, 0, 2,
  138357. 4, 6, 8, 10, 12,
  138358. };
  138359. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138360. _vq_quantthresh__44c1_s_p7_0,
  138361. _vq_quantmap__44c1_s_p7_0,
  138362. 13,
  138363. 13
  138364. };
  138365. static static_codebook _44c1_s_p7_0 = {
  138366. 2, 169,
  138367. _vq_lengthlist__44c1_s_p7_0,
  138368. 1, -526516224, 1616117760, 4, 0,
  138369. _vq_quantlist__44c1_s_p7_0,
  138370. NULL,
  138371. &_vq_auxt__44c1_s_p7_0,
  138372. NULL,
  138373. 0
  138374. };
  138375. static long _vq_quantlist__44c1_s_p7_1[] = {
  138376. 2,
  138377. 1,
  138378. 3,
  138379. 0,
  138380. 4,
  138381. };
  138382. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138383. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138384. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138385. };
  138386. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138387. -1.5, -0.5, 0.5, 1.5,
  138388. };
  138389. static long _vq_quantmap__44c1_s_p7_1[] = {
  138390. 3, 1, 0, 2, 4,
  138391. };
  138392. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138393. _vq_quantthresh__44c1_s_p7_1,
  138394. _vq_quantmap__44c1_s_p7_1,
  138395. 5,
  138396. 5
  138397. };
  138398. static static_codebook _44c1_s_p7_1 = {
  138399. 2, 25,
  138400. _vq_lengthlist__44c1_s_p7_1,
  138401. 1, -533725184, 1611661312, 3, 0,
  138402. _vq_quantlist__44c1_s_p7_1,
  138403. NULL,
  138404. &_vq_auxt__44c1_s_p7_1,
  138405. NULL,
  138406. 0
  138407. };
  138408. static long _vq_quantlist__44c1_s_p8_0[] = {
  138409. 6,
  138410. 5,
  138411. 7,
  138412. 4,
  138413. 8,
  138414. 3,
  138415. 9,
  138416. 2,
  138417. 10,
  138418. 1,
  138419. 11,
  138420. 0,
  138421. 12,
  138422. };
  138423. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138424. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138425. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138426. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138427. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138428. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138429. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138430. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138431. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138432. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138433. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138434. 10,10,10,10,10,10,10,10,10,
  138435. };
  138436. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138437. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138438. 552.5, 773.5, 994.5, 1215.5,
  138439. };
  138440. static long _vq_quantmap__44c1_s_p8_0[] = {
  138441. 11, 9, 7, 5, 3, 1, 0, 2,
  138442. 4, 6, 8, 10, 12,
  138443. };
  138444. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138445. _vq_quantthresh__44c1_s_p8_0,
  138446. _vq_quantmap__44c1_s_p8_0,
  138447. 13,
  138448. 13
  138449. };
  138450. static static_codebook _44c1_s_p8_0 = {
  138451. 2, 169,
  138452. _vq_lengthlist__44c1_s_p8_0,
  138453. 1, -514541568, 1627103232, 4, 0,
  138454. _vq_quantlist__44c1_s_p8_0,
  138455. NULL,
  138456. &_vq_auxt__44c1_s_p8_0,
  138457. NULL,
  138458. 0
  138459. };
  138460. static long _vq_quantlist__44c1_s_p8_1[] = {
  138461. 6,
  138462. 5,
  138463. 7,
  138464. 4,
  138465. 8,
  138466. 3,
  138467. 9,
  138468. 2,
  138469. 10,
  138470. 1,
  138471. 11,
  138472. 0,
  138473. 12,
  138474. };
  138475. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138476. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138477. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138478. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138479. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138480. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138481. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138482. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138483. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138484. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138485. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138486. 16,13,12,12,11,14,12,15,13,
  138487. };
  138488. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138489. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138490. 42.5, 59.5, 76.5, 93.5,
  138491. };
  138492. static long _vq_quantmap__44c1_s_p8_1[] = {
  138493. 11, 9, 7, 5, 3, 1, 0, 2,
  138494. 4, 6, 8, 10, 12,
  138495. };
  138496. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  138497. _vq_quantthresh__44c1_s_p8_1,
  138498. _vq_quantmap__44c1_s_p8_1,
  138499. 13,
  138500. 13
  138501. };
  138502. static static_codebook _44c1_s_p8_1 = {
  138503. 2, 169,
  138504. _vq_lengthlist__44c1_s_p8_1,
  138505. 1, -522616832, 1620115456, 4, 0,
  138506. _vq_quantlist__44c1_s_p8_1,
  138507. NULL,
  138508. &_vq_auxt__44c1_s_p8_1,
  138509. NULL,
  138510. 0
  138511. };
  138512. static long _vq_quantlist__44c1_s_p8_2[] = {
  138513. 8,
  138514. 7,
  138515. 9,
  138516. 6,
  138517. 10,
  138518. 5,
  138519. 11,
  138520. 4,
  138521. 12,
  138522. 3,
  138523. 13,
  138524. 2,
  138525. 14,
  138526. 1,
  138527. 15,
  138528. 0,
  138529. 16,
  138530. };
  138531. static long _vq_lengthlist__44c1_s_p8_2[] = {
  138532. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138533. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138534. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138535. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138536. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138537. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138538. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138539. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  138540. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  138541. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  138542. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  138543. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  138544. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  138545. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  138546. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138547. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  138548. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  138549. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  138550. 9,
  138551. };
  138552. static float _vq_quantthresh__44c1_s_p8_2[] = {
  138553. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138554. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138555. };
  138556. static long _vq_quantmap__44c1_s_p8_2[] = {
  138557. 15, 13, 11, 9, 7, 5, 3, 1,
  138558. 0, 2, 4, 6, 8, 10, 12, 14,
  138559. 16,
  138560. };
  138561. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  138562. _vq_quantthresh__44c1_s_p8_2,
  138563. _vq_quantmap__44c1_s_p8_2,
  138564. 17,
  138565. 17
  138566. };
  138567. static static_codebook _44c1_s_p8_2 = {
  138568. 2, 289,
  138569. _vq_lengthlist__44c1_s_p8_2,
  138570. 1, -529530880, 1611661312, 5, 0,
  138571. _vq_quantlist__44c1_s_p8_2,
  138572. NULL,
  138573. &_vq_auxt__44c1_s_p8_2,
  138574. NULL,
  138575. 0
  138576. };
  138577. static long _huff_lengthlist__44c1_s_short[] = {
  138578. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  138579. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  138580. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  138581. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  138582. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  138583. 11,
  138584. };
  138585. static static_codebook _huff_book__44c1_s_short = {
  138586. 2, 81,
  138587. _huff_lengthlist__44c1_s_short,
  138588. 0, 0, 0, 0, 0,
  138589. NULL,
  138590. NULL,
  138591. NULL,
  138592. NULL,
  138593. 0
  138594. };
  138595. static long _huff_lengthlist__44c1_sm_long[] = {
  138596. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  138597. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  138598. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  138599. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  138600. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  138601. 11,
  138602. };
  138603. static static_codebook _huff_book__44c1_sm_long = {
  138604. 2, 81,
  138605. _huff_lengthlist__44c1_sm_long,
  138606. 0, 0, 0, 0, 0,
  138607. NULL,
  138608. NULL,
  138609. NULL,
  138610. NULL,
  138611. 0
  138612. };
  138613. static long _vq_quantlist__44c1_sm_p1_0[] = {
  138614. 1,
  138615. 0,
  138616. 2,
  138617. };
  138618. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  138619. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138620. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138624. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138625. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138629. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  138630. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  138665. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138670. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  138675. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138710. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138711. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138715. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138716. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  138717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138720. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138721. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  138722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138727. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138732. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138737. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  138772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  138777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  138782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138818. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138823. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  139030. };
  139031. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139032. -0.5, 0.5,
  139033. };
  139034. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139035. 1, 0, 2,
  139036. };
  139037. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139038. _vq_quantthresh__44c1_sm_p1_0,
  139039. _vq_quantmap__44c1_sm_p1_0,
  139040. 3,
  139041. 3
  139042. };
  139043. static static_codebook _44c1_sm_p1_0 = {
  139044. 8, 6561,
  139045. _vq_lengthlist__44c1_sm_p1_0,
  139046. 1, -535822336, 1611661312, 2, 0,
  139047. _vq_quantlist__44c1_sm_p1_0,
  139048. NULL,
  139049. &_vq_auxt__44c1_sm_p1_0,
  139050. NULL,
  139051. 0
  139052. };
  139053. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139054. 2,
  139055. 1,
  139056. 3,
  139057. 0,
  139058. 4,
  139059. };
  139060. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139061. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139064. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139067. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  139101. };
  139102. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139103. -1.5, -0.5, 0.5, 1.5,
  139104. };
  139105. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139106. 3, 1, 0, 2, 4,
  139107. };
  139108. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139109. _vq_quantthresh__44c1_sm_p2_0,
  139110. _vq_quantmap__44c1_sm_p2_0,
  139111. 5,
  139112. 5
  139113. };
  139114. static static_codebook _44c1_sm_p2_0 = {
  139115. 4, 625,
  139116. _vq_lengthlist__44c1_sm_p2_0,
  139117. 1, -533725184, 1611661312, 3, 0,
  139118. _vq_quantlist__44c1_sm_p2_0,
  139119. NULL,
  139120. &_vq_auxt__44c1_sm_p2_0,
  139121. NULL,
  139122. 0
  139123. };
  139124. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139125. 4,
  139126. 3,
  139127. 5,
  139128. 2,
  139129. 6,
  139130. 1,
  139131. 7,
  139132. 0,
  139133. 8,
  139134. };
  139135. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139136. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139137. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139138. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139139. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139140. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139141. 0,
  139142. };
  139143. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139144. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139145. };
  139146. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139147. 7, 5, 3, 1, 0, 2, 4, 6,
  139148. 8,
  139149. };
  139150. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139151. _vq_quantthresh__44c1_sm_p3_0,
  139152. _vq_quantmap__44c1_sm_p3_0,
  139153. 9,
  139154. 9
  139155. };
  139156. static static_codebook _44c1_sm_p3_0 = {
  139157. 2, 81,
  139158. _vq_lengthlist__44c1_sm_p3_0,
  139159. 1, -531628032, 1611661312, 4, 0,
  139160. _vq_quantlist__44c1_sm_p3_0,
  139161. NULL,
  139162. &_vq_auxt__44c1_sm_p3_0,
  139163. NULL,
  139164. 0
  139165. };
  139166. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139167. 4,
  139168. 3,
  139169. 5,
  139170. 2,
  139171. 6,
  139172. 1,
  139173. 7,
  139174. 0,
  139175. 8,
  139176. };
  139177. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139178. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139179. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139180. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139181. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139182. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139183. 11,
  139184. };
  139185. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139186. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139187. };
  139188. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139189. 7, 5, 3, 1, 0, 2, 4, 6,
  139190. 8,
  139191. };
  139192. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139193. _vq_quantthresh__44c1_sm_p4_0,
  139194. _vq_quantmap__44c1_sm_p4_0,
  139195. 9,
  139196. 9
  139197. };
  139198. static static_codebook _44c1_sm_p4_0 = {
  139199. 2, 81,
  139200. _vq_lengthlist__44c1_sm_p4_0,
  139201. 1, -531628032, 1611661312, 4, 0,
  139202. _vq_quantlist__44c1_sm_p4_0,
  139203. NULL,
  139204. &_vq_auxt__44c1_sm_p4_0,
  139205. NULL,
  139206. 0
  139207. };
  139208. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139209. 8,
  139210. 7,
  139211. 9,
  139212. 6,
  139213. 10,
  139214. 5,
  139215. 11,
  139216. 4,
  139217. 12,
  139218. 3,
  139219. 13,
  139220. 2,
  139221. 14,
  139222. 1,
  139223. 15,
  139224. 0,
  139225. 16,
  139226. };
  139227. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139228. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139229. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139230. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139231. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139232. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139233. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139234. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139235. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139236. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139237. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139238. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139239. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139240. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139241. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139242. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139243. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139244. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139245. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139246. 14,
  139247. };
  139248. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139249. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139250. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139251. };
  139252. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139253. 15, 13, 11, 9, 7, 5, 3, 1,
  139254. 0, 2, 4, 6, 8, 10, 12, 14,
  139255. 16,
  139256. };
  139257. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139258. _vq_quantthresh__44c1_sm_p5_0,
  139259. _vq_quantmap__44c1_sm_p5_0,
  139260. 17,
  139261. 17
  139262. };
  139263. static static_codebook _44c1_sm_p5_0 = {
  139264. 2, 289,
  139265. _vq_lengthlist__44c1_sm_p5_0,
  139266. 1, -529530880, 1611661312, 5, 0,
  139267. _vq_quantlist__44c1_sm_p5_0,
  139268. NULL,
  139269. &_vq_auxt__44c1_sm_p5_0,
  139270. NULL,
  139271. 0
  139272. };
  139273. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139274. 1,
  139275. 0,
  139276. 2,
  139277. };
  139278. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139279. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139280. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139281. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139282. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139283. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139284. 11,
  139285. };
  139286. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139287. -5.5, 5.5,
  139288. };
  139289. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139290. 1, 0, 2,
  139291. };
  139292. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139293. _vq_quantthresh__44c1_sm_p6_0,
  139294. _vq_quantmap__44c1_sm_p6_0,
  139295. 3,
  139296. 3
  139297. };
  139298. static static_codebook _44c1_sm_p6_0 = {
  139299. 4, 81,
  139300. _vq_lengthlist__44c1_sm_p6_0,
  139301. 1, -529137664, 1618345984, 2, 0,
  139302. _vq_quantlist__44c1_sm_p6_0,
  139303. NULL,
  139304. &_vq_auxt__44c1_sm_p6_0,
  139305. NULL,
  139306. 0
  139307. };
  139308. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139309. 5,
  139310. 4,
  139311. 6,
  139312. 3,
  139313. 7,
  139314. 2,
  139315. 8,
  139316. 1,
  139317. 9,
  139318. 0,
  139319. 10,
  139320. };
  139321. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139322. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139323. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139324. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139325. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139326. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139327. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139328. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139329. 10,10,10, 8, 8, 8, 8, 8, 8,
  139330. };
  139331. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139332. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139333. 3.5, 4.5,
  139334. };
  139335. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139336. 9, 7, 5, 3, 1, 0, 2, 4,
  139337. 6, 8, 10,
  139338. };
  139339. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139340. _vq_quantthresh__44c1_sm_p6_1,
  139341. _vq_quantmap__44c1_sm_p6_1,
  139342. 11,
  139343. 11
  139344. };
  139345. static static_codebook _44c1_sm_p6_1 = {
  139346. 2, 121,
  139347. _vq_lengthlist__44c1_sm_p6_1,
  139348. 1, -531365888, 1611661312, 4, 0,
  139349. _vq_quantlist__44c1_sm_p6_1,
  139350. NULL,
  139351. &_vq_auxt__44c1_sm_p6_1,
  139352. NULL,
  139353. 0
  139354. };
  139355. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139356. 6,
  139357. 5,
  139358. 7,
  139359. 4,
  139360. 8,
  139361. 3,
  139362. 9,
  139363. 2,
  139364. 10,
  139365. 1,
  139366. 11,
  139367. 0,
  139368. 12,
  139369. };
  139370. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139371. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139372. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139373. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139374. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139375. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139376. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139377. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139378. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139379. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139380. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139381. 0,12,12,11,11,13,12,14,13,
  139382. };
  139383. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139384. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139385. 12.5, 17.5, 22.5, 27.5,
  139386. };
  139387. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139388. 11, 9, 7, 5, 3, 1, 0, 2,
  139389. 4, 6, 8, 10, 12,
  139390. };
  139391. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139392. _vq_quantthresh__44c1_sm_p7_0,
  139393. _vq_quantmap__44c1_sm_p7_0,
  139394. 13,
  139395. 13
  139396. };
  139397. static static_codebook _44c1_sm_p7_0 = {
  139398. 2, 169,
  139399. _vq_lengthlist__44c1_sm_p7_0,
  139400. 1, -526516224, 1616117760, 4, 0,
  139401. _vq_quantlist__44c1_sm_p7_0,
  139402. NULL,
  139403. &_vq_auxt__44c1_sm_p7_0,
  139404. NULL,
  139405. 0
  139406. };
  139407. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139408. 2,
  139409. 1,
  139410. 3,
  139411. 0,
  139412. 4,
  139413. };
  139414. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139415. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139416. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139417. };
  139418. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139419. -1.5, -0.5, 0.5, 1.5,
  139420. };
  139421. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139422. 3, 1, 0, 2, 4,
  139423. };
  139424. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139425. _vq_quantthresh__44c1_sm_p7_1,
  139426. _vq_quantmap__44c1_sm_p7_1,
  139427. 5,
  139428. 5
  139429. };
  139430. static static_codebook _44c1_sm_p7_1 = {
  139431. 2, 25,
  139432. _vq_lengthlist__44c1_sm_p7_1,
  139433. 1, -533725184, 1611661312, 3, 0,
  139434. _vq_quantlist__44c1_sm_p7_1,
  139435. NULL,
  139436. &_vq_auxt__44c1_sm_p7_1,
  139437. NULL,
  139438. 0
  139439. };
  139440. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139441. 6,
  139442. 5,
  139443. 7,
  139444. 4,
  139445. 8,
  139446. 3,
  139447. 9,
  139448. 2,
  139449. 10,
  139450. 1,
  139451. 11,
  139452. 0,
  139453. 12,
  139454. };
  139455. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139456. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139457. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139458. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139459. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139460. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139461. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139462. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139463. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139464. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139465. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139466. 13,13,13,13,13,13,13,13,13,
  139467. };
  139468. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139469. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139470. 552.5, 773.5, 994.5, 1215.5,
  139471. };
  139472. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139473. 11, 9, 7, 5, 3, 1, 0, 2,
  139474. 4, 6, 8, 10, 12,
  139475. };
  139476. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139477. _vq_quantthresh__44c1_sm_p8_0,
  139478. _vq_quantmap__44c1_sm_p8_0,
  139479. 13,
  139480. 13
  139481. };
  139482. static static_codebook _44c1_sm_p8_0 = {
  139483. 2, 169,
  139484. _vq_lengthlist__44c1_sm_p8_0,
  139485. 1, -514541568, 1627103232, 4, 0,
  139486. _vq_quantlist__44c1_sm_p8_0,
  139487. NULL,
  139488. &_vq_auxt__44c1_sm_p8_0,
  139489. NULL,
  139490. 0
  139491. };
  139492. static long _vq_quantlist__44c1_sm_p8_1[] = {
  139493. 6,
  139494. 5,
  139495. 7,
  139496. 4,
  139497. 8,
  139498. 3,
  139499. 9,
  139500. 2,
  139501. 10,
  139502. 1,
  139503. 11,
  139504. 0,
  139505. 12,
  139506. };
  139507. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  139508. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  139509. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  139510. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  139511. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  139512. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  139513. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  139514. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  139515. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  139516. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  139517. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  139518. 20,13,12,12,12,14,12,14,13,
  139519. };
  139520. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  139521. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139522. 42.5, 59.5, 76.5, 93.5,
  139523. };
  139524. static long _vq_quantmap__44c1_sm_p8_1[] = {
  139525. 11, 9, 7, 5, 3, 1, 0, 2,
  139526. 4, 6, 8, 10, 12,
  139527. };
  139528. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  139529. _vq_quantthresh__44c1_sm_p8_1,
  139530. _vq_quantmap__44c1_sm_p8_1,
  139531. 13,
  139532. 13
  139533. };
  139534. static static_codebook _44c1_sm_p8_1 = {
  139535. 2, 169,
  139536. _vq_lengthlist__44c1_sm_p8_1,
  139537. 1, -522616832, 1620115456, 4, 0,
  139538. _vq_quantlist__44c1_sm_p8_1,
  139539. NULL,
  139540. &_vq_auxt__44c1_sm_p8_1,
  139541. NULL,
  139542. 0
  139543. };
  139544. static long _vq_quantlist__44c1_sm_p8_2[] = {
  139545. 8,
  139546. 7,
  139547. 9,
  139548. 6,
  139549. 10,
  139550. 5,
  139551. 11,
  139552. 4,
  139553. 12,
  139554. 3,
  139555. 13,
  139556. 2,
  139557. 14,
  139558. 1,
  139559. 15,
  139560. 0,
  139561. 16,
  139562. };
  139563. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  139564. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139565. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139566. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  139567. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139568. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  139569. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139570. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139571. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  139572. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  139573. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139574. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  139575. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  139576. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  139577. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  139578. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139579. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  139580. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139581. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  139582. 9,
  139583. };
  139584. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  139585. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139586. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139587. };
  139588. static long _vq_quantmap__44c1_sm_p8_2[] = {
  139589. 15, 13, 11, 9, 7, 5, 3, 1,
  139590. 0, 2, 4, 6, 8, 10, 12, 14,
  139591. 16,
  139592. };
  139593. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  139594. _vq_quantthresh__44c1_sm_p8_2,
  139595. _vq_quantmap__44c1_sm_p8_2,
  139596. 17,
  139597. 17
  139598. };
  139599. static static_codebook _44c1_sm_p8_2 = {
  139600. 2, 289,
  139601. _vq_lengthlist__44c1_sm_p8_2,
  139602. 1, -529530880, 1611661312, 5, 0,
  139603. _vq_quantlist__44c1_sm_p8_2,
  139604. NULL,
  139605. &_vq_auxt__44c1_sm_p8_2,
  139606. NULL,
  139607. 0
  139608. };
  139609. static long _huff_lengthlist__44c1_sm_short[] = {
  139610. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  139611. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  139612. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  139613. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  139614. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  139615. 11,
  139616. };
  139617. static static_codebook _huff_book__44c1_sm_short = {
  139618. 2, 81,
  139619. _huff_lengthlist__44c1_sm_short,
  139620. 0, 0, 0, 0, 0,
  139621. NULL,
  139622. NULL,
  139623. NULL,
  139624. NULL,
  139625. 0
  139626. };
  139627. static long _huff_lengthlist__44cn1_s_long[] = {
  139628. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  139629. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  139630. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  139631. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  139632. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  139633. 20,
  139634. };
  139635. static static_codebook _huff_book__44cn1_s_long = {
  139636. 2, 81,
  139637. _huff_lengthlist__44cn1_s_long,
  139638. 0, 0, 0, 0, 0,
  139639. NULL,
  139640. NULL,
  139641. NULL,
  139642. NULL,
  139643. 0
  139644. };
  139645. static long _vq_quantlist__44cn1_s_p1_0[] = {
  139646. 1,
  139647. 0,
  139648. 2,
  139649. };
  139650. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  139651. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139652. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139656. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  139657. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139661. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  139662. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  139697. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  139698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  139702. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  139707. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  139708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139742. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  139743. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139747. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139748. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  139749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139752. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  139753. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  139754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139759. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139764. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139769. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  139804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  139809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  139814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139850. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139855. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  140062. };
  140063. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140064. -0.5, 0.5,
  140065. };
  140066. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140067. 1, 0, 2,
  140068. };
  140069. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140070. _vq_quantthresh__44cn1_s_p1_0,
  140071. _vq_quantmap__44cn1_s_p1_0,
  140072. 3,
  140073. 3
  140074. };
  140075. static static_codebook _44cn1_s_p1_0 = {
  140076. 8, 6561,
  140077. _vq_lengthlist__44cn1_s_p1_0,
  140078. 1, -535822336, 1611661312, 2, 0,
  140079. _vq_quantlist__44cn1_s_p1_0,
  140080. NULL,
  140081. &_vq_auxt__44cn1_s_p1_0,
  140082. NULL,
  140083. 0
  140084. };
  140085. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140086. 2,
  140087. 1,
  140088. 3,
  140089. 0,
  140090. 4,
  140091. };
  140092. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140093. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140096. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140099. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  140133. };
  140134. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140135. -1.5, -0.5, 0.5, 1.5,
  140136. };
  140137. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140138. 3, 1, 0, 2, 4,
  140139. };
  140140. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140141. _vq_quantthresh__44cn1_s_p2_0,
  140142. _vq_quantmap__44cn1_s_p2_0,
  140143. 5,
  140144. 5
  140145. };
  140146. static static_codebook _44cn1_s_p2_0 = {
  140147. 4, 625,
  140148. _vq_lengthlist__44cn1_s_p2_0,
  140149. 1, -533725184, 1611661312, 3, 0,
  140150. _vq_quantlist__44cn1_s_p2_0,
  140151. NULL,
  140152. &_vq_auxt__44cn1_s_p2_0,
  140153. NULL,
  140154. 0
  140155. };
  140156. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140157. 4,
  140158. 3,
  140159. 5,
  140160. 2,
  140161. 6,
  140162. 1,
  140163. 7,
  140164. 0,
  140165. 8,
  140166. };
  140167. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140168. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140169. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140170. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140171. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140172. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140173. 0,
  140174. };
  140175. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140176. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140177. };
  140178. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140179. 7, 5, 3, 1, 0, 2, 4, 6,
  140180. 8,
  140181. };
  140182. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140183. _vq_quantthresh__44cn1_s_p3_0,
  140184. _vq_quantmap__44cn1_s_p3_0,
  140185. 9,
  140186. 9
  140187. };
  140188. static static_codebook _44cn1_s_p3_0 = {
  140189. 2, 81,
  140190. _vq_lengthlist__44cn1_s_p3_0,
  140191. 1, -531628032, 1611661312, 4, 0,
  140192. _vq_quantlist__44cn1_s_p3_0,
  140193. NULL,
  140194. &_vq_auxt__44cn1_s_p3_0,
  140195. NULL,
  140196. 0
  140197. };
  140198. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140199. 4,
  140200. 3,
  140201. 5,
  140202. 2,
  140203. 6,
  140204. 1,
  140205. 7,
  140206. 0,
  140207. 8,
  140208. };
  140209. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140210. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140211. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140212. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140213. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140214. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140215. 11,
  140216. };
  140217. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140218. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140219. };
  140220. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140221. 7, 5, 3, 1, 0, 2, 4, 6,
  140222. 8,
  140223. };
  140224. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140225. _vq_quantthresh__44cn1_s_p4_0,
  140226. _vq_quantmap__44cn1_s_p4_0,
  140227. 9,
  140228. 9
  140229. };
  140230. static static_codebook _44cn1_s_p4_0 = {
  140231. 2, 81,
  140232. _vq_lengthlist__44cn1_s_p4_0,
  140233. 1, -531628032, 1611661312, 4, 0,
  140234. _vq_quantlist__44cn1_s_p4_0,
  140235. NULL,
  140236. &_vq_auxt__44cn1_s_p4_0,
  140237. NULL,
  140238. 0
  140239. };
  140240. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140241. 8,
  140242. 7,
  140243. 9,
  140244. 6,
  140245. 10,
  140246. 5,
  140247. 11,
  140248. 4,
  140249. 12,
  140250. 3,
  140251. 13,
  140252. 2,
  140253. 14,
  140254. 1,
  140255. 15,
  140256. 0,
  140257. 16,
  140258. };
  140259. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140260. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140261. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140262. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140263. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140264. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140265. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140266. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140267. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140268. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140269. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140270. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140271. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140272. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140273. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140274. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140275. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140276. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140277. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140278. 14,
  140279. };
  140280. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140281. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140282. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140283. };
  140284. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140285. 15, 13, 11, 9, 7, 5, 3, 1,
  140286. 0, 2, 4, 6, 8, 10, 12, 14,
  140287. 16,
  140288. };
  140289. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140290. _vq_quantthresh__44cn1_s_p5_0,
  140291. _vq_quantmap__44cn1_s_p5_0,
  140292. 17,
  140293. 17
  140294. };
  140295. static static_codebook _44cn1_s_p5_0 = {
  140296. 2, 289,
  140297. _vq_lengthlist__44cn1_s_p5_0,
  140298. 1, -529530880, 1611661312, 5, 0,
  140299. _vq_quantlist__44cn1_s_p5_0,
  140300. NULL,
  140301. &_vq_auxt__44cn1_s_p5_0,
  140302. NULL,
  140303. 0
  140304. };
  140305. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140306. 1,
  140307. 0,
  140308. 2,
  140309. };
  140310. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140311. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140312. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140313. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140314. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140315. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140316. 10,
  140317. };
  140318. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140319. -5.5, 5.5,
  140320. };
  140321. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140322. 1, 0, 2,
  140323. };
  140324. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140325. _vq_quantthresh__44cn1_s_p6_0,
  140326. _vq_quantmap__44cn1_s_p6_0,
  140327. 3,
  140328. 3
  140329. };
  140330. static static_codebook _44cn1_s_p6_0 = {
  140331. 4, 81,
  140332. _vq_lengthlist__44cn1_s_p6_0,
  140333. 1, -529137664, 1618345984, 2, 0,
  140334. _vq_quantlist__44cn1_s_p6_0,
  140335. NULL,
  140336. &_vq_auxt__44cn1_s_p6_0,
  140337. NULL,
  140338. 0
  140339. };
  140340. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140341. 5,
  140342. 4,
  140343. 6,
  140344. 3,
  140345. 7,
  140346. 2,
  140347. 8,
  140348. 1,
  140349. 9,
  140350. 0,
  140351. 10,
  140352. };
  140353. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140354. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140355. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140356. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140357. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140358. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140359. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140360. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140361. 10,10,10, 9, 9, 9, 9, 9, 9,
  140362. };
  140363. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140364. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140365. 3.5, 4.5,
  140366. };
  140367. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140368. 9, 7, 5, 3, 1, 0, 2, 4,
  140369. 6, 8, 10,
  140370. };
  140371. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140372. _vq_quantthresh__44cn1_s_p6_1,
  140373. _vq_quantmap__44cn1_s_p6_1,
  140374. 11,
  140375. 11
  140376. };
  140377. static static_codebook _44cn1_s_p6_1 = {
  140378. 2, 121,
  140379. _vq_lengthlist__44cn1_s_p6_1,
  140380. 1, -531365888, 1611661312, 4, 0,
  140381. _vq_quantlist__44cn1_s_p6_1,
  140382. NULL,
  140383. &_vq_auxt__44cn1_s_p6_1,
  140384. NULL,
  140385. 0
  140386. };
  140387. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140388. 6,
  140389. 5,
  140390. 7,
  140391. 4,
  140392. 8,
  140393. 3,
  140394. 9,
  140395. 2,
  140396. 10,
  140397. 1,
  140398. 11,
  140399. 0,
  140400. 12,
  140401. };
  140402. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140403. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140404. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140405. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140406. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140407. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140408. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140409. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140410. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140411. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140412. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140413. 0,13,13,12,12,13,13,13,14,
  140414. };
  140415. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140416. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140417. 12.5, 17.5, 22.5, 27.5,
  140418. };
  140419. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140420. 11, 9, 7, 5, 3, 1, 0, 2,
  140421. 4, 6, 8, 10, 12,
  140422. };
  140423. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140424. _vq_quantthresh__44cn1_s_p7_0,
  140425. _vq_quantmap__44cn1_s_p7_0,
  140426. 13,
  140427. 13
  140428. };
  140429. static static_codebook _44cn1_s_p7_0 = {
  140430. 2, 169,
  140431. _vq_lengthlist__44cn1_s_p7_0,
  140432. 1, -526516224, 1616117760, 4, 0,
  140433. _vq_quantlist__44cn1_s_p7_0,
  140434. NULL,
  140435. &_vq_auxt__44cn1_s_p7_0,
  140436. NULL,
  140437. 0
  140438. };
  140439. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140440. 2,
  140441. 1,
  140442. 3,
  140443. 0,
  140444. 4,
  140445. };
  140446. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140447. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140448. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140449. };
  140450. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140451. -1.5, -0.5, 0.5, 1.5,
  140452. };
  140453. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140454. 3, 1, 0, 2, 4,
  140455. };
  140456. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140457. _vq_quantthresh__44cn1_s_p7_1,
  140458. _vq_quantmap__44cn1_s_p7_1,
  140459. 5,
  140460. 5
  140461. };
  140462. static static_codebook _44cn1_s_p7_1 = {
  140463. 2, 25,
  140464. _vq_lengthlist__44cn1_s_p7_1,
  140465. 1, -533725184, 1611661312, 3, 0,
  140466. _vq_quantlist__44cn1_s_p7_1,
  140467. NULL,
  140468. &_vq_auxt__44cn1_s_p7_1,
  140469. NULL,
  140470. 0
  140471. };
  140472. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140473. 2,
  140474. 1,
  140475. 3,
  140476. 0,
  140477. 4,
  140478. };
  140479. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140480. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140481. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140482. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140483. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140484. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140485. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140486. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140487. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140488. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140489. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140490. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140491. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140492. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140493. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140494. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140495. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  140496. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140497. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140498. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140499. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140500. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140501. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140502. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140503. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140504. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140505. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140506. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140507. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140508. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140509. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140510. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140511. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140512. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140513. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  140514. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140515. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140516. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140517. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140518. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140519. 12,
  140520. };
  140521. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  140522. -331.5, -110.5, 110.5, 331.5,
  140523. };
  140524. static long _vq_quantmap__44cn1_s_p8_0[] = {
  140525. 3, 1, 0, 2, 4,
  140526. };
  140527. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  140528. _vq_quantthresh__44cn1_s_p8_0,
  140529. _vq_quantmap__44cn1_s_p8_0,
  140530. 5,
  140531. 5
  140532. };
  140533. static static_codebook _44cn1_s_p8_0 = {
  140534. 4, 625,
  140535. _vq_lengthlist__44cn1_s_p8_0,
  140536. 1, -518283264, 1627103232, 3, 0,
  140537. _vq_quantlist__44cn1_s_p8_0,
  140538. NULL,
  140539. &_vq_auxt__44cn1_s_p8_0,
  140540. NULL,
  140541. 0
  140542. };
  140543. static long _vq_quantlist__44cn1_s_p8_1[] = {
  140544. 6,
  140545. 5,
  140546. 7,
  140547. 4,
  140548. 8,
  140549. 3,
  140550. 9,
  140551. 2,
  140552. 10,
  140553. 1,
  140554. 11,
  140555. 0,
  140556. 12,
  140557. };
  140558. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  140559. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  140560. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  140561. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  140562. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  140563. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  140564. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  140565. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  140566. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  140567. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  140568. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  140569. 15,12,12,11,11,14,12,13,14,
  140570. };
  140571. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  140572. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140573. 42.5, 59.5, 76.5, 93.5,
  140574. };
  140575. static long _vq_quantmap__44cn1_s_p8_1[] = {
  140576. 11, 9, 7, 5, 3, 1, 0, 2,
  140577. 4, 6, 8, 10, 12,
  140578. };
  140579. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  140580. _vq_quantthresh__44cn1_s_p8_1,
  140581. _vq_quantmap__44cn1_s_p8_1,
  140582. 13,
  140583. 13
  140584. };
  140585. static static_codebook _44cn1_s_p8_1 = {
  140586. 2, 169,
  140587. _vq_lengthlist__44cn1_s_p8_1,
  140588. 1, -522616832, 1620115456, 4, 0,
  140589. _vq_quantlist__44cn1_s_p8_1,
  140590. NULL,
  140591. &_vq_auxt__44cn1_s_p8_1,
  140592. NULL,
  140593. 0
  140594. };
  140595. static long _vq_quantlist__44cn1_s_p8_2[] = {
  140596. 8,
  140597. 7,
  140598. 9,
  140599. 6,
  140600. 10,
  140601. 5,
  140602. 11,
  140603. 4,
  140604. 12,
  140605. 3,
  140606. 13,
  140607. 2,
  140608. 14,
  140609. 1,
  140610. 15,
  140611. 0,
  140612. 16,
  140613. };
  140614. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  140615. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140616. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140617. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140618. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  140619. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  140620. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  140621. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  140622. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  140623. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  140624. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  140625. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  140626. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  140627. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  140628. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  140629. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  140630. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140631. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140632. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  140633. 9,
  140634. };
  140635. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  140636. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140637. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140638. };
  140639. static long _vq_quantmap__44cn1_s_p8_2[] = {
  140640. 15, 13, 11, 9, 7, 5, 3, 1,
  140641. 0, 2, 4, 6, 8, 10, 12, 14,
  140642. 16,
  140643. };
  140644. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  140645. _vq_quantthresh__44cn1_s_p8_2,
  140646. _vq_quantmap__44cn1_s_p8_2,
  140647. 17,
  140648. 17
  140649. };
  140650. static static_codebook _44cn1_s_p8_2 = {
  140651. 2, 289,
  140652. _vq_lengthlist__44cn1_s_p8_2,
  140653. 1, -529530880, 1611661312, 5, 0,
  140654. _vq_quantlist__44cn1_s_p8_2,
  140655. NULL,
  140656. &_vq_auxt__44cn1_s_p8_2,
  140657. NULL,
  140658. 0
  140659. };
  140660. static long _huff_lengthlist__44cn1_s_short[] = {
  140661. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  140662. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  140663. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  140664. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  140665. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  140666. 10,
  140667. };
  140668. static static_codebook _huff_book__44cn1_s_short = {
  140669. 2, 81,
  140670. _huff_lengthlist__44cn1_s_short,
  140671. 0, 0, 0, 0, 0,
  140672. NULL,
  140673. NULL,
  140674. NULL,
  140675. NULL,
  140676. 0
  140677. };
  140678. static long _huff_lengthlist__44cn1_sm_long[] = {
  140679. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  140680. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  140681. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  140682. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  140683. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  140684. 17,
  140685. };
  140686. static static_codebook _huff_book__44cn1_sm_long = {
  140687. 2, 81,
  140688. _huff_lengthlist__44cn1_sm_long,
  140689. 0, 0, 0, 0, 0,
  140690. NULL,
  140691. NULL,
  140692. NULL,
  140693. NULL,
  140694. 0
  140695. };
  140696. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  140697. 1,
  140698. 0,
  140699. 2,
  140700. };
  140701. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  140702. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140703. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140707. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140708. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140712. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  140713. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  140748. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  140753. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  140758. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  140759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140793. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140794. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140798. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140799. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  140800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140803. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  140804. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  140805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140810. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140815. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140820. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  140855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  140860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  140865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140901. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140906. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  141113. };
  141114. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141115. -0.5, 0.5,
  141116. };
  141117. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141118. 1, 0, 2,
  141119. };
  141120. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141121. _vq_quantthresh__44cn1_sm_p1_0,
  141122. _vq_quantmap__44cn1_sm_p1_0,
  141123. 3,
  141124. 3
  141125. };
  141126. static static_codebook _44cn1_sm_p1_0 = {
  141127. 8, 6561,
  141128. _vq_lengthlist__44cn1_sm_p1_0,
  141129. 1, -535822336, 1611661312, 2, 0,
  141130. _vq_quantlist__44cn1_sm_p1_0,
  141131. NULL,
  141132. &_vq_auxt__44cn1_sm_p1_0,
  141133. NULL,
  141134. 0
  141135. };
  141136. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141137. 2,
  141138. 1,
  141139. 3,
  141140. 0,
  141141. 4,
  141142. };
  141143. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141144. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141147. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141150. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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,
  141184. };
  141185. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141186. -1.5, -0.5, 0.5, 1.5,
  141187. };
  141188. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141189. 3, 1, 0, 2, 4,
  141190. };
  141191. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141192. _vq_quantthresh__44cn1_sm_p2_0,
  141193. _vq_quantmap__44cn1_sm_p2_0,
  141194. 5,
  141195. 5
  141196. };
  141197. static static_codebook _44cn1_sm_p2_0 = {
  141198. 4, 625,
  141199. _vq_lengthlist__44cn1_sm_p2_0,
  141200. 1, -533725184, 1611661312, 3, 0,
  141201. _vq_quantlist__44cn1_sm_p2_0,
  141202. NULL,
  141203. &_vq_auxt__44cn1_sm_p2_0,
  141204. NULL,
  141205. 0
  141206. };
  141207. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141208. 4,
  141209. 3,
  141210. 5,
  141211. 2,
  141212. 6,
  141213. 1,
  141214. 7,
  141215. 0,
  141216. 8,
  141217. };
  141218. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141219. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141220. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141221. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141222. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141223. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141224. 0,
  141225. };
  141226. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141227. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141228. };
  141229. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141230. 7, 5, 3, 1, 0, 2, 4, 6,
  141231. 8,
  141232. };
  141233. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141234. _vq_quantthresh__44cn1_sm_p3_0,
  141235. _vq_quantmap__44cn1_sm_p3_0,
  141236. 9,
  141237. 9
  141238. };
  141239. static static_codebook _44cn1_sm_p3_0 = {
  141240. 2, 81,
  141241. _vq_lengthlist__44cn1_sm_p3_0,
  141242. 1, -531628032, 1611661312, 4, 0,
  141243. _vq_quantlist__44cn1_sm_p3_0,
  141244. NULL,
  141245. &_vq_auxt__44cn1_sm_p3_0,
  141246. NULL,
  141247. 0
  141248. };
  141249. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141250. 4,
  141251. 3,
  141252. 5,
  141253. 2,
  141254. 6,
  141255. 1,
  141256. 7,
  141257. 0,
  141258. 8,
  141259. };
  141260. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141261. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141262. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141263. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141264. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141265. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141266. 11,
  141267. };
  141268. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141269. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141270. };
  141271. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141272. 7, 5, 3, 1, 0, 2, 4, 6,
  141273. 8,
  141274. };
  141275. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141276. _vq_quantthresh__44cn1_sm_p4_0,
  141277. _vq_quantmap__44cn1_sm_p4_0,
  141278. 9,
  141279. 9
  141280. };
  141281. static static_codebook _44cn1_sm_p4_0 = {
  141282. 2, 81,
  141283. _vq_lengthlist__44cn1_sm_p4_0,
  141284. 1, -531628032, 1611661312, 4, 0,
  141285. _vq_quantlist__44cn1_sm_p4_0,
  141286. NULL,
  141287. &_vq_auxt__44cn1_sm_p4_0,
  141288. NULL,
  141289. 0
  141290. };
  141291. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141292. 8,
  141293. 7,
  141294. 9,
  141295. 6,
  141296. 10,
  141297. 5,
  141298. 11,
  141299. 4,
  141300. 12,
  141301. 3,
  141302. 13,
  141303. 2,
  141304. 14,
  141305. 1,
  141306. 15,
  141307. 0,
  141308. 16,
  141309. };
  141310. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141311. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141312. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141313. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141314. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141315. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141316. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141317. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141318. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141319. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141320. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141321. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141322. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141323. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141324. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141325. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141326. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141327. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141328. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141329. 14,
  141330. };
  141331. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141332. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141333. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141334. };
  141335. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141336. 15, 13, 11, 9, 7, 5, 3, 1,
  141337. 0, 2, 4, 6, 8, 10, 12, 14,
  141338. 16,
  141339. };
  141340. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141341. _vq_quantthresh__44cn1_sm_p5_0,
  141342. _vq_quantmap__44cn1_sm_p5_0,
  141343. 17,
  141344. 17
  141345. };
  141346. static static_codebook _44cn1_sm_p5_0 = {
  141347. 2, 289,
  141348. _vq_lengthlist__44cn1_sm_p5_0,
  141349. 1, -529530880, 1611661312, 5, 0,
  141350. _vq_quantlist__44cn1_sm_p5_0,
  141351. NULL,
  141352. &_vq_auxt__44cn1_sm_p5_0,
  141353. NULL,
  141354. 0
  141355. };
  141356. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141357. 1,
  141358. 0,
  141359. 2,
  141360. };
  141361. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141362. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141363. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141364. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141365. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141366. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141367. 10,
  141368. };
  141369. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141370. -5.5, 5.5,
  141371. };
  141372. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141373. 1, 0, 2,
  141374. };
  141375. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141376. _vq_quantthresh__44cn1_sm_p6_0,
  141377. _vq_quantmap__44cn1_sm_p6_0,
  141378. 3,
  141379. 3
  141380. };
  141381. static static_codebook _44cn1_sm_p6_0 = {
  141382. 4, 81,
  141383. _vq_lengthlist__44cn1_sm_p6_0,
  141384. 1, -529137664, 1618345984, 2, 0,
  141385. _vq_quantlist__44cn1_sm_p6_0,
  141386. NULL,
  141387. &_vq_auxt__44cn1_sm_p6_0,
  141388. NULL,
  141389. 0
  141390. };
  141391. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141392. 5,
  141393. 4,
  141394. 6,
  141395. 3,
  141396. 7,
  141397. 2,
  141398. 8,
  141399. 1,
  141400. 9,
  141401. 0,
  141402. 10,
  141403. };
  141404. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141405. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141406. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141407. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141408. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141409. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141410. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141411. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141412. 10,10,10, 8, 9, 8, 8, 9, 8,
  141413. };
  141414. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141415. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141416. 3.5, 4.5,
  141417. };
  141418. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141419. 9, 7, 5, 3, 1, 0, 2, 4,
  141420. 6, 8, 10,
  141421. };
  141422. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141423. _vq_quantthresh__44cn1_sm_p6_1,
  141424. _vq_quantmap__44cn1_sm_p6_1,
  141425. 11,
  141426. 11
  141427. };
  141428. static static_codebook _44cn1_sm_p6_1 = {
  141429. 2, 121,
  141430. _vq_lengthlist__44cn1_sm_p6_1,
  141431. 1, -531365888, 1611661312, 4, 0,
  141432. _vq_quantlist__44cn1_sm_p6_1,
  141433. NULL,
  141434. &_vq_auxt__44cn1_sm_p6_1,
  141435. NULL,
  141436. 0
  141437. };
  141438. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141439. 6,
  141440. 5,
  141441. 7,
  141442. 4,
  141443. 8,
  141444. 3,
  141445. 9,
  141446. 2,
  141447. 10,
  141448. 1,
  141449. 11,
  141450. 0,
  141451. 12,
  141452. };
  141453. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141454. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141455. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141456. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141457. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141458. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141459. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141460. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141461. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141462. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141463. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141464. 0,13,12,12,12,13,13,13,14,
  141465. };
  141466. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141467. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141468. 12.5, 17.5, 22.5, 27.5,
  141469. };
  141470. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141471. 11, 9, 7, 5, 3, 1, 0, 2,
  141472. 4, 6, 8, 10, 12,
  141473. };
  141474. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141475. _vq_quantthresh__44cn1_sm_p7_0,
  141476. _vq_quantmap__44cn1_sm_p7_0,
  141477. 13,
  141478. 13
  141479. };
  141480. static static_codebook _44cn1_sm_p7_0 = {
  141481. 2, 169,
  141482. _vq_lengthlist__44cn1_sm_p7_0,
  141483. 1, -526516224, 1616117760, 4, 0,
  141484. _vq_quantlist__44cn1_sm_p7_0,
  141485. NULL,
  141486. &_vq_auxt__44cn1_sm_p7_0,
  141487. NULL,
  141488. 0
  141489. };
  141490. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141491. 2,
  141492. 1,
  141493. 3,
  141494. 0,
  141495. 4,
  141496. };
  141497. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  141498. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  141499. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  141500. };
  141501. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  141502. -1.5, -0.5, 0.5, 1.5,
  141503. };
  141504. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  141505. 3, 1, 0, 2, 4,
  141506. };
  141507. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  141508. _vq_quantthresh__44cn1_sm_p7_1,
  141509. _vq_quantmap__44cn1_sm_p7_1,
  141510. 5,
  141511. 5
  141512. };
  141513. static static_codebook _44cn1_sm_p7_1 = {
  141514. 2, 25,
  141515. _vq_lengthlist__44cn1_sm_p7_1,
  141516. 1, -533725184, 1611661312, 3, 0,
  141517. _vq_quantlist__44cn1_sm_p7_1,
  141518. NULL,
  141519. &_vq_auxt__44cn1_sm_p7_1,
  141520. NULL,
  141521. 0
  141522. };
  141523. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  141524. 4,
  141525. 3,
  141526. 5,
  141527. 2,
  141528. 6,
  141529. 1,
  141530. 7,
  141531. 0,
  141532. 8,
  141533. };
  141534. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  141535. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  141536. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  141537. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  141538. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  141539. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  141540. 14,
  141541. };
  141542. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  141543. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  141544. };
  141545. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  141546. 7, 5, 3, 1, 0, 2, 4, 6,
  141547. 8,
  141548. };
  141549. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  141550. _vq_quantthresh__44cn1_sm_p8_0,
  141551. _vq_quantmap__44cn1_sm_p8_0,
  141552. 9,
  141553. 9
  141554. };
  141555. static static_codebook _44cn1_sm_p8_0 = {
  141556. 2, 81,
  141557. _vq_lengthlist__44cn1_sm_p8_0,
  141558. 1, -516186112, 1627103232, 4, 0,
  141559. _vq_quantlist__44cn1_sm_p8_0,
  141560. NULL,
  141561. &_vq_auxt__44cn1_sm_p8_0,
  141562. NULL,
  141563. 0
  141564. };
  141565. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  141566. 6,
  141567. 5,
  141568. 7,
  141569. 4,
  141570. 8,
  141571. 3,
  141572. 9,
  141573. 2,
  141574. 10,
  141575. 1,
  141576. 11,
  141577. 0,
  141578. 12,
  141579. };
  141580. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  141581. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  141582. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  141583. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  141584. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  141585. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  141586. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  141587. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  141588. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  141589. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  141590. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  141591. 17,12,12,11,10,13,11,13,13,
  141592. };
  141593. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  141594. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141595. 42.5, 59.5, 76.5, 93.5,
  141596. };
  141597. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  141598. 11, 9, 7, 5, 3, 1, 0, 2,
  141599. 4, 6, 8, 10, 12,
  141600. };
  141601. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  141602. _vq_quantthresh__44cn1_sm_p8_1,
  141603. _vq_quantmap__44cn1_sm_p8_1,
  141604. 13,
  141605. 13
  141606. };
  141607. static static_codebook _44cn1_sm_p8_1 = {
  141608. 2, 169,
  141609. _vq_lengthlist__44cn1_sm_p8_1,
  141610. 1, -522616832, 1620115456, 4, 0,
  141611. _vq_quantlist__44cn1_sm_p8_1,
  141612. NULL,
  141613. &_vq_auxt__44cn1_sm_p8_1,
  141614. NULL,
  141615. 0
  141616. };
  141617. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  141618. 8,
  141619. 7,
  141620. 9,
  141621. 6,
  141622. 10,
  141623. 5,
  141624. 11,
  141625. 4,
  141626. 12,
  141627. 3,
  141628. 13,
  141629. 2,
  141630. 14,
  141631. 1,
  141632. 15,
  141633. 0,
  141634. 16,
  141635. };
  141636. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  141637. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  141638. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  141639. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  141640. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  141641. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  141642. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  141643. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  141644. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  141645. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  141646. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  141647. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  141648. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  141649. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  141650. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  141651. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  141652. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141653. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141654. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  141655. 9,
  141656. };
  141657. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  141658. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141659. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141660. };
  141661. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  141662. 15, 13, 11, 9, 7, 5, 3, 1,
  141663. 0, 2, 4, 6, 8, 10, 12, 14,
  141664. 16,
  141665. };
  141666. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  141667. _vq_quantthresh__44cn1_sm_p8_2,
  141668. _vq_quantmap__44cn1_sm_p8_2,
  141669. 17,
  141670. 17
  141671. };
  141672. static static_codebook _44cn1_sm_p8_2 = {
  141673. 2, 289,
  141674. _vq_lengthlist__44cn1_sm_p8_2,
  141675. 1, -529530880, 1611661312, 5, 0,
  141676. _vq_quantlist__44cn1_sm_p8_2,
  141677. NULL,
  141678. &_vq_auxt__44cn1_sm_p8_2,
  141679. NULL,
  141680. 0
  141681. };
  141682. static long _huff_lengthlist__44cn1_sm_short[] = {
  141683. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  141684. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  141685. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  141686. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  141687. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  141688. 9,
  141689. };
  141690. static static_codebook _huff_book__44cn1_sm_short = {
  141691. 2, 81,
  141692. _huff_lengthlist__44cn1_sm_short,
  141693. 0, 0, 0, 0, 0,
  141694. NULL,
  141695. NULL,
  141696. NULL,
  141697. NULL,
  141698. 0
  141699. };
  141700. /*** End of inlined file: res_books_stereo.h ***/
  141701. /***** residue backends *********************************************/
  141702. static vorbis_info_residue0 _residue_44_low={
  141703. 0,-1, -1, 9,-1,
  141704. /* 0 1 2 3 4 5 6 7 */
  141705. {0},
  141706. {-1},
  141707. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141708. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  141709. };
  141710. static vorbis_info_residue0 _residue_44_mid={
  141711. 0,-1, -1, 10,-1,
  141712. /* 0 1 2 3 4 5 6 7 8 */
  141713. {0},
  141714. {-1},
  141715. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141716. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  141717. };
  141718. static vorbis_info_residue0 _residue_44_high={
  141719. 0,-1, -1, 10,-1,
  141720. /* 0 1 2 3 4 5 6 7 8 */
  141721. {0},
  141722. {-1},
  141723. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  141724. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  141725. };
  141726. static static_bookblock _resbook_44s_n1={
  141727. {
  141728. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  141729. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  141730. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  141731. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  141732. }
  141733. };
  141734. static static_bookblock _resbook_44sm_n1={
  141735. {
  141736. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  141737. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  141738. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  141739. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  141740. }
  141741. };
  141742. static static_bookblock _resbook_44s_0={
  141743. {
  141744. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  141745. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  141746. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  141747. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  141748. }
  141749. };
  141750. static static_bookblock _resbook_44sm_0={
  141751. {
  141752. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  141753. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  141754. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  141755. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  141756. }
  141757. };
  141758. static static_bookblock _resbook_44s_1={
  141759. {
  141760. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  141761. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  141762. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  141763. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  141764. }
  141765. };
  141766. static static_bookblock _resbook_44sm_1={
  141767. {
  141768. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  141769. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  141770. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  141771. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  141772. }
  141773. };
  141774. static static_bookblock _resbook_44s_2={
  141775. {
  141776. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  141777. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  141778. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  141779. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  141780. }
  141781. };
  141782. static static_bookblock _resbook_44s_3={
  141783. {
  141784. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  141785. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  141786. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  141787. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  141788. }
  141789. };
  141790. static static_bookblock _resbook_44s_4={
  141791. {
  141792. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  141793. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  141794. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  141795. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  141796. }
  141797. };
  141798. static static_bookblock _resbook_44s_5={
  141799. {
  141800. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  141801. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  141802. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  141803. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  141804. }
  141805. };
  141806. static static_bookblock _resbook_44s_6={
  141807. {
  141808. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  141809. {0,0,&_44c6_s_p4_0},
  141810. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  141811. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  141812. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  141813. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  141814. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  141815. }
  141816. };
  141817. static static_bookblock _resbook_44s_7={
  141818. {
  141819. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  141820. {0,0,&_44c7_s_p4_0},
  141821. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  141822. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  141823. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  141824. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  141825. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  141826. }
  141827. };
  141828. static static_bookblock _resbook_44s_8={
  141829. {
  141830. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  141831. {0,0,&_44c8_s_p4_0},
  141832. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  141833. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  141834. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  141835. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  141836. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  141837. }
  141838. };
  141839. static static_bookblock _resbook_44s_9={
  141840. {
  141841. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  141842. {0,0,&_44c9_s_p4_0},
  141843. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  141844. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  141845. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  141846. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  141847. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  141848. }
  141849. };
  141850. static vorbis_residue_template _res_44s_n1[]={
  141851. {2,0, &_residue_44_low,
  141852. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  141853. &_resbook_44s_n1,&_resbook_44sm_n1},
  141854. {2,0, &_residue_44_low,
  141855. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  141856. &_resbook_44s_n1,&_resbook_44sm_n1}
  141857. };
  141858. static vorbis_residue_template _res_44s_0[]={
  141859. {2,0, &_residue_44_low,
  141860. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  141861. &_resbook_44s_0,&_resbook_44sm_0},
  141862. {2,0, &_residue_44_low,
  141863. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  141864. &_resbook_44s_0,&_resbook_44sm_0}
  141865. };
  141866. static vorbis_residue_template _res_44s_1[]={
  141867. {2,0, &_residue_44_low,
  141868. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  141869. &_resbook_44s_1,&_resbook_44sm_1},
  141870. {2,0, &_residue_44_low,
  141871. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  141872. &_resbook_44s_1,&_resbook_44sm_1}
  141873. };
  141874. static vorbis_residue_template _res_44s_2[]={
  141875. {2,0, &_residue_44_mid,
  141876. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  141877. &_resbook_44s_2,&_resbook_44s_2},
  141878. {2,0, &_residue_44_mid,
  141879. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  141880. &_resbook_44s_2,&_resbook_44s_2}
  141881. };
  141882. static vorbis_residue_template _res_44s_3[]={
  141883. {2,0, &_residue_44_mid,
  141884. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  141885. &_resbook_44s_3,&_resbook_44s_3},
  141886. {2,0, &_residue_44_mid,
  141887. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  141888. &_resbook_44s_3,&_resbook_44s_3}
  141889. };
  141890. static vorbis_residue_template _res_44s_4[]={
  141891. {2,0, &_residue_44_mid,
  141892. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  141893. &_resbook_44s_4,&_resbook_44s_4},
  141894. {2,0, &_residue_44_mid,
  141895. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  141896. &_resbook_44s_4,&_resbook_44s_4}
  141897. };
  141898. static vorbis_residue_template _res_44s_5[]={
  141899. {2,0, &_residue_44_mid,
  141900. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  141901. &_resbook_44s_5,&_resbook_44s_5},
  141902. {2,0, &_residue_44_mid,
  141903. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  141904. &_resbook_44s_5,&_resbook_44s_5}
  141905. };
  141906. static vorbis_residue_template _res_44s_6[]={
  141907. {2,0, &_residue_44_high,
  141908. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  141909. &_resbook_44s_6,&_resbook_44s_6},
  141910. {2,0, &_residue_44_high,
  141911. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  141912. &_resbook_44s_6,&_resbook_44s_6}
  141913. };
  141914. static vorbis_residue_template _res_44s_7[]={
  141915. {2,0, &_residue_44_high,
  141916. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  141917. &_resbook_44s_7,&_resbook_44s_7},
  141918. {2,0, &_residue_44_high,
  141919. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  141920. &_resbook_44s_7,&_resbook_44s_7}
  141921. };
  141922. static vorbis_residue_template _res_44s_8[]={
  141923. {2,0, &_residue_44_high,
  141924. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  141925. &_resbook_44s_8,&_resbook_44s_8},
  141926. {2,0, &_residue_44_high,
  141927. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  141928. &_resbook_44s_8,&_resbook_44s_8}
  141929. };
  141930. static vorbis_residue_template _res_44s_9[]={
  141931. {2,0, &_residue_44_high,
  141932. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  141933. &_resbook_44s_9,&_resbook_44s_9},
  141934. {2,0, &_residue_44_high,
  141935. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  141936. &_resbook_44s_9,&_resbook_44s_9}
  141937. };
  141938. static vorbis_mapping_template _mapres_template_44_stereo[]={
  141939. { _map_nominal, _res_44s_n1 }, /* -1 */
  141940. { _map_nominal, _res_44s_0 }, /* 0 */
  141941. { _map_nominal, _res_44s_1 }, /* 1 */
  141942. { _map_nominal, _res_44s_2 }, /* 2 */
  141943. { _map_nominal, _res_44s_3 }, /* 3 */
  141944. { _map_nominal, _res_44s_4 }, /* 4 */
  141945. { _map_nominal, _res_44s_5 }, /* 5 */
  141946. { _map_nominal, _res_44s_6 }, /* 6 */
  141947. { _map_nominal, _res_44s_7 }, /* 7 */
  141948. { _map_nominal, _res_44s_8 }, /* 8 */
  141949. { _map_nominal, _res_44s_9 }, /* 9 */
  141950. };
  141951. /*** End of inlined file: residue_44.h ***/
  141952. /*** Start of inlined file: psych_44.h ***/
  141953. /* preecho trigger settings *****************************************/
  141954. static vorbis_info_psy_global _psy_global_44[5]={
  141955. {8, /* lines per eighth octave */
  141956. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  141957. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  141958. -6.f,
  141959. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141960. },
  141961. {8, /* lines per eighth octave */
  141962. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141963. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  141964. -6.f,
  141965. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141966. },
  141967. {8, /* lines per eighth octave */
  141968. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141969. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  141970. -6.f,
  141971. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141972. },
  141973. {8, /* lines per eighth octave */
  141974. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  141975. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  141976. -6.f,
  141977. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141978. },
  141979. {8, /* lines per eighth octave */
  141980. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  141981. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  141982. -6.f,
  141983. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141984. },
  141985. };
  141986. /* noise compander lookups * low, mid, high quality ****************/
  141987. static compandblock _psy_compand_44[6]={
  141988. /* sub-mode Z short */
  141989. {{
  141990. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141991. 8, 9,10,11,12,13,14, 15, /* 15dB */
  141992. 16,17,18,19,20,21,22, 23, /* 23dB */
  141993. 24,25,26,27,28,29,30, 31, /* 31dB */
  141994. 32,33,34,35,36,37,38, 39, /* 39dB */
  141995. }},
  141996. /* mode_Z nominal short */
  141997. {{
  141998. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  141999. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  142000. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  142001. 15,16,17,17,17,18,18, 19, /* 31dB */
  142002. 19,19,20,21,22,23,24, 25, /* 39dB */
  142003. }},
  142004. /* mode A short */
  142005. {{
  142006. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142007. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142008. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142009. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142010. 11,12,13,14,15,16,17, 18, /* 39dB */
  142011. }},
  142012. /* sub-mode Z long */
  142013. {{
  142014. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142015. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142016. 16,17,18,19,20,21,22, 23, /* 23dB */
  142017. 24,25,26,27,28,29,30, 31, /* 31dB */
  142018. 32,33,34,35,36,37,38, 39, /* 39dB */
  142019. }},
  142020. /* mode_Z nominal long */
  142021. {{
  142022. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142023. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142024. 13,14,14,14,15,15,15, 15, /* 23dB */
  142025. 16,16,17,17,17,18,18, 19, /* 31dB */
  142026. 19,19,20,21,22,23,24, 25, /* 39dB */
  142027. }},
  142028. /* mode A long */
  142029. {{
  142030. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142031. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142032. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142033. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142034. 11,12,13,14,15,16,17, 18, /* 39dB */
  142035. }}
  142036. };
  142037. /* tonal masking curve level adjustments *************************/
  142038. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142039. /* 63 125 250 500 1 2 4 8 16 */
  142040. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142041. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142042. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142043. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142044. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142045. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142046. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142047. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142048. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142049. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142050. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142051. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142052. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142053. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142054. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142055. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142056. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142057. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142058. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142059. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142060. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142061. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142062. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142063. };
  142064. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142065. /* 63 125 250 500 1 2 4 8 16 */
  142066. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142067. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142068. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142069. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142070. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142071. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142072. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142073. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142074. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142075. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  142076. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142077. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142078. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142079. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142080. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142081. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142082. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142083. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142084. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142085. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142086. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142087. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142088. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142089. };
  142090. /* noise bias (transition block) */
  142091. static noise3 _psy_noisebias_trans[12]={
  142092. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142093. /* -1 */
  142094. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142095. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142096. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142097. /* 0
  142098. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142099. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142100. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142101. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142102. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142103. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142104. /* 1
  142105. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142106. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142107. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142108. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142109. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142110. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142111. /* 2
  142112. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142113. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142114. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142115. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142116. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142117. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142118. /* 3
  142119. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142120. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142121. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142122. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142123. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142124. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142125. /* 4
  142126. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142127. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142128. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142129. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142130. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142131. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142132. /* 5
  142133. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142134. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142135. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142136. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142137. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142138. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142139. /* 6
  142140. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142141. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142142. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142143. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142144. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142145. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142146. /* 7
  142147. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142148. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142149. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142150. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142151. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142152. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142153. /* 8
  142154. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142155. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142156. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142157. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142158. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142159. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142160. /* 9
  142161. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142162. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142163. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142164. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142165. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142166. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142167. /* 10 */
  142168. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142169. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142170. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142171. };
  142172. /* noise bias (long block) */
  142173. static noise3 _psy_noisebias_long[12]={
  142174. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142175. /* -1 */
  142176. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142177. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142178. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142179. /* 0 */
  142180. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142181. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142182. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142183. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142184. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142185. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142186. /* 1 */
  142187. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142188. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142189. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142190. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142191. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142192. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142193. /* 2 */
  142194. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142195. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142196. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142197. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142198. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142199. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142200. /* 3 */
  142201. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142202. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142203. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142204. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142205. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142206. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142207. /* 4 */
  142208. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142209. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142210. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142211. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142212. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142213. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142214. /* 5 */
  142215. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142216. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142217. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142218. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142219. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142220. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142221. /* 6 */
  142222. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142223. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142224. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142225. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142226. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142227. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142228. /* 7 */
  142229. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142230. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142231. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142232. /* 8 */
  142233. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142234. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142235. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142236. /* 9 */
  142237. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142238. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142239. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142240. /* 10 */
  142241. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142242. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142243. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142244. };
  142245. /* noise bias (impulse block) */
  142246. static noise3 _psy_noisebias_impulse[12]={
  142247. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142248. /* -1 */
  142249. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142250. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142251. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142252. /* 0 */
  142253. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142254. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142255. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142256. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142257. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142258. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142259. /* 1 */
  142260. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142261. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142262. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142263. /* 2 */
  142264. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142265. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142266. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142267. /* 3 */
  142268. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142269. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142270. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142271. /* 4 */
  142272. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142273. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142274. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142275. /* 5 */
  142276. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142277. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142278. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142279. /* 6
  142280. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142281. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142282. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142283. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142284. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142285. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142286. /* 7 */
  142287. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142288. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142289. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142290. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142291. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142292. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142293. /* 8 */
  142294. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142295. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142296. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142297. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142298. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142299. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142300. /* 9 */
  142301. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142302. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142303. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142304. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142305. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142306. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142307. /* 10 */
  142308. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142309. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142310. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142311. };
  142312. /* noise bias (padding block) */
  142313. static noise3 _psy_noisebias_padding[12]={
  142314. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142315. /* -1 */
  142316. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142317. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142318. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142319. /* 0 */
  142320. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142321. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142322. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142323. /* 1 */
  142324. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142325. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142326. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142327. /* 2 */
  142328. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142329. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142330. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142331. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142332. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142333. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142334. /* 3 */
  142335. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142336. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142337. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142338. /* 4 */
  142339. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142340. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142341. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142342. /* 5 */
  142343. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142344. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142345. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142346. /* 6 */
  142347. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142348. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142349. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142350. /* 7 */
  142351. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142352. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142353. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142354. /* 8 */
  142355. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142356. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142357. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142358. /* 9 */
  142359. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142360. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142361. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142362. /* 10 */
  142363. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142364. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142365. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142366. };
  142367. static noiseguard _psy_noiseguards_44[4]={
  142368. {3,3,15},
  142369. {3,3,15},
  142370. {10,10,100},
  142371. {10,10,100},
  142372. };
  142373. static int _psy_tone_suppress[12]={
  142374. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142375. };
  142376. static int _psy_tone_0dB[12]={
  142377. 90,90,95,95,95,95,105,105,105,105,105,105,
  142378. };
  142379. static int _psy_noise_suppress[12]={
  142380. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142381. };
  142382. static vorbis_info_psy _psy_info_template={
  142383. /* blockflag */
  142384. -1,
  142385. /* ath_adjatt, ath_maxatt */
  142386. -140.,-140.,
  142387. /* tonemask att boost/decay,suppr,curves */
  142388. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142389. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142390. 1, -0.f, .5f, .5f, 0,0,0,
  142391. /* noiseoffset*3, noisecompand, max_curve_dB */
  142392. {{-1},{-1},{-1}},{-1},105.f,
  142393. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142394. 0,0,-1,-1,0.,
  142395. };
  142396. /* ath ****************/
  142397. static int _psy_ath_floater[12]={
  142398. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142399. };
  142400. static int _psy_ath_abs[12]={
  142401. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142402. };
  142403. /* stereo setup. These don't map directly to quality level, there's
  142404. an additional indirection as several of the below may be used in a
  142405. single bitmanaged stream
  142406. ****************/
  142407. /* various stereo possibilities */
  142408. /* stereo mode by base quality level */
  142409. static adj_stereo _psy_stereo_modes_44[12]={
  142410. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142411. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142412. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142413. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142414. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142415. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142416. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142417. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142418. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142419. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142420. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142421. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142422. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142423. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142424. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142425. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142426. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142427. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142428. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142429. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142430. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142431. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142432. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142433. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142434. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142435. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142436. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142437. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142438. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142439. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142440. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142441. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142442. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142443. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142444. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142445. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142446. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142447. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142448. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142449. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142450. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142451. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142452. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142453. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142454. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142455. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142456. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142457. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142458. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142459. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142460. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142461. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142462. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142463. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142464. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142465. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142466. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142467. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142468. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142469. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142470. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142471. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142472. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142473. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142474. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142475. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142476. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142477. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142478. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142479. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142480. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142481. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142482. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142483. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142484. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142485. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142486. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142487. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142488. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142489. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142490. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142491. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142492. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142493. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142494. };
  142495. /* tone master attenuation by base quality mode and bitrate tweak */
  142496. static att3 _psy_tone_masteratt_44[12]={
  142497. {{ 35, 21, 9}, 0, 0}, /* -1 */
  142498. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  142499. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  142500. {{ 25, 12, 2}, 0, 0}, /* 1 */
  142501. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  142502. {{ 20, 9, -3}, 0, 0}, /* 2 */
  142503. {{ 20, 9, -4}, 0, 0}, /* 3 */
  142504. {{ 20, 9, -4}, 0, 0}, /* 4 */
  142505. {{ 20, 6, -6}, 0, 0}, /* 5 */
  142506. {{ 20, 3, -10}, 0, 0}, /* 6 */
  142507. {{ 18, 1, -14}, 0, 0}, /* 7 */
  142508. {{ 18, 0, -16}, 0, 0}, /* 8 */
  142509. {{ 18, -2, -16}, 0, 0}, /* 9 */
  142510. {{ 12, -2, -20}, 0, 0}, /* 10 */
  142511. };
  142512. /* lowpass by mode **************/
  142513. static double _psy_lowpass_44[12]={
  142514. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  142515. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  142516. };
  142517. /* noise normalization **********/
  142518. static int _noise_start_short_44[11]={
  142519. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  142520. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  142521. };
  142522. static int _noise_start_long_44[11]={
  142523. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  142524. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  142525. };
  142526. static int _noise_part_short_44[11]={
  142527. 8,8,8,8,8,8,8,8,8,8,8
  142528. };
  142529. static int _noise_part_long_44[11]={
  142530. 32,32,32,32,32,32,32,32,32,32,32
  142531. };
  142532. static double _noise_thresh_44[11]={
  142533. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  142534. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  142535. };
  142536. static double _noise_thresh_5only[2]={
  142537. .5,.5,
  142538. };
  142539. /*** End of inlined file: psych_44.h ***/
  142540. static double rate_mapping_44_stereo[12]={
  142541. 22500.,32000.,40000.,48000.,56000.,64000.,
  142542. 80000.,96000.,112000.,128000.,160000.,250001.
  142543. };
  142544. static double quality_mapping_44[12]={
  142545. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  142546. };
  142547. static int blocksize_short_44[11]={
  142548. 512,256,256,256,256,256,256,256,256,256,256
  142549. };
  142550. static int blocksize_long_44[11]={
  142551. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  142552. };
  142553. static double _psy_compand_short_mapping[12]={
  142554. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  142555. };
  142556. static double _psy_compand_long_mapping[12]={
  142557. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  142558. };
  142559. static double _global_mapping_44[12]={
  142560. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  142561. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  142562. };
  142563. static int _floor_short_mapping_44[11]={
  142564. 1,0,0,2,2,4,5,5,5,5,5
  142565. };
  142566. static int _floor_long_mapping_44[11]={
  142567. 8,7,7,7,7,7,7,7,7,7,7
  142568. };
  142569. ve_setup_data_template ve_setup_44_stereo={
  142570. 11,
  142571. rate_mapping_44_stereo,
  142572. quality_mapping_44,
  142573. 2,
  142574. 40000,
  142575. 50000,
  142576. blocksize_short_44,
  142577. blocksize_long_44,
  142578. _psy_tone_masteratt_44,
  142579. _psy_tone_0dB,
  142580. _psy_tone_suppress,
  142581. _vp_tonemask_adj_otherblock,
  142582. _vp_tonemask_adj_longblock,
  142583. _vp_tonemask_adj_otherblock,
  142584. _psy_noiseguards_44,
  142585. _psy_noisebias_impulse,
  142586. _psy_noisebias_padding,
  142587. _psy_noisebias_trans,
  142588. _psy_noisebias_long,
  142589. _psy_noise_suppress,
  142590. _psy_compand_44,
  142591. _psy_compand_short_mapping,
  142592. _psy_compand_long_mapping,
  142593. {_noise_start_short_44,_noise_start_long_44},
  142594. {_noise_part_short_44,_noise_part_long_44},
  142595. _noise_thresh_44,
  142596. _psy_ath_floater,
  142597. _psy_ath_abs,
  142598. _psy_lowpass_44,
  142599. _psy_global_44,
  142600. _global_mapping_44,
  142601. _psy_stereo_modes_44,
  142602. _floor_books,
  142603. _floor,
  142604. _floor_short_mapping_44,
  142605. _floor_long_mapping_44,
  142606. _mapres_template_44_stereo
  142607. };
  142608. /*** End of inlined file: setup_44.h ***/
  142609. /*** Start of inlined file: setup_44u.h ***/
  142610. /*** Start of inlined file: residue_44u.h ***/
  142611. /*** Start of inlined file: res_books_uncoupled.h ***/
  142612. static long _vq_quantlist__16u0__p1_0[] = {
  142613. 1,
  142614. 0,
  142615. 2,
  142616. };
  142617. static long _vq_lengthlist__16u0__p1_0[] = {
  142618. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  142619. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  142620. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  142621. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  142622. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  142623. 12,
  142624. };
  142625. static float _vq_quantthresh__16u0__p1_0[] = {
  142626. -0.5, 0.5,
  142627. };
  142628. static long _vq_quantmap__16u0__p1_0[] = {
  142629. 1, 0, 2,
  142630. };
  142631. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  142632. _vq_quantthresh__16u0__p1_0,
  142633. _vq_quantmap__16u0__p1_0,
  142634. 3,
  142635. 3
  142636. };
  142637. static static_codebook _16u0__p1_0 = {
  142638. 4, 81,
  142639. _vq_lengthlist__16u0__p1_0,
  142640. 1, -535822336, 1611661312, 2, 0,
  142641. _vq_quantlist__16u0__p1_0,
  142642. NULL,
  142643. &_vq_auxt__16u0__p1_0,
  142644. NULL,
  142645. 0
  142646. };
  142647. static long _vq_quantlist__16u0__p2_0[] = {
  142648. 1,
  142649. 0,
  142650. 2,
  142651. };
  142652. static long _vq_lengthlist__16u0__p2_0[] = {
  142653. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  142654. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  142655. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  142656. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  142657. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  142658. 8,
  142659. };
  142660. static float _vq_quantthresh__16u0__p2_0[] = {
  142661. -0.5, 0.5,
  142662. };
  142663. static long _vq_quantmap__16u0__p2_0[] = {
  142664. 1, 0, 2,
  142665. };
  142666. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  142667. _vq_quantthresh__16u0__p2_0,
  142668. _vq_quantmap__16u0__p2_0,
  142669. 3,
  142670. 3
  142671. };
  142672. static static_codebook _16u0__p2_0 = {
  142673. 4, 81,
  142674. _vq_lengthlist__16u0__p2_0,
  142675. 1, -535822336, 1611661312, 2, 0,
  142676. _vq_quantlist__16u0__p2_0,
  142677. NULL,
  142678. &_vq_auxt__16u0__p2_0,
  142679. NULL,
  142680. 0
  142681. };
  142682. static long _vq_quantlist__16u0__p3_0[] = {
  142683. 2,
  142684. 1,
  142685. 3,
  142686. 0,
  142687. 4,
  142688. };
  142689. static long _vq_lengthlist__16u0__p3_0[] = {
  142690. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  142691. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  142692. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  142693. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  142694. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  142695. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  142696. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  142697. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  142698. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  142699. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  142700. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  142701. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  142702. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  142703. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  142704. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  142705. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  142706. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  142707. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  142708. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  142709. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  142710. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  142711. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  142712. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  142713. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  142714. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  142715. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  142716. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  142717. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  142718. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  142719. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  142720. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  142721. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  142722. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  142723. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  142724. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  142725. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  142726. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  142727. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  142728. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  142729. 18,
  142730. };
  142731. static float _vq_quantthresh__16u0__p3_0[] = {
  142732. -1.5, -0.5, 0.5, 1.5,
  142733. };
  142734. static long _vq_quantmap__16u0__p3_0[] = {
  142735. 3, 1, 0, 2, 4,
  142736. };
  142737. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  142738. _vq_quantthresh__16u0__p3_0,
  142739. _vq_quantmap__16u0__p3_0,
  142740. 5,
  142741. 5
  142742. };
  142743. static static_codebook _16u0__p3_0 = {
  142744. 4, 625,
  142745. _vq_lengthlist__16u0__p3_0,
  142746. 1, -533725184, 1611661312, 3, 0,
  142747. _vq_quantlist__16u0__p3_0,
  142748. NULL,
  142749. &_vq_auxt__16u0__p3_0,
  142750. NULL,
  142751. 0
  142752. };
  142753. static long _vq_quantlist__16u0__p4_0[] = {
  142754. 2,
  142755. 1,
  142756. 3,
  142757. 0,
  142758. 4,
  142759. };
  142760. static long _vq_lengthlist__16u0__p4_0[] = {
  142761. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  142762. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  142763. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  142764. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  142765. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  142766. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  142767. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  142768. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  142769. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  142770. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  142771. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  142772. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  142773. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  142774. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  142775. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  142776. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  142777. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  142778. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  142779. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  142780. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  142781. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  142782. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  142783. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  142784. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  142785. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  142786. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  142787. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  142788. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  142789. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  142790. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  142791. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  142792. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  142793. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  142794. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  142795. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  142796. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  142797. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  142798. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  142799. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  142800. 11,
  142801. };
  142802. static float _vq_quantthresh__16u0__p4_0[] = {
  142803. -1.5, -0.5, 0.5, 1.5,
  142804. };
  142805. static long _vq_quantmap__16u0__p4_0[] = {
  142806. 3, 1, 0, 2, 4,
  142807. };
  142808. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  142809. _vq_quantthresh__16u0__p4_0,
  142810. _vq_quantmap__16u0__p4_0,
  142811. 5,
  142812. 5
  142813. };
  142814. static static_codebook _16u0__p4_0 = {
  142815. 4, 625,
  142816. _vq_lengthlist__16u0__p4_0,
  142817. 1, -533725184, 1611661312, 3, 0,
  142818. _vq_quantlist__16u0__p4_0,
  142819. NULL,
  142820. &_vq_auxt__16u0__p4_0,
  142821. NULL,
  142822. 0
  142823. };
  142824. static long _vq_quantlist__16u0__p5_0[] = {
  142825. 4,
  142826. 3,
  142827. 5,
  142828. 2,
  142829. 6,
  142830. 1,
  142831. 7,
  142832. 0,
  142833. 8,
  142834. };
  142835. static long _vq_lengthlist__16u0__p5_0[] = {
  142836. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142837. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142838. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  142839. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142840. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  142841. 12,
  142842. };
  142843. static float _vq_quantthresh__16u0__p5_0[] = {
  142844. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142845. };
  142846. static long _vq_quantmap__16u0__p5_0[] = {
  142847. 7, 5, 3, 1, 0, 2, 4, 6,
  142848. 8,
  142849. };
  142850. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  142851. _vq_quantthresh__16u0__p5_0,
  142852. _vq_quantmap__16u0__p5_0,
  142853. 9,
  142854. 9
  142855. };
  142856. static static_codebook _16u0__p5_0 = {
  142857. 2, 81,
  142858. _vq_lengthlist__16u0__p5_0,
  142859. 1, -531628032, 1611661312, 4, 0,
  142860. _vq_quantlist__16u0__p5_0,
  142861. NULL,
  142862. &_vq_auxt__16u0__p5_0,
  142863. NULL,
  142864. 0
  142865. };
  142866. static long _vq_quantlist__16u0__p6_0[] = {
  142867. 6,
  142868. 5,
  142869. 7,
  142870. 4,
  142871. 8,
  142872. 3,
  142873. 9,
  142874. 2,
  142875. 10,
  142876. 1,
  142877. 11,
  142878. 0,
  142879. 12,
  142880. };
  142881. static long _vq_lengthlist__16u0__p6_0[] = {
  142882. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  142883. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  142884. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  142885. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  142886. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  142887. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  142888. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  142889. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  142890. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  142891. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  142892. 18, 0,19, 0, 0, 0, 0, 0, 0,
  142893. };
  142894. static float _vq_quantthresh__16u0__p6_0[] = {
  142895. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142896. 12.5, 17.5, 22.5, 27.5,
  142897. };
  142898. static long _vq_quantmap__16u0__p6_0[] = {
  142899. 11, 9, 7, 5, 3, 1, 0, 2,
  142900. 4, 6, 8, 10, 12,
  142901. };
  142902. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  142903. _vq_quantthresh__16u0__p6_0,
  142904. _vq_quantmap__16u0__p6_0,
  142905. 13,
  142906. 13
  142907. };
  142908. static static_codebook _16u0__p6_0 = {
  142909. 2, 169,
  142910. _vq_lengthlist__16u0__p6_0,
  142911. 1, -526516224, 1616117760, 4, 0,
  142912. _vq_quantlist__16u0__p6_0,
  142913. NULL,
  142914. &_vq_auxt__16u0__p6_0,
  142915. NULL,
  142916. 0
  142917. };
  142918. static long _vq_quantlist__16u0__p6_1[] = {
  142919. 2,
  142920. 1,
  142921. 3,
  142922. 0,
  142923. 4,
  142924. };
  142925. static long _vq_lengthlist__16u0__p6_1[] = {
  142926. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  142927. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  142928. };
  142929. static float _vq_quantthresh__16u0__p6_1[] = {
  142930. -1.5, -0.5, 0.5, 1.5,
  142931. };
  142932. static long _vq_quantmap__16u0__p6_1[] = {
  142933. 3, 1, 0, 2, 4,
  142934. };
  142935. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  142936. _vq_quantthresh__16u0__p6_1,
  142937. _vq_quantmap__16u0__p6_1,
  142938. 5,
  142939. 5
  142940. };
  142941. static static_codebook _16u0__p6_1 = {
  142942. 2, 25,
  142943. _vq_lengthlist__16u0__p6_1,
  142944. 1, -533725184, 1611661312, 3, 0,
  142945. _vq_quantlist__16u0__p6_1,
  142946. NULL,
  142947. &_vq_auxt__16u0__p6_1,
  142948. NULL,
  142949. 0
  142950. };
  142951. static long _vq_quantlist__16u0__p7_0[] = {
  142952. 1,
  142953. 0,
  142954. 2,
  142955. };
  142956. static long _vq_lengthlist__16u0__p7_0[] = {
  142957. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142958. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142959. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142960. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142961. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142962. 7,
  142963. };
  142964. static float _vq_quantthresh__16u0__p7_0[] = {
  142965. -157.5, 157.5,
  142966. };
  142967. static long _vq_quantmap__16u0__p7_0[] = {
  142968. 1, 0, 2,
  142969. };
  142970. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  142971. _vq_quantthresh__16u0__p7_0,
  142972. _vq_quantmap__16u0__p7_0,
  142973. 3,
  142974. 3
  142975. };
  142976. static static_codebook _16u0__p7_0 = {
  142977. 4, 81,
  142978. _vq_lengthlist__16u0__p7_0,
  142979. 1, -518803456, 1628680192, 2, 0,
  142980. _vq_quantlist__16u0__p7_0,
  142981. NULL,
  142982. &_vq_auxt__16u0__p7_0,
  142983. NULL,
  142984. 0
  142985. };
  142986. static long _vq_quantlist__16u0__p7_1[] = {
  142987. 7,
  142988. 6,
  142989. 8,
  142990. 5,
  142991. 9,
  142992. 4,
  142993. 10,
  142994. 3,
  142995. 11,
  142996. 2,
  142997. 12,
  142998. 1,
  142999. 13,
  143000. 0,
  143001. 14,
  143002. };
  143003. static long _vq_lengthlist__16u0__p7_1[] = {
  143004. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  143005. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  143006. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143007. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143008. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143009. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143010. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143011. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143012. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143013. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143014. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143015. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143016. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143017. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143018. 10,
  143019. };
  143020. static float _vq_quantthresh__16u0__p7_1[] = {
  143021. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143022. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143023. };
  143024. static long _vq_quantmap__16u0__p7_1[] = {
  143025. 13, 11, 9, 7, 5, 3, 1, 0,
  143026. 2, 4, 6, 8, 10, 12, 14,
  143027. };
  143028. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143029. _vq_quantthresh__16u0__p7_1,
  143030. _vq_quantmap__16u0__p7_1,
  143031. 15,
  143032. 15
  143033. };
  143034. static static_codebook _16u0__p7_1 = {
  143035. 2, 225,
  143036. _vq_lengthlist__16u0__p7_1,
  143037. 1, -520986624, 1620377600, 4, 0,
  143038. _vq_quantlist__16u0__p7_1,
  143039. NULL,
  143040. &_vq_auxt__16u0__p7_1,
  143041. NULL,
  143042. 0
  143043. };
  143044. static long _vq_quantlist__16u0__p7_2[] = {
  143045. 10,
  143046. 9,
  143047. 11,
  143048. 8,
  143049. 12,
  143050. 7,
  143051. 13,
  143052. 6,
  143053. 14,
  143054. 5,
  143055. 15,
  143056. 4,
  143057. 16,
  143058. 3,
  143059. 17,
  143060. 2,
  143061. 18,
  143062. 1,
  143063. 19,
  143064. 0,
  143065. 20,
  143066. };
  143067. static long _vq_lengthlist__16u0__p7_2[] = {
  143068. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143069. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143070. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143071. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143072. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143073. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143074. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143075. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143076. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143077. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143078. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143079. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143080. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143081. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143082. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143083. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143084. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143085. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143086. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143087. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143088. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143089. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143090. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143091. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143092. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143093. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143094. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143095. 10,10,12,11,10,11,11,11,10,
  143096. };
  143097. static float _vq_quantthresh__16u0__p7_2[] = {
  143098. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143099. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143100. 6.5, 7.5, 8.5, 9.5,
  143101. };
  143102. static long _vq_quantmap__16u0__p7_2[] = {
  143103. 19, 17, 15, 13, 11, 9, 7, 5,
  143104. 3, 1, 0, 2, 4, 6, 8, 10,
  143105. 12, 14, 16, 18, 20,
  143106. };
  143107. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143108. _vq_quantthresh__16u0__p7_2,
  143109. _vq_quantmap__16u0__p7_2,
  143110. 21,
  143111. 21
  143112. };
  143113. static static_codebook _16u0__p7_2 = {
  143114. 2, 441,
  143115. _vq_lengthlist__16u0__p7_2,
  143116. 1, -529268736, 1611661312, 5, 0,
  143117. _vq_quantlist__16u0__p7_2,
  143118. NULL,
  143119. &_vq_auxt__16u0__p7_2,
  143120. NULL,
  143121. 0
  143122. };
  143123. static long _huff_lengthlist__16u0__single[] = {
  143124. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143125. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143126. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143127. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143128. };
  143129. static static_codebook _huff_book__16u0__single = {
  143130. 2, 64,
  143131. _huff_lengthlist__16u0__single,
  143132. 0, 0, 0, 0, 0,
  143133. NULL,
  143134. NULL,
  143135. NULL,
  143136. NULL,
  143137. 0
  143138. };
  143139. static long _huff_lengthlist__16u1__long[] = {
  143140. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143141. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143142. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143143. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143144. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143145. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143146. 16,13,16,18,
  143147. };
  143148. static static_codebook _huff_book__16u1__long = {
  143149. 2, 100,
  143150. _huff_lengthlist__16u1__long,
  143151. 0, 0, 0, 0, 0,
  143152. NULL,
  143153. NULL,
  143154. NULL,
  143155. NULL,
  143156. 0
  143157. };
  143158. static long _vq_quantlist__16u1__p1_0[] = {
  143159. 1,
  143160. 0,
  143161. 2,
  143162. };
  143163. static long _vq_lengthlist__16u1__p1_0[] = {
  143164. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143165. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143166. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143167. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143168. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143169. 11,
  143170. };
  143171. static float _vq_quantthresh__16u1__p1_0[] = {
  143172. -0.5, 0.5,
  143173. };
  143174. static long _vq_quantmap__16u1__p1_0[] = {
  143175. 1, 0, 2,
  143176. };
  143177. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143178. _vq_quantthresh__16u1__p1_0,
  143179. _vq_quantmap__16u1__p1_0,
  143180. 3,
  143181. 3
  143182. };
  143183. static static_codebook _16u1__p1_0 = {
  143184. 4, 81,
  143185. _vq_lengthlist__16u1__p1_0,
  143186. 1, -535822336, 1611661312, 2, 0,
  143187. _vq_quantlist__16u1__p1_0,
  143188. NULL,
  143189. &_vq_auxt__16u1__p1_0,
  143190. NULL,
  143191. 0
  143192. };
  143193. static long _vq_quantlist__16u1__p2_0[] = {
  143194. 1,
  143195. 0,
  143196. 2,
  143197. };
  143198. static long _vq_lengthlist__16u1__p2_0[] = {
  143199. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143200. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143201. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143202. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143203. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143204. 8,
  143205. };
  143206. static float _vq_quantthresh__16u1__p2_0[] = {
  143207. -0.5, 0.5,
  143208. };
  143209. static long _vq_quantmap__16u1__p2_0[] = {
  143210. 1, 0, 2,
  143211. };
  143212. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143213. _vq_quantthresh__16u1__p2_0,
  143214. _vq_quantmap__16u1__p2_0,
  143215. 3,
  143216. 3
  143217. };
  143218. static static_codebook _16u1__p2_0 = {
  143219. 4, 81,
  143220. _vq_lengthlist__16u1__p2_0,
  143221. 1, -535822336, 1611661312, 2, 0,
  143222. _vq_quantlist__16u1__p2_0,
  143223. NULL,
  143224. &_vq_auxt__16u1__p2_0,
  143225. NULL,
  143226. 0
  143227. };
  143228. static long _vq_quantlist__16u1__p3_0[] = {
  143229. 2,
  143230. 1,
  143231. 3,
  143232. 0,
  143233. 4,
  143234. };
  143235. static long _vq_lengthlist__16u1__p3_0[] = {
  143236. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143237. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143238. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143239. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143240. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143241. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143242. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143243. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143244. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143245. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143246. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143247. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143248. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143249. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143250. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143251. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143252. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143253. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143254. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143255. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143256. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143257. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143258. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143259. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143260. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143261. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143262. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143263. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143264. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143265. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143266. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143267. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143268. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143269. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143270. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143271. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143272. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143273. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143274. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143275. 16,
  143276. };
  143277. static float _vq_quantthresh__16u1__p3_0[] = {
  143278. -1.5, -0.5, 0.5, 1.5,
  143279. };
  143280. static long _vq_quantmap__16u1__p3_0[] = {
  143281. 3, 1, 0, 2, 4,
  143282. };
  143283. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143284. _vq_quantthresh__16u1__p3_0,
  143285. _vq_quantmap__16u1__p3_0,
  143286. 5,
  143287. 5
  143288. };
  143289. static static_codebook _16u1__p3_0 = {
  143290. 4, 625,
  143291. _vq_lengthlist__16u1__p3_0,
  143292. 1, -533725184, 1611661312, 3, 0,
  143293. _vq_quantlist__16u1__p3_0,
  143294. NULL,
  143295. &_vq_auxt__16u1__p3_0,
  143296. NULL,
  143297. 0
  143298. };
  143299. static long _vq_quantlist__16u1__p4_0[] = {
  143300. 2,
  143301. 1,
  143302. 3,
  143303. 0,
  143304. 4,
  143305. };
  143306. static long _vq_lengthlist__16u1__p4_0[] = {
  143307. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143308. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143309. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143310. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143311. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143312. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143313. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143314. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143315. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143316. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143317. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143318. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143319. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143320. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143321. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143322. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143323. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143324. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143325. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143326. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143327. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143328. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143329. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143330. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143331. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143332. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143333. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143334. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143335. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143336. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143337. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143338. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143339. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143340. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143341. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143342. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143343. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143344. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143345. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143346. 11,
  143347. };
  143348. static float _vq_quantthresh__16u1__p4_0[] = {
  143349. -1.5, -0.5, 0.5, 1.5,
  143350. };
  143351. static long _vq_quantmap__16u1__p4_0[] = {
  143352. 3, 1, 0, 2, 4,
  143353. };
  143354. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143355. _vq_quantthresh__16u1__p4_0,
  143356. _vq_quantmap__16u1__p4_0,
  143357. 5,
  143358. 5
  143359. };
  143360. static static_codebook _16u1__p4_0 = {
  143361. 4, 625,
  143362. _vq_lengthlist__16u1__p4_0,
  143363. 1, -533725184, 1611661312, 3, 0,
  143364. _vq_quantlist__16u1__p4_0,
  143365. NULL,
  143366. &_vq_auxt__16u1__p4_0,
  143367. NULL,
  143368. 0
  143369. };
  143370. static long _vq_quantlist__16u1__p5_0[] = {
  143371. 4,
  143372. 3,
  143373. 5,
  143374. 2,
  143375. 6,
  143376. 1,
  143377. 7,
  143378. 0,
  143379. 8,
  143380. };
  143381. static long _vq_lengthlist__16u1__p5_0[] = {
  143382. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143383. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143384. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143385. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143386. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143387. 13,
  143388. };
  143389. static float _vq_quantthresh__16u1__p5_0[] = {
  143390. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143391. };
  143392. static long _vq_quantmap__16u1__p5_0[] = {
  143393. 7, 5, 3, 1, 0, 2, 4, 6,
  143394. 8,
  143395. };
  143396. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143397. _vq_quantthresh__16u1__p5_0,
  143398. _vq_quantmap__16u1__p5_0,
  143399. 9,
  143400. 9
  143401. };
  143402. static static_codebook _16u1__p5_0 = {
  143403. 2, 81,
  143404. _vq_lengthlist__16u1__p5_0,
  143405. 1, -531628032, 1611661312, 4, 0,
  143406. _vq_quantlist__16u1__p5_0,
  143407. NULL,
  143408. &_vq_auxt__16u1__p5_0,
  143409. NULL,
  143410. 0
  143411. };
  143412. static long _vq_quantlist__16u1__p6_0[] = {
  143413. 4,
  143414. 3,
  143415. 5,
  143416. 2,
  143417. 6,
  143418. 1,
  143419. 7,
  143420. 0,
  143421. 8,
  143422. };
  143423. static long _vq_lengthlist__16u1__p6_0[] = {
  143424. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143425. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143426. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143427. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143428. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143429. 11,
  143430. };
  143431. static float _vq_quantthresh__16u1__p6_0[] = {
  143432. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143433. };
  143434. static long _vq_quantmap__16u1__p6_0[] = {
  143435. 7, 5, 3, 1, 0, 2, 4, 6,
  143436. 8,
  143437. };
  143438. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143439. _vq_quantthresh__16u1__p6_0,
  143440. _vq_quantmap__16u1__p6_0,
  143441. 9,
  143442. 9
  143443. };
  143444. static static_codebook _16u1__p6_0 = {
  143445. 2, 81,
  143446. _vq_lengthlist__16u1__p6_0,
  143447. 1, -531628032, 1611661312, 4, 0,
  143448. _vq_quantlist__16u1__p6_0,
  143449. NULL,
  143450. &_vq_auxt__16u1__p6_0,
  143451. NULL,
  143452. 0
  143453. };
  143454. static long _vq_quantlist__16u1__p7_0[] = {
  143455. 1,
  143456. 0,
  143457. 2,
  143458. };
  143459. static long _vq_lengthlist__16u1__p7_0[] = {
  143460. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143461. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143462. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143463. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143464. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143465. 13,
  143466. };
  143467. static float _vq_quantthresh__16u1__p7_0[] = {
  143468. -5.5, 5.5,
  143469. };
  143470. static long _vq_quantmap__16u1__p7_0[] = {
  143471. 1, 0, 2,
  143472. };
  143473. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143474. _vq_quantthresh__16u1__p7_0,
  143475. _vq_quantmap__16u1__p7_0,
  143476. 3,
  143477. 3
  143478. };
  143479. static static_codebook _16u1__p7_0 = {
  143480. 4, 81,
  143481. _vq_lengthlist__16u1__p7_0,
  143482. 1, -529137664, 1618345984, 2, 0,
  143483. _vq_quantlist__16u1__p7_0,
  143484. NULL,
  143485. &_vq_auxt__16u1__p7_0,
  143486. NULL,
  143487. 0
  143488. };
  143489. static long _vq_quantlist__16u1__p7_1[] = {
  143490. 5,
  143491. 4,
  143492. 6,
  143493. 3,
  143494. 7,
  143495. 2,
  143496. 8,
  143497. 1,
  143498. 9,
  143499. 0,
  143500. 10,
  143501. };
  143502. static long _vq_lengthlist__16u1__p7_1[] = {
  143503. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  143504. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  143505. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143506. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  143507. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  143508. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  143509. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  143510. 8, 9, 9,10,10,10,10,10,10,
  143511. };
  143512. static float _vq_quantthresh__16u1__p7_1[] = {
  143513. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143514. 3.5, 4.5,
  143515. };
  143516. static long _vq_quantmap__16u1__p7_1[] = {
  143517. 9, 7, 5, 3, 1, 0, 2, 4,
  143518. 6, 8, 10,
  143519. };
  143520. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  143521. _vq_quantthresh__16u1__p7_1,
  143522. _vq_quantmap__16u1__p7_1,
  143523. 11,
  143524. 11
  143525. };
  143526. static static_codebook _16u1__p7_1 = {
  143527. 2, 121,
  143528. _vq_lengthlist__16u1__p7_1,
  143529. 1, -531365888, 1611661312, 4, 0,
  143530. _vq_quantlist__16u1__p7_1,
  143531. NULL,
  143532. &_vq_auxt__16u1__p7_1,
  143533. NULL,
  143534. 0
  143535. };
  143536. static long _vq_quantlist__16u1__p8_0[] = {
  143537. 5,
  143538. 4,
  143539. 6,
  143540. 3,
  143541. 7,
  143542. 2,
  143543. 8,
  143544. 1,
  143545. 9,
  143546. 0,
  143547. 10,
  143548. };
  143549. static long _vq_lengthlist__16u1__p8_0[] = {
  143550. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  143551. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  143552. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  143553. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  143554. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  143555. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  143556. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  143557. 13,14,14,15,15,16,16,15,16,
  143558. };
  143559. static float _vq_quantthresh__16u1__p8_0[] = {
  143560. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143561. 38.5, 49.5,
  143562. };
  143563. static long _vq_quantmap__16u1__p8_0[] = {
  143564. 9, 7, 5, 3, 1, 0, 2, 4,
  143565. 6, 8, 10,
  143566. };
  143567. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  143568. _vq_quantthresh__16u1__p8_0,
  143569. _vq_quantmap__16u1__p8_0,
  143570. 11,
  143571. 11
  143572. };
  143573. static static_codebook _16u1__p8_0 = {
  143574. 2, 121,
  143575. _vq_lengthlist__16u1__p8_0,
  143576. 1, -524582912, 1618345984, 4, 0,
  143577. _vq_quantlist__16u1__p8_0,
  143578. NULL,
  143579. &_vq_auxt__16u1__p8_0,
  143580. NULL,
  143581. 0
  143582. };
  143583. static long _vq_quantlist__16u1__p8_1[] = {
  143584. 5,
  143585. 4,
  143586. 6,
  143587. 3,
  143588. 7,
  143589. 2,
  143590. 8,
  143591. 1,
  143592. 9,
  143593. 0,
  143594. 10,
  143595. };
  143596. static long _vq_lengthlist__16u1__p8_1[] = {
  143597. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  143598. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  143599. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  143600. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143601. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143602. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143603. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143604. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143605. };
  143606. static float _vq_quantthresh__16u1__p8_1[] = {
  143607. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143608. 3.5, 4.5,
  143609. };
  143610. static long _vq_quantmap__16u1__p8_1[] = {
  143611. 9, 7, 5, 3, 1, 0, 2, 4,
  143612. 6, 8, 10,
  143613. };
  143614. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  143615. _vq_quantthresh__16u1__p8_1,
  143616. _vq_quantmap__16u1__p8_1,
  143617. 11,
  143618. 11
  143619. };
  143620. static static_codebook _16u1__p8_1 = {
  143621. 2, 121,
  143622. _vq_lengthlist__16u1__p8_1,
  143623. 1, -531365888, 1611661312, 4, 0,
  143624. _vq_quantlist__16u1__p8_1,
  143625. NULL,
  143626. &_vq_auxt__16u1__p8_1,
  143627. NULL,
  143628. 0
  143629. };
  143630. static long _vq_quantlist__16u1__p9_0[] = {
  143631. 7,
  143632. 6,
  143633. 8,
  143634. 5,
  143635. 9,
  143636. 4,
  143637. 10,
  143638. 3,
  143639. 11,
  143640. 2,
  143641. 12,
  143642. 1,
  143643. 13,
  143644. 0,
  143645. 14,
  143646. };
  143647. static long _vq_lengthlist__16u1__p9_0[] = {
  143648. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143649. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143650. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143651. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143652. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143653. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143654. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143655. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143656. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143657. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143658. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143659. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143660. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143661. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143662. 8,
  143663. };
  143664. static float _vq_quantthresh__16u1__p9_0[] = {
  143665. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143666. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143667. };
  143668. static long _vq_quantmap__16u1__p9_0[] = {
  143669. 13, 11, 9, 7, 5, 3, 1, 0,
  143670. 2, 4, 6, 8, 10, 12, 14,
  143671. };
  143672. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  143673. _vq_quantthresh__16u1__p9_0,
  143674. _vq_quantmap__16u1__p9_0,
  143675. 15,
  143676. 15
  143677. };
  143678. static static_codebook _16u1__p9_0 = {
  143679. 2, 225,
  143680. _vq_lengthlist__16u1__p9_0,
  143681. 1, -514071552, 1627381760, 4, 0,
  143682. _vq_quantlist__16u1__p9_0,
  143683. NULL,
  143684. &_vq_auxt__16u1__p9_0,
  143685. NULL,
  143686. 0
  143687. };
  143688. static long _vq_quantlist__16u1__p9_1[] = {
  143689. 7,
  143690. 6,
  143691. 8,
  143692. 5,
  143693. 9,
  143694. 4,
  143695. 10,
  143696. 3,
  143697. 11,
  143698. 2,
  143699. 12,
  143700. 1,
  143701. 13,
  143702. 0,
  143703. 14,
  143704. };
  143705. static long _vq_lengthlist__16u1__p9_1[] = {
  143706. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  143707. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  143708. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  143709. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  143710. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  143711. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  143712. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  143713. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  143714. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  143715. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143716. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  143717. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143718. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143719. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143720. 9,
  143721. };
  143722. static float _vq_quantthresh__16u1__p9_1[] = {
  143723. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143724. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143725. };
  143726. static long _vq_quantmap__16u1__p9_1[] = {
  143727. 13, 11, 9, 7, 5, 3, 1, 0,
  143728. 2, 4, 6, 8, 10, 12, 14,
  143729. };
  143730. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  143731. _vq_quantthresh__16u1__p9_1,
  143732. _vq_quantmap__16u1__p9_1,
  143733. 15,
  143734. 15
  143735. };
  143736. static static_codebook _16u1__p9_1 = {
  143737. 2, 225,
  143738. _vq_lengthlist__16u1__p9_1,
  143739. 1, -522338304, 1620115456, 4, 0,
  143740. _vq_quantlist__16u1__p9_1,
  143741. NULL,
  143742. &_vq_auxt__16u1__p9_1,
  143743. NULL,
  143744. 0
  143745. };
  143746. static long _vq_quantlist__16u1__p9_2[] = {
  143747. 8,
  143748. 7,
  143749. 9,
  143750. 6,
  143751. 10,
  143752. 5,
  143753. 11,
  143754. 4,
  143755. 12,
  143756. 3,
  143757. 13,
  143758. 2,
  143759. 14,
  143760. 1,
  143761. 15,
  143762. 0,
  143763. 16,
  143764. };
  143765. static long _vq_lengthlist__16u1__p9_2[] = {
  143766. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  143767. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  143768. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  143769. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  143770. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  143771. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  143772. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  143773. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  143774. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  143775. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  143776. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  143777. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  143778. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  143779. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  143780. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  143781. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  143782. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  143783. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  143784. 10,
  143785. };
  143786. static float _vq_quantthresh__16u1__p9_2[] = {
  143787. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143788. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143789. };
  143790. static long _vq_quantmap__16u1__p9_2[] = {
  143791. 15, 13, 11, 9, 7, 5, 3, 1,
  143792. 0, 2, 4, 6, 8, 10, 12, 14,
  143793. 16,
  143794. };
  143795. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  143796. _vq_quantthresh__16u1__p9_2,
  143797. _vq_quantmap__16u1__p9_2,
  143798. 17,
  143799. 17
  143800. };
  143801. static static_codebook _16u1__p9_2 = {
  143802. 2, 289,
  143803. _vq_lengthlist__16u1__p9_2,
  143804. 1, -529530880, 1611661312, 5, 0,
  143805. _vq_quantlist__16u1__p9_2,
  143806. NULL,
  143807. &_vq_auxt__16u1__p9_2,
  143808. NULL,
  143809. 0
  143810. };
  143811. static long _huff_lengthlist__16u1__short[] = {
  143812. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  143813. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  143814. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  143815. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  143816. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  143817. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  143818. 16,16,16,16,
  143819. };
  143820. static static_codebook _huff_book__16u1__short = {
  143821. 2, 100,
  143822. _huff_lengthlist__16u1__short,
  143823. 0, 0, 0, 0, 0,
  143824. NULL,
  143825. NULL,
  143826. NULL,
  143827. NULL,
  143828. 0
  143829. };
  143830. static long _huff_lengthlist__16u2__long[] = {
  143831. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  143832. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  143833. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  143834. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  143835. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  143836. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  143837. 13,14,18,18,
  143838. };
  143839. static static_codebook _huff_book__16u2__long = {
  143840. 2, 100,
  143841. _huff_lengthlist__16u2__long,
  143842. 0, 0, 0, 0, 0,
  143843. NULL,
  143844. NULL,
  143845. NULL,
  143846. NULL,
  143847. 0
  143848. };
  143849. static long _huff_lengthlist__16u2__short[] = {
  143850. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  143851. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  143852. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  143853. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  143854. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  143855. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  143856. 16,16,16,16,
  143857. };
  143858. static static_codebook _huff_book__16u2__short = {
  143859. 2, 100,
  143860. _huff_lengthlist__16u2__short,
  143861. 0, 0, 0, 0, 0,
  143862. NULL,
  143863. NULL,
  143864. NULL,
  143865. NULL,
  143866. 0
  143867. };
  143868. static long _vq_quantlist__16u2_p1_0[] = {
  143869. 1,
  143870. 0,
  143871. 2,
  143872. };
  143873. static long _vq_lengthlist__16u2_p1_0[] = {
  143874. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  143875. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  143876. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  143877. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  143878. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  143879. 10,
  143880. };
  143881. static float _vq_quantthresh__16u2_p1_0[] = {
  143882. -0.5, 0.5,
  143883. };
  143884. static long _vq_quantmap__16u2_p1_0[] = {
  143885. 1, 0, 2,
  143886. };
  143887. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  143888. _vq_quantthresh__16u2_p1_0,
  143889. _vq_quantmap__16u2_p1_0,
  143890. 3,
  143891. 3
  143892. };
  143893. static static_codebook _16u2_p1_0 = {
  143894. 4, 81,
  143895. _vq_lengthlist__16u2_p1_0,
  143896. 1, -535822336, 1611661312, 2, 0,
  143897. _vq_quantlist__16u2_p1_0,
  143898. NULL,
  143899. &_vq_auxt__16u2_p1_0,
  143900. NULL,
  143901. 0
  143902. };
  143903. static long _vq_quantlist__16u2_p2_0[] = {
  143904. 2,
  143905. 1,
  143906. 3,
  143907. 0,
  143908. 4,
  143909. };
  143910. static long _vq_lengthlist__16u2_p2_0[] = {
  143911. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143912. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143913. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  143914. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  143915. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  143916. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  143917. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  143918. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  143919. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143920. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  143921. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  143922. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143923. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  143924. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  143925. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  143926. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  143927. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  143928. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  143929. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  143930. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  143931. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  143932. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  143933. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  143934. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  143935. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  143936. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  143937. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  143938. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  143939. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  143940. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  143941. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  143942. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  143943. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  143944. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  143945. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  143946. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  143947. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  143948. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  143949. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  143950. 13,
  143951. };
  143952. static float _vq_quantthresh__16u2_p2_0[] = {
  143953. -1.5, -0.5, 0.5, 1.5,
  143954. };
  143955. static long _vq_quantmap__16u2_p2_0[] = {
  143956. 3, 1, 0, 2, 4,
  143957. };
  143958. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  143959. _vq_quantthresh__16u2_p2_0,
  143960. _vq_quantmap__16u2_p2_0,
  143961. 5,
  143962. 5
  143963. };
  143964. static static_codebook _16u2_p2_0 = {
  143965. 4, 625,
  143966. _vq_lengthlist__16u2_p2_0,
  143967. 1, -533725184, 1611661312, 3, 0,
  143968. _vq_quantlist__16u2_p2_0,
  143969. NULL,
  143970. &_vq_auxt__16u2_p2_0,
  143971. NULL,
  143972. 0
  143973. };
  143974. static long _vq_quantlist__16u2_p3_0[] = {
  143975. 4,
  143976. 3,
  143977. 5,
  143978. 2,
  143979. 6,
  143980. 1,
  143981. 7,
  143982. 0,
  143983. 8,
  143984. };
  143985. static long _vq_lengthlist__16u2_p3_0[] = {
  143986. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  143987. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  143988. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143989. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143990. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143991. 11,
  143992. };
  143993. static float _vq_quantthresh__16u2_p3_0[] = {
  143994. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143995. };
  143996. static long _vq_quantmap__16u2_p3_0[] = {
  143997. 7, 5, 3, 1, 0, 2, 4, 6,
  143998. 8,
  143999. };
  144000. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  144001. _vq_quantthresh__16u2_p3_0,
  144002. _vq_quantmap__16u2_p3_0,
  144003. 9,
  144004. 9
  144005. };
  144006. static static_codebook _16u2_p3_0 = {
  144007. 2, 81,
  144008. _vq_lengthlist__16u2_p3_0,
  144009. 1, -531628032, 1611661312, 4, 0,
  144010. _vq_quantlist__16u2_p3_0,
  144011. NULL,
  144012. &_vq_auxt__16u2_p3_0,
  144013. NULL,
  144014. 0
  144015. };
  144016. static long _vq_quantlist__16u2_p4_0[] = {
  144017. 8,
  144018. 7,
  144019. 9,
  144020. 6,
  144021. 10,
  144022. 5,
  144023. 11,
  144024. 4,
  144025. 12,
  144026. 3,
  144027. 13,
  144028. 2,
  144029. 14,
  144030. 1,
  144031. 15,
  144032. 0,
  144033. 16,
  144034. };
  144035. static long _vq_lengthlist__16u2_p4_0[] = {
  144036. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144037. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144038. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144039. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144040. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144041. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144042. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144043. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144044. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144045. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144046. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144047. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144048. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144049. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144050. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144051. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144052. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144053. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144054. 14,
  144055. };
  144056. static float _vq_quantthresh__16u2_p4_0[] = {
  144057. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144058. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144059. };
  144060. static long _vq_quantmap__16u2_p4_0[] = {
  144061. 15, 13, 11, 9, 7, 5, 3, 1,
  144062. 0, 2, 4, 6, 8, 10, 12, 14,
  144063. 16,
  144064. };
  144065. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144066. _vq_quantthresh__16u2_p4_0,
  144067. _vq_quantmap__16u2_p4_0,
  144068. 17,
  144069. 17
  144070. };
  144071. static static_codebook _16u2_p4_0 = {
  144072. 2, 289,
  144073. _vq_lengthlist__16u2_p4_0,
  144074. 1, -529530880, 1611661312, 5, 0,
  144075. _vq_quantlist__16u2_p4_0,
  144076. NULL,
  144077. &_vq_auxt__16u2_p4_0,
  144078. NULL,
  144079. 0
  144080. };
  144081. static long _vq_quantlist__16u2_p5_0[] = {
  144082. 1,
  144083. 0,
  144084. 2,
  144085. };
  144086. static long _vq_lengthlist__16u2_p5_0[] = {
  144087. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144088. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144089. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144090. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144091. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144092. 10,
  144093. };
  144094. static float _vq_quantthresh__16u2_p5_0[] = {
  144095. -5.5, 5.5,
  144096. };
  144097. static long _vq_quantmap__16u2_p5_0[] = {
  144098. 1, 0, 2,
  144099. };
  144100. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144101. _vq_quantthresh__16u2_p5_0,
  144102. _vq_quantmap__16u2_p5_0,
  144103. 3,
  144104. 3
  144105. };
  144106. static static_codebook _16u2_p5_0 = {
  144107. 4, 81,
  144108. _vq_lengthlist__16u2_p5_0,
  144109. 1, -529137664, 1618345984, 2, 0,
  144110. _vq_quantlist__16u2_p5_0,
  144111. NULL,
  144112. &_vq_auxt__16u2_p5_0,
  144113. NULL,
  144114. 0
  144115. };
  144116. static long _vq_quantlist__16u2_p5_1[] = {
  144117. 5,
  144118. 4,
  144119. 6,
  144120. 3,
  144121. 7,
  144122. 2,
  144123. 8,
  144124. 1,
  144125. 9,
  144126. 0,
  144127. 10,
  144128. };
  144129. static long _vq_lengthlist__16u2_p5_1[] = {
  144130. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144131. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144132. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144133. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144134. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144135. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144136. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144137. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144138. };
  144139. static float _vq_quantthresh__16u2_p5_1[] = {
  144140. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144141. 3.5, 4.5,
  144142. };
  144143. static long _vq_quantmap__16u2_p5_1[] = {
  144144. 9, 7, 5, 3, 1, 0, 2, 4,
  144145. 6, 8, 10,
  144146. };
  144147. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144148. _vq_quantthresh__16u2_p5_1,
  144149. _vq_quantmap__16u2_p5_1,
  144150. 11,
  144151. 11
  144152. };
  144153. static static_codebook _16u2_p5_1 = {
  144154. 2, 121,
  144155. _vq_lengthlist__16u2_p5_1,
  144156. 1, -531365888, 1611661312, 4, 0,
  144157. _vq_quantlist__16u2_p5_1,
  144158. NULL,
  144159. &_vq_auxt__16u2_p5_1,
  144160. NULL,
  144161. 0
  144162. };
  144163. static long _vq_quantlist__16u2_p6_0[] = {
  144164. 6,
  144165. 5,
  144166. 7,
  144167. 4,
  144168. 8,
  144169. 3,
  144170. 9,
  144171. 2,
  144172. 10,
  144173. 1,
  144174. 11,
  144175. 0,
  144176. 12,
  144177. };
  144178. static long _vq_lengthlist__16u2_p6_0[] = {
  144179. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144180. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144181. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144182. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144183. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144184. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144185. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144186. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144187. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144188. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144189. 12,13,13,14,14,14,14,15,15,
  144190. };
  144191. static float _vq_quantthresh__16u2_p6_0[] = {
  144192. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144193. 12.5, 17.5, 22.5, 27.5,
  144194. };
  144195. static long _vq_quantmap__16u2_p6_0[] = {
  144196. 11, 9, 7, 5, 3, 1, 0, 2,
  144197. 4, 6, 8, 10, 12,
  144198. };
  144199. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144200. _vq_quantthresh__16u2_p6_0,
  144201. _vq_quantmap__16u2_p6_0,
  144202. 13,
  144203. 13
  144204. };
  144205. static static_codebook _16u2_p6_0 = {
  144206. 2, 169,
  144207. _vq_lengthlist__16u2_p6_0,
  144208. 1, -526516224, 1616117760, 4, 0,
  144209. _vq_quantlist__16u2_p6_0,
  144210. NULL,
  144211. &_vq_auxt__16u2_p6_0,
  144212. NULL,
  144213. 0
  144214. };
  144215. static long _vq_quantlist__16u2_p6_1[] = {
  144216. 2,
  144217. 1,
  144218. 3,
  144219. 0,
  144220. 4,
  144221. };
  144222. static long _vq_lengthlist__16u2_p6_1[] = {
  144223. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144224. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144225. };
  144226. static float _vq_quantthresh__16u2_p6_1[] = {
  144227. -1.5, -0.5, 0.5, 1.5,
  144228. };
  144229. static long _vq_quantmap__16u2_p6_1[] = {
  144230. 3, 1, 0, 2, 4,
  144231. };
  144232. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144233. _vq_quantthresh__16u2_p6_1,
  144234. _vq_quantmap__16u2_p6_1,
  144235. 5,
  144236. 5
  144237. };
  144238. static static_codebook _16u2_p6_1 = {
  144239. 2, 25,
  144240. _vq_lengthlist__16u2_p6_1,
  144241. 1, -533725184, 1611661312, 3, 0,
  144242. _vq_quantlist__16u2_p6_1,
  144243. NULL,
  144244. &_vq_auxt__16u2_p6_1,
  144245. NULL,
  144246. 0
  144247. };
  144248. static long _vq_quantlist__16u2_p7_0[] = {
  144249. 6,
  144250. 5,
  144251. 7,
  144252. 4,
  144253. 8,
  144254. 3,
  144255. 9,
  144256. 2,
  144257. 10,
  144258. 1,
  144259. 11,
  144260. 0,
  144261. 12,
  144262. };
  144263. static long _vq_lengthlist__16u2_p7_0[] = {
  144264. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144265. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144266. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144267. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144268. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144269. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144270. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144271. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144272. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144273. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144274. 12,13,13,13,14,14,14,15,14,
  144275. };
  144276. static float _vq_quantthresh__16u2_p7_0[] = {
  144277. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144278. 27.5, 38.5, 49.5, 60.5,
  144279. };
  144280. static long _vq_quantmap__16u2_p7_0[] = {
  144281. 11, 9, 7, 5, 3, 1, 0, 2,
  144282. 4, 6, 8, 10, 12,
  144283. };
  144284. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144285. _vq_quantthresh__16u2_p7_0,
  144286. _vq_quantmap__16u2_p7_0,
  144287. 13,
  144288. 13
  144289. };
  144290. static static_codebook _16u2_p7_0 = {
  144291. 2, 169,
  144292. _vq_lengthlist__16u2_p7_0,
  144293. 1, -523206656, 1618345984, 4, 0,
  144294. _vq_quantlist__16u2_p7_0,
  144295. NULL,
  144296. &_vq_auxt__16u2_p7_0,
  144297. NULL,
  144298. 0
  144299. };
  144300. static long _vq_quantlist__16u2_p7_1[] = {
  144301. 5,
  144302. 4,
  144303. 6,
  144304. 3,
  144305. 7,
  144306. 2,
  144307. 8,
  144308. 1,
  144309. 9,
  144310. 0,
  144311. 10,
  144312. };
  144313. static long _vq_lengthlist__16u2_p7_1[] = {
  144314. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144315. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144316. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144317. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144318. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144319. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144320. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144321. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144322. };
  144323. static float _vq_quantthresh__16u2_p7_1[] = {
  144324. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144325. 3.5, 4.5,
  144326. };
  144327. static long _vq_quantmap__16u2_p7_1[] = {
  144328. 9, 7, 5, 3, 1, 0, 2, 4,
  144329. 6, 8, 10,
  144330. };
  144331. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144332. _vq_quantthresh__16u2_p7_1,
  144333. _vq_quantmap__16u2_p7_1,
  144334. 11,
  144335. 11
  144336. };
  144337. static static_codebook _16u2_p7_1 = {
  144338. 2, 121,
  144339. _vq_lengthlist__16u2_p7_1,
  144340. 1, -531365888, 1611661312, 4, 0,
  144341. _vq_quantlist__16u2_p7_1,
  144342. NULL,
  144343. &_vq_auxt__16u2_p7_1,
  144344. NULL,
  144345. 0
  144346. };
  144347. static long _vq_quantlist__16u2_p8_0[] = {
  144348. 7,
  144349. 6,
  144350. 8,
  144351. 5,
  144352. 9,
  144353. 4,
  144354. 10,
  144355. 3,
  144356. 11,
  144357. 2,
  144358. 12,
  144359. 1,
  144360. 13,
  144361. 0,
  144362. 14,
  144363. };
  144364. static long _vq_lengthlist__16u2_p8_0[] = {
  144365. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144366. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144367. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144368. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144369. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144370. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144371. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144372. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144373. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144374. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144375. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144376. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144377. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144378. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144379. 14,
  144380. };
  144381. static float _vq_quantthresh__16u2_p8_0[] = {
  144382. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144383. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144384. };
  144385. static long _vq_quantmap__16u2_p8_0[] = {
  144386. 13, 11, 9, 7, 5, 3, 1, 0,
  144387. 2, 4, 6, 8, 10, 12, 14,
  144388. };
  144389. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144390. _vq_quantthresh__16u2_p8_0,
  144391. _vq_quantmap__16u2_p8_0,
  144392. 15,
  144393. 15
  144394. };
  144395. static static_codebook _16u2_p8_0 = {
  144396. 2, 225,
  144397. _vq_lengthlist__16u2_p8_0,
  144398. 1, -520986624, 1620377600, 4, 0,
  144399. _vq_quantlist__16u2_p8_0,
  144400. NULL,
  144401. &_vq_auxt__16u2_p8_0,
  144402. NULL,
  144403. 0
  144404. };
  144405. static long _vq_quantlist__16u2_p8_1[] = {
  144406. 10,
  144407. 9,
  144408. 11,
  144409. 8,
  144410. 12,
  144411. 7,
  144412. 13,
  144413. 6,
  144414. 14,
  144415. 5,
  144416. 15,
  144417. 4,
  144418. 16,
  144419. 3,
  144420. 17,
  144421. 2,
  144422. 18,
  144423. 1,
  144424. 19,
  144425. 0,
  144426. 20,
  144427. };
  144428. static long _vq_lengthlist__16u2_p8_1[] = {
  144429. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144430. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144431. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144432. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144433. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144434. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144435. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144436. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144437. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144438. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144439. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144440. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144441. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144442. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144443. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144444. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144445. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144446. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144447. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144448. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144449. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144450. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144451. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144452. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144453. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144454. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144455. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144456. 11,11,10,11,11,11,10,11,11,
  144457. };
  144458. static float _vq_quantthresh__16u2_p8_1[] = {
  144459. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144460. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144461. 6.5, 7.5, 8.5, 9.5,
  144462. };
  144463. static long _vq_quantmap__16u2_p8_1[] = {
  144464. 19, 17, 15, 13, 11, 9, 7, 5,
  144465. 3, 1, 0, 2, 4, 6, 8, 10,
  144466. 12, 14, 16, 18, 20,
  144467. };
  144468. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144469. _vq_quantthresh__16u2_p8_1,
  144470. _vq_quantmap__16u2_p8_1,
  144471. 21,
  144472. 21
  144473. };
  144474. static static_codebook _16u2_p8_1 = {
  144475. 2, 441,
  144476. _vq_lengthlist__16u2_p8_1,
  144477. 1, -529268736, 1611661312, 5, 0,
  144478. _vq_quantlist__16u2_p8_1,
  144479. NULL,
  144480. &_vq_auxt__16u2_p8_1,
  144481. NULL,
  144482. 0
  144483. };
  144484. static long _vq_quantlist__16u2_p9_0[] = {
  144485. 5586,
  144486. 4655,
  144487. 6517,
  144488. 3724,
  144489. 7448,
  144490. 2793,
  144491. 8379,
  144492. 1862,
  144493. 9310,
  144494. 931,
  144495. 10241,
  144496. 0,
  144497. 11172,
  144498. 5521,
  144499. 5651,
  144500. };
  144501. static long _vq_lengthlist__16u2_p9_0[] = {
  144502. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  144503. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144504. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144505. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144506. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144507. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144508. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144509. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144510. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144511. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144512. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144513. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144514. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  144515. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  144516. 5,
  144517. };
  144518. static float _vq_quantthresh__16u2_p9_0[] = {
  144519. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  144520. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  144521. };
  144522. static long _vq_quantmap__16u2_p9_0[] = {
  144523. 11, 9, 7, 5, 3, 1, 13, 0,
  144524. 14, 2, 4, 6, 8, 10, 12,
  144525. };
  144526. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  144527. _vq_quantthresh__16u2_p9_0,
  144528. _vq_quantmap__16u2_p9_0,
  144529. 15,
  144530. 15
  144531. };
  144532. static static_codebook _16u2_p9_0 = {
  144533. 2, 225,
  144534. _vq_lengthlist__16u2_p9_0,
  144535. 1, -510275072, 1611661312, 14, 0,
  144536. _vq_quantlist__16u2_p9_0,
  144537. NULL,
  144538. &_vq_auxt__16u2_p9_0,
  144539. NULL,
  144540. 0
  144541. };
  144542. static long _vq_quantlist__16u2_p9_1[] = {
  144543. 392,
  144544. 343,
  144545. 441,
  144546. 294,
  144547. 490,
  144548. 245,
  144549. 539,
  144550. 196,
  144551. 588,
  144552. 147,
  144553. 637,
  144554. 98,
  144555. 686,
  144556. 49,
  144557. 735,
  144558. 0,
  144559. 784,
  144560. 388,
  144561. 396,
  144562. };
  144563. static long _vq_lengthlist__16u2_p9_1[] = {
  144564. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  144565. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  144566. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  144567. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  144568. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  144569. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  144570. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144571. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  144572. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  144573. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144574. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144575. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144576. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144577. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144578. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  144579. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144580. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144581. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144582. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144583. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144584. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  144585. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  144586. 11,11,11,11,11,11,11, 5, 4,
  144587. };
  144588. static float _vq_quantthresh__16u2_p9_1[] = {
  144589. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  144590. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  144591. 318.5, 367.5,
  144592. };
  144593. static long _vq_quantmap__16u2_p9_1[] = {
  144594. 15, 13, 11, 9, 7, 5, 3, 1,
  144595. 17, 0, 18, 2, 4, 6, 8, 10,
  144596. 12, 14, 16,
  144597. };
  144598. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  144599. _vq_quantthresh__16u2_p9_1,
  144600. _vq_quantmap__16u2_p9_1,
  144601. 19,
  144602. 19
  144603. };
  144604. static static_codebook _16u2_p9_1 = {
  144605. 2, 361,
  144606. _vq_lengthlist__16u2_p9_1,
  144607. 1, -518488064, 1611661312, 10, 0,
  144608. _vq_quantlist__16u2_p9_1,
  144609. NULL,
  144610. &_vq_auxt__16u2_p9_1,
  144611. NULL,
  144612. 0
  144613. };
  144614. static long _vq_quantlist__16u2_p9_2[] = {
  144615. 24,
  144616. 23,
  144617. 25,
  144618. 22,
  144619. 26,
  144620. 21,
  144621. 27,
  144622. 20,
  144623. 28,
  144624. 19,
  144625. 29,
  144626. 18,
  144627. 30,
  144628. 17,
  144629. 31,
  144630. 16,
  144631. 32,
  144632. 15,
  144633. 33,
  144634. 14,
  144635. 34,
  144636. 13,
  144637. 35,
  144638. 12,
  144639. 36,
  144640. 11,
  144641. 37,
  144642. 10,
  144643. 38,
  144644. 9,
  144645. 39,
  144646. 8,
  144647. 40,
  144648. 7,
  144649. 41,
  144650. 6,
  144651. 42,
  144652. 5,
  144653. 43,
  144654. 4,
  144655. 44,
  144656. 3,
  144657. 45,
  144658. 2,
  144659. 46,
  144660. 1,
  144661. 47,
  144662. 0,
  144663. 48,
  144664. };
  144665. static long _vq_lengthlist__16u2_p9_2[] = {
  144666. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  144667. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  144668. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  144669. 11,
  144670. };
  144671. static float _vq_quantthresh__16u2_p9_2[] = {
  144672. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144673. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144674. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144675. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144676. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144677. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144678. };
  144679. static long _vq_quantmap__16u2_p9_2[] = {
  144680. 47, 45, 43, 41, 39, 37, 35, 33,
  144681. 31, 29, 27, 25, 23, 21, 19, 17,
  144682. 15, 13, 11, 9, 7, 5, 3, 1,
  144683. 0, 2, 4, 6, 8, 10, 12, 14,
  144684. 16, 18, 20, 22, 24, 26, 28, 30,
  144685. 32, 34, 36, 38, 40, 42, 44, 46,
  144686. 48,
  144687. };
  144688. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  144689. _vq_quantthresh__16u2_p9_2,
  144690. _vq_quantmap__16u2_p9_2,
  144691. 49,
  144692. 49
  144693. };
  144694. static static_codebook _16u2_p9_2 = {
  144695. 1, 49,
  144696. _vq_lengthlist__16u2_p9_2,
  144697. 1, -526909440, 1611661312, 6, 0,
  144698. _vq_quantlist__16u2_p9_2,
  144699. NULL,
  144700. &_vq_auxt__16u2_p9_2,
  144701. NULL,
  144702. 0
  144703. };
  144704. static long _vq_quantlist__8u0__p1_0[] = {
  144705. 1,
  144706. 0,
  144707. 2,
  144708. };
  144709. static long _vq_lengthlist__8u0__p1_0[] = {
  144710. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144711. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  144712. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  144713. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  144714. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  144715. 11,
  144716. };
  144717. static float _vq_quantthresh__8u0__p1_0[] = {
  144718. -0.5, 0.5,
  144719. };
  144720. static long _vq_quantmap__8u0__p1_0[] = {
  144721. 1, 0, 2,
  144722. };
  144723. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  144724. _vq_quantthresh__8u0__p1_0,
  144725. _vq_quantmap__8u0__p1_0,
  144726. 3,
  144727. 3
  144728. };
  144729. static static_codebook _8u0__p1_0 = {
  144730. 4, 81,
  144731. _vq_lengthlist__8u0__p1_0,
  144732. 1, -535822336, 1611661312, 2, 0,
  144733. _vq_quantlist__8u0__p1_0,
  144734. NULL,
  144735. &_vq_auxt__8u0__p1_0,
  144736. NULL,
  144737. 0
  144738. };
  144739. static long _vq_quantlist__8u0__p2_0[] = {
  144740. 1,
  144741. 0,
  144742. 2,
  144743. };
  144744. static long _vq_lengthlist__8u0__p2_0[] = {
  144745. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  144746. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  144747. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  144748. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  144749. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  144750. 8,
  144751. };
  144752. static float _vq_quantthresh__8u0__p2_0[] = {
  144753. -0.5, 0.5,
  144754. };
  144755. static long _vq_quantmap__8u0__p2_0[] = {
  144756. 1, 0, 2,
  144757. };
  144758. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  144759. _vq_quantthresh__8u0__p2_0,
  144760. _vq_quantmap__8u0__p2_0,
  144761. 3,
  144762. 3
  144763. };
  144764. static static_codebook _8u0__p2_0 = {
  144765. 4, 81,
  144766. _vq_lengthlist__8u0__p2_0,
  144767. 1, -535822336, 1611661312, 2, 0,
  144768. _vq_quantlist__8u0__p2_0,
  144769. NULL,
  144770. &_vq_auxt__8u0__p2_0,
  144771. NULL,
  144772. 0
  144773. };
  144774. static long _vq_quantlist__8u0__p3_0[] = {
  144775. 2,
  144776. 1,
  144777. 3,
  144778. 0,
  144779. 4,
  144780. };
  144781. static long _vq_lengthlist__8u0__p3_0[] = {
  144782. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  144783. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  144784. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  144785. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  144786. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  144787. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  144788. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  144789. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  144790. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  144791. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  144792. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  144793. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  144794. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  144795. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  144796. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  144797. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  144798. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  144799. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  144800. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  144801. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  144802. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  144803. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  144804. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  144805. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  144806. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  144807. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  144808. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  144809. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  144810. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  144811. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  144812. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  144813. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  144814. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  144815. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  144816. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  144817. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  144818. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  144819. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  144820. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  144821. 16,
  144822. };
  144823. static float _vq_quantthresh__8u0__p3_0[] = {
  144824. -1.5, -0.5, 0.5, 1.5,
  144825. };
  144826. static long _vq_quantmap__8u0__p3_0[] = {
  144827. 3, 1, 0, 2, 4,
  144828. };
  144829. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  144830. _vq_quantthresh__8u0__p3_0,
  144831. _vq_quantmap__8u0__p3_0,
  144832. 5,
  144833. 5
  144834. };
  144835. static static_codebook _8u0__p3_0 = {
  144836. 4, 625,
  144837. _vq_lengthlist__8u0__p3_0,
  144838. 1, -533725184, 1611661312, 3, 0,
  144839. _vq_quantlist__8u0__p3_0,
  144840. NULL,
  144841. &_vq_auxt__8u0__p3_0,
  144842. NULL,
  144843. 0
  144844. };
  144845. static long _vq_quantlist__8u0__p4_0[] = {
  144846. 2,
  144847. 1,
  144848. 3,
  144849. 0,
  144850. 4,
  144851. };
  144852. static long _vq_lengthlist__8u0__p4_0[] = {
  144853. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  144854. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  144855. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  144856. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  144857. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  144858. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  144859. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  144860. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  144861. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  144862. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  144863. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  144864. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  144865. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  144866. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  144867. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  144868. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  144869. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  144870. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  144871. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  144872. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  144873. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  144874. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  144875. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  144876. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  144877. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  144878. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  144879. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  144880. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  144881. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  144882. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  144883. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  144884. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  144885. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  144886. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  144887. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  144888. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  144889. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  144890. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  144891. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  144892. 12,
  144893. };
  144894. static float _vq_quantthresh__8u0__p4_0[] = {
  144895. -1.5, -0.5, 0.5, 1.5,
  144896. };
  144897. static long _vq_quantmap__8u0__p4_0[] = {
  144898. 3, 1, 0, 2, 4,
  144899. };
  144900. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  144901. _vq_quantthresh__8u0__p4_0,
  144902. _vq_quantmap__8u0__p4_0,
  144903. 5,
  144904. 5
  144905. };
  144906. static static_codebook _8u0__p4_0 = {
  144907. 4, 625,
  144908. _vq_lengthlist__8u0__p4_0,
  144909. 1, -533725184, 1611661312, 3, 0,
  144910. _vq_quantlist__8u0__p4_0,
  144911. NULL,
  144912. &_vq_auxt__8u0__p4_0,
  144913. NULL,
  144914. 0
  144915. };
  144916. static long _vq_quantlist__8u0__p5_0[] = {
  144917. 4,
  144918. 3,
  144919. 5,
  144920. 2,
  144921. 6,
  144922. 1,
  144923. 7,
  144924. 0,
  144925. 8,
  144926. };
  144927. static long _vq_lengthlist__8u0__p5_0[] = {
  144928. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  144929. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  144930. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  144931. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  144932. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  144933. 12,
  144934. };
  144935. static float _vq_quantthresh__8u0__p5_0[] = {
  144936. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144937. };
  144938. static long _vq_quantmap__8u0__p5_0[] = {
  144939. 7, 5, 3, 1, 0, 2, 4, 6,
  144940. 8,
  144941. };
  144942. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  144943. _vq_quantthresh__8u0__p5_0,
  144944. _vq_quantmap__8u0__p5_0,
  144945. 9,
  144946. 9
  144947. };
  144948. static static_codebook _8u0__p5_0 = {
  144949. 2, 81,
  144950. _vq_lengthlist__8u0__p5_0,
  144951. 1, -531628032, 1611661312, 4, 0,
  144952. _vq_quantlist__8u0__p5_0,
  144953. NULL,
  144954. &_vq_auxt__8u0__p5_0,
  144955. NULL,
  144956. 0
  144957. };
  144958. static long _vq_quantlist__8u0__p6_0[] = {
  144959. 6,
  144960. 5,
  144961. 7,
  144962. 4,
  144963. 8,
  144964. 3,
  144965. 9,
  144966. 2,
  144967. 10,
  144968. 1,
  144969. 11,
  144970. 0,
  144971. 12,
  144972. };
  144973. static long _vq_lengthlist__8u0__p6_0[] = {
  144974. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  144975. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  144976. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  144977. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  144978. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  144979. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  144980. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  144981. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  144982. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  144983. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  144984. 16, 0,15, 0,17, 0, 0, 0, 0,
  144985. };
  144986. static float _vq_quantthresh__8u0__p6_0[] = {
  144987. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144988. 12.5, 17.5, 22.5, 27.5,
  144989. };
  144990. static long _vq_quantmap__8u0__p6_0[] = {
  144991. 11, 9, 7, 5, 3, 1, 0, 2,
  144992. 4, 6, 8, 10, 12,
  144993. };
  144994. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  144995. _vq_quantthresh__8u0__p6_0,
  144996. _vq_quantmap__8u0__p6_0,
  144997. 13,
  144998. 13
  144999. };
  145000. static static_codebook _8u0__p6_0 = {
  145001. 2, 169,
  145002. _vq_lengthlist__8u0__p6_0,
  145003. 1, -526516224, 1616117760, 4, 0,
  145004. _vq_quantlist__8u0__p6_0,
  145005. NULL,
  145006. &_vq_auxt__8u0__p6_0,
  145007. NULL,
  145008. 0
  145009. };
  145010. static long _vq_quantlist__8u0__p6_1[] = {
  145011. 2,
  145012. 1,
  145013. 3,
  145014. 0,
  145015. 4,
  145016. };
  145017. static long _vq_lengthlist__8u0__p6_1[] = {
  145018. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145019. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145020. };
  145021. static float _vq_quantthresh__8u0__p6_1[] = {
  145022. -1.5, -0.5, 0.5, 1.5,
  145023. };
  145024. static long _vq_quantmap__8u0__p6_1[] = {
  145025. 3, 1, 0, 2, 4,
  145026. };
  145027. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145028. _vq_quantthresh__8u0__p6_1,
  145029. _vq_quantmap__8u0__p6_1,
  145030. 5,
  145031. 5
  145032. };
  145033. static static_codebook _8u0__p6_1 = {
  145034. 2, 25,
  145035. _vq_lengthlist__8u0__p6_1,
  145036. 1, -533725184, 1611661312, 3, 0,
  145037. _vq_quantlist__8u0__p6_1,
  145038. NULL,
  145039. &_vq_auxt__8u0__p6_1,
  145040. NULL,
  145041. 0
  145042. };
  145043. static long _vq_quantlist__8u0__p7_0[] = {
  145044. 1,
  145045. 0,
  145046. 2,
  145047. };
  145048. static long _vq_lengthlist__8u0__p7_0[] = {
  145049. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145050. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145051. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145052. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145053. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145054. 7,
  145055. };
  145056. static float _vq_quantthresh__8u0__p7_0[] = {
  145057. -157.5, 157.5,
  145058. };
  145059. static long _vq_quantmap__8u0__p7_0[] = {
  145060. 1, 0, 2,
  145061. };
  145062. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145063. _vq_quantthresh__8u0__p7_0,
  145064. _vq_quantmap__8u0__p7_0,
  145065. 3,
  145066. 3
  145067. };
  145068. static static_codebook _8u0__p7_0 = {
  145069. 4, 81,
  145070. _vq_lengthlist__8u0__p7_0,
  145071. 1, -518803456, 1628680192, 2, 0,
  145072. _vq_quantlist__8u0__p7_0,
  145073. NULL,
  145074. &_vq_auxt__8u0__p7_0,
  145075. NULL,
  145076. 0
  145077. };
  145078. static long _vq_quantlist__8u0__p7_1[] = {
  145079. 7,
  145080. 6,
  145081. 8,
  145082. 5,
  145083. 9,
  145084. 4,
  145085. 10,
  145086. 3,
  145087. 11,
  145088. 2,
  145089. 12,
  145090. 1,
  145091. 13,
  145092. 0,
  145093. 14,
  145094. };
  145095. static long _vq_lengthlist__8u0__p7_1[] = {
  145096. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145097. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145098. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145099. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145100. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145101. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145102. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145103. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145104. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145105. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145106. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145107. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145108. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145109. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145110. 10,
  145111. };
  145112. static float _vq_quantthresh__8u0__p7_1[] = {
  145113. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145114. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145115. };
  145116. static long _vq_quantmap__8u0__p7_1[] = {
  145117. 13, 11, 9, 7, 5, 3, 1, 0,
  145118. 2, 4, 6, 8, 10, 12, 14,
  145119. };
  145120. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145121. _vq_quantthresh__8u0__p7_1,
  145122. _vq_quantmap__8u0__p7_1,
  145123. 15,
  145124. 15
  145125. };
  145126. static static_codebook _8u0__p7_1 = {
  145127. 2, 225,
  145128. _vq_lengthlist__8u0__p7_1,
  145129. 1, -520986624, 1620377600, 4, 0,
  145130. _vq_quantlist__8u0__p7_1,
  145131. NULL,
  145132. &_vq_auxt__8u0__p7_1,
  145133. NULL,
  145134. 0
  145135. };
  145136. static long _vq_quantlist__8u0__p7_2[] = {
  145137. 10,
  145138. 9,
  145139. 11,
  145140. 8,
  145141. 12,
  145142. 7,
  145143. 13,
  145144. 6,
  145145. 14,
  145146. 5,
  145147. 15,
  145148. 4,
  145149. 16,
  145150. 3,
  145151. 17,
  145152. 2,
  145153. 18,
  145154. 1,
  145155. 19,
  145156. 0,
  145157. 20,
  145158. };
  145159. static long _vq_lengthlist__8u0__p7_2[] = {
  145160. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145161. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145162. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145163. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145164. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145165. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145166. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145167. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145168. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145169. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145170. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145171. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145172. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145173. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145174. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145175. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145176. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145177. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145178. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145179. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145180. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145181. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145182. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145183. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145184. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145185. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145186. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145187. 11,12,11,11,11,10,10,11,11,
  145188. };
  145189. static float _vq_quantthresh__8u0__p7_2[] = {
  145190. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145191. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145192. 6.5, 7.5, 8.5, 9.5,
  145193. };
  145194. static long _vq_quantmap__8u0__p7_2[] = {
  145195. 19, 17, 15, 13, 11, 9, 7, 5,
  145196. 3, 1, 0, 2, 4, 6, 8, 10,
  145197. 12, 14, 16, 18, 20,
  145198. };
  145199. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145200. _vq_quantthresh__8u0__p7_2,
  145201. _vq_quantmap__8u0__p7_2,
  145202. 21,
  145203. 21
  145204. };
  145205. static static_codebook _8u0__p7_2 = {
  145206. 2, 441,
  145207. _vq_lengthlist__8u0__p7_2,
  145208. 1, -529268736, 1611661312, 5, 0,
  145209. _vq_quantlist__8u0__p7_2,
  145210. NULL,
  145211. &_vq_auxt__8u0__p7_2,
  145212. NULL,
  145213. 0
  145214. };
  145215. static long _huff_lengthlist__8u0__single[] = {
  145216. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145217. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145218. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145219. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145220. };
  145221. static static_codebook _huff_book__8u0__single = {
  145222. 2, 64,
  145223. _huff_lengthlist__8u0__single,
  145224. 0, 0, 0, 0, 0,
  145225. NULL,
  145226. NULL,
  145227. NULL,
  145228. NULL,
  145229. 0
  145230. };
  145231. static long _vq_quantlist__8u1__p1_0[] = {
  145232. 1,
  145233. 0,
  145234. 2,
  145235. };
  145236. static long _vq_lengthlist__8u1__p1_0[] = {
  145237. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145238. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145239. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145240. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145241. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145242. 10,
  145243. };
  145244. static float _vq_quantthresh__8u1__p1_0[] = {
  145245. -0.5, 0.5,
  145246. };
  145247. static long _vq_quantmap__8u1__p1_0[] = {
  145248. 1, 0, 2,
  145249. };
  145250. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145251. _vq_quantthresh__8u1__p1_0,
  145252. _vq_quantmap__8u1__p1_0,
  145253. 3,
  145254. 3
  145255. };
  145256. static static_codebook _8u1__p1_0 = {
  145257. 4, 81,
  145258. _vq_lengthlist__8u1__p1_0,
  145259. 1, -535822336, 1611661312, 2, 0,
  145260. _vq_quantlist__8u1__p1_0,
  145261. NULL,
  145262. &_vq_auxt__8u1__p1_0,
  145263. NULL,
  145264. 0
  145265. };
  145266. static long _vq_quantlist__8u1__p2_0[] = {
  145267. 1,
  145268. 0,
  145269. 2,
  145270. };
  145271. static long _vq_lengthlist__8u1__p2_0[] = {
  145272. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145273. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145274. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145275. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145276. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145277. 7,
  145278. };
  145279. static float _vq_quantthresh__8u1__p2_0[] = {
  145280. -0.5, 0.5,
  145281. };
  145282. static long _vq_quantmap__8u1__p2_0[] = {
  145283. 1, 0, 2,
  145284. };
  145285. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145286. _vq_quantthresh__8u1__p2_0,
  145287. _vq_quantmap__8u1__p2_0,
  145288. 3,
  145289. 3
  145290. };
  145291. static static_codebook _8u1__p2_0 = {
  145292. 4, 81,
  145293. _vq_lengthlist__8u1__p2_0,
  145294. 1, -535822336, 1611661312, 2, 0,
  145295. _vq_quantlist__8u1__p2_0,
  145296. NULL,
  145297. &_vq_auxt__8u1__p2_0,
  145298. NULL,
  145299. 0
  145300. };
  145301. static long _vq_quantlist__8u1__p3_0[] = {
  145302. 2,
  145303. 1,
  145304. 3,
  145305. 0,
  145306. 4,
  145307. };
  145308. static long _vq_lengthlist__8u1__p3_0[] = {
  145309. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145310. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145311. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145312. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145313. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145314. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145315. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145316. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145317. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145318. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145319. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145320. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145321. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145322. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145323. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145324. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145325. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145326. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145327. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145328. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145329. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145330. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145331. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145332. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145333. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145334. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145335. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145336. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145337. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145338. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145339. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145340. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145341. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145342. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145343. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145344. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145345. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145346. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145347. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145348. 16,
  145349. };
  145350. static float _vq_quantthresh__8u1__p3_0[] = {
  145351. -1.5, -0.5, 0.5, 1.5,
  145352. };
  145353. static long _vq_quantmap__8u1__p3_0[] = {
  145354. 3, 1, 0, 2, 4,
  145355. };
  145356. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145357. _vq_quantthresh__8u1__p3_0,
  145358. _vq_quantmap__8u1__p3_0,
  145359. 5,
  145360. 5
  145361. };
  145362. static static_codebook _8u1__p3_0 = {
  145363. 4, 625,
  145364. _vq_lengthlist__8u1__p3_0,
  145365. 1, -533725184, 1611661312, 3, 0,
  145366. _vq_quantlist__8u1__p3_0,
  145367. NULL,
  145368. &_vq_auxt__8u1__p3_0,
  145369. NULL,
  145370. 0
  145371. };
  145372. static long _vq_quantlist__8u1__p4_0[] = {
  145373. 2,
  145374. 1,
  145375. 3,
  145376. 0,
  145377. 4,
  145378. };
  145379. static long _vq_lengthlist__8u1__p4_0[] = {
  145380. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145381. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145382. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145383. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145384. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145385. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145386. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145387. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145388. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145389. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145390. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145391. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145392. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145393. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145394. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145395. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145396. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145397. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145398. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145399. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145400. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145401. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145402. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145403. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145404. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145405. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145406. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145407. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145408. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145409. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145410. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145411. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145412. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145413. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145414. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145415. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145416. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145417. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145418. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145419. 10,
  145420. };
  145421. static float _vq_quantthresh__8u1__p4_0[] = {
  145422. -1.5, -0.5, 0.5, 1.5,
  145423. };
  145424. static long _vq_quantmap__8u1__p4_0[] = {
  145425. 3, 1, 0, 2, 4,
  145426. };
  145427. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145428. _vq_quantthresh__8u1__p4_0,
  145429. _vq_quantmap__8u1__p4_0,
  145430. 5,
  145431. 5
  145432. };
  145433. static static_codebook _8u1__p4_0 = {
  145434. 4, 625,
  145435. _vq_lengthlist__8u1__p4_0,
  145436. 1, -533725184, 1611661312, 3, 0,
  145437. _vq_quantlist__8u1__p4_0,
  145438. NULL,
  145439. &_vq_auxt__8u1__p4_0,
  145440. NULL,
  145441. 0
  145442. };
  145443. static long _vq_quantlist__8u1__p5_0[] = {
  145444. 4,
  145445. 3,
  145446. 5,
  145447. 2,
  145448. 6,
  145449. 1,
  145450. 7,
  145451. 0,
  145452. 8,
  145453. };
  145454. static long _vq_lengthlist__8u1__p5_0[] = {
  145455. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145456. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145457. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145458. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145459. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145460. 13,
  145461. };
  145462. static float _vq_quantthresh__8u1__p5_0[] = {
  145463. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145464. };
  145465. static long _vq_quantmap__8u1__p5_0[] = {
  145466. 7, 5, 3, 1, 0, 2, 4, 6,
  145467. 8,
  145468. };
  145469. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145470. _vq_quantthresh__8u1__p5_0,
  145471. _vq_quantmap__8u1__p5_0,
  145472. 9,
  145473. 9
  145474. };
  145475. static static_codebook _8u1__p5_0 = {
  145476. 2, 81,
  145477. _vq_lengthlist__8u1__p5_0,
  145478. 1, -531628032, 1611661312, 4, 0,
  145479. _vq_quantlist__8u1__p5_0,
  145480. NULL,
  145481. &_vq_auxt__8u1__p5_0,
  145482. NULL,
  145483. 0
  145484. };
  145485. static long _vq_quantlist__8u1__p6_0[] = {
  145486. 4,
  145487. 3,
  145488. 5,
  145489. 2,
  145490. 6,
  145491. 1,
  145492. 7,
  145493. 0,
  145494. 8,
  145495. };
  145496. static long _vq_lengthlist__8u1__p6_0[] = {
  145497. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  145498. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  145499. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145500. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  145501. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145502. 10,
  145503. };
  145504. static float _vq_quantthresh__8u1__p6_0[] = {
  145505. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145506. };
  145507. static long _vq_quantmap__8u1__p6_0[] = {
  145508. 7, 5, 3, 1, 0, 2, 4, 6,
  145509. 8,
  145510. };
  145511. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  145512. _vq_quantthresh__8u1__p6_0,
  145513. _vq_quantmap__8u1__p6_0,
  145514. 9,
  145515. 9
  145516. };
  145517. static static_codebook _8u1__p6_0 = {
  145518. 2, 81,
  145519. _vq_lengthlist__8u1__p6_0,
  145520. 1, -531628032, 1611661312, 4, 0,
  145521. _vq_quantlist__8u1__p6_0,
  145522. NULL,
  145523. &_vq_auxt__8u1__p6_0,
  145524. NULL,
  145525. 0
  145526. };
  145527. static long _vq_quantlist__8u1__p7_0[] = {
  145528. 1,
  145529. 0,
  145530. 2,
  145531. };
  145532. static long _vq_lengthlist__8u1__p7_0[] = {
  145533. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  145534. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  145535. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  145536. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  145537. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  145538. 11,
  145539. };
  145540. static float _vq_quantthresh__8u1__p7_0[] = {
  145541. -5.5, 5.5,
  145542. };
  145543. static long _vq_quantmap__8u1__p7_0[] = {
  145544. 1, 0, 2,
  145545. };
  145546. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  145547. _vq_quantthresh__8u1__p7_0,
  145548. _vq_quantmap__8u1__p7_0,
  145549. 3,
  145550. 3
  145551. };
  145552. static static_codebook _8u1__p7_0 = {
  145553. 4, 81,
  145554. _vq_lengthlist__8u1__p7_0,
  145555. 1, -529137664, 1618345984, 2, 0,
  145556. _vq_quantlist__8u1__p7_0,
  145557. NULL,
  145558. &_vq_auxt__8u1__p7_0,
  145559. NULL,
  145560. 0
  145561. };
  145562. static long _vq_quantlist__8u1__p7_1[] = {
  145563. 5,
  145564. 4,
  145565. 6,
  145566. 3,
  145567. 7,
  145568. 2,
  145569. 8,
  145570. 1,
  145571. 9,
  145572. 0,
  145573. 10,
  145574. };
  145575. static long _vq_lengthlist__8u1__p7_1[] = {
  145576. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145577. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  145578. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145579. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145580. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145581. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145582. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145583. 9, 9, 9, 9, 9,10,10,10,10,
  145584. };
  145585. static float _vq_quantthresh__8u1__p7_1[] = {
  145586. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145587. 3.5, 4.5,
  145588. };
  145589. static long _vq_quantmap__8u1__p7_1[] = {
  145590. 9, 7, 5, 3, 1, 0, 2, 4,
  145591. 6, 8, 10,
  145592. };
  145593. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  145594. _vq_quantthresh__8u1__p7_1,
  145595. _vq_quantmap__8u1__p7_1,
  145596. 11,
  145597. 11
  145598. };
  145599. static static_codebook _8u1__p7_1 = {
  145600. 2, 121,
  145601. _vq_lengthlist__8u1__p7_1,
  145602. 1, -531365888, 1611661312, 4, 0,
  145603. _vq_quantlist__8u1__p7_1,
  145604. NULL,
  145605. &_vq_auxt__8u1__p7_1,
  145606. NULL,
  145607. 0
  145608. };
  145609. static long _vq_quantlist__8u1__p8_0[] = {
  145610. 5,
  145611. 4,
  145612. 6,
  145613. 3,
  145614. 7,
  145615. 2,
  145616. 8,
  145617. 1,
  145618. 9,
  145619. 0,
  145620. 10,
  145621. };
  145622. static long _vq_lengthlist__8u1__p8_0[] = {
  145623. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145624. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  145625. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  145626. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  145627. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  145628. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  145629. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  145630. 12,13,13,14,14,15,15,15,15,
  145631. };
  145632. static float _vq_quantthresh__8u1__p8_0[] = {
  145633. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145634. 38.5, 49.5,
  145635. };
  145636. static long _vq_quantmap__8u1__p8_0[] = {
  145637. 9, 7, 5, 3, 1, 0, 2, 4,
  145638. 6, 8, 10,
  145639. };
  145640. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  145641. _vq_quantthresh__8u1__p8_0,
  145642. _vq_quantmap__8u1__p8_0,
  145643. 11,
  145644. 11
  145645. };
  145646. static static_codebook _8u1__p8_0 = {
  145647. 2, 121,
  145648. _vq_lengthlist__8u1__p8_0,
  145649. 1, -524582912, 1618345984, 4, 0,
  145650. _vq_quantlist__8u1__p8_0,
  145651. NULL,
  145652. &_vq_auxt__8u1__p8_0,
  145653. NULL,
  145654. 0
  145655. };
  145656. static long _vq_quantlist__8u1__p8_1[] = {
  145657. 5,
  145658. 4,
  145659. 6,
  145660. 3,
  145661. 7,
  145662. 2,
  145663. 8,
  145664. 1,
  145665. 9,
  145666. 0,
  145667. 10,
  145668. };
  145669. static long _vq_lengthlist__8u1__p8_1[] = {
  145670. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  145671. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  145672. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145673. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145674. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145675. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  145676. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  145677. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145678. };
  145679. static float _vq_quantthresh__8u1__p8_1[] = {
  145680. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145681. 3.5, 4.5,
  145682. };
  145683. static long _vq_quantmap__8u1__p8_1[] = {
  145684. 9, 7, 5, 3, 1, 0, 2, 4,
  145685. 6, 8, 10,
  145686. };
  145687. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  145688. _vq_quantthresh__8u1__p8_1,
  145689. _vq_quantmap__8u1__p8_1,
  145690. 11,
  145691. 11
  145692. };
  145693. static static_codebook _8u1__p8_1 = {
  145694. 2, 121,
  145695. _vq_lengthlist__8u1__p8_1,
  145696. 1, -531365888, 1611661312, 4, 0,
  145697. _vq_quantlist__8u1__p8_1,
  145698. NULL,
  145699. &_vq_auxt__8u1__p8_1,
  145700. NULL,
  145701. 0
  145702. };
  145703. static long _vq_quantlist__8u1__p9_0[] = {
  145704. 7,
  145705. 6,
  145706. 8,
  145707. 5,
  145708. 9,
  145709. 4,
  145710. 10,
  145711. 3,
  145712. 11,
  145713. 2,
  145714. 12,
  145715. 1,
  145716. 13,
  145717. 0,
  145718. 14,
  145719. };
  145720. static long _vq_lengthlist__8u1__p9_0[] = {
  145721. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  145722. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  145723. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145724. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145725. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145726. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145727. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145728. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145729. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145730. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145731. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145732. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145733. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  145734. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145735. 10,
  145736. };
  145737. static float _vq_quantthresh__8u1__p9_0[] = {
  145738. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  145739. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  145740. };
  145741. static long _vq_quantmap__8u1__p9_0[] = {
  145742. 13, 11, 9, 7, 5, 3, 1, 0,
  145743. 2, 4, 6, 8, 10, 12, 14,
  145744. };
  145745. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  145746. _vq_quantthresh__8u1__p9_0,
  145747. _vq_quantmap__8u1__p9_0,
  145748. 15,
  145749. 15
  145750. };
  145751. static static_codebook _8u1__p9_0 = {
  145752. 2, 225,
  145753. _vq_lengthlist__8u1__p9_0,
  145754. 1, -514071552, 1627381760, 4, 0,
  145755. _vq_quantlist__8u1__p9_0,
  145756. NULL,
  145757. &_vq_auxt__8u1__p9_0,
  145758. NULL,
  145759. 0
  145760. };
  145761. static long _vq_quantlist__8u1__p9_1[] = {
  145762. 7,
  145763. 6,
  145764. 8,
  145765. 5,
  145766. 9,
  145767. 4,
  145768. 10,
  145769. 3,
  145770. 11,
  145771. 2,
  145772. 12,
  145773. 1,
  145774. 13,
  145775. 0,
  145776. 14,
  145777. };
  145778. static long _vq_lengthlist__8u1__p9_1[] = {
  145779. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  145780. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  145781. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  145782. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  145783. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  145784. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  145785. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  145786. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  145787. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  145788. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  145789. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  145790. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  145791. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  145792. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  145793. 13,
  145794. };
  145795. static float _vq_quantthresh__8u1__p9_1[] = {
  145796. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145797. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145798. };
  145799. static long _vq_quantmap__8u1__p9_1[] = {
  145800. 13, 11, 9, 7, 5, 3, 1, 0,
  145801. 2, 4, 6, 8, 10, 12, 14,
  145802. };
  145803. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  145804. _vq_quantthresh__8u1__p9_1,
  145805. _vq_quantmap__8u1__p9_1,
  145806. 15,
  145807. 15
  145808. };
  145809. static static_codebook _8u1__p9_1 = {
  145810. 2, 225,
  145811. _vq_lengthlist__8u1__p9_1,
  145812. 1, -522338304, 1620115456, 4, 0,
  145813. _vq_quantlist__8u1__p9_1,
  145814. NULL,
  145815. &_vq_auxt__8u1__p9_1,
  145816. NULL,
  145817. 0
  145818. };
  145819. static long _vq_quantlist__8u1__p9_2[] = {
  145820. 8,
  145821. 7,
  145822. 9,
  145823. 6,
  145824. 10,
  145825. 5,
  145826. 11,
  145827. 4,
  145828. 12,
  145829. 3,
  145830. 13,
  145831. 2,
  145832. 14,
  145833. 1,
  145834. 15,
  145835. 0,
  145836. 16,
  145837. };
  145838. static long _vq_lengthlist__8u1__p9_2[] = {
  145839. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145840. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145841. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145842. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  145843. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145844. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  145845. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145846. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  145847. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145848. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  145849. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  145850. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  145851. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145852. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145853. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  145854. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145855. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145856. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145857. 10,
  145858. };
  145859. static float _vq_quantthresh__8u1__p9_2[] = {
  145860. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145861. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145862. };
  145863. static long _vq_quantmap__8u1__p9_2[] = {
  145864. 15, 13, 11, 9, 7, 5, 3, 1,
  145865. 0, 2, 4, 6, 8, 10, 12, 14,
  145866. 16,
  145867. };
  145868. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  145869. _vq_quantthresh__8u1__p9_2,
  145870. _vq_quantmap__8u1__p9_2,
  145871. 17,
  145872. 17
  145873. };
  145874. static static_codebook _8u1__p9_2 = {
  145875. 2, 289,
  145876. _vq_lengthlist__8u1__p9_2,
  145877. 1, -529530880, 1611661312, 5, 0,
  145878. _vq_quantlist__8u1__p9_2,
  145879. NULL,
  145880. &_vq_auxt__8u1__p9_2,
  145881. NULL,
  145882. 0
  145883. };
  145884. static long _huff_lengthlist__8u1__single[] = {
  145885. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  145886. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  145887. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  145888. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  145889. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  145890. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  145891. 13, 8, 8,15,
  145892. };
  145893. static static_codebook _huff_book__8u1__single = {
  145894. 2, 100,
  145895. _huff_lengthlist__8u1__single,
  145896. 0, 0, 0, 0, 0,
  145897. NULL,
  145898. NULL,
  145899. NULL,
  145900. NULL,
  145901. 0
  145902. };
  145903. static long _huff_lengthlist__44u0__long[] = {
  145904. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  145905. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  145906. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  145907. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  145908. };
  145909. static static_codebook _huff_book__44u0__long = {
  145910. 2, 64,
  145911. _huff_lengthlist__44u0__long,
  145912. 0, 0, 0, 0, 0,
  145913. NULL,
  145914. NULL,
  145915. NULL,
  145916. NULL,
  145917. 0
  145918. };
  145919. static long _vq_quantlist__44u0__p1_0[] = {
  145920. 1,
  145921. 0,
  145922. 2,
  145923. };
  145924. static long _vq_lengthlist__44u0__p1_0[] = {
  145925. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  145926. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  145927. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  145928. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  145929. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  145930. 13,
  145931. };
  145932. static float _vq_quantthresh__44u0__p1_0[] = {
  145933. -0.5, 0.5,
  145934. };
  145935. static long _vq_quantmap__44u0__p1_0[] = {
  145936. 1, 0, 2,
  145937. };
  145938. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  145939. _vq_quantthresh__44u0__p1_0,
  145940. _vq_quantmap__44u0__p1_0,
  145941. 3,
  145942. 3
  145943. };
  145944. static static_codebook _44u0__p1_0 = {
  145945. 4, 81,
  145946. _vq_lengthlist__44u0__p1_0,
  145947. 1, -535822336, 1611661312, 2, 0,
  145948. _vq_quantlist__44u0__p1_0,
  145949. NULL,
  145950. &_vq_auxt__44u0__p1_0,
  145951. NULL,
  145952. 0
  145953. };
  145954. static long _vq_quantlist__44u0__p2_0[] = {
  145955. 1,
  145956. 0,
  145957. 2,
  145958. };
  145959. static long _vq_lengthlist__44u0__p2_0[] = {
  145960. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  145961. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  145962. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  145963. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  145964. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  145965. 9,
  145966. };
  145967. static float _vq_quantthresh__44u0__p2_0[] = {
  145968. -0.5, 0.5,
  145969. };
  145970. static long _vq_quantmap__44u0__p2_0[] = {
  145971. 1, 0, 2,
  145972. };
  145973. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  145974. _vq_quantthresh__44u0__p2_0,
  145975. _vq_quantmap__44u0__p2_0,
  145976. 3,
  145977. 3
  145978. };
  145979. static static_codebook _44u0__p2_0 = {
  145980. 4, 81,
  145981. _vq_lengthlist__44u0__p2_0,
  145982. 1, -535822336, 1611661312, 2, 0,
  145983. _vq_quantlist__44u0__p2_0,
  145984. NULL,
  145985. &_vq_auxt__44u0__p2_0,
  145986. NULL,
  145987. 0
  145988. };
  145989. static long _vq_quantlist__44u0__p3_0[] = {
  145990. 2,
  145991. 1,
  145992. 3,
  145993. 0,
  145994. 4,
  145995. };
  145996. static long _vq_lengthlist__44u0__p3_0[] = {
  145997. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  145998. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  145999. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146000. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146001. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146002. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146003. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146004. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146005. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146006. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146007. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146008. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146009. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146010. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146011. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146012. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146013. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146014. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146015. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146016. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146017. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146018. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146019. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146020. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146021. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146022. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146023. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146024. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146025. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146026. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146027. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146028. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146029. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146030. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146031. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146032. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146033. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146034. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146035. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146036. 19,
  146037. };
  146038. static float _vq_quantthresh__44u0__p3_0[] = {
  146039. -1.5, -0.5, 0.5, 1.5,
  146040. };
  146041. static long _vq_quantmap__44u0__p3_0[] = {
  146042. 3, 1, 0, 2, 4,
  146043. };
  146044. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146045. _vq_quantthresh__44u0__p3_0,
  146046. _vq_quantmap__44u0__p3_0,
  146047. 5,
  146048. 5
  146049. };
  146050. static static_codebook _44u0__p3_0 = {
  146051. 4, 625,
  146052. _vq_lengthlist__44u0__p3_0,
  146053. 1, -533725184, 1611661312, 3, 0,
  146054. _vq_quantlist__44u0__p3_0,
  146055. NULL,
  146056. &_vq_auxt__44u0__p3_0,
  146057. NULL,
  146058. 0
  146059. };
  146060. static long _vq_quantlist__44u0__p4_0[] = {
  146061. 2,
  146062. 1,
  146063. 3,
  146064. 0,
  146065. 4,
  146066. };
  146067. static long _vq_lengthlist__44u0__p4_0[] = {
  146068. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146069. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146070. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146071. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146072. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146073. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146074. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146075. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146076. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146077. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146078. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146079. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146080. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146081. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146082. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146083. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146084. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146085. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146086. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146087. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146088. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146089. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146090. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146091. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146092. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146093. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146094. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146095. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146096. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146097. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146098. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146099. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146100. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146101. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146102. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146103. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146104. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146105. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146106. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146107. 12,
  146108. };
  146109. static float _vq_quantthresh__44u0__p4_0[] = {
  146110. -1.5, -0.5, 0.5, 1.5,
  146111. };
  146112. static long _vq_quantmap__44u0__p4_0[] = {
  146113. 3, 1, 0, 2, 4,
  146114. };
  146115. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146116. _vq_quantthresh__44u0__p4_0,
  146117. _vq_quantmap__44u0__p4_0,
  146118. 5,
  146119. 5
  146120. };
  146121. static static_codebook _44u0__p4_0 = {
  146122. 4, 625,
  146123. _vq_lengthlist__44u0__p4_0,
  146124. 1, -533725184, 1611661312, 3, 0,
  146125. _vq_quantlist__44u0__p4_0,
  146126. NULL,
  146127. &_vq_auxt__44u0__p4_0,
  146128. NULL,
  146129. 0
  146130. };
  146131. static long _vq_quantlist__44u0__p5_0[] = {
  146132. 4,
  146133. 3,
  146134. 5,
  146135. 2,
  146136. 6,
  146137. 1,
  146138. 7,
  146139. 0,
  146140. 8,
  146141. };
  146142. static long _vq_lengthlist__44u0__p5_0[] = {
  146143. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146144. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146145. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146146. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146147. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146148. 12,
  146149. };
  146150. static float _vq_quantthresh__44u0__p5_0[] = {
  146151. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146152. };
  146153. static long _vq_quantmap__44u0__p5_0[] = {
  146154. 7, 5, 3, 1, 0, 2, 4, 6,
  146155. 8,
  146156. };
  146157. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146158. _vq_quantthresh__44u0__p5_0,
  146159. _vq_quantmap__44u0__p5_0,
  146160. 9,
  146161. 9
  146162. };
  146163. static static_codebook _44u0__p5_0 = {
  146164. 2, 81,
  146165. _vq_lengthlist__44u0__p5_0,
  146166. 1, -531628032, 1611661312, 4, 0,
  146167. _vq_quantlist__44u0__p5_0,
  146168. NULL,
  146169. &_vq_auxt__44u0__p5_0,
  146170. NULL,
  146171. 0
  146172. };
  146173. static long _vq_quantlist__44u0__p6_0[] = {
  146174. 6,
  146175. 5,
  146176. 7,
  146177. 4,
  146178. 8,
  146179. 3,
  146180. 9,
  146181. 2,
  146182. 10,
  146183. 1,
  146184. 11,
  146185. 0,
  146186. 12,
  146187. };
  146188. static long _vq_lengthlist__44u0__p6_0[] = {
  146189. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146190. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146191. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146192. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146193. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146194. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146195. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146196. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146197. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146198. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146199. 15,17,16,17,18,17,17,18, 0,
  146200. };
  146201. static float _vq_quantthresh__44u0__p6_0[] = {
  146202. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146203. 12.5, 17.5, 22.5, 27.5,
  146204. };
  146205. static long _vq_quantmap__44u0__p6_0[] = {
  146206. 11, 9, 7, 5, 3, 1, 0, 2,
  146207. 4, 6, 8, 10, 12,
  146208. };
  146209. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146210. _vq_quantthresh__44u0__p6_0,
  146211. _vq_quantmap__44u0__p6_0,
  146212. 13,
  146213. 13
  146214. };
  146215. static static_codebook _44u0__p6_0 = {
  146216. 2, 169,
  146217. _vq_lengthlist__44u0__p6_0,
  146218. 1, -526516224, 1616117760, 4, 0,
  146219. _vq_quantlist__44u0__p6_0,
  146220. NULL,
  146221. &_vq_auxt__44u0__p6_0,
  146222. NULL,
  146223. 0
  146224. };
  146225. static long _vq_quantlist__44u0__p6_1[] = {
  146226. 2,
  146227. 1,
  146228. 3,
  146229. 0,
  146230. 4,
  146231. };
  146232. static long _vq_lengthlist__44u0__p6_1[] = {
  146233. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146234. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146235. };
  146236. static float _vq_quantthresh__44u0__p6_1[] = {
  146237. -1.5, -0.5, 0.5, 1.5,
  146238. };
  146239. static long _vq_quantmap__44u0__p6_1[] = {
  146240. 3, 1, 0, 2, 4,
  146241. };
  146242. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146243. _vq_quantthresh__44u0__p6_1,
  146244. _vq_quantmap__44u0__p6_1,
  146245. 5,
  146246. 5
  146247. };
  146248. static static_codebook _44u0__p6_1 = {
  146249. 2, 25,
  146250. _vq_lengthlist__44u0__p6_1,
  146251. 1, -533725184, 1611661312, 3, 0,
  146252. _vq_quantlist__44u0__p6_1,
  146253. NULL,
  146254. &_vq_auxt__44u0__p6_1,
  146255. NULL,
  146256. 0
  146257. };
  146258. static long _vq_quantlist__44u0__p7_0[] = {
  146259. 2,
  146260. 1,
  146261. 3,
  146262. 0,
  146263. 4,
  146264. };
  146265. static long _vq_lengthlist__44u0__p7_0[] = {
  146266. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146267. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146268. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146269. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146270. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146271. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146272. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146273. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146274. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146275. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146276. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146277. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146278. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146279. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146280. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146281. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146282. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146283. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146284. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146285. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146286. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146287. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146288. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146289. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146290. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146291. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146292. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146293. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146294. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146295. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146296. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146297. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146298. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146299. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146300. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146301. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146302. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146303. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146304. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146305. 10,
  146306. };
  146307. static float _vq_quantthresh__44u0__p7_0[] = {
  146308. -253.5, -84.5, 84.5, 253.5,
  146309. };
  146310. static long _vq_quantmap__44u0__p7_0[] = {
  146311. 3, 1, 0, 2, 4,
  146312. };
  146313. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146314. _vq_quantthresh__44u0__p7_0,
  146315. _vq_quantmap__44u0__p7_0,
  146316. 5,
  146317. 5
  146318. };
  146319. static static_codebook _44u0__p7_0 = {
  146320. 4, 625,
  146321. _vq_lengthlist__44u0__p7_0,
  146322. 1, -518709248, 1626677248, 3, 0,
  146323. _vq_quantlist__44u0__p7_0,
  146324. NULL,
  146325. &_vq_auxt__44u0__p7_0,
  146326. NULL,
  146327. 0
  146328. };
  146329. static long _vq_quantlist__44u0__p7_1[] = {
  146330. 6,
  146331. 5,
  146332. 7,
  146333. 4,
  146334. 8,
  146335. 3,
  146336. 9,
  146337. 2,
  146338. 10,
  146339. 1,
  146340. 11,
  146341. 0,
  146342. 12,
  146343. };
  146344. static long _vq_lengthlist__44u0__p7_1[] = {
  146345. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146346. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146347. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146348. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146349. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146350. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146351. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146352. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146353. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146354. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146355. 15,15,15,15,15,15,15,15,15,
  146356. };
  146357. static float _vq_quantthresh__44u0__p7_1[] = {
  146358. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146359. 32.5, 45.5, 58.5, 71.5,
  146360. };
  146361. static long _vq_quantmap__44u0__p7_1[] = {
  146362. 11, 9, 7, 5, 3, 1, 0, 2,
  146363. 4, 6, 8, 10, 12,
  146364. };
  146365. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146366. _vq_quantthresh__44u0__p7_1,
  146367. _vq_quantmap__44u0__p7_1,
  146368. 13,
  146369. 13
  146370. };
  146371. static static_codebook _44u0__p7_1 = {
  146372. 2, 169,
  146373. _vq_lengthlist__44u0__p7_1,
  146374. 1, -523010048, 1618608128, 4, 0,
  146375. _vq_quantlist__44u0__p7_1,
  146376. NULL,
  146377. &_vq_auxt__44u0__p7_1,
  146378. NULL,
  146379. 0
  146380. };
  146381. static long _vq_quantlist__44u0__p7_2[] = {
  146382. 6,
  146383. 5,
  146384. 7,
  146385. 4,
  146386. 8,
  146387. 3,
  146388. 9,
  146389. 2,
  146390. 10,
  146391. 1,
  146392. 11,
  146393. 0,
  146394. 12,
  146395. };
  146396. static long _vq_lengthlist__44u0__p7_2[] = {
  146397. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146398. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146399. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146400. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146401. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146402. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146403. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146404. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146405. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146406. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146407. 9, 9, 9,10, 9, 9,10,10, 9,
  146408. };
  146409. static float _vq_quantthresh__44u0__p7_2[] = {
  146410. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146411. 2.5, 3.5, 4.5, 5.5,
  146412. };
  146413. static long _vq_quantmap__44u0__p7_2[] = {
  146414. 11, 9, 7, 5, 3, 1, 0, 2,
  146415. 4, 6, 8, 10, 12,
  146416. };
  146417. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146418. _vq_quantthresh__44u0__p7_2,
  146419. _vq_quantmap__44u0__p7_2,
  146420. 13,
  146421. 13
  146422. };
  146423. static static_codebook _44u0__p7_2 = {
  146424. 2, 169,
  146425. _vq_lengthlist__44u0__p7_2,
  146426. 1, -531103744, 1611661312, 4, 0,
  146427. _vq_quantlist__44u0__p7_2,
  146428. NULL,
  146429. &_vq_auxt__44u0__p7_2,
  146430. NULL,
  146431. 0
  146432. };
  146433. static long _huff_lengthlist__44u0__short[] = {
  146434. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146435. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146436. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146437. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146438. };
  146439. static static_codebook _huff_book__44u0__short = {
  146440. 2, 64,
  146441. _huff_lengthlist__44u0__short,
  146442. 0, 0, 0, 0, 0,
  146443. NULL,
  146444. NULL,
  146445. NULL,
  146446. NULL,
  146447. 0
  146448. };
  146449. static long _huff_lengthlist__44u1__long[] = {
  146450. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146451. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146452. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146453. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146454. };
  146455. static static_codebook _huff_book__44u1__long = {
  146456. 2, 64,
  146457. _huff_lengthlist__44u1__long,
  146458. 0, 0, 0, 0, 0,
  146459. NULL,
  146460. NULL,
  146461. NULL,
  146462. NULL,
  146463. 0
  146464. };
  146465. static long _vq_quantlist__44u1__p1_0[] = {
  146466. 1,
  146467. 0,
  146468. 2,
  146469. };
  146470. static long _vq_lengthlist__44u1__p1_0[] = {
  146471. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146472. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146473. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146474. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146475. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146476. 13,
  146477. };
  146478. static float _vq_quantthresh__44u1__p1_0[] = {
  146479. -0.5, 0.5,
  146480. };
  146481. static long _vq_quantmap__44u1__p1_0[] = {
  146482. 1, 0, 2,
  146483. };
  146484. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146485. _vq_quantthresh__44u1__p1_0,
  146486. _vq_quantmap__44u1__p1_0,
  146487. 3,
  146488. 3
  146489. };
  146490. static static_codebook _44u1__p1_0 = {
  146491. 4, 81,
  146492. _vq_lengthlist__44u1__p1_0,
  146493. 1, -535822336, 1611661312, 2, 0,
  146494. _vq_quantlist__44u1__p1_0,
  146495. NULL,
  146496. &_vq_auxt__44u1__p1_0,
  146497. NULL,
  146498. 0
  146499. };
  146500. static long _vq_quantlist__44u1__p2_0[] = {
  146501. 1,
  146502. 0,
  146503. 2,
  146504. };
  146505. static long _vq_lengthlist__44u1__p2_0[] = {
  146506. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146507. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146508. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146509. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146510. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146511. 9,
  146512. };
  146513. static float _vq_quantthresh__44u1__p2_0[] = {
  146514. -0.5, 0.5,
  146515. };
  146516. static long _vq_quantmap__44u1__p2_0[] = {
  146517. 1, 0, 2,
  146518. };
  146519. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  146520. _vq_quantthresh__44u1__p2_0,
  146521. _vq_quantmap__44u1__p2_0,
  146522. 3,
  146523. 3
  146524. };
  146525. static static_codebook _44u1__p2_0 = {
  146526. 4, 81,
  146527. _vq_lengthlist__44u1__p2_0,
  146528. 1, -535822336, 1611661312, 2, 0,
  146529. _vq_quantlist__44u1__p2_0,
  146530. NULL,
  146531. &_vq_auxt__44u1__p2_0,
  146532. NULL,
  146533. 0
  146534. };
  146535. static long _vq_quantlist__44u1__p3_0[] = {
  146536. 2,
  146537. 1,
  146538. 3,
  146539. 0,
  146540. 4,
  146541. };
  146542. static long _vq_lengthlist__44u1__p3_0[] = {
  146543. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146544. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146545. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146546. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146547. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146548. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146549. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146550. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146551. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146552. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146553. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146554. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146555. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146556. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146557. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146558. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146559. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146560. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146561. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146562. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146563. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146564. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146565. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146566. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146567. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146568. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146569. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146570. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146571. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146572. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146573. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146574. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146575. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146576. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146577. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146578. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146579. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146580. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146581. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146582. 19,
  146583. };
  146584. static float _vq_quantthresh__44u1__p3_0[] = {
  146585. -1.5, -0.5, 0.5, 1.5,
  146586. };
  146587. static long _vq_quantmap__44u1__p3_0[] = {
  146588. 3, 1, 0, 2, 4,
  146589. };
  146590. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  146591. _vq_quantthresh__44u1__p3_0,
  146592. _vq_quantmap__44u1__p3_0,
  146593. 5,
  146594. 5
  146595. };
  146596. static static_codebook _44u1__p3_0 = {
  146597. 4, 625,
  146598. _vq_lengthlist__44u1__p3_0,
  146599. 1, -533725184, 1611661312, 3, 0,
  146600. _vq_quantlist__44u1__p3_0,
  146601. NULL,
  146602. &_vq_auxt__44u1__p3_0,
  146603. NULL,
  146604. 0
  146605. };
  146606. static long _vq_quantlist__44u1__p4_0[] = {
  146607. 2,
  146608. 1,
  146609. 3,
  146610. 0,
  146611. 4,
  146612. };
  146613. static long _vq_lengthlist__44u1__p4_0[] = {
  146614. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146615. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146616. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146617. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146618. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146619. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146620. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146621. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146622. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146623. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146624. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146625. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146626. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146627. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146628. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146629. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146630. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146631. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146632. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146633. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146634. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146635. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146636. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146637. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146638. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146639. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146640. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146641. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146642. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146643. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146644. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146645. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146646. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146647. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146648. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146649. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146650. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146651. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146652. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146653. 12,
  146654. };
  146655. static float _vq_quantthresh__44u1__p4_0[] = {
  146656. -1.5, -0.5, 0.5, 1.5,
  146657. };
  146658. static long _vq_quantmap__44u1__p4_0[] = {
  146659. 3, 1, 0, 2, 4,
  146660. };
  146661. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  146662. _vq_quantthresh__44u1__p4_0,
  146663. _vq_quantmap__44u1__p4_0,
  146664. 5,
  146665. 5
  146666. };
  146667. static static_codebook _44u1__p4_0 = {
  146668. 4, 625,
  146669. _vq_lengthlist__44u1__p4_0,
  146670. 1, -533725184, 1611661312, 3, 0,
  146671. _vq_quantlist__44u1__p4_0,
  146672. NULL,
  146673. &_vq_auxt__44u1__p4_0,
  146674. NULL,
  146675. 0
  146676. };
  146677. static long _vq_quantlist__44u1__p5_0[] = {
  146678. 4,
  146679. 3,
  146680. 5,
  146681. 2,
  146682. 6,
  146683. 1,
  146684. 7,
  146685. 0,
  146686. 8,
  146687. };
  146688. static long _vq_lengthlist__44u1__p5_0[] = {
  146689. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146690. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146691. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146692. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146693. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146694. 12,
  146695. };
  146696. static float _vq_quantthresh__44u1__p5_0[] = {
  146697. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146698. };
  146699. static long _vq_quantmap__44u1__p5_0[] = {
  146700. 7, 5, 3, 1, 0, 2, 4, 6,
  146701. 8,
  146702. };
  146703. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  146704. _vq_quantthresh__44u1__p5_0,
  146705. _vq_quantmap__44u1__p5_0,
  146706. 9,
  146707. 9
  146708. };
  146709. static static_codebook _44u1__p5_0 = {
  146710. 2, 81,
  146711. _vq_lengthlist__44u1__p5_0,
  146712. 1, -531628032, 1611661312, 4, 0,
  146713. _vq_quantlist__44u1__p5_0,
  146714. NULL,
  146715. &_vq_auxt__44u1__p5_0,
  146716. NULL,
  146717. 0
  146718. };
  146719. static long _vq_quantlist__44u1__p6_0[] = {
  146720. 6,
  146721. 5,
  146722. 7,
  146723. 4,
  146724. 8,
  146725. 3,
  146726. 9,
  146727. 2,
  146728. 10,
  146729. 1,
  146730. 11,
  146731. 0,
  146732. 12,
  146733. };
  146734. static long _vq_lengthlist__44u1__p6_0[] = {
  146735. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146736. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146737. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146738. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146739. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146740. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146741. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146742. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146743. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146744. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146745. 15,17,16,17,18,17,17,18, 0,
  146746. };
  146747. static float _vq_quantthresh__44u1__p6_0[] = {
  146748. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146749. 12.5, 17.5, 22.5, 27.5,
  146750. };
  146751. static long _vq_quantmap__44u1__p6_0[] = {
  146752. 11, 9, 7, 5, 3, 1, 0, 2,
  146753. 4, 6, 8, 10, 12,
  146754. };
  146755. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  146756. _vq_quantthresh__44u1__p6_0,
  146757. _vq_quantmap__44u1__p6_0,
  146758. 13,
  146759. 13
  146760. };
  146761. static static_codebook _44u1__p6_0 = {
  146762. 2, 169,
  146763. _vq_lengthlist__44u1__p6_0,
  146764. 1, -526516224, 1616117760, 4, 0,
  146765. _vq_quantlist__44u1__p6_0,
  146766. NULL,
  146767. &_vq_auxt__44u1__p6_0,
  146768. NULL,
  146769. 0
  146770. };
  146771. static long _vq_quantlist__44u1__p6_1[] = {
  146772. 2,
  146773. 1,
  146774. 3,
  146775. 0,
  146776. 4,
  146777. };
  146778. static long _vq_lengthlist__44u1__p6_1[] = {
  146779. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146780. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146781. };
  146782. static float _vq_quantthresh__44u1__p6_1[] = {
  146783. -1.5, -0.5, 0.5, 1.5,
  146784. };
  146785. static long _vq_quantmap__44u1__p6_1[] = {
  146786. 3, 1, 0, 2, 4,
  146787. };
  146788. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  146789. _vq_quantthresh__44u1__p6_1,
  146790. _vq_quantmap__44u1__p6_1,
  146791. 5,
  146792. 5
  146793. };
  146794. static static_codebook _44u1__p6_1 = {
  146795. 2, 25,
  146796. _vq_lengthlist__44u1__p6_1,
  146797. 1, -533725184, 1611661312, 3, 0,
  146798. _vq_quantlist__44u1__p6_1,
  146799. NULL,
  146800. &_vq_auxt__44u1__p6_1,
  146801. NULL,
  146802. 0
  146803. };
  146804. static long _vq_quantlist__44u1__p7_0[] = {
  146805. 3,
  146806. 2,
  146807. 4,
  146808. 1,
  146809. 5,
  146810. 0,
  146811. 6,
  146812. };
  146813. static long _vq_lengthlist__44u1__p7_0[] = {
  146814. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146815. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146816. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146817. 8,
  146818. };
  146819. static float _vq_quantthresh__44u1__p7_0[] = {
  146820. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  146821. };
  146822. static long _vq_quantmap__44u1__p7_0[] = {
  146823. 5, 3, 1, 0, 2, 4, 6,
  146824. };
  146825. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  146826. _vq_quantthresh__44u1__p7_0,
  146827. _vq_quantmap__44u1__p7_0,
  146828. 7,
  146829. 7
  146830. };
  146831. static static_codebook _44u1__p7_0 = {
  146832. 2, 49,
  146833. _vq_lengthlist__44u1__p7_0,
  146834. 1, -518017024, 1626677248, 3, 0,
  146835. _vq_quantlist__44u1__p7_0,
  146836. NULL,
  146837. &_vq_auxt__44u1__p7_0,
  146838. NULL,
  146839. 0
  146840. };
  146841. static long _vq_quantlist__44u1__p7_1[] = {
  146842. 6,
  146843. 5,
  146844. 7,
  146845. 4,
  146846. 8,
  146847. 3,
  146848. 9,
  146849. 2,
  146850. 10,
  146851. 1,
  146852. 11,
  146853. 0,
  146854. 12,
  146855. };
  146856. static long _vq_lengthlist__44u1__p7_1[] = {
  146857. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146858. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146859. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146860. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146861. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146862. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146863. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146864. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146865. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146866. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146867. 15,15,15,15,15,15,15,15,15,
  146868. };
  146869. static float _vq_quantthresh__44u1__p7_1[] = {
  146870. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146871. 32.5, 45.5, 58.5, 71.5,
  146872. };
  146873. static long _vq_quantmap__44u1__p7_1[] = {
  146874. 11, 9, 7, 5, 3, 1, 0, 2,
  146875. 4, 6, 8, 10, 12,
  146876. };
  146877. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  146878. _vq_quantthresh__44u1__p7_1,
  146879. _vq_quantmap__44u1__p7_1,
  146880. 13,
  146881. 13
  146882. };
  146883. static static_codebook _44u1__p7_1 = {
  146884. 2, 169,
  146885. _vq_lengthlist__44u1__p7_1,
  146886. 1, -523010048, 1618608128, 4, 0,
  146887. _vq_quantlist__44u1__p7_1,
  146888. NULL,
  146889. &_vq_auxt__44u1__p7_1,
  146890. NULL,
  146891. 0
  146892. };
  146893. static long _vq_quantlist__44u1__p7_2[] = {
  146894. 6,
  146895. 5,
  146896. 7,
  146897. 4,
  146898. 8,
  146899. 3,
  146900. 9,
  146901. 2,
  146902. 10,
  146903. 1,
  146904. 11,
  146905. 0,
  146906. 12,
  146907. };
  146908. static long _vq_lengthlist__44u1__p7_2[] = {
  146909. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146910. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146911. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146912. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146913. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146914. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146915. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146916. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146917. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146918. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146919. 9, 9, 9,10, 9, 9,10,10, 9,
  146920. };
  146921. static float _vq_quantthresh__44u1__p7_2[] = {
  146922. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146923. 2.5, 3.5, 4.5, 5.5,
  146924. };
  146925. static long _vq_quantmap__44u1__p7_2[] = {
  146926. 11, 9, 7, 5, 3, 1, 0, 2,
  146927. 4, 6, 8, 10, 12,
  146928. };
  146929. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  146930. _vq_quantthresh__44u1__p7_2,
  146931. _vq_quantmap__44u1__p7_2,
  146932. 13,
  146933. 13
  146934. };
  146935. static static_codebook _44u1__p7_2 = {
  146936. 2, 169,
  146937. _vq_lengthlist__44u1__p7_2,
  146938. 1, -531103744, 1611661312, 4, 0,
  146939. _vq_quantlist__44u1__p7_2,
  146940. NULL,
  146941. &_vq_auxt__44u1__p7_2,
  146942. NULL,
  146943. 0
  146944. };
  146945. static long _huff_lengthlist__44u1__short[] = {
  146946. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146947. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146948. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146949. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146950. };
  146951. static static_codebook _huff_book__44u1__short = {
  146952. 2, 64,
  146953. _huff_lengthlist__44u1__short,
  146954. 0, 0, 0, 0, 0,
  146955. NULL,
  146956. NULL,
  146957. NULL,
  146958. NULL,
  146959. 0
  146960. };
  146961. static long _huff_lengthlist__44u2__long[] = {
  146962. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  146963. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  146964. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  146965. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  146966. };
  146967. static static_codebook _huff_book__44u2__long = {
  146968. 2, 64,
  146969. _huff_lengthlist__44u2__long,
  146970. 0, 0, 0, 0, 0,
  146971. NULL,
  146972. NULL,
  146973. NULL,
  146974. NULL,
  146975. 0
  146976. };
  146977. static long _vq_quantlist__44u2__p1_0[] = {
  146978. 1,
  146979. 0,
  146980. 2,
  146981. };
  146982. static long _vq_lengthlist__44u2__p1_0[] = {
  146983. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146984. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146985. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  146986. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  146987. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  146988. 13,
  146989. };
  146990. static float _vq_quantthresh__44u2__p1_0[] = {
  146991. -0.5, 0.5,
  146992. };
  146993. static long _vq_quantmap__44u2__p1_0[] = {
  146994. 1, 0, 2,
  146995. };
  146996. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  146997. _vq_quantthresh__44u2__p1_0,
  146998. _vq_quantmap__44u2__p1_0,
  146999. 3,
  147000. 3
  147001. };
  147002. static static_codebook _44u2__p1_0 = {
  147003. 4, 81,
  147004. _vq_lengthlist__44u2__p1_0,
  147005. 1, -535822336, 1611661312, 2, 0,
  147006. _vq_quantlist__44u2__p1_0,
  147007. NULL,
  147008. &_vq_auxt__44u2__p1_0,
  147009. NULL,
  147010. 0
  147011. };
  147012. static long _vq_quantlist__44u2__p2_0[] = {
  147013. 1,
  147014. 0,
  147015. 2,
  147016. };
  147017. static long _vq_lengthlist__44u2__p2_0[] = {
  147018. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147019. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147020. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147021. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147022. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147023. 9,
  147024. };
  147025. static float _vq_quantthresh__44u2__p2_0[] = {
  147026. -0.5, 0.5,
  147027. };
  147028. static long _vq_quantmap__44u2__p2_0[] = {
  147029. 1, 0, 2,
  147030. };
  147031. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147032. _vq_quantthresh__44u2__p2_0,
  147033. _vq_quantmap__44u2__p2_0,
  147034. 3,
  147035. 3
  147036. };
  147037. static static_codebook _44u2__p2_0 = {
  147038. 4, 81,
  147039. _vq_lengthlist__44u2__p2_0,
  147040. 1, -535822336, 1611661312, 2, 0,
  147041. _vq_quantlist__44u2__p2_0,
  147042. NULL,
  147043. &_vq_auxt__44u2__p2_0,
  147044. NULL,
  147045. 0
  147046. };
  147047. static long _vq_quantlist__44u2__p3_0[] = {
  147048. 2,
  147049. 1,
  147050. 3,
  147051. 0,
  147052. 4,
  147053. };
  147054. static long _vq_lengthlist__44u2__p3_0[] = {
  147055. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147056. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147057. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147058. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147059. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147060. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147061. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147062. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147063. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147064. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147065. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147066. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147067. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147068. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147069. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147070. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147071. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147072. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147073. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147074. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147075. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147076. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147077. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147078. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147079. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147080. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147081. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147082. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147083. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147084. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147085. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147086. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147087. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147088. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147089. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147090. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147091. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147092. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147093. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147094. 0,
  147095. };
  147096. static float _vq_quantthresh__44u2__p3_0[] = {
  147097. -1.5, -0.5, 0.5, 1.5,
  147098. };
  147099. static long _vq_quantmap__44u2__p3_0[] = {
  147100. 3, 1, 0, 2, 4,
  147101. };
  147102. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147103. _vq_quantthresh__44u2__p3_0,
  147104. _vq_quantmap__44u2__p3_0,
  147105. 5,
  147106. 5
  147107. };
  147108. static static_codebook _44u2__p3_0 = {
  147109. 4, 625,
  147110. _vq_lengthlist__44u2__p3_0,
  147111. 1, -533725184, 1611661312, 3, 0,
  147112. _vq_quantlist__44u2__p3_0,
  147113. NULL,
  147114. &_vq_auxt__44u2__p3_0,
  147115. NULL,
  147116. 0
  147117. };
  147118. static long _vq_quantlist__44u2__p4_0[] = {
  147119. 2,
  147120. 1,
  147121. 3,
  147122. 0,
  147123. 4,
  147124. };
  147125. static long _vq_lengthlist__44u2__p4_0[] = {
  147126. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147127. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147128. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147129. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147130. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147131. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147132. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147133. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147134. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147135. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147136. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147137. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147138. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147139. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147140. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147141. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147142. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147143. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147144. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147145. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147146. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147147. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147148. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147149. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147150. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147151. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147152. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147153. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147154. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147155. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147156. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147157. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147158. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147159. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147160. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147161. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147162. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147163. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147164. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147165. 13,
  147166. };
  147167. static float _vq_quantthresh__44u2__p4_0[] = {
  147168. -1.5, -0.5, 0.5, 1.5,
  147169. };
  147170. static long _vq_quantmap__44u2__p4_0[] = {
  147171. 3, 1, 0, 2, 4,
  147172. };
  147173. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147174. _vq_quantthresh__44u2__p4_0,
  147175. _vq_quantmap__44u2__p4_0,
  147176. 5,
  147177. 5
  147178. };
  147179. static static_codebook _44u2__p4_0 = {
  147180. 4, 625,
  147181. _vq_lengthlist__44u2__p4_0,
  147182. 1, -533725184, 1611661312, 3, 0,
  147183. _vq_quantlist__44u2__p4_0,
  147184. NULL,
  147185. &_vq_auxt__44u2__p4_0,
  147186. NULL,
  147187. 0
  147188. };
  147189. static long _vq_quantlist__44u2__p5_0[] = {
  147190. 4,
  147191. 3,
  147192. 5,
  147193. 2,
  147194. 6,
  147195. 1,
  147196. 7,
  147197. 0,
  147198. 8,
  147199. };
  147200. static long _vq_lengthlist__44u2__p5_0[] = {
  147201. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147202. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147203. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147204. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147205. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147206. 13,
  147207. };
  147208. static float _vq_quantthresh__44u2__p5_0[] = {
  147209. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147210. };
  147211. static long _vq_quantmap__44u2__p5_0[] = {
  147212. 7, 5, 3, 1, 0, 2, 4, 6,
  147213. 8,
  147214. };
  147215. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147216. _vq_quantthresh__44u2__p5_0,
  147217. _vq_quantmap__44u2__p5_0,
  147218. 9,
  147219. 9
  147220. };
  147221. static static_codebook _44u2__p5_0 = {
  147222. 2, 81,
  147223. _vq_lengthlist__44u2__p5_0,
  147224. 1, -531628032, 1611661312, 4, 0,
  147225. _vq_quantlist__44u2__p5_0,
  147226. NULL,
  147227. &_vq_auxt__44u2__p5_0,
  147228. NULL,
  147229. 0
  147230. };
  147231. static long _vq_quantlist__44u2__p6_0[] = {
  147232. 6,
  147233. 5,
  147234. 7,
  147235. 4,
  147236. 8,
  147237. 3,
  147238. 9,
  147239. 2,
  147240. 10,
  147241. 1,
  147242. 11,
  147243. 0,
  147244. 12,
  147245. };
  147246. static long _vq_lengthlist__44u2__p6_0[] = {
  147247. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147248. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147249. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147250. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147251. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147252. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147253. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147254. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147255. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147256. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147257. 15,17,17,16,18,17,18, 0, 0,
  147258. };
  147259. static float _vq_quantthresh__44u2__p6_0[] = {
  147260. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147261. 12.5, 17.5, 22.5, 27.5,
  147262. };
  147263. static long _vq_quantmap__44u2__p6_0[] = {
  147264. 11, 9, 7, 5, 3, 1, 0, 2,
  147265. 4, 6, 8, 10, 12,
  147266. };
  147267. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147268. _vq_quantthresh__44u2__p6_0,
  147269. _vq_quantmap__44u2__p6_0,
  147270. 13,
  147271. 13
  147272. };
  147273. static static_codebook _44u2__p6_0 = {
  147274. 2, 169,
  147275. _vq_lengthlist__44u2__p6_0,
  147276. 1, -526516224, 1616117760, 4, 0,
  147277. _vq_quantlist__44u2__p6_0,
  147278. NULL,
  147279. &_vq_auxt__44u2__p6_0,
  147280. NULL,
  147281. 0
  147282. };
  147283. static long _vq_quantlist__44u2__p6_1[] = {
  147284. 2,
  147285. 1,
  147286. 3,
  147287. 0,
  147288. 4,
  147289. };
  147290. static long _vq_lengthlist__44u2__p6_1[] = {
  147291. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147292. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147293. };
  147294. static float _vq_quantthresh__44u2__p6_1[] = {
  147295. -1.5, -0.5, 0.5, 1.5,
  147296. };
  147297. static long _vq_quantmap__44u2__p6_1[] = {
  147298. 3, 1, 0, 2, 4,
  147299. };
  147300. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147301. _vq_quantthresh__44u2__p6_1,
  147302. _vq_quantmap__44u2__p6_1,
  147303. 5,
  147304. 5
  147305. };
  147306. static static_codebook _44u2__p6_1 = {
  147307. 2, 25,
  147308. _vq_lengthlist__44u2__p6_1,
  147309. 1, -533725184, 1611661312, 3, 0,
  147310. _vq_quantlist__44u2__p6_1,
  147311. NULL,
  147312. &_vq_auxt__44u2__p6_1,
  147313. NULL,
  147314. 0
  147315. };
  147316. static long _vq_quantlist__44u2__p7_0[] = {
  147317. 4,
  147318. 3,
  147319. 5,
  147320. 2,
  147321. 6,
  147322. 1,
  147323. 7,
  147324. 0,
  147325. 8,
  147326. };
  147327. static long _vq_lengthlist__44u2__p7_0[] = {
  147328. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147329. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147330. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147331. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147332. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147333. 11,
  147334. };
  147335. static float _vq_quantthresh__44u2__p7_0[] = {
  147336. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147337. };
  147338. static long _vq_quantmap__44u2__p7_0[] = {
  147339. 7, 5, 3, 1, 0, 2, 4, 6,
  147340. 8,
  147341. };
  147342. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147343. _vq_quantthresh__44u2__p7_0,
  147344. _vq_quantmap__44u2__p7_0,
  147345. 9,
  147346. 9
  147347. };
  147348. static static_codebook _44u2__p7_0 = {
  147349. 2, 81,
  147350. _vq_lengthlist__44u2__p7_0,
  147351. 1, -516612096, 1626677248, 4, 0,
  147352. _vq_quantlist__44u2__p7_0,
  147353. NULL,
  147354. &_vq_auxt__44u2__p7_0,
  147355. NULL,
  147356. 0
  147357. };
  147358. static long _vq_quantlist__44u2__p7_1[] = {
  147359. 6,
  147360. 5,
  147361. 7,
  147362. 4,
  147363. 8,
  147364. 3,
  147365. 9,
  147366. 2,
  147367. 10,
  147368. 1,
  147369. 11,
  147370. 0,
  147371. 12,
  147372. };
  147373. static long _vq_lengthlist__44u2__p7_1[] = {
  147374. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147375. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147376. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147377. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147378. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147379. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147380. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147381. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147382. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147383. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147384. 14,14,14,17,15,17,17,17,17,
  147385. };
  147386. static float _vq_quantthresh__44u2__p7_1[] = {
  147387. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147388. 32.5, 45.5, 58.5, 71.5,
  147389. };
  147390. static long _vq_quantmap__44u2__p7_1[] = {
  147391. 11, 9, 7, 5, 3, 1, 0, 2,
  147392. 4, 6, 8, 10, 12,
  147393. };
  147394. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147395. _vq_quantthresh__44u2__p7_1,
  147396. _vq_quantmap__44u2__p7_1,
  147397. 13,
  147398. 13
  147399. };
  147400. static static_codebook _44u2__p7_1 = {
  147401. 2, 169,
  147402. _vq_lengthlist__44u2__p7_1,
  147403. 1, -523010048, 1618608128, 4, 0,
  147404. _vq_quantlist__44u2__p7_1,
  147405. NULL,
  147406. &_vq_auxt__44u2__p7_1,
  147407. NULL,
  147408. 0
  147409. };
  147410. static long _vq_quantlist__44u2__p7_2[] = {
  147411. 6,
  147412. 5,
  147413. 7,
  147414. 4,
  147415. 8,
  147416. 3,
  147417. 9,
  147418. 2,
  147419. 10,
  147420. 1,
  147421. 11,
  147422. 0,
  147423. 12,
  147424. };
  147425. static long _vq_lengthlist__44u2__p7_2[] = {
  147426. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147427. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147428. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147429. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147430. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147431. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147432. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147433. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147434. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147435. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147436. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147437. };
  147438. static float _vq_quantthresh__44u2__p7_2[] = {
  147439. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147440. 2.5, 3.5, 4.5, 5.5,
  147441. };
  147442. static long _vq_quantmap__44u2__p7_2[] = {
  147443. 11, 9, 7, 5, 3, 1, 0, 2,
  147444. 4, 6, 8, 10, 12,
  147445. };
  147446. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147447. _vq_quantthresh__44u2__p7_2,
  147448. _vq_quantmap__44u2__p7_2,
  147449. 13,
  147450. 13
  147451. };
  147452. static static_codebook _44u2__p7_2 = {
  147453. 2, 169,
  147454. _vq_lengthlist__44u2__p7_2,
  147455. 1, -531103744, 1611661312, 4, 0,
  147456. _vq_quantlist__44u2__p7_2,
  147457. NULL,
  147458. &_vq_auxt__44u2__p7_2,
  147459. NULL,
  147460. 0
  147461. };
  147462. static long _huff_lengthlist__44u2__short[] = {
  147463. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147464. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147465. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147466. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147467. };
  147468. static static_codebook _huff_book__44u2__short = {
  147469. 2, 64,
  147470. _huff_lengthlist__44u2__short,
  147471. 0, 0, 0, 0, 0,
  147472. NULL,
  147473. NULL,
  147474. NULL,
  147475. NULL,
  147476. 0
  147477. };
  147478. static long _huff_lengthlist__44u3__long[] = {
  147479. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147480. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147481. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147482. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147483. };
  147484. static static_codebook _huff_book__44u3__long = {
  147485. 2, 64,
  147486. _huff_lengthlist__44u3__long,
  147487. 0, 0, 0, 0, 0,
  147488. NULL,
  147489. NULL,
  147490. NULL,
  147491. NULL,
  147492. 0
  147493. };
  147494. static long _vq_quantlist__44u3__p1_0[] = {
  147495. 1,
  147496. 0,
  147497. 2,
  147498. };
  147499. static long _vq_lengthlist__44u3__p1_0[] = {
  147500. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147501. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147502. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  147503. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147504. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  147505. 13,
  147506. };
  147507. static float _vq_quantthresh__44u3__p1_0[] = {
  147508. -0.5, 0.5,
  147509. };
  147510. static long _vq_quantmap__44u3__p1_0[] = {
  147511. 1, 0, 2,
  147512. };
  147513. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  147514. _vq_quantthresh__44u3__p1_0,
  147515. _vq_quantmap__44u3__p1_0,
  147516. 3,
  147517. 3
  147518. };
  147519. static static_codebook _44u3__p1_0 = {
  147520. 4, 81,
  147521. _vq_lengthlist__44u3__p1_0,
  147522. 1, -535822336, 1611661312, 2, 0,
  147523. _vq_quantlist__44u3__p1_0,
  147524. NULL,
  147525. &_vq_auxt__44u3__p1_0,
  147526. NULL,
  147527. 0
  147528. };
  147529. static long _vq_quantlist__44u3__p2_0[] = {
  147530. 1,
  147531. 0,
  147532. 2,
  147533. };
  147534. static long _vq_lengthlist__44u3__p2_0[] = {
  147535. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147536. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  147537. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147538. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147539. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  147540. 9,
  147541. };
  147542. static float _vq_quantthresh__44u3__p2_0[] = {
  147543. -0.5, 0.5,
  147544. };
  147545. static long _vq_quantmap__44u3__p2_0[] = {
  147546. 1, 0, 2,
  147547. };
  147548. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  147549. _vq_quantthresh__44u3__p2_0,
  147550. _vq_quantmap__44u3__p2_0,
  147551. 3,
  147552. 3
  147553. };
  147554. static static_codebook _44u3__p2_0 = {
  147555. 4, 81,
  147556. _vq_lengthlist__44u3__p2_0,
  147557. 1, -535822336, 1611661312, 2, 0,
  147558. _vq_quantlist__44u3__p2_0,
  147559. NULL,
  147560. &_vq_auxt__44u3__p2_0,
  147561. NULL,
  147562. 0
  147563. };
  147564. static long _vq_quantlist__44u3__p3_0[] = {
  147565. 2,
  147566. 1,
  147567. 3,
  147568. 0,
  147569. 4,
  147570. };
  147571. static long _vq_lengthlist__44u3__p3_0[] = {
  147572. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147573. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147574. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147575. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147576. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  147577. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  147578. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  147579. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  147580. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147581. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147582. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  147583. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147584. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  147585. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  147586. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  147587. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  147588. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  147589. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  147590. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  147591. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  147592. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  147593. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  147594. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  147595. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  147596. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  147597. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  147598. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  147599. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  147600. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  147601. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  147602. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  147603. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  147604. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  147605. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  147606. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  147607. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  147608. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  147609. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  147610. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  147611. 0,
  147612. };
  147613. static float _vq_quantthresh__44u3__p3_0[] = {
  147614. -1.5, -0.5, 0.5, 1.5,
  147615. };
  147616. static long _vq_quantmap__44u3__p3_0[] = {
  147617. 3, 1, 0, 2, 4,
  147618. };
  147619. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  147620. _vq_quantthresh__44u3__p3_0,
  147621. _vq_quantmap__44u3__p3_0,
  147622. 5,
  147623. 5
  147624. };
  147625. static static_codebook _44u3__p3_0 = {
  147626. 4, 625,
  147627. _vq_lengthlist__44u3__p3_0,
  147628. 1, -533725184, 1611661312, 3, 0,
  147629. _vq_quantlist__44u3__p3_0,
  147630. NULL,
  147631. &_vq_auxt__44u3__p3_0,
  147632. NULL,
  147633. 0
  147634. };
  147635. static long _vq_quantlist__44u3__p4_0[] = {
  147636. 2,
  147637. 1,
  147638. 3,
  147639. 0,
  147640. 4,
  147641. };
  147642. static long _vq_lengthlist__44u3__p4_0[] = {
  147643. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147644. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147645. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147646. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147647. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147648. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147649. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  147650. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  147651. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147652. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147653. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147654. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147655. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147656. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  147657. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147658. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147659. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147660. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147661. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147662. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  147663. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147664. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147665. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  147666. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147667. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  147668. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  147669. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  147670. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  147671. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147672. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  147673. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  147674. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147675. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147676. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147677. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  147678. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  147679. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  147680. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  147681. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  147682. 13,
  147683. };
  147684. static float _vq_quantthresh__44u3__p4_0[] = {
  147685. -1.5, -0.5, 0.5, 1.5,
  147686. };
  147687. static long _vq_quantmap__44u3__p4_0[] = {
  147688. 3, 1, 0, 2, 4,
  147689. };
  147690. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  147691. _vq_quantthresh__44u3__p4_0,
  147692. _vq_quantmap__44u3__p4_0,
  147693. 5,
  147694. 5
  147695. };
  147696. static static_codebook _44u3__p4_0 = {
  147697. 4, 625,
  147698. _vq_lengthlist__44u3__p4_0,
  147699. 1, -533725184, 1611661312, 3, 0,
  147700. _vq_quantlist__44u3__p4_0,
  147701. NULL,
  147702. &_vq_auxt__44u3__p4_0,
  147703. NULL,
  147704. 0
  147705. };
  147706. static long _vq_quantlist__44u3__p5_0[] = {
  147707. 4,
  147708. 3,
  147709. 5,
  147710. 2,
  147711. 6,
  147712. 1,
  147713. 7,
  147714. 0,
  147715. 8,
  147716. };
  147717. static long _vq_lengthlist__44u3__p5_0[] = {
  147718. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147719. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147720. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  147721. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147722. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  147723. 12,
  147724. };
  147725. static float _vq_quantthresh__44u3__p5_0[] = {
  147726. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147727. };
  147728. static long _vq_quantmap__44u3__p5_0[] = {
  147729. 7, 5, 3, 1, 0, 2, 4, 6,
  147730. 8,
  147731. };
  147732. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  147733. _vq_quantthresh__44u3__p5_0,
  147734. _vq_quantmap__44u3__p5_0,
  147735. 9,
  147736. 9
  147737. };
  147738. static static_codebook _44u3__p5_0 = {
  147739. 2, 81,
  147740. _vq_lengthlist__44u3__p5_0,
  147741. 1, -531628032, 1611661312, 4, 0,
  147742. _vq_quantlist__44u3__p5_0,
  147743. NULL,
  147744. &_vq_auxt__44u3__p5_0,
  147745. NULL,
  147746. 0
  147747. };
  147748. static long _vq_quantlist__44u3__p6_0[] = {
  147749. 6,
  147750. 5,
  147751. 7,
  147752. 4,
  147753. 8,
  147754. 3,
  147755. 9,
  147756. 2,
  147757. 10,
  147758. 1,
  147759. 11,
  147760. 0,
  147761. 12,
  147762. };
  147763. static long _vq_lengthlist__44u3__p6_0[] = {
  147764. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  147765. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  147766. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147767. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  147768. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  147769. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  147770. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  147771. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  147772. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  147773. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  147774. 15,16,16,16,17,18,16,20,18,
  147775. };
  147776. static float _vq_quantthresh__44u3__p6_0[] = {
  147777. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147778. 12.5, 17.5, 22.5, 27.5,
  147779. };
  147780. static long _vq_quantmap__44u3__p6_0[] = {
  147781. 11, 9, 7, 5, 3, 1, 0, 2,
  147782. 4, 6, 8, 10, 12,
  147783. };
  147784. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  147785. _vq_quantthresh__44u3__p6_0,
  147786. _vq_quantmap__44u3__p6_0,
  147787. 13,
  147788. 13
  147789. };
  147790. static static_codebook _44u3__p6_0 = {
  147791. 2, 169,
  147792. _vq_lengthlist__44u3__p6_0,
  147793. 1, -526516224, 1616117760, 4, 0,
  147794. _vq_quantlist__44u3__p6_0,
  147795. NULL,
  147796. &_vq_auxt__44u3__p6_0,
  147797. NULL,
  147798. 0
  147799. };
  147800. static long _vq_quantlist__44u3__p6_1[] = {
  147801. 2,
  147802. 1,
  147803. 3,
  147804. 0,
  147805. 4,
  147806. };
  147807. static long _vq_lengthlist__44u3__p6_1[] = {
  147808. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147809. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147810. };
  147811. static float _vq_quantthresh__44u3__p6_1[] = {
  147812. -1.5, -0.5, 0.5, 1.5,
  147813. };
  147814. static long _vq_quantmap__44u3__p6_1[] = {
  147815. 3, 1, 0, 2, 4,
  147816. };
  147817. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  147818. _vq_quantthresh__44u3__p6_1,
  147819. _vq_quantmap__44u3__p6_1,
  147820. 5,
  147821. 5
  147822. };
  147823. static static_codebook _44u3__p6_1 = {
  147824. 2, 25,
  147825. _vq_lengthlist__44u3__p6_1,
  147826. 1, -533725184, 1611661312, 3, 0,
  147827. _vq_quantlist__44u3__p6_1,
  147828. NULL,
  147829. &_vq_auxt__44u3__p6_1,
  147830. NULL,
  147831. 0
  147832. };
  147833. static long _vq_quantlist__44u3__p7_0[] = {
  147834. 4,
  147835. 3,
  147836. 5,
  147837. 2,
  147838. 6,
  147839. 1,
  147840. 7,
  147841. 0,
  147842. 8,
  147843. };
  147844. static long _vq_lengthlist__44u3__p7_0[] = {
  147845. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  147846. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147847. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147848. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147849. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147850. 9,
  147851. };
  147852. static float _vq_quantthresh__44u3__p7_0[] = {
  147853. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  147854. };
  147855. static long _vq_quantmap__44u3__p7_0[] = {
  147856. 7, 5, 3, 1, 0, 2, 4, 6,
  147857. 8,
  147858. };
  147859. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  147860. _vq_quantthresh__44u3__p7_0,
  147861. _vq_quantmap__44u3__p7_0,
  147862. 9,
  147863. 9
  147864. };
  147865. static static_codebook _44u3__p7_0 = {
  147866. 2, 81,
  147867. _vq_lengthlist__44u3__p7_0,
  147868. 1, -515907584, 1627381760, 4, 0,
  147869. _vq_quantlist__44u3__p7_0,
  147870. NULL,
  147871. &_vq_auxt__44u3__p7_0,
  147872. NULL,
  147873. 0
  147874. };
  147875. static long _vq_quantlist__44u3__p7_1[] = {
  147876. 7,
  147877. 6,
  147878. 8,
  147879. 5,
  147880. 9,
  147881. 4,
  147882. 10,
  147883. 3,
  147884. 11,
  147885. 2,
  147886. 12,
  147887. 1,
  147888. 13,
  147889. 0,
  147890. 14,
  147891. };
  147892. static long _vq_lengthlist__44u3__p7_1[] = {
  147893. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  147894. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  147895. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  147896. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  147897. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  147898. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  147899. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  147900. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  147901. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  147902. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  147903. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  147904. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  147905. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  147906. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  147907. 17,
  147908. };
  147909. static float _vq_quantthresh__44u3__p7_1[] = {
  147910. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  147911. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  147912. };
  147913. static long _vq_quantmap__44u3__p7_1[] = {
  147914. 13, 11, 9, 7, 5, 3, 1, 0,
  147915. 2, 4, 6, 8, 10, 12, 14,
  147916. };
  147917. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  147918. _vq_quantthresh__44u3__p7_1,
  147919. _vq_quantmap__44u3__p7_1,
  147920. 15,
  147921. 15
  147922. };
  147923. static static_codebook _44u3__p7_1 = {
  147924. 2, 225,
  147925. _vq_lengthlist__44u3__p7_1,
  147926. 1, -522338304, 1620115456, 4, 0,
  147927. _vq_quantlist__44u3__p7_1,
  147928. NULL,
  147929. &_vq_auxt__44u3__p7_1,
  147930. NULL,
  147931. 0
  147932. };
  147933. static long _vq_quantlist__44u3__p7_2[] = {
  147934. 8,
  147935. 7,
  147936. 9,
  147937. 6,
  147938. 10,
  147939. 5,
  147940. 11,
  147941. 4,
  147942. 12,
  147943. 3,
  147944. 13,
  147945. 2,
  147946. 14,
  147947. 1,
  147948. 15,
  147949. 0,
  147950. 16,
  147951. };
  147952. static long _vq_lengthlist__44u3__p7_2[] = {
  147953. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147954. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147955. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  147956. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147957. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  147958. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147959. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  147960. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147961. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  147962. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  147963. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  147964. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  147965. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  147966. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147967. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  147968. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  147969. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147970. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  147971. 11,
  147972. };
  147973. static float _vq_quantthresh__44u3__p7_2[] = {
  147974. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147975. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147976. };
  147977. static long _vq_quantmap__44u3__p7_2[] = {
  147978. 15, 13, 11, 9, 7, 5, 3, 1,
  147979. 0, 2, 4, 6, 8, 10, 12, 14,
  147980. 16,
  147981. };
  147982. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  147983. _vq_quantthresh__44u3__p7_2,
  147984. _vq_quantmap__44u3__p7_2,
  147985. 17,
  147986. 17
  147987. };
  147988. static static_codebook _44u3__p7_2 = {
  147989. 2, 289,
  147990. _vq_lengthlist__44u3__p7_2,
  147991. 1, -529530880, 1611661312, 5, 0,
  147992. _vq_quantlist__44u3__p7_2,
  147993. NULL,
  147994. &_vq_auxt__44u3__p7_2,
  147995. NULL,
  147996. 0
  147997. };
  147998. static long _huff_lengthlist__44u3__short[] = {
  147999. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  148000. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  148001. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  148002. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  148003. };
  148004. static static_codebook _huff_book__44u3__short = {
  148005. 2, 64,
  148006. _huff_lengthlist__44u3__short,
  148007. 0, 0, 0, 0, 0,
  148008. NULL,
  148009. NULL,
  148010. NULL,
  148011. NULL,
  148012. 0
  148013. };
  148014. static long _huff_lengthlist__44u4__long[] = {
  148015. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  148016. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  148017. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  148018. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148019. };
  148020. static static_codebook _huff_book__44u4__long = {
  148021. 2, 64,
  148022. _huff_lengthlist__44u4__long,
  148023. 0, 0, 0, 0, 0,
  148024. NULL,
  148025. NULL,
  148026. NULL,
  148027. NULL,
  148028. 0
  148029. };
  148030. static long _vq_quantlist__44u4__p1_0[] = {
  148031. 1,
  148032. 0,
  148033. 2,
  148034. };
  148035. static long _vq_lengthlist__44u4__p1_0[] = {
  148036. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148037. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148038. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148039. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148040. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148041. 13,
  148042. };
  148043. static float _vq_quantthresh__44u4__p1_0[] = {
  148044. -0.5, 0.5,
  148045. };
  148046. static long _vq_quantmap__44u4__p1_0[] = {
  148047. 1, 0, 2,
  148048. };
  148049. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148050. _vq_quantthresh__44u4__p1_0,
  148051. _vq_quantmap__44u4__p1_0,
  148052. 3,
  148053. 3
  148054. };
  148055. static static_codebook _44u4__p1_0 = {
  148056. 4, 81,
  148057. _vq_lengthlist__44u4__p1_0,
  148058. 1, -535822336, 1611661312, 2, 0,
  148059. _vq_quantlist__44u4__p1_0,
  148060. NULL,
  148061. &_vq_auxt__44u4__p1_0,
  148062. NULL,
  148063. 0
  148064. };
  148065. static long _vq_quantlist__44u4__p2_0[] = {
  148066. 1,
  148067. 0,
  148068. 2,
  148069. };
  148070. static long _vq_lengthlist__44u4__p2_0[] = {
  148071. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148072. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148073. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148074. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148075. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148076. 9,
  148077. };
  148078. static float _vq_quantthresh__44u4__p2_0[] = {
  148079. -0.5, 0.5,
  148080. };
  148081. static long _vq_quantmap__44u4__p2_0[] = {
  148082. 1, 0, 2,
  148083. };
  148084. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148085. _vq_quantthresh__44u4__p2_0,
  148086. _vq_quantmap__44u4__p2_0,
  148087. 3,
  148088. 3
  148089. };
  148090. static static_codebook _44u4__p2_0 = {
  148091. 4, 81,
  148092. _vq_lengthlist__44u4__p2_0,
  148093. 1, -535822336, 1611661312, 2, 0,
  148094. _vq_quantlist__44u4__p2_0,
  148095. NULL,
  148096. &_vq_auxt__44u4__p2_0,
  148097. NULL,
  148098. 0
  148099. };
  148100. static long _vq_quantlist__44u4__p3_0[] = {
  148101. 2,
  148102. 1,
  148103. 3,
  148104. 0,
  148105. 4,
  148106. };
  148107. static long _vq_lengthlist__44u4__p3_0[] = {
  148108. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148109. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148110. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148111. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148112. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148113. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148114. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148115. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148116. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148117. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148118. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148119. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148120. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148121. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148122. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148123. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148124. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148125. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148126. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148127. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148128. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148129. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148130. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148131. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148132. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148133. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148134. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148135. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148136. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148137. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148138. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148139. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148140. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148141. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148142. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148143. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148144. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148145. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148146. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148147. 0,
  148148. };
  148149. static float _vq_quantthresh__44u4__p3_0[] = {
  148150. -1.5, -0.5, 0.5, 1.5,
  148151. };
  148152. static long _vq_quantmap__44u4__p3_0[] = {
  148153. 3, 1, 0, 2, 4,
  148154. };
  148155. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148156. _vq_quantthresh__44u4__p3_0,
  148157. _vq_quantmap__44u4__p3_0,
  148158. 5,
  148159. 5
  148160. };
  148161. static static_codebook _44u4__p3_0 = {
  148162. 4, 625,
  148163. _vq_lengthlist__44u4__p3_0,
  148164. 1, -533725184, 1611661312, 3, 0,
  148165. _vq_quantlist__44u4__p3_0,
  148166. NULL,
  148167. &_vq_auxt__44u4__p3_0,
  148168. NULL,
  148169. 0
  148170. };
  148171. static long _vq_quantlist__44u4__p4_0[] = {
  148172. 2,
  148173. 1,
  148174. 3,
  148175. 0,
  148176. 4,
  148177. };
  148178. static long _vq_lengthlist__44u4__p4_0[] = {
  148179. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148180. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148181. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148182. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148183. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148184. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148185. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148186. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148187. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148188. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148189. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148190. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148191. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148192. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148193. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148194. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148195. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148196. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148197. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148198. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148199. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148200. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148201. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148202. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148203. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148204. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148205. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148206. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148207. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148208. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148209. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148210. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148211. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148212. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148213. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148214. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148215. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148216. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148217. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148218. 13,
  148219. };
  148220. static float _vq_quantthresh__44u4__p4_0[] = {
  148221. -1.5, -0.5, 0.5, 1.5,
  148222. };
  148223. static long _vq_quantmap__44u4__p4_0[] = {
  148224. 3, 1, 0, 2, 4,
  148225. };
  148226. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148227. _vq_quantthresh__44u4__p4_0,
  148228. _vq_quantmap__44u4__p4_0,
  148229. 5,
  148230. 5
  148231. };
  148232. static static_codebook _44u4__p4_0 = {
  148233. 4, 625,
  148234. _vq_lengthlist__44u4__p4_0,
  148235. 1, -533725184, 1611661312, 3, 0,
  148236. _vq_quantlist__44u4__p4_0,
  148237. NULL,
  148238. &_vq_auxt__44u4__p4_0,
  148239. NULL,
  148240. 0
  148241. };
  148242. static long _vq_quantlist__44u4__p5_0[] = {
  148243. 4,
  148244. 3,
  148245. 5,
  148246. 2,
  148247. 6,
  148248. 1,
  148249. 7,
  148250. 0,
  148251. 8,
  148252. };
  148253. static long _vq_lengthlist__44u4__p5_0[] = {
  148254. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148255. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148256. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148257. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148258. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148259. 12,
  148260. };
  148261. static float _vq_quantthresh__44u4__p5_0[] = {
  148262. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148263. };
  148264. static long _vq_quantmap__44u4__p5_0[] = {
  148265. 7, 5, 3, 1, 0, 2, 4, 6,
  148266. 8,
  148267. };
  148268. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148269. _vq_quantthresh__44u4__p5_0,
  148270. _vq_quantmap__44u4__p5_0,
  148271. 9,
  148272. 9
  148273. };
  148274. static static_codebook _44u4__p5_0 = {
  148275. 2, 81,
  148276. _vq_lengthlist__44u4__p5_0,
  148277. 1, -531628032, 1611661312, 4, 0,
  148278. _vq_quantlist__44u4__p5_0,
  148279. NULL,
  148280. &_vq_auxt__44u4__p5_0,
  148281. NULL,
  148282. 0
  148283. };
  148284. static long _vq_quantlist__44u4__p6_0[] = {
  148285. 6,
  148286. 5,
  148287. 7,
  148288. 4,
  148289. 8,
  148290. 3,
  148291. 9,
  148292. 2,
  148293. 10,
  148294. 1,
  148295. 11,
  148296. 0,
  148297. 12,
  148298. };
  148299. static long _vq_lengthlist__44u4__p6_0[] = {
  148300. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148301. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148302. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148303. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148304. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148305. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148306. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148307. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148308. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148309. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148310. 16,16,16,17,17,18,17,20,21,
  148311. };
  148312. static float _vq_quantthresh__44u4__p6_0[] = {
  148313. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148314. 12.5, 17.5, 22.5, 27.5,
  148315. };
  148316. static long _vq_quantmap__44u4__p6_0[] = {
  148317. 11, 9, 7, 5, 3, 1, 0, 2,
  148318. 4, 6, 8, 10, 12,
  148319. };
  148320. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148321. _vq_quantthresh__44u4__p6_0,
  148322. _vq_quantmap__44u4__p6_0,
  148323. 13,
  148324. 13
  148325. };
  148326. static static_codebook _44u4__p6_0 = {
  148327. 2, 169,
  148328. _vq_lengthlist__44u4__p6_0,
  148329. 1, -526516224, 1616117760, 4, 0,
  148330. _vq_quantlist__44u4__p6_0,
  148331. NULL,
  148332. &_vq_auxt__44u4__p6_0,
  148333. NULL,
  148334. 0
  148335. };
  148336. static long _vq_quantlist__44u4__p6_1[] = {
  148337. 2,
  148338. 1,
  148339. 3,
  148340. 0,
  148341. 4,
  148342. };
  148343. static long _vq_lengthlist__44u4__p6_1[] = {
  148344. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148345. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148346. };
  148347. static float _vq_quantthresh__44u4__p6_1[] = {
  148348. -1.5, -0.5, 0.5, 1.5,
  148349. };
  148350. static long _vq_quantmap__44u4__p6_1[] = {
  148351. 3, 1, 0, 2, 4,
  148352. };
  148353. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148354. _vq_quantthresh__44u4__p6_1,
  148355. _vq_quantmap__44u4__p6_1,
  148356. 5,
  148357. 5
  148358. };
  148359. static static_codebook _44u4__p6_1 = {
  148360. 2, 25,
  148361. _vq_lengthlist__44u4__p6_1,
  148362. 1, -533725184, 1611661312, 3, 0,
  148363. _vq_quantlist__44u4__p6_1,
  148364. NULL,
  148365. &_vq_auxt__44u4__p6_1,
  148366. NULL,
  148367. 0
  148368. };
  148369. static long _vq_quantlist__44u4__p7_0[] = {
  148370. 6,
  148371. 5,
  148372. 7,
  148373. 4,
  148374. 8,
  148375. 3,
  148376. 9,
  148377. 2,
  148378. 10,
  148379. 1,
  148380. 11,
  148381. 0,
  148382. 12,
  148383. };
  148384. static long _vq_lengthlist__44u4__p7_0[] = {
  148385. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148386. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148387. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148388. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148389. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148390. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148391. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148392. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148393. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148394. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148395. 11,11,11,11,11,11,11,11,11,
  148396. };
  148397. static float _vq_quantthresh__44u4__p7_0[] = {
  148398. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148399. 637.5, 892.5, 1147.5, 1402.5,
  148400. };
  148401. static long _vq_quantmap__44u4__p7_0[] = {
  148402. 11, 9, 7, 5, 3, 1, 0, 2,
  148403. 4, 6, 8, 10, 12,
  148404. };
  148405. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148406. _vq_quantthresh__44u4__p7_0,
  148407. _vq_quantmap__44u4__p7_0,
  148408. 13,
  148409. 13
  148410. };
  148411. static static_codebook _44u4__p7_0 = {
  148412. 2, 169,
  148413. _vq_lengthlist__44u4__p7_0,
  148414. 1, -514332672, 1627381760, 4, 0,
  148415. _vq_quantlist__44u4__p7_0,
  148416. NULL,
  148417. &_vq_auxt__44u4__p7_0,
  148418. NULL,
  148419. 0
  148420. };
  148421. static long _vq_quantlist__44u4__p7_1[] = {
  148422. 7,
  148423. 6,
  148424. 8,
  148425. 5,
  148426. 9,
  148427. 4,
  148428. 10,
  148429. 3,
  148430. 11,
  148431. 2,
  148432. 12,
  148433. 1,
  148434. 13,
  148435. 0,
  148436. 14,
  148437. };
  148438. static long _vq_lengthlist__44u4__p7_1[] = {
  148439. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148440. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148441. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148442. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148443. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148444. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148445. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148446. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148447. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148448. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148449. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148450. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148451. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148452. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148453. 16,
  148454. };
  148455. static float _vq_quantthresh__44u4__p7_1[] = {
  148456. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148457. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148458. };
  148459. static long _vq_quantmap__44u4__p7_1[] = {
  148460. 13, 11, 9, 7, 5, 3, 1, 0,
  148461. 2, 4, 6, 8, 10, 12, 14,
  148462. };
  148463. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148464. _vq_quantthresh__44u4__p7_1,
  148465. _vq_quantmap__44u4__p7_1,
  148466. 15,
  148467. 15
  148468. };
  148469. static static_codebook _44u4__p7_1 = {
  148470. 2, 225,
  148471. _vq_lengthlist__44u4__p7_1,
  148472. 1, -522338304, 1620115456, 4, 0,
  148473. _vq_quantlist__44u4__p7_1,
  148474. NULL,
  148475. &_vq_auxt__44u4__p7_1,
  148476. NULL,
  148477. 0
  148478. };
  148479. static long _vq_quantlist__44u4__p7_2[] = {
  148480. 8,
  148481. 7,
  148482. 9,
  148483. 6,
  148484. 10,
  148485. 5,
  148486. 11,
  148487. 4,
  148488. 12,
  148489. 3,
  148490. 13,
  148491. 2,
  148492. 14,
  148493. 1,
  148494. 15,
  148495. 0,
  148496. 16,
  148497. };
  148498. static long _vq_lengthlist__44u4__p7_2[] = {
  148499. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148500. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148501. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148502. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148503. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148504. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148505. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148506. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148507. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148508. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  148509. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148510. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  148511. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148512. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  148513. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148514. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148515. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148516. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  148517. 10,
  148518. };
  148519. static float _vq_quantthresh__44u4__p7_2[] = {
  148520. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148521. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148522. };
  148523. static long _vq_quantmap__44u4__p7_2[] = {
  148524. 15, 13, 11, 9, 7, 5, 3, 1,
  148525. 0, 2, 4, 6, 8, 10, 12, 14,
  148526. 16,
  148527. };
  148528. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  148529. _vq_quantthresh__44u4__p7_2,
  148530. _vq_quantmap__44u4__p7_2,
  148531. 17,
  148532. 17
  148533. };
  148534. static static_codebook _44u4__p7_2 = {
  148535. 2, 289,
  148536. _vq_lengthlist__44u4__p7_2,
  148537. 1, -529530880, 1611661312, 5, 0,
  148538. _vq_quantlist__44u4__p7_2,
  148539. NULL,
  148540. &_vq_auxt__44u4__p7_2,
  148541. NULL,
  148542. 0
  148543. };
  148544. static long _huff_lengthlist__44u4__short[] = {
  148545. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  148546. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  148547. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  148548. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  148549. };
  148550. static static_codebook _huff_book__44u4__short = {
  148551. 2, 64,
  148552. _huff_lengthlist__44u4__short,
  148553. 0, 0, 0, 0, 0,
  148554. NULL,
  148555. NULL,
  148556. NULL,
  148557. NULL,
  148558. 0
  148559. };
  148560. static long _huff_lengthlist__44u5__long[] = {
  148561. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  148562. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  148563. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  148564. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  148565. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  148566. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  148567. 14, 8, 7, 8,
  148568. };
  148569. static static_codebook _huff_book__44u5__long = {
  148570. 2, 100,
  148571. _huff_lengthlist__44u5__long,
  148572. 0, 0, 0, 0, 0,
  148573. NULL,
  148574. NULL,
  148575. NULL,
  148576. NULL,
  148577. 0
  148578. };
  148579. static long _vq_quantlist__44u5__p1_0[] = {
  148580. 1,
  148581. 0,
  148582. 2,
  148583. };
  148584. static long _vq_lengthlist__44u5__p1_0[] = {
  148585. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148586. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148587. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148588. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  148589. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148590. 12,
  148591. };
  148592. static float _vq_quantthresh__44u5__p1_0[] = {
  148593. -0.5, 0.5,
  148594. };
  148595. static long _vq_quantmap__44u5__p1_0[] = {
  148596. 1, 0, 2,
  148597. };
  148598. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  148599. _vq_quantthresh__44u5__p1_0,
  148600. _vq_quantmap__44u5__p1_0,
  148601. 3,
  148602. 3
  148603. };
  148604. static static_codebook _44u5__p1_0 = {
  148605. 4, 81,
  148606. _vq_lengthlist__44u5__p1_0,
  148607. 1, -535822336, 1611661312, 2, 0,
  148608. _vq_quantlist__44u5__p1_0,
  148609. NULL,
  148610. &_vq_auxt__44u5__p1_0,
  148611. NULL,
  148612. 0
  148613. };
  148614. static long _vq_quantlist__44u5__p2_0[] = {
  148615. 1,
  148616. 0,
  148617. 2,
  148618. };
  148619. static long _vq_lengthlist__44u5__p2_0[] = {
  148620. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148621. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148622. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  148623. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148624. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148625. 9,
  148626. };
  148627. static float _vq_quantthresh__44u5__p2_0[] = {
  148628. -0.5, 0.5,
  148629. };
  148630. static long _vq_quantmap__44u5__p2_0[] = {
  148631. 1, 0, 2,
  148632. };
  148633. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  148634. _vq_quantthresh__44u5__p2_0,
  148635. _vq_quantmap__44u5__p2_0,
  148636. 3,
  148637. 3
  148638. };
  148639. static static_codebook _44u5__p2_0 = {
  148640. 4, 81,
  148641. _vq_lengthlist__44u5__p2_0,
  148642. 1, -535822336, 1611661312, 2, 0,
  148643. _vq_quantlist__44u5__p2_0,
  148644. NULL,
  148645. &_vq_auxt__44u5__p2_0,
  148646. NULL,
  148647. 0
  148648. };
  148649. static long _vq_quantlist__44u5__p3_0[] = {
  148650. 2,
  148651. 1,
  148652. 3,
  148653. 0,
  148654. 4,
  148655. };
  148656. static long _vq_lengthlist__44u5__p3_0[] = {
  148657. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148658. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148659. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148660. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  148661. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  148662. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  148663. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  148664. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  148665. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  148666. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148667. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  148668. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148669. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  148670. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  148671. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  148672. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  148673. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148674. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  148675. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  148676. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  148677. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  148678. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  148679. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  148680. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  148681. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  148682. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  148683. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  148684. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  148685. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  148686. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  148687. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  148688. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  148689. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  148690. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  148691. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  148692. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  148693. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  148694. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  148695. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  148696. 0,
  148697. };
  148698. static float _vq_quantthresh__44u5__p3_0[] = {
  148699. -1.5, -0.5, 0.5, 1.5,
  148700. };
  148701. static long _vq_quantmap__44u5__p3_0[] = {
  148702. 3, 1, 0, 2, 4,
  148703. };
  148704. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  148705. _vq_quantthresh__44u5__p3_0,
  148706. _vq_quantmap__44u5__p3_0,
  148707. 5,
  148708. 5
  148709. };
  148710. static static_codebook _44u5__p3_0 = {
  148711. 4, 625,
  148712. _vq_lengthlist__44u5__p3_0,
  148713. 1, -533725184, 1611661312, 3, 0,
  148714. _vq_quantlist__44u5__p3_0,
  148715. NULL,
  148716. &_vq_auxt__44u5__p3_0,
  148717. NULL,
  148718. 0
  148719. };
  148720. static long _vq_quantlist__44u5__p4_0[] = {
  148721. 2,
  148722. 1,
  148723. 3,
  148724. 0,
  148725. 4,
  148726. };
  148727. static long _vq_lengthlist__44u5__p4_0[] = {
  148728. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  148729. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148730. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  148731. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  148732. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  148733. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  148734. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148735. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  148736. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  148737. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  148738. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  148739. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148740. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  148741. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  148742. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  148743. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  148744. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  148745. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148746. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  148747. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  148748. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  148749. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  148750. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  148751. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  148752. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  148753. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  148754. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  148755. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  148756. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  148757. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  148758. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  148759. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148760. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  148761. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  148762. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  148763. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  148764. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  148765. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  148766. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  148767. 12,
  148768. };
  148769. static float _vq_quantthresh__44u5__p4_0[] = {
  148770. -1.5, -0.5, 0.5, 1.5,
  148771. };
  148772. static long _vq_quantmap__44u5__p4_0[] = {
  148773. 3, 1, 0, 2, 4,
  148774. };
  148775. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  148776. _vq_quantthresh__44u5__p4_0,
  148777. _vq_quantmap__44u5__p4_0,
  148778. 5,
  148779. 5
  148780. };
  148781. static static_codebook _44u5__p4_0 = {
  148782. 4, 625,
  148783. _vq_lengthlist__44u5__p4_0,
  148784. 1, -533725184, 1611661312, 3, 0,
  148785. _vq_quantlist__44u5__p4_0,
  148786. NULL,
  148787. &_vq_auxt__44u5__p4_0,
  148788. NULL,
  148789. 0
  148790. };
  148791. static long _vq_quantlist__44u5__p5_0[] = {
  148792. 4,
  148793. 3,
  148794. 5,
  148795. 2,
  148796. 6,
  148797. 1,
  148798. 7,
  148799. 0,
  148800. 8,
  148801. };
  148802. static long _vq_lengthlist__44u5__p5_0[] = {
  148803. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  148804. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  148805. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  148806. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  148807. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  148808. 14,
  148809. };
  148810. static float _vq_quantthresh__44u5__p5_0[] = {
  148811. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148812. };
  148813. static long _vq_quantmap__44u5__p5_0[] = {
  148814. 7, 5, 3, 1, 0, 2, 4, 6,
  148815. 8,
  148816. };
  148817. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  148818. _vq_quantthresh__44u5__p5_0,
  148819. _vq_quantmap__44u5__p5_0,
  148820. 9,
  148821. 9
  148822. };
  148823. static static_codebook _44u5__p5_0 = {
  148824. 2, 81,
  148825. _vq_lengthlist__44u5__p5_0,
  148826. 1, -531628032, 1611661312, 4, 0,
  148827. _vq_quantlist__44u5__p5_0,
  148828. NULL,
  148829. &_vq_auxt__44u5__p5_0,
  148830. NULL,
  148831. 0
  148832. };
  148833. static long _vq_quantlist__44u5__p6_0[] = {
  148834. 4,
  148835. 3,
  148836. 5,
  148837. 2,
  148838. 6,
  148839. 1,
  148840. 7,
  148841. 0,
  148842. 8,
  148843. };
  148844. static long _vq_lengthlist__44u5__p6_0[] = {
  148845. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  148846. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  148847. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  148848. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  148849. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  148850. 11,
  148851. };
  148852. static float _vq_quantthresh__44u5__p6_0[] = {
  148853. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148854. };
  148855. static long _vq_quantmap__44u5__p6_0[] = {
  148856. 7, 5, 3, 1, 0, 2, 4, 6,
  148857. 8,
  148858. };
  148859. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  148860. _vq_quantthresh__44u5__p6_0,
  148861. _vq_quantmap__44u5__p6_0,
  148862. 9,
  148863. 9
  148864. };
  148865. static static_codebook _44u5__p6_0 = {
  148866. 2, 81,
  148867. _vq_lengthlist__44u5__p6_0,
  148868. 1, -531628032, 1611661312, 4, 0,
  148869. _vq_quantlist__44u5__p6_0,
  148870. NULL,
  148871. &_vq_auxt__44u5__p6_0,
  148872. NULL,
  148873. 0
  148874. };
  148875. static long _vq_quantlist__44u5__p7_0[] = {
  148876. 1,
  148877. 0,
  148878. 2,
  148879. };
  148880. static long _vq_lengthlist__44u5__p7_0[] = {
  148881. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  148882. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  148883. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  148884. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  148885. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  148886. 12,
  148887. };
  148888. static float _vq_quantthresh__44u5__p7_0[] = {
  148889. -5.5, 5.5,
  148890. };
  148891. static long _vq_quantmap__44u5__p7_0[] = {
  148892. 1, 0, 2,
  148893. };
  148894. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  148895. _vq_quantthresh__44u5__p7_0,
  148896. _vq_quantmap__44u5__p7_0,
  148897. 3,
  148898. 3
  148899. };
  148900. static static_codebook _44u5__p7_0 = {
  148901. 4, 81,
  148902. _vq_lengthlist__44u5__p7_0,
  148903. 1, -529137664, 1618345984, 2, 0,
  148904. _vq_quantlist__44u5__p7_0,
  148905. NULL,
  148906. &_vq_auxt__44u5__p7_0,
  148907. NULL,
  148908. 0
  148909. };
  148910. static long _vq_quantlist__44u5__p7_1[] = {
  148911. 5,
  148912. 4,
  148913. 6,
  148914. 3,
  148915. 7,
  148916. 2,
  148917. 8,
  148918. 1,
  148919. 9,
  148920. 0,
  148921. 10,
  148922. };
  148923. static long _vq_lengthlist__44u5__p7_1[] = {
  148924. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  148925. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  148926. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  148927. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  148928. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  148929. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  148930. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  148931. 9, 9, 9, 9, 9,10,10,10,10,
  148932. };
  148933. static float _vq_quantthresh__44u5__p7_1[] = {
  148934. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148935. 3.5, 4.5,
  148936. };
  148937. static long _vq_quantmap__44u5__p7_1[] = {
  148938. 9, 7, 5, 3, 1, 0, 2, 4,
  148939. 6, 8, 10,
  148940. };
  148941. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  148942. _vq_quantthresh__44u5__p7_1,
  148943. _vq_quantmap__44u5__p7_1,
  148944. 11,
  148945. 11
  148946. };
  148947. static static_codebook _44u5__p7_1 = {
  148948. 2, 121,
  148949. _vq_lengthlist__44u5__p7_1,
  148950. 1, -531365888, 1611661312, 4, 0,
  148951. _vq_quantlist__44u5__p7_1,
  148952. NULL,
  148953. &_vq_auxt__44u5__p7_1,
  148954. NULL,
  148955. 0
  148956. };
  148957. static long _vq_quantlist__44u5__p8_0[] = {
  148958. 5,
  148959. 4,
  148960. 6,
  148961. 3,
  148962. 7,
  148963. 2,
  148964. 8,
  148965. 1,
  148966. 9,
  148967. 0,
  148968. 10,
  148969. };
  148970. static long _vq_lengthlist__44u5__p8_0[] = {
  148971. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  148972. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  148973. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  148974. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  148975. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  148976. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  148977. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  148978. 12,13,13,14,14,14,14,15,15,
  148979. };
  148980. static float _vq_quantthresh__44u5__p8_0[] = {
  148981. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  148982. 38.5, 49.5,
  148983. };
  148984. static long _vq_quantmap__44u5__p8_0[] = {
  148985. 9, 7, 5, 3, 1, 0, 2, 4,
  148986. 6, 8, 10,
  148987. };
  148988. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  148989. _vq_quantthresh__44u5__p8_0,
  148990. _vq_quantmap__44u5__p8_0,
  148991. 11,
  148992. 11
  148993. };
  148994. static static_codebook _44u5__p8_0 = {
  148995. 2, 121,
  148996. _vq_lengthlist__44u5__p8_0,
  148997. 1, -524582912, 1618345984, 4, 0,
  148998. _vq_quantlist__44u5__p8_0,
  148999. NULL,
  149000. &_vq_auxt__44u5__p8_0,
  149001. NULL,
  149002. 0
  149003. };
  149004. static long _vq_quantlist__44u5__p8_1[] = {
  149005. 5,
  149006. 4,
  149007. 6,
  149008. 3,
  149009. 7,
  149010. 2,
  149011. 8,
  149012. 1,
  149013. 9,
  149014. 0,
  149015. 10,
  149016. };
  149017. static long _vq_lengthlist__44u5__p8_1[] = {
  149018. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149019. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149020. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149021. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149022. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149023. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149024. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149025. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149026. };
  149027. static float _vq_quantthresh__44u5__p8_1[] = {
  149028. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149029. 3.5, 4.5,
  149030. };
  149031. static long _vq_quantmap__44u5__p8_1[] = {
  149032. 9, 7, 5, 3, 1, 0, 2, 4,
  149033. 6, 8, 10,
  149034. };
  149035. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149036. _vq_quantthresh__44u5__p8_1,
  149037. _vq_quantmap__44u5__p8_1,
  149038. 11,
  149039. 11
  149040. };
  149041. static static_codebook _44u5__p8_1 = {
  149042. 2, 121,
  149043. _vq_lengthlist__44u5__p8_1,
  149044. 1, -531365888, 1611661312, 4, 0,
  149045. _vq_quantlist__44u5__p8_1,
  149046. NULL,
  149047. &_vq_auxt__44u5__p8_1,
  149048. NULL,
  149049. 0
  149050. };
  149051. static long _vq_quantlist__44u5__p9_0[] = {
  149052. 6,
  149053. 5,
  149054. 7,
  149055. 4,
  149056. 8,
  149057. 3,
  149058. 9,
  149059. 2,
  149060. 10,
  149061. 1,
  149062. 11,
  149063. 0,
  149064. 12,
  149065. };
  149066. static long _vq_lengthlist__44u5__p9_0[] = {
  149067. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149068. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149069. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149070. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149071. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149072. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149073. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149074. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149075. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149076. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149077. 12,12,12,12,12,12,12,12,12,
  149078. };
  149079. static float _vq_quantthresh__44u5__p9_0[] = {
  149080. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149081. 637.5, 892.5, 1147.5, 1402.5,
  149082. };
  149083. static long _vq_quantmap__44u5__p9_0[] = {
  149084. 11, 9, 7, 5, 3, 1, 0, 2,
  149085. 4, 6, 8, 10, 12,
  149086. };
  149087. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149088. _vq_quantthresh__44u5__p9_0,
  149089. _vq_quantmap__44u5__p9_0,
  149090. 13,
  149091. 13
  149092. };
  149093. static static_codebook _44u5__p9_0 = {
  149094. 2, 169,
  149095. _vq_lengthlist__44u5__p9_0,
  149096. 1, -514332672, 1627381760, 4, 0,
  149097. _vq_quantlist__44u5__p9_0,
  149098. NULL,
  149099. &_vq_auxt__44u5__p9_0,
  149100. NULL,
  149101. 0
  149102. };
  149103. static long _vq_quantlist__44u5__p9_1[] = {
  149104. 7,
  149105. 6,
  149106. 8,
  149107. 5,
  149108. 9,
  149109. 4,
  149110. 10,
  149111. 3,
  149112. 11,
  149113. 2,
  149114. 12,
  149115. 1,
  149116. 13,
  149117. 0,
  149118. 14,
  149119. };
  149120. static long _vq_lengthlist__44u5__p9_1[] = {
  149121. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149122. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149123. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149124. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149125. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149126. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149127. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149128. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149129. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149130. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149131. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149132. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149133. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149134. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149135. 14,
  149136. };
  149137. static float _vq_quantthresh__44u5__p9_1[] = {
  149138. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149139. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149140. };
  149141. static long _vq_quantmap__44u5__p9_1[] = {
  149142. 13, 11, 9, 7, 5, 3, 1, 0,
  149143. 2, 4, 6, 8, 10, 12, 14,
  149144. };
  149145. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149146. _vq_quantthresh__44u5__p9_1,
  149147. _vq_quantmap__44u5__p9_1,
  149148. 15,
  149149. 15
  149150. };
  149151. static static_codebook _44u5__p9_1 = {
  149152. 2, 225,
  149153. _vq_lengthlist__44u5__p9_1,
  149154. 1, -522338304, 1620115456, 4, 0,
  149155. _vq_quantlist__44u5__p9_1,
  149156. NULL,
  149157. &_vq_auxt__44u5__p9_1,
  149158. NULL,
  149159. 0
  149160. };
  149161. static long _vq_quantlist__44u5__p9_2[] = {
  149162. 8,
  149163. 7,
  149164. 9,
  149165. 6,
  149166. 10,
  149167. 5,
  149168. 11,
  149169. 4,
  149170. 12,
  149171. 3,
  149172. 13,
  149173. 2,
  149174. 14,
  149175. 1,
  149176. 15,
  149177. 0,
  149178. 16,
  149179. };
  149180. static long _vq_lengthlist__44u5__p9_2[] = {
  149181. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149182. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149183. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149184. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149185. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149186. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149187. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149188. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149189. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149190. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149191. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149192. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149193. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149194. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149195. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149196. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149197. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149198. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149199. 10,
  149200. };
  149201. static float _vq_quantthresh__44u5__p9_2[] = {
  149202. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149203. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149204. };
  149205. static long _vq_quantmap__44u5__p9_2[] = {
  149206. 15, 13, 11, 9, 7, 5, 3, 1,
  149207. 0, 2, 4, 6, 8, 10, 12, 14,
  149208. 16,
  149209. };
  149210. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149211. _vq_quantthresh__44u5__p9_2,
  149212. _vq_quantmap__44u5__p9_2,
  149213. 17,
  149214. 17
  149215. };
  149216. static static_codebook _44u5__p9_2 = {
  149217. 2, 289,
  149218. _vq_lengthlist__44u5__p9_2,
  149219. 1, -529530880, 1611661312, 5, 0,
  149220. _vq_quantlist__44u5__p9_2,
  149221. NULL,
  149222. &_vq_auxt__44u5__p9_2,
  149223. NULL,
  149224. 0
  149225. };
  149226. static long _huff_lengthlist__44u5__short[] = {
  149227. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149228. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149229. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149230. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149231. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149232. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149233. 6, 8,15,17,
  149234. };
  149235. static static_codebook _huff_book__44u5__short = {
  149236. 2, 100,
  149237. _huff_lengthlist__44u5__short,
  149238. 0, 0, 0, 0, 0,
  149239. NULL,
  149240. NULL,
  149241. NULL,
  149242. NULL,
  149243. 0
  149244. };
  149245. static long _huff_lengthlist__44u6__long[] = {
  149246. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149247. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149248. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149249. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149250. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149251. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149252. 13, 8, 7, 7,
  149253. };
  149254. static static_codebook _huff_book__44u6__long = {
  149255. 2, 100,
  149256. _huff_lengthlist__44u6__long,
  149257. 0, 0, 0, 0, 0,
  149258. NULL,
  149259. NULL,
  149260. NULL,
  149261. NULL,
  149262. 0
  149263. };
  149264. static long _vq_quantlist__44u6__p1_0[] = {
  149265. 1,
  149266. 0,
  149267. 2,
  149268. };
  149269. static long _vq_lengthlist__44u6__p1_0[] = {
  149270. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149271. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149272. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149273. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149274. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149275. 12,
  149276. };
  149277. static float _vq_quantthresh__44u6__p1_0[] = {
  149278. -0.5, 0.5,
  149279. };
  149280. static long _vq_quantmap__44u6__p1_0[] = {
  149281. 1, 0, 2,
  149282. };
  149283. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149284. _vq_quantthresh__44u6__p1_0,
  149285. _vq_quantmap__44u6__p1_0,
  149286. 3,
  149287. 3
  149288. };
  149289. static static_codebook _44u6__p1_0 = {
  149290. 4, 81,
  149291. _vq_lengthlist__44u6__p1_0,
  149292. 1, -535822336, 1611661312, 2, 0,
  149293. _vq_quantlist__44u6__p1_0,
  149294. NULL,
  149295. &_vq_auxt__44u6__p1_0,
  149296. NULL,
  149297. 0
  149298. };
  149299. static long _vq_quantlist__44u6__p2_0[] = {
  149300. 1,
  149301. 0,
  149302. 2,
  149303. };
  149304. static long _vq_lengthlist__44u6__p2_0[] = {
  149305. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149306. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149307. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149308. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149309. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149310. 9,
  149311. };
  149312. static float _vq_quantthresh__44u6__p2_0[] = {
  149313. -0.5, 0.5,
  149314. };
  149315. static long _vq_quantmap__44u6__p2_0[] = {
  149316. 1, 0, 2,
  149317. };
  149318. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149319. _vq_quantthresh__44u6__p2_0,
  149320. _vq_quantmap__44u6__p2_0,
  149321. 3,
  149322. 3
  149323. };
  149324. static static_codebook _44u6__p2_0 = {
  149325. 4, 81,
  149326. _vq_lengthlist__44u6__p2_0,
  149327. 1, -535822336, 1611661312, 2, 0,
  149328. _vq_quantlist__44u6__p2_0,
  149329. NULL,
  149330. &_vq_auxt__44u6__p2_0,
  149331. NULL,
  149332. 0
  149333. };
  149334. static long _vq_quantlist__44u6__p3_0[] = {
  149335. 2,
  149336. 1,
  149337. 3,
  149338. 0,
  149339. 4,
  149340. };
  149341. static long _vq_lengthlist__44u6__p3_0[] = {
  149342. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149343. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149344. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149345. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149346. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149347. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149348. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149349. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149350. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149351. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149352. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149353. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149354. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149355. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149356. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149357. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149358. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149359. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149360. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149361. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149362. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149363. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149364. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149365. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149366. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149367. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149368. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149369. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149370. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149371. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149372. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149373. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149374. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149375. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149376. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149377. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149378. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149379. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149380. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149381. 19,
  149382. };
  149383. static float _vq_quantthresh__44u6__p3_0[] = {
  149384. -1.5, -0.5, 0.5, 1.5,
  149385. };
  149386. static long _vq_quantmap__44u6__p3_0[] = {
  149387. 3, 1, 0, 2, 4,
  149388. };
  149389. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149390. _vq_quantthresh__44u6__p3_0,
  149391. _vq_quantmap__44u6__p3_0,
  149392. 5,
  149393. 5
  149394. };
  149395. static static_codebook _44u6__p3_0 = {
  149396. 4, 625,
  149397. _vq_lengthlist__44u6__p3_0,
  149398. 1, -533725184, 1611661312, 3, 0,
  149399. _vq_quantlist__44u6__p3_0,
  149400. NULL,
  149401. &_vq_auxt__44u6__p3_0,
  149402. NULL,
  149403. 0
  149404. };
  149405. static long _vq_quantlist__44u6__p4_0[] = {
  149406. 2,
  149407. 1,
  149408. 3,
  149409. 0,
  149410. 4,
  149411. };
  149412. static long _vq_lengthlist__44u6__p4_0[] = {
  149413. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149414. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149415. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149416. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149417. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149418. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149419. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149420. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149421. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149422. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149423. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149424. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149425. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149426. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149427. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149428. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149429. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149430. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149431. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149432. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149433. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149434. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149435. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149436. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149437. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149438. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149439. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149440. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149441. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149442. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149443. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149444. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149445. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149446. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149447. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149448. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149449. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149450. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149451. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149452. 13,
  149453. };
  149454. static float _vq_quantthresh__44u6__p4_0[] = {
  149455. -1.5, -0.5, 0.5, 1.5,
  149456. };
  149457. static long _vq_quantmap__44u6__p4_0[] = {
  149458. 3, 1, 0, 2, 4,
  149459. };
  149460. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149461. _vq_quantthresh__44u6__p4_0,
  149462. _vq_quantmap__44u6__p4_0,
  149463. 5,
  149464. 5
  149465. };
  149466. static static_codebook _44u6__p4_0 = {
  149467. 4, 625,
  149468. _vq_lengthlist__44u6__p4_0,
  149469. 1, -533725184, 1611661312, 3, 0,
  149470. _vq_quantlist__44u6__p4_0,
  149471. NULL,
  149472. &_vq_auxt__44u6__p4_0,
  149473. NULL,
  149474. 0
  149475. };
  149476. static long _vq_quantlist__44u6__p5_0[] = {
  149477. 4,
  149478. 3,
  149479. 5,
  149480. 2,
  149481. 6,
  149482. 1,
  149483. 7,
  149484. 0,
  149485. 8,
  149486. };
  149487. static long _vq_lengthlist__44u6__p5_0[] = {
  149488. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149489. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149490. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149491. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149492. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  149493. 14,
  149494. };
  149495. static float _vq_quantthresh__44u6__p5_0[] = {
  149496. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149497. };
  149498. static long _vq_quantmap__44u6__p5_0[] = {
  149499. 7, 5, 3, 1, 0, 2, 4, 6,
  149500. 8,
  149501. };
  149502. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  149503. _vq_quantthresh__44u6__p5_0,
  149504. _vq_quantmap__44u6__p5_0,
  149505. 9,
  149506. 9
  149507. };
  149508. static static_codebook _44u6__p5_0 = {
  149509. 2, 81,
  149510. _vq_lengthlist__44u6__p5_0,
  149511. 1, -531628032, 1611661312, 4, 0,
  149512. _vq_quantlist__44u6__p5_0,
  149513. NULL,
  149514. &_vq_auxt__44u6__p5_0,
  149515. NULL,
  149516. 0
  149517. };
  149518. static long _vq_quantlist__44u6__p6_0[] = {
  149519. 4,
  149520. 3,
  149521. 5,
  149522. 2,
  149523. 6,
  149524. 1,
  149525. 7,
  149526. 0,
  149527. 8,
  149528. };
  149529. static long _vq_lengthlist__44u6__p6_0[] = {
  149530. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149531. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  149532. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149533. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  149534. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  149535. 12,
  149536. };
  149537. static float _vq_quantthresh__44u6__p6_0[] = {
  149538. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149539. };
  149540. static long _vq_quantmap__44u6__p6_0[] = {
  149541. 7, 5, 3, 1, 0, 2, 4, 6,
  149542. 8,
  149543. };
  149544. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  149545. _vq_quantthresh__44u6__p6_0,
  149546. _vq_quantmap__44u6__p6_0,
  149547. 9,
  149548. 9
  149549. };
  149550. static static_codebook _44u6__p6_0 = {
  149551. 2, 81,
  149552. _vq_lengthlist__44u6__p6_0,
  149553. 1, -531628032, 1611661312, 4, 0,
  149554. _vq_quantlist__44u6__p6_0,
  149555. NULL,
  149556. &_vq_auxt__44u6__p6_0,
  149557. NULL,
  149558. 0
  149559. };
  149560. static long _vq_quantlist__44u6__p7_0[] = {
  149561. 1,
  149562. 0,
  149563. 2,
  149564. };
  149565. static long _vq_lengthlist__44u6__p7_0[] = {
  149566. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  149567. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  149568. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  149569. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  149570. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  149571. 10,
  149572. };
  149573. static float _vq_quantthresh__44u6__p7_0[] = {
  149574. -5.5, 5.5,
  149575. };
  149576. static long _vq_quantmap__44u6__p7_0[] = {
  149577. 1, 0, 2,
  149578. };
  149579. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  149580. _vq_quantthresh__44u6__p7_0,
  149581. _vq_quantmap__44u6__p7_0,
  149582. 3,
  149583. 3
  149584. };
  149585. static static_codebook _44u6__p7_0 = {
  149586. 4, 81,
  149587. _vq_lengthlist__44u6__p7_0,
  149588. 1, -529137664, 1618345984, 2, 0,
  149589. _vq_quantlist__44u6__p7_0,
  149590. NULL,
  149591. &_vq_auxt__44u6__p7_0,
  149592. NULL,
  149593. 0
  149594. };
  149595. static long _vq_quantlist__44u6__p7_1[] = {
  149596. 5,
  149597. 4,
  149598. 6,
  149599. 3,
  149600. 7,
  149601. 2,
  149602. 8,
  149603. 1,
  149604. 9,
  149605. 0,
  149606. 10,
  149607. };
  149608. static long _vq_lengthlist__44u6__p7_1[] = {
  149609. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  149610. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  149611. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  149612. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  149613. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  149614. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  149615. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  149616. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149617. };
  149618. static float _vq_quantthresh__44u6__p7_1[] = {
  149619. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149620. 3.5, 4.5,
  149621. };
  149622. static long _vq_quantmap__44u6__p7_1[] = {
  149623. 9, 7, 5, 3, 1, 0, 2, 4,
  149624. 6, 8, 10,
  149625. };
  149626. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  149627. _vq_quantthresh__44u6__p7_1,
  149628. _vq_quantmap__44u6__p7_1,
  149629. 11,
  149630. 11
  149631. };
  149632. static static_codebook _44u6__p7_1 = {
  149633. 2, 121,
  149634. _vq_lengthlist__44u6__p7_1,
  149635. 1, -531365888, 1611661312, 4, 0,
  149636. _vq_quantlist__44u6__p7_1,
  149637. NULL,
  149638. &_vq_auxt__44u6__p7_1,
  149639. NULL,
  149640. 0
  149641. };
  149642. static long _vq_quantlist__44u6__p8_0[] = {
  149643. 5,
  149644. 4,
  149645. 6,
  149646. 3,
  149647. 7,
  149648. 2,
  149649. 8,
  149650. 1,
  149651. 9,
  149652. 0,
  149653. 10,
  149654. };
  149655. static long _vq_lengthlist__44u6__p8_0[] = {
  149656. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149657. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149658. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  149659. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  149660. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  149661. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  149662. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  149663. 12,13,13,14,14,14,15,15,15,
  149664. };
  149665. static float _vq_quantthresh__44u6__p8_0[] = {
  149666. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149667. 38.5, 49.5,
  149668. };
  149669. static long _vq_quantmap__44u6__p8_0[] = {
  149670. 9, 7, 5, 3, 1, 0, 2, 4,
  149671. 6, 8, 10,
  149672. };
  149673. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  149674. _vq_quantthresh__44u6__p8_0,
  149675. _vq_quantmap__44u6__p8_0,
  149676. 11,
  149677. 11
  149678. };
  149679. static static_codebook _44u6__p8_0 = {
  149680. 2, 121,
  149681. _vq_lengthlist__44u6__p8_0,
  149682. 1, -524582912, 1618345984, 4, 0,
  149683. _vq_quantlist__44u6__p8_0,
  149684. NULL,
  149685. &_vq_auxt__44u6__p8_0,
  149686. NULL,
  149687. 0
  149688. };
  149689. static long _vq_quantlist__44u6__p8_1[] = {
  149690. 5,
  149691. 4,
  149692. 6,
  149693. 3,
  149694. 7,
  149695. 2,
  149696. 8,
  149697. 1,
  149698. 9,
  149699. 0,
  149700. 10,
  149701. };
  149702. static long _vq_lengthlist__44u6__p8_1[] = {
  149703. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  149704. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  149705. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  149706. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149707. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  149708. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149709. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  149710. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149711. };
  149712. static float _vq_quantthresh__44u6__p8_1[] = {
  149713. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149714. 3.5, 4.5,
  149715. };
  149716. static long _vq_quantmap__44u6__p8_1[] = {
  149717. 9, 7, 5, 3, 1, 0, 2, 4,
  149718. 6, 8, 10,
  149719. };
  149720. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  149721. _vq_quantthresh__44u6__p8_1,
  149722. _vq_quantmap__44u6__p8_1,
  149723. 11,
  149724. 11
  149725. };
  149726. static static_codebook _44u6__p8_1 = {
  149727. 2, 121,
  149728. _vq_lengthlist__44u6__p8_1,
  149729. 1, -531365888, 1611661312, 4, 0,
  149730. _vq_quantlist__44u6__p8_1,
  149731. NULL,
  149732. &_vq_auxt__44u6__p8_1,
  149733. NULL,
  149734. 0
  149735. };
  149736. static long _vq_quantlist__44u6__p9_0[] = {
  149737. 7,
  149738. 6,
  149739. 8,
  149740. 5,
  149741. 9,
  149742. 4,
  149743. 10,
  149744. 3,
  149745. 11,
  149746. 2,
  149747. 12,
  149748. 1,
  149749. 13,
  149750. 0,
  149751. 14,
  149752. };
  149753. static long _vq_lengthlist__44u6__p9_0[] = {
  149754. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  149755. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  149756. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  149757. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  149758. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149759. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149760. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149761. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149762. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149763. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149764. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149765. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149766. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149767. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149768. 14,
  149769. };
  149770. static float _vq_quantthresh__44u6__p9_0[] = {
  149771. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  149772. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  149773. };
  149774. static long _vq_quantmap__44u6__p9_0[] = {
  149775. 13, 11, 9, 7, 5, 3, 1, 0,
  149776. 2, 4, 6, 8, 10, 12, 14,
  149777. };
  149778. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  149779. _vq_quantthresh__44u6__p9_0,
  149780. _vq_quantmap__44u6__p9_0,
  149781. 15,
  149782. 15
  149783. };
  149784. static static_codebook _44u6__p9_0 = {
  149785. 2, 225,
  149786. _vq_lengthlist__44u6__p9_0,
  149787. 1, -514071552, 1627381760, 4, 0,
  149788. _vq_quantlist__44u6__p9_0,
  149789. NULL,
  149790. &_vq_auxt__44u6__p9_0,
  149791. NULL,
  149792. 0
  149793. };
  149794. static long _vq_quantlist__44u6__p9_1[] = {
  149795. 7,
  149796. 6,
  149797. 8,
  149798. 5,
  149799. 9,
  149800. 4,
  149801. 10,
  149802. 3,
  149803. 11,
  149804. 2,
  149805. 12,
  149806. 1,
  149807. 13,
  149808. 0,
  149809. 14,
  149810. };
  149811. static long _vq_lengthlist__44u6__p9_1[] = {
  149812. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  149813. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  149814. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  149815. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  149816. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  149817. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  149818. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  149819. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  149820. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  149821. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  149822. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  149823. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  149824. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  149825. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  149826. 13,
  149827. };
  149828. static float _vq_quantthresh__44u6__p9_1[] = {
  149829. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149830. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149831. };
  149832. static long _vq_quantmap__44u6__p9_1[] = {
  149833. 13, 11, 9, 7, 5, 3, 1, 0,
  149834. 2, 4, 6, 8, 10, 12, 14,
  149835. };
  149836. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  149837. _vq_quantthresh__44u6__p9_1,
  149838. _vq_quantmap__44u6__p9_1,
  149839. 15,
  149840. 15
  149841. };
  149842. static static_codebook _44u6__p9_1 = {
  149843. 2, 225,
  149844. _vq_lengthlist__44u6__p9_1,
  149845. 1, -522338304, 1620115456, 4, 0,
  149846. _vq_quantlist__44u6__p9_1,
  149847. NULL,
  149848. &_vq_auxt__44u6__p9_1,
  149849. NULL,
  149850. 0
  149851. };
  149852. static long _vq_quantlist__44u6__p9_2[] = {
  149853. 8,
  149854. 7,
  149855. 9,
  149856. 6,
  149857. 10,
  149858. 5,
  149859. 11,
  149860. 4,
  149861. 12,
  149862. 3,
  149863. 13,
  149864. 2,
  149865. 14,
  149866. 1,
  149867. 15,
  149868. 0,
  149869. 16,
  149870. };
  149871. static long _vq_lengthlist__44u6__p9_2[] = {
  149872. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  149873. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  149874. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  149875. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149876. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149877. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149878. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149879. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149880. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  149881. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  149882. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  149883. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149884. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  149885. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  149886. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  149887. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  149888. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  149889. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  149890. 10,
  149891. };
  149892. static float _vq_quantthresh__44u6__p9_2[] = {
  149893. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149894. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149895. };
  149896. static long _vq_quantmap__44u6__p9_2[] = {
  149897. 15, 13, 11, 9, 7, 5, 3, 1,
  149898. 0, 2, 4, 6, 8, 10, 12, 14,
  149899. 16,
  149900. };
  149901. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  149902. _vq_quantthresh__44u6__p9_2,
  149903. _vq_quantmap__44u6__p9_2,
  149904. 17,
  149905. 17
  149906. };
  149907. static static_codebook _44u6__p9_2 = {
  149908. 2, 289,
  149909. _vq_lengthlist__44u6__p9_2,
  149910. 1, -529530880, 1611661312, 5, 0,
  149911. _vq_quantlist__44u6__p9_2,
  149912. NULL,
  149913. &_vq_auxt__44u6__p9_2,
  149914. NULL,
  149915. 0
  149916. };
  149917. static long _huff_lengthlist__44u6__short[] = {
  149918. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  149919. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  149920. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  149921. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  149922. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  149923. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  149924. 7, 6, 9,16,
  149925. };
  149926. static static_codebook _huff_book__44u6__short = {
  149927. 2, 100,
  149928. _huff_lengthlist__44u6__short,
  149929. 0, 0, 0, 0, 0,
  149930. NULL,
  149931. NULL,
  149932. NULL,
  149933. NULL,
  149934. 0
  149935. };
  149936. static long _huff_lengthlist__44u7__long[] = {
  149937. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  149938. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  149939. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  149940. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  149941. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  149942. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  149943. 12, 8, 6, 7,
  149944. };
  149945. static static_codebook _huff_book__44u7__long = {
  149946. 2, 100,
  149947. _huff_lengthlist__44u7__long,
  149948. 0, 0, 0, 0, 0,
  149949. NULL,
  149950. NULL,
  149951. NULL,
  149952. NULL,
  149953. 0
  149954. };
  149955. static long _vq_quantlist__44u7__p1_0[] = {
  149956. 1,
  149957. 0,
  149958. 2,
  149959. };
  149960. static long _vq_lengthlist__44u7__p1_0[] = {
  149961. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149962. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  149963. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149964. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  149965. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  149966. 12,
  149967. };
  149968. static float _vq_quantthresh__44u7__p1_0[] = {
  149969. -0.5, 0.5,
  149970. };
  149971. static long _vq_quantmap__44u7__p1_0[] = {
  149972. 1, 0, 2,
  149973. };
  149974. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  149975. _vq_quantthresh__44u7__p1_0,
  149976. _vq_quantmap__44u7__p1_0,
  149977. 3,
  149978. 3
  149979. };
  149980. static static_codebook _44u7__p1_0 = {
  149981. 4, 81,
  149982. _vq_lengthlist__44u7__p1_0,
  149983. 1, -535822336, 1611661312, 2, 0,
  149984. _vq_quantlist__44u7__p1_0,
  149985. NULL,
  149986. &_vq_auxt__44u7__p1_0,
  149987. NULL,
  149988. 0
  149989. };
  149990. static long _vq_quantlist__44u7__p2_0[] = {
  149991. 1,
  149992. 0,
  149993. 2,
  149994. };
  149995. static long _vq_lengthlist__44u7__p2_0[] = {
  149996. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149997. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149998. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  149999. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150000. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150001. 9,
  150002. };
  150003. static float _vq_quantthresh__44u7__p2_0[] = {
  150004. -0.5, 0.5,
  150005. };
  150006. static long _vq_quantmap__44u7__p2_0[] = {
  150007. 1, 0, 2,
  150008. };
  150009. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150010. _vq_quantthresh__44u7__p2_0,
  150011. _vq_quantmap__44u7__p2_0,
  150012. 3,
  150013. 3
  150014. };
  150015. static static_codebook _44u7__p2_0 = {
  150016. 4, 81,
  150017. _vq_lengthlist__44u7__p2_0,
  150018. 1, -535822336, 1611661312, 2, 0,
  150019. _vq_quantlist__44u7__p2_0,
  150020. NULL,
  150021. &_vq_auxt__44u7__p2_0,
  150022. NULL,
  150023. 0
  150024. };
  150025. static long _vq_quantlist__44u7__p3_0[] = {
  150026. 2,
  150027. 1,
  150028. 3,
  150029. 0,
  150030. 4,
  150031. };
  150032. static long _vq_lengthlist__44u7__p3_0[] = {
  150033. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150034. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150035. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150036. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150037. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150038. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150039. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150040. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150041. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150042. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150043. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150044. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150045. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150046. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150047. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150048. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150049. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150050. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150051. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150052. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150053. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150054. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150055. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150056. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150057. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150058. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150059. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150060. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150061. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150062. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150063. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150064. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150065. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150066. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150067. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150068. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150069. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150070. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150071. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150072. 0,
  150073. };
  150074. static float _vq_quantthresh__44u7__p3_0[] = {
  150075. -1.5, -0.5, 0.5, 1.5,
  150076. };
  150077. static long _vq_quantmap__44u7__p3_0[] = {
  150078. 3, 1, 0, 2, 4,
  150079. };
  150080. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150081. _vq_quantthresh__44u7__p3_0,
  150082. _vq_quantmap__44u7__p3_0,
  150083. 5,
  150084. 5
  150085. };
  150086. static static_codebook _44u7__p3_0 = {
  150087. 4, 625,
  150088. _vq_lengthlist__44u7__p3_0,
  150089. 1, -533725184, 1611661312, 3, 0,
  150090. _vq_quantlist__44u7__p3_0,
  150091. NULL,
  150092. &_vq_auxt__44u7__p3_0,
  150093. NULL,
  150094. 0
  150095. };
  150096. static long _vq_quantlist__44u7__p4_0[] = {
  150097. 2,
  150098. 1,
  150099. 3,
  150100. 0,
  150101. 4,
  150102. };
  150103. static long _vq_lengthlist__44u7__p4_0[] = {
  150104. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150105. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150106. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150107. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150108. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150109. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150110. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150111. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150112. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150113. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150114. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150115. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150116. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150117. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150118. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150119. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150120. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150121. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150122. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150123. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150124. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150125. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150126. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150127. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150128. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150129. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150130. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150131. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150132. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150133. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150134. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150135. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150136. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150137. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150138. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150139. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150140. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150141. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150142. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150143. 14,
  150144. };
  150145. static float _vq_quantthresh__44u7__p4_0[] = {
  150146. -1.5, -0.5, 0.5, 1.5,
  150147. };
  150148. static long _vq_quantmap__44u7__p4_0[] = {
  150149. 3, 1, 0, 2, 4,
  150150. };
  150151. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150152. _vq_quantthresh__44u7__p4_0,
  150153. _vq_quantmap__44u7__p4_0,
  150154. 5,
  150155. 5
  150156. };
  150157. static static_codebook _44u7__p4_0 = {
  150158. 4, 625,
  150159. _vq_lengthlist__44u7__p4_0,
  150160. 1, -533725184, 1611661312, 3, 0,
  150161. _vq_quantlist__44u7__p4_0,
  150162. NULL,
  150163. &_vq_auxt__44u7__p4_0,
  150164. NULL,
  150165. 0
  150166. };
  150167. static long _vq_quantlist__44u7__p5_0[] = {
  150168. 4,
  150169. 3,
  150170. 5,
  150171. 2,
  150172. 6,
  150173. 1,
  150174. 7,
  150175. 0,
  150176. 8,
  150177. };
  150178. static long _vq_lengthlist__44u7__p5_0[] = {
  150179. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150180. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150181. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150182. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150183. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150184. 14,
  150185. };
  150186. static float _vq_quantthresh__44u7__p5_0[] = {
  150187. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150188. };
  150189. static long _vq_quantmap__44u7__p5_0[] = {
  150190. 7, 5, 3, 1, 0, 2, 4, 6,
  150191. 8,
  150192. };
  150193. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150194. _vq_quantthresh__44u7__p5_0,
  150195. _vq_quantmap__44u7__p5_0,
  150196. 9,
  150197. 9
  150198. };
  150199. static static_codebook _44u7__p5_0 = {
  150200. 2, 81,
  150201. _vq_lengthlist__44u7__p5_0,
  150202. 1, -531628032, 1611661312, 4, 0,
  150203. _vq_quantlist__44u7__p5_0,
  150204. NULL,
  150205. &_vq_auxt__44u7__p5_0,
  150206. NULL,
  150207. 0
  150208. };
  150209. static long _vq_quantlist__44u7__p6_0[] = {
  150210. 4,
  150211. 3,
  150212. 5,
  150213. 2,
  150214. 6,
  150215. 1,
  150216. 7,
  150217. 0,
  150218. 8,
  150219. };
  150220. static long _vq_lengthlist__44u7__p6_0[] = {
  150221. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150222. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150223. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150224. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150225. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150226. 12,
  150227. };
  150228. static float _vq_quantthresh__44u7__p6_0[] = {
  150229. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150230. };
  150231. static long _vq_quantmap__44u7__p6_0[] = {
  150232. 7, 5, 3, 1, 0, 2, 4, 6,
  150233. 8,
  150234. };
  150235. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150236. _vq_quantthresh__44u7__p6_0,
  150237. _vq_quantmap__44u7__p6_0,
  150238. 9,
  150239. 9
  150240. };
  150241. static static_codebook _44u7__p6_0 = {
  150242. 2, 81,
  150243. _vq_lengthlist__44u7__p6_0,
  150244. 1, -531628032, 1611661312, 4, 0,
  150245. _vq_quantlist__44u7__p6_0,
  150246. NULL,
  150247. &_vq_auxt__44u7__p6_0,
  150248. NULL,
  150249. 0
  150250. };
  150251. static long _vq_quantlist__44u7__p7_0[] = {
  150252. 1,
  150253. 0,
  150254. 2,
  150255. };
  150256. static long _vq_lengthlist__44u7__p7_0[] = {
  150257. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150258. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150259. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150260. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150261. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150262. 10,
  150263. };
  150264. static float _vq_quantthresh__44u7__p7_0[] = {
  150265. -5.5, 5.5,
  150266. };
  150267. static long _vq_quantmap__44u7__p7_0[] = {
  150268. 1, 0, 2,
  150269. };
  150270. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150271. _vq_quantthresh__44u7__p7_0,
  150272. _vq_quantmap__44u7__p7_0,
  150273. 3,
  150274. 3
  150275. };
  150276. static static_codebook _44u7__p7_0 = {
  150277. 4, 81,
  150278. _vq_lengthlist__44u7__p7_0,
  150279. 1, -529137664, 1618345984, 2, 0,
  150280. _vq_quantlist__44u7__p7_0,
  150281. NULL,
  150282. &_vq_auxt__44u7__p7_0,
  150283. NULL,
  150284. 0
  150285. };
  150286. static long _vq_quantlist__44u7__p7_1[] = {
  150287. 5,
  150288. 4,
  150289. 6,
  150290. 3,
  150291. 7,
  150292. 2,
  150293. 8,
  150294. 1,
  150295. 9,
  150296. 0,
  150297. 10,
  150298. };
  150299. static long _vq_lengthlist__44u7__p7_1[] = {
  150300. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150301. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150302. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150303. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150304. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150305. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150306. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150307. 8, 9, 9, 9, 9, 9,10,10,10,
  150308. };
  150309. static float _vq_quantthresh__44u7__p7_1[] = {
  150310. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150311. 3.5, 4.5,
  150312. };
  150313. static long _vq_quantmap__44u7__p7_1[] = {
  150314. 9, 7, 5, 3, 1, 0, 2, 4,
  150315. 6, 8, 10,
  150316. };
  150317. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150318. _vq_quantthresh__44u7__p7_1,
  150319. _vq_quantmap__44u7__p7_1,
  150320. 11,
  150321. 11
  150322. };
  150323. static static_codebook _44u7__p7_1 = {
  150324. 2, 121,
  150325. _vq_lengthlist__44u7__p7_1,
  150326. 1, -531365888, 1611661312, 4, 0,
  150327. _vq_quantlist__44u7__p7_1,
  150328. NULL,
  150329. &_vq_auxt__44u7__p7_1,
  150330. NULL,
  150331. 0
  150332. };
  150333. static long _vq_quantlist__44u7__p8_0[] = {
  150334. 5,
  150335. 4,
  150336. 6,
  150337. 3,
  150338. 7,
  150339. 2,
  150340. 8,
  150341. 1,
  150342. 9,
  150343. 0,
  150344. 10,
  150345. };
  150346. static long _vq_lengthlist__44u7__p8_0[] = {
  150347. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150348. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150349. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150350. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150351. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150352. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150353. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150354. 12,13,13,14,14,15,15,15,16,
  150355. };
  150356. static float _vq_quantthresh__44u7__p8_0[] = {
  150357. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150358. 38.5, 49.5,
  150359. };
  150360. static long _vq_quantmap__44u7__p8_0[] = {
  150361. 9, 7, 5, 3, 1, 0, 2, 4,
  150362. 6, 8, 10,
  150363. };
  150364. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150365. _vq_quantthresh__44u7__p8_0,
  150366. _vq_quantmap__44u7__p8_0,
  150367. 11,
  150368. 11
  150369. };
  150370. static static_codebook _44u7__p8_0 = {
  150371. 2, 121,
  150372. _vq_lengthlist__44u7__p8_0,
  150373. 1, -524582912, 1618345984, 4, 0,
  150374. _vq_quantlist__44u7__p8_0,
  150375. NULL,
  150376. &_vq_auxt__44u7__p8_0,
  150377. NULL,
  150378. 0
  150379. };
  150380. static long _vq_quantlist__44u7__p8_1[] = {
  150381. 5,
  150382. 4,
  150383. 6,
  150384. 3,
  150385. 7,
  150386. 2,
  150387. 8,
  150388. 1,
  150389. 9,
  150390. 0,
  150391. 10,
  150392. };
  150393. static long _vq_lengthlist__44u7__p8_1[] = {
  150394. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150395. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150396. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150397. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150398. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150399. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150400. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150401. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150402. };
  150403. static float _vq_quantthresh__44u7__p8_1[] = {
  150404. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150405. 3.5, 4.5,
  150406. };
  150407. static long _vq_quantmap__44u7__p8_1[] = {
  150408. 9, 7, 5, 3, 1, 0, 2, 4,
  150409. 6, 8, 10,
  150410. };
  150411. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150412. _vq_quantthresh__44u7__p8_1,
  150413. _vq_quantmap__44u7__p8_1,
  150414. 11,
  150415. 11
  150416. };
  150417. static static_codebook _44u7__p8_1 = {
  150418. 2, 121,
  150419. _vq_lengthlist__44u7__p8_1,
  150420. 1, -531365888, 1611661312, 4, 0,
  150421. _vq_quantlist__44u7__p8_1,
  150422. NULL,
  150423. &_vq_auxt__44u7__p8_1,
  150424. NULL,
  150425. 0
  150426. };
  150427. static long _vq_quantlist__44u7__p9_0[] = {
  150428. 5,
  150429. 4,
  150430. 6,
  150431. 3,
  150432. 7,
  150433. 2,
  150434. 8,
  150435. 1,
  150436. 9,
  150437. 0,
  150438. 10,
  150439. };
  150440. static long _vq_lengthlist__44u7__p9_0[] = {
  150441. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150442. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150443. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150444. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150445. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150446. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150447. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150448. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150449. };
  150450. static float _vq_quantthresh__44u7__p9_0[] = {
  150451. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150452. 2229.5, 2866.5,
  150453. };
  150454. static long _vq_quantmap__44u7__p9_0[] = {
  150455. 9, 7, 5, 3, 1, 0, 2, 4,
  150456. 6, 8, 10,
  150457. };
  150458. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150459. _vq_quantthresh__44u7__p9_0,
  150460. _vq_quantmap__44u7__p9_0,
  150461. 11,
  150462. 11
  150463. };
  150464. static static_codebook _44u7__p9_0 = {
  150465. 2, 121,
  150466. _vq_lengthlist__44u7__p9_0,
  150467. 1, -512171520, 1630791680, 4, 0,
  150468. _vq_quantlist__44u7__p9_0,
  150469. NULL,
  150470. &_vq_auxt__44u7__p9_0,
  150471. NULL,
  150472. 0
  150473. };
  150474. static long _vq_quantlist__44u7__p9_1[] = {
  150475. 6,
  150476. 5,
  150477. 7,
  150478. 4,
  150479. 8,
  150480. 3,
  150481. 9,
  150482. 2,
  150483. 10,
  150484. 1,
  150485. 11,
  150486. 0,
  150487. 12,
  150488. };
  150489. static long _vq_lengthlist__44u7__p9_1[] = {
  150490. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150491. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150492. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  150493. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  150494. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  150495. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  150496. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  150497. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  150498. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  150499. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  150500. 15,15,15,15,17,17,16,17,16,
  150501. };
  150502. static float _vq_quantthresh__44u7__p9_1[] = {
  150503. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  150504. 122.5, 171.5, 220.5, 269.5,
  150505. };
  150506. static long _vq_quantmap__44u7__p9_1[] = {
  150507. 11, 9, 7, 5, 3, 1, 0, 2,
  150508. 4, 6, 8, 10, 12,
  150509. };
  150510. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  150511. _vq_quantthresh__44u7__p9_1,
  150512. _vq_quantmap__44u7__p9_1,
  150513. 13,
  150514. 13
  150515. };
  150516. static static_codebook _44u7__p9_1 = {
  150517. 2, 169,
  150518. _vq_lengthlist__44u7__p9_1,
  150519. 1, -518889472, 1622704128, 4, 0,
  150520. _vq_quantlist__44u7__p9_1,
  150521. NULL,
  150522. &_vq_auxt__44u7__p9_1,
  150523. NULL,
  150524. 0
  150525. };
  150526. static long _vq_quantlist__44u7__p9_2[] = {
  150527. 24,
  150528. 23,
  150529. 25,
  150530. 22,
  150531. 26,
  150532. 21,
  150533. 27,
  150534. 20,
  150535. 28,
  150536. 19,
  150537. 29,
  150538. 18,
  150539. 30,
  150540. 17,
  150541. 31,
  150542. 16,
  150543. 32,
  150544. 15,
  150545. 33,
  150546. 14,
  150547. 34,
  150548. 13,
  150549. 35,
  150550. 12,
  150551. 36,
  150552. 11,
  150553. 37,
  150554. 10,
  150555. 38,
  150556. 9,
  150557. 39,
  150558. 8,
  150559. 40,
  150560. 7,
  150561. 41,
  150562. 6,
  150563. 42,
  150564. 5,
  150565. 43,
  150566. 4,
  150567. 44,
  150568. 3,
  150569. 45,
  150570. 2,
  150571. 46,
  150572. 1,
  150573. 47,
  150574. 0,
  150575. 48,
  150576. };
  150577. static long _vq_lengthlist__44u7__p9_2[] = {
  150578. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  150579. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150580. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  150581. 8,
  150582. };
  150583. static float _vq_quantthresh__44u7__p9_2[] = {
  150584. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150585. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150586. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150587. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150588. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150589. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150590. };
  150591. static long _vq_quantmap__44u7__p9_2[] = {
  150592. 47, 45, 43, 41, 39, 37, 35, 33,
  150593. 31, 29, 27, 25, 23, 21, 19, 17,
  150594. 15, 13, 11, 9, 7, 5, 3, 1,
  150595. 0, 2, 4, 6, 8, 10, 12, 14,
  150596. 16, 18, 20, 22, 24, 26, 28, 30,
  150597. 32, 34, 36, 38, 40, 42, 44, 46,
  150598. 48,
  150599. };
  150600. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  150601. _vq_quantthresh__44u7__p9_2,
  150602. _vq_quantmap__44u7__p9_2,
  150603. 49,
  150604. 49
  150605. };
  150606. static static_codebook _44u7__p9_2 = {
  150607. 1, 49,
  150608. _vq_lengthlist__44u7__p9_2,
  150609. 1, -526909440, 1611661312, 6, 0,
  150610. _vq_quantlist__44u7__p9_2,
  150611. NULL,
  150612. &_vq_auxt__44u7__p9_2,
  150613. NULL,
  150614. 0
  150615. };
  150616. static long _huff_lengthlist__44u7__short[] = {
  150617. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  150618. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  150619. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  150620. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  150621. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  150622. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  150623. 6, 8, 5, 9,
  150624. };
  150625. static static_codebook _huff_book__44u7__short = {
  150626. 2, 100,
  150627. _huff_lengthlist__44u7__short,
  150628. 0, 0, 0, 0, 0,
  150629. NULL,
  150630. NULL,
  150631. NULL,
  150632. NULL,
  150633. 0
  150634. };
  150635. static long _huff_lengthlist__44u8__long[] = {
  150636. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  150637. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  150638. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  150639. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  150640. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  150641. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  150642. 10, 8, 8, 9,
  150643. };
  150644. static static_codebook _huff_book__44u8__long = {
  150645. 2, 100,
  150646. _huff_lengthlist__44u8__long,
  150647. 0, 0, 0, 0, 0,
  150648. NULL,
  150649. NULL,
  150650. NULL,
  150651. NULL,
  150652. 0
  150653. };
  150654. static long _huff_lengthlist__44u8__short[] = {
  150655. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  150656. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  150657. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  150658. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  150659. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  150660. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  150661. 10,10,15,17,
  150662. };
  150663. static static_codebook _huff_book__44u8__short = {
  150664. 2, 100,
  150665. _huff_lengthlist__44u8__short,
  150666. 0, 0, 0, 0, 0,
  150667. NULL,
  150668. NULL,
  150669. NULL,
  150670. NULL,
  150671. 0
  150672. };
  150673. static long _vq_quantlist__44u8_p1_0[] = {
  150674. 1,
  150675. 0,
  150676. 2,
  150677. };
  150678. static long _vq_lengthlist__44u8_p1_0[] = {
  150679. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  150680. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  150681. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  150682. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  150683. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  150684. 10,
  150685. };
  150686. static float _vq_quantthresh__44u8_p1_0[] = {
  150687. -0.5, 0.5,
  150688. };
  150689. static long _vq_quantmap__44u8_p1_0[] = {
  150690. 1, 0, 2,
  150691. };
  150692. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  150693. _vq_quantthresh__44u8_p1_0,
  150694. _vq_quantmap__44u8_p1_0,
  150695. 3,
  150696. 3
  150697. };
  150698. static static_codebook _44u8_p1_0 = {
  150699. 4, 81,
  150700. _vq_lengthlist__44u8_p1_0,
  150701. 1, -535822336, 1611661312, 2, 0,
  150702. _vq_quantlist__44u8_p1_0,
  150703. NULL,
  150704. &_vq_auxt__44u8_p1_0,
  150705. NULL,
  150706. 0
  150707. };
  150708. static long _vq_quantlist__44u8_p2_0[] = {
  150709. 2,
  150710. 1,
  150711. 3,
  150712. 0,
  150713. 4,
  150714. };
  150715. static long _vq_lengthlist__44u8_p2_0[] = {
  150716. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150717. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  150718. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  150719. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  150720. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  150721. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  150722. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150723. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  150724. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  150725. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  150726. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  150727. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  150728. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  150729. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  150730. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  150731. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  150732. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  150733. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  150734. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  150735. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  150736. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  150737. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  150738. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  150739. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150740. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  150741. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  150742. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  150743. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  150744. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  150745. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  150746. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  150747. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150748. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  150749. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  150750. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  150751. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  150752. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  150753. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  150754. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  150755. 14,
  150756. };
  150757. static float _vq_quantthresh__44u8_p2_0[] = {
  150758. -1.5, -0.5, 0.5, 1.5,
  150759. };
  150760. static long _vq_quantmap__44u8_p2_0[] = {
  150761. 3, 1, 0, 2, 4,
  150762. };
  150763. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  150764. _vq_quantthresh__44u8_p2_0,
  150765. _vq_quantmap__44u8_p2_0,
  150766. 5,
  150767. 5
  150768. };
  150769. static static_codebook _44u8_p2_0 = {
  150770. 4, 625,
  150771. _vq_lengthlist__44u8_p2_0,
  150772. 1, -533725184, 1611661312, 3, 0,
  150773. _vq_quantlist__44u8_p2_0,
  150774. NULL,
  150775. &_vq_auxt__44u8_p2_0,
  150776. NULL,
  150777. 0
  150778. };
  150779. static long _vq_quantlist__44u8_p3_0[] = {
  150780. 4,
  150781. 3,
  150782. 5,
  150783. 2,
  150784. 6,
  150785. 1,
  150786. 7,
  150787. 0,
  150788. 8,
  150789. };
  150790. static long _vq_lengthlist__44u8_p3_0[] = {
  150791. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  150792. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150793. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  150794. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  150795. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  150796. 12,
  150797. };
  150798. static float _vq_quantthresh__44u8_p3_0[] = {
  150799. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150800. };
  150801. static long _vq_quantmap__44u8_p3_0[] = {
  150802. 7, 5, 3, 1, 0, 2, 4, 6,
  150803. 8,
  150804. };
  150805. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  150806. _vq_quantthresh__44u8_p3_0,
  150807. _vq_quantmap__44u8_p3_0,
  150808. 9,
  150809. 9
  150810. };
  150811. static static_codebook _44u8_p3_0 = {
  150812. 2, 81,
  150813. _vq_lengthlist__44u8_p3_0,
  150814. 1, -531628032, 1611661312, 4, 0,
  150815. _vq_quantlist__44u8_p3_0,
  150816. NULL,
  150817. &_vq_auxt__44u8_p3_0,
  150818. NULL,
  150819. 0
  150820. };
  150821. static long _vq_quantlist__44u8_p4_0[] = {
  150822. 8,
  150823. 7,
  150824. 9,
  150825. 6,
  150826. 10,
  150827. 5,
  150828. 11,
  150829. 4,
  150830. 12,
  150831. 3,
  150832. 13,
  150833. 2,
  150834. 14,
  150835. 1,
  150836. 15,
  150837. 0,
  150838. 16,
  150839. };
  150840. static long _vq_lengthlist__44u8_p4_0[] = {
  150841. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  150842. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  150843. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  150844. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  150845. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  150846. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  150847. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  150848. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  150849. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  150850. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  150851. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  150852. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  150853. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  150854. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  150855. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  150856. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  150857. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  150858. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  150859. 14,
  150860. };
  150861. static float _vq_quantthresh__44u8_p4_0[] = {
  150862. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150863. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150864. };
  150865. static long _vq_quantmap__44u8_p4_0[] = {
  150866. 15, 13, 11, 9, 7, 5, 3, 1,
  150867. 0, 2, 4, 6, 8, 10, 12, 14,
  150868. 16,
  150869. };
  150870. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  150871. _vq_quantthresh__44u8_p4_0,
  150872. _vq_quantmap__44u8_p4_0,
  150873. 17,
  150874. 17
  150875. };
  150876. static static_codebook _44u8_p4_0 = {
  150877. 2, 289,
  150878. _vq_lengthlist__44u8_p4_0,
  150879. 1, -529530880, 1611661312, 5, 0,
  150880. _vq_quantlist__44u8_p4_0,
  150881. NULL,
  150882. &_vq_auxt__44u8_p4_0,
  150883. NULL,
  150884. 0
  150885. };
  150886. static long _vq_quantlist__44u8_p5_0[] = {
  150887. 1,
  150888. 0,
  150889. 2,
  150890. };
  150891. static long _vq_lengthlist__44u8_p5_0[] = {
  150892. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  150893. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  150894. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  150895. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  150896. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  150897. 10,
  150898. };
  150899. static float _vq_quantthresh__44u8_p5_0[] = {
  150900. -5.5, 5.5,
  150901. };
  150902. static long _vq_quantmap__44u8_p5_0[] = {
  150903. 1, 0, 2,
  150904. };
  150905. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  150906. _vq_quantthresh__44u8_p5_0,
  150907. _vq_quantmap__44u8_p5_0,
  150908. 3,
  150909. 3
  150910. };
  150911. static static_codebook _44u8_p5_0 = {
  150912. 4, 81,
  150913. _vq_lengthlist__44u8_p5_0,
  150914. 1, -529137664, 1618345984, 2, 0,
  150915. _vq_quantlist__44u8_p5_0,
  150916. NULL,
  150917. &_vq_auxt__44u8_p5_0,
  150918. NULL,
  150919. 0
  150920. };
  150921. static long _vq_quantlist__44u8_p5_1[] = {
  150922. 5,
  150923. 4,
  150924. 6,
  150925. 3,
  150926. 7,
  150927. 2,
  150928. 8,
  150929. 1,
  150930. 9,
  150931. 0,
  150932. 10,
  150933. };
  150934. static long _vq_lengthlist__44u8_p5_1[] = {
  150935. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  150936. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  150937. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  150938. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  150939. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  150940. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150941. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  150942. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  150943. };
  150944. static float _vq_quantthresh__44u8_p5_1[] = {
  150945. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150946. 3.5, 4.5,
  150947. };
  150948. static long _vq_quantmap__44u8_p5_1[] = {
  150949. 9, 7, 5, 3, 1, 0, 2, 4,
  150950. 6, 8, 10,
  150951. };
  150952. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  150953. _vq_quantthresh__44u8_p5_1,
  150954. _vq_quantmap__44u8_p5_1,
  150955. 11,
  150956. 11
  150957. };
  150958. static static_codebook _44u8_p5_1 = {
  150959. 2, 121,
  150960. _vq_lengthlist__44u8_p5_1,
  150961. 1, -531365888, 1611661312, 4, 0,
  150962. _vq_quantlist__44u8_p5_1,
  150963. NULL,
  150964. &_vq_auxt__44u8_p5_1,
  150965. NULL,
  150966. 0
  150967. };
  150968. static long _vq_quantlist__44u8_p6_0[] = {
  150969. 6,
  150970. 5,
  150971. 7,
  150972. 4,
  150973. 8,
  150974. 3,
  150975. 9,
  150976. 2,
  150977. 10,
  150978. 1,
  150979. 11,
  150980. 0,
  150981. 12,
  150982. };
  150983. static long _vq_lengthlist__44u8_p6_0[] = {
  150984. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  150985. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  150986. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  150987. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  150988. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  150989. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  150990. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  150991. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  150992. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  150993. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  150994. 11,11,11,11,11,12,11,12,12,
  150995. };
  150996. static float _vq_quantthresh__44u8_p6_0[] = {
  150997. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  150998. 12.5, 17.5, 22.5, 27.5,
  150999. };
  151000. static long _vq_quantmap__44u8_p6_0[] = {
  151001. 11, 9, 7, 5, 3, 1, 0, 2,
  151002. 4, 6, 8, 10, 12,
  151003. };
  151004. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  151005. _vq_quantthresh__44u8_p6_0,
  151006. _vq_quantmap__44u8_p6_0,
  151007. 13,
  151008. 13
  151009. };
  151010. static static_codebook _44u8_p6_0 = {
  151011. 2, 169,
  151012. _vq_lengthlist__44u8_p6_0,
  151013. 1, -526516224, 1616117760, 4, 0,
  151014. _vq_quantlist__44u8_p6_0,
  151015. NULL,
  151016. &_vq_auxt__44u8_p6_0,
  151017. NULL,
  151018. 0
  151019. };
  151020. static long _vq_quantlist__44u8_p6_1[] = {
  151021. 2,
  151022. 1,
  151023. 3,
  151024. 0,
  151025. 4,
  151026. };
  151027. static long _vq_lengthlist__44u8_p6_1[] = {
  151028. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151029. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151030. };
  151031. static float _vq_quantthresh__44u8_p6_1[] = {
  151032. -1.5, -0.5, 0.5, 1.5,
  151033. };
  151034. static long _vq_quantmap__44u8_p6_1[] = {
  151035. 3, 1, 0, 2, 4,
  151036. };
  151037. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151038. _vq_quantthresh__44u8_p6_1,
  151039. _vq_quantmap__44u8_p6_1,
  151040. 5,
  151041. 5
  151042. };
  151043. static static_codebook _44u8_p6_1 = {
  151044. 2, 25,
  151045. _vq_lengthlist__44u8_p6_1,
  151046. 1, -533725184, 1611661312, 3, 0,
  151047. _vq_quantlist__44u8_p6_1,
  151048. NULL,
  151049. &_vq_auxt__44u8_p6_1,
  151050. NULL,
  151051. 0
  151052. };
  151053. static long _vq_quantlist__44u8_p7_0[] = {
  151054. 6,
  151055. 5,
  151056. 7,
  151057. 4,
  151058. 8,
  151059. 3,
  151060. 9,
  151061. 2,
  151062. 10,
  151063. 1,
  151064. 11,
  151065. 0,
  151066. 12,
  151067. };
  151068. static long _vq_lengthlist__44u8_p7_0[] = {
  151069. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151070. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151071. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151072. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151073. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151074. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151075. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151076. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151077. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151078. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151079. 13,13,14,14,14,15,15,15,16,
  151080. };
  151081. static float _vq_quantthresh__44u8_p7_0[] = {
  151082. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151083. 27.5, 38.5, 49.5, 60.5,
  151084. };
  151085. static long _vq_quantmap__44u8_p7_0[] = {
  151086. 11, 9, 7, 5, 3, 1, 0, 2,
  151087. 4, 6, 8, 10, 12,
  151088. };
  151089. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151090. _vq_quantthresh__44u8_p7_0,
  151091. _vq_quantmap__44u8_p7_0,
  151092. 13,
  151093. 13
  151094. };
  151095. static static_codebook _44u8_p7_0 = {
  151096. 2, 169,
  151097. _vq_lengthlist__44u8_p7_0,
  151098. 1, -523206656, 1618345984, 4, 0,
  151099. _vq_quantlist__44u8_p7_0,
  151100. NULL,
  151101. &_vq_auxt__44u8_p7_0,
  151102. NULL,
  151103. 0
  151104. };
  151105. static long _vq_quantlist__44u8_p7_1[] = {
  151106. 5,
  151107. 4,
  151108. 6,
  151109. 3,
  151110. 7,
  151111. 2,
  151112. 8,
  151113. 1,
  151114. 9,
  151115. 0,
  151116. 10,
  151117. };
  151118. static long _vq_lengthlist__44u8_p7_1[] = {
  151119. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151120. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151121. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151122. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151123. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151124. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151125. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151126. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151127. };
  151128. static float _vq_quantthresh__44u8_p7_1[] = {
  151129. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151130. 3.5, 4.5,
  151131. };
  151132. static long _vq_quantmap__44u8_p7_1[] = {
  151133. 9, 7, 5, 3, 1, 0, 2, 4,
  151134. 6, 8, 10,
  151135. };
  151136. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151137. _vq_quantthresh__44u8_p7_1,
  151138. _vq_quantmap__44u8_p7_1,
  151139. 11,
  151140. 11
  151141. };
  151142. static static_codebook _44u8_p7_1 = {
  151143. 2, 121,
  151144. _vq_lengthlist__44u8_p7_1,
  151145. 1, -531365888, 1611661312, 4, 0,
  151146. _vq_quantlist__44u8_p7_1,
  151147. NULL,
  151148. &_vq_auxt__44u8_p7_1,
  151149. NULL,
  151150. 0
  151151. };
  151152. static long _vq_quantlist__44u8_p8_0[] = {
  151153. 7,
  151154. 6,
  151155. 8,
  151156. 5,
  151157. 9,
  151158. 4,
  151159. 10,
  151160. 3,
  151161. 11,
  151162. 2,
  151163. 12,
  151164. 1,
  151165. 13,
  151166. 0,
  151167. 14,
  151168. };
  151169. static long _vq_lengthlist__44u8_p8_0[] = {
  151170. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151171. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151172. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151173. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151174. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151175. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151176. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151177. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151178. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151179. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151180. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151181. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151182. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151183. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151184. 17,
  151185. };
  151186. static float _vq_quantthresh__44u8_p8_0[] = {
  151187. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151188. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151189. };
  151190. static long _vq_quantmap__44u8_p8_0[] = {
  151191. 13, 11, 9, 7, 5, 3, 1, 0,
  151192. 2, 4, 6, 8, 10, 12, 14,
  151193. };
  151194. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151195. _vq_quantthresh__44u8_p8_0,
  151196. _vq_quantmap__44u8_p8_0,
  151197. 15,
  151198. 15
  151199. };
  151200. static static_codebook _44u8_p8_0 = {
  151201. 2, 225,
  151202. _vq_lengthlist__44u8_p8_0,
  151203. 1, -520986624, 1620377600, 4, 0,
  151204. _vq_quantlist__44u8_p8_0,
  151205. NULL,
  151206. &_vq_auxt__44u8_p8_0,
  151207. NULL,
  151208. 0
  151209. };
  151210. static long _vq_quantlist__44u8_p8_1[] = {
  151211. 10,
  151212. 9,
  151213. 11,
  151214. 8,
  151215. 12,
  151216. 7,
  151217. 13,
  151218. 6,
  151219. 14,
  151220. 5,
  151221. 15,
  151222. 4,
  151223. 16,
  151224. 3,
  151225. 17,
  151226. 2,
  151227. 18,
  151228. 1,
  151229. 19,
  151230. 0,
  151231. 20,
  151232. };
  151233. static long _vq_lengthlist__44u8_p8_1[] = {
  151234. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151235. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151236. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151237. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151238. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151239. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151240. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151241. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151242. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151243. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151244. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151245. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151246. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151247. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151248. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151249. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151250. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151251. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151252. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151253. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151254. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151255. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151256. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151257. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151258. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151259. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151260. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151261. 10,10,10,10,10,10,10,10,10,
  151262. };
  151263. static float _vq_quantthresh__44u8_p8_1[] = {
  151264. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151265. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151266. 6.5, 7.5, 8.5, 9.5,
  151267. };
  151268. static long _vq_quantmap__44u8_p8_1[] = {
  151269. 19, 17, 15, 13, 11, 9, 7, 5,
  151270. 3, 1, 0, 2, 4, 6, 8, 10,
  151271. 12, 14, 16, 18, 20,
  151272. };
  151273. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151274. _vq_quantthresh__44u8_p8_1,
  151275. _vq_quantmap__44u8_p8_1,
  151276. 21,
  151277. 21
  151278. };
  151279. static static_codebook _44u8_p8_1 = {
  151280. 2, 441,
  151281. _vq_lengthlist__44u8_p8_1,
  151282. 1, -529268736, 1611661312, 5, 0,
  151283. _vq_quantlist__44u8_p8_1,
  151284. NULL,
  151285. &_vq_auxt__44u8_p8_1,
  151286. NULL,
  151287. 0
  151288. };
  151289. static long _vq_quantlist__44u8_p9_0[] = {
  151290. 4,
  151291. 3,
  151292. 5,
  151293. 2,
  151294. 6,
  151295. 1,
  151296. 7,
  151297. 0,
  151298. 8,
  151299. };
  151300. static long _vq_lengthlist__44u8_p9_0[] = {
  151301. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151302. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151303. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151304. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151305. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151306. 8,
  151307. };
  151308. static float _vq_quantthresh__44u8_p9_0[] = {
  151309. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151310. };
  151311. static long _vq_quantmap__44u8_p9_0[] = {
  151312. 7, 5, 3, 1, 0, 2, 4, 6,
  151313. 8,
  151314. };
  151315. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151316. _vq_quantthresh__44u8_p9_0,
  151317. _vq_quantmap__44u8_p9_0,
  151318. 9,
  151319. 9
  151320. };
  151321. static static_codebook _44u8_p9_0 = {
  151322. 2, 81,
  151323. _vq_lengthlist__44u8_p9_0,
  151324. 1, -511895552, 1631393792, 4, 0,
  151325. _vq_quantlist__44u8_p9_0,
  151326. NULL,
  151327. &_vq_auxt__44u8_p9_0,
  151328. NULL,
  151329. 0
  151330. };
  151331. static long _vq_quantlist__44u8_p9_1[] = {
  151332. 9,
  151333. 8,
  151334. 10,
  151335. 7,
  151336. 11,
  151337. 6,
  151338. 12,
  151339. 5,
  151340. 13,
  151341. 4,
  151342. 14,
  151343. 3,
  151344. 15,
  151345. 2,
  151346. 16,
  151347. 1,
  151348. 17,
  151349. 0,
  151350. 18,
  151351. };
  151352. static long _vq_lengthlist__44u8_p9_1[] = {
  151353. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151354. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151355. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151356. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151357. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151358. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151359. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151360. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151361. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151362. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151363. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151364. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151365. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151366. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151367. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151368. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151369. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151370. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151371. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151372. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151373. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151374. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151375. 16,15,16,16,16,16,16,16,16,
  151376. };
  151377. static float _vq_quantthresh__44u8_p9_1[] = {
  151378. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151379. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151380. 367.5, 416.5,
  151381. };
  151382. static long _vq_quantmap__44u8_p9_1[] = {
  151383. 17, 15, 13, 11, 9, 7, 5, 3,
  151384. 1, 0, 2, 4, 6, 8, 10, 12,
  151385. 14, 16, 18,
  151386. };
  151387. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151388. _vq_quantthresh__44u8_p9_1,
  151389. _vq_quantmap__44u8_p9_1,
  151390. 19,
  151391. 19
  151392. };
  151393. static static_codebook _44u8_p9_1 = {
  151394. 2, 361,
  151395. _vq_lengthlist__44u8_p9_1,
  151396. 1, -518287360, 1622704128, 5, 0,
  151397. _vq_quantlist__44u8_p9_1,
  151398. NULL,
  151399. &_vq_auxt__44u8_p9_1,
  151400. NULL,
  151401. 0
  151402. };
  151403. static long _vq_quantlist__44u8_p9_2[] = {
  151404. 24,
  151405. 23,
  151406. 25,
  151407. 22,
  151408. 26,
  151409. 21,
  151410. 27,
  151411. 20,
  151412. 28,
  151413. 19,
  151414. 29,
  151415. 18,
  151416. 30,
  151417. 17,
  151418. 31,
  151419. 16,
  151420. 32,
  151421. 15,
  151422. 33,
  151423. 14,
  151424. 34,
  151425. 13,
  151426. 35,
  151427. 12,
  151428. 36,
  151429. 11,
  151430. 37,
  151431. 10,
  151432. 38,
  151433. 9,
  151434. 39,
  151435. 8,
  151436. 40,
  151437. 7,
  151438. 41,
  151439. 6,
  151440. 42,
  151441. 5,
  151442. 43,
  151443. 4,
  151444. 44,
  151445. 3,
  151446. 45,
  151447. 2,
  151448. 46,
  151449. 1,
  151450. 47,
  151451. 0,
  151452. 48,
  151453. };
  151454. static long _vq_lengthlist__44u8_p9_2[] = {
  151455. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151456. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151457. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151458. 7,
  151459. };
  151460. static float _vq_quantthresh__44u8_p9_2[] = {
  151461. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151462. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151463. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151464. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151465. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151466. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151467. };
  151468. static long _vq_quantmap__44u8_p9_2[] = {
  151469. 47, 45, 43, 41, 39, 37, 35, 33,
  151470. 31, 29, 27, 25, 23, 21, 19, 17,
  151471. 15, 13, 11, 9, 7, 5, 3, 1,
  151472. 0, 2, 4, 6, 8, 10, 12, 14,
  151473. 16, 18, 20, 22, 24, 26, 28, 30,
  151474. 32, 34, 36, 38, 40, 42, 44, 46,
  151475. 48,
  151476. };
  151477. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151478. _vq_quantthresh__44u8_p9_2,
  151479. _vq_quantmap__44u8_p9_2,
  151480. 49,
  151481. 49
  151482. };
  151483. static static_codebook _44u8_p9_2 = {
  151484. 1, 49,
  151485. _vq_lengthlist__44u8_p9_2,
  151486. 1, -526909440, 1611661312, 6, 0,
  151487. _vq_quantlist__44u8_p9_2,
  151488. NULL,
  151489. &_vq_auxt__44u8_p9_2,
  151490. NULL,
  151491. 0
  151492. };
  151493. static long _huff_lengthlist__44u9__long[] = {
  151494. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  151495. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  151496. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  151497. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  151498. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  151499. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  151500. 10, 8, 8, 9,
  151501. };
  151502. static static_codebook _huff_book__44u9__long = {
  151503. 2, 100,
  151504. _huff_lengthlist__44u9__long,
  151505. 0, 0, 0, 0, 0,
  151506. NULL,
  151507. NULL,
  151508. NULL,
  151509. NULL,
  151510. 0
  151511. };
  151512. static long _huff_lengthlist__44u9__short[] = {
  151513. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  151514. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  151515. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  151516. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  151517. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  151518. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  151519. 9, 9,12,15,
  151520. };
  151521. static static_codebook _huff_book__44u9__short = {
  151522. 2, 100,
  151523. _huff_lengthlist__44u9__short,
  151524. 0, 0, 0, 0, 0,
  151525. NULL,
  151526. NULL,
  151527. NULL,
  151528. NULL,
  151529. 0
  151530. };
  151531. static long _vq_quantlist__44u9_p1_0[] = {
  151532. 1,
  151533. 0,
  151534. 2,
  151535. };
  151536. static long _vq_lengthlist__44u9_p1_0[] = {
  151537. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  151538. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  151539. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  151540. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  151541. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  151542. 10,
  151543. };
  151544. static float _vq_quantthresh__44u9_p1_0[] = {
  151545. -0.5, 0.5,
  151546. };
  151547. static long _vq_quantmap__44u9_p1_0[] = {
  151548. 1, 0, 2,
  151549. };
  151550. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  151551. _vq_quantthresh__44u9_p1_0,
  151552. _vq_quantmap__44u9_p1_0,
  151553. 3,
  151554. 3
  151555. };
  151556. static static_codebook _44u9_p1_0 = {
  151557. 4, 81,
  151558. _vq_lengthlist__44u9_p1_0,
  151559. 1, -535822336, 1611661312, 2, 0,
  151560. _vq_quantlist__44u9_p1_0,
  151561. NULL,
  151562. &_vq_auxt__44u9_p1_0,
  151563. NULL,
  151564. 0
  151565. };
  151566. static long _vq_quantlist__44u9_p2_0[] = {
  151567. 2,
  151568. 1,
  151569. 3,
  151570. 0,
  151571. 4,
  151572. };
  151573. static long _vq_lengthlist__44u9_p2_0[] = {
  151574. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  151575. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  151576. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  151577. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  151578. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  151579. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  151580. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  151581. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  151582. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151583. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151584. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  151585. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  151586. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  151587. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  151588. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  151589. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  151590. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  151591. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  151592. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  151593. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  151594. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  151595. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  151596. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  151597. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  151598. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  151599. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  151600. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  151601. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  151602. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  151603. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  151604. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  151605. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  151606. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  151607. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  151608. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  151609. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  151610. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  151611. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  151612. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  151613. 14,
  151614. };
  151615. static float _vq_quantthresh__44u9_p2_0[] = {
  151616. -1.5, -0.5, 0.5, 1.5,
  151617. };
  151618. static long _vq_quantmap__44u9_p2_0[] = {
  151619. 3, 1, 0, 2, 4,
  151620. };
  151621. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  151622. _vq_quantthresh__44u9_p2_0,
  151623. _vq_quantmap__44u9_p2_0,
  151624. 5,
  151625. 5
  151626. };
  151627. static static_codebook _44u9_p2_0 = {
  151628. 4, 625,
  151629. _vq_lengthlist__44u9_p2_0,
  151630. 1, -533725184, 1611661312, 3, 0,
  151631. _vq_quantlist__44u9_p2_0,
  151632. NULL,
  151633. &_vq_auxt__44u9_p2_0,
  151634. NULL,
  151635. 0
  151636. };
  151637. static long _vq_quantlist__44u9_p3_0[] = {
  151638. 4,
  151639. 3,
  151640. 5,
  151641. 2,
  151642. 6,
  151643. 1,
  151644. 7,
  151645. 0,
  151646. 8,
  151647. };
  151648. static long _vq_lengthlist__44u9_p3_0[] = {
  151649. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  151650. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151651. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  151652. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  151653. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  151654. 11,
  151655. };
  151656. static float _vq_quantthresh__44u9_p3_0[] = {
  151657. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151658. };
  151659. static long _vq_quantmap__44u9_p3_0[] = {
  151660. 7, 5, 3, 1, 0, 2, 4, 6,
  151661. 8,
  151662. };
  151663. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  151664. _vq_quantthresh__44u9_p3_0,
  151665. _vq_quantmap__44u9_p3_0,
  151666. 9,
  151667. 9
  151668. };
  151669. static static_codebook _44u9_p3_0 = {
  151670. 2, 81,
  151671. _vq_lengthlist__44u9_p3_0,
  151672. 1, -531628032, 1611661312, 4, 0,
  151673. _vq_quantlist__44u9_p3_0,
  151674. NULL,
  151675. &_vq_auxt__44u9_p3_0,
  151676. NULL,
  151677. 0
  151678. };
  151679. static long _vq_quantlist__44u9_p4_0[] = {
  151680. 8,
  151681. 7,
  151682. 9,
  151683. 6,
  151684. 10,
  151685. 5,
  151686. 11,
  151687. 4,
  151688. 12,
  151689. 3,
  151690. 13,
  151691. 2,
  151692. 14,
  151693. 1,
  151694. 15,
  151695. 0,
  151696. 16,
  151697. };
  151698. static long _vq_lengthlist__44u9_p4_0[] = {
  151699. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  151700. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  151701. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  151702. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  151703. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  151704. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  151705. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  151706. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  151707. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  151708. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  151709. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  151710. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  151711. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  151712. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  151713. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  151714. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  151715. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  151716. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  151717. 14,
  151718. };
  151719. static float _vq_quantthresh__44u9_p4_0[] = {
  151720. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151721. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151722. };
  151723. static long _vq_quantmap__44u9_p4_0[] = {
  151724. 15, 13, 11, 9, 7, 5, 3, 1,
  151725. 0, 2, 4, 6, 8, 10, 12, 14,
  151726. 16,
  151727. };
  151728. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  151729. _vq_quantthresh__44u9_p4_0,
  151730. _vq_quantmap__44u9_p4_0,
  151731. 17,
  151732. 17
  151733. };
  151734. static static_codebook _44u9_p4_0 = {
  151735. 2, 289,
  151736. _vq_lengthlist__44u9_p4_0,
  151737. 1, -529530880, 1611661312, 5, 0,
  151738. _vq_quantlist__44u9_p4_0,
  151739. NULL,
  151740. &_vq_auxt__44u9_p4_0,
  151741. NULL,
  151742. 0
  151743. };
  151744. static long _vq_quantlist__44u9_p5_0[] = {
  151745. 1,
  151746. 0,
  151747. 2,
  151748. };
  151749. static long _vq_lengthlist__44u9_p5_0[] = {
  151750. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151751. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151752. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  151753. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151754. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151755. 10,
  151756. };
  151757. static float _vq_quantthresh__44u9_p5_0[] = {
  151758. -5.5, 5.5,
  151759. };
  151760. static long _vq_quantmap__44u9_p5_0[] = {
  151761. 1, 0, 2,
  151762. };
  151763. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  151764. _vq_quantthresh__44u9_p5_0,
  151765. _vq_quantmap__44u9_p5_0,
  151766. 3,
  151767. 3
  151768. };
  151769. static static_codebook _44u9_p5_0 = {
  151770. 4, 81,
  151771. _vq_lengthlist__44u9_p5_0,
  151772. 1, -529137664, 1618345984, 2, 0,
  151773. _vq_quantlist__44u9_p5_0,
  151774. NULL,
  151775. &_vq_auxt__44u9_p5_0,
  151776. NULL,
  151777. 0
  151778. };
  151779. static long _vq_quantlist__44u9_p5_1[] = {
  151780. 5,
  151781. 4,
  151782. 6,
  151783. 3,
  151784. 7,
  151785. 2,
  151786. 8,
  151787. 1,
  151788. 9,
  151789. 0,
  151790. 10,
  151791. };
  151792. static long _vq_lengthlist__44u9_p5_1[] = {
  151793. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  151794. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  151795. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  151796. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  151797. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  151798. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  151799. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  151800. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  151801. };
  151802. static float _vq_quantthresh__44u9_p5_1[] = {
  151803. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151804. 3.5, 4.5,
  151805. };
  151806. static long _vq_quantmap__44u9_p5_1[] = {
  151807. 9, 7, 5, 3, 1, 0, 2, 4,
  151808. 6, 8, 10,
  151809. };
  151810. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  151811. _vq_quantthresh__44u9_p5_1,
  151812. _vq_quantmap__44u9_p5_1,
  151813. 11,
  151814. 11
  151815. };
  151816. static static_codebook _44u9_p5_1 = {
  151817. 2, 121,
  151818. _vq_lengthlist__44u9_p5_1,
  151819. 1, -531365888, 1611661312, 4, 0,
  151820. _vq_quantlist__44u9_p5_1,
  151821. NULL,
  151822. &_vq_auxt__44u9_p5_1,
  151823. NULL,
  151824. 0
  151825. };
  151826. static long _vq_quantlist__44u9_p6_0[] = {
  151827. 6,
  151828. 5,
  151829. 7,
  151830. 4,
  151831. 8,
  151832. 3,
  151833. 9,
  151834. 2,
  151835. 10,
  151836. 1,
  151837. 11,
  151838. 0,
  151839. 12,
  151840. };
  151841. static long _vq_lengthlist__44u9_p6_0[] = {
  151842. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151843. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  151844. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151845. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  151846. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  151847. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151848. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151849. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  151850. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  151851. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151852. 10,11,11,11,11,12,11,12,12,
  151853. };
  151854. static float _vq_quantthresh__44u9_p6_0[] = {
  151855. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151856. 12.5, 17.5, 22.5, 27.5,
  151857. };
  151858. static long _vq_quantmap__44u9_p6_0[] = {
  151859. 11, 9, 7, 5, 3, 1, 0, 2,
  151860. 4, 6, 8, 10, 12,
  151861. };
  151862. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  151863. _vq_quantthresh__44u9_p6_0,
  151864. _vq_quantmap__44u9_p6_0,
  151865. 13,
  151866. 13
  151867. };
  151868. static static_codebook _44u9_p6_0 = {
  151869. 2, 169,
  151870. _vq_lengthlist__44u9_p6_0,
  151871. 1, -526516224, 1616117760, 4, 0,
  151872. _vq_quantlist__44u9_p6_0,
  151873. NULL,
  151874. &_vq_auxt__44u9_p6_0,
  151875. NULL,
  151876. 0
  151877. };
  151878. static long _vq_quantlist__44u9_p6_1[] = {
  151879. 2,
  151880. 1,
  151881. 3,
  151882. 0,
  151883. 4,
  151884. };
  151885. static long _vq_lengthlist__44u9_p6_1[] = {
  151886. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  151887. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151888. };
  151889. static float _vq_quantthresh__44u9_p6_1[] = {
  151890. -1.5, -0.5, 0.5, 1.5,
  151891. };
  151892. static long _vq_quantmap__44u9_p6_1[] = {
  151893. 3, 1, 0, 2, 4,
  151894. };
  151895. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  151896. _vq_quantthresh__44u9_p6_1,
  151897. _vq_quantmap__44u9_p6_1,
  151898. 5,
  151899. 5
  151900. };
  151901. static static_codebook _44u9_p6_1 = {
  151902. 2, 25,
  151903. _vq_lengthlist__44u9_p6_1,
  151904. 1, -533725184, 1611661312, 3, 0,
  151905. _vq_quantlist__44u9_p6_1,
  151906. NULL,
  151907. &_vq_auxt__44u9_p6_1,
  151908. NULL,
  151909. 0
  151910. };
  151911. static long _vq_quantlist__44u9_p7_0[] = {
  151912. 6,
  151913. 5,
  151914. 7,
  151915. 4,
  151916. 8,
  151917. 3,
  151918. 9,
  151919. 2,
  151920. 10,
  151921. 1,
  151922. 11,
  151923. 0,
  151924. 12,
  151925. };
  151926. static long _vq_lengthlist__44u9_p7_0[] = {
  151927. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  151928. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  151929. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  151930. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  151931. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151932. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151933. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  151934. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  151935. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  151936. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  151937. 12,13,13,14,14,14,15,15,15,
  151938. };
  151939. static float _vq_quantthresh__44u9_p7_0[] = {
  151940. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151941. 27.5, 38.5, 49.5, 60.5,
  151942. };
  151943. static long _vq_quantmap__44u9_p7_0[] = {
  151944. 11, 9, 7, 5, 3, 1, 0, 2,
  151945. 4, 6, 8, 10, 12,
  151946. };
  151947. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  151948. _vq_quantthresh__44u9_p7_0,
  151949. _vq_quantmap__44u9_p7_0,
  151950. 13,
  151951. 13
  151952. };
  151953. static static_codebook _44u9_p7_0 = {
  151954. 2, 169,
  151955. _vq_lengthlist__44u9_p7_0,
  151956. 1, -523206656, 1618345984, 4, 0,
  151957. _vq_quantlist__44u9_p7_0,
  151958. NULL,
  151959. &_vq_auxt__44u9_p7_0,
  151960. NULL,
  151961. 0
  151962. };
  151963. static long _vq_quantlist__44u9_p7_1[] = {
  151964. 5,
  151965. 4,
  151966. 6,
  151967. 3,
  151968. 7,
  151969. 2,
  151970. 8,
  151971. 1,
  151972. 9,
  151973. 0,
  151974. 10,
  151975. };
  151976. static long _vq_lengthlist__44u9_p7_1[] = {
  151977. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  151978. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151979. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  151980. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151981. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151982. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151983. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  151984. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151985. };
  151986. static float _vq_quantthresh__44u9_p7_1[] = {
  151987. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151988. 3.5, 4.5,
  151989. };
  151990. static long _vq_quantmap__44u9_p7_1[] = {
  151991. 9, 7, 5, 3, 1, 0, 2, 4,
  151992. 6, 8, 10,
  151993. };
  151994. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  151995. _vq_quantthresh__44u9_p7_1,
  151996. _vq_quantmap__44u9_p7_1,
  151997. 11,
  151998. 11
  151999. };
  152000. static static_codebook _44u9_p7_1 = {
  152001. 2, 121,
  152002. _vq_lengthlist__44u9_p7_1,
  152003. 1, -531365888, 1611661312, 4, 0,
  152004. _vq_quantlist__44u9_p7_1,
  152005. NULL,
  152006. &_vq_auxt__44u9_p7_1,
  152007. NULL,
  152008. 0
  152009. };
  152010. static long _vq_quantlist__44u9_p8_0[] = {
  152011. 7,
  152012. 6,
  152013. 8,
  152014. 5,
  152015. 9,
  152016. 4,
  152017. 10,
  152018. 3,
  152019. 11,
  152020. 2,
  152021. 12,
  152022. 1,
  152023. 13,
  152024. 0,
  152025. 14,
  152026. };
  152027. static long _vq_lengthlist__44u9_p8_0[] = {
  152028. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152029. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152030. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152031. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152032. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152033. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152034. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152035. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152036. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152037. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152038. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152039. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152040. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152041. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152042. 15,
  152043. };
  152044. static float _vq_quantthresh__44u9_p8_0[] = {
  152045. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152046. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152047. };
  152048. static long _vq_quantmap__44u9_p8_0[] = {
  152049. 13, 11, 9, 7, 5, 3, 1, 0,
  152050. 2, 4, 6, 8, 10, 12, 14,
  152051. };
  152052. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152053. _vq_quantthresh__44u9_p8_0,
  152054. _vq_quantmap__44u9_p8_0,
  152055. 15,
  152056. 15
  152057. };
  152058. static static_codebook _44u9_p8_0 = {
  152059. 2, 225,
  152060. _vq_lengthlist__44u9_p8_0,
  152061. 1, -520986624, 1620377600, 4, 0,
  152062. _vq_quantlist__44u9_p8_0,
  152063. NULL,
  152064. &_vq_auxt__44u9_p8_0,
  152065. NULL,
  152066. 0
  152067. };
  152068. static long _vq_quantlist__44u9_p8_1[] = {
  152069. 10,
  152070. 9,
  152071. 11,
  152072. 8,
  152073. 12,
  152074. 7,
  152075. 13,
  152076. 6,
  152077. 14,
  152078. 5,
  152079. 15,
  152080. 4,
  152081. 16,
  152082. 3,
  152083. 17,
  152084. 2,
  152085. 18,
  152086. 1,
  152087. 19,
  152088. 0,
  152089. 20,
  152090. };
  152091. static long _vq_lengthlist__44u9_p8_1[] = {
  152092. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152093. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152094. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152095. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152096. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152097. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152098. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152099. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152100. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152101. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152102. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152103. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152104. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152105. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152106. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152107. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152108. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152109. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152110. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152111. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152112. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152113. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152114. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152115. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152116. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152117. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152118. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152119. 10,10,10,10,10,10,10,10,10,
  152120. };
  152121. static float _vq_quantthresh__44u9_p8_1[] = {
  152122. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152123. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152124. 6.5, 7.5, 8.5, 9.5,
  152125. };
  152126. static long _vq_quantmap__44u9_p8_1[] = {
  152127. 19, 17, 15, 13, 11, 9, 7, 5,
  152128. 3, 1, 0, 2, 4, 6, 8, 10,
  152129. 12, 14, 16, 18, 20,
  152130. };
  152131. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152132. _vq_quantthresh__44u9_p8_1,
  152133. _vq_quantmap__44u9_p8_1,
  152134. 21,
  152135. 21
  152136. };
  152137. static static_codebook _44u9_p8_1 = {
  152138. 2, 441,
  152139. _vq_lengthlist__44u9_p8_1,
  152140. 1, -529268736, 1611661312, 5, 0,
  152141. _vq_quantlist__44u9_p8_1,
  152142. NULL,
  152143. &_vq_auxt__44u9_p8_1,
  152144. NULL,
  152145. 0
  152146. };
  152147. static long _vq_quantlist__44u9_p9_0[] = {
  152148. 7,
  152149. 6,
  152150. 8,
  152151. 5,
  152152. 9,
  152153. 4,
  152154. 10,
  152155. 3,
  152156. 11,
  152157. 2,
  152158. 12,
  152159. 1,
  152160. 13,
  152161. 0,
  152162. 14,
  152163. };
  152164. static long _vq_lengthlist__44u9_p9_0[] = {
  152165. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152166. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152167. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152168. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152169. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152170. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152171. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152172. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152173. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152174. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152175. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152176. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152177. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152178. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152179. 10,
  152180. };
  152181. static float _vq_quantthresh__44u9_p9_0[] = {
  152182. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152183. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152184. };
  152185. static long _vq_quantmap__44u9_p9_0[] = {
  152186. 13, 11, 9, 7, 5, 3, 1, 0,
  152187. 2, 4, 6, 8, 10, 12, 14,
  152188. };
  152189. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152190. _vq_quantthresh__44u9_p9_0,
  152191. _vq_quantmap__44u9_p9_0,
  152192. 15,
  152193. 15
  152194. };
  152195. static static_codebook _44u9_p9_0 = {
  152196. 2, 225,
  152197. _vq_lengthlist__44u9_p9_0,
  152198. 1, -510036736, 1631393792, 4, 0,
  152199. _vq_quantlist__44u9_p9_0,
  152200. NULL,
  152201. &_vq_auxt__44u9_p9_0,
  152202. NULL,
  152203. 0
  152204. };
  152205. static long _vq_quantlist__44u9_p9_1[] = {
  152206. 9,
  152207. 8,
  152208. 10,
  152209. 7,
  152210. 11,
  152211. 6,
  152212. 12,
  152213. 5,
  152214. 13,
  152215. 4,
  152216. 14,
  152217. 3,
  152218. 15,
  152219. 2,
  152220. 16,
  152221. 1,
  152222. 17,
  152223. 0,
  152224. 18,
  152225. };
  152226. static long _vq_lengthlist__44u9_p9_1[] = {
  152227. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152228. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152229. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152230. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152231. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152232. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152233. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152234. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152235. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152236. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152237. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152238. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152239. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152240. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152241. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152242. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152243. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152244. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152245. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152246. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152247. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152248. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152249. 17,17,15,17,15,17,16,16,17,
  152250. };
  152251. static float _vq_quantthresh__44u9_p9_1[] = {
  152252. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152253. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152254. 367.5, 416.5,
  152255. };
  152256. static long _vq_quantmap__44u9_p9_1[] = {
  152257. 17, 15, 13, 11, 9, 7, 5, 3,
  152258. 1, 0, 2, 4, 6, 8, 10, 12,
  152259. 14, 16, 18,
  152260. };
  152261. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152262. _vq_quantthresh__44u9_p9_1,
  152263. _vq_quantmap__44u9_p9_1,
  152264. 19,
  152265. 19
  152266. };
  152267. static static_codebook _44u9_p9_1 = {
  152268. 2, 361,
  152269. _vq_lengthlist__44u9_p9_1,
  152270. 1, -518287360, 1622704128, 5, 0,
  152271. _vq_quantlist__44u9_p9_1,
  152272. NULL,
  152273. &_vq_auxt__44u9_p9_1,
  152274. NULL,
  152275. 0
  152276. };
  152277. static long _vq_quantlist__44u9_p9_2[] = {
  152278. 24,
  152279. 23,
  152280. 25,
  152281. 22,
  152282. 26,
  152283. 21,
  152284. 27,
  152285. 20,
  152286. 28,
  152287. 19,
  152288. 29,
  152289. 18,
  152290. 30,
  152291. 17,
  152292. 31,
  152293. 16,
  152294. 32,
  152295. 15,
  152296. 33,
  152297. 14,
  152298. 34,
  152299. 13,
  152300. 35,
  152301. 12,
  152302. 36,
  152303. 11,
  152304. 37,
  152305. 10,
  152306. 38,
  152307. 9,
  152308. 39,
  152309. 8,
  152310. 40,
  152311. 7,
  152312. 41,
  152313. 6,
  152314. 42,
  152315. 5,
  152316. 43,
  152317. 4,
  152318. 44,
  152319. 3,
  152320. 45,
  152321. 2,
  152322. 46,
  152323. 1,
  152324. 47,
  152325. 0,
  152326. 48,
  152327. };
  152328. static long _vq_lengthlist__44u9_p9_2[] = {
  152329. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152330. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152331. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152332. 7,
  152333. };
  152334. static float _vq_quantthresh__44u9_p9_2[] = {
  152335. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152336. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152337. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152338. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152339. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152340. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152341. };
  152342. static long _vq_quantmap__44u9_p9_2[] = {
  152343. 47, 45, 43, 41, 39, 37, 35, 33,
  152344. 31, 29, 27, 25, 23, 21, 19, 17,
  152345. 15, 13, 11, 9, 7, 5, 3, 1,
  152346. 0, 2, 4, 6, 8, 10, 12, 14,
  152347. 16, 18, 20, 22, 24, 26, 28, 30,
  152348. 32, 34, 36, 38, 40, 42, 44, 46,
  152349. 48,
  152350. };
  152351. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152352. _vq_quantthresh__44u9_p9_2,
  152353. _vq_quantmap__44u9_p9_2,
  152354. 49,
  152355. 49
  152356. };
  152357. static static_codebook _44u9_p9_2 = {
  152358. 1, 49,
  152359. _vq_lengthlist__44u9_p9_2,
  152360. 1, -526909440, 1611661312, 6, 0,
  152361. _vq_quantlist__44u9_p9_2,
  152362. NULL,
  152363. &_vq_auxt__44u9_p9_2,
  152364. NULL,
  152365. 0
  152366. };
  152367. static long _huff_lengthlist__44un1__long[] = {
  152368. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152369. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152370. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152371. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152372. };
  152373. static static_codebook _huff_book__44un1__long = {
  152374. 2, 64,
  152375. _huff_lengthlist__44un1__long,
  152376. 0, 0, 0, 0, 0,
  152377. NULL,
  152378. NULL,
  152379. NULL,
  152380. NULL,
  152381. 0
  152382. };
  152383. static long _vq_quantlist__44un1__p1_0[] = {
  152384. 1,
  152385. 0,
  152386. 2,
  152387. };
  152388. static long _vq_lengthlist__44un1__p1_0[] = {
  152389. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152390. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152391. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152392. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152393. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152394. 12,
  152395. };
  152396. static float _vq_quantthresh__44un1__p1_0[] = {
  152397. -0.5, 0.5,
  152398. };
  152399. static long _vq_quantmap__44un1__p1_0[] = {
  152400. 1, 0, 2,
  152401. };
  152402. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152403. _vq_quantthresh__44un1__p1_0,
  152404. _vq_quantmap__44un1__p1_0,
  152405. 3,
  152406. 3
  152407. };
  152408. static static_codebook _44un1__p1_0 = {
  152409. 4, 81,
  152410. _vq_lengthlist__44un1__p1_0,
  152411. 1, -535822336, 1611661312, 2, 0,
  152412. _vq_quantlist__44un1__p1_0,
  152413. NULL,
  152414. &_vq_auxt__44un1__p1_0,
  152415. NULL,
  152416. 0
  152417. };
  152418. static long _vq_quantlist__44un1__p2_0[] = {
  152419. 1,
  152420. 0,
  152421. 2,
  152422. };
  152423. static long _vq_lengthlist__44un1__p2_0[] = {
  152424. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152425. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152426. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152427. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152428. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152429. 8,
  152430. };
  152431. static float _vq_quantthresh__44un1__p2_0[] = {
  152432. -0.5, 0.5,
  152433. };
  152434. static long _vq_quantmap__44un1__p2_0[] = {
  152435. 1, 0, 2,
  152436. };
  152437. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152438. _vq_quantthresh__44un1__p2_0,
  152439. _vq_quantmap__44un1__p2_0,
  152440. 3,
  152441. 3
  152442. };
  152443. static static_codebook _44un1__p2_0 = {
  152444. 4, 81,
  152445. _vq_lengthlist__44un1__p2_0,
  152446. 1, -535822336, 1611661312, 2, 0,
  152447. _vq_quantlist__44un1__p2_0,
  152448. NULL,
  152449. &_vq_auxt__44un1__p2_0,
  152450. NULL,
  152451. 0
  152452. };
  152453. static long _vq_quantlist__44un1__p3_0[] = {
  152454. 2,
  152455. 1,
  152456. 3,
  152457. 0,
  152458. 4,
  152459. };
  152460. static long _vq_lengthlist__44un1__p3_0[] = {
  152461. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152462. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152463. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152464. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152465. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152466. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152467. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152468. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152469. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152470. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152471. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152472. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152473. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152474. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152475. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152476. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152477. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152478. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152479. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152480. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152481. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152482. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152483. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152484. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152485. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152486. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152487. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152488. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152489. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152490. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152491. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152492. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  152493. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  152494. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  152495. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  152496. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  152497. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  152498. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  152499. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  152500. 17,
  152501. };
  152502. static float _vq_quantthresh__44un1__p3_0[] = {
  152503. -1.5, -0.5, 0.5, 1.5,
  152504. };
  152505. static long _vq_quantmap__44un1__p3_0[] = {
  152506. 3, 1, 0, 2, 4,
  152507. };
  152508. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  152509. _vq_quantthresh__44un1__p3_0,
  152510. _vq_quantmap__44un1__p3_0,
  152511. 5,
  152512. 5
  152513. };
  152514. static static_codebook _44un1__p3_0 = {
  152515. 4, 625,
  152516. _vq_lengthlist__44un1__p3_0,
  152517. 1, -533725184, 1611661312, 3, 0,
  152518. _vq_quantlist__44un1__p3_0,
  152519. NULL,
  152520. &_vq_auxt__44un1__p3_0,
  152521. NULL,
  152522. 0
  152523. };
  152524. static long _vq_quantlist__44un1__p4_0[] = {
  152525. 2,
  152526. 1,
  152527. 3,
  152528. 0,
  152529. 4,
  152530. };
  152531. static long _vq_lengthlist__44un1__p4_0[] = {
  152532. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  152533. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  152534. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  152535. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  152536. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  152537. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  152538. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  152539. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  152540. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  152541. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  152542. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  152543. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  152544. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  152545. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  152546. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  152547. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  152548. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  152549. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  152550. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  152551. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  152552. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  152553. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  152554. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  152555. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  152556. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  152557. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  152558. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  152559. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  152560. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  152561. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  152562. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  152563. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  152564. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  152565. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  152566. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  152567. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  152568. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  152569. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  152570. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  152571. 12,
  152572. };
  152573. static float _vq_quantthresh__44un1__p4_0[] = {
  152574. -1.5, -0.5, 0.5, 1.5,
  152575. };
  152576. static long _vq_quantmap__44un1__p4_0[] = {
  152577. 3, 1, 0, 2, 4,
  152578. };
  152579. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  152580. _vq_quantthresh__44un1__p4_0,
  152581. _vq_quantmap__44un1__p4_0,
  152582. 5,
  152583. 5
  152584. };
  152585. static static_codebook _44un1__p4_0 = {
  152586. 4, 625,
  152587. _vq_lengthlist__44un1__p4_0,
  152588. 1, -533725184, 1611661312, 3, 0,
  152589. _vq_quantlist__44un1__p4_0,
  152590. NULL,
  152591. &_vq_auxt__44un1__p4_0,
  152592. NULL,
  152593. 0
  152594. };
  152595. static long _vq_quantlist__44un1__p5_0[] = {
  152596. 4,
  152597. 3,
  152598. 5,
  152599. 2,
  152600. 6,
  152601. 1,
  152602. 7,
  152603. 0,
  152604. 8,
  152605. };
  152606. static long _vq_lengthlist__44un1__p5_0[] = {
  152607. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  152608. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  152609. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  152610. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  152611. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  152612. 12,
  152613. };
  152614. static float _vq_quantthresh__44un1__p5_0[] = {
  152615. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152616. };
  152617. static long _vq_quantmap__44un1__p5_0[] = {
  152618. 7, 5, 3, 1, 0, 2, 4, 6,
  152619. 8,
  152620. };
  152621. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  152622. _vq_quantthresh__44un1__p5_0,
  152623. _vq_quantmap__44un1__p5_0,
  152624. 9,
  152625. 9
  152626. };
  152627. static static_codebook _44un1__p5_0 = {
  152628. 2, 81,
  152629. _vq_lengthlist__44un1__p5_0,
  152630. 1, -531628032, 1611661312, 4, 0,
  152631. _vq_quantlist__44un1__p5_0,
  152632. NULL,
  152633. &_vq_auxt__44un1__p5_0,
  152634. NULL,
  152635. 0
  152636. };
  152637. static long _vq_quantlist__44un1__p6_0[] = {
  152638. 6,
  152639. 5,
  152640. 7,
  152641. 4,
  152642. 8,
  152643. 3,
  152644. 9,
  152645. 2,
  152646. 10,
  152647. 1,
  152648. 11,
  152649. 0,
  152650. 12,
  152651. };
  152652. static long _vq_lengthlist__44un1__p6_0[] = {
  152653. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  152654. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  152655. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  152656. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  152657. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  152658. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  152659. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  152660. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  152661. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  152662. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  152663. 16, 0,15,18,18, 0,16, 0, 0,
  152664. };
  152665. static float _vq_quantthresh__44un1__p6_0[] = {
  152666. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152667. 12.5, 17.5, 22.5, 27.5,
  152668. };
  152669. static long _vq_quantmap__44un1__p6_0[] = {
  152670. 11, 9, 7, 5, 3, 1, 0, 2,
  152671. 4, 6, 8, 10, 12,
  152672. };
  152673. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  152674. _vq_quantthresh__44un1__p6_0,
  152675. _vq_quantmap__44un1__p6_0,
  152676. 13,
  152677. 13
  152678. };
  152679. static static_codebook _44un1__p6_0 = {
  152680. 2, 169,
  152681. _vq_lengthlist__44un1__p6_0,
  152682. 1, -526516224, 1616117760, 4, 0,
  152683. _vq_quantlist__44un1__p6_0,
  152684. NULL,
  152685. &_vq_auxt__44un1__p6_0,
  152686. NULL,
  152687. 0
  152688. };
  152689. static long _vq_quantlist__44un1__p6_1[] = {
  152690. 2,
  152691. 1,
  152692. 3,
  152693. 0,
  152694. 4,
  152695. };
  152696. static long _vq_lengthlist__44un1__p6_1[] = {
  152697. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  152698. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  152699. };
  152700. static float _vq_quantthresh__44un1__p6_1[] = {
  152701. -1.5, -0.5, 0.5, 1.5,
  152702. };
  152703. static long _vq_quantmap__44un1__p6_1[] = {
  152704. 3, 1, 0, 2, 4,
  152705. };
  152706. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  152707. _vq_quantthresh__44un1__p6_1,
  152708. _vq_quantmap__44un1__p6_1,
  152709. 5,
  152710. 5
  152711. };
  152712. static static_codebook _44un1__p6_1 = {
  152713. 2, 25,
  152714. _vq_lengthlist__44un1__p6_1,
  152715. 1, -533725184, 1611661312, 3, 0,
  152716. _vq_quantlist__44un1__p6_1,
  152717. NULL,
  152718. &_vq_auxt__44un1__p6_1,
  152719. NULL,
  152720. 0
  152721. };
  152722. static long _vq_quantlist__44un1__p7_0[] = {
  152723. 2,
  152724. 1,
  152725. 3,
  152726. 0,
  152727. 4,
  152728. };
  152729. static long _vq_lengthlist__44un1__p7_0[] = {
  152730. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  152731. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  152732. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152733. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152734. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152735. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152736. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152737. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  152738. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152739. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152740. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  152741. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152742. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152743. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152744. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152745. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  152746. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152747. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  152748. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152749. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152750. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152751. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152752. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152753. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152754. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152755. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152756. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152757. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152758. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152759. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152760. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152761. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152762. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152763. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152764. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152765. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152766. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152767. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152768. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152769. 10,
  152770. };
  152771. static float _vq_quantthresh__44un1__p7_0[] = {
  152772. -253.5, -84.5, 84.5, 253.5,
  152773. };
  152774. static long _vq_quantmap__44un1__p7_0[] = {
  152775. 3, 1, 0, 2, 4,
  152776. };
  152777. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  152778. _vq_quantthresh__44un1__p7_0,
  152779. _vq_quantmap__44un1__p7_0,
  152780. 5,
  152781. 5
  152782. };
  152783. static static_codebook _44un1__p7_0 = {
  152784. 4, 625,
  152785. _vq_lengthlist__44un1__p7_0,
  152786. 1, -518709248, 1626677248, 3, 0,
  152787. _vq_quantlist__44un1__p7_0,
  152788. NULL,
  152789. &_vq_auxt__44un1__p7_0,
  152790. NULL,
  152791. 0
  152792. };
  152793. static long _vq_quantlist__44un1__p7_1[] = {
  152794. 6,
  152795. 5,
  152796. 7,
  152797. 4,
  152798. 8,
  152799. 3,
  152800. 9,
  152801. 2,
  152802. 10,
  152803. 1,
  152804. 11,
  152805. 0,
  152806. 12,
  152807. };
  152808. static long _vq_lengthlist__44un1__p7_1[] = {
  152809. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  152810. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  152811. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  152812. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  152813. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  152814. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  152815. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  152816. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  152817. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  152818. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  152819. 12,13,13,12,13,13,14,14,14,
  152820. };
  152821. static float _vq_quantthresh__44un1__p7_1[] = {
  152822. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  152823. 32.5, 45.5, 58.5, 71.5,
  152824. };
  152825. static long _vq_quantmap__44un1__p7_1[] = {
  152826. 11, 9, 7, 5, 3, 1, 0, 2,
  152827. 4, 6, 8, 10, 12,
  152828. };
  152829. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  152830. _vq_quantthresh__44un1__p7_1,
  152831. _vq_quantmap__44un1__p7_1,
  152832. 13,
  152833. 13
  152834. };
  152835. static static_codebook _44un1__p7_1 = {
  152836. 2, 169,
  152837. _vq_lengthlist__44un1__p7_1,
  152838. 1, -523010048, 1618608128, 4, 0,
  152839. _vq_quantlist__44un1__p7_1,
  152840. NULL,
  152841. &_vq_auxt__44un1__p7_1,
  152842. NULL,
  152843. 0
  152844. };
  152845. static long _vq_quantlist__44un1__p7_2[] = {
  152846. 6,
  152847. 5,
  152848. 7,
  152849. 4,
  152850. 8,
  152851. 3,
  152852. 9,
  152853. 2,
  152854. 10,
  152855. 1,
  152856. 11,
  152857. 0,
  152858. 12,
  152859. };
  152860. static long _vq_lengthlist__44un1__p7_2[] = {
  152861. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  152862. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  152863. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  152864. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  152865. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  152866. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  152867. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  152868. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  152869. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  152870. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  152871. 9, 9, 9,10,10,10,10,10,10,
  152872. };
  152873. static float _vq_quantthresh__44un1__p7_2[] = {
  152874. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  152875. 2.5, 3.5, 4.5, 5.5,
  152876. };
  152877. static long _vq_quantmap__44un1__p7_2[] = {
  152878. 11, 9, 7, 5, 3, 1, 0, 2,
  152879. 4, 6, 8, 10, 12,
  152880. };
  152881. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  152882. _vq_quantthresh__44un1__p7_2,
  152883. _vq_quantmap__44un1__p7_2,
  152884. 13,
  152885. 13
  152886. };
  152887. static static_codebook _44un1__p7_2 = {
  152888. 2, 169,
  152889. _vq_lengthlist__44un1__p7_2,
  152890. 1, -531103744, 1611661312, 4, 0,
  152891. _vq_quantlist__44un1__p7_2,
  152892. NULL,
  152893. &_vq_auxt__44un1__p7_2,
  152894. NULL,
  152895. 0
  152896. };
  152897. static long _huff_lengthlist__44un1__short[] = {
  152898. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  152899. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  152900. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  152901. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  152902. };
  152903. static static_codebook _huff_book__44un1__short = {
  152904. 2, 64,
  152905. _huff_lengthlist__44un1__short,
  152906. 0, 0, 0, 0, 0,
  152907. NULL,
  152908. NULL,
  152909. NULL,
  152910. NULL,
  152911. 0
  152912. };
  152913. /*** End of inlined file: res_books_uncoupled.h ***/
  152914. /***** residue backends *********************************************/
  152915. static vorbis_info_residue0 _residue_44_low_un={
  152916. 0,-1, -1, 8,-1,
  152917. {0},
  152918. {-1},
  152919. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  152920. { -1, 25, -1, 45, -1, -1, -1}
  152921. };
  152922. static vorbis_info_residue0 _residue_44_mid_un={
  152923. 0,-1, -1, 10,-1,
  152924. /* 0 1 2 3 4 5 6 7 8 9 */
  152925. {0},
  152926. {-1},
  152927. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  152928. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  152929. };
  152930. static vorbis_info_residue0 _residue_44_hi_un={
  152931. 0,-1, -1, 10,-1,
  152932. /* 0 1 2 3 4 5 6 7 8 9 */
  152933. {0},
  152934. {-1},
  152935. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  152936. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  152937. };
  152938. /* mapping conventions:
  152939. only one submap (this would change for efficient 5.1 support for example)*/
  152940. /* Four psychoacoustic profiles are used, one for each blocktype */
  152941. static vorbis_info_mapping0 _map_nominal_u[2]={
  152942. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  152943. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  152944. };
  152945. static static_bookblock _resbook_44u_n1={
  152946. {
  152947. {0},
  152948. {0,0,&_44un1__p1_0},
  152949. {0,0,&_44un1__p2_0},
  152950. {0,0,&_44un1__p3_0},
  152951. {0,0,&_44un1__p4_0},
  152952. {0,0,&_44un1__p5_0},
  152953. {&_44un1__p6_0,&_44un1__p6_1},
  152954. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  152955. }
  152956. };
  152957. static static_bookblock _resbook_44u_0={
  152958. {
  152959. {0},
  152960. {0,0,&_44u0__p1_0},
  152961. {0,0,&_44u0__p2_0},
  152962. {0,0,&_44u0__p3_0},
  152963. {0,0,&_44u0__p4_0},
  152964. {0,0,&_44u0__p5_0},
  152965. {&_44u0__p6_0,&_44u0__p6_1},
  152966. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  152967. }
  152968. };
  152969. static static_bookblock _resbook_44u_1={
  152970. {
  152971. {0},
  152972. {0,0,&_44u1__p1_0},
  152973. {0,0,&_44u1__p2_0},
  152974. {0,0,&_44u1__p3_0},
  152975. {0,0,&_44u1__p4_0},
  152976. {0,0,&_44u1__p5_0},
  152977. {&_44u1__p6_0,&_44u1__p6_1},
  152978. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  152979. }
  152980. };
  152981. static static_bookblock _resbook_44u_2={
  152982. {
  152983. {0},
  152984. {0,0,&_44u2__p1_0},
  152985. {0,0,&_44u2__p2_0},
  152986. {0,0,&_44u2__p3_0},
  152987. {0,0,&_44u2__p4_0},
  152988. {0,0,&_44u2__p5_0},
  152989. {&_44u2__p6_0,&_44u2__p6_1},
  152990. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  152991. }
  152992. };
  152993. static static_bookblock _resbook_44u_3={
  152994. {
  152995. {0},
  152996. {0,0,&_44u3__p1_0},
  152997. {0,0,&_44u3__p2_0},
  152998. {0,0,&_44u3__p3_0},
  152999. {0,0,&_44u3__p4_0},
  153000. {0,0,&_44u3__p5_0},
  153001. {&_44u3__p6_0,&_44u3__p6_1},
  153002. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  153003. }
  153004. };
  153005. static static_bookblock _resbook_44u_4={
  153006. {
  153007. {0},
  153008. {0,0,&_44u4__p1_0},
  153009. {0,0,&_44u4__p2_0},
  153010. {0,0,&_44u4__p3_0},
  153011. {0,0,&_44u4__p4_0},
  153012. {0,0,&_44u4__p5_0},
  153013. {&_44u4__p6_0,&_44u4__p6_1},
  153014. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  153015. }
  153016. };
  153017. static static_bookblock _resbook_44u_5={
  153018. {
  153019. {0},
  153020. {0,0,&_44u5__p1_0},
  153021. {0,0,&_44u5__p2_0},
  153022. {0,0,&_44u5__p3_0},
  153023. {0,0,&_44u5__p4_0},
  153024. {0,0,&_44u5__p5_0},
  153025. {0,0,&_44u5__p6_0},
  153026. {&_44u5__p7_0,&_44u5__p7_1},
  153027. {&_44u5__p8_0,&_44u5__p8_1},
  153028. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153029. }
  153030. };
  153031. static static_bookblock _resbook_44u_6={
  153032. {
  153033. {0},
  153034. {0,0,&_44u6__p1_0},
  153035. {0,0,&_44u6__p2_0},
  153036. {0,0,&_44u6__p3_0},
  153037. {0,0,&_44u6__p4_0},
  153038. {0,0,&_44u6__p5_0},
  153039. {0,0,&_44u6__p6_0},
  153040. {&_44u6__p7_0,&_44u6__p7_1},
  153041. {&_44u6__p8_0,&_44u6__p8_1},
  153042. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153043. }
  153044. };
  153045. static static_bookblock _resbook_44u_7={
  153046. {
  153047. {0},
  153048. {0,0,&_44u7__p1_0},
  153049. {0,0,&_44u7__p2_0},
  153050. {0,0,&_44u7__p3_0},
  153051. {0,0,&_44u7__p4_0},
  153052. {0,0,&_44u7__p5_0},
  153053. {0,0,&_44u7__p6_0},
  153054. {&_44u7__p7_0,&_44u7__p7_1},
  153055. {&_44u7__p8_0,&_44u7__p8_1},
  153056. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153057. }
  153058. };
  153059. static static_bookblock _resbook_44u_8={
  153060. {
  153061. {0},
  153062. {0,0,&_44u8_p1_0},
  153063. {0,0,&_44u8_p2_0},
  153064. {0,0,&_44u8_p3_0},
  153065. {0,0,&_44u8_p4_0},
  153066. {&_44u8_p5_0,&_44u8_p5_1},
  153067. {&_44u8_p6_0,&_44u8_p6_1},
  153068. {&_44u8_p7_0,&_44u8_p7_1},
  153069. {&_44u8_p8_0,&_44u8_p8_1},
  153070. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153071. }
  153072. };
  153073. static static_bookblock _resbook_44u_9={
  153074. {
  153075. {0},
  153076. {0,0,&_44u9_p1_0},
  153077. {0,0,&_44u9_p2_0},
  153078. {0,0,&_44u9_p3_0},
  153079. {0,0,&_44u9_p4_0},
  153080. {&_44u9_p5_0,&_44u9_p5_1},
  153081. {&_44u9_p6_0,&_44u9_p6_1},
  153082. {&_44u9_p7_0,&_44u9_p7_1},
  153083. {&_44u9_p8_0,&_44u9_p8_1},
  153084. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153085. }
  153086. };
  153087. static vorbis_residue_template _res_44u_n1[]={
  153088. {1,0, &_residue_44_low_un,
  153089. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153090. &_resbook_44u_n1,&_resbook_44u_n1},
  153091. {1,0, &_residue_44_low_un,
  153092. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153093. &_resbook_44u_n1,&_resbook_44u_n1}
  153094. };
  153095. static vorbis_residue_template _res_44u_0[]={
  153096. {1,0, &_residue_44_low_un,
  153097. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153098. &_resbook_44u_0,&_resbook_44u_0},
  153099. {1,0, &_residue_44_low_un,
  153100. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153101. &_resbook_44u_0,&_resbook_44u_0}
  153102. };
  153103. static vorbis_residue_template _res_44u_1[]={
  153104. {1,0, &_residue_44_low_un,
  153105. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153106. &_resbook_44u_1,&_resbook_44u_1},
  153107. {1,0, &_residue_44_low_un,
  153108. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153109. &_resbook_44u_1,&_resbook_44u_1}
  153110. };
  153111. static vorbis_residue_template _res_44u_2[]={
  153112. {1,0, &_residue_44_low_un,
  153113. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153114. &_resbook_44u_2,&_resbook_44u_2},
  153115. {1,0, &_residue_44_low_un,
  153116. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153117. &_resbook_44u_2,&_resbook_44u_2}
  153118. };
  153119. static vorbis_residue_template _res_44u_3[]={
  153120. {1,0, &_residue_44_low_un,
  153121. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153122. &_resbook_44u_3,&_resbook_44u_3},
  153123. {1,0, &_residue_44_low_un,
  153124. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153125. &_resbook_44u_3,&_resbook_44u_3}
  153126. };
  153127. static vorbis_residue_template _res_44u_4[]={
  153128. {1,0, &_residue_44_low_un,
  153129. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153130. &_resbook_44u_4,&_resbook_44u_4},
  153131. {1,0, &_residue_44_low_un,
  153132. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153133. &_resbook_44u_4,&_resbook_44u_4}
  153134. };
  153135. static vorbis_residue_template _res_44u_5[]={
  153136. {1,0, &_residue_44_mid_un,
  153137. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153138. &_resbook_44u_5,&_resbook_44u_5},
  153139. {1,0, &_residue_44_mid_un,
  153140. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153141. &_resbook_44u_5,&_resbook_44u_5}
  153142. };
  153143. static vorbis_residue_template _res_44u_6[]={
  153144. {1,0, &_residue_44_mid_un,
  153145. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153146. &_resbook_44u_6,&_resbook_44u_6},
  153147. {1,0, &_residue_44_mid_un,
  153148. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153149. &_resbook_44u_6,&_resbook_44u_6}
  153150. };
  153151. static vorbis_residue_template _res_44u_7[]={
  153152. {1,0, &_residue_44_mid_un,
  153153. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153154. &_resbook_44u_7,&_resbook_44u_7},
  153155. {1,0, &_residue_44_mid_un,
  153156. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153157. &_resbook_44u_7,&_resbook_44u_7}
  153158. };
  153159. static vorbis_residue_template _res_44u_8[]={
  153160. {1,0, &_residue_44_hi_un,
  153161. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153162. &_resbook_44u_8,&_resbook_44u_8},
  153163. {1,0, &_residue_44_hi_un,
  153164. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153165. &_resbook_44u_8,&_resbook_44u_8}
  153166. };
  153167. static vorbis_residue_template _res_44u_9[]={
  153168. {1,0, &_residue_44_hi_un,
  153169. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153170. &_resbook_44u_9,&_resbook_44u_9},
  153171. {1,0, &_residue_44_hi_un,
  153172. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153173. &_resbook_44u_9,&_resbook_44u_9}
  153174. };
  153175. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153176. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153177. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153178. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153179. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153180. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153181. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153182. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153183. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153184. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153185. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153186. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153187. };
  153188. /*** End of inlined file: residue_44u.h ***/
  153189. static double rate_mapping_44_un[12]={
  153190. 32000.,48000.,60000.,70000.,80000.,86000.,
  153191. 96000.,110000.,120000.,140000.,160000.,240001.
  153192. };
  153193. ve_setup_data_template ve_setup_44_uncoupled={
  153194. 11,
  153195. rate_mapping_44_un,
  153196. quality_mapping_44,
  153197. -1,
  153198. 40000,
  153199. 50000,
  153200. blocksize_short_44,
  153201. blocksize_long_44,
  153202. _psy_tone_masteratt_44,
  153203. _psy_tone_0dB,
  153204. _psy_tone_suppress,
  153205. _vp_tonemask_adj_otherblock,
  153206. _vp_tonemask_adj_longblock,
  153207. _vp_tonemask_adj_otherblock,
  153208. _psy_noiseguards_44,
  153209. _psy_noisebias_impulse,
  153210. _psy_noisebias_padding,
  153211. _psy_noisebias_trans,
  153212. _psy_noisebias_long,
  153213. _psy_noise_suppress,
  153214. _psy_compand_44,
  153215. _psy_compand_short_mapping,
  153216. _psy_compand_long_mapping,
  153217. {_noise_start_short_44,_noise_start_long_44},
  153218. {_noise_part_short_44,_noise_part_long_44},
  153219. _noise_thresh_44,
  153220. _psy_ath_floater,
  153221. _psy_ath_abs,
  153222. _psy_lowpass_44,
  153223. _psy_global_44,
  153224. _global_mapping_44,
  153225. NULL,
  153226. _floor_books,
  153227. _floor,
  153228. _floor_short_mapping_44,
  153229. _floor_long_mapping_44,
  153230. _mapres_template_44_uncoupled
  153231. };
  153232. /*** End of inlined file: setup_44u.h ***/
  153233. /*** Start of inlined file: setup_32.h ***/
  153234. static double rate_mapping_32[12]={
  153235. 18000.,28000.,35000.,45000.,56000.,60000.,
  153236. 75000.,90000.,100000.,115000.,150000.,190000.,
  153237. };
  153238. static double rate_mapping_32_un[12]={
  153239. 30000.,42000.,52000.,64000.,72000.,78000.,
  153240. 86000.,92000.,110000.,120000.,140000.,190000.,
  153241. };
  153242. static double _psy_lowpass_32[12]={
  153243. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153244. };
  153245. ve_setup_data_template ve_setup_32_stereo={
  153246. 11,
  153247. rate_mapping_32,
  153248. quality_mapping_44,
  153249. 2,
  153250. 26000,
  153251. 40000,
  153252. blocksize_short_44,
  153253. blocksize_long_44,
  153254. _psy_tone_masteratt_44,
  153255. _psy_tone_0dB,
  153256. _psy_tone_suppress,
  153257. _vp_tonemask_adj_otherblock,
  153258. _vp_tonemask_adj_longblock,
  153259. _vp_tonemask_adj_otherblock,
  153260. _psy_noiseguards_44,
  153261. _psy_noisebias_impulse,
  153262. _psy_noisebias_padding,
  153263. _psy_noisebias_trans,
  153264. _psy_noisebias_long,
  153265. _psy_noise_suppress,
  153266. _psy_compand_44,
  153267. _psy_compand_short_mapping,
  153268. _psy_compand_long_mapping,
  153269. {_noise_start_short_44,_noise_start_long_44},
  153270. {_noise_part_short_44,_noise_part_long_44},
  153271. _noise_thresh_44,
  153272. _psy_ath_floater,
  153273. _psy_ath_abs,
  153274. _psy_lowpass_32,
  153275. _psy_global_44,
  153276. _global_mapping_44,
  153277. _psy_stereo_modes_44,
  153278. _floor_books,
  153279. _floor,
  153280. _floor_short_mapping_44,
  153281. _floor_long_mapping_44,
  153282. _mapres_template_44_stereo
  153283. };
  153284. ve_setup_data_template ve_setup_32_uncoupled={
  153285. 11,
  153286. rate_mapping_32_un,
  153287. quality_mapping_44,
  153288. -1,
  153289. 26000,
  153290. 40000,
  153291. blocksize_short_44,
  153292. blocksize_long_44,
  153293. _psy_tone_masteratt_44,
  153294. _psy_tone_0dB,
  153295. _psy_tone_suppress,
  153296. _vp_tonemask_adj_otherblock,
  153297. _vp_tonemask_adj_longblock,
  153298. _vp_tonemask_adj_otherblock,
  153299. _psy_noiseguards_44,
  153300. _psy_noisebias_impulse,
  153301. _psy_noisebias_padding,
  153302. _psy_noisebias_trans,
  153303. _psy_noisebias_long,
  153304. _psy_noise_suppress,
  153305. _psy_compand_44,
  153306. _psy_compand_short_mapping,
  153307. _psy_compand_long_mapping,
  153308. {_noise_start_short_44,_noise_start_long_44},
  153309. {_noise_part_short_44,_noise_part_long_44},
  153310. _noise_thresh_44,
  153311. _psy_ath_floater,
  153312. _psy_ath_abs,
  153313. _psy_lowpass_32,
  153314. _psy_global_44,
  153315. _global_mapping_44,
  153316. NULL,
  153317. _floor_books,
  153318. _floor,
  153319. _floor_short_mapping_44,
  153320. _floor_long_mapping_44,
  153321. _mapres_template_44_uncoupled
  153322. };
  153323. /*** End of inlined file: setup_32.h ***/
  153324. /*** Start of inlined file: setup_8.h ***/
  153325. /*** Start of inlined file: psych_8.h ***/
  153326. static att3 _psy_tone_masteratt_8[3]={
  153327. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153328. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153329. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153330. };
  153331. static vp_adjblock _vp_tonemask_adj_8[3]={
  153332. /* adjust for mode zero */
  153333. /* 63 125 250 500 1 2 4 8 16 */
  153334. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153335. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153336. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153337. };
  153338. static noise3 _psy_noisebias_8[3]={
  153339. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153340. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153341. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153342. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153343. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153344. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153345. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153346. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153347. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153348. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153349. };
  153350. /* stereo mode by base quality level */
  153351. static adj_stereo _psy_stereo_modes_8[3]={
  153352. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153353. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153354. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153355. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153356. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153357. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153358. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153359. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153360. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153361. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153362. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153363. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153364. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153365. };
  153366. static noiseguard _psy_noiseguards_8[2]={
  153367. {10,10,-1},
  153368. {10,10,-1},
  153369. };
  153370. static compandblock _psy_compand_8[2]={
  153371. {{
  153372. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153373. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153374. 12,12,13,13,14,14,15, 15, /* 23dB */
  153375. 16,16,17,17,17,18,18, 19, /* 31dB */
  153376. 19,19,20,21,22,23,24, 25, /* 39dB */
  153377. }},
  153378. {{
  153379. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153380. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153381. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153382. 9,10,11,12,13,14,15, 16, /* 31dB */
  153383. 17,18,19,20,21,22,23, 24, /* 39dB */
  153384. }},
  153385. };
  153386. static double _psy_lowpass_8[3]={3.,4.,4.};
  153387. static int _noise_start_8[2]={
  153388. 64,64,
  153389. };
  153390. static int _noise_part_8[2]={
  153391. 8,8,
  153392. };
  153393. static int _psy_ath_floater_8[3]={
  153394. -100,-100,-105,
  153395. };
  153396. static int _psy_ath_abs_8[3]={
  153397. -130,-130,-140,
  153398. };
  153399. /*** End of inlined file: psych_8.h ***/
  153400. /*** Start of inlined file: residue_8.h ***/
  153401. /***** residue backends *********************************************/
  153402. static static_bookblock _resbook_8s_0={
  153403. {
  153404. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153405. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153406. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153407. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153408. }
  153409. };
  153410. static static_bookblock _resbook_8s_1={
  153411. {
  153412. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153413. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153414. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153415. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153416. }
  153417. };
  153418. static vorbis_residue_template _res_8s_0[]={
  153419. {2,0, &_residue_44_mid,
  153420. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153421. &_resbook_8s_0,&_resbook_8s_0},
  153422. };
  153423. static vorbis_residue_template _res_8s_1[]={
  153424. {2,0, &_residue_44_mid,
  153425. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153426. &_resbook_8s_1,&_resbook_8s_1},
  153427. };
  153428. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153429. { _map_nominal, _res_8s_0 }, /* 0 */
  153430. { _map_nominal, _res_8s_1 }, /* 1 */
  153431. };
  153432. static static_bookblock _resbook_8u_0={
  153433. {
  153434. {0},
  153435. {0,0,&_8u0__p1_0},
  153436. {0,0,&_8u0__p2_0},
  153437. {0,0,&_8u0__p3_0},
  153438. {0,0,&_8u0__p4_0},
  153439. {0,0,&_8u0__p5_0},
  153440. {&_8u0__p6_0,&_8u0__p6_1},
  153441. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153442. }
  153443. };
  153444. static static_bookblock _resbook_8u_1={
  153445. {
  153446. {0},
  153447. {0,0,&_8u1__p1_0},
  153448. {0,0,&_8u1__p2_0},
  153449. {0,0,&_8u1__p3_0},
  153450. {0,0,&_8u1__p4_0},
  153451. {0,0,&_8u1__p5_0},
  153452. {0,0,&_8u1__p6_0},
  153453. {&_8u1__p7_0,&_8u1__p7_1},
  153454. {&_8u1__p8_0,&_8u1__p8_1},
  153455. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153456. }
  153457. };
  153458. static vorbis_residue_template _res_8u_0[]={
  153459. {1,0, &_residue_44_low_un,
  153460. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153461. &_resbook_8u_0,&_resbook_8u_0},
  153462. };
  153463. static vorbis_residue_template _res_8u_1[]={
  153464. {1,0, &_residue_44_mid_un,
  153465. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153466. &_resbook_8u_1,&_resbook_8u_1},
  153467. };
  153468. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153469. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153470. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153471. };
  153472. /*** End of inlined file: residue_8.h ***/
  153473. static int blocksize_8[2]={
  153474. 512,512
  153475. };
  153476. static int _floor_mapping_8[2]={
  153477. 6,6,
  153478. };
  153479. static double rate_mapping_8[3]={
  153480. 6000.,9000.,32000.,
  153481. };
  153482. static double rate_mapping_8_uncoupled[3]={
  153483. 8000.,14000.,42000.,
  153484. };
  153485. static double quality_mapping_8[3]={
  153486. -.1,.0,1.
  153487. };
  153488. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153489. static double _global_mapping_8[3]={ 1., 2., 3. };
  153490. ve_setup_data_template ve_setup_8_stereo={
  153491. 2,
  153492. rate_mapping_8,
  153493. quality_mapping_8,
  153494. 2,
  153495. 8000,
  153496. 9000,
  153497. blocksize_8,
  153498. blocksize_8,
  153499. _psy_tone_masteratt_8,
  153500. _psy_tone_0dB,
  153501. _psy_tone_suppress,
  153502. _vp_tonemask_adj_8,
  153503. NULL,
  153504. _vp_tonemask_adj_8,
  153505. _psy_noiseguards_8,
  153506. _psy_noisebias_8,
  153507. _psy_noisebias_8,
  153508. NULL,
  153509. NULL,
  153510. _psy_noise_suppress,
  153511. _psy_compand_8,
  153512. _psy_compand_8_mapping,
  153513. NULL,
  153514. {_noise_start_8,_noise_start_8},
  153515. {_noise_part_8,_noise_part_8},
  153516. _noise_thresh_5only,
  153517. _psy_ath_floater_8,
  153518. _psy_ath_abs_8,
  153519. _psy_lowpass_8,
  153520. _psy_global_44,
  153521. _global_mapping_8,
  153522. _psy_stereo_modes_8,
  153523. _floor_books,
  153524. _floor,
  153525. _floor_mapping_8,
  153526. NULL,
  153527. _mapres_template_8_stereo
  153528. };
  153529. ve_setup_data_template ve_setup_8_uncoupled={
  153530. 2,
  153531. rate_mapping_8_uncoupled,
  153532. quality_mapping_8,
  153533. -1,
  153534. 8000,
  153535. 9000,
  153536. blocksize_8,
  153537. blocksize_8,
  153538. _psy_tone_masteratt_8,
  153539. _psy_tone_0dB,
  153540. _psy_tone_suppress,
  153541. _vp_tonemask_adj_8,
  153542. NULL,
  153543. _vp_tonemask_adj_8,
  153544. _psy_noiseguards_8,
  153545. _psy_noisebias_8,
  153546. _psy_noisebias_8,
  153547. NULL,
  153548. NULL,
  153549. _psy_noise_suppress,
  153550. _psy_compand_8,
  153551. _psy_compand_8_mapping,
  153552. NULL,
  153553. {_noise_start_8,_noise_start_8},
  153554. {_noise_part_8,_noise_part_8},
  153555. _noise_thresh_5only,
  153556. _psy_ath_floater_8,
  153557. _psy_ath_abs_8,
  153558. _psy_lowpass_8,
  153559. _psy_global_44,
  153560. _global_mapping_8,
  153561. _psy_stereo_modes_8,
  153562. _floor_books,
  153563. _floor,
  153564. _floor_mapping_8,
  153565. NULL,
  153566. _mapres_template_8_uncoupled
  153567. };
  153568. /*** End of inlined file: setup_8.h ***/
  153569. /*** Start of inlined file: setup_11.h ***/
  153570. /*** Start of inlined file: psych_11.h ***/
  153571. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  153572. static att3 _psy_tone_masteratt_11[3]={
  153573. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153574. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153575. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153576. };
  153577. static vp_adjblock _vp_tonemask_adj_11[3]={
  153578. /* adjust for mode zero */
  153579. /* 63 125 250 500 1 2 4 8 16 */
  153580. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  153581. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  153582. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  153583. };
  153584. static noise3 _psy_noisebias_11[3]={
  153585. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153586. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153587. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  153588. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153589. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153590. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153591. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153592. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153593. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153594. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153595. };
  153596. static double _noise_thresh_11[3]={ .3,.5,.5 };
  153597. /*** End of inlined file: psych_11.h ***/
  153598. static int blocksize_11[2]={
  153599. 512,512
  153600. };
  153601. static int _floor_mapping_11[2]={
  153602. 6,6,
  153603. };
  153604. static double rate_mapping_11[3]={
  153605. 8000.,13000.,44000.,
  153606. };
  153607. static double rate_mapping_11_uncoupled[3]={
  153608. 12000.,20000.,50000.,
  153609. };
  153610. static double quality_mapping_11[3]={
  153611. -.1,.0,1.
  153612. };
  153613. ve_setup_data_template ve_setup_11_stereo={
  153614. 2,
  153615. rate_mapping_11,
  153616. quality_mapping_11,
  153617. 2,
  153618. 9000,
  153619. 15000,
  153620. blocksize_11,
  153621. blocksize_11,
  153622. _psy_tone_masteratt_11,
  153623. _psy_tone_0dB,
  153624. _psy_tone_suppress,
  153625. _vp_tonemask_adj_11,
  153626. NULL,
  153627. _vp_tonemask_adj_11,
  153628. _psy_noiseguards_8,
  153629. _psy_noisebias_11,
  153630. _psy_noisebias_11,
  153631. NULL,
  153632. NULL,
  153633. _psy_noise_suppress,
  153634. _psy_compand_8,
  153635. _psy_compand_8_mapping,
  153636. NULL,
  153637. {_noise_start_8,_noise_start_8},
  153638. {_noise_part_8,_noise_part_8},
  153639. _noise_thresh_11,
  153640. _psy_ath_floater_8,
  153641. _psy_ath_abs_8,
  153642. _psy_lowpass_11,
  153643. _psy_global_44,
  153644. _global_mapping_8,
  153645. _psy_stereo_modes_8,
  153646. _floor_books,
  153647. _floor,
  153648. _floor_mapping_11,
  153649. NULL,
  153650. _mapres_template_8_stereo
  153651. };
  153652. ve_setup_data_template ve_setup_11_uncoupled={
  153653. 2,
  153654. rate_mapping_11_uncoupled,
  153655. quality_mapping_11,
  153656. -1,
  153657. 9000,
  153658. 15000,
  153659. blocksize_11,
  153660. blocksize_11,
  153661. _psy_tone_masteratt_11,
  153662. _psy_tone_0dB,
  153663. _psy_tone_suppress,
  153664. _vp_tonemask_adj_11,
  153665. NULL,
  153666. _vp_tonemask_adj_11,
  153667. _psy_noiseguards_8,
  153668. _psy_noisebias_11,
  153669. _psy_noisebias_11,
  153670. NULL,
  153671. NULL,
  153672. _psy_noise_suppress,
  153673. _psy_compand_8,
  153674. _psy_compand_8_mapping,
  153675. NULL,
  153676. {_noise_start_8,_noise_start_8},
  153677. {_noise_part_8,_noise_part_8},
  153678. _noise_thresh_11,
  153679. _psy_ath_floater_8,
  153680. _psy_ath_abs_8,
  153681. _psy_lowpass_11,
  153682. _psy_global_44,
  153683. _global_mapping_8,
  153684. _psy_stereo_modes_8,
  153685. _floor_books,
  153686. _floor,
  153687. _floor_mapping_11,
  153688. NULL,
  153689. _mapres_template_8_uncoupled
  153690. };
  153691. /*** End of inlined file: setup_11.h ***/
  153692. /*** Start of inlined file: setup_16.h ***/
  153693. /*** Start of inlined file: psych_16.h ***/
  153694. /* stereo mode by base quality level */
  153695. static adj_stereo _psy_stereo_modes_16[4]={
  153696. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153697. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153698. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153699. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  153700. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153701. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153702. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153703. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  153704. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153705. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153706. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153707. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153708. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153709. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153710. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153711. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  153712. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153713. };
  153714. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  153715. static att3 _psy_tone_masteratt_16[4]={
  153716. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153717. {{ 25, 22, 12}, 0, 0}, /* 0 */
  153718. {{ 20, 12, 0}, 0, 0}, /* 0 */
  153719. {{ 15, 0, -14}, 0, 0}, /* 0 */
  153720. };
  153721. static vp_adjblock _vp_tonemask_adj_16[4]={
  153722. /* adjust for mode zero */
  153723. /* 63 125 250 500 1 2 4 8 16 */
  153724. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  153725. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  153726. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153727. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153728. };
  153729. static noise3 _psy_noisebias_16_short[4]={
  153730. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153731. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153732. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153733. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153734. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153735. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  153736. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153737. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153738. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  153739. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153740. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153741. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153742. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153743. };
  153744. static noise3 _psy_noisebias_16_impulse[4]={
  153745. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153746. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153747. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153748. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153749. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  153750. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  153751. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153752. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  153753. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  153754. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153755. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153756. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  153757. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153758. };
  153759. static noise3 _psy_noisebias_16[4]={
  153760. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153761. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  153762. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153763. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153764. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153765. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153766. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153767. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153768. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  153769. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153770. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153771. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153772. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153773. };
  153774. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  153775. static int _noise_start_16[3]={ 256,256,9999 };
  153776. static int _noise_part_16[4]={ 8,8,8,8 };
  153777. static int _psy_ath_floater_16[4]={
  153778. -100,-100,-100,-105,
  153779. };
  153780. static int _psy_ath_abs_16[4]={
  153781. -130,-130,-130,-140,
  153782. };
  153783. /*** End of inlined file: psych_16.h ***/
  153784. /*** Start of inlined file: residue_16.h ***/
  153785. /***** residue backends *********************************************/
  153786. static static_bookblock _resbook_16s_0={
  153787. {
  153788. {0},
  153789. {0,0,&_16c0_s_p1_0},
  153790. {0,0,&_16c0_s_p2_0},
  153791. {0,0,&_16c0_s_p3_0},
  153792. {0,0,&_16c0_s_p4_0},
  153793. {0,0,&_16c0_s_p5_0},
  153794. {0,0,&_16c0_s_p6_0},
  153795. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  153796. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  153797. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  153798. }
  153799. };
  153800. static static_bookblock _resbook_16s_1={
  153801. {
  153802. {0},
  153803. {0,0,&_16c1_s_p1_0},
  153804. {0,0,&_16c1_s_p2_0},
  153805. {0,0,&_16c1_s_p3_0},
  153806. {0,0,&_16c1_s_p4_0},
  153807. {0,0,&_16c1_s_p5_0},
  153808. {0,0,&_16c1_s_p6_0},
  153809. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  153810. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  153811. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  153812. }
  153813. };
  153814. static static_bookblock _resbook_16s_2={
  153815. {
  153816. {0},
  153817. {0,0,&_16c2_s_p1_0},
  153818. {0,0,&_16c2_s_p2_0},
  153819. {0,0,&_16c2_s_p3_0},
  153820. {0,0,&_16c2_s_p4_0},
  153821. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  153822. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  153823. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  153824. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  153825. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  153826. }
  153827. };
  153828. static vorbis_residue_template _res_16s_0[]={
  153829. {2,0, &_residue_44_mid,
  153830. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  153831. &_resbook_16s_0,&_resbook_16s_0},
  153832. };
  153833. static vorbis_residue_template _res_16s_1[]={
  153834. {2,0, &_residue_44_mid,
  153835. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  153836. &_resbook_16s_1,&_resbook_16s_1},
  153837. {2,0, &_residue_44_mid,
  153838. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  153839. &_resbook_16s_1,&_resbook_16s_1}
  153840. };
  153841. static vorbis_residue_template _res_16s_2[]={
  153842. {2,0, &_residue_44_high,
  153843. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  153844. &_resbook_16s_2,&_resbook_16s_2},
  153845. {2,0, &_residue_44_high,
  153846. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  153847. &_resbook_16s_2,&_resbook_16s_2}
  153848. };
  153849. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  153850. { _map_nominal, _res_16s_0 }, /* 0 */
  153851. { _map_nominal, _res_16s_1 }, /* 1 */
  153852. { _map_nominal, _res_16s_2 }, /* 2 */
  153853. };
  153854. static static_bookblock _resbook_16u_0={
  153855. {
  153856. {0},
  153857. {0,0,&_16u0__p1_0},
  153858. {0,0,&_16u0__p2_0},
  153859. {0,0,&_16u0__p3_0},
  153860. {0,0,&_16u0__p4_0},
  153861. {0,0,&_16u0__p5_0},
  153862. {&_16u0__p6_0,&_16u0__p6_1},
  153863. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  153864. }
  153865. };
  153866. static static_bookblock _resbook_16u_1={
  153867. {
  153868. {0},
  153869. {0,0,&_16u1__p1_0},
  153870. {0,0,&_16u1__p2_0},
  153871. {0,0,&_16u1__p3_0},
  153872. {0,0,&_16u1__p4_0},
  153873. {0,0,&_16u1__p5_0},
  153874. {0,0,&_16u1__p6_0},
  153875. {&_16u1__p7_0,&_16u1__p7_1},
  153876. {&_16u1__p8_0,&_16u1__p8_1},
  153877. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  153878. }
  153879. };
  153880. static static_bookblock _resbook_16u_2={
  153881. {
  153882. {0},
  153883. {0,0,&_16u2_p1_0},
  153884. {0,0,&_16u2_p2_0},
  153885. {0,0,&_16u2_p3_0},
  153886. {0,0,&_16u2_p4_0},
  153887. {&_16u2_p5_0,&_16u2_p5_1},
  153888. {&_16u2_p6_0,&_16u2_p6_1},
  153889. {&_16u2_p7_0,&_16u2_p7_1},
  153890. {&_16u2_p8_0,&_16u2_p8_1},
  153891. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  153892. }
  153893. };
  153894. static vorbis_residue_template _res_16u_0[]={
  153895. {1,0, &_residue_44_low_un,
  153896. &_huff_book__16u0__single,&_huff_book__16u0__single,
  153897. &_resbook_16u_0,&_resbook_16u_0},
  153898. };
  153899. static vorbis_residue_template _res_16u_1[]={
  153900. {1,0, &_residue_44_mid_un,
  153901. &_huff_book__16u1__short,&_huff_book__16u1__short,
  153902. &_resbook_16u_1,&_resbook_16u_1},
  153903. {1,0, &_residue_44_mid_un,
  153904. &_huff_book__16u1__long,&_huff_book__16u1__long,
  153905. &_resbook_16u_1,&_resbook_16u_1}
  153906. };
  153907. static vorbis_residue_template _res_16u_2[]={
  153908. {1,0, &_residue_44_hi_un,
  153909. &_huff_book__16u2__short,&_huff_book__16u2__short,
  153910. &_resbook_16u_2,&_resbook_16u_2},
  153911. {1,0, &_residue_44_hi_un,
  153912. &_huff_book__16u2__long,&_huff_book__16u2__long,
  153913. &_resbook_16u_2,&_resbook_16u_2}
  153914. };
  153915. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  153916. { _map_nominal_u, _res_16u_0 }, /* 0 */
  153917. { _map_nominal_u, _res_16u_1 }, /* 1 */
  153918. { _map_nominal_u, _res_16u_2 }, /* 2 */
  153919. };
  153920. /*** End of inlined file: residue_16.h ***/
  153921. static int blocksize_16_short[3]={
  153922. 1024,512,512
  153923. };
  153924. static int blocksize_16_long[3]={
  153925. 1024,1024,1024
  153926. };
  153927. static int _floor_mapping_16_short[3]={
  153928. 9,3,3
  153929. };
  153930. static int _floor_mapping_16[3]={
  153931. 9,9,9
  153932. };
  153933. static double rate_mapping_16[4]={
  153934. 12000.,20000.,44000.,86000.
  153935. };
  153936. static double rate_mapping_16_uncoupled[4]={
  153937. 16000.,28000.,64000.,100000.
  153938. };
  153939. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  153940. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  153941. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  153942. ve_setup_data_template ve_setup_16_stereo={
  153943. 3,
  153944. rate_mapping_16,
  153945. quality_mapping_16,
  153946. 2,
  153947. 15000,
  153948. 19000,
  153949. blocksize_16_short,
  153950. blocksize_16_long,
  153951. _psy_tone_masteratt_16,
  153952. _psy_tone_0dB,
  153953. _psy_tone_suppress,
  153954. _vp_tonemask_adj_16,
  153955. _vp_tonemask_adj_16,
  153956. _vp_tonemask_adj_16,
  153957. _psy_noiseguards_8,
  153958. _psy_noisebias_16_impulse,
  153959. _psy_noisebias_16_short,
  153960. _psy_noisebias_16_short,
  153961. _psy_noisebias_16,
  153962. _psy_noise_suppress,
  153963. _psy_compand_8,
  153964. _psy_compand_16_mapping,
  153965. _psy_compand_16_mapping,
  153966. {_noise_start_16,_noise_start_16},
  153967. { _noise_part_16, _noise_part_16},
  153968. _noise_thresh_16,
  153969. _psy_ath_floater_16,
  153970. _psy_ath_abs_16,
  153971. _psy_lowpass_16,
  153972. _psy_global_44,
  153973. _global_mapping_16,
  153974. _psy_stereo_modes_16,
  153975. _floor_books,
  153976. _floor,
  153977. _floor_mapping_16_short,
  153978. _floor_mapping_16,
  153979. _mapres_template_16_stereo
  153980. };
  153981. ve_setup_data_template ve_setup_16_uncoupled={
  153982. 3,
  153983. rate_mapping_16_uncoupled,
  153984. quality_mapping_16,
  153985. -1,
  153986. 15000,
  153987. 19000,
  153988. blocksize_16_short,
  153989. blocksize_16_long,
  153990. _psy_tone_masteratt_16,
  153991. _psy_tone_0dB,
  153992. _psy_tone_suppress,
  153993. _vp_tonemask_adj_16,
  153994. _vp_tonemask_adj_16,
  153995. _vp_tonemask_adj_16,
  153996. _psy_noiseguards_8,
  153997. _psy_noisebias_16_impulse,
  153998. _psy_noisebias_16_short,
  153999. _psy_noisebias_16_short,
  154000. _psy_noisebias_16,
  154001. _psy_noise_suppress,
  154002. _psy_compand_8,
  154003. _psy_compand_16_mapping,
  154004. _psy_compand_16_mapping,
  154005. {_noise_start_16,_noise_start_16},
  154006. { _noise_part_16, _noise_part_16},
  154007. _noise_thresh_16,
  154008. _psy_ath_floater_16,
  154009. _psy_ath_abs_16,
  154010. _psy_lowpass_16,
  154011. _psy_global_44,
  154012. _global_mapping_16,
  154013. _psy_stereo_modes_16,
  154014. _floor_books,
  154015. _floor,
  154016. _floor_mapping_16_short,
  154017. _floor_mapping_16,
  154018. _mapres_template_16_uncoupled
  154019. };
  154020. /*** End of inlined file: setup_16.h ***/
  154021. /*** Start of inlined file: setup_22.h ***/
  154022. static double rate_mapping_22[4]={
  154023. 15000.,20000.,44000.,86000.
  154024. };
  154025. static double rate_mapping_22_uncoupled[4]={
  154026. 16000.,28000.,50000.,90000.
  154027. };
  154028. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154029. ve_setup_data_template ve_setup_22_stereo={
  154030. 3,
  154031. rate_mapping_22,
  154032. quality_mapping_16,
  154033. 2,
  154034. 19000,
  154035. 26000,
  154036. blocksize_16_short,
  154037. blocksize_16_long,
  154038. _psy_tone_masteratt_16,
  154039. _psy_tone_0dB,
  154040. _psy_tone_suppress,
  154041. _vp_tonemask_adj_16,
  154042. _vp_tonemask_adj_16,
  154043. _vp_tonemask_adj_16,
  154044. _psy_noiseguards_8,
  154045. _psy_noisebias_16_impulse,
  154046. _psy_noisebias_16_short,
  154047. _psy_noisebias_16_short,
  154048. _psy_noisebias_16,
  154049. _psy_noise_suppress,
  154050. _psy_compand_8,
  154051. _psy_compand_8_mapping,
  154052. _psy_compand_8_mapping,
  154053. {_noise_start_16,_noise_start_16},
  154054. { _noise_part_16, _noise_part_16},
  154055. _noise_thresh_16,
  154056. _psy_ath_floater_16,
  154057. _psy_ath_abs_16,
  154058. _psy_lowpass_22,
  154059. _psy_global_44,
  154060. _global_mapping_16,
  154061. _psy_stereo_modes_16,
  154062. _floor_books,
  154063. _floor,
  154064. _floor_mapping_16_short,
  154065. _floor_mapping_16,
  154066. _mapres_template_16_stereo
  154067. };
  154068. ve_setup_data_template ve_setup_22_uncoupled={
  154069. 3,
  154070. rate_mapping_22_uncoupled,
  154071. quality_mapping_16,
  154072. -1,
  154073. 19000,
  154074. 26000,
  154075. blocksize_16_short,
  154076. blocksize_16_long,
  154077. _psy_tone_masteratt_16,
  154078. _psy_tone_0dB,
  154079. _psy_tone_suppress,
  154080. _vp_tonemask_adj_16,
  154081. _vp_tonemask_adj_16,
  154082. _vp_tonemask_adj_16,
  154083. _psy_noiseguards_8,
  154084. _psy_noisebias_16_impulse,
  154085. _psy_noisebias_16_short,
  154086. _psy_noisebias_16_short,
  154087. _psy_noisebias_16,
  154088. _psy_noise_suppress,
  154089. _psy_compand_8,
  154090. _psy_compand_8_mapping,
  154091. _psy_compand_8_mapping,
  154092. {_noise_start_16,_noise_start_16},
  154093. { _noise_part_16, _noise_part_16},
  154094. _noise_thresh_16,
  154095. _psy_ath_floater_16,
  154096. _psy_ath_abs_16,
  154097. _psy_lowpass_22,
  154098. _psy_global_44,
  154099. _global_mapping_16,
  154100. _psy_stereo_modes_16,
  154101. _floor_books,
  154102. _floor,
  154103. _floor_mapping_16_short,
  154104. _floor_mapping_16,
  154105. _mapres_template_16_uncoupled
  154106. };
  154107. /*** End of inlined file: setup_22.h ***/
  154108. /*** Start of inlined file: setup_X.h ***/
  154109. static double rate_mapping_X[12]={
  154110. -1.,-1.,-1.,-1.,-1.,-1.,
  154111. -1.,-1.,-1.,-1.,-1.,-1.
  154112. };
  154113. ve_setup_data_template ve_setup_X_stereo={
  154114. 11,
  154115. rate_mapping_X,
  154116. quality_mapping_44,
  154117. 2,
  154118. 50000,
  154119. 200000,
  154120. blocksize_short_44,
  154121. blocksize_long_44,
  154122. _psy_tone_masteratt_44,
  154123. _psy_tone_0dB,
  154124. _psy_tone_suppress,
  154125. _vp_tonemask_adj_otherblock,
  154126. _vp_tonemask_adj_longblock,
  154127. _vp_tonemask_adj_otherblock,
  154128. _psy_noiseguards_44,
  154129. _psy_noisebias_impulse,
  154130. _psy_noisebias_padding,
  154131. _psy_noisebias_trans,
  154132. _psy_noisebias_long,
  154133. _psy_noise_suppress,
  154134. _psy_compand_44,
  154135. _psy_compand_short_mapping,
  154136. _psy_compand_long_mapping,
  154137. {_noise_start_short_44,_noise_start_long_44},
  154138. {_noise_part_short_44,_noise_part_long_44},
  154139. _noise_thresh_44,
  154140. _psy_ath_floater,
  154141. _psy_ath_abs,
  154142. _psy_lowpass_44,
  154143. _psy_global_44,
  154144. _global_mapping_44,
  154145. _psy_stereo_modes_44,
  154146. _floor_books,
  154147. _floor,
  154148. _floor_short_mapping_44,
  154149. _floor_long_mapping_44,
  154150. _mapres_template_44_stereo
  154151. };
  154152. ve_setup_data_template ve_setup_X_uncoupled={
  154153. 11,
  154154. rate_mapping_X,
  154155. quality_mapping_44,
  154156. -1,
  154157. 50000,
  154158. 200000,
  154159. blocksize_short_44,
  154160. blocksize_long_44,
  154161. _psy_tone_masteratt_44,
  154162. _psy_tone_0dB,
  154163. _psy_tone_suppress,
  154164. _vp_tonemask_adj_otherblock,
  154165. _vp_tonemask_adj_longblock,
  154166. _vp_tonemask_adj_otherblock,
  154167. _psy_noiseguards_44,
  154168. _psy_noisebias_impulse,
  154169. _psy_noisebias_padding,
  154170. _psy_noisebias_trans,
  154171. _psy_noisebias_long,
  154172. _psy_noise_suppress,
  154173. _psy_compand_44,
  154174. _psy_compand_short_mapping,
  154175. _psy_compand_long_mapping,
  154176. {_noise_start_short_44,_noise_start_long_44},
  154177. {_noise_part_short_44,_noise_part_long_44},
  154178. _noise_thresh_44,
  154179. _psy_ath_floater,
  154180. _psy_ath_abs,
  154181. _psy_lowpass_44,
  154182. _psy_global_44,
  154183. _global_mapping_44,
  154184. NULL,
  154185. _floor_books,
  154186. _floor,
  154187. _floor_short_mapping_44,
  154188. _floor_long_mapping_44,
  154189. _mapres_template_44_uncoupled
  154190. };
  154191. ve_setup_data_template ve_setup_XX_stereo={
  154192. 2,
  154193. rate_mapping_X,
  154194. quality_mapping_8,
  154195. 2,
  154196. 0,
  154197. 8000,
  154198. blocksize_8,
  154199. blocksize_8,
  154200. _psy_tone_masteratt_8,
  154201. _psy_tone_0dB,
  154202. _psy_tone_suppress,
  154203. _vp_tonemask_adj_8,
  154204. NULL,
  154205. _vp_tonemask_adj_8,
  154206. _psy_noiseguards_8,
  154207. _psy_noisebias_8,
  154208. _psy_noisebias_8,
  154209. NULL,
  154210. NULL,
  154211. _psy_noise_suppress,
  154212. _psy_compand_8,
  154213. _psy_compand_8_mapping,
  154214. NULL,
  154215. {_noise_start_8,_noise_start_8},
  154216. {_noise_part_8,_noise_part_8},
  154217. _noise_thresh_5only,
  154218. _psy_ath_floater_8,
  154219. _psy_ath_abs_8,
  154220. _psy_lowpass_8,
  154221. _psy_global_44,
  154222. _global_mapping_8,
  154223. _psy_stereo_modes_8,
  154224. _floor_books,
  154225. _floor,
  154226. _floor_mapping_8,
  154227. NULL,
  154228. _mapres_template_8_stereo
  154229. };
  154230. ve_setup_data_template ve_setup_XX_uncoupled={
  154231. 2,
  154232. rate_mapping_X,
  154233. quality_mapping_8,
  154234. -1,
  154235. 0,
  154236. 8000,
  154237. blocksize_8,
  154238. blocksize_8,
  154239. _psy_tone_masteratt_8,
  154240. _psy_tone_0dB,
  154241. _psy_tone_suppress,
  154242. _vp_tonemask_adj_8,
  154243. NULL,
  154244. _vp_tonemask_adj_8,
  154245. _psy_noiseguards_8,
  154246. _psy_noisebias_8,
  154247. _psy_noisebias_8,
  154248. NULL,
  154249. NULL,
  154250. _psy_noise_suppress,
  154251. _psy_compand_8,
  154252. _psy_compand_8_mapping,
  154253. NULL,
  154254. {_noise_start_8,_noise_start_8},
  154255. {_noise_part_8,_noise_part_8},
  154256. _noise_thresh_5only,
  154257. _psy_ath_floater_8,
  154258. _psy_ath_abs_8,
  154259. _psy_lowpass_8,
  154260. _psy_global_44,
  154261. _global_mapping_8,
  154262. _psy_stereo_modes_8,
  154263. _floor_books,
  154264. _floor,
  154265. _floor_mapping_8,
  154266. NULL,
  154267. _mapres_template_8_uncoupled
  154268. };
  154269. /*** End of inlined file: setup_X.h ***/
  154270. static ve_setup_data_template *setup_list[]={
  154271. &ve_setup_44_stereo,
  154272. &ve_setup_44_uncoupled,
  154273. &ve_setup_32_stereo,
  154274. &ve_setup_32_uncoupled,
  154275. &ve_setup_22_stereo,
  154276. &ve_setup_22_uncoupled,
  154277. &ve_setup_16_stereo,
  154278. &ve_setup_16_uncoupled,
  154279. &ve_setup_11_stereo,
  154280. &ve_setup_11_uncoupled,
  154281. &ve_setup_8_stereo,
  154282. &ve_setup_8_uncoupled,
  154283. &ve_setup_X_stereo,
  154284. &ve_setup_X_uncoupled,
  154285. &ve_setup_XX_stereo,
  154286. &ve_setup_XX_uncoupled,
  154287. 0
  154288. };
  154289. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154290. if(vi && vi->codec_setup){
  154291. vi->version=0;
  154292. vi->channels=ch;
  154293. vi->rate=rate;
  154294. return(0);
  154295. }
  154296. return(OV_EINVAL);
  154297. }
  154298. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154299. static_codebook ***books,
  154300. vorbis_info_floor1 *in,
  154301. int *x){
  154302. int i,k,is=s;
  154303. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154304. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154305. memcpy(f,in+x[is],sizeof(*f));
  154306. /* fill in the lowpass field, even if it's temporary */
  154307. f->n=ci->blocksizes[block]>>1;
  154308. /* books */
  154309. {
  154310. int partitions=f->partitions;
  154311. int maxclass=-1;
  154312. int maxbook=-1;
  154313. for(i=0;i<partitions;i++)
  154314. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154315. for(i=0;i<=maxclass;i++){
  154316. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154317. f->class_book[i]+=ci->books;
  154318. for(k=0;k<(1<<f->class_subs[i]);k++){
  154319. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154320. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154321. }
  154322. }
  154323. for(i=0;i<=maxbook;i++)
  154324. ci->book_param[ci->books++]=books[x[is]][i];
  154325. }
  154326. /* for now, we're only using floor 1 */
  154327. ci->floor_type[ci->floors]=1;
  154328. ci->floor_param[ci->floors]=f;
  154329. ci->floors++;
  154330. return;
  154331. }
  154332. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154333. vorbis_info_psy_global *in,
  154334. double *x){
  154335. int i,is=s;
  154336. double ds=s-is;
  154337. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154338. vorbis_info_psy_global *g=&ci->psy_g_param;
  154339. memcpy(g,in+(int)x[is],sizeof(*g));
  154340. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154341. is=(int)ds;
  154342. ds-=is;
  154343. if(ds==0 && is>0){
  154344. is--;
  154345. ds=1.;
  154346. }
  154347. /* interpolate the trigger threshholds */
  154348. for(i=0;i<4;i++){
  154349. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154350. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154351. }
  154352. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154353. return;
  154354. }
  154355. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154356. highlevel_encode_setup *hi,
  154357. adj_stereo *p){
  154358. float s=hi->stereo_point_setting;
  154359. int i,is=s;
  154360. double ds=s-is;
  154361. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154362. vorbis_info_psy_global *g=&ci->psy_g_param;
  154363. if(p){
  154364. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154365. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154366. if(hi->managed){
  154367. /* interpolate the kHz threshholds */
  154368. for(i=0;i<PACKETBLOBS;i++){
  154369. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154370. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154371. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154372. g->coupling_pkHz[i]=kHz;
  154373. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154374. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154375. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154376. }
  154377. }else{
  154378. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154379. for(i=0;i<PACKETBLOBS;i++){
  154380. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154381. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154382. g->coupling_pkHz[i]=kHz;
  154383. }
  154384. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154385. for(i=0;i<PACKETBLOBS;i++){
  154386. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154387. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154388. }
  154389. }
  154390. }else{
  154391. for(i=0;i<PACKETBLOBS;i++){
  154392. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154393. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154394. }
  154395. }
  154396. return;
  154397. }
  154398. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154399. int *nn_start,
  154400. int *nn_partition,
  154401. double *nn_thresh,
  154402. int block){
  154403. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154404. vorbis_info_psy *p=ci->psy_param[block];
  154405. highlevel_encode_setup *hi=&ci->hi;
  154406. int is=s;
  154407. if(block>=ci->psys)
  154408. ci->psys=block+1;
  154409. if(!p){
  154410. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154411. ci->psy_param[block]=p;
  154412. }
  154413. memcpy(p,&_psy_info_template,sizeof(*p));
  154414. p->blockflag=block>>1;
  154415. if(hi->noise_normalize_p){
  154416. p->normal_channel_p=1;
  154417. p->normal_point_p=1;
  154418. p->normal_start=nn_start[is];
  154419. p->normal_partition=nn_partition[is];
  154420. p->normal_thresh=nn_thresh[is];
  154421. }
  154422. return;
  154423. }
  154424. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154425. att3 *att,
  154426. int *max,
  154427. vp_adjblock *in){
  154428. int i,is=s;
  154429. double ds=s-is;
  154430. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154431. vorbis_info_psy *p=ci->psy_param[block];
  154432. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154433. filling the values in here */
  154434. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154435. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154436. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154437. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154438. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154439. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154440. for(i=0;i<P_BANDS;i++)
  154441. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154442. return;
  154443. }
  154444. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154445. compandblock *in, double *x){
  154446. int i,is=s;
  154447. double ds=s-is;
  154448. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154449. vorbis_info_psy *p=ci->psy_param[block];
  154450. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154451. is=(int)ds;
  154452. ds-=is;
  154453. if(ds==0 && is>0){
  154454. is--;
  154455. ds=1.;
  154456. }
  154457. /* interpolate the compander settings */
  154458. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154459. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154460. return;
  154461. }
  154462. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154463. int *suppress){
  154464. int is=s;
  154465. double ds=s-is;
  154466. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154467. vorbis_info_psy *p=ci->psy_param[block];
  154468. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154469. return;
  154470. }
  154471. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154472. int *suppress,
  154473. noise3 *in,
  154474. noiseguard *guard,
  154475. double userbias){
  154476. int i,is=s,j;
  154477. double ds=s-is;
  154478. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154479. vorbis_info_psy *p=ci->psy_param[block];
  154480. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154481. p->noisewindowlomin=guard[block].lo;
  154482. p->noisewindowhimin=guard[block].hi;
  154483. p->noisewindowfixed=guard[block].fixed;
  154484. for(j=0;j<P_NOISECURVES;j++)
  154485. for(i=0;i<P_BANDS;i++)
  154486. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154487. /* impulse blocks may take a user specified bias to boost the
  154488. nominal/high noise encoding depth */
  154489. for(j=0;j<P_NOISECURVES;j++){
  154490. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154491. for(i=0;i<P_BANDS;i++){
  154492. p->noiseoff[j][i]+=userbias;
  154493. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  154494. }
  154495. }
  154496. return;
  154497. }
  154498. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  154499. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154500. vorbis_info_psy *p=ci->psy_param[block];
  154501. p->ath_adjatt=ci->hi.ath_floating_dB;
  154502. p->ath_maxatt=ci->hi.ath_absolute_dB;
  154503. return;
  154504. }
  154505. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  154506. int i;
  154507. for(i=0;i<ci->books;i++)
  154508. if(ci->book_param[i]==book)return(i);
  154509. return(ci->books++);
  154510. }
  154511. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  154512. int *shortb,int *longb){
  154513. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154514. int is=s;
  154515. int blockshort=shortb[is];
  154516. int blocklong=longb[is];
  154517. ci->blocksizes[0]=blockshort;
  154518. ci->blocksizes[1]=blocklong;
  154519. }
  154520. static void vorbis_encode_residue_setup(vorbis_info *vi,
  154521. int number, int block,
  154522. vorbis_residue_template *res){
  154523. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154524. int i,n;
  154525. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  154526. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  154527. memcpy(r,res->res,sizeof(*r));
  154528. if(ci->residues<=number)ci->residues=number+1;
  154529. switch(ci->blocksizes[block]){
  154530. case 64:case 128:case 256:
  154531. r->grouping=16;
  154532. break;
  154533. default:
  154534. r->grouping=32;
  154535. break;
  154536. }
  154537. ci->residue_type[number]=res->res_type;
  154538. /* to be adjusted by lowpass/pointlimit later */
  154539. n=r->end=ci->blocksizes[block]>>1;
  154540. if(res->res_type==2)
  154541. n=r->end*=vi->channels;
  154542. /* fill in all the books */
  154543. {
  154544. int booklist=0,k;
  154545. if(ci->hi.managed){
  154546. for(i=0;i<r->partitions;i++)
  154547. for(k=0;k<3;k++)
  154548. if(res->books_base_managed->books[i][k])
  154549. r->secondstages[i]|=(1<<k);
  154550. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  154551. ci->book_param[r->groupbook]=res->book_aux_managed;
  154552. for(i=0;i<r->partitions;i++){
  154553. for(k=0;k<3;k++){
  154554. if(res->books_base_managed->books[i][k]){
  154555. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  154556. r->booklist[booklist++]=bookid;
  154557. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  154558. }
  154559. }
  154560. }
  154561. }else{
  154562. for(i=0;i<r->partitions;i++)
  154563. for(k=0;k<3;k++)
  154564. if(res->books_base->books[i][k])
  154565. r->secondstages[i]|=(1<<k);
  154566. r->groupbook=book_dup_or_new(ci,res->book_aux);
  154567. ci->book_param[r->groupbook]=res->book_aux;
  154568. for(i=0;i<r->partitions;i++){
  154569. for(k=0;k<3;k++){
  154570. if(res->books_base->books[i][k]){
  154571. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  154572. r->booklist[booklist++]=bookid;
  154573. ci->book_param[bookid]=res->books_base->books[i][k];
  154574. }
  154575. }
  154576. }
  154577. }
  154578. }
  154579. /* lowpass setup/pointlimit */
  154580. {
  154581. double freq=ci->hi.lowpass_kHz*1000.;
  154582. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  154583. double nyq=vi->rate/2.;
  154584. long blocksize=ci->blocksizes[block]>>1;
  154585. /* lowpass needs to be set in the floor and the residue. */
  154586. if(freq>nyq)freq=nyq;
  154587. /* in the floor, the granularity can be very fine; it doesn't alter
  154588. the encoding structure, only the samples used to fit the floor
  154589. approximation */
  154590. f->n=freq/nyq*blocksize;
  154591. /* this res may by limited by the maximum pointlimit of the mode,
  154592. not the lowpass. the floor is always lowpass limited. */
  154593. if(res->limit_type){
  154594. if(ci->hi.managed)
  154595. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  154596. else
  154597. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  154598. if(freq>nyq)freq=nyq;
  154599. }
  154600. /* in the residue, we're constrained, physically, by partition
  154601. boundaries. We still lowpass 'wherever', but we have to round up
  154602. here to next boundary, or the vorbis spec will round it *down* to
  154603. previous boundary in encode/decode */
  154604. if(ci->residue_type[block]==2)
  154605. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  154606. r->grouping;
  154607. else
  154608. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  154609. r->grouping;
  154610. }
  154611. }
  154612. /* we assume two maps in this encoder */
  154613. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  154614. vorbis_mapping_template *maps){
  154615. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154616. int i,j,is=s,modes=2;
  154617. vorbis_info_mapping0 *map=maps[is].map;
  154618. vorbis_info_mode *mode=_mode_template;
  154619. vorbis_residue_template *res=maps[is].res;
  154620. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  154621. for(i=0;i<modes;i++){
  154622. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  154623. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  154624. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  154625. if(i>=ci->modes)ci->modes=i+1;
  154626. ci->map_type[i]=0;
  154627. memcpy(ci->map_param[i],map+i,sizeof(*map));
  154628. if(i>=ci->maps)ci->maps=i+1;
  154629. for(j=0;j<map[i].submaps;j++)
  154630. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  154631. ,res+map[i].residuesubmap[j]);
  154632. }
  154633. }
  154634. static double setting_to_approx_bitrate(vorbis_info *vi){
  154635. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154636. highlevel_encode_setup *hi=&ci->hi;
  154637. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  154638. int is=hi->base_setting;
  154639. double ds=hi->base_setting-is;
  154640. int ch=vi->channels;
  154641. double *r=setup->rate_mapping;
  154642. if(r==NULL)
  154643. return(-1);
  154644. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  154645. }
  154646. static void get_setup_template(vorbis_info *vi,
  154647. long ch,long srate,
  154648. double req,int q_or_bitrate){
  154649. int i=0,j;
  154650. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154651. highlevel_encode_setup *hi=&ci->hi;
  154652. if(q_or_bitrate)req/=ch;
  154653. while(setup_list[i]){
  154654. if(setup_list[i]->coupling_restriction==-1 ||
  154655. setup_list[i]->coupling_restriction==ch){
  154656. if(srate>=setup_list[i]->samplerate_min_restriction &&
  154657. srate<=setup_list[i]->samplerate_max_restriction){
  154658. int mappings=setup_list[i]->mappings;
  154659. double *map=(q_or_bitrate?
  154660. setup_list[i]->rate_mapping:
  154661. setup_list[i]->quality_mapping);
  154662. /* the template matches. Does the requested quality mode
  154663. fall within this template's modes? */
  154664. if(req<map[0]){++i;continue;}
  154665. if(req>map[setup_list[i]->mappings]){++i;continue;}
  154666. for(j=0;j<mappings;j++)
  154667. if(req>=map[j] && req<map[j+1])break;
  154668. /* an all-points match */
  154669. hi->setup=setup_list[i];
  154670. if(j==mappings)
  154671. hi->base_setting=j-.001;
  154672. else{
  154673. float low=map[j];
  154674. float high=map[j+1];
  154675. float del=(req-low)/(high-low);
  154676. hi->base_setting=j+del;
  154677. }
  154678. return;
  154679. }
  154680. }
  154681. i++;
  154682. }
  154683. hi->setup=NULL;
  154684. }
  154685. /* encoders will need to use vorbis_info_init beforehand and call
  154686. vorbis_info clear when all done */
  154687. /* two interfaces; this, more detailed one, and later a convenience
  154688. layer on top */
  154689. /* the final setup call */
  154690. int vorbis_encode_setup_init(vorbis_info *vi){
  154691. int i0=0,singleblock=0;
  154692. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154693. ve_setup_data_template *setup=NULL;
  154694. highlevel_encode_setup *hi=&ci->hi;
  154695. if(ci==NULL)return(OV_EINVAL);
  154696. if(!hi->impulse_block_p)i0=1;
  154697. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  154698. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  154699. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  154700. /* again, bound this to avoid the app shooting itself int he foot
  154701. too badly */
  154702. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  154703. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  154704. /* get the appropriate setup template; matches the fetch in previous
  154705. stages */
  154706. setup=(ve_setup_data_template *)hi->setup;
  154707. if(setup==NULL)return(OV_EINVAL);
  154708. hi->set_in_stone=1;
  154709. /* choose block sizes from configured sizes as well as paying
  154710. attention to long_block_p and short_block_p. If the configured
  154711. short and long blocks are the same length, we set long_block_p
  154712. and unset short_block_p */
  154713. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  154714. setup->blocksize_short,
  154715. setup->blocksize_long);
  154716. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  154717. /* floor setup; choose proper floor params. Allocated on the floor
  154718. stack in order; if we alloc only long floor, it's 0 */
  154719. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  154720. setup->floor_books,
  154721. setup->floor_params,
  154722. setup->floor_short_mapping);
  154723. if(!singleblock)
  154724. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  154725. setup->floor_books,
  154726. setup->floor_params,
  154727. setup->floor_long_mapping);
  154728. /* setup of [mostly] short block detection and stereo*/
  154729. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  154730. setup->global_params,
  154731. setup->global_mapping);
  154732. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  154733. /* basic psych setup and noise normalization */
  154734. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154735. setup->psy_noise_normal_start[0],
  154736. setup->psy_noise_normal_partition[0],
  154737. setup->psy_noise_normal_thresh,
  154738. 0);
  154739. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154740. setup->psy_noise_normal_start[0],
  154741. setup->psy_noise_normal_partition[0],
  154742. setup->psy_noise_normal_thresh,
  154743. 1);
  154744. if(!singleblock){
  154745. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154746. setup->psy_noise_normal_start[1],
  154747. setup->psy_noise_normal_partition[1],
  154748. setup->psy_noise_normal_thresh,
  154749. 2);
  154750. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154751. setup->psy_noise_normal_start[1],
  154752. setup->psy_noise_normal_partition[1],
  154753. setup->psy_noise_normal_thresh,
  154754. 3);
  154755. }
  154756. /* tone masking setup */
  154757. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  154758. setup->psy_tone_masteratt,
  154759. setup->psy_tone_0dB,
  154760. setup->psy_tone_adj_impulse);
  154761. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  154762. setup->psy_tone_masteratt,
  154763. setup->psy_tone_0dB,
  154764. setup->psy_tone_adj_other);
  154765. if(!singleblock){
  154766. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  154767. setup->psy_tone_masteratt,
  154768. setup->psy_tone_0dB,
  154769. setup->psy_tone_adj_other);
  154770. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  154771. setup->psy_tone_masteratt,
  154772. setup->psy_tone_0dB,
  154773. setup->psy_tone_adj_long);
  154774. }
  154775. /* noise companding setup */
  154776. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  154777. setup->psy_noise_compand,
  154778. setup->psy_noise_compand_short_mapping);
  154779. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  154780. setup->psy_noise_compand,
  154781. setup->psy_noise_compand_short_mapping);
  154782. if(!singleblock){
  154783. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  154784. setup->psy_noise_compand,
  154785. setup->psy_noise_compand_long_mapping);
  154786. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  154787. setup->psy_noise_compand,
  154788. setup->psy_noise_compand_long_mapping);
  154789. }
  154790. /* peak guarding setup */
  154791. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  154792. setup->psy_tone_dBsuppress);
  154793. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  154794. setup->psy_tone_dBsuppress);
  154795. if(!singleblock){
  154796. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  154797. setup->psy_tone_dBsuppress);
  154798. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  154799. setup->psy_tone_dBsuppress);
  154800. }
  154801. /* noise bias setup */
  154802. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  154803. setup->psy_noise_dBsuppress,
  154804. setup->psy_noise_bias_impulse,
  154805. setup->psy_noiseguards,
  154806. (i0==0?hi->impulse_noisetune:0.));
  154807. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  154808. setup->psy_noise_dBsuppress,
  154809. setup->psy_noise_bias_padding,
  154810. setup->psy_noiseguards,0.);
  154811. if(!singleblock){
  154812. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  154813. setup->psy_noise_dBsuppress,
  154814. setup->psy_noise_bias_trans,
  154815. setup->psy_noiseguards,0.);
  154816. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  154817. setup->psy_noise_dBsuppress,
  154818. setup->psy_noise_bias_long,
  154819. setup->psy_noiseguards,0.);
  154820. }
  154821. vorbis_encode_ath_setup(vi,0);
  154822. vorbis_encode_ath_setup(vi,1);
  154823. if(!singleblock){
  154824. vorbis_encode_ath_setup(vi,2);
  154825. vorbis_encode_ath_setup(vi,3);
  154826. }
  154827. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  154828. /* set bitrate readonlies and management */
  154829. if(hi->bitrate_av>0)
  154830. vi->bitrate_nominal=hi->bitrate_av;
  154831. else{
  154832. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  154833. }
  154834. vi->bitrate_lower=hi->bitrate_min;
  154835. vi->bitrate_upper=hi->bitrate_max;
  154836. if(hi->bitrate_av)
  154837. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  154838. else
  154839. vi->bitrate_window=0.;
  154840. if(hi->managed){
  154841. ci->bi.avg_rate=hi->bitrate_av;
  154842. ci->bi.min_rate=hi->bitrate_min;
  154843. ci->bi.max_rate=hi->bitrate_max;
  154844. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  154845. ci->bi.reservoir_bias=
  154846. hi->bitrate_reservoir_bias;
  154847. ci->bi.slew_damp=hi->bitrate_av_damp;
  154848. }
  154849. return(0);
  154850. }
  154851. static int vorbis_encode_setup_setting(vorbis_info *vi,
  154852. long channels,
  154853. long rate){
  154854. int ret=0,i,is;
  154855. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154856. highlevel_encode_setup *hi=&ci->hi;
  154857. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  154858. double ds;
  154859. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  154860. if(ret)return(ret);
  154861. is=hi->base_setting;
  154862. ds=hi->base_setting-is;
  154863. hi->short_setting=hi->base_setting;
  154864. hi->long_setting=hi->base_setting;
  154865. hi->managed=0;
  154866. hi->impulse_block_p=1;
  154867. hi->noise_normalize_p=1;
  154868. hi->stereo_point_setting=hi->base_setting;
  154869. hi->lowpass_kHz=
  154870. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  154871. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  154872. setup->psy_ath_float[is+1]*ds;
  154873. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  154874. setup->psy_ath_abs[is+1]*ds;
  154875. hi->amplitude_track_dBpersec=-6.;
  154876. hi->trigger_setting=hi->base_setting;
  154877. for(i=0;i<4;i++){
  154878. hi->block[i].tone_mask_setting=hi->base_setting;
  154879. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  154880. hi->block[i].noise_bias_setting=hi->base_setting;
  154881. hi->block[i].noise_compand_setting=hi->base_setting;
  154882. }
  154883. return(ret);
  154884. }
  154885. int vorbis_encode_setup_vbr(vorbis_info *vi,
  154886. long channels,
  154887. long rate,
  154888. float quality){
  154889. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154890. highlevel_encode_setup *hi=&ci->hi;
  154891. quality+=.0000001;
  154892. if(quality>=1.)quality=.9999;
  154893. get_setup_template(vi,channels,rate,quality,0);
  154894. if(!hi->setup)return OV_EIMPL;
  154895. return vorbis_encode_setup_setting(vi,channels,rate);
  154896. }
  154897. int vorbis_encode_init_vbr(vorbis_info *vi,
  154898. long channels,
  154899. long rate,
  154900. float base_quality /* 0. to 1. */
  154901. ){
  154902. int ret=0;
  154903. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  154904. if(ret){
  154905. vorbis_info_clear(vi);
  154906. return ret;
  154907. }
  154908. ret=vorbis_encode_setup_init(vi);
  154909. if(ret)
  154910. vorbis_info_clear(vi);
  154911. return(ret);
  154912. }
  154913. int vorbis_encode_setup_managed(vorbis_info *vi,
  154914. long channels,
  154915. long rate,
  154916. long max_bitrate,
  154917. long nominal_bitrate,
  154918. long min_bitrate){
  154919. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154920. highlevel_encode_setup *hi=&ci->hi;
  154921. double tnominal=nominal_bitrate;
  154922. int ret=0;
  154923. if(nominal_bitrate<=0.){
  154924. if(max_bitrate>0.){
  154925. if(min_bitrate>0.)
  154926. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  154927. else
  154928. nominal_bitrate=max_bitrate*.875;
  154929. }else{
  154930. if(min_bitrate>0.){
  154931. nominal_bitrate=min_bitrate;
  154932. }else{
  154933. return(OV_EINVAL);
  154934. }
  154935. }
  154936. }
  154937. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  154938. if(!hi->setup)return OV_EIMPL;
  154939. ret=vorbis_encode_setup_setting(vi,channels,rate);
  154940. if(ret){
  154941. vorbis_info_clear(vi);
  154942. return ret;
  154943. }
  154944. /* initialize management with sane defaults */
  154945. hi->managed=1;
  154946. hi->bitrate_min=min_bitrate;
  154947. hi->bitrate_max=max_bitrate;
  154948. hi->bitrate_av=tnominal;
  154949. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  154950. hi->bitrate_reservoir=nominal_bitrate*2;
  154951. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  154952. return(ret);
  154953. }
  154954. int vorbis_encode_init(vorbis_info *vi,
  154955. long channels,
  154956. long rate,
  154957. long max_bitrate,
  154958. long nominal_bitrate,
  154959. long min_bitrate){
  154960. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  154961. max_bitrate,
  154962. nominal_bitrate,
  154963. min_bitrate);
  154964. if(ret){
  154965. vorbis_info_clear(vi);
  154966. return(ret);
  154967. }
  154968. ret=vorbis_encode_setup_init(vi);
  154969. if(ret)
  154970. vorbis_info_clear(vi);
  154971. return(ret);
  154972. }
  154973. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  154974. if(vi){
  154975. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154976. highlevel_encode_setup *hi=&ci->hi;
  154977. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  154978. if(setp && hi->set_in_stone)return(OV_EINVAL);
  154979. switch(number){
  154980. /* now deprecated *****************/
  154981. case OV_ECTL_RATEMANAGE_GET:
  154982. {
  154983. struct ovectl_ratemanage_arg *ai=
  154984. (struct ovectl_ratemanage_arg *)arg;
  154985. ai->management_active=hi->managed;
  154986. ai->bitrate_hard_window=ai->bitrate_av_window=
  154987. (double)hi->bitrate_reservoir/vi->rate;
  154988. ai->bitrate_av_window_center=1.;
  154989. ai->bitrate_hard_min=hi->bitrate_min;
  154990. ai->bitrate_hard_max=hi->bitrate_max;
  154991. ai->bitrate_av_lo=hi->bitrate_av;
  154992. ai->bitrate_av_hi=hi->bitrate_av;
  154993. }
  154994. return(0);
  154995. /* now deprecated *****************/
  154996. case OV_ECTL_RATEMANAGE_SET:
  154997. {
  154998. struct ovectl_ratemanage_arg *ai=
  154999. (struct ovectl_ratemanage_arg *)arg;
  155000. if(ai==NULL){
  155001. hi->managed=0;
  155002. }else{
  155003. hi->managed=ai->management_active;
  155004. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  155005. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  155006. }
  155007. }
  155008. return 0;
  155009. /* now deprecated *****************/
  155010. case OV_ECTL_RATEMANAGE_AVG:
  155011. {
  155012. struct ovectl_ratemanage_arg *ai=
  155013. (struct ovectl_ratemanage_arg *)arg;
  155014. if(ai==NULL){
  155015. hi->bitrate_av=0;
  155016. }else{
  155017. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  155018. }
  155019. }
  155020. return(0);
  155021. /* now deprecated *****************/
  155022. case OV_ECTL_RATEMANAGE_HARD:
  155023. {
  155024. struct ovectl_ratemanage_arg *ai=
  155025. (struct ovectl_ratemanage_arg *)arg;
  155026. if(ai==NULL){
  155027. hi->bitrate_min=0;
  155028. hi->bitrate_max=0;
  155029. }else{
  155030. hi->bitrate_min=ai->bitrate_hard_min;
  155031. hi->bitrate_max=ai->bitrate_hard_max;
  155032. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155033. (hi->bitrate_max+hi->bitrate_min)*.5;
  155034. }
  155035. if(hi->bitrate_reservoir<128.)
  155036. hi->bitrate_reservoir=128.;
  155037. }
  155038. return(0);
  155039. /* replacement ratemanage interface */
  155040. case OV_ECTL_RATEMANAGE2_GET:
  155041. {
  155042. struct ovectl_ratemanage2_arg *ai=
  155043. (struct ovectl_ratemanage2_arg *)arg;
  155044. if(ai==NULL)return OV_EINVAL;
  155045. ai->management_active=hi->managed;
  155046. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155047. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155048. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155049. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155050. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155051. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155052. }
  155053. return (0);
  155054. case OV_ECTL_RATEMANAGE2_SET:
  155055. {
  155056. struct ovectl_ratemanage2_arg *ai=
  155057. (struct ovectl_ratemanage2_arg *)arg;
  155058. if(ai==NULL){
  155059. hi->managed=0;
  155060. }else{
  155061. /* sanity check; only catch invariant violations */
  155062. if(ai->bitrate_limit_min_kbps>0 &&
  155063. ai->bitrate_average_kbps>0 &&
  155064. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155065. return OV_EINVAL;
  155066. if(ai->bitrate_limit_max_kbps>0 &&
  155067. ai->bitrate_average_kbps>0 &&
  155068. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155069. return OV_EINVAL;
  155070. if(ai->bitrate_limit_min_kbps>0 &&
  155071. ai->bitrate_limit_max_kbps>0 &&
  155072. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155073. return OV_EINVAL;
  155074. if(ai->bitrate_average_damping <= 0.)
  155075. return OV_EINVAL;
  155076. if(ai->bitrate_limit_reservoir_bits < 0)
  155077. return OV_EINVAL;
  155078. if(ai->bitrate_limit_reservoir_bias < 0.)
  155079. return OV_EINVAL;
  155080. if(ai->bitrate_limit_reservoir_bias > 1.)
  155081. return OV_EINVAL;
  155082. hi->managed=ai->management_active;
  155083. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155084. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155085. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155086. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155087. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155088. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155089. }
  155090. }
  155091. return 0;
  155092. case OV_ECTL_LOWPASS_GET:
  155093. {
  155094. double *farg=(double *)arg;
  155095. *farg=hi->lowpass_kHz;
  155096. }
  155097. return(0);
  155098. case OV_ECTL_LOWPASS_SET:
  155099. {
  155100. double *farg=(double *)arg;
  155101. hi->lowpass_kHz=*farg;
  155102. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155103. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155104. }
  155105. return(0);
  155106. case OV_ECTL_IBLOCK_GET:
  155107. {
  155108. double *farg=(double *)arg;
  155109. *farg=hi->impulse_noisetune;
  155110. }
  155111. return(0);
  155112. case OV_ECTL_IBLOCK_SET:
  155113. {
  155114. double *farg=(double *)arg;
  155115. hi->impulse_noisetune=*farg;
  155116. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155117. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155118. }
  155119. return(0);
  155120. }
  155121. return(OV_EIMPL);
  155122. }
  155123. return(OV_EINVAL);
  155124. }
  155125. #endif
  155126. /*** End of inlined file: vorbisenc.c ***/
  155127. /*** Start of inlined file: vorbisfile.c ***/
  155128. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155129. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155130. // tasks..
  155131. #if JUCE_MSVC
  155132. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155133. #endif
  155134. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155135. #if JUCE_USE_OGGVORBIS
  155136. #include <stdlib.h>
  155137. #include <stdio.h>
  155138. #include <errno.h>
  155139. #include <string.h>
  155140. #include <math.h>
  155141. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155142. one logical bitstream arranged end to end (the only form of Ogg
  155143. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155144. multiplexing] is not allowed in Vorbis) */
  155145. /* A Vorbis file can be played beginning to end (streamed) without
  155146. worrying ahead of time about chaining (see decoder_example.c). If
  155147. we have the whole file, however, and want random access
  155148. (seeking/scrubbing) or desire to know the total length/time of a
  155149. file, we need to account for the possibility of chaining. */
  155150. /* We can handle things a number of ways; we can determine the entire
  155151. bitstream structure right off the bat, or find pieces on demand.
  155152. This example determines and caches structure for the entire
  155153. bitstream, but builds a virtual decoder on the fly when moving
  155154. between links in the chain. */
  155155. /* There are also different ways to implement seeking. Enough
  155156. information exists in an Ogg bitstream to seek to
  155157. sample-granularity positions in the output. Or, one can seek by
  155158. picking some portion of the stream roughly in the desired area if
  155159. we only want coarse navigation through the stream. */
  155160. /*************************************************************************
  155161. * Many, many internal helpers. The intention is not to be confusing;
  155162. * rampant duplication and monolithic function implementation would be
  155163. * harder to understand anyway. The high level functions are last. Begin
  155164. * grokking near the end of the file */
  155165. /* read a little more data from the file/pipe into the ogg_sync framer
  155166. */
  155167. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155168. over 8k gets what they deserve */
  155169. static long _get_data(OggVorbis_File *vf){
  155170. errno=0;
  155171. if(vf->datasource){
  155172. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155173. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155174. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155175. if(bytes==0 && errno)return(-1);
  155176. return(bytes);
  155177. }else
  155178. return(0);
  155179. }
  155180. /* save a tiny smidge of verbosity to make the code more readable */
  155181. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155182. if(vf->datasource){
  155183. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155184. vf->offset=offset;
  155185. ogg_sync_reset(&vf->oy);
  155186. }else{
  155187. /* shouldn't happen unless someone writes a broken callback */
  155188. return;
  155189. }
  155190. }
  155191. /* The read/seek functions track absolute position within the stream */
  155192. /* from the head of the stream, get the next page. boundary specifies
  155193. if the function is allowed to fetch more data from the stream (and
  155194. how much) or only use internally buffered data.
  155195. boundary: -1) unbounded search
  155196. 0) read no additional data; use cached only
  155197. n) search for a new page beginning for n bytes
  155198. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155199. n) found a page at absolute offset n */
  155200. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155201. ogg_int64_t boundary){
  155202. if(boundary>0)boundary+=vf->offset;
  155203. while(1){
  155204. long more;
  155205. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155206. more=ogg_sync_pageseek(&vf->oy,og);
  155207. if(more<0){
  155208. /* skipped n bytes */
  155209. vf->offset-=more;
  155210. }else{
  155211. if(more==0){
  155212. /* send more paramedics */
  155213. if(!boundary)return(OV_FALSE);
  155214. {
  155215. long ret=_get_data(vf);
  155216. if(ret==0)return(OV_EOF);
  155217. if(ret<0)return(OV_EREAD);
  155218. }
  155219. }else{
  155220. /* got a page. Return the offset at the page beginning,
  155221. advance the internal offset past the page end */
  155222. ogg_int64_t ret=vf->offset;
  155223. vf->offset+=more;
  155224. return(ret);
  155225. }
  155226. }
  155227. }
  155228. }
  155229. /* find the latest page beginning before the current stream cursor
  155230. position. Much dirtier than the above as Ogg doesn't have any
  155231. backward search linkage. no 'readp' as it will certainly have to
  155232. read. */
  155233. /* returns offset or OV_EREAD, OV_FAULT */
  155234. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155235. ogg_int64_t begin=vf->offset;
  155236. ogg_int64_t end=begin;
  155237. ogg_int64_t ret;
  155238. ogg_int64_t offset=-1;
  155239. while(offset==-1){
  155240. begin-=CHUNKSIZE;
  155241. if(begin<0)
  155242. begin=0;
  155243. _seek_helper(vf,begin);
  155244. while(vf->offset<end){
  155245. ret=_get_next_page(vf,og,end-vf->offset);
  155246. if(ret==OV_EREAD)return(OV_EREAD);
  155247. if(ret<0){
  155248. break;
  155249. }else{
  155250. offset=ret;
  155251. }
  155252. }
  155253. }
  155254. /* we have the offset. Actually snork and hold the page now */
  155255. _seek_helper(vf,offset);
  155256. ret=_get_next_page(vf,og,CHUNKSIZE);
  155257. if(ret<0)
  155258. /* this shouldn't be possible */
  155259. return(OV_EFAULT);
  155260. return(offset);
  155261. }
  155262. /* finds each bitstream link one at a time using a bisection search
  155263. (has to begin by knowing the offset of the lb's initial page).
  155264. Recurses for each link so it can alloc the link storage after
  155265. finding them all, then unroll and fill the cache at the same time */
  155266. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155267. ogg_int64_t begin,
  155268. ogg_int64_t searched,
  155269. ogg_int64_t end,
  155270. long currentno,
  155271. long m){
  155272. ogg_int64_t endsearched=end;
  155273. ogg_int64_t next=end;
  155274. ogg_page og;
  155275. ogg_int64_t ret;
  155276. /* the below guards against garbage seperating the last and
  155277. first pages of two links. */
  155278. while(searched<endsearched){
  155279. ogg_int64_t bisect;
  155280. if(endsearched-searched<CHUNKSIZE){
  155281. bisect=searched;
  155282. }else{
  155283. bisect=(searched+endsearched)/2;
  155284. }
  155285. _seek_helper(vf,bisect);
  155286. ret=_get_next_page(vf,&og,-1);
  155287. if(ret==OV_EREAD)return(OV_EREAD);
  155288. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155289. endsearched=bisect;
  155290. if(ret>=0)next=ret;
  155291. }else{
  155292. searched=ret+og.header_len+og.body_len;
  155293. }
  155294. }
  155295. _seek_helper(vf,next);
  155296. ret=_get_next_page(vf,&og,-1);
  155297. if(ret==OV_EREAD)return(OV_EREAD);
  155298. if(searched>=end || ret<0){
  155299. vf->links=m+1;
  155300. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155301. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155302. vf->offsets[m+1]=searched;
  155303. }else{
  155304. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155305. end,ogg_page_serialno(&og),m+1);
  155306. if(ret==OV_EREAD)return(OV_EREAD);
  155307. }
  155308. vf->offsets[m]=begin;
  155309. vf->serialnos[m]=currentno;
  155310. return(0);
  155311. }
  155312. /* uses the local ogg_stream storage in vf; this is important for
  155313. non-streaming input sources */
  155314. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155315. long *serialno,ogg_page *og_ptr){
  155316. ogg_page og;
  155317. ogg_packet op;
  155318. int i,ret;
  155319. if(!og_ptr){
  155320. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155321. if(llret==OV_EREAD)return(OV_EREAD);
  155322. if(llret<0)return OV_ENOTVORBIS;
  155323. og_ptr=&og;
  155324. }
  155325. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155326. if(serialno)*serialno=vf->os.serialno;
  155327. vf->ready_state=STREAMSET;
  155328. /* extract the initial header from the first page and verify that the
  155329. Ogg bitstream is in fact Vorbis data */
  155330. vorbis_info_init(vi);
  155331. vorbis_comment_init(vc);
  155332. i=0;
  155333. while(i<3){
  155334. ogg_stream_pagein(&vf->os,og_ptr);
  155335. while(i<3){
  155336. int result=ogg_stream_packetout(&vf->os,&op);
  155337. if(result==0)break;
  155338. if(result==-1){
  155339. ret=OV_EBADHEADER;
  155340. goto bail_header;
  155341. }
  155342. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155343. goto bail_header;
  155344. }
  155345. i++;
  155346. }
  155347. if(i<3)
  155348. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155349. ret=OV_EBADHEADER;
  155350. goto bail_header;
  155351. }
  155352. }
  155353. return 0;
  155354. bail_header:
  155355. vorbis_info_clear(vi);
  155356. vorbis_comment_clear(vc);
  155357. vf->ready_state=OPENED;
  155358. return ret;
  155359. }
  155360. /* last step of the OggVorbis_File initialization; get all the
  155361. vorbis_info structs and PCM positions. Only called by the seekable
  155362. initialization (local stream storage is hacked slightly; pay
  155363. attention to how that's done) */
  155364. /* this is void and does not propogate errors up because we want to be
  155365. able to open and use damaged bitstreams as well as we can. Just
  155366. watch out for missing information for links in the OggVorbis_File
  155367. struct */
  155368. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155369. ogg_page og;
  155370. int i;
  155371. ogg_int64_t ret;
  155372. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155373. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155374. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155375. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155376. for(i=0;i<vf->links;i++){
  155377. if(i==0){
  155378. /* we already grabbed the initial header earlier. Just set the offset */
  155379. vf->dataoffsets[i]=dataoffset;
  155380. _seek_helper(vf,dataoffset);
  155381. }else{
  155382. /* seek to the location of the initial header */
  155383. _seek_helper(vf,vf->offsets[i]);
  155384. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155385. vf->dataoffsets[i]=-1;
  155386. }else{
  155387. vf->dataoffsets[i]=vf->offset;
  155388. }
  155389. }
  155390. /* fetch beginning PCM offset */
  155391. if(vf->dataoffsets[i]!=-1){
  155392. ogg_int64_t accumulated=0;
  155393. long lastblock=-1;
  155394. int result;
  155395. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155396. while(1){
  155397. ogg_packet op;
  155398. ret=_get_next_page(vf,&og,-1);
  155399. if(ret<0)
  155400. /* this should not be possible unless the file is
  155401. truncated/mangled */
  155402. break;
  155403. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155404. break;
  155405. /* count blocksizes of all frames in the page */
  155406. ogg_stream_pagein(&vf->os,&og);
  155407. while((result=ogg_stream_packetout(&vf->os,&op))){
  155408. if(result>0){ /* ignore holes */
  155409. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155410. if(lastblock!=-1)
  155411. accumulated+=(lastblock+thisblock)>>2;
  155412. lastblock=thisblock;
  155413. }
  155414. }
  155415. if(ogg_page_granulepos(&og)!=-1){
  155416. /* pcm offset of last packet on the first audio page */
  155417. accumulated= ogg_page_granulepos(&og)-accumulated;
  155418. break;
  155419. }
  155420. }
  155421. /* less than zero? This is a stream with samples trimmed off
  155422. the beginning, a normal occurrence; set the offset to zero */
  155423. if(accumulated<0)accumulated=0;
  155424. vf->pcmlengths[i*2]=accumulated;
  155425. }
  155426. /* get the PCM length of this link. To do this,
  155427. get the last page of the stream */
  155428. {
  155429. ogg_int64_t end=vf->offsets[i+1];
  155430. _seek_helper(vf,end);
  155431. while(1){
  155432. ret=_get_prev_page(vf,&og);
  155433. if(ret<0){
  155434. /* this should not be possible */
  155435. vorbis_info_clear(vf->vi+i);
  155436. vorbis_comment_clear(vf->vc+i);
  155437. break;
  155438. }
  155439. if(ogg_page_granulepos(&og)!=-1){
  155440. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155441. break;
  155442. }
  155443. vf->offset=ret;
  155444. }
  155445. }
  155446. }
  155447. }
  155448. static int _make_decode_ready(OggVorbis_File *vf){
  155449. if(vf->ready_state>STREAMSET)return 0;
  155450. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155451. if(vf->seekable){
  155452. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155453. return OV_EBADLINK;
  155454. }else{
  155455. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155456. return OV_EBADLINK;
  155457. }
  155458. vorbis_block_init(&vf->vd,&vf->vb);
  155459. vf->ready_state=INITSET;
  155460. vf->bittrack=0.f;
  155461. vf->samptrack=0.f;
  155462. return 0;
  155463. }
  155464. static int _open_seekable2(OggVorbis_File *vf){
  155465. long serialno=vf->current_serialno;
  155466. ogg_int64_t dataoffset=vf->offset, end;
  155467. ogg_page og;
  155468. /* we're partially open and have a first link header state in
  155469. storage in vf */
  155470. /* we can seek, so set out learning all about this file */
  155471. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155472. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155473. /* We get the offset for the last page of the physical bitstream.
  155474. Most OggVorbis files will contain a single logical bitstream */
  155475. end=_get_prev_page(vf,&og);
  155476. if(end<0)return(end);
  155477. /* more than one logical bitstream? */
  155478. if(ogg_page_serialno(&og)!=serialno){
  155479. /* Chained bitstream. Bisect-search each logical bitstream
  155480. section. Do so based on serial number only */
  155481. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155482. }else{
  155483. /* Only one logical bitstream */
  155484. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155485. }
  155486. /* the initial header memory is referenced by vf after; don't free it */
  155487. _prefetch_all_headers(vf,dataoffset);
  155488. return(ov_raw_seek(vf,0));
  155489. }
  155490. /* clear out the current logical bitstream decoder */
  155491. static void _decode_clear(OggVorbis_File *vf){
  155492. vorbis_dsp_clear(&vf->vd);
  155493. vorbis_block_clear(&vf->vb);
  155494. vf->ready_state=OPENED;
  155495. }
  155496. /* fetch and process a packet. Handles the case where we're at a
  155497. bitstream boundary and dumps the decoding machine. If the decoding
  155498. machine is unloaded, it loads it. It also keeps pcm_offset up to
  155499. date (seek and read both use this. seek uses a special hack with
  155500. readp).
  155501. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  155502. 0) need more data (only if readp==0)
  155503. 1) got a packet
  155504. */
  155505. static int _fetch_and_process_packet(OggVorbis_File *vf,
  155506. ogg_packet *op_in,
  155507. int readp,
  155508. int spanp){
  155509. ogg_page og;
  155510. /* handle one packet. Try to fetch it from current stream state */
  155511. /* extract packets from page */
  155512. while(1){
  155513. /* process a packet if we can. If the machine isn't loaded,
  155514. neither is a page */
  155515. if(vf->ready_state==INITSET){
  155516. while(1) {
  155517. ogg_packet op;
  155518. ogg_packet *op_ptr=(op_in?op_in:&op);
  155519. int result=ogg_stream_packetout(&vf->os,op_ptr);
  155520. ogg_int64_t granulepos;
  155521. op_in=NULL;
  155522. if(result==-1)return(OV_HOLE); /* hole in the data. */
  155523. if(result>0){
  155524. /* got a packet. process it */
  155525. granulepos=op_ptr->granulepos;
  155526. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  155527. header handling. The
  155528. header packets aren't
  155529. audio, so if/when we
  155530. submit them,
  155531. vorbis_synthesis will
  155532. reject them */
  155533. /* suck in the synthesis data and track bitrate */
  155534. {
  155535. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155536. /* for proper use of libvorbis within libvorbisfile,
  155537. oldsamples will always be zero. */
  155538. if(oldsamples)return(OV_EFAULT);
  155539. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155540. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  155541. vf->bittrack+=op_ptr->bytes*8;
  155542. }
  155543. /* update the pcm offset. */
  155544. if(granulepos!=-1 && !op_ptr->e_o_s){
  155545. int link=(vf->seekable?vf->current_link:0);
  155546. int i,samples;
  155547. /* this packet has a pcm_offset on it (the last packet
  155548. completed on a page carries the offset) After processing
  155549. (above), we know the pcm position of the *last* sample
  155550. ready to be returned. Find the offset of the *first*
  155551. As an aside, this trick is inaccurate if we begin
  155552. reading anew right at the last page; the end-of-stream
  155553. granulepos declares the last frame in the stream, and the
  155554. last packet of the last page may be a partial frame.
  155555. So, we need a previous granulepos from an in-sequence page
  155556. to have a reference point. Thus the !op_ptr->e_o_s clause
  155557. above */
  155558. if(vf->seekable && link>0)
  155559. granulepos-=vf->pcmlengths[link*2];
  155560. if(granulepos<0)granulepos=0; /* actually, this
  155561. shouldn't be possible
  155562. here unless the stream
  155563. is very broken */
  155564. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155565. granulepos-=samples;
  155566. for(i=0;i<link;i++)
  155567. granulepos+=vf->pcmlengths[i*2+1];
  155568. vf->pcm_offset=granulepos;
  155569. }
  155570. return(1);
  155571. }
  155572. }
  155573. else
  155574. break;
  155575. }
  155576. }
  155577. if(vf->ready_state>=OPENED){
  155578. ogg_int64_t ret;
  155579. if(!readp)return(0);
  155580. if((ret=_get_next_page(vf,&og,-1))<0){
  155581. return(OV_EOF); /* eof.
  155582. leave unitialized */
  155583. }
  155584. /* bitrate tracking; add the header's bytes here, the body bytes
  155585. are done by packet above */
  155586. vf->bittrack+=og.header_len*8;
  155587. /* has our decoding just traversed a bitstream boundary? */
  155588. if(vf->ready_state==INITSET){
  155589. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155590. if(!spanp)
  155591. return(OV_EOF);
  155592. _decode_clear(vf);
  155593. if(!vf->seekable){
  155594. vorbis_info_clear(vf->vi);
  155595. vorbis_comment_clear(vf->vc);
  155596. }
  155597. }
  155598. }
  155599. }
  155600. /* Do we need to load a new machine before submitting the page? */
  155601. /* This is different in the seekable and non-seekable cases.
  155602. In the seekable case, we already have all the header
  155603. information loaded and cached; we just initialize the machine
  155604. with it and continue on our merry way.
  155605. In the non-seekable (streaming) case, we'll only be at a
  155606. boundary if we just left the previous logical bitstream and
  155607. we're now nominally at the header of the next bitstream
  155608. */
  155609. if(vf->ready_state!=INITSET){
  155610. int link;
  155611. if(vf->ready_state<STREAMSET){
  155612. if(vf->seekable){
  155613. vf->current_serialno=ogg_page_serialno(&og);
  155614. /* match the serialno to bitstream section. We use this rather than
  155615. offset positions to avoid problems near logical bitstream
  155616. boundaries */
  155617. for(link=0;link<vf->links;link++)
  155618. if(vf->serialnos[link]==vf->current_serialno)break;
  155619. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  155620. stream. error out,
  155621. leave machine
  155622. uninitialized */
  155623. vf->current_link=link;
  155624. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155625. vf->ready_state=STREAMSET;
  155626. }else{
  155627. /* we're streaming */
  155628. /* fetch the three header packets, build the info struct */
  155629. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  155630. if(ret)return(ret);
  155631. vf->current_link++;
  155632. link=0;
  155633. }
  155634. }
  155635. {
  155636. int ret=_make_decode_ready(vf);
  155637. if(ret<0)return ret;
  155638. }
  155639. }
  155640. ogg_stream_pagein(&vf->os,&og);
  155641. }
  155642. }
  155643. /* if, eg, 64 bit stdio is configured by default, this will build with
  155644. fseek64 */
  155645. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  155646. if(f==NULL)return(-1);
  155647. return fseek(f,off,whence);
  155648. }
  155649. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  155650. long ibytes, ov_callbacks callbacks){
  155651. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  155652. int ret;
  155653. memset(vf,0,sizeof(*vf));
  155654. vf->datasource=f;
  155655. vf->callbacks = callbacks;
  155656. /* init the framing state */
  155657. ogg_sync_init(&vf->oy);
  155658. /* perhaps some data was previously read into a buffer for testing
  155659. against other stream types. Allow initialization from this
  155660. previously read data (as we may be reading from a non-seekable
  155661. stream) */
  155662. if(initial){
  155663. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  155664. memcpy(buffer,initial,ibytes);
  155665. ogg_sync_wrote(&vf->oy,ibytes);
  155666. }
  155667. /* can we seek? Stevens suggests the seek test was portable */
  155668. if(offsettest!=-1)vf->seekable=1;
  155669. /* No seeking yet; Set up a 'single' (current) logical bitstream
  155670. entry for partial open */
  155671. vf->links=1;
  155672. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  155673. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  155674. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  155675. /* Try to fetch the headers, maintaining all the storage */
  155676. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  155677. vf->datasource=NULL;
  155678. ov_clear(vf);
  155679. }else
  155680. vf->ready_state=PARTOPEN;
  155681. return(ret);
  155682. }
  155683. static int _ov_open2(OggVorbis_File *vf){
  155684. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  155685. vf->ready_state=OPENED;
  155686. if(vf->seekable){
  155687. int ret=_open_seekable2(vf);
  155688. if(ret){
  155689. vf->datasource=NULL;
  155690. ov_clear(vf);
  155691. }
  155692. return(ret);
  155693. }else
  155694. vf->ready_state=STREAMSET;
  155695. return 0;
  155696. }
  155697. /* clear out the OggVorbis_File struct */
  155698. int ov_clear(OggVorbis_File *vf){
  155699. if(vf){
  155700. vorbis_block_clear(&vf->vb);
  155701. vorbis_dsp_clear(&vf->vd);
  155702. ogg_stream_clear(&vf->os);
  155703. if(vf->vi && vf->links){
  155704. int i;
  155705. for(i=0;i<vf->links;i++){
  155706. vorbis_info_clear(vf->vi+i);
  155707. vorbis_comment_clear(vf->vc+i);
  155708. }
  155709. _ogg_free(vf->vi);
  155710. _ogg_free(vf->vc);
  155711. }
  155712. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  155713. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  155714. if(vf->serialnos)_ogg_free(vf->serialnos);
  155715. if(vf->offsets)_ogg_free(vf->offsets);
  155716. ogg_sync_clear(&vf->oy);
  155717. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  155718. memset(vf,0,sizeof(*vf));
  155719. }
  155720. #ifdef DEBUG_LEAKS
  155721. _VDBG_dump();
  155722. #endif
  155723. return(0);
  155724. }
  155725. /* inspects the OggVorbis file and finds/documents all the logical
  155726. bitstreams contained in it. Tries to be tolerant of logical
  155727. bitstream sections that are truncated/woogie.
  155728. return: -1) error
  155729. 0) OK
  155730. */
  155731. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155732. ov_callbacks callbacks){
  155733. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  155734. if(ret)return ret;
  155735. return _ov_open2(vf);
  155736. }
  155737. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155738. ov_callbacks callbacks = {
  155739. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155740. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155741. (int (*)(void *)) fclose,
  155742. (long (*)(void *)) ftell
  155743. };
  155744. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155745. }
  155746. /* cheap hack for game usage where downsampling is desirable; there's
  155747. no need for SRC as we can just do it cheaply in libvorbis. */
  155748. int ov_halfrate(OggVorbis_File *vf,int flag){
  155749. int i;
  155750. if(vf->vi==NULL)return OV_EINVAL;
  155751. if(!vf->seekable)return OV_EINVAL;
  155752. if(vf->ready_state>=STREAMSET)
  155753. _decode_clear(vf); /* clear out stream state; later on libvorbis
  155754. will be able to swap this on the fly, but
  155755. for now dumping the decode machine is needed
  155756. to reinit the MDCT lookups. 1.1 libvorbis
  155757. is planned to be able to switch on the fly */
  155758. for(i=0;i<vf->links;i++){
  155759. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  155760. ov_halfrate(vf,0);
  155761. return OV_EINVAL;
  155762. }
  155763. }
  155764. return 0;
  155765. }
  155766. int ov_halfrate_p(OggVorbis_File *vf){
  155767. if(vf->vi==NULL)return OV_EINVAL;
  155768. return vorbis_synthesis_halfrate_p(vf->vi);
  155769. }
  155770. /* Only partially open the vorbis file; test for Vorbisness, and load
  155771. the headers for the first chain. Do not seek (although test for
  155772. seekability). Use ov_test_open to finish opening the file, else
  155773. ov_clear to close/free it. Same return codes as open. */
  155774. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155775. ov_callbacks callbacks)
  155776. {
  155777. return _ov_open1(f,vf,initial,ibytes,callbacks);
  155778. }
  155779. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155780. ov_callbacks callbacks = {
  155781. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155782. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155783. (int (*)(void *)) fclose,
  155784. (long (*)(void *)) ftell
  155785. };
  155786. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155787. }
  155788. int ov_test_open(OggVorbis_File *vf){
  155789. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  155790. return _ov_open2(vf);
  155791. }
  155792. /* How many logical bitstreams in this physical bitstream? */
  155793. long ov_streams(OggVorbis_File *vf){
  155794. return vf->links;
  155795. }
  155796. /* Is the FILE * associated with vf seekable? */
  155797. long ov_seekable(OggVorbis_File *vf){
  155798. return vf->seekable;
  155799. }
  155800. /* returns the bitrate for a given logical bitstream or the entire
  155801. physical bitstream. If the file is open for random access, it will
  155802. find the *actual* average bitrate. If the file is streaming, it
  155803. returns the nominal bitrate (if set) else the average of the
  155804. upper/lower bounds (if set) else -1 (unset).
  155805. If you want the actual bitrate field settings, get them from the
  155806. vorbis_info structs */
  155807. long ov_bitrate(OggVorbis_File *vf,int i){
  155808. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155809. if(i>=vf->links)return(OV_EINVAL);
  155810. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  155811. if(i<0){
  155812. ogg_int64_t bits=0;
  155813. int i;
  155814. float br;
  155815. for(i=0;i<vf->links;i++)
  155816. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  155817. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  155818. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  155819. * so this is slightly transformed to make it work.
  155820. */
  155821. br = bits/ov_time_total(vf,-1);
  155822. return(rint(br));
  155823. }else{
  155824. if(vf->seekable){
  155825. /* return the actual bitrate */
  155826. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  155827. }else{
  155828. /* return nominal if set */
  155829. if(vf->vi[i].bitrate_nominal>0){
  155830. return vf->vi[i].bitrate_nominal;
  155831. }else{
  155832. if(vf->vi[i].bitrate_upper>0){
  155833. if(vf->vi[i].bitrate_lower>0){
  155834. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  155835. }else{
  155836. return vf->vi[i].bitrate_upper;
  155837. }
  155838. }
  155839. return(OV_FALSE);
  155840. }
  155841. }
  155842. }
  155843. }
  155844. /* returns the actual bitrate since last call. returns -1 if no
  155845. additional data to offer since last call (or at beginning of stream),
  155846. EINVAL if stream is only partially open
  155847. */
  155848. long ov_bitrate_instant(OggVorbis_File *vf){
  155849. int link=(vf->seekable?vf->current_link:0);
  155850. long ret;
  155851. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155852. if(vf->samptrack==0)return(OV_FALSE);
  155853. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  155854. vf->bittrack=0.f;
  155855. vf->samptrack=0.f;
  155856. return(ret);
  155857. }
  155858. /* Guess */
  155859. long ov_serialnumber(OggVorbis_File *vf,int i){
  155860. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  155861. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  155862. if(i<0){
  155863. return(vf->current_serialno);
  155864. }else{
  155865. return(vf->serialnos[i]);
  155866. }
  155867. }
  155868. /* returns: total raw (compressed) length of content if i==-1
  155869. raw (compressed) length of that logical bitstream for i==0 to n
  155870. OV_EINVAL if the stream is not seekable (we can't know the length)
  155871. or if stream is only partially open
  155872. */
  155873. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  155874. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155875. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155876. if(i<0){
  155877. ogg_int64_t acc=0;
  155878. int i;
  155879. for(i=0;i<vf->links;i++)
  155880. acc+=ov_raw_total(vf,i);
  155881. return(acc);
  155882. }else{
  155883. return(vf->offsets[i+1]-vf->offsets[i]);
  155884. }
  155885. }
  155886. /* returns: total PCM length (samples) of content if i==-1 PCM length
  155887. (samples) of that logical bitstream for i==0 to n
  155888. OV_EINVAL if the stream is not seekable (we can't know the
  155889. length) or only partially open
  155890. */
  155891. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  155892. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155893. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155894. if(i<0){
  155895. ogg_int64_t acc=0;
  155896. int i;
  155897. for(i=0;i<vf->links;i++)
  155898. acc+=ov_pcm_total(vf,i);
  155899. return(acc);
  155900. }else{
  155901. return(vf->pcmlengths[i*2+1]);
  155902. }
  155903. }
  155904. /* returns: total seconds of content if i==-1
  155905. seconds in that logical bitstream for i==0 to n
  155906. OV_EINVAL if the stream is not seekable (we can't know the
  155907. length) or only partially open
  155908. */
  155909. double ov_time_total(OggVorbis_File *vf,int i){
  155910. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155911. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155912. if(i<0){
  155913. double acc=0;
  155914. int i;
  155915. for(i=0;i<vf->links;i++)
  155916. acc+=ov_time_total(vf,i);
  155917. return(acc);
  155918. }else{
  155919. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  155920. }
  155921. }
  155922. /* seek to an offset relative to the *compressed* data. This also
  155923. scans packets to update the PCM cursor. It will cross a logical
  155924. bitstream boundary, but only if it can't get any packets out of the
  155925. tail of the bitstream we seek to (so no surprises).
  155926. returns zero on success, nonzero on failure */
  155927. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  155928. ogg_stream_state work_os;
  155929. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155930. if(!vf->seekable)
  155931. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  155932. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  155933. /* don't yet clear out decoding machine (if it's initialized), in
  155934. the case we're in the same link. Restart the decode lapping, and
  155935. let _fetch_and_process_packet deal with a potential bitstream
  155936. boundary */
  155937. vf->pcm_offset=-1;
  155938. ogg_stream_reset_serialno(&vf->os,
  155939. vf->current_serialno); /* must set serialno */
  155940. vorbis_synthesis_restart(&vf->vd);
  155941. _seek_helper(vf,pos);
  155942. /* we need to make sure the pcm_offset is set, but we don't want to
  155943. advance the raw cursor past good packets just to get to the first
  155944. with a granulepos. That's not equivalent behavior to beginning
  155945. decoding as immediately after the seek position as possible.
  155946. So, a hack. We use two stream states; a local scratch state and
  155947. the shared vf->os stream state. We use the local state to
  155948. scan, and the shared state as a buffer for later decode.
  155949. Unfortuantely, on the last page we still advance to last packet
  155950. because the granulepos on the last page is not necessarily on a
  155951. packet boundary, and we need to make sure the granpos is
  155952. correct.
  155953. */
  155954. {
  155955. ogg_page og;
  155956. ogg_packet op;
  155957. int lastblock=0;
  155958. int accblock=0;
  155959. int thisblock;
  155960. int eosflag;
  155961. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  155962. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  155963. return from not necessarily
  155964. starting from the beginning */
  155965. while(1){
  155966. if(vf->ready_state>=STREAMSET){
  155967. /* snarf/scan a packet if we can */
  155968. int result=ogg_stream_packetout(&work_os,&op);
  155969. if(result>0){
  155970. if(vf->vi[vf->current_link].codec_setup){
  155971. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  155972. if(thisblock<0){
  155973. ogg_stream_packetout(&vf->os,NULL);
  155974. thisblock=0;
  155975. }else{
  155976. if(eosflag)
  155977. ogg_stream_packetout(&vf->os,NULL);
  155978. else
  155979. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  155980. }
  155981. if(op.granulepos!=-1){
  155982. int i,link=vf->current_link;
  155983. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  155984. if(granulepos<0)granulepos=0;
  155985. for(i=0;i<link;i++)
  155986. granulepos+=vf->pcmlengths[i*2+1];
  155987. vf->pcm_offset=granulepos-accblock;
  155988. break;
  155989. }
  155990. lastblock=thisblock;
  155991. continue;
  155992. }else
  155993. ogg_stream_packetout(&vf->os,NULL);
  155994. }
  155995. }
  155996. if(!lastblock){
  155997. if(_get_next_page(vf,&og,-1)<0){
  155998. vf->pcm_offset=ov_pcm_total(vf,-1);
  155999. break;
  156000. }
  156001. }else{
  156002. /* huh? Bogus stream with packets but no granulepos */
  156003. vf->pcm_offset=-1;
  156004. break;
  156005. }
  156006. /* has our decoding just traversed a bitstream boundary? */
  156007. if(vf->ready_state>=STREAMSET)
  156008. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156009. _decode_clear(vf); /* clear out stream state */
  156010. ogg_stream_clear(&work_os);
  156011. }
  156012. if(vf->ready_state<STREAMSET){
  156013. int link;
  156014. vf->current_serialno=ogg_page_serialno(&og);
  156015. for(link=0;link<vf->links;link++)
  156016. if(vf->serialnos[link]==vf->current_serialno)break;
  156017. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  156018. error out, leave
  156019. machine uninitialized */
  156020. vf->current_link=link;
  156021. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156022. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156023. vf->ready_state=STREAMSET;
  156024. }
  156025. ogg_stream_pagein(&vf->os,&og);
  156026. ogg_stream_pagein(&work_os,&og);
  156027. eosflag=ogg_page_eos(&og);
  156028. }
  156029. }
  156030. ogg_stream_clear(&work_os);
  156031. vf->bittrack=0.f;
  156032. vf->samptrack=0.f;
  156033. return(0);
  156034. seek_error:
  156035. /* dump the machine so we're in a known state */
  156036. vf->pcm_offset=-1;
  156037. ogg_stream_clear(&work_os);
  156038. _decode_clear(vf);
  156039. return OV_EBADLINK;
  156040. }
  156041. /* Page granularity seek (faster than sample granularity because we
  156042. don't do the last bit of decode to find a specific sample).
  156043. Seek to the last [granule marked] page preceeding the specified pos
  156044. location, such that decoding past the returned point will quickly
  156045. arrive at the requested position. */
  156046. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156047. int link=-1;
  156048. ogg_int64_t result=0;
  156049. ogg_int64_t total=ov_pcm_total(vf,-1);
  156050. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156051. if(!vf->seekable)return(OV_ENOSEEK);
  156052. if(pos<0 || pos>total)return(OV_EINVAL);
  156053. /* which bitstream section does this pcm offset occur in? */
  156054. for(link=vf->links-1;link>=0;link--){
  156055. total-=vf->pcmlengths[link*2+1];
  156056. if(pos>=total)break;
  156057. }
  156058. /* search within the logical bitstream for the page with the highest
  156059. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156060. missing pages or incorrect frame number information in the
  156061. bitstream could make our task impossible. Account for that (it
  156062. would be an error condition) */
  156063. /* new search algorithm by HB (Nicholas Vinen) */
  156064. {
  156065. ogg_int64_t end=vf->offsets[link+1];
  156066. ogg_int64_t begin=vf->offsets[link];
  156067. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156068. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156069. ogg_int64_t target=pos-total+begintime;
  156070. ogg_int64_t best=begin;
  156071. ogg_page og;
  156072. while(begin<end){
  156073. ogg_int64_t bisect;
  156074. if(end-begin<CHUNKSIZE){
  156075. bisect=begin;
  156076. }else{
  156077. /* take a (pretty decent) guess. */
  156078. bisect=begin +
  156079. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156080. if(bisect<=begin)
  156081. bisect=begin+1;
  156082. }
  156083. _seek_helper(vf,bisect);
  156084. while(begin<end){
  156085. result=_get_next_page(vf,&og,end-vf->offset);
  156086. if(result==OV_EREAD) goto seek_error;
  156087. if(result<0){
  156088. if(bisect<=begin+1)
  156089. end=begin; /* found it */
  156090. else{
  156091. if(bisect==0) goto seek_error;
  156092. bisect-=CHUNKSIZE;
  156093. if(bisect<=begin)bisect=begin+1;
  156094. _seek_helper(vf,bisect);
  156095. }
  156096. }else{
  156097. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156098. if(granulepos==-1)continue;
  156099. if(granulepos<target){
  156100. best=result; /* raw offset of packet with granulepos */
  156101. begin=vf->offset; /* raw offset of next page */
  156102. begintime=granulepos;
  156103. if(target-begintime>44100)break;
  156104. bisect=begin; /* *not* begin + 1 */
  156105. }else{
  156106. if(bisect<=begin+1)
  156107. end=begin; /* found it */
  156108. else{
  156109. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156110. end=result;
  156111. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156112. if(bisect<=begin)bisect=begin+1;
  156113. _seek_helper(vf,bisect);
  156114. }else{
  156115. end=result;
  156116. endtime=granulepos;
  156117. break;
  156118. }
  156119. }
  156120. }
  156121. }
  156122. }
  156123. }
  156124. /* found our page. seek to it, update pcm offset. Easier case than
  156125. raw_seek, don't keep packets preceeding granulepos. */
  156126. {
  156127. ogg_page og;
  156128. ogg_packet op;
  156129. /* seek */
  156130. _seek_helper(vf,best);
  156131. vf->pcm_offset=-1;
  156132. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156133. if(link!=vf->current_link){
  156134. /* Different link; dump entire decode machine */
  156135. _decode_clear(vf);
  156136. vf->current_link=link;
  156137. vf->current_serialno=ogg_page_serialno(&og);
  156138. vf->ready_state=STREAMSET;
  156139. }else{
  156140. vorbis_synthesis_restart(&vf->vd);
  156141. }
  156142. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156143. ogg_stream_pagein(&vf->os,&og);
  156144. /* pull out all but last packet; the one with granulepos */
  156145. while(1){
  156146. result=ogg_stream_packetpeek(&vf->os,&op);
  156147. if(result==0){
  156148. /* !!! the packet finishing this page originated on a
  156149. preceeding page. Keep fetching previous pages until we
  156150. get one with a granulepos or without the 'continued' flag
  156151. set. Then just use raw_seek for simplicity. */
  156152. _seek_helper(vf,best);
  156153. while(1){
  156154. result=_get_prev_page(vf,&og);
  156155. if(result<0) goto seek_error;
  156156. if(ogg_page_granulepos(&og)>-1 ||
  156157. !ogg_page_continued(&og)){
  156158. return ov_raw_seek(vf,result);
  156159. }
  156160. vf->offset=result;
  156161. }
  156162. }
  156163. if(result<0){
  156164. result = OV_EBADPACKET;
  156165. goto seek_error;
  156166. }
  156167. if(op.granulepos!=-1){
  156168. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156169. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156170. vf->pcm_offset+=total;
  156171. break;
  156172. }else
  156173. result=ogg_stream_packetout(&vf->os,NULL);
  156174. }
  156175. }
  156176. }
  156177. /* verify result */
  156178. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156179. result=OV_EFAULT;
  156180. goto seek_error;
  156181. }
  156182. vf->bittrack=0.f;
  156183. vf->samptrack=0.f;
  156184. return(0);
  156185. seek_error:
  156186. /* dump machine so we're in a known state */
  156187. vf->pcm_offset=-1;
  156188. _decode_clear(vf);
  156189. return (int)result;
  156190. }
  156191. /* seek to a sample offset relative to the decompressed pcm stream
  156192. returns zero on success, nonzero on failure */
  156193. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156194. int thisblock,lastblock=0;
  156195. int ret=ov_pcm_seek_page(vf,pos);
  156196. if(ret<0)return(ret);
  156197. if((ret=_make_decode_ready(vf)))return ret;
  156198. /* discard leading packets we don't need for the lapping of the
  156199. position we want; don't decode them */
  156200. while(1){
  156201. ogg_packet op;
  156202. ogg_page og;
  156203. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156204. if(ret>0){
  156205. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156206. if(thisblock<0){
  156207. ogg_stream_packetout(&vf->os,NULL);
  156208. continue; /* non audio packet */
  156209. }
  156210. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156211. if(vf->pcm_offset+((thisblock+
  156212. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156213. /* remove the packet from packet queue and track its granulepos */
  156214. ogg_stream_packetout(&vf->os,NULL);
  156215. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156216. only tracking, no
  156217. pcm_decode */
  156218. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156219. /* end of logical stream case is hard, especially with exact
  156220. length positioning. */
  156221. if(op.granulepos>-1){
  156222. int i;
  156223. /* always believe the stream markers */
  156224. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156225. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156226. for(i=0;i<vf->current_link;i++)
  156227. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156228. }
  156229. lastblock=thisblock;
  156230. }else{
  156231. if(ret<0 && ret!=OV_HOLE)break;
  156232. /* suck in a new page */
  156233. if(_get_next_page(vf,&og,-1)<0)break;
  156234. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156235. if(vf->ready_state<STREAMSET){
  156236. int link;
  156237. vf->current_serialno=ogg_page_serialno(&og);
  156238. for(link=0;link<vf->links;link++)
  156239. if(vf->serialnos[link]==vf->current_serialno)break;
  156240. if(link==vf->links)return(OV_EBADLINK);
  156241. vf->current_link=link;
  156242. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156243. vf->ready_state=STREAMSET;
  156244. ret=_make_decode_ready(vf);
  156245. if(ret)return ret;
  156246. lastblock=0;
  156247. }
  156248. ogg_stream_pagein(&vf->os,&og);
  156249. }
  156250. }
  156251. vf->bittrack=0.f;
  156252. vf->samptrack=0.f;
  156253. /* discard samples until we reach the desired position. Crossing a
  156254. logical bitstream boundary with abandon is OK. */
  156255. while(vf->pcm_offset<pos){
  156256. ogg_int64_t target=pos-vf->pcm_offset;
  156257. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156258. if(samples>target)samples=target;
  156259. vorbis_synthesis_read(&vf->vd,samples);
  156260. vf->pcm_offset+=samples;
  156261. if(samples<target)
  156262. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156263. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156264. }
  156265. return 0;
  156266. }
  156267. /* seek to a playback time relative to the decompressed pcm stream
  156268. returns zero on success, nonzero on failure */
  156269. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156270. /* translate time to PCM position and call ov_pcm_seek */
  156271. int link=-1;
  156272. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156273. double time_total=ov_time_total(vf,-1);
  156274. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156275. if(!vf->seekable)return(OV_ENOSEEK);
  156276. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156277. /* which bitstream section does this time offset occur in? */
  156278. for(link=vf->links-1;link>=0;link--){
  156279. pcm_total-=vf->pcmlengths[link*2+1];
  156280. time_total-=ov_time_total(vf,link);
  156281. if(seconds>=time_total)break;
  156282. }
  156283. /* enough information to convert time offset to pcm offset */
  156284. {
  156285. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156286. return(ov_pcm_seek(vf,target));
  156287. }
  156288. }
  156289. /* page-granularity version of ov_time_seek
  156290. returns zero on success, nonzero on failure */
  156291. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156292. /* translate time to PCM position and call ov_pcm_seek */
  156293. int link=-1;
  156294. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156295. double time_total=ov_time_total(vf,-1);
  156296. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156297. if(!vf->seekable)return(OV_ENOSEEK);
  156298. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156299. /* which bitstream section does this time offset occur in? */
  156300. for(link=vf->links-1;link>=0;link--){
  156301. pcm_total-=vf->pcmlengths[link*2+1];
  156302. time_total-=ov_time_total(vf,link);
  156303. if(seconds>=time_total)break;
  156304. }
  156305. /* enough information to convert time offset to pcm offset */
  156306. {
  156307. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156308. return(ov_pcm_seek_page(vf,target));
  156309. }
  156310. }
  156311. /* tell the current stream offset cursor. Note that seek followed by
  156312. tell will likely not give the set offset due to caching */
  156313. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156314. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156315. return(vf->offset);
  156316. }
  156317. /* return PCM offset (sample) of next PCM sample to be read */
  156318. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156319. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156320. return(vf->pcm_offset);
  156321. }
  156322. /* return time offset (seconds) of next PCM sample to be read */
  156323. double ov_time_tell(OggVorbis_File *vf){
  156324. int link=0;
  156325. ogg_int64_t pcm_total=0;
  156326. double time_total=0.f;
  156327. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156328. if(vf->seekable){
  156329. pcm_total=ov_pcm_total(vf,-1);
  156330. time_total=ov_time_total(vf,-1);
  156331. /* which bitstream section does this time offset occur in? */
  156332. for(link=vf->links-1;link>=0;link--){
  156333. pcm_total-=vf->pcmlengths[link*2+1];
  156334. time_total-=ov_time_total(vf,link);
  156335. if(vf->pcm_offset>=pcm_total)break;
  156336. }
  156337. }
  156338. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156339. }
  156340. /* link: -1) return the vorbis_info struct for the bitstream section
  156341. currently being decoded
  156342. 0-n) to request information for a specific bitstream section
  156343. In the case of a non-seekable bitstream, any call returns the
  156344. current bitstream. NULL in the case that the machine is not
  156345. initialized */
  156346. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156347. if(vf->seekable){
  156348. if(link<0)
  156349. if(vf->ready_state>=STREAMSET)
  156350. return vf->vi+vf->current_link;
  156351. else
  156352. return vf->vi;
  156353. else
  156354. if(link>=vf->links)
  156355. return NULL;
  156356. else
  156357. return vf->vi+link;
  156358. }else{
  156359. return vf->vi;
  156360. }
  156361. }
  156362. /* grr, strong typing, grr, no templates/inheritence, grr */
  156363. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156364. if(vf->seekable){
  156365. if(link<0)
  156366. if(vf->ready_state>=STREAMSET)
  156367. return vf->vc+vf->current_link;
  156368. else
  156369. return vf->vc;
  156370. else
  156371. if(link>=vf->links)
  156372. return NULL;
  156373. else
  156374. return vf->vc+link;
  156375. }else{
  156376. return vf->vc;
  156377. }
  156378. }
  156379. static int host_is_big_endian() {
  156380. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156381. unsigned char *bytewise = (unsigned char *)&pattern;
  156382. if (bytewise[0] == 0xfe) return 1;
  156383. return 0;
  156384. }
  156385. /* up to this point, everything could more or less hide the multiple
  156386. logical bitstream nature of chaining from the toplevel application
  156387. if the toplevel application didn't particularly care. However, at
  156388. the point that we actually read audio back, the multiple-section
  156389. nature must surface: Multiple bitstream sections do not necessarily
  156390. have to have the same number of channels or sampling rate.
  156391. ov_read returns the sequential logical bitstream number currently
  156392. being decoded along with the PCM data in order that the toplevel
  156393. application can take action on channel/sample rate changes. This
  156394. number will be incremented even for streamed (non-seekable) streams
  156395. (for seekable streams, it represents the actual logical bitstream
  156396. index within the physical bitstream. Note that the accessor
  156397. functions above are aware of this dichotomy).
  156398. input values: buffer) a buffer to hold packed PCM data for return
  156399. length) the byte length requested to be placed into buffer
  156400. bigendianp) should the data be packed LSB first (0) or
  156401. MSB first (1)
  156402. word) word size for output. currently 1 (byte) or
  156403. 2 (16 bit short)
  156404. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156405. 0) EOF
  156406. n) number of bytes of PCM actually returned. The
  156407. below works on a packet-by-packet basis, so the
  156408. return length is not related to the 'length' passed
  156409. in, just guaranteed to fit.
  156410. *section) set to the logical bitstream number */
  156411. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156412. int bigendianp,int word,int sgned,int *bitstream){
  156413. int i,j;
  156414. int host_endian = host_is_big_endian();
  156415. float **pcm;
  156416. long samples;
  156417. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156418. while(1){
  156419. if(vf->ready_state==INITSET){
  156420. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156421. if(samples)break;
  156422. }
  156423. /* suck in another packet */
  156424. {
  156425. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156426. if(ret==OV_EOF)
  156427. return(0);
  156428. if(ret<=0)
  156429. return(ret);
  156430. }
  156431. }
  156432. if(samples>0){
  156433. /* yay! proceed to pack data into the byte buffer */
  156434. long channels=ov_info(vf,-1)->channels;
  156435. long bytespersample=word * channels;
  156436. vorbis_fpu_control fpu;
  156437. (void) fpu; // (to avoid a warning about it being unused)
  156438. if(samples>length/bytespersample)samples=length/bytespersample;
  156439. if(samples <= 0)
  156440. return OV_EINVAL;
  156441. /* a tight loop to pack each size */
  156442. {
  156443. int val;
  156444. if(word==1){
  156445. int off=(sgned?0:128);
  156446. vorbis_fpu_setround(&fpu);
  156447. for(j=0;j<samples;j++)
  156448. for(i=0;i<channels;i++){
  156449. val=vorbis_ftoi(pcm[i][j]*128.f);
  156450. if(val>127)val=127;
  156451. else if(val<-128)val=-128;
  156452. *buffer++=val+off;
  156453. }
  156454. vorbis_fpu_restore(fpu);
  156455. }else{
  156456. int off=(sgned?0:32768);
  156457. if(host_endian==bigendianp){
  156458. if(sgned){
  156459. vorbis_fpu_setround(&fpu);
  156460. for(i=0;i<channels;i++) { /* It's faster in this order */
  156461. float *src=pcm[i];
  156462. short *dest=((short *)buffer)+i;
  156463. for(j=0;j<samples;j++) {
  156464. val=vorbis_ftoi(src[j]*32768.f);
  156465. if(val>32767)val=32767;
  156466. else if(val<-32768)val=-32768;
  156467. *dest=val;
  156468. dest+=channels;
  156469. }
  156470. }
  156471. vorbis_fpu_restore(fpu);
  156472. }else{
  156473. vorbis_fpu_setround(&fpu);
  156474. for(i=0;i<channels;i++) {
  156475. float *src=pcm[i];
  156476. short *dest=((short *)buffer)+i;
  156477. for(j=0;j<samples;j++) {
  156478. val=vorbis_ftoi(src[j]*32768.f);
  156479. if(val>32767)val=32767;
  156480. else if(val<-32768)val=-32768;
  156481. *dest=val+off;
  156482. dest+=channels;
  156483. }
  156484. }
  156485. vorbis_fpu_restore(fpu);
  156486. }
  156487. }else if(bigendianp){
  156488. vorbis_fpu_setround(&fpu);
  156489. for(j=0;j<samples;j++)
  156490. for(i=0;i<channels;i++){
  156491. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156492. if(val>32767)val=32767;
  156493. else if(val<-32768)val=-32768;
  156494. val+=off;
  156495. *buffer++=(val>>8);
  156496. *buffer++=(val&0xff);
  156497. }
  156498. vorbis_fpu_restore(fpu);
  156499. }else{
  156500. int val;
  156501. vorbis_fpu_setround(&fpu);
  156502. for(j=0;j<samples;j++)
  156503. for(i=0;i<channels;i++){
  156504. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156505. if(val>32767)val=32767;
  156506. else if(val<-32768)val=-32768;
  156507. val+=off;
  156508. *buffer++=(val&0xff);
  156509. *buffer++=(val>>8);
  156510. }
  156511. vorbis_fpu_restore(fpu);
  156512. }
  156513. }
  156514. }
  156515. vorbis_synthesis_read(&vf->vd,samples);
  156516. vf->pcm_offset+=samples;
  156517. if(bitstream)*bitstream=vf->current_link;
  156518. return(samples*bytespersample);
  156519. }else{
  156520. return(samples);
  156521. }
  156522. }
  156523. /* input values: pcm_channels) a float vector per channel of output
  156524. length) the sample length being read by the app
  156525. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156526. 0) EOF
  156527. n) number of samples of PCM actually returned. The
  156528. below works on a packet-by-packet basis, so the
  156529. return length is not related to the 'length' passed
  156530. in, just guaranteed to fit.
  156531. *section) set to the logical bitstream number */
  156532. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  156533. int *bitstream){
  156534. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156535. while(1){
  156536. if(vf->ready_state==INITSET){
  156537. float **pcm;
  156538. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156539. if(samples){
  156540. if(pcm_channels)*pcm_channels=pcm;
  156541. if(samples>length)samples=length;
  156542. vorbis_synthesis_read(&vf->vd,samples);
  156543. vf->pcm_offset+=samples;
  156544. if(bitstream)*bitstream=vf->current_link;
  156545. return samples;
  156546. }
  156547. }
  156548. /* suck in another packet */
  156549. {
  156550. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156551. if(ret==OV_EOF)return(0);
  156552. if(ret<=0)return(ret);
  156553. }
  156554. }
  156555. }
  156556. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  156557. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  156558. ogg_int64_t off);
  156559. static void _ov_splice(float **pcm,float **lappcm,
  156560. int n1, int n2,
  156561. int ch1, int ch2,
  156562. float *w1, float *w2){
  156563. int i,j;
  156564. float *w=w1;
  156565. int n=n1;
  156566. if(n1>n2){
  156567. n=n2;
  156568. w=w2;
  156569. }
  156570. /* splice */
  156571. for(j=0;j<ch1 && j<ch2;j++){
  156572. float *s=lappcm[j];
  156573. float *d=pcm[j];
  156574. for(i=0;i<n;i++){
  156575. float wd=w[i]*w[i];
  156576. float ws=1.-wd;
  156577. d[i]=d[i]*wd + s[i]*ws;
  156578. }
  156579. }
  156580. /* window from zero */
  156581. for(;j<ch2;j++){
  156582. float *d=pcm[j];
  156583. for(i=0;i<n;i++){
  156584. float wd=w[i]*w[i];
  156585. d[i]=d[i]*wd;
  156586. }
  156587. }
  156588. }
  156589. /* make sure vf is INITSET */
  156590. static int _ov_initset(OggVorbis_File *vf){
  156591. while(1){
  156592. if(vf->ready_state==INITSET)break;
  156593. /* suck in another packet */
  156594. {
  156595. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156596. if(ret<0 && ret!=OV_HOLE)return(ret);
  156597. }
  156598. }
  156599. return 0;
  156600. }
  156601. /* make sure vf is INITSET and that we have a primed buffer; if
  156602. we're crosslapping at a stream section boundary, this also makes
  156603. sure we're sanity checking against the right stream information */
  156604. static int _ov_initprime(OggVorbis_File *vf){
  156605. vorbis_dsp_state *vd=&vf->vd;
  156606. while(1){
  156607. if(vf->ready_state==INITSET)
  156608. if(vorbis_synthesis_pcmout(vd,NULL))break;
  156609. /* suck in another packet */
  156610. {
  156611. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156612. if(ret<0 && ret!=OV_HOLE)return(ret);
  156613. }
  156614. }
  156615. return 0;
  156616. }
  156617. /* grab enough data for lapping from vf; this may be in the form of
  156618. unreturned, already-decoded pcm, remaining PCM we will need to
  156619. decode, or synthetic postextrapolation from last packets. */
  156620. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  156621. float **lappcm,int lapsize){
  156622. int lapcount=0,i;
  156623. float **pcm;
  156624. /* try first to decode the lapping data */
  156625. while(lapcount<lapsize){
  156626. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  156627. if(samples){
  156628. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156629. for(i=0;i<vi->channels;i++)
  156630. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156631. lapcount+=samples;
  156632. vorbis_synthesis_read(vd,samples);
  156633. }else{
  156634. /* suck in another packet */
  156635. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  156636. if(ret==OV_EOF)break;
  156637. }
  156638. }
  156639. if(lapcount<lapsize){
  156640. /* failed to get lapping data from normal decode; pry it from the
  156641. postextrapolation buffering, or the second half of the MDCT
  156642. from the last packet */
  156643. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  156644. if(samples==0){
  156645. for(i=0;i<vi->channels;i++)
  156646. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  156647. lapcount=lapsize;
  156648. }else{
  156649. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156650. for(i=0;i<vi->channels;i++)
  156651. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156652. lapcount+=samples;
  156653. }
  156654. }
  156655. }
  156656. /* this sets up crosslapping of a sample by using trailing data from
  156657. sample 1 and lapping it into the windowing buffer of sample 2 */
  156658. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  156659. vorbis_info *vi1,*vi2;
  156660. float **lappcm;
  156661. float **pcm;
  156662. float *w1,*w2;
  156663. int n1,n2,i,ret,hs1,hs2;
  156664. if(vf1==vf2)return(0); /* degenerate case */
  156665. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  156666. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  156667. /* the relevant overlap buffers must be pre-checked and pre-primed
  156668. before looking at settings in the event that priming would cross
  156669. a bitstream boundary. So, do it now */
  156670. ret=_ov_initset(vf1);
  156671. if(ret)return(ret);
  156672. ret=_ov_initprime(vf2);
  156673. if(ret)return(ret);
  156674. vi1=ov_info(vf1,-1);
  156675. vi2=ov_info(vf2,-1);
  156676. hs1=ov_halfrate_p(vf1);
  156677. hs2=ov_halfrate_p(vf2);
  156678. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  156679. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  156680. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  156681. w1=vorbis_window(&vf1->vd,0);
  156682. w2=vorbis_window(&vf2->vd,0);
  156683. for(i=0;i<vi1->channels;i++)
  156684. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156685. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  156686. /* have a lapping buffer from vf1; now to splice it into the lapping
  156687. buffer of vf2 */
  156688. /* consolidate and expose the buffer. */
  156689. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  156690. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  156691. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  156692. /* splice */
  156693. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  156694. /* done */
  156695. return(0);
  156696. }
  156697. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  156698. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  156699. vorbis_info *vi;
  156700. float **lappcm;
  156701. float **pcm;
  156702. float *w1,*w2;
  156703. int n1,n2,ch1,ch2,hs;
  156704. int i,ret;
  156705. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156706. ret=_ov_initset(vf);
  156707. if(ret)return(ret);
  156708. vi=ov_info(vf,-1);
  156709. hs=ov_halfrate_p(vf);
  156710. ch1=vi->channels;
  156711. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156712. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156713. persistent; even if the decode state
  156714. from this link gets dumped, this
  156715. window array continues to exist */
  156716. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156717. for(i=0;i<ch1;i++)
  156718. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156719. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156720. /* have lapping data; seek and prime the buffer */
  156721. ret=localseek(vf,pos);
  156722. if(ret)return ret;
  156723. ret=_ov_initprime(vf);
  156724. if(ret)return(ret);
  156725. /* Guard against cross-link changes; they're perfectly legal */
  156726. vi=ov_info(vf,-1);
  156727. ch2=vi->channels;
  156728. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156729. w2=vorbis_window(&vf->vd,0);
  156730. /* consolidate and expose the buffer. */
  156731. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156732. /* splice */
  156733. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156734. /* done */
  156735. return(0);
  156736. }
  156737. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156738. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  156739. }
  156740. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156741. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  156742. }
  156743. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156744. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  156745. }
  156746. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  156747. int (*localseek)(OggVorbis_File *,double)){
  156748. vorbis_info *vi;
  156749. float **lappcm;
  156750. float **pcm;
  156751. float *w1,*w2;
  156752. int n1,n2,ch1,ch2,hs;
  156753. int i,ret;
  156754. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156755. ret=_ov_initset(vf);
  156756. if(ret)return(ret);
  156757. vi=ov_info(vf,-1);
  156758. hs=ov_halfrate_p(vf);
  156759. ch1=vi->channels;
  156760. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156761. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156762. persistent; even if the decode state
  156763. from this link gets dumped, this
  156764. window array continues to exist */
  156765. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156766. for(i=0;i<ch1;i++)
  156767. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156768. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156769. /* have lapping data; seek and prime the buffer */
  156770. ret=localseek(vf,pos);
  156771. if(ret)return ret;
  156772. ret=_ov_initprime(vf);
  156773. if(ret)return(ret);
  156774. /* Guard against cross-link changes; they're perfectly legal */
  156775. vi=ov_info(vf,-1);
  156776. ch2=vi->channels;
  156777. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156778. w2=vorbis_window(&vf->vd,0);
  156779. /* consolidate and expose the buffer. */
  156780. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156781. /* splice */
  156782. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156783. /* done */
  156784. return(0);
  156785. }
  156786. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  156787. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  156788. }
  156789. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  156790. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  156791. }
  156792. #endif
  156793. /*** End of inlined file: vorbisfile.c ***/
  156794. /*** Start of inlined file: window.c ***/
  156795. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  156796. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  156797. // tasks..
  156798. #if JUCE_MSVC
  156799. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  156800. #endif
  156801. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  156802. #if JUCE_USE_OGGVORBIS
  156803. #include <stdlib.h>
  156804. #include <math.h>
  156805. static float vwin64[32] = {
  156806. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  156807. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  156808. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  156809. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  156810. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  156811. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  156812. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  156813. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  156814. };
  156815. static float vwin128[64] = {
  156816. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  156817. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  156818. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  156819. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  156820. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  156821. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  156822. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  156823. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  156824. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  156825. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  156826. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  156827. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  156828. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  156829. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  156830. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  156831. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  156832. };
  156833. static float vwin256[128] = {
  156834. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  156835. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  156836. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  156837. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  156838. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  156839. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  156840. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  156841. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  156842. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  156843. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  156844. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  156845. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  156846. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  156847. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  156848. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  156849. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  156850. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  156851. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  156852. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  156853. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  156854. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  156855. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  156856. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  156857. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  156858. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  156859. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  156860. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  156861. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  156862. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  156863. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  156864. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  156865. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  156866. };
  156867. static float vwin512[256] = {
  156868. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  156869. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  156870. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  156871. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  156872. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  156873. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  156874. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  156875. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  156876. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  156877. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  156878. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  156879. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  156880. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  156881. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  156882. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  156883. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  156884. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  156885. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  156886. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  156887. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  156888. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  156889. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  156890. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  156891. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  156892. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  156893. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  156894. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  156895. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  156896. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  156897. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  156898. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  156899. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  156900. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  156901. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  156902. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  156903. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  156904. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  156905. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  156906. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  156907. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  156908. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  156909. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  156910. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  156911. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  156912. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  156913. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  156914. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  156915. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  156916. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  156917. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  156918. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  156919. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  156920. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  156921. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  156922. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  156923. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  156924. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  156925. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  156926. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  156927. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  156928. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  156929. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  156930. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  156931. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  156932. };
  156933. static float vwin1024[512] = {
  156934. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  156935. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  156936. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  156937. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  156938. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  156939. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  156940. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  156941. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  156942. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  156943. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  156944. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  156945. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  156946. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  156947. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  156948. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  156949. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  156950. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  156951. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  156952. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  156953. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  156954. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  156955. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  156956. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  156957. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  156958. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  156959. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  156960. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  156961. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  156962. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  156963. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  156964. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  156965. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  156966. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  156967. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  156968. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  156969. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  156970. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  156971. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  156972. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  156973. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  156974. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  156975. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  156976. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  156977. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  156978. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  156979. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  156980. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  156981. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  156982. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  156983. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  156984. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  156985. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  156986. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  156987. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  156988. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  156989. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  156990. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  156991. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  156992. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  156993. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  156994. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  156995. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  156996. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  156997. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  156998. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  156999. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  157000. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  157001. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  157002. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  157003. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  157004. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  157005. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  157006. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  157007. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  157008. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  157009. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  157010. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  157011. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  157012. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  157013. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  157014. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  157015. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  157016. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  157017. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  157018. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157019. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157020. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157021. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157022. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157023. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157024. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157025. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157026. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157027. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157028. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157029. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157030. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157031. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157032. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157033. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157034. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157035. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157036. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157037. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157038. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157039. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157040. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157041. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157042. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157043. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157044. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157045. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157046. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157047. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157048. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157049. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157050. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157051. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157052. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157053. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157054. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157055. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157056. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157057. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157058. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157059. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157060. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157061. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157062. };
  157063. static float vwin2048[1024] = {
  157064. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157065. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157066. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157067. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157068. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157069. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157070. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157071. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157072. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157073. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157074. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157075. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157076. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157077. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157078. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157079. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157080. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157081. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157082. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157083. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157084. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157085. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157086. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157087. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157088. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157089. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157090. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157091. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157092. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157093. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157094. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157095. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157096. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157097. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157098. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157099. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157100. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157101. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157102. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157103. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157104. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157105. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157106. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157107. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157108. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157109. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157110. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157111. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157112. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157113. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157114. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157115. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157116. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157117. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157118. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157119. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157120. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157121. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157122. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157123. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157124. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157125. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157126. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157127. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157128. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157129. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157130. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157131. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157132. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157133. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157134. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157135. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157136. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157137. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157138. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157139. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157140. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157141. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157142. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157143. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157144. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157145. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157146. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157147. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157148. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157149. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157150. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157151. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157152. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157153. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157154. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157155. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157156. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157157. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157158. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157159. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157160. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157161. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157162. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157163. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157164. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157165. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157166. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157167. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157168. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157169. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157170. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157171. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157172. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157173. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157174. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157175. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157176. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157177. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157178. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157179. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157180. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157181. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157182. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157183. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157184. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157185. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157186. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157187. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157188. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157189. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157190. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157191. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157192. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157193. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157194. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157195. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157196. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157197. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157198. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157199. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157200. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157201. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157202. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157203. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157204. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157205. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157206. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157207. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157208. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157209. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157210. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157211. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157212. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157213. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157214. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157215. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157216. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157217. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157218. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157219. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157220. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157221. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157222. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157223. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157224. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157225. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157226. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157227. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157228. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157229. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157230. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157231. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157232. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157233. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157234. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157235. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157236. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157237. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157238. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157239. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157240. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157241. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157242. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157243. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157244. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157245. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157246. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157247. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157248. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157249. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157250. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157251. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157252. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157253. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157254. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157255. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157256. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157257. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157258. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157259. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157260. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157261. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157262. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157263. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157264. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157265. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157266. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157267. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157268. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157269. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157270. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157271. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157272. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157273. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157274. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157275. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157276. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157277. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157278. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157279. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157280. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157281. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157282. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157283. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157284. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157285. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157286. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157287. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157288. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157289. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157290. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157291. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157292. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157293. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157294. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157295. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157296. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157297. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157298. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157299. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157300. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157301. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157302. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157303. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157304. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157305. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157306. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157307. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157308. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157309. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157310. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157311. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157312. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157313. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157314. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157315. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157316. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157317. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157318. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157319. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157320. };
  157321. static float vwin4096[2048] = {
  157322. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157323. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157324. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157325. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157326. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157327. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157328. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157329. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157330. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157331. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157332. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157333. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157334. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157335. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157336. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157337. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157338. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157339. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157340. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157341. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157342. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157343. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157344. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157345. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157346. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157347. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157348. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157349. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157350. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157351. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157352. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157353. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157354. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157355. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157356. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157357. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157358. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157359. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157360. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157361. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157362. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157363. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157364. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157365. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157366. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157367. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157368. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157369. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157370. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157371. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157372. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157373. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157374. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157375. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157376. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157377. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157378. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157379. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157380. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157381. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157382. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157383. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157384. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157385. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157386. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157387. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157388. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157389. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157390. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157391. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157392. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157393. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157394. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157395. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157396. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157397. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157398. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157399. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157400. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157401. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157402. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157403. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157404. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157405. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157406. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157407. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157408. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157409. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157410. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157411. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157412. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157413. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157414. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157415. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157416. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157417. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157418. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157419. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157420. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157421. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157422. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157423. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157424. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157425. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157426. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157427. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157428. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157429. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157430. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157431. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157432. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157433. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157434. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157435. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157436. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157437. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157438. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157439. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157440. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157441. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157442. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157443. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157444. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157445. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157446. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157447. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157448. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157449. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157450. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157451. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157452. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157453. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157454. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157455. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157456. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157457. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157458. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157459. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157460. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157461. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157462. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157463. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157464. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157465. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157466. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157467. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157468. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157469. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157470. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157471. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157472. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157473. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157474. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157475. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157476. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157477. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157478. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157479. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157480. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157481. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157482. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157483. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157484. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157485. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157486. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157487. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157488. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157489. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157490. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157491. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157492. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  157493. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  157494. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  157495. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  157496. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  157497. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  157498. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  157499. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  157500. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  157501. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  157502. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  157503. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  157504. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  157505. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  157506. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  157507. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  157508. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  157509. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  157510. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  157511. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  157512. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  157513. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  157514. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  157515. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  157516. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  157517. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  157518. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  157519. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  157520. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  157521. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  157522. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  157523. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  157524. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  157525. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  157526. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  157527. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  157528. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  157529. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  157530. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  157531. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  157532. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  157533. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  157534. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  157535. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  157536. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  157537. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  157538. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  157539. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  157540. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  157541. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  157542. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  157543. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  157544. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  157545. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  157546. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  157547. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  157548. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  157549. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  157550. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  157551. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  157552. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  157553. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  157554. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  157555. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  157556. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  157557. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  157558. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  157559. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  157560. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  157561. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  157562. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  157563. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  157564. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  157565. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  157566. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  157567. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  157568. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  157569. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  157570. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  157571. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  157572. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  157573. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  157574. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  157575. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  157576. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  157577. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  157578. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  157579. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  157580. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  157581. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  157582. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  157583. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  157584. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  157585. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  157586. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  157587. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  157588. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  157589. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  157590. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  157591. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  157592. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  157593. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  157594. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  157595. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  157596. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  157597. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  157598. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  157599. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  157600. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  157601. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  157602. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  157603. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  157604. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  157605. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  157606. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  157607. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  157608. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  157609. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  157610. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  157611. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  157612. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  157613. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  157614. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  157615. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  157616. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  157617. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  157618. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  157619. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  157620. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  157621. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  157622. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  157623. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  157624. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  157625. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  157626. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  157627. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  157628. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  157629. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  157630. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  157631. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  157632. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  157633. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  157634. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  157635. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  157636. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  157637. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  157638. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  157639. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  157640. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  157641. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  157642. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  157643. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  157644. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  157645. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  157646. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  157647. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  157648. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  157649. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  157650. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  157651. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  157652. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  157653. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  157654. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  157655. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  157656. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  157657. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  157658. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  157659. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  157660. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  157661. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  157662. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  157663. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  157664. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  157665. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  157666. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  157667. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  157668. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  157669. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  157670. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  157671. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  157672. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  157673. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  157674. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  157675. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  157676. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  157677. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  157678. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  157679. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  157680. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  157681. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  157682. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  157683. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  157684. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  157685. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  157686. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  157687. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  157688. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  157689. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  157690. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  157691. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  157692. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  157693. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  157694. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  157695. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  157696. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  157697. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  157698. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  157699. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  157700. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  157701. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  157702. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  157703. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  157704. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  157705. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  157706. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  157707. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  157708. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  157709. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  157710. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  157711. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  157712. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  157713. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  157714. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  157715. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  157716. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  157717. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  157718. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  157719. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  157720. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  157721. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  157722. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  157723. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  157724. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  157725. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  157726. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  157727. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  157728. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  157729. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  157730. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  157731. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  157732. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  157733. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  157734. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  157735. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  157736. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  157737. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  157738. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  157739. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  157740. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  157741. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  157742. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  157743. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  157744. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  157745. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  157746. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  157747. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  157748. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  157749. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  157750. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  157751. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  157752. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  157753. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  157754. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  157755. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  157756. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  157757. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  157758. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  157759. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  157760. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  157761. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  157762. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  157763. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  157764. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  157765. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  157766. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  157767. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  157768. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  157769. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  157770. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  157771. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  157772. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  157773. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  157774. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  157775. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  157776. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  157777. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  157778. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  157779. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  157780. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  157781. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  157782. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  157783. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  157784. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  157785. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  157786. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  157787. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  157788. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  157789. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  157790. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  157791. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  157792. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  157793. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  157794. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  157795. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  157796. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  157797. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  157798. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  157799. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  157800. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  157801. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  157802. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  157803. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  157804. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  157805. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  157806. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  157807. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  157808. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  157809. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  157810. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  157811. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  157812. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  157813. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  157814. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  157815. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  157816. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  157817. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  157818. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  157819. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  157820. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  157821. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  157822. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  157823. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  157824. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  157825. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  157826. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  157827. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  157828. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  157829. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  157830. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  157831. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  157832. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  157833. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  157834. };
  157835. static float vwin8192[4096] = {
  157836. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  157837. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  157838. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  157839. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  157840. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  157841. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  157842. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  157843. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  157844. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  157845. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  157846. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  157847. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  157848. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  157849. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  157850. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  157851. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  157852. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  157853. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  157854. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  157855. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  157856. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  157857. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  157858. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  157859. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  157860. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  157861. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  157862. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  157863. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  157864. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  157865. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  157866. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  157867. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  157868. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  157869. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  157870. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  157871. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  157872. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  157873. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  157874. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  157875. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  157876. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  157877. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  157878. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  157879. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  157880. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  157881. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  157882. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  157883. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  157884. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  157885. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  157886. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  157887. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  157888. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  157889. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  157890. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  157891. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  157892. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  157893. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  157894. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  157895. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  157896. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  157897. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  157898. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  157899. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  157900. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  157901. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  157902. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  157903. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  157904. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  157905. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  157906. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  157907. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  157908. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  157909. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  157910. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  157911. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  157912. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  157913. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  157914. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  157915. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  157916. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  157917. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  157918. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  157919. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  157920. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  157921. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  157922. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  157923. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  157924. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  157925. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  157926. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  157927. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  157928. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  157929. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  157930. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  157931. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  157932. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  157933. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  157934. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  157935. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  157936. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  157937. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  157938. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  157939. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  157940. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  157941. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  157942. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  157943. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  157944. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  157945. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  157946. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  157947. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  157948. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  157949. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  157950. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  157951. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  157952. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  157953. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  157954. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  157955. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  157956. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  157957. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  157958. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  157959. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  157960. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  157961. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  157962. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  157963. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  157964. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  157965. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  157966. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  157967. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  157968. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  157969. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  157970. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  157971. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  157972. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  157973. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  157974. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  157975. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  157976. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  157977. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  157978. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  157979. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  157980. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  157981. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  157982. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  157983. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  157984. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  157985. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  157986. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  157987. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  157988. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  157989. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  157990. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  157991. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  157992. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  157993. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  157994. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  157995. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  157996. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  157997. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  157998. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  157999. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  158000. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  158001. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  158002. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  158003. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  158004. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  158005. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  158006. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  158007. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  158008. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  158009. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  158010. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  158011. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  158012. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  158013. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  158014. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  158015. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  158016. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  158017. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  158018. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158019. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158020. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158021. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158022. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158023. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158024. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158025. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158026. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158027. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158028. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158029. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158030. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158031. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158032. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158033. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158034. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158035. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158036. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158037. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158038. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158039. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158040. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158041. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158042. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158043. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158044. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158045. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158046. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158047. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158048. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158049. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158050. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158051. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158052. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158053. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158054. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158055. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158056. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158057. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158058. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158059. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158060. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158061. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158062. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158063. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158064. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158065. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158066. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158067. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158068. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158069. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158070. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158071. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158072. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158073. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158074. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158075. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158076. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158077. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158078. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158079. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158080. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158081. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158082. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158083. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158084. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158085. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158086. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158087. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158088. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158089. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158090. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158091. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158092. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158093. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158094. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158095. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158096. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158097. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158098. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158099. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158100. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158101. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158102. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158103. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158104. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158105. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158106. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158107. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158108. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158109. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158110. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158111. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158112. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158113. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158114. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158115. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158116. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158117. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158118. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158119. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158120. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158121. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158122. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158123. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158124. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158125. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158126. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158127. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158128. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158129. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158130. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158131. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158132. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158133. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158134. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158135. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158136. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158137. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158138. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158139. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158140. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158141. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158142. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158143. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158144. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158145. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158146. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158147. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158148. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158149. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158150. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158151. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158152. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158153. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158154. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158155. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158156. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158157. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158158. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158159. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158160. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158161. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158162. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158163. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158164. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158165. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158166. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158167. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158168. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158169. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158170. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158171. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158172. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158173. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158174. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158175. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158176. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158177. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158178. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158179. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158180. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158181. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158182. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158183. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158184. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158185. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158186. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158187. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158188. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158189. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158190. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158191. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158192. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158193. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158194. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158195. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158196. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158197. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158198. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158199. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158200. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158201. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158202. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158203. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158204. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158205. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158206. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158207. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158208. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158209. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158210. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158211. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158212. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158213. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158214. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158215. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158216. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158217. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158218. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158219. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158220. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158221. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158222. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158223. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158224. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158225. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158226. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158227. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158228. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158229. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158230. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158231. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158232. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158233. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158234. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158235. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158236. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158237. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158238. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158239. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158240. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158241. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158242. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158243. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158244. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158245. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158246. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158247. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158248. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158249. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158250. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158251. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158252. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158253. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158254. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158255. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158256. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158257. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158258. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158259. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158260. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158261. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158262. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158263. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158264. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158265. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158266. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158267. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158268. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158269. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158270. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158271. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158272. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158273. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158274. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158275. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158276. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158277. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158278. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158279. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158280. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158281. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158282. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158283. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158284. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158285. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158286. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158287. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158288. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158289. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158290. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158291. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158292. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158293. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158294. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158295. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158296. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158297. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158298. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158299. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158300. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158301. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158302. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158303. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158304. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158305. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158306. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158307. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158308. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158309. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158310. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158311. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158312. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158313. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158314. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158315. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158316. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158317. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158318. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158319. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158320. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158321. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158322. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158323. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158324. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158325. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158326. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158327. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158328. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158329. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158330. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158331. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158332. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158333. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158334. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158335. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158336. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158337. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158338. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158339. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158340. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158341. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158342. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158343. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158344. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158345. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158346. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158347. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158348. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158349. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158350. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158351. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158352. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158353. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158354. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158355. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158356. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158357. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158358. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158359. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158360. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158361. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158362. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158363. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158364. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158365. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158366. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158367. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158368. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158369. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158370. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158371. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158372. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158373. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158374. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158375. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158376. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158377. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158378. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158379. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158380. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158381. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158382. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158383. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158384. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158385. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158386. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158387. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158388. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158389. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158390. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158391. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158392. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158393. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158394. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158395. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158396. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158397. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158398. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158399. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158400. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158401. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158402. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158403. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158404. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158405. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158406. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158407. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158408. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158409. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158410. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158411. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158412. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158413. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158414. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158415. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158416. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158417. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158418. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158419. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158420. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158421. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158422. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158423. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158424. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158425. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158426. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158427. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158428. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158429. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158430. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158431. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158432. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158433. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158434. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158435. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158436. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158437. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158438. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158439. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158440. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158441. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158442. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158443. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158444. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158445. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158446. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158447. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158448. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158449. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158450. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158451. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158452. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158453. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158454. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158455. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158456. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158457. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158458. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158459. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158460. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158461. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158462. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158463. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158464. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158465. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158466. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158467. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158468. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158469. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158470. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158471. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158472. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158473. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158474. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158475. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158476. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158477. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158478. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158479. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158480. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158481. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158482. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158483. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158484. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158485. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158486. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158487. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158488. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158489. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158490. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158491. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158492. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  158493. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  158494. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  158495. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  158496. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  158497. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  158498. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  158499. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  158500. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  158501. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  158502. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  158503. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  158504. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  158505. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  158506. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  158507. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  158508. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  158509. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  158510. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  158511. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  158512. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  158513. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  158514. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  158515. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  158516. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  158517. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  158518. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  158519. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  158520. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  158521. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  158522. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  158523. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  158524. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  158525. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  158526. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  158527. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  158528. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  158529. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  158530. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  158531. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  158532. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  158533. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  158534. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  158535. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  158536. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  158537. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  158538. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  158539. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  158540. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  158541. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  158542. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  158543. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  158544. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  158545. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  158546. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  158547. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  158548. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  158549. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  158550. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  158551. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  158552. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  158553. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  158554. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  158555. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  158556. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  158557. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  158558. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  158559. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  158560. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  158561. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  158562. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  158563. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  158564. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  158565. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  158566. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  158567. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  158568. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  158569. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  158570. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  158571. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  158572. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  158573. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  158574. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  158575. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  158576. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  158577. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  158578. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  158579. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  158580. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  158581. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  158582. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  158583. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  158584. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  158585. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  158586. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  158587. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  158588. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  158589. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  158590. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  158591. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  158592. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  158593. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  158594. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  158595. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  158596. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  158597. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  158598. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  158599. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  158600. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  158601. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  158602. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  158603. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  158604. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  158605. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  158606. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  158607. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  158608. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  158609. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  158610. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  158611. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  158612. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  158613. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  158614. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  158615. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  158616. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  158617. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  158618. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  158619. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  158620. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  158621. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  158622. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  158623. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  158624. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  158625. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  158626. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  158627. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  158628. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  158629. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  158630. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  158631. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  158632. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  158633. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  158634. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  158635. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  158636. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  158637. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  158638. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  158639. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  158640. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  158641. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  158642. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  158643. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  158644. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  158645. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  158646. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  158647. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  158648. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  158649. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  158650. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  158651. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  158652. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  158653. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  158654. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  158655. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  158656. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  158657. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  158658. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  158659. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  158660. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  158661. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  158662. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  158663. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  158664. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  158665. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  158666. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  158667. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  158668. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  158669. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  158670. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  158671. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  158672. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  158673. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  158674. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  158675. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  158676. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  158677. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  158678. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  158679. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  158680. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  158681. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  158682. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  158683. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  158684. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  158685. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  158686. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  158687. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  158688. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  158689. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  158690. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  158691. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  158692. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  158693. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  158694. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  158695. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  158696. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  158697. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  158698. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  158699. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  158700. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  158701. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  158702. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  158703. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  158704. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  158705. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  158706. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  158707. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  158708. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  158709. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  158710. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  158711. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  158712. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  158713. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  158714. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  158715. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  158716. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  158717. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  158718. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  158719. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  158720. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  158721. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  158722. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  158723. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  158724. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  158725. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  158726. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  158727. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  158728. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  158729. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  158730. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  158731. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  158732. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  158733. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  158734. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  158735. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  158736. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  158737. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  158738. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  158739. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  158740. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  158741. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  158742. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  158743. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  158744. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  158745. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  158746. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  158747. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  158748. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  158749. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  158750. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  158751. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  158752. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  158753. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  158754. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  158755. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  158756. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  158757. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  158758. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  158759. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  158760. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  158761. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  158762. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  158763. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  158764. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  158765. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  158766. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  158767. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  158768. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  158769. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  158770. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  158771. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  158772. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  158773. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  158774. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  158775. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  158776. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  158777. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  158778. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  158779. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  158780. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  158781. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  158782. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  158783. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  158784. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  158785. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  158786. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  158787. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  158788. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  158789. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  158790. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  158791. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  158792. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  158793. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  158794. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  158795. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  158796. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  158797. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  158798. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  158799. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  158800. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  158801. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  158802. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  158803. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  158804. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  158805. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  158806. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  158807. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  158808. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  158809. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  158810. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  158811. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  158812. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  158813. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  158814. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  158815. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  158816. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  158817. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  158818. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  158819. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  158820. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  158821. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  158822. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  158823. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  158824. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  158825. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  158826. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  158827. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  158828. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  158829. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  158830. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  158831. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  158832. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  158833. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  158834. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  158835. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  158836. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  158837. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  158838. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  158839. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  158840. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  158841. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  158842. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  158843. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  158844. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  158845. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  158846. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  158847. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  158848. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  158849. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  158850. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  158851. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  158852. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  158853. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  158854. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  158855. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  158856. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  158857. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  158858. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158859. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158860. };
  158861. static float *vwin[8] = {
  158862. vwin64,
  158863. vwin128,
  158864. vwin256,
  158865. vwin512,
  158866. vwin1024,
  158867. vwin2048,
  158868. vwin4096,
  158869. vwin8192,
  158870. };
  158871. float *_vorbis_window_get(int n){
  158872. return vwin[n];
  158873. }
  158874. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  158875. int lW,int W,int nW){
  158876. lW=(W?lW:0);
  158877. nW=(W?nW:0);
  158878. {
  158879. float *windowLW=vwin[winno[lW]];
  158880. float *windowNW=vwin[winno[nW]];
  158881. long n=blocksizes[W];
  158882. long ln=blocksizes[lW];
  158883. long rn=blocksizes[nW];
  158884. long leftbegin=n/4-ln/4;
  158885. long leftend=leftbegin+ln/2;
  158886. long rightbegin=n/2+n/4-rn/4;
  158887. long rightend=rightbegin+rn/2;
  158888. int i,p;
  158889. for(i=0;i<leftbegin;i++)
  158890. d[i]=0.f;
  158891. for(p=0;i<leftend;i++,p++)
  158892. d[i]*=windowLW[p];
  158893. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  158894. d[i]*=windowNW[p];
  158895. for(;i<n;i++)
  158896. d[i]=0.f;
  158897. }
  158898. }
  158899. #endif
  158900. /*** End of inlined file: window.c ***/
  158901. #else
  158902. #include <vorbis/vorbisenc.h>
  158903. #include <vorbis/codec.h>
  158904. #include <vorbis/vorbisfile.h>
  158905. #endif
  158906. }
  158907. #undef max
  158908. #undef min
  158909. BEGIN_JUCE_NAMESPACE
  158910. static const char* const oggFormatName = "Ogg-Vorbis file";
  158911. static const char* const oggExtensions[] = { ".ogg", 0 };
  158912. class OggReader : public AudioFormatReader
  158913. {
  158914. OggVorbisNamespace::OggVorbis_File ovFile;
  158915. OggVorbisNamespace::ov_callbacks callbacks;
  158916. AudioSampleBuffer reservoir;
  158917. int reservoirStart, samplesInReservoir;
  158918. public:
  158919. OggReader (InputStream* const inp)
  158920. : AudioFormatReader (inp, TRANS (oggFormatName)),
  158921. reservoir (2, 4096),
  158922. reservoirStart (0),
  158923. samplesInReservoir (0)
  158924. {
  158925. using namespace OggVorbisNamespace;
  158926. sampleRate = 0;
  158927. usesFloatingPointData = true;
  158928. callbacks.read_func = &oggReadCallback;
  158929. callbacks.seek_func = &oggSeekCallback;
  158930. callbacks.close_func = &oggCloseCallback;
  158931. callbacks.tell_func = &oggTellCallback;
  158932. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  158933. if (err == 0)
  158934. {
  158935. vorbis_info* info = ov_info (&ovFile, -1);
  158936. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  158937. numChannels = info->channels;
  158938. bitsPerSample = 16;
  158939. sampleRate = info->rate;
  158940. reservoir.setSize (numChannels,
  158941. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  158942. }
  158943. }
  158944. ~OggReader()
  158945. {
  158946. OggVorbisNamespace::ov_clear (&ovFile);
  158947. }
  158948. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  158949. int64 startSampleInFile, int numSamples)
  158950. {
  158951. while (numSamples > 0)
  158952. {
  158953. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  158954. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  158955. {
  158956. // got a few samples overlapping, so use them before seeking..
  158957. const int numToUse = jmin (numSamples, numAvailable);
  158958. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  158959. if (destSamples[i] != 0)
  158960. memcpy (destSamples[i] + startOffsetInDestBuffer,
  158961. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  158962. sizeof (float) * numToUse);
  158963. startSampleInFile += numToUse;
  158964. numSamples -= numToUse;
  158965. startOffsetInDestBuffer += numToUse;
  158966. if (numSamples == 0)
  158967. break;
  158968. }
  158969. if (startSampleInFile < reservoirStart
  158970. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  158971. {
  158972. // buffer miss, so refill the reservoir
  158973. int bitStream = 0;
  158974. reservoirStart = jmax (0, (int) startSampleInFile);
  158975. samplesInReservoir = reservoir.getNumSamples();
  158976. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  158977. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  158978. int offset = 0;
  158979. int numToRead = samplesInReservoir;
  158980. while (numToRead > 0)
  158981. {
  158982. float** dataIn = 0;
  158983. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  158984. if (samps <= 0)
  158985. break;
  158986. jassert (samps <= numToRead);
  158987. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  158988. {
  158989. memcpy (reservoir.getSampleData (i, offset),
  158990. dataIn[i],
  158991. sizeof (float) * samps);
  158992. }
  158993. numToRead -= samps;
  158994. offset += samps;
  158995. }
  158996. if (numToRead > 0)
  158997. reservoir.clear (offset, numToRead);
  158998. }
  158999. }
  159000. if (numSamples > 0)
  159001. {
  159002. for (int i = numDestChannels; --i >= 0;)
  159003. if (destSamples[i] != 0)
  159004. zeromem (destSamples[i] + startOffsetInDestBuffer,
  159005. sizeof (int) * numSamples);
  159006. }
  159007. return true;
  159008. }
  159009. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  159010. {
  159011. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  159012. }
  159013. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  159014. {
  159015. InputStream* const in = static_cast <InputStream*> (datasource);
  159016. if (whence == SEEK_CUR)
  159017. offset += in->getPosition();
  159018. else if (whence == SEEK_END)
  159019. offset += in->getTotalLength();
  159020. in->setPosition (offset);
  159021. return 0;
  159022. }
  159023. static int oggCloseCallback (void*)
  159024. {
  159025. return 0;
  159026. }
  159027. static long oggTellCallback (void* datasource)
  159028. {
  159029. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159030. }
  159031. private:
  159032. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggReader);
  159033. };
  159034. class OggWriter : public AudioFormatWriter
  159035. {
  159036. OggVorbisNamespace::ogg_stream_state os;
  159037. OggVorbisNamespace::ogg_page og;
  159038. OggVorbisNamespace::ogg_packet op;
  159039. OggVorbisNamespace::vorbis_info vi;
  159040. OggVorbisNamespace::vorbis_comment vc;
  159041. OggVorbisNamespace::vorbis_dsp_state vd;
  159042. OggVorbisNamespace::vorbis_block vb;
  159043. public:
  159044. bool ok;
  159045. OggWriter (OutputStream* const out,
  159046. const double sampleRate,
  159047. const int numChannels,
  159048. const int bitsPerSample,
  159049. const int qualityIndex)
  159050. : AudioFormatWriter (out, TRANS (oggFormatName),
  159051. sampleRate,
  159052. numChannels,
  159053. bitsPerSample)
  159054. {
  159055. using namespace OggVorbisNamespace;
  159056. ok = false;
  159057. vorbis_info_init (&vi);
  159058. if (vorbis_encode_init_vbr (&vi,
  159059. numChannels,
  159060. (int) sampleRate,
  159061. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159062. {
  159063. vorbis_comment_init (&vc);
  159064. if (JUCEApplication::getInstance() != 0)
  159065. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8().getAddress()));
  159066. vorbis_analysis_init (&vd, &vi);
  159067. vorbis_block_init (&vd, &vb);
  159068. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159069. ogg_packet header;
  159070. ogg_packet header_comm;
  159071. ogg_packet header_code;
  159072. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159073. ogg_stream_packetin (&os, &header);
  159074. ogg_stream_packetin (&os, &header_comm);
  159075. ogg_stream_packetin (&os, &header_code);
  159076. for (;;)
  159077. {
  159078. if (ogg_stream_flush (&os, &og) == 0)
  159079. break;
  159080. output->write (og.header, og.header_len);
  159081. output->write (og.body, og.body_len);
  159082. }
  159083. ok = true;
  159084. }
  159085. }
  159086. ~OggWriter()
  159087. {
  159088. using namespace OggVorbisNamespace;
  159089. if (ok)
  159090. {
  159091. // write a zero-length packet to show ogg that we're finished..
  159092. write (0, 0);
  159093. ogg_stream_clear (&os);
  159094. vorbis_block_clear (&vb);
  159095. vorbis_dsp_clear (&vd);
  159096. vorbis_comment_clear (&vc);
  159097. vorbis_info_clear (&vi);
  159098. output->flush();
  159099. }
  159100. else
  159101. {
  159102. vorbis_info_clear (&vi);
  159103. output = 0; // to stop the base class deleting this, as it needs to be returned
  159104. // to the caller of createWriter()
  159105. }
  159106. }
  159107. bool write (const int** samplesToWrite, int numSamples)
  159108. {
  159109. using namespace OggVorbisNamespace;
  159110. if (! ok)
  159111. return false;
  159112. if (numSamples > 0)
  159113. {
  159114. const double gain = 1.0 / 0x80000000u;
  159115. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159116. for (int i = numChannels; --i >= 0;)
  159117. {
  159118. float* const dst = vorbisBuffer[i];
  159119. const int* const src = samplesToWrite [i];
  159120. if (src != 0 && dst != 0)
  159121. {
  159122. for (int j = 0; j < numSamples; ++j)
  159123. dst[j] = (float) (src[j] * gain);
  159124. }
  159125. }
  159126. }
  159127. vorbis_analysis_wrote (&vd, numSamples);
  159128. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159129. {
  159130. vorbis_analysis (&vb, 0);
  159131. vorbis_bitrate_addblock (&vb);
  159132. while (vorbis_bitrate_flushpacket (&vd, &op))
  159133. {
  159134. ogg_stream_packetin (&os, &op);
  159135. for (;;)
  159136. {
  159137. if (ogg_stream_pageout (&os, &og) == 0)
  159138. break;
  159139. output->write (og.header, og.header_len);
  159140. output->write (og.body, og.body_len);
  159141. if (ogg_page_eos (&og))
  159142. break;
  159143. }
  159144. }
  159145. }
  159146. return true;
  159147. }
  159148. private:
  159149. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggWriter);
  159150. };
  159151. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159152. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159153. {
  159154. }
  159155. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159156. {
  159157. }
  159158. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159159. {
  159160. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159161. return Array <int> (rates);
  159162. }
  159163. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159164. {
  159165. const int depths[] = { 32, 0 };
  159166. return Array <int> (depths);
  159167. }
  159168. bool OggVorbisAudioFormat::canDoStereo() { return true; }
  159169. bool OggVorbisAudioFormat::canDoMono() { return true; }
  159170. bool OggVorbisAudioFormat::isCompressed() { return true; }
  159171. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159172. const bool deleteStreamIfOpeningFails)
  159173. {
  159174. ScopedPointer <OggReader> r (new OggReader (in));
  159175. if (r->sampleRate != 0)
  159176. return r.release();
  159177. if (! deleteStreamIfOpeningFails)
  159178. r->input = 0;
  159179. return 0;
  159180. }
  159181. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159182. double sampleRate,
  159183. unsigned int numChannels,
  159184. int bitsPerSample,
  159185. const StringPairArray& /*metadataValues*/,
  159186. int qualityOptionIndex)
  159187. {
  159188. ScopedPointer <OggWriter> w (new OggWriter (out,
  159189. sampleRate,
  159190. numChannels,
  159191. bitsPerSample,
  159192. qualityOptionIndex));
  159193. return w->ok ? w.release() : 0;
  159194. }
  159195. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159196. {
  159197. StringArray s;
  159198. s.add ("Low Quality");
  159199. s.add ("Medium Quality");
  159200. s.add ("High Quality");
  159201. return s;
  159202. }
  159203. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159204. {
  159205. FileInputStream* const in = source.createInputStream();
  159206. if (in != 0)
  159207. {
  159208. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159209. if (r != 0)
  159210. {
  159211. const int64 numSamps = r->lengthInSamples;
  159212. r = 0;
  159213. const int64 fileNumSamps = source.getSize() / 4;
  159214. const double ratio = numSamps / (double) fileNumSamps;
  159215. if (ratio > 12.0)
  159216. return 0;
  159217. else if (ratio > 6.0)
  159218. return 1;
  159219. else
  159220. return 2;
  159221. }
  159222. }
  159223. return 1;
  159224. }
  159225. END_JUCE_NAMESPACE
  159226. #endif
  159227. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159228. #endif
  159229. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159230. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159231. #if JUCE_MSVC
  159232. #pragma warning (push)
  159233. #endif
  159234. namespace jpeglibNamespace
  159235. {
  159236. #if JUCE_INCLUDE_JPEGLIB_CODE
  159237. #if JUCE_MINGW
  159238. typedef unsigned char boolean;
  159239. #endif
  159240. #define JPEG_INTERNALS
  159241. #undef FAR
  159242. /*** Start of inlined file: jpeglib.h ***/
  159243. #ifndef JPEGLIB_H
  159244. #define JPEGLIB_H
  159245. /*
  159246. * First we include the configuration files that record how this
  159247. * installation of the JPEG library is set up. jconfig.h can be
  159248. * generated automatically for many systems. jmorecfg.h contains
  159249. * manual configuration options that most people need not worry about.
  159250. */
  159251. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159252. /*** Start of inlined file: jconfig.h ***/
  159253. /* see jconfig.doc for explanations */
  159254. // disable all the warnings under MSVC
  159255. #ifdef _MSC_VER
  159256. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159257. #endif
  159258. #ifdef __BORLANDC__
  159259. #pragma warn -8057
  159260. #pragma warn -8019
  159261. #pragma warn -8004
  159262. #pragma warn -8008
  159263. #endif
  159264. #define HAVE_PROTOTYPES
  159265. #define HAVE_UNSIGNED_CHAR
  159266. #define HAVE_UNSIGNED_SHORT
  159267. /* #define void char */
  159268. /* #define const */
  159269. #undef CHAR_IS_UNSIGNED
  159270. #define HAVE_STDDEF_H
  159271. #define HAVE_STDLIB_H
  159272. #undef NEED_BSD_STRINGS
  159273. #undef NEED_SYS_TYPES_H
  159274. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159275. #undef NEED_SHORT_EXTERNAL_NAMES
  159276. #undef INCOMPLETE_TYPES_BROKEN
  159277. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159278. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159279. typedef unsigned char boolean;
  159280. #endif
  159281. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159282. #ifdef JPEG_INTERNALS
  159283. #undef RIGHT_SHIFT_IS_UNSIGNED
  159284. #endif /* JPEG_INTERNALS */
  159285. #ifdef JPEG_CJPEG_DJPEG
  159286. #define BMP_SUPPORTED /* BMP image file format */
  159287. #define GIF_SUPPORTED /* GIF image file format */
  159288. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159289. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159290. #define TARGA_SUPPORTED /* Targa image file format */
  159291. #define TWO_FILE_COMMANDLINE /* optional */
  159292. #define USE_SETMODE /* Microsoft has setmode() */
  159293. #undef NEED_SIGNAL_CATCHER
  159294. #undef DONT_USE_B_MODE
  159295. #undef PROGRESS_REPORT /* optional */
  159296. #endif /* JPEG_CJPEG_DJPEG */
  159297. /*** End of inlined file: jconfig.h ***/
  159298. /* widely used configuration options */
  159299. #endif
  159300. /*** Start of inlined file: jmorecfg.h ***/
  159301. /*
  159302. * Define BITS_IN_JSAMPLE as either
  159303. * 8 for 8-bit sample values (the usual setting)
  159304. * 12 for 12-bit sample values
  159305. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159306. * JPEG standard, and the IJG code does not support anything else!
  159307. * We do not support run-time selection of data precision, sorry.
  159308. */
  159309. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159310. /*
  159311. * Maximum number of components (color channels) allowed in JPEG image.
  159312. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159313. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159314. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159315. * really short on memory. (Each allowed component costs a hundred or so
  159316. * bytes of storage, whether actually used in an image or not.)
  159317. */
  159318. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159319. /*
  159320. * Basic data types.
  159321. * You may need to change these if you have a machine with unusual data
  159322. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159323. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159324. * but it had better be at least 16.
  159325. */
  159326. /* Representation of a single sample (pixel element value).
  159327. * We frequently allocate large arrays of these, so it's important to keep
  159328. * them small. But if you have memory to burn and access to char or short
  159329. * arrays is very slow on your hardware, you might want to change these.
  159330. */
  159331. #if BITS_IN_JSAMPLE == 8
  159332. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159333. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159334. */
  159335. #ifdef HAVE_UNSIGNED_CHAR
  159336. typedef unsigned char JSAMPLE;
  159337. #define GETJSAMPLE(value) ((int) (value))
  159338. #else /* not HAVE_UNSIGNED_CHAR */
  159339. typedef char JSAMPLE;
  159340. #ifdef CHAR_IS_UNSIGNED
  159341. #define GETJSAMPLE(value) ((int) (value))
  159342. #else
  159343. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159344. #endif /* CHAR_IS_UNSIGNED */
  159345. #endif /* HAVE_UNSIGNED_CHAR */
  159346. #define MAXJSAMPLE 255
  159347. #define CENTERJSAMPLE 128
  159348. #endif /* BITS_IN_JSAMPLE == 8 */
  159349. #if BITS_IN_JSAMPLE == 12
  159350. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159351. * On nearly all machines "short" will do nicely.
  159352. */
  159353. typedef short JSAMPLE;
  159354. #define GETJSAMPLE(value) ((int) (value))
  159355. #define MAXJSAMPLE 4095
  159356. #define CENTERJSAMPLE 2048
  159357. #endif /* BITS_IN_JSAMPLE == 12 */
  159358. /* Representation of a DCT frequency coefficient.
  159359. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159360. * Again, we allocate large arrays of these, but you can change to int
  159361. * if you have memory to burn and "short" is really slow.
  159362. */
  159363. typedef short JCOEF;
  159364. /* Compressed datastreams are represented as arrays of JOCTET.
  159365. * These must be EXACTLY 8 bits wide, at least once they are written to
  159366. * external storage. Note that when using the stdio data source/destination
  159367. * managers, this is also the data type passed to fread/fwrite.
  159368. */
  159369. #ifdef HAVE_UNSIGNED_CHAR
  159370. typedef unsigned char JOCTET;
  159371. #define GETJOCTET(value) (value)
  159372. #else /* not HAVE_UNSIGNED_CHAR */
  159373. typedef char JOCTET;
  159374. #ifdef CHAR_IS_UNSIGNED
  159375. #define GETJOCTET(value) (value)
  159376. #else
  159377. #define GETJOCTET(value) ((value) & 0xFF)
  159378. #endif /* CHAR_IS_UNSIGNED */
  159379. #endif /* HAVE_UNSIGNED_CHAR */
  159380. /* These typedefs are used for various table entries and so forth.
  159381. * They must be at least as wide as specified; but making them too big
  159382. * won't cost a huge amount of memory, so we don't provide special
  159383. * extraction code like we did for JSAMPLE. (In other words, these
  159384. * typedefs live at a different point on the speed/space tradeoff curve.)
  159385. */
  159386. /* UINT8 must hold at least the values 0..255. */
  159387. #ifdef HAVE_UNSIGNED_CHAR
  159388. typedef unsigned char UINT8;
  159389. #else /* not HAVE_UNSIGNED_CHAR */
  159390. #ifdef CHAR_IS_UNSIGNED
  159391. typedef char UINT8;
  159392. #else /* not CHAR_IS_UNSIGNED */
  159393. typedef short UINT8;
  159394. #endif /* CHAR_IS_UNSIGNED */
  159395. #endif /* HAVE_UNSIGNED_CHAR */
  159396. /* UINT16 must hold at least the values 0..65535. */
  159397. #ifdef HAVE_UNSIGNED_SHORT
  159398. typedef unsigned short UINT16;
  159399. #else /* not HAVE_UNSIGNED_SHORT */
  159400. typedef unsigned int UINT16;
  159401. #endif /* HAVE_UNSIGNED_SHORT */
  159402. /* INT16 must hold at least the values -32768..32767. */
  159403. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159404. typedef short INT16;
  159405. #endif
  159406. /* INT32 must hold at least signed 32-bit values. */
  159407. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159408. typedef long INT32;
  159409. #endif
  159410. /* Datatype used for image dimensions. The JPEG standard only supports
  159411. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159412. * "unsigned int" is sufficient on all machines. However, if you need to
  159413. * handle larger images and you don't mind deviating from the spec, you
  159414. * can change this datatype.
  159415. */
  159416. typedef unsigned int JDIMENSION;
  159417. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159418. /* These macros are used in all function definitions and extern declarations.
  159419. * You could modify them if you need to change function linkage conventions;
  159420. * in particular, you'll need to do that to make the library a Windows DLL.
  159421. * Another application is to make all functions global for use with debuggers
  159422. * or code profilers that require it.
  159423. */
  159424. /* a function called through method pointers: */
  159425. #define METHODDEF(type) static type
  159426. /* a function used only in its module: */
  159427. #define LOCAL(type) static type
  159428. /* a function referenced thru EXTERNs: */
  159429. #define GLOBAL(type) type
  159430. /* a reference to a GLOBAL function: */
  159431. #define EXTERN(type) extern type
  159432. /* This macro is used to declare a "method", that is, a function pointer.
  159433. * We want to supply prototype parameters if the compiler can cope.
  159434. * Note that the arglist parameter must be parenthesized!
  159435. * Again, you can customize this if you need special linkage keywords.
  159436. */
  159437. #ifdef HAVE_PROTOTYPES
  159438. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159439. #else
  159440. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159441. #endif
  159442. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159443. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159444. * by just saying "FAR *" where such a pointer is needed. In a few places
  159445. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159446. */
  159447. #ifdef NEED_FAR_POINTERS
  159448. #define FAR far
  159449. #else
  159450. #define FAR
  159451. #endif
  159452. /*
  159453. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159454. * in standard header files. Or you may have conflicts with application-
  159455. * specific header files that you want to include together with these files.
  159456. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159457. */
  159458. #ifndef HAVE_BOOLEAN
  159459. typedef int boolean;
  159460. #endif
  159461. #ifndef FALSE /* in case these macros already exist */
  159462. #define FALSE 0 /* values of boolean */
  159463. #endif
  159464. #ifndef TRUE
  159465. #define TRUE 1
  159466. #endif
  159467. /*
  159468. * The remaining options affect code selection within the JPEG library,
  159469. * but they don't need to be visible to most applications using the library.
  159470. * To minimize application namespace pollution, the symbols won't be
  159471. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159472. */
  159473. #ifdef JPEG_INTERNALS
  159474. #define JPEG_INTERNAL_OPTIONS
  159475. #endif
  159476. #ifdef JPEG_INTERNAL_OPTIONS
  159477. /*
  159478. * These defines indicate whether to include various optional functions.
  159479. * Undefining some of these symbols will produce a smaller but less capable
  159480. * library. Note that you can leave certain source files out of the
  159481. * compilation/linking process if you've #undef'd the corresponding symbols.
  159482. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159483. */
  159484. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159485. /* Capability options common to encoder and decoder: */
  159486. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159487. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  159488. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  159489. /* Encoder capability options: */
  159490. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159491. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159492. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159493. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  159494. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  159495. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  159496. * precision, so jchuff.c normally uses entropy optimization to compute
  159497. * usable tables for higher precision. If you don't want to do optimization,
  159498. * you'll have to supply different default Huffman tables.
  159499. * The exact same statements apply for progressive JPEG: the default tables
  159500. * don't work for progressive mode. (This may get fixed, however.)
  159501. */
  159502. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  159503. /* Decoder capability options: */
  159504. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159505. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159506. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159507. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  159508. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  159509. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  159510. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  159511. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  159512. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  159513. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  159514. /* more capability options later, no doubt */
  159515. /*
  159516. * Ordering of RGB data in scanlines passed to or from the application.
  159517. * If your application wants to deal with data in the order B,G,R, just
  159518. * change these macros. You can also deal with formats such as R,G,B,X
  159519. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  159520. * the offsets will also change the order in which colormap data is organized.
  159521. * RESTRICTIONS:
  159522. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  159523. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  159524. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  159525. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  159526. * is not 3 (they don't understand about dummy color components!). So you
  159527. * can't use color quantization if you change that value.
  159528. */
  159529. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  159530. #define RGB_GREEN 1 /* Offset of Green */
  159531. #define RGB_BLUE 2 /* Offset of Blue */
  159532. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  159533. /* Definitions for speed-related optimizations. */
  159534. /* If your compiler supports inline functions, define INLINE
  159535. * as the inline keyword; otherwise define it as empty.
  159536. */
  159537. #ifndef INLINE
  159538. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  159539. #define INLINE __inline__
  159540. #endif
  159541. #ifndef INLINE
  159542. #define INLINE /* default is to define it as empty */
  159543. #endif
  159544. #endif
  159545. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  159546. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  159547. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  159548. */
  159549. #ifndef MULTIPLIER
  159550. #define MULTIPLIER int /* type for fastest integer multiply */
  159551. #endif
  159552. /* FAST_FLOAT should be either float or double, whichever is done faster
  159553. * by your compiler. (Note that this type is only used in the floating point
  159554. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  159555. * Typically, float is faster in ANSI C compilers, while double is faster in
  159556. * pre-ANSI compilers (because they insist on converting to double anyway).
  159557. * The code below therefore chooses float if we have ANSI-style prototypes.
  159558. */
  159559. #ifndef FAST_FLOAT
  159560. #ifdef HAVE_PROTOTYPES
  159561. #define FAST_FLOAT float
  159562. #else
  159563. #define FAST_FLOAT double
  159564. #endif
  159565. #endif
  159566. #endif /* JPEG_INTERNAL_OPTIONS */
  159567. /*** End of inlined file: jmorecfg.h ***/
  159568. /* seldom changed options */
  159569. /* Version ID for the JPEG library.
  159570. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  159571. */
  159572. #define JPEG_LIB_VERSION 62 /* Version 6b */
  159573. /* Various constants determining the sizes of things.
  159574. * All of these are specified by the JPEG standard, so don't change them
  159575. * if you want to be compatible.
  159576. */
  159577. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  159578. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  159579. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  159580. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  159581. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  159582. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  159583. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  159584. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  159585. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  159586. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  159587. * to handle it. We even let you do this from the jconfig.h file. However,
  159588. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  159589. * sometimes emits noncompliant files doesn't mean you should too.
  159590. */
  159591. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  159592. #ifndef D_MAX_BLOCKS_IN_MCU
  159593. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  159594. #endif
  159595. /* Data structures for images (arrays of samples and of DCT coefficients).
  159596. * On 80x86 machines, the image arrays are too big for near pointers,
  159597. * but the pointer arrays can fit in near memory.
  159598. */
  159599. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  159600. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  159601. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  159602. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  159603. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  159604. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  159605. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  159606. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  159607. /* Types for JPEG compression parameters and working tables. */
  159608. /* DCT coefficient quantization tables. */
  159609. typedef struct {
  159610. /* This array gives the coefficient quantizers in natural array order
  159611. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  159612. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  159613. */
  159614. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  159615. /* This field is used only during compression. It's initialized FALSE when
  159616. * the table is created, and set TRUE when it's been output to the file.
  159617. * You could suppress output of a table by setting this to TRUE.
  159618. * (See jpeg_suppress_tables for an example.)
  159619. */
  159620. boolean sent_table; /* TRUE when table has been output */
  159621. } JQUANT_TBL;
  159622. /* Huffman coding tables. */
  159623. typedef struct {
  159624. /* These two fields directly represent the contents of a JPEG DHT marker */
  159625. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  159626. /* length k bits; bits[0] is unused */
  159627. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  159628. /* This field is used only during compression. It's initialized FALSE when
  159629. * the table is created, and set TRUE when it's been output to the file.
  159630. * You could suppress output of a table by setting this to TRUE.
  159631. * (See jpeg_suppress_tables for an example.)
  159632. */
  159633. boolean sent_table; /* TRUE when table has been output */
  159634. } JHUFF_TBL;
  159635. /* Basic info about one component (color channel). */
  159636. typedef struct {
  159637. /* These values are fixed over the whole image. */
  159638. /* For compression, they must be supplied by parameter setup; */
  159639. /* for decompression, they are read from the SOF marker. */
  159640. int component_id; /* identifier for this component (0..255) */
  159641. int component_index; /* its index in SOF or cinfo->comp_info[] */
  159642. int h_samp_factor; /* horizontal sampling factor (1..4) */
  159643. int v_samp_factor; /* vertical sampling factor (1..4) */
  159644. int quant_tbl_no; /* quantization table selector (0..3) */
  159645. /* These values may vary between scans. */
  159646. /* For compression, they must be supplied by parameter setup; */
  159647. /* for decompression, they are read from the SOS marker. */
  159648. /* The decompressor output side may not use these variables. */
  159649. int dc_tbl_no; /* DC entropy table selector (0..3) */
  159650. int ac_tbl_no; /* AC entropy table selector (0..3) */
  159651. /* Remaining fields should be treated as private by applications. */
  159652. /* These values are computed during compression or decompression startup: */
  159653. /* Component's size in DCT blocks.
  159654. * Any dummy blocks added to complete an MCU are not counted; therefore
  159655. * these values do not depend on whether a scan is interleaved or not.
  159656. */
  159657. JDIMENSION width_in_blocks;
  159658. JDIMENSION height_in_blocks;
  159659. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  159660. * For decompression this is the size of the output from one DCT block,
  159661. * reflecting any scaling we choose to apply during the IDCT step.
  159662. * Values of 1,2,4,8 are likely to be supported. Note that different
  159663. * components may receive different IDCT scalings.
  159664. */
  159665. int DCT_scaled_size;
  159666. /* The downsampled dimensions are the component's actual, unpadded number
  159667. * of samples at the main buffer (preprocessing/compression interface), thus
  159668. * downsampled_width = ceil(image_width * Hi/Hmax)
  159669. * and similarly for height. For decompression, IDCT scaling is included, so
  159670. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  159671. */
  159672. JDIMENSION downsampled_width; /* actual width in samples */
  159673. JDIMENSION downsampled_height; /* actual height in samples */
  159674. /* This flag is used only for decompression. In cases where some of the
  159675. * components will be ignored (eg grayscale output from YCbCr image),
  159676. * we can skip most computations for the unused components.
  159677. */
  159678. boolean component_needed; /* do we need the value of this component? */
  159679. /* These values are computed before starting a scan of the component. */
  159680. /* The decompressor output side may not use these variables. */
  159681. int MCU_width; /* number of blocks per MCU, horizontally */
  159682. int MCU_height; /* number of blocks per MCU, vertically */
  159683. int MCU_blocks; /* MCU_width * MCU_height */
  159684. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  159685. int last_col_width; /* # of non-dummy blocks across in last MCU */
  159686. int last_row_height; /* # of non-dummy blocks down in last MCU */
  159687. /* Saved quantization table for component; NULL if none yet saved.
  159688. * See jdinput.c comments about the need for this information.
  159689. * This field is currently used only for decompression.
  159690. */
  159691. JQUANT_TBL * quant_table;
  159692. /* Private per-component storage for DCT or IDCT subsystem. */
  159693. void * dct_table;
  159694. } jpeg_component_info;
  159695. /* The script for encoding a multiple-scan file is an array of these: */
  159696. typedef struct {
  159697. int comps_in_scan; /* number of components encoded in this scan */
  159698. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  159699. int Ss, Se; /* progressive JPEG spectral selection parms */
  159700. int Ah, Al; /* progressive JPEG successive approx. parms */
  159701. } jpeg_scan_info;
  159702. /* The decompressor can save APPn and COM markers in a list of these: */
  159703. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  159704. struct jpeg_marker_struct {
  159705. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  159706. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  159707. unsigned int original_length; /* # bytes of data in the file */
  159708. unsigned int data_length; /* # bytes of data saved at data[] */
  159709. JOCTET FAR * data; /* the data contained in the marker */
  159710. /* the marker length word is not counted in data_length or original_length */
  159711. };
  159712. /* Known color spaces. */
  159713. typedef enum {
  159714. JCS_UNKNOWN, /* error/unspecified */
  159715. JCS_GRAYSCALE, /* monochrome */
  159716. JCS_RGB, /* red/green/blue */
  159717. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  159718. JCS_CMYK, /* C/M/Y/K */
  159719. JCS_YCCK /* Y/Cb/Cr/K */
  159720. } J_COLOR_SPACE;
  159721. /* DCT/IDCT algorithm options. */
  159722. typedef enum {
  159723. JDCT_ISLOW, /* slow but accurate integer algorithm */
  159724. JDCT_IFAST, /* faster, less accurate integer method */
  159725. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  159726. } J_DCT_METHOD;
  159727. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  159728. #define JDCT_DEFAULT JDCT_ISLOW
  159729. #endif
  159730. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  159731. #define JDCT_FASTEST JDCT_IFAST
  159732. #endif
  159733. /* Dithering options for decompression. */
  159734. typedef enum {
  159735. JDITHER_NONE, /* no dithering */
  159736. JDITHER_ORDERED, /* simple ordered dither */
  159737. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  159738. } J_DITHER_MODE;
  159739. /* Common fields between JPEG compression and decompression master structs. */
  159740. #define jpeg_common_fields \
  159741. struct jpeg_error_mgr * err; /* Error handler module */\
  159742. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  159743. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  159744. void * client_data; /* Available for use by application */\
  159745. boolean is_decompressor; /* So common code can tell which is which */\
  159746. int global_state /* For checking call sequence validity */
  159747. /* Routines that are to be used by both halves of the library are declared
  159748. * to receive a pointer to this structure. There are no actual instances of
  159749. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  159750. */
  159751. struct jpeg_common_struct {
  159752. jpeg_common_fields; /* Fields common to both master struct types */
  159753. /* Additional fields follow in an actual jpeg_compress_struct or
  159754. * jpeg_decompress_struct. All three structs must agree on these
  159755. * initial fields! (This would be a lot cleaner in C++.)
  159756. */
  159757. };
  159758. typedef struct jpeg_common_struct * j_common_ptr;
  159759. typedef struct jpeg_compress_struct * j_compress_ptr;
  159760. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  159761. /* Master record for a compression instance */
  159762. struct jpeg_compress_struct {
  159763. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  159764. /* Destination for compressed data */
  159765. struct jpeg_destination_mgr * dest;
  159766. /* Description of source image --- these fields must be filled in by
  159767. * outer application before starting compression. in_color_space must
  159768. * be correct before you can even call jpeg_set_defaults().
  159769. */
  159770. JDIMENSION image_width; /* input image width */
  159771. JDIMENSION image_height; /* input image height */
  159772. int input_components; /* # of color components in input image */
  159773. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  159774. double input_gamma; /* image gamma of input image */
  159775. /* Compression parameters --- these fields must be set before calling
  159776. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  159777. * initialize everything to reasonable defaults, then changing anything
  159778. * the application specifically wants to change. That way you won't get
  159779. * burnt when new parameters are added. Also note that there are several
  159780. * helper routines to simplify changing parameters.
  159781. */
  159782. int data_precision; /* bits of precision in image data */
  159783. int num_components; /* # of color components in JPEG image */
  159784. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159785. jpeg_component_info * comp_info;
  159786. /* comp_info[i] describes component that appears i'th in SOF */
  159787. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159788. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159789. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159790. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159791. /* ptrs to Huffman coding tables, or NULL if not defined */
  159792. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159793. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159794. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159795. int num_scans; /* # of entries in scan_info array */
  159796. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  159797. /* The default value of scan_info is NULL, which causes a single-scan
  159798. * sequential JPEG file to be emitted. To create a multi-scan file,
  159799. * set num_scans and scan_info to point to an array of scan definitions.
  159800. */
  159801. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  159802. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159803. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  159804. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159805. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  159806. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  159807. /* The restart interval can be specified in absolute MCUs by setting
  159808. * restart_interval, or in MCU rows by setting restart_in_rows
  159809. * (in which case the correct restart_interval will be figured
  159810. * for each scan).
  159811. */
  159812. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  159813. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  159814. /* Parameters controlling emission of special markers. */
  159815. boolean write_JFIF_header; /* should a JFIF marker be written? */
  159816. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  159817. UINT8 JFIF_minor_version;
  159818. /* These three values are not used by the JPEG code, merely copied */
  159819. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  159820. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  159821. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  159822. UINT8 density_unit; /* JFIF code for pixel size units */
  159823. UINT16 X_density; /* Horizontal pixel density */
  159824. UINT16 Y_density; /* Vertical pixel density */
  159825. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  159826. /* State variable: index of next scanline to be written to
  159827. * jpeg_write_scanlines(). Application may use this to control its
  159828. * processing loop, e.g., "while (next_scanline < image_height)".
  159829. */
  159830. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  159831. /* Remaining fields are known throughout compressor, but generally
  159832. * should not be touched by a surrounding application.
  159833. */
  159834. /*
  159835. * These fields are computed during compression startup
  159836. */
  159837. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  159838. int max_h_samp_factor; /* largest h_samp_factor */
  159839. int max_v_samp_factor; /* largest v_samp_factor */
  159840. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  159841. /* The coefficient controller receives data in units of MCU rows as defined
  159842. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  159843. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  159844. * "iMCU" (interleaved MCU) row.
  159845. */
  159846. /*
  159847. * These fields are valid during any one scan.
  159848. * They describe the components and MCUs actually appearing in the scan.
  159849. */
  159850. int comps_in_scan; /* # of JPEG components in this scan */
  159851. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  159852. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  159853. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  159854. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  159855. int blocks_in_MCU; /* # of DCT blocks per MCU */
  159856. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  159857. /* MCU_membership[i] is index in cur_comp_info of component owning */
  159858. /* i'th block in an MCU */
  159859. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  159860. /*
  159861. * Links to compression subobjects (methods and private variables of modules)
  159862. */
  159863. struct jpeg_comp_master * master;
  159864. struct jpeg_c_main_controller * main;
  159865. struct jpeg_c_prep_controller * prep;
  159866. struct jpeg_c_coef_controller * coef;
  159867. struct jpeg_marker_writer * marker;
  159868. struct jpeg_color_converter * cconvert;
  159869. struct jpeg_downsampler * downsample;
  159870. struct jpeg_forward_dct * fdct;
  159871. struct jpeg_entropy_encoder * entropy;
  159872. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  159873. int script_space_size;
  159874. };
  159875. /* Master record for a decompression instance */
  159876. struct jpeg_decompress_struct {
  159877. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  159878. /* Source of compressed data */
  159879. struct jpeg_source_mgr * src;
  159880. /* Basic description of image --- filled in by jpeg_read_header(). */
  159881. /* Application may inspect these values to decide how to process image. */
  159882. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  159883. JDIMENSION image_height; /* nominal image height */
  159884. int num_components; /* # of color components in JPEG image */
  159885. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159886. /* Decompression processing parameters --- these fields must be set before
  159887. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  159888. * them to default values.
  159889. */
  159890. J_COLOR_SPACE out_color_space; /* colorspace for output */
  159891. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  159892. double output_gamma; /* image gamma wanted in output */
  159893. boolean buffered_image; /* TRUE=multiple output passes */
  159894. boolean raw_data_out; /* TRUE=downsampled data wanted */
  159895. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  159896. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  159897. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  159898. boolean quantize_colors; /* TRUE=colormapped output wanted */
  159899. /* the following are ignored if not quantize_colors: */
  159900. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  159901. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  159902. int desired_number_of_colors; /* max # colors to use in created colormap */
  159903. /* these are significant only in buffered-image mode: */
  159904. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  159905. boolean enable_external_quant;/* enable future use of external colormap */
  159906. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  159907. /* Description of actual output image that will be returned to application.
  159908. * These fields are computed by jpeg_start_decompress().
  159909. * You can also use jpeg_calc_output_dimensions() to determine these values
  159910. * in advance of calling jpeg_start_decompress().
  159911. */
  159912. JDIMENSION output_width; /* scaled image width */
  159913. JDIMENSION output_height; /* scaled image height */
  159914. int out_color_components; /* # of color components in out_color_space */
  159915. int output_components; /* # of color components returned */
  159916. /* output_components is 1 (a colormap index) when quantizing colors;
  159917. * otherwise it equals out_color_components.
  159918. */
  159919. int rec_outbuf_height; /* min recommended height of scanline buffer */
  159920. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  159921. * high, space and time will be wasted due to unnecessary data copying.
  159922. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  159923. */
  159924. /* When quantizing colors, the output colormap is described by these fields.
  159925. * The application can supply a colormap by setting colormap non-NULL before
  159926. * calling jpeg_start_decompress; otherwise a colormap is created during
  159927. * jpeg_start_decompress or jpeg_start_output.
  159928. * The map has out_color_components rows and actual_number_of_colors columns.
  159929. */
  159930. int actual_number_of_colors; /* number of entries in use */
  159931. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  159932. /* State variables: these variables indicate the progress of decompression.
  159933. * The application may examine these but must not modify them.
  159934. */
  159935. /* Row index of next scanline to be read from jpeg_read_scanlines().
  159936. * Application may use this to control its processing loop, e.g.,
  159937. * "while (output_scanline < output_height)".
  159938. */
  159939. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  159940. /* Current input scan number and number of iMCU rows completed in scan.
  159941. * These indicate the progress of the decompressor input side.
  159942. */
  159943. int input_scan_number; /* Number of SOS markers seen so far */
  159944. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  159945. /* The "output scan number" is the notional scan being displayed by the
  159946. * output side. The decompressor will not allow output scan/row number
  159947. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  159948. */
  159949. int output_scan_number; /* Nominal scan number being displayed */
  159950. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  159951. /* Current progression status. coef_bits[c][i] indicates the precision
  159952. * with which component c's DCT coefficient i (in zigzag order) is known.
  159953. * It is -1 when no data has yet been received, otherwise it is the point
  159954. * transform (shift) value for the most recent scan of the coefficient
  159955. * (thus, 0 at completion of the progression).
  159956. * This pointer is NULL when reading a non-progressive file.
  159957. */
  159958. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  159959. /* Internal JPEG parameters --- the application usually need not look at
  159960. * these fields. Note that the decompressor output side may not use
  159961. * any parameters that can change between scans.
  159962. */
  159963. /* Quantization and Huffman tables are carried forward across input
  159964. * datastreams when processing abbreviated JPEG datastreams.
  159965. */
  159966. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159967. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159968. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159969. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159970. /* ptrs to Huffman coding tables, or NULL if not defined */
  159971. /* These parameters are never carried across datastreams, since they
  159972. * are given in SOF/SOS markers or defined to be reset by SOI.
  159973. */
  159974. int data_precision; /* bits of precision in image data */
  159975. jpeg_component_info * comp_info;
  159976. /* comp_info[i] describes component that appears i'th in SOF */
  159977. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  159978. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159979. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159980. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159981. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159982. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  159983. /* These fields record data obtained from optional markers recognized by
  159984. * the JPEG library.
  159985. */
  159986. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  159987. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  159988. UINT8 JFIF_major_version; /* JFIF version number */
  159989. UINT8 JFIF_minor_version;
  159990. UINT8 density_unit; /* JFIF code for pixel size units */
  159991. UINT16 X_density; /* Horizontal pixel density */
  159992. UINT16 Y_density; /* Vertical pixel density */
  159993. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  159994. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  159995. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159996. /* Aside from the specific data retained from APPn markers known to the
  159997. * library, the uninterpreted contents of any or all APPn and COM markers
  159998. * can be saved in a list for examination by the application.
  159999. */
  160000. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  160001. /* Remaining fields are known throughout decompressor, but generally
  160002. * should not be touched by a surrounding application.
  160003. */
  160004. /*
  160005. * These fields are computed during decompression startup
  160006. */
  160007. int max_h_samp_factor; /* largest h_samp_factor */
  160008. int max_v_samp_factor; /* largest v_samp_factor */
  160009. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  160010. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  160011. /* The coefficient controller's input and output progress is measured in
  160012. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  160013. * in fully interleaved JPEG scans, but are used whether the scan is
  160014. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  160015. * rows of each component. Therefore, the IDCT output contains
  160016. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  160017. */
  160018. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160019. /*
  160020. * These fields are valid during any one scan.
  160021. * They describe the components and MCUs actually appearing in the scan.
  160022. * Note that the decompressor output side must not use these fields.
  160023. */
  160024. int comps_in_scan; /* # of JPEG components in this scan */
  160025. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160026. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160027. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160028. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160029. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160030. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160031. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160032. /* i'th block in an MCU */
  160033. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160034. /* This field is shared between entropy decoder and marker parser.
  160035. * It is either zero or the code of a JPEG marker that has been
  160036. * read from the data source, but has not yet been processed.
  160037. */
  160038. int unread_marker;
  160039. /*
  160040. * Links to decompression subobjects (methods, private variables of modules)
  160041. */
  160042. struct jpeg_decomp_master * master;
  160043. struct jpeg_d_main_controller * main;
  160044. struct jpeg_d_coef_controller * coef;
  160045. struct jpeg_d_post_controller * post;
  160046. struct jpeg_input_controller * inputctl;
  160047. struct jpeg_marker_reader * marker;
  160048. struct jpeg_entropy_decoder * entropy;
  160049. struct jpeg_inverse_dct * idct;
  160050. struct jpeg_upsampler * upsample;
  160051. struct jpeg_color_deconverter * cconvert;
  160052. struct jpeg_color_quantizer * cquantize;
  160053. };
  160054. /* "Object" declarations for JPEG modules that may be supplied or called
  160055. * directly by the surrounding application.
  160056. * As with all objects in the JPEG library, these structs only define the
  160057. * publicly visible methods and state variables of a module. Additional
  160058. * private fields may exist after the public ones.
  160059. */
  160060. /* Error handler object */
  160061. struct jpeg_error_mgr {
  160062. /* Error exit handler: does not return to caller */
  160063. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160064. /* Conditionally emit a trace or warning message */
  160065. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160066. /* Routine that actually outputs a trace or error message */
  160067. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160068. /* Format a message string for the most recent JPEG error or message */
  160069. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160070. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160071. /* Reset error state variables at start of a new image */
  160072. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160073. /* The message ID code and any parameters are saved here.
  160074. * A message can have one string parameter or up to 8 int parameters.
  160075. */
  160076. int msg_code;
  160077. #define JMSG_STR_PARM_MAX 80
  160078. union {
  160079. int i[8];
  160080. char s[JMSG_STR_PARM_MAX];
  160081. } msg_parm;
  160082. /* Standard state variables for error facility */
  160083. int trace_level; /* max msg_level that will be displayed */
  160084. /* For recoverable corrupt-data errors, we emit a warning message,
  160085. * but keep going unless emit_message chooses to abort. emit_message
  160086. * should count warnings in num_warnings. The surrounding application
  160087. * can check for bad data by seeing if num_warnings is nonzero at the
  160088. * end of processing.
  160089. */
  160090. long num_warnings; /* number of corrupt-data warnings */
  160091. /* These fields point to the table(s) of error message strings.
  160092. * An application can change the table pointer to switch to a different
  160093. * message list (typically, to change the language in which errors are
  160094. * reported). Some applications may wish to add additional error codes
  160095. * that will be handled by the JPEG library error mechanism; the second
  160096. * table pointer is used for this purpose.
  160097. *
  160098. * First table includes all errors generated by JPEG library itself.
  160099. * Error code 0 is reserved for a "no such error string" message.
  160100. */
  160101. const char * const * jpeg_message_table; /* Library errors */
  160102. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160103. /* Second table can be added by application (see cjpeg/djpeg for example).
  160104. * It contains strings numbered first_addon_message..last_addon_message.
  160105. */
  160106. const char * const * addon_message_table; /* Non-library errors */
  160107. int first_addon_message; /* code for first string in addon table */
  160108. int last_addon_message; /* code for last string in addon table */
  160109. };
  160110. /* Progress monitor object */
  160111. struct jpeg_progress_mgr {
  160112. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160113. long pass_counter; /* work units completed in this pass */
  160114. long pass_limit; /* total number of work units in this pass */
  160115. int completed_passes; /* passes completed so far */
  160116. int total_passes; /* total number of passes expected */
  160117. };
  160118. /* Data destination object for compression */
  160119. struct jpeg_destination_mgr {
  160120. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160121. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160122. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160123. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160124. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160125. };
  160126. /* Data source object for decompression */
  160127. struct jpeg_source_mgr {
  160128. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160129. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160130. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160131. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160132. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160133. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160134. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160135. };
  160136. /* Memory manager object.
  160137. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160138. * and "really big" objects (virtual arrays with backing store if needed).
  160139. * The memory manager does not allow individual objects to be freed; rather,
  160140. * each created object is assigned to a pool, and whole pools can be freed
  160141. * at once. This is faster and more convenient than remembering exactly what
  160142. * to free, especially where malloc()/free() are not too speedy.
  160143. * NB: alloc routines never return NULL. They exit to error_exit if not
  160144. * successful.
  160145. */
  160146. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160147. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160148. #define JPOOL_NUMPOOLS 2
  160149. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160150. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160151. struct jpeg_memory_mgr {
  160152. /* Method pointers */
  160153. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160154. size_t sizeofobject));
  160155. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160156. size_t sizeofobject));
  160157. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160158. JDIMENSION samplesperrow,
  160159. JDIMENSION numrows));
  160160. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160161. JDIMENSION blocksperrow,
  160162. JDIMENSION numrows));
  160163. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160164. int pool_id,
  160165. boolean pre_zero,
  160166. JDIMENSION samplesperrow,
  160167. JDIMENSION numrows,
  160168. JDIMENSION maxaccess));
  160169. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160170. int pool_id,
  160171. boolean pre_zero,
  160172. JDIMENSION blocksperrow,
  160173. JDIMENSION numrows,
  160174. JDIMENSION maxaccess));
  160175. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160176. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160177. jvirt_sarray_ptr ptr,
  160178. JDIMENSION start_row,
  160179. JDIMENSION num_rows,
  160180. boolean writable));
  160181. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160182. jvirt_barray_ptr ptr,
  160183. JDIMENSION start_row,
  160184. JDIMENSION num_rows,
  160185. boolean writable));
  160186. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160187. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160188. /* Limit on memory allocation for this JPEG object. (Note that this is
  160189. * merely advisory, not a guaranteed maximum; it only affects the space
  160190. * used for virtual-array buffers.) May be changed by outer application
  160191. * after creating the JPEG object.
  160192. */
  160193. long max_memory_to_use;
  160194. /* Maximum allocation request accepted by alloc_large. */
  160195. long max_alloc_chunk;
  160196. };
  160197. /* Routine signature for application-supplied marker processing methods.
  160198. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160199. */
  160200. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160201. /* Declarations for routines called by application.
  160202. * The JPP macro hides prototype parameters from compilers that can't cope.
  160203. * Note JPP requires double parentheses.
  160204. */
  160205. #ifdef HAVE_PROTOTYPES
  160206. #define JPP(arglist) arglist
  160207. #else
  160208. #define JPP(arglist) ()
  160209. #endif
  160210. /* Short forms of external names for systems with brain-damaged linkers.
  160211. * We shorten external names to be unique in the first six letters, which
  160212. * is good enough for all known systems.
  160213. * (If your compiler itself needs names to be unique in less than 15
  160214. * characters, you are out of luck. Get a better compiler.)
  160215. */
  160216. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160217. #define jpeg_std_error jStdError
  160218. #define jpeg_CreateCompress jCreaCompress
  160219. #define jpeg_CreateDecompress jCreaDecompress
  160220. #define jpeg_destroy_compress jDestCompress
  160221. #define jpeg_destroy_decompress jDestDecompress
  160222. #define jpeg_stdio_dest jStdDest
  160223. #define jpeg_stdio_src jStdSrc
  160224. #define jpeg_set_defaults jSetDefaults
  160225. #define jpeg_set_colorspace jSetColorspace
  160226. #define jpeg_default_colorspace jDefColorspace
  160227. #define jpeg_set_quality jSetQuality
  160228. #define jpeg_set_linear_quality jSetLQuality
  160229. #define jpeg_add_quant_table jAddQuantTable
  160230. #define jpeg_quality_scaling jQualityScaling
  160231. #define jpeg_simple_progression jSimProgress
  160232. #define jpeg_suppress_tables jSuppressTables
  160233. #define jpeg_alloc_quant_table jAlcQTable
  160234. #define jpeg_alloc_huff_table jAlcHTable
  160235. #define jpeg_start_compress jStrtCompress
  160236. #define jpeg_write_scanlines jWrtScanlines
  160237. #define jpeg_finish_compress jFinCompress
  160238. #define jpeg_write_raw_data jWrtRawData
  160239. #define jpeg_write_marker jWrtMarker
  160240. #define jpeg_write_m_header jWrtMHeader
  160241. #define jpeg_write_m_byte jWrtMByte
  160242. #define jpeg_write_tables jWrtTables
  160243. #define jpeg_read_header jReadHeader
  160244. #define jpeg_start_decompress jStrtDecompress
  160245. #define jpeg_read_scanlines jReadScanlines
  160246. #define jpeg_finish_decompress jFinDecompress
  160247. #define jpeg_read_raw_data jReadRawData
  160248. #define jpeg_has_multiple_scans jHasMultScn
  160249. #define jpeg_start_output jStrtOutput
  160250. #define jpeg_finish_output jFinOutput
  160251. #define jpeg_input_complete jInComplete
  160252. #define jpeg_new_colormap jNewCMap
  160253. #define jpeg_consume_input jConsumeInput
  160254. #define jpeg_calc_output_dimensions jCalcDimensions
  160255. #define jpeg_save_markers jSaveMarkers
  160256. #define jpeg_set_marker_processor jSetMarker
  160257. #define jpeg_read_coefficients jReadCoefs
  160258. #define jpeg_write_coefficients jWrtCoefs
  160259. #define jpeg_copy_critical_parameters jCopyCrit
  160260. #define jpeg_abort_compress jAbrtCompress
  160261. #define jpeg_abort_decompress jAbrtDecompress
  160262. #define jpeg_abort jAbort
  160263. #define jpeg_destroy jDestroy
  160264. #define jpeg_resync_to_restart jResyncRestart
  160265. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160266. /* Default error-management setup */
  160267. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160268. JPP((struct jpeg_error_mgr * err));
  160269. /* Initialization of JPEG compression objects.
  160270. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160271. * names that applications should call. These expand to calls on
  160272. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160273. * passed for version mismatch checking.
  160274. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160275. */
  160276. #define jpeg_create_compress(cinfo) \
  160277. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160278. (size_t) sizeof(struct jpeg_compress_struct))
  160279. #define jpeg_create_decompress(cinfo) \
  160280. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160281. (size_t) sizeof(struct jpeg_decompress_struct))
  160282. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160283. int version, size_t structsize));
  160284. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160285. int version, size_t structsize));
  160286. /* Destruction of JPEG compression objects */
  160287. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160288. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160289. /* Standard data source and destination managers: stdio streams. */
  160290. /* Caller is responsible for opening the file before and closing after. */
  160291. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160292. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160293. /* Default parameter setup for compression */
  160294. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160295. /* Compression parameter setup aids */
  160296. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160297. J_COLOR_SPACE colorspace));
  160298. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160299. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160300. boolean force_baseline));
  160301. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160302. int scale_factor,
  160303. boolean force_baseline));
  160304. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160305. const unsigned int *basic_table,
  160306. int scale_factor,
  160307. boolean force_baseline));
  160308. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160309. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160310. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160311. boolean suppress));
  160312. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160313. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160314. /* Main entry points for compression */
  160315. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160316. boolean write_all_tables));
  160317. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160318. JSAMPARRAY scanlines,
  160319. JDIMENSION num_lines));
  160320. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160321. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160322. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160323. JSAMPIMAGE data,
  160324. JDIMENSION num_lines));
  160325. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160326. EXTERN(void) jpeg_write_marker
  160327. JPP((j_compress_ptr cinfo, int marker,
  160328. const JOCTET * dataptr, unsigned int datalen));
  160329. /* Same, but piecemeal. */
  160330. EXTERN(void) jpeg_write_m_header
  160331. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160332. EXTERN(void) jpeg_write_m_byte
  160333. JPP((j_compress_ptr cinfo, int val));
  160334. /* Alternate compression function: just write an abbreviated table file */
  160335. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160336. /* Decompression startup: read start of JPEG datastream to see what's there */
  160337. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160338. boolean require_image));
  160339. /* Return value is one of: */
  160340. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160341. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160342. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160343. /* If you pass require_image = TRUE (normal case), you need not check for
  160344. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160345. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160346. * give a suspension return (the stdio source module doesn't).
  160347. */
  160348. /* Main entry points for decompression */
  160349. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160350. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160351. JSAMPARRAY scanlines,
  160352. JDIMENSION max_lines));
  160353. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160354. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160355. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160356. JSAMPIMAGE data,
  160357. JDIMENSION max_lines));
  160358. /* Additional entry points for buffered-image mode. */
  160359. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160360. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160361. int scan_number));
  160362. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160363. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160364. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160365. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160366. /* Return value is one of: */
  160367. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160368. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160369. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160370. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160371. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160372. /* Precalculate output dimensions for current decompression parameters. */
  160373. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160374. /* Control saving of COM and APPn markers into marker_list. */
  160375. EXTERN(void) jpeg_save_markers
  160376. JPP((j_decompress_ptr cinfo, int marker_code,
  160377. unsigned int length_limit));
  160378. /* Install a special processing method for COM or APPn markers. */
  160379. EXTERN(void) jpeg_set_marker_processor
  160380. JPP((j_decompress_ptr cinfo, int marker_code,
  160381. jpeg_marker_parser_method routine));
  160382. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160383. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160384. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160385. jvirt_barray_ptr * coef_arrays));
  160386. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160387. j_compress_ptr dstinfo));
  160388. /* If you choose to abort compression or decompression before completing
  160389. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160390. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160391. * if you're done with the JPEG object, but if you want to clean it up and
  160392. * reuse it, call this:
  160393. */
  160394. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160395. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160396. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160397. * flavor of JPEG object. These may be more convenient in some places.
  160398. */
  160399. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160400. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160401. /* Default restart-marker-resync procedure for use by data source modules */
  160402. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160403. int desired));
  160404. /* These marker codes are exported since applications and data source modules
  160405. * are likely to want to use them.
  160406. */
  160407. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160408. #define JPEG_EOI 0xD9 /* EOI marker code */
  160409. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160410. #define JPEG_COM 0xFE /* COM marker code */
  160411. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160412. * for structure definitions that are never filled in, keep it quiet by
  160413. * supplying dummy definitions for the various substructures.
  160414. */
  160415. #ifdef INCOMPLETE_TYPES_BROKEN
  160416. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160417. struct jvirt_sarray_control { long dummy; };
  160418. struct jvirt_barray_control { long dummy; };
  160419. struct jpeg_comp_master { long dummy; };
  160420. struct jpeg_c_main_controller { long dummy; };
  160421. struct jpeg_c_prep_controller { long dummy; };
  160422. struct jpeg_c_coef_controller { long dummy; };
  160423. struct jpeg_marker_writer { long dummy; };
  160424. struct jpeg_color_converter { long dummy; };
  160425. struct jpeg_downsampler { long dummy; };
  160426. struct jpeg_forward_dct { long dummy; };
  160427. struct jpeg_entropy_encoder { long dummy; };
  160428. struct jpeg_decomp_master { long dummy; };
  160429. struct jpeg_d_main_controller { long dummy; };
  160430. struct jpeg_d_coef_controller { long dummy; };
  160431. struct jpeg_d_post_controller { long dummy; };
  160432. struct jpeg_input_controller { long dummy; };
  160433. struct jpeg_marker_reader { long dummy; };
  160434. struct jpeg_entropy_decoder { long dummy; };
  160435. struct jpeg_inverse_dct { long dummy; };
  160436. struct jpeg_upsampler { long dummy; };
  160437. struct jpeg_color_deconverter { long dummy; };
  160438. struct jpeg_color_quantizer { long dummy; };
  160439. #endif /* JPEG_INTERNALS */
  160440. #endif /* INCOMPLETE_TYPES_BROKEN */
  160441. /*
  160442. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160443. * The internal structure declarations are read only when that is true.
  160444. * Applications using the library should not include jpegint.h, but may wish
  160445. * to include jerror.h.
  160446. */
  160447. #ifdef JPEG_INTERNALS
  160448. /*** Start of inlined file: jpegint.h ***/
  160449. /* Declarations for both compression & decompression */
  160450. typedef enum { /* Operating modes for buffer controllers */
  160451. JBUF_PASS_THRU, /* Plain stripwise operation */
  160452. /* Remaining modes require a full-image buffer to have been created */
  160453. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160454. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160455. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160456. } J_BUF_MODE;
  160457. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160458. #define CSTATE_START 100 /* after create_compress */
  160459. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160460. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160461. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160462. #define DSTATE_START 200 /* after create_decompress */
  160463. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160464. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160465. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160466. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160467. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160468. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160469. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160470. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160471. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160472. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160473. /* Declarations for compression modules */
  160474. /* Master control module */
  160475. struct jpeg_comp_master {
  160476. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160477. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160478. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160479. /* State variables made visible to other modules */
  160480. boolean call_pass_startup; /* True if pass_startup must be called */
  160481. boolean is_last_pass; /* True during last pass */
  160482. };
  160483. /* Main buffer control (downsampled-data buffer) */
  160484. struct jpeg_c_main_controller {
  160485. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160486. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160487. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160488. JDIMENSION in_rows_avail));
  160489. };
  160490. /* Compression preprocessing (downsampling input buffer control) */
  160491. struct jpeg_c_prep_controller {
  160492. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160493. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  160494. JSAMPARRAY input_buf,
  160495. JDIMENSION *in_row_ctr,
  160496. JDIMENSION in_rows_avail,
  160497. JSAMPIMAGE output_buf,
  160498. JDIMENSION *out_row_group_ctr,
  160499. JDIMENSION out_row_groups_avail));
  160500. };
  160501. /* Coefficient buffer control */
  160502. struct jpeg_c_coef_controller {
  160503. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160504. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  160505. JSAMPIMAGE input_buf));
  160506. };
  160507. /* Colorspace conversion */
  160508. struct jpeg_color_converter {
  160509. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160510. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  160511. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  160512. JDIMENSION output_row, int num_rows));
  160513. };
  160514. /* Downsampling */
  160515. struct jpeg_downsampler {
  160516. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160517. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  160518. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160519. JSAMPIMAGE output_buf,
  160520. JDIMENSION out_row_group_index));
  160521. boolean need_context_rows; /* TRUE if need rows above & below */
  160522. };
  160523. /* Forward DCT (also controls coefficient quantization) */
  160524. struct jpeg_forward_dct {
  160525. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160526. /* perhaps this should be an array??? */
  160527. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  160528. jpeg_component_info * compptr,
  160529. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160530. JDIMENSION start_row, JDIMENSION start_col,
  160531. JDIMENSION num_blocks));
  160532. };
  160533. /* Entropy encoding */
  160534. struct jpeg_entropy_encoder {
  160535. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  160536. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  160537. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160538. };
  160539. /* Marker writing */
  160540. struct jpeg_marker_writer {
  160541. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  160542. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  160543. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  160544. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  160545. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  160546. /* These routines are exported to allow insertion of extra markers */
  160547. /* Probably only COM and APPn markers should be written this way */
  160548. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  160549. unsigned int datalen));
  160550. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  160551. };
  160552. /* Declarations for decompression modules */
  160553. /* Master control module */
  160554. struct jpeg_decomp_master {
  160555. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  160556. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  160557. /* State variables made visible to other modules */
  160558. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  160559. };
  160560. /* Input control module */
  160561. struct jpeg_input_controller {
  160562. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  160563. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  160564. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160565. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  160566. /* State variables made visible to other modules */
  160567. boolean has_multiple_scans; /* True if file has multiple scans */
  160568. boolean eoi_reached; /* True when EOI has been consumed */
  160569. };
  160570. /* Main buffer control (downsampled-data buffer) */
  160571. struct jpeg_d_main_controller {
  160572. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160573. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  160574. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  160575. JDIMENSION out_rows_avail));
  160576. };
  160577. /* Coefficient buffer control */
  160578. struct jpeg_d_coef_controller {
  160579. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160580. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  160581. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  160582. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  160583. JSAMPIMAGE output_buf));
  160584. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  160585. jvirt_barray_ptr *coef_arrays;
  160586. };
  160587. /* Decompression postprocessing (color quantization buffer control) */
  160588. struct jpeg_d_post_controller {
  160589. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160590. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  160591. JSAMPIMAGE input_buf,
  160592. JDIMENSION *in_row_group_ctr,
  160593. JDIMENSION in_row_groups_avail,
  160594. JSAMPARRAY output_buf,
  160595. JDIMENSION *out_row_ctr,
  160596. JDIMENSION out_rows_avail));
  160597. };
  160598. /* Marker reading & parsing */
  160599. struct jpeg_marker_reader {
  160600. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  160601. /* Read markers until SOS or EOI.
  160602. * Returns same codes as are defined for jpeg_consume_input:
  160603. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  160604. */
  160605. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  160606. /* Read a restart marker --- exported for use by entropy decoder only */
  160607. jpeg_marker_parser_method read_restart_marker;
  160608. /* State of marker reader --- nominally internal, but applications
  160609. * supplying COM or APPn handlers might like to know the state.
  160610. */
  160611. boolean saw_SOI; /* found SOI? */
  160612. boolean saw_SOF; /* found SOF? */
  160613. int next_restart_num; /* next restart number expected (0-7) */
  160614. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  160615. };
  160616. /* Entropy decoding */
  160617. struct jpeg_entropy_decoder {
  160618. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160619. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  160620. JBLOCKROW *MCU_data));
  160621. /* This is here to share code between baseline and progressive decoders; */
  160622. /* other modules probably should not use it */
  160623. boolean insufficient_data; /* set TRUE after emitting warning */
  160624. };
  160625. /* Inverse DCT (also performs dequantization) */
  160626. typedef JMETHOD(void, inverse_DCT_method_ptr,
  160627. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  160628. JCOEFPTR coef_block,
  160629. JSAMPARRAY output_buf, JDIMENSION output_col));
  160630. struct jpeg_inverse_dct {
  160631. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160632. /* It is useful to allow each component to have a separate IDCT method. */
  160633. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  160634. };
  160635. /* Upsampling (note that upsampler must also call color converter) */
  160636. struct jpeg_upsampler {
  160637. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160638. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  160639. JSAMPIMAGE input_buf,
  160640. JDIMENSION *in_row_group_ctr,
  160641. JDIMENSION in_row_groups_avail,
  160642. JSAMPARRAY output_buf,
  160643. JDIMENSION *out_row_ctr,
  160644. JDIMENSION out_rows_avail));
  160645. boolean need_context_rows; /* TRUE if need rows above & below */
  160646. };
  160647. /* Colorspace conversion */
  160648. struct jpeg_color_deconverter {
  160649. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160650. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  160651. JSAMPIMAGE input_buf, JDIMENSION input_row,
  160652. JSAMPARRAY output_buf, int num_rows));
  160653. };
  160654. /* Color quantization or color precision reduction */
  160655. struct jpeg_color_quantizer {
  160656. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  160657. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  160658. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  160659. int num_rows));
  160660. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  160661. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  160662. };
  160663. /* Miscellaneous useful macros */
  160664. #undef MAX
  160665. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  160666. #undef MIN
  160667. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  160668. /* We assume that right shift corresponds to signed division by 2 with
  160669. * rounding towards minus infinity. This is correct for typical "arithmetic
  160670. * shift" instructions that shift in copies of the sign bit. But some
  160671. * C compilers implement >> with an unsigned shift. For these machines you
  160672. * must define RIGHT_SHIFT_IS_UNSIGNED.
  160673. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  160674. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  160675. * included in the variables of any routine using RIGHT_SHIFT.
  160676. */
  160677. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  160678. #define SHIFT_TEMPS INT32 shift_temp;
  160679. #define RIGHT_SHIFT(x,shft) \
  160680. ((shift_temp = (x)) < 0 ? \
  160681. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  160682. (shift_temp >> (shft)))
  160683. #else
  160684. #define SHIFT_TEMPS
  160685. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  160686. #endif
  160687. /* Short forms of external names for systems with brain-damaged linkers. */
  160688. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160689. #define jinit_compress_master jICompress
  160690. #define jinit_c_master_control jICMaster
  160691. #define jinit_c_main_controller jICMainC
  160692. #define jinit_c_prep_controller jICPrepC
  160693. #define jinit_c_coef_controller jICCoefC
  160694. #define jinit_color_converter jICColor
  160695. #define jinit_downsampler jIDownsampler
  160696. #define jinit_forward_dct jIFDCT
  160697. #define jinit_huff_encoder jIHEncoder
  160698. #define jinit_phuff_encoder jIPHEncoder
  160699. #define jinit_marker_writer jIMWriter
  160700. #define jinit_master_decompress jIDMaster
  160701. #define jinit_d_main_controller jIDMainC
  160702. #define jinit_d_coef_controller jIDCoefC
  160703. #define jinit_d_post_controller jIDPostC
  160704. #define jinit_input_controller jIInCtlr
  160705. #define jinit_marker_reader jIMReader
  160706. #define jinit_huff_decoder jIHDecoder
  160707. #define jinit_phuff_decoder jIPHDecoder
  160708. #define jinit_inverse_dct jIIDCT
  160709. #define jinit_upsampler jIUpsampler
  160710. #define jinit_color_deconverter jIDColor
  160711. #define jinit_1pass_quantizer jI1Quant
  160712. #define jinit_2pass_quantizer jI2Quant
  160713. #define jinit_merged_upsampler jIMUpsampler
  160714. #define jinit_memory_mgr jIMemMgr
  160715. #define jdiv_round_up jDivRound
  160716. #define jround_up jRound
  160717. #define jcopy_sample_rows jCopySamples
  160718. #define jcopy_block_row jCopyBlocks
  160719. #define jzero_far jZeroFar
  160720. #define jpeg_zigzag_order jZIGTable
  160721. #define jpeg_natural_order jZAGTable
  160722. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160723. /* Compression module initialization routines */
  160724. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  160725. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  160726. boolean transcode_only));
  160727. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  160728. boolean need_full_buffer));
  160729. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  160730. boolean need_full_buffer));
  160731. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  160732. boolean need_full_buffer));
  160733. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  160734. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  160735. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  160736. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  160737. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  160738. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  160739. /* Decompression module initialization routines */
  160740. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  160741. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  160742. boolean need_full_buffer));
  160743. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  160744. boolean need_full_buffer));
  160745. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  160746. boolean need_full_buffer));
  160747. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  160748. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  160749. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  160750. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  160751. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  160752. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  160753. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  160754. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  160755. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  160756. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  160757. /* Memory manager initialization */
  160758. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  160759. /* Utility routines in jutils.c */
  160760. EXTERN(long) jdiv_round_up JPP((long a, long b));
  160761. EXTERN(long) jround_up JPP((long a, long b));
  160762. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  160763. JSAMPARRAY output_array, int dest_row,
  160764. int num_rows, JDIMENSION num_cols));
  160765. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  160766. JDIMENSION num_blocks));
  160767. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  160768. /* Constant tables in jutils.c */
  160769. #if 0 /* This table is not actually needed in v6a */
  160770. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  160771. #endif
  160772. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  160773. /* Suppress undefined-structure complaints if necessary. */
  160774. #ifdef INCOMPLETE_TYPES_BROKEN
  160775. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  160776. struct jvirt_sarray_control { long dummy; };
  160777. struct jvirt_barray_control { long dummy; };
  160778. #endif
  160779. #endif /* INCOMPLETE_TYPES_BROKEN */
  160780. /*** End of inlined file: jpegint.h ***/
  160781. /* fetch private declarations */
  160782. /*** Start of inlined file: jerror.h ***/
  160783. /*
  160784. * To define the enum list of message codes, include this file without
  160785. * defining macro JMESSAGE. To create a message string table, include it
  160786. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  160787. */
  160788. #ifndef JMESSAGE
  160789. #ifndef JERROR_H
  160790. /* First time through, define the enum list */
  160791. #define JMAKE_ENUM_LIST
  160792. #else
  160793. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  160794. #define JMESSAGE(code,string)
  160795. #endif /* JERROR_H */
  160796. #endif /* JMESSAGE */
  160797. #ifdef JMAKE_ENUM_LIST
  160798. typedef enum {
  160799. #define JMESSAGE(code,string) code ,
  160800. #endif /* JMAKE_ENUM_LIST */
  160801. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  160802. /* For maintenance convenience, list is alphabetical by message code name */
  160803. JMESSAGE(JERR_ARITH_NOTIMPL,
  160804. "Sorry, there are legal restrictions on arithmetic coding")
  160805. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  160806. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  160807. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  160808. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  160809. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  160810. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  160811. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  160812. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  160813. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  160814. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  160815. JMESSAGE(JERR_BAD_LIB_VERSION,
  160816. "Wrong JPEG library version: library is %d, caller expects %d")
  160817. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  160818. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  160819. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  160820. JMESSAGE(JERR_BAD_PROGRESSION,
  160821. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  160822. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  160823. "Invalid progressive parameters at scan script entry %d")
  160824. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  160825. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  160826. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  160827. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  160828. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  160829. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  160830. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  160831. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  160832. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  160833. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  160834. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  160835. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  160836. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  160837. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  160838. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  160839. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  160840. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  160841. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  160842. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  160843. JMESSAGE(JERR_FILE_READ, "Input file read error")
  160844. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  160845. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  160846. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  160847. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  160848. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  160849. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  160850. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  160851. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  160852. "Cannot transcode due to multiple use of quantization table %d")
  160853. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  160854. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  160855. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  160856. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  160857. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  160858. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  160859. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  160860. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  160861. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  160862. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  160863. JMESSAGE(JERR_QUANT_COMPONENTS,
  160864. "Cannot quantize more than %d color components")
  160865. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  160866. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  160867. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  160868. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  160869. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  160870. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  160871. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  160872. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  160873. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  160874. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  160875. JMESSAGE(JERR_TFILE_WRITE,
  160876. "Write failed on temporary file --- out of disk space?")
  160877. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  160878. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  160879. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  160880. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  160881. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  160882. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  160883. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  160884. JMESSAGE(JMSG_VERSION, JVERSION)
  160885. JMESSAGE(JTRC_16BIT_TABLES,
  160886. "Caution: quantization tables are too coarse for baseline JPEG")
  160887. JMESSAGE(JTRC_ADOBE,
  160888. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  160889. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  160890. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  160891. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  160892. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  160893. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  160894. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  160895. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  160896. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  160897. JMESSAGE(JTRC_EOI, "End Of Image")
  160898. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  160899. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  160900. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  160901. "Warning: thumbnail image size does not match data length %u")
  160902. JMESSAGE(JTRC_JFIF_EXTENSION,
  160903. "JFIF extension marker: type 0x%02x, length %u")
  160904. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  160905. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  160906. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  160907. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  160908. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  160909. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  160910. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  160911. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  160912. JMESSAGE(JTRC_RST, "RST%d")
  160913. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  160914. "Smoothing not supported with nonstandard sampling ratios")
  160915. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  160916. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  160917. JMESSAGE(JTRC_SOI, "Start of Image")
  160918. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  160919. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  160920. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  160921. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  160922. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  160923. JMESSAGE(JTRC_THUMB_JPEG,
  160924. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  160925. JMESSAGE(JTRC_THUMB_PALETTE,
  160926. "JFIF extension marker: palette thumbnail image, length %u")
  160927. JMESSAGE(JTRC_THUMB_RGB,
  160928. "JFIF extension marker: RGB thumbnail image, length %u")
  160929. JMESSAGE(JTRC_UNKNOWN_IDS,
  160930. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  160931. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  160932. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  160933. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  160934. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  160935. "Inconsistent progression sequence for component %d coefficient %d")
  160936. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  160937. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  160938. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  160939. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  160940. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  160941. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  160942. JMESSAGE(JWRN_MUST_RESYNC,
  160943. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  160944. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  160945. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  160946. #ifdef JMAKE_ENUM_LIST
  160947. JMSG_LASTMSGCODE
  160948. } J_MESSAGE_CODE;
  160949. #undef JMAKE_ENUM_LIST
  160950. #endif /* JMAKE_ENUM_LIST */
  160951. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  160952. #undef JMESSAGE
  160953. #ifndef JERROR_H
  160954. #define JERROR_H
  160955. /* Macros to simplify using the error and trace message stuff */
  160956. /* The first parameter is either type of cinfo pointer */
  160957. /* Fatal errors (print message and exit) */
  160958. #define ERREXIT(cinfo,code) \
  160959. ((cinfo)->err->msg_code = (code), \
  160960. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160961. #define ERREXIT1(cinfo,code,p1) \
  160962. ((cinfo)->err->msg_code = (code), \
  160963. (cinfo)->err->msg_parm.i[0] = (p1), \
  160964. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160965. #define ERREXIT2(cinfo,code,p1,p2) \
  160966. ((cinfo)->err->msg_code = (code), \
  160967. (cinfo)->err->msg_parm.i[0] = (p1), \
  160968. (cinfo)->err->msg_parm.i[1] = (p2), \
  160969. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160970. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  160971. ((cinfo)->err->msg_code = (code), \
  160972. (cinfo)->err->msg_parm.i[0] = (p1), \
  160973. (cinfo)->err->msg_parm.i[1] = (p2), \
  160974. (cinfo)->err->msg_parm.i[2] = (p3), \
  160975. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160976. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  160977. ((cinfo)->err->msg_code = (code), \
  160978. (cinfo)->err->msg_parm.i[0] = (p1), \
  160979. (cinfo)->err->msg_parm.i[1] = (p2), \
  160980. (cinfo)->err->msg_parm.i[2] = (p3), \
  160981. (cinfo)->err->msg_parm.i[3] = (p4), \
  160982. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160983. #define ERREXITS(cinfo,code,str) \
  160984. ((cinfo)->err->msg_code = (code), \
  160985. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  160986. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160987. #define MAKESTMT(stuff) do { stuff } while (0)
  160988. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  160989. #define WARNMS(cinfo,code) \
  160990. ((cinfo)->err->msg_code = (code), \
  160991. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160992. #define WARNMS1(cinfo,code,p1) \
  160993. ((cinfo)->err->msg_code = (code), \
  160994. (cinfo)->err->msg_parm.i[0] = (p1), \
  160995. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160996. #define WARNMS2(cinfo,code,p1,p2) \
  160997. ((cinfo)->err->msg_code = (code), \
  160998. (cinfo)->err->msg_parm.i[0] = (p1), \
  160999. (cinfo)->err->msg_parm.i[1] = (p2), \
  161000. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161001. /* Informational/debugging messages */
  161002. #define TRACEMS(cinfo,lvl,code) \
  161003. ((cinfo)->err->msg_code = (code), \
  161004. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161005. #define TRACEMS1(cinfo,lvl,code,p1) \
  161006. ((cinfo)->err->msg_code = (code), \
  161007. (cinfo)->err->msg_parm.i[0] = (p1), \
  161008. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161009. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161010. ((cinfo)->err->msg_code = (code), \
  161011. (cinfo)->err->msg_parm.i[0] = (p1), \
  161012. (cinfo)->err->msg_parm.i[1] = (p2), \
  161013. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161014. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161015. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161016. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161017. (cinfo)->err->msg_code = (code); \
  161018. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161019. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161020. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161021. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161022. (cinfo)->err->msg_code = (code); \
  161023. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161024. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161025. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161026. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161027. _mp[4] = (p5); \
  161028. (cinfo)->err->msg_code = (code); \
  161029. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161030. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161031. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161032. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161033. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161034. (cinfo)->err->msg_code = (code); \
  161035. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161036. #define TRACEMSS(cinfo,lvl,code,str) \
  161037. ((cinfo)->err->msg_code = (code), \
  161038. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161039. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161040. #endif /* JERROR_H */
  161041. /*** End of inlined file: jerror.h ***/
  161042. /* fetch error codes too */
  161043. #endif
  161044. #endif /* JPEGLIB_H */
  161045. /*** End of inlined file: jpeglib.h ***/
  161046. /*** Start of inlined file: jcapimin.c ***/
  161047. #define JPEG_INTERNALS
  161048. /*** Start of inlined file: jinclude.h ***/
  161049. /* Include auto-config file to find out which system include files we need. */
  161050. #ifndef __jinclude_h__
  161051. #define __jinclude_h__
  161052. /*** Start of inlined file: jconfig.h ***/
  161053. /* see jconfig.doc for explanations */
  161054. // disable all the warnings under MSVC
  161055. #ifdef _MSC_VER
  161056. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161057. #endif
  161058. #ifdef __BORLANDC__
  161059. #pragma warn -8057
  161060. #pragma warn -8019
  161061. #pragma warn -8004
  161062. #pragma warn -8008
  161063. #endif
  161064. #define HAVE_PROTOTYPES
  161065. #define HAVE_UNSIGNED_CHAR
  161066. #define HAVE_UNSIGNED_SHORT
  161067. /* #define void char */
  161068. /* #define const */
  161069. #undef CHAR_IS_UNSIGNED
  161070. #define HAVE_STDDEF_H
  161071. #define HAVE_STDLIB_H
  161072. #undef NEED_BSD_STRINGS
  161073. #undef NEED_SYS_TYPES_H
  161074. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161075. #undef NEED_SHORT_EXTERNAL_NAMES
  161076. #undef INCOMPLETE_TYPES_BROKEN
  161077. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161078. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161079. typedef unsigned char boolean;
  161080. #endif
  161081. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161082. #ifdef JPEG_INTERNALS
  161083. #undef RIGHT_SHIFT_IS_UNSIGNED
  161084. #endif /* JPEG_INTERNALS */
  161085. #ifdef JPEG_CJPEG_DJPEG
  161086. #define BMP_SUPPORTED /* BMP image file format */
  161087. #define GIF_SUPPORTED /* GIF image file format */
  161088. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161089. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161090. #define TARGA_SUPPORTED /* Targa image file format */
  161091. #define TWO_FILE_COMMANDLINE /* optional */
  161092. #define USE_SETMODE /* Microsoft has setmode() */
  161093. #undef NEED_SIGNAL_CATCHER
  161094. #undef DONT_USE_B_MODE
  161095. #undef PROGRESS_REPORT /* optional */
  161096. #endif /* JPEG_CJPEG_DJPEG */
  161097. /*** End of inlined file: jconfig.h ***/
  161098. /* auto configuration options */
  161099. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161100. /*
  161101. * We need the NULL macro and size_t typedef.
  161102. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161103. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161104. * pull in <sys/types.h> as well.
  161105. * Note that the core JPEG library does not require <stdio.h>;
  161106. * only the default error handler and data source/destination modules do.
  161107. * But we must pull it in because of the references to FILE in jpeglib.h.
  161108. * You can remove those references if you want to compile without <stdio.h>.
  161109. */
  161110. #ifdef HAVE_STDDEF_H
  161111. #include <stddef.h>
  161112. #endif
  161113. #ifdef HAVE_STDLIB_H
  161114. #include <stdlib.h>
  161115. #endif
  161116. #ifdef NEED_SYS_TYPES_H
  161117. #include <sys/types.h>
  161118. #endif
  161119. #include <stdio.h>
  161120. /*
  161121. * We need memory copying and zeroing functions, plus strncpy().
  161122. * ANSI and System V implementations declare these in <string.h>.
  161123. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161124. * Some systems may declare memset and memcpy in <memory.h>.
  161125. *
  161126. * NOTE: we assume the size parameters to these functions are of type size_t.
  161127. * Change the casts in these macros if not!
  161128. */
  161129. #ifdef NEED_BSD_STRINGS
  161130. #include <strings.h>
  161131. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161132. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161133. #else /* not BSD, assume ANSI/SysV string lib */
  161134. #include <string.h>
  161135. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161136. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161137. #endif
  161138. /*
  161139. * In ANSI C, and indeed any rational implementation, size_t is also the
  161140. * type returned by sizeof(). However, it seems there are some irrational
  161141. * implementations out there, in which sizeof() returns an int even though
  161142. * size_t is defined as long or unsigned long. To ensure consistent results
  161143. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161144. */
  161145. #define SIZEOF(object) ((size_t) sizeof(object))
  161146. /*
  161147. * The modules that use fread() and fwrite() always invoke them through
  161148. * these macros. On some systems you may need to twiddle the argument casts.
  161149. * CAUTION: argument order is different from underlying functions!
  161150. */
  161151. #define JFREAD(file,buf,sizeofbuf) \
  161152. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161153. #define JFWRITE(file,buf,sizeofbuf) \
  161154. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161155. typedef enum { /* JPEG marker codes */
  161156. M_SOF0 = 0xc0,
  161157. M_SOF1 = 0xc1,
  161158. M_SOF2 = 0xc2,
  161159. M_SOF3 = 0xc3,
  161160. M_SOF5 = 0xc5,
  161161. M_SOF6 = 0xc6,
  161162. M_SOF7 = 0xc7,
  161163. M_JPG = 0xc8,
  161164. M_SOF9 = 0xc9,
  161165. M_SOF10 = 0xca,
  161166. M_SOF11 = 0xcb,
  161167. M_SOF13 = 0xcd,
  161168. M_SOF14 = 0xce,
  161169. M_SOF15 = 0xcf,
  161170. M_DHT = 0xc4,
  161171. M_DAC = 0xcc,
  161172. M_RST0 = 0xd0,
  161173. M_RST1 = 0xd1,
  161174. M_RST2 = 0xd2,
  161175. M_RST3 = 0xd3,
  161176. M_RST4 = 0xd4,
  161177. M_RST5 = 0xd5,
  161178. M_RST6 = 0xd6,
  161179. M_RST7 = 0xd7,
  161180. M_SOI = 0xd8,
  161181. M_EOI = 0xd9,
  161182. M_SOS = 0xda,
  161183. M_DQT = 0xdb,
  161184. M_DNL = 0xdc,
  161185. M_DRI = 0xdd,
  161186. M_DHP = 0xde,
  161187. M_EXP = 0xdf,
  161188. M_APP0 = 0xe0,
  161189. M_APP1 = 0xe1,
  161190. M_APP2 = 0xe2,
  161191. M_APP3 = 0xe3,
  161192. M_APP4 = 0xe4,
  161193. M_APP5 = 0xe5,
  161194. M_APP6 = 0xe6,
  161195. M_APP7 = 0xe7,
  161196. M_APP8 = 0xe8,
  161197. M_APP9 = 0xe9,
  161198. M_APP10 = 0xea,
  161199. M_APP11 = 0xeb,
  161200. M_APP12 = 0xec,
  161201. M_APP13 = 0xed,
  161202. M_APP14 = 0xee,
  161203. M_APP15 = 0xef,
  161204. M_JPG0 = 0xf0,
  161205. M_JPG13 = 0xfd,
  161206. M_COM = 0xfe,
  161207. M_TEM = 0x01,
  161208. M_ERROR = 0x100
  161209. } JPEG_MARKER;
  161210. /*
  161211. * Figure F.12: extend sign bit.
  161212. * On some machines, a shift and add will be faster than a table lookup.
  161213. */
  161214. #ifdef AVOID_TABLES
  161215. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161216. #else
  161217. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161218. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161219. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161220. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161221. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161222. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161223. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161224. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161225. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161226. #endif /* AVOID_TABLES */
  161227. #endif
  161228. /*** End of inlined file: jinclude.h ***/
  161229. /*
  161230. * Initialization of a JPEG compression object.
  161231. * The error manager must already be set up (in case memory manager fails).
  161232. */
  161233. GLOBAL(void)
  161234. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161235. {
  161236. int i;
  161237. /* Guard against version mismatches between library and caller. */
  161238. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161239. if (version != JPEG_LIB_VERSION)
  161240. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161241. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161242. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161243. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161244. /* For debugging purposes, we zero the whole master structure.
  161245. * But the application has already set the err pointer, and may have set
  161246. * client_data, so we have to save and restore those fields.
  161247. * Note: if application hasn't set client_data, tools like Purify may
  161248. * complain here.
  161249. */
  161250. {
  161251. struct jpeg_error_mgr * err = cinfo->err;
  161252. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161253. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161254. cinfo->err = err;
  161255. cinfo->client_data = client_data;
  161256. }
  161257. cinfo->is_decompressor = FALSE;
  161258. /* Initialize a memory manager instance for this object */
  161259. jinit_memory_mgr((j_common_ptr) cinfo);
  161260. /* Zero out pointers to permanent structures. */
  161261. cinfo->progress = NULL;
  161262. cinfo->dest = NULL;
  161263. cinfo->comp_info = NULL;
  161264. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161265. cinfo->quant_tbl_ptrs[i] = NULL;
  161266. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161267. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161268. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161269. }
  161270. cinfo->script_space = NULL;
  161271. cinfo->input_gamma = 1.0; /* in case application forgets */
  161272. /* OK, I'm ready */
  161273. cinfo->global_state = CSTATE_START;
  161274. }
  161275. /*
  161276. * Destruction of a JPEG compression object
  161277. */
  161278. GLOBAL(void)
  161279. jpeg_destroy_compress (j_compress_ptr cinfo)
  161280. {
  161281. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161282. }
  161283. /*
  161284. * Abort processing of a JPEG compression operation,
  161285. * but don't destroy the object itself.
  161286. */
  161287. GLOBAL(void)
  161288. jpeg_abort_compress (j_compress_ptr cinfo)
  161289. {
  161290. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161291. }
  161292. /*
  161293. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161294. * Marks all currently defined tables as already written (if suppress)
  161295. * or not written (if !suppress). This will control whether they get emitted
  161296. * by a subsequent jpeg_start_compress call.
  161297. *
  161298. * This routine is exported for use by applications that want to produce
  161299. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161300. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161301. * jcparam.o would be linked whether the application used it or not.
  161302. */
  161303. GLOBAL(void)
  161304. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161305. {
  161306. int i;
  161307. JQUANT_TBL * qtbl;
  161308. JHUFF_TBL * htbl;
  161309. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161310. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161311. qtbl->sent_table = suppress;
  161312. }
  161313. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161314. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161315. htbl->sent_table = suppress;
  161316. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161317. htbl->sent_table = suppress;
  161318. }
  161319. }
  161320. /*
  161321. * Finish JPEG compression.
  161322. *
  161323. * If a multipass operating mode was selected, this may do a great deal of
  161324. * work including most of the actual output.
  161325. */
  161326. GLOBAL(void)
  161327. jpeg_finish_compress (j_compress_ptr cinfo)
  161328. {
  161329. JDIMENSION iMCU_row;
  161330. if (cinfo->global_state == CSTATE_SCANNING ||
  161331. cinfo->global_state == CSTATE_RAW_OK) {
  161332. /* Terminate first pass */
  161333. if (cinfo->next_scanline < cinfo->image_height)
  161334. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161335. (*cinfo->master->finish_pass) (cinfo);
  161336. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161337. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161338. /* Perform any remaining passes */
  161339. while (! cinfo->master->is_last_pass) {
  161340. (*cinfo->master->prepare_for_pass) (cinfo);
  161341. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161342. if (cinfo->progress != NULL) {
  161343. cinfo->progress->pass_counter = (long) iMCU_row;
  161344. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161345. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161346. }
  161347. /* We bypass the main controller and invoke coef controller directly;
  161348. * all work is being done from the coefficient buffer.
  161349. */
  161350. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161351. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161352. }
  161353. (*cinfo->master->finish_pass) (cinfo);
  161354. }
  161355. /* Write EOI, do final cleanup */
  161356. (*cinfo->marker->write_file_trailer) (cinfo);
  161357. (*cinfo->dest->term_destination) (cinfo);
  161358. /* We can use jpeg_abort to release memory and reset global_state */
  161359. jpeg_abort((j_common_ptr) cinfo);
  161360. }
  161361. /*
  161362. * Write a special marker.
  161363. * This is only recommended for writing COM or APPn markers.
  161364. * Must be called after jpeg_start_compress() and before
  161365. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161366. */
  161367. GLOBAL(void)
  161368. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161369. const JOCTET *dataptr, unsigned int datalen)
  161370. {
  161371. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161372. if (cinfo->next_scanline != 0 ||
  161373. (cinfo->global_state != CSTATE_SCANNING &&
  161374. cinfo->global_state != CSTATE_RAW_OK &&
  161375. cinfo->global_state != CSTATE_WRCOEFS))
  161376. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161377. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161378. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161379. while (datalen--) {
  161380. (*write_marker_byte) (cinfo, *dataptr);
  161381. dataptr++;
  161382. }
  161383. }
  161384. /* Same, but piecemeal. */
  161385. GLOBAL(void)
  161386. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161387. {
  161388. if (cinfo->next_scanline != 0 ||
  161389. (cinfo->global_state != CSTATE_SCANNING &&
  161390. cinfo->global_state != CSTATE_RAW_OK &&
  161391. cinfo->global_state != CSTATE_WRCOEFS))
  161392. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161393. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161394. }
  161395. GLOBAL(void)
  161396. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161397. {
  161398. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161399. }
  161400. /*
  161401. * Alternate compression function: just write an abbreviated table file.
  161402. * Before calling this, all parameters and a data destination must be set up.
  161403. *
  161404. * To produce a pair of files containing abbreviated tables and abbreviated
  161405. * image data, one would proceed as follows:
  161406. *
  161407. * initialize JPEG object
  161408. * set JPEG parameters
  161409. * set destination to table file
  161410. * jpeg_write_tables(cinfo);
  161411. * set destination to image file
  161412. * jpeg_start_compress(cinfo, FALSE);
  161413. * write data...
  161414. * jpeg_finish_compress(cinfo);
  161415. *
  161416. * jpeg_write_tables has the side effect of marking all tables written
  161417. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161418. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161419. */
  161420. GLOBAL(void)
  161421. jpeg_write_tables (j_compress_ptr cinfo)
  161422. {
  161423. if (cinfo->global_state != CSTATE_START)
  161424. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161425. /* (Re)initialize error mgr and destination modules */
  161426. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161427. (*cinfo->dest->init_destination) (cinfo);
  161428. /* Initialize the marker writer ... bit of a crock to do it here. */
  161429. jinit_marker_writer(cinfo);
  161430. /* Write them tables! */
  161431. (*cinfo->marker->write_tables_only) (cinfo);
  161432. /* And clean up. */
  161433. (*cinfo->dest->term_destination) (cinfo);
  161434. /*
  161435. * In library releases up through v6a, we called jpeg_abort() here to free
  161436. * any working memory allocated by the destination manager and marker
  161437. * writer. Some applications had a problem with that: they allocated space
  161438. * of their own from the library memory manager, and didn't want it to go
  161439. * away during write_tables. So now we do nothing. This will cause a
  161440. * memory leak if an app calls write_tables repeatedly without doing a full
  161441. * compression cycle or otherwise resetting the JPEG object. However, that
  161442. * seems less bad than unexpectedly freeing memory in the normal case.
  161443. * An app that prefers the old behavior can call jpeg_abort for itself after
  161444. * each call to jpeg_write_tables().
  161445. */
  161446. }
  161447. /*** End of inlined file: jcapimin.c ***/
  161448. /*** Start of inlined file: jcapistd.c ***/
  161449. #define JPEG_INTERNALS
  161450. /*
  161451. * Compression initialization.
  161452. * Before calling this, all parameters and a data destination must be set up.
  161453. *
  161454. * We require a write_all_tables parameter as a failsafe check when writing
  161455. * multiple datastreams from the same compression object. Since prior runs
  161456. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161457. * would emit an abbreviated stream (no tables) by default. This may be what
  161458. * is wanted, but for safety's sake it should not be the default behavior:
  161459. * programmers should have to make a deliberate choice to emit abbreviated
  161460. * images. Therefore the documentation and examples should encourage people
  161461. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161462. * wrong thing.
  161463. */
  161464. GLOBAL(void)
  161465. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161466. {
  161467. if (cinfo->global_state != CSTATE_START)
  161468. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161469. if (write_all_tables)
  161470. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161471. /* (Re)initialize error mgr and destination modules */
  161472. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161473. (*cinfo->dest->init_destination) (cinfo);
  161474. /* Perform master selection of active modules */
  161475. jinit_compress_master(cinfo);
  161476. /* Set up for the first pass */
  161477. (*cinfo->master->prepare_for_pass) (cinfo);
  161478. /* Ready for application to drive first pass through jpeg_write_scanlines
  161479. * or jpeg_write_raw_data.
  161480. */
  161481. cinfo->next_scanline = 0;
  161482. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161483. }
  161484. /*
  161485. * Write some scanlines of data to the JPEG compressor.
  161486. *
  161487. * The return value will be the number of lines actually written.
  161488. * This should be less than the supplied num_lines only in case that
  161489. * the data destination module has requested suspension of the compressor,
  161490. * or if more than image_height scanlines are passed in.
  161491. *
  161492. * Note: we warn about excess calls to jpeg_write_scanlines() since
  161493. * this likely signals an application programmer error. However,
  161494. * excess scanlines passed in the last valid call are *silently* ignored,
  161495. * so that the application need not adjust num_lines for end-of-image
  161496. * when using a multiple-scanline buffer.
  161497. */
  161498. GLOBAL(JDIMENSION)
  161499. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  161500. JDIMENSION num_lines)
  161501. {
  161502. JDIMENSION row_ctr, rows_left;
  161503. if (cinfo->global_state != CSTATE_SCANNING)
  161504. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161505. if (cinfo->next_scanline >= cinfo->image_height)
  161506. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161507. /* Call progress monitor hook if present */
  161508. if (cinfo->progress != NULL) {
  161509. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161510. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161511. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161512. }
  161513. /* Give master control module another chance if this is first call to
  161514. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  161515. * delayed so that application can write COM, etc, markers between
  161516. * jpeg_start_compress and jpeg_write_scanlines.
  161517. */
  161518. if (cinfo->master->call_pass_startup)
  161519. (*cinfo->master->pass_startup) (cinfo);
  161520. /* Ignore any extra scanlines at bottom of image. */
  161521. rows_left = cinfo->image_height - cinfo->next_scanline;
  161522. if (num_lines > rows_left)
  161523. num_lines = rows_left;
  161524. row_ctr = 0;
  161525. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  161526. cinfo->next_scanline += row_ctr;
  161527. return row_ctr;
  161528. }
  161529. /*
  161530. * Alternate entry point to write raw data.
  161531. * Processes exactly one iMCU row per call, unless suspended.
  161532. */
  161533. GLOBAL(JDIMENSION)
  161534. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  161535. JDIMENSION num_lines)
  161536. {
  161537. JDIMENSION lines_per_iMCU_row;
  161538. if (cinfo->global_state != CSTATE_RAW_OK)
  161539. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161540. if (cinfo->next_scanline >= cinfo->image_height) {
  161541. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161542. return 0;
  161543. }
  161544. /* Call progress monitor hook if present */
  161545. if (cinfo->progress != NULL) {
  161546. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161547. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161548. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161549. }
  161550. /* Give master control module another chance if this is first call to
  161551. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  161552. * delayed so that application can write COM, etc, markers between
  161553. * jpeg_start_compress and jpeg_write_raw_data.
  161554. */
  161555. if (cinfo->master->call_pass_startup)
  161556. (*cinfo->master->pass_startup) (cinfo);
  161557. /* Verify that at least one iMCU row has been passed. */
  161558. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  161559. if (num_lines < lines_per_iMCU_row)
  161560. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161561. /* Directly compress the row. */
  161562. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  161563. /* If compressor did not consume the whole row, suspend processing. */
  161564. return 0;
  161565. }
  161566. /* OK, we processed one iMCU row. */
  161567. cinfo->next_scanline += lines_per_iMCU_row;
  161568. return lines_per_iMCU_row;
  161569. }
  161570. /*** End of inlined file: jcapistd.c ***/
  161571. /*** Start of inlined file: jccoefct.c ***/
  161572. #define JPEG_INTERNALS
  161573. /* We use a full-image coefficient buffer when doing Huffman optimization,
  161574. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  161575. * step is run during the first pass, and subsequent passes need only read
  161576. * the buffered coefficients.
  161577. */
  161578. #ifdef ENTROPY_OPT_SUPPORTED
  161579. #define FULL_COEF_BUFFER_SUPPORTED
  161580. #else
  161581. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161582. #define FULL_COEF_BUFFER_SUPPORTED
  161583. #endif
  161584. #endif
  161585. /* Private buffer controller object */
  161586. typedef struct {
  161587. struct jpeg_c_coef_controller pub; /* public fields */
  161588. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161589. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161590. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161591. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161592. /* For single-pass compression, it's sufficient to buffer just one MCU
  161593. * (although this may prove a bit slow in practice). We allocate a
  161594. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  161595. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  161596. * it's not really very big; this is to keep the module interfaces unchanged
  161597. * when a large coefficient buffer is necessary.)
  161598. * In multi-pass modes, this array points to the current MCU's blocks
  161599. * within the virtual arrays.
  161600. */
  161601. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161602. /* In multi-pass modes, we need a virtual block array for each component. */
  161603. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161604. } my_coef_controller;
  161605. typedef my_coef_controller * my_coef_ptr;
  161606. /* Forward declarations */
  161607. METHODDEF(boolean) compress_data
  161608. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161609. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161610. METHODDEF(boolean) compress_first_pass
  161611. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161612. METHODDEF(boolean) compress_output
  161613. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161614. #endif
  161615. LOCAL(void)
  161616. start_iMCU_row (j_compress_ptr cinfo)
  161617. /* Reset within-iMCU-row counters for a new row */
  161618. {
  161619. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161620. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161621. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161622. * But at the bottom of the image, process only what's left.
  161623. */
  161624. if (cinfo->comps_in_scan > 1) {
  161625. coef->MCU_rows_per_iMCU_row = 1;
  161626. } else {
  161627. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161628. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161629. else
  161630. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161631. }
  161632. coef->mcu_ctr = 0;
  161633. coef->MCU_vert_offset = 0;
  161634. }
  161635. /*
  161636. * Initialize for a processing pass.
  161637. */
  161638. METHODDEF(void)
  161639. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161640. {
  161641. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161642. coef->iMCU_row_num = 0;
  161643. start_iMCU_row(cinfo);
  161644. switch (pass_mode) {
  161645. case JBUF_PASS_THRU:
  161646. if (coef->whole_image[0] != NULL)
  161647. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161648. coef->pub.compress_data = compress_data;
  161649. break;
  161650. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161651. case JBUF_SAVE_AND_PASS:
  161652. if (coef->whole_image[0] == NULL)
  161653. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161654. coef->pub.compress_data = compress_first_pass;
  161655. break;
  161656. case JBUF_CRANK_DEST:
  161657. if (coef->whole_image[0] == NULL)
  161658. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161659. coef->pub.compress_data = compress_output;
  161660. break;
  161661. #endif
  161662. default:
  161663. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161664. break;
  161665. }
  161666. }
  161667. /*
  161668. * Process some data in the single-pass case.
  161669. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161670. * per call, ie, v_samp_factor block rows for each component in the image.
  161671. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161672. *
  161673. * NB: input_buf contains a plane for each component in image,
  161674. * which we index according to the component's SOF position.
  161675. */
  161676. METHODDEF(boolean)
  161677. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161678. {
  161679. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161680. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161681. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161682. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161683. int blkn, bi, ci, yindex, yoffset, blockcnt;
  161684. JDIMENSION ypos, xpos;
  161685. jpeg_component_info *compptr;
  161686. /* Loop to write as much as one whole iMCU row */
  161687. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161688. yoffset++) {
  161689. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  161690. MCU_col_num++) {
  161691. /* Determine where data comes from in input_buf and do the DCT thing.
  161692. * Each call on forward_DCT processes a horizontal row of DCT blocks
  161693. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  161694. * sequentially. Dummy blocks at the right or bottom edge are filled in
  161695. * specially. The data in them does not matter for image reconstruction,
  161696. * so we fill them with values that will encode to the smallest amount of
  161697. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  161698. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  161699. */
  161700. blkn = 0;
  161701. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161702. compptr = cinfo->cur_comp_info[ci];
  161703. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  161704. : compptr->last_col_width;
  161705. xpos = MCU_col_num * compptr->MCU_sample_width;
  161706. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  161707. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161708. if (coef->iMCU_row_num < last_iMCU_row ||
  161709. yoffset+yindex < compptr->last_row_height) {
  161710. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161711. input_buf[compptr->component_index],
  161712. coef->MCU_buffer[blkn],
  161713. ypos, xpos, (JDIMENSION) blockcnt);
  161714. if (blockcnt < compptr->MCU_width) {
  161715. /* Create some dummy blocks at the right edge of the image. */
  161716. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  161717. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  161718. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  161719. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  161720. }
  161721. }
  161722. } else {
  161723. /* Create a row of dummy blocks at the bottom of the image. */
  161724. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  161725. compptr->MCU_width * SIZEOF(JBLOCK));
  161726. for (bi = 0; bi < compptr->MCU_width; bi++) {
  161727. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  161728. }
  161729. }
  161730. blkn += compptr->MCU_width;
  161731. ypos += DCTSIZE;
  161732. }
  161733. }
  161734. /* Try to write the MCU. In event of a suspension failure, we will
  161735. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  161736. */
  161737. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161738. /* Suspension forced; update state counters and exit */
  161739. coef->MCU_vert_offset = yoffset;
  161740. coef->mcu_ctr = MCU_col_num;
  161741. return FALSE;
  161742. }
  161743. }
  161744. /* Completed an MCU row, but perhaps not an iMCU row */
  161745. coef->mcu_ctr = 0;
  161746. }
  161747. /* Completed the iMCU row, advance counters for next one */
  161748. coef->iMCU_row_num++;
  161749. start_iMCU_row(cinfo);
  161750. return TRUE;
  161751. }
  161752. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161753. /*
  161754. * Process some data in the first pass of a multi-pass case.
  161755. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161756. * per call, ie, v_samp_factor block rows for each component in the image.
  161757. * This amount of data is read from the source buffer, DCT'd and quantized,
  161758. * and saved into the virtual arrays. We also generate suitable dummy blocks
  161759. * as needed at the right and lower edges. (The dummy blocks are constructed
  161760. * in the virtual arrays, which have been padded appropriately.) This makes
  161761. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  161762. *
  161763. * We must also emit the data to the entropy encoder. This is conveniently
  161764. * done by calling compress_output() after we've loaded the current strip
  161765. * of the virtual arrays.
  161766. *
  161767. * NB: input_buf contains a plane for each component in image. All
  161768. * components are DCT'd and loaded into the virtual arrays in this pass.
  161769. * However, it may be that only a subset of the components are emitted to
  161770. * the entropy encoder during this first pass; be careful about looking
  161771. * at the scan-dependent variables (MCU dimensions, etc).
  161772. */
  161773. METHODDEF(boolean)
  161774. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161775. {
  161776. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161777. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161778. JDIMENSION blocks_across, MCUs_across, MCUindex;
  161779. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  161780. JCOEF lastDC;
  161781. jpeg_component_info *compptr;
  161782. JBLOCKARRAY buffer;
  161783. JBLOCKROW thisblockrow, lastblockrow;
  161784. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161785. ci++, compptr++) {
  161786. /* Align the virtual buffer for this component. */
  161787. buffer = (*cinfo->mem->access_virt_barray)
  161788. ((j_common_ptr) cinfo, coef->whole_image[ci],
  161789. coef->iMCU_row_num * compptr->v_samp_factor,
  161790. (JDIMENSION) compptr->v_samp_factor, TRUE);
  161791. /* Count non-dummy DCT block rows in this iMCU row. */
  161792. if (coef->iMCU_row_num < last_iMCU_row)
  161793. block_rows = compptr->v_samp_factor;
  161794. else {
  161795. /* NB: can't use last_row_height here, since may not be set! */
  161796. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  161797. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  161798. }
  161799. blocks_across = compptr->width_in_blocks;
  161800. h_samp_factor = compptr->h_samp_factor;
  161801. /* Count number of dummy blocks to be added at the right margin. */
  161802. ndummy = (int) (blocks_across % h_samp_factor);
  161803. if (ndummy > 0)
  161804. ndummy = h_samp_factor - ndummy;
  161805. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  161806. * on forward_DCT processes a complete horizontal row of DCT blocks.
  161807. */
  161808. for (block_row = 0; block_row < block_rows; block_row++) {
  161809. thisblockrow = buffer[block_row];
  161810. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161811. input_buf[ci], thisblockrow,
  161812. (JDIMENSION) (block_row * DCTSIZE),
  161813. (JDIMENSION) 0, blocks_across);
  161814. if (ndummy > 0) {
  161815. /* Create dummy blocks at the right edge of the image. */
  161816. thisblockrow += blocks_across; /* => first dummy block */
  161817. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  161818. lastDC = thisblockrow[-1][0];
  161819. for (bi = 0; bi < ndummy; bi++) {
  161820. thisblockrow[bi][0] = lastDC;
  161821. }
  161822. }
  161823. }
  161824. /* If at end of image, create dummy block rows as needed.
  161825. * The tricky part here is that within each MCU, we want the DC values
  161826. * of the dummy blocks to match the last real block's DC value.
  161827. * This squeezes a few more bytes out of the resulting file...
  161828. */
  161829. if (coef->iMCU_row_num == last_iMCU_row) {
  161830. blocks_across += ndummy; /* include lower right corner */
  161831. MCUs_across = blocks_across / h_samp_factor;
  161832. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  161833. block_row++) {
  161834. thisblockrow = buffer[block_row];
  161835. lastblockrow = buffer[block_row-1];
  161836. jzero_far((void FAR *) thisblockrow,
  161837. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  161838. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  161839. lastDC = lastblockrow[h_samp_factor-1][0];
  161840. for (bi = 0; bi < h_samp_factor; bi++) {
  161841. thisblockrow[bi][0] = lastDC;
  161842. }
  161843. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  161844. lastblockrow += h_samp_factor;
  161845. }
  161846. }
  161847. }
  161848. }
  161849. /* NB: compress_output will increment iMCU_row_num if successful.
  161850. * A suspension return will result in redoing all the work above next time.
  161851. */
  161852. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  161853. return compress_output(cinfo, input_buf);
  161854. }
  161855. /*
  161856. * Process some data in subsequent passes of a multi-pass case.
  161857. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161858. * per call, ie, v_samp_factor block rows for each component in the scan.
  161859. * The data is obtained from the virtual arrays and fed to the entropy coder.
  161860. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161861. *
  161862. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  161863. */
  161864. METHODDEF(boolean)
  161865. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  161866. {
  161867. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161868. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161869. int blkn, ci, xindex, yindex, yoffset;
  161870. JDIMENSION start_col;
  161871. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  161872. JBLOCKROW buffer_ptr;
  161873. jpeg_component_info *compptr;
  161874. /* Align the virtual buffers for the components used in this scan.
  161875. * NB: during first pass, this is safe only because the buffers will
  161876. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  161877. */
  161878. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161879. compptr = cinfo->cur_comp_info[ci];
  161880. buffer[ci] = (*cinfo->mem->access_virt_barray)
  161881. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  161882. coef->iMCU_row_num * compptr->v_samp_factor,
  161883. (JDIMENSION) compptr->v_samp_factor, FALSE);
  161884. }
  161885. /* Loop to process one whole iMCU row */
  161886. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161887. yoffset++) {
  161888. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  161889. MCU_col_num++) {
  161890. /* Construct list of pointers to DCT blocks belonging to this MCU */
  161891. blkn = 0; /* index of current DCT block within MCU */
  161892. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161893. compptr = cinfo->cur_comp_info[ci];
  161894. start_col = MCU_col_num * compptr->MCU_width;
  161895. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161896. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  161897. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  161898. coef->MCU_buffer[blkn++] = buffer_ptr++;
  161899. }
  161900. }
  161901. }
  161902. /* Try to write the MCU. */
  161903. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161904. /* Suspension forced; update state counters and exit */
  161905. coef->MCU_vert_offset = yoffset;
  161906. coef->mcu_ctr = MCU_col_num;
  161907. return FALSE;
  161908. }
  161909. }
  161910. /* Completed an MCU row, but perhaps not an iMCU row */
  161911. coef->mcu_ctr = 0;
  161912. }
  161913. /* Completed the iMCU row, advance counters for next one */
  161914. coef->iMCU_row_num++;
  161915. start_iMCU_row(cinfo);
  161916. return TRUE;
  161917. }
  161918. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  161919. /*
  161920. * Initialize coefficient buffer controller.
  161921. */
  161922. GLOBAL(void)
  161923. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  161924. {
  161925. my_coef_ptr coef;
  161926. coef = (my_coef_ptr)
  161927. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161928. SIZEOF(my_coef_controller));
  161929. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  161930. coef->pub.start_pass = start_pass_coef;
  161931. /* Create the coefficient buffer. */
  161932. if (need_full_buffer) {
  161933. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161934. /* Allocate a full-image virtual array for each component, */
  161935. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  161936. int ci;
  161937. jpeg_component_info *compptr;
  161938. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161939. ci++, compptr++) {
  161940. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  161941. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  161942. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  161943. (long) compptr->h_samp_factor),
  161944. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  161945. (long) compptr->v_samp_factor),
  161946. (JDIMENSION) compptr->v_samp_factor);
  161947. }
  161948. #else
  161949. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161950. #endif
  161951. } else {
  161952. /* We only need a single-MCU buffer. */
  161953. JBLOCKROW buffer;
  161954. int i;
  161955. buffer = (JBLOCKROW)
  161956. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161957. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  161958. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  161959. coef->MCU_buffer[i] = buffer + i;
  161960. }
  161961. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  161962. }
  161963. }
  161964. /*** End of inlined file: jccoefct.c ***/
  161965. /*** Start of inlined file: jccolor.c ***/
  161966. #define JPEG_INTERNALS
  161967. /* Private subobject */
  161968. typedef struct {
  161969. struct jpeg_color_converter pub; /* public fields */
  161970. /* Private state for RGB->YCC conversion */
  161971. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  161972. } my_color_converter;
  161973. typedef my_color_converter * my_cconvert_ptr;
  161974. /**************** RGB -> YCbCr conversion: most common case **************/
  161975. /*
  161976. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  161977. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  161978. * The conversion equations to be implemented are therefore
  161979. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  161980. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  161981. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  161982. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  161983. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  161984. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  161985. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  161986. * were not represented exactly. Now we sacrifice exact representation of
  161987. * maximum red and maximum blue in order to get exact grayscales.
  161988. *
  161989. * To avoid floating-point arithmetic, we represent the fractional constants
  161990. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  161991. * the products by 2^16, with appropriate rounding, to get the correct answer.
  161992. *
  161993. * For even more speed, we avoid doing any multiplications in the inner loop
  161994. * by precalculating the constants times R,G,B for all possible values.
  161995. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  161996. * for 12-bit samples it is still acceptable. It's not very reasonable for
  161997. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  161998. * colorspace anyway.
  161999. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  162000. * in the tables to save adding them separately in the inner loop.
  162001. */
  162002. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162003. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  162004. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162005. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162006. /* We allocate one big table and divide it up into eight parts, instead of
  162007. * doing eight alloc_small requests. This lets us use a single table base
  162008. * address, which can be held in a register in the inner loops on many
  162009. * machines (more than can hold all eight addresses, anyway).
  162010. */
  162011. #define R_Y_OFF 0 /* offset to R => Y section */
  162012. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  162013. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  162014. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  162015. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  162016. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  162017. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  162018. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162019. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162020. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162021. /*
  162022. * Initialize for RGB->YCC colorspace conversion.
  162023. */
  162024. METHODDEF(void)
  162025. rgb_ycc_start (j_compress_ptr cinfo)
  162026. {
  162027. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162028. INT32 * rgb_ycc_tab;
  162029. INT32 i;
  162030. /* Allocate and fill in the conversion tables. */
  162031. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162032. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162033. (TABLE_SIZE * SIZEOF(INT32)));
  162034. for (i = 0; i <= MAXJSAMPLE; i++) {
  162035. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162036. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162037. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162038. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162039. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162040. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162041. * This ensures that the maximum output will round to MAXJSAMPLE
  162042. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162043. */
  162044. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162045. /* B=>Cb and R=>Cr tables are the same
  162046. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162047. */
  162048. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162049. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162050. }
  162051. }
  162052. /*
  162053. * Convert some rows of samples to the JPEG colorspace.
  162054. *
  162055. * Note that we change from the application's interleaved-pixel format
  162056. * to our internal noninterleaved, one-plane-per-component format.
  162057. * The input buffer is therefore three times as wide as the output buffer.
  162058. *
  162059. * A starting row offset is provided only for the output buffer. The caller
  162060. * can easily adjust the passed input_buf value to accommodate any row
  162061. * offset required on that side.
  162062. */
  162063. METHODDEF(void)
  162064. rgb_ycc_convert (j_compress_ptr cinfo,
  162065. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162066. JDIMENSION output_row, int num_rows)
  162067. {
  162068. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162069. register int r, g, b;
  162070. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162071. register JSAMPROW inptr;
  162072. register JSAMPROW outptr0, outptr1, outptr2;
  162073. register JDIMENSION col;
  162074. JDIMENSION num_cols = cinfo->image_width;
  162075. while (--num_rows >= 0) {
  162076. inptr = *input_buf++;
  162077. outptr0 = output_buf[0][output_row];
  162078. outptr1 = output_buf[1][output_row];
  162079. outptr2 = output_buf[2][output_row];
  162080. output_row++;
  162081. for (col = 0; col < num_cols; col++) {
  162082. r = GETJSAMPLE(inptr[RGB_RED]);
  162083. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162084. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162085. inptr += RGB_PIXELSIZE;
  162086. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162087. * must be too; we do not need an explicit range-limiting operation.
  162088. * Hence the value being shifted is never negative, and we don't
  162089. * need the general RIGHT_SHIFT macro.
  162090. */
  162091. /* Y */
  162092. outptr0[col] = (JSAMPLE)
  162093. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162094. >> SCALEBITS);
  162095. /* Cb */
  162096. outptr1[col] = (JSAMPLE)
  162097. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162098. >> SCALEBITS);
  162099. /* Cr */
  162100. outptr2[col] = (JSAMPLE)
  162101. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162102. >> SCALEBITS);
  162103. }
  162104. }
  162105. }
  162106. /**************** Cases other than RGB -> YCbCr **************/
  162107. /*
  162108. * Convert some rows of samples to the JPEG colorspace.
  162109. * This version handles RGB->grayscale conversion, which is the same
  162110. * as the RGB->Y portion of RGB->YCbCr.
  162111. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162112. */
  162113. METHODDEF(void)
  162114. rgb_gray_convert (j_compress_ptr cinfo,
  162115. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162116. JDIMENSION output_row, int num_rows)
  162117. {
  162118. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162119. register int r, g, b;
  162120. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162121. register JSAMPROW inptr;
  162122. register JSAMPROW outptr;
  162123. register JDIMENSION col;
  162124. JDIMENSION num_cols = cinfo->image_width;
  162125. while (--num_rows >= 0) {
  162126. inptr = *input_buf++;
  162127. outptr = output_buf[0][output_row];
  162128. output_row++;
  162129. for (col = 0; col < num_cols; col++) {
  162130. r = GETJSAMPLE(inptr[RGB_RED]);
  162131. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162132. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162133. inptr += RGB_PIXELSIZE;
  162134. /* Y */
  162135. outptr[col] = (JSAMPLE)
  162136. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162137. >> SCALEBITS);
  162138. }
  162139. }
  162140. }
  162141. /*
  162142. * Convert some rows of samples to the JPEG colorspace.
  162143. * This version handles Adobe-style CMYK->YCCK conversion,
  162144. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162145. * conversion as above, while passing K (black) unchanged.
  162146. * We assume rgb_ycc_start has been called.
  162147. */
  162148. METHODDEF(void)
  162149. cmyk_ycck_convert (j_compress_ptr cinfo,
  162150. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162151. JDIMENSION output_row, int num_rows)
  162152. {
  162153. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162154. register int r, g, b;
  162155. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162156. register JSAMPROW inptr;
  162157. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162158. register JDIMENSION col;
  162159. JDIMENSION num_cols = cinfo->image_width;
  162160. while (--num_rows >= 0) {
  162161. inptr = *input_buf++;
  162162. outptr0 = output_buf[0][output_row];
  162163. outptr1 = output_buf[1][output_row];
  162164. outptr2 = output_buf[2][output_row];
  162165. outptr3 = output_buf[3][output_row];
  162166. output_row++;
  162167. for (col = 0; col < num_cols; col++) {
  162168. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162169. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162170. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162171. /* K passes through as-is */
  162172. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162173. inptr += 4;
  162174. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162175. * must be too; we do not need an explicit range-limiting operation.
  162176. * Hence the value being shifted is never negative, and we don't
  162177. * need the general RIGHT_SHIFT macro.
  162178. */
  162179. /* Y */
  162180. outptr0[col] = (JSAMPLE)
  162181. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162182. >> SCALEBITS);
  162183. /* Cb */
  162184. outptr1[col] = (JSAMPLE)
  162185. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162186. >> SCALEBITS);
  162187. /* Cr */
  162188. outptr2[col] = (JSAMPLE)
  162189. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162190. >> SCALEBITS);
  162191. }
  162192. }
  162193. }
  162194. /*
  162195. * Convert some rows of samples to the JPEG colorspace.
  162196. * This version handles grayscale output with no conversion.
  162197. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162198. */
  162199. METHODDEF(void)
  162200. grayscale_convert (j_compress_ptr cinfo,
  162201. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162202. JDIMENSION output_row, int num_rows)
  162203. {
  162204. register JSAMPROW inptr;
  162205. register JSAMPROW outptr;
  162206. register JDIMENSION col;
  162207. JDIMENSION num_cols = cinfo->image_width;
  162208. int instride = cinfo->input_components;
  162209. while (--num_rows >= 0) {
  162210. inptr = *input_buf++;
  162211. outptr = output_buf[0][output_row];
  162212. output_row++;
  162213. for (col = 0; col < num_cols; col++) {
  162214. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162215. inptr += instride;
  162216. }
  162217. }
  162218. }
  162219. /*
  162220. * Convert some rows of samples to the JPEG colorspace.
  162221. * This version handles multi-component colorspaces without conversion.
  162222. * We assume input_components == num_components.
  162223. */
  162224. METHODDEF(void)
  162225. null_convert (j_compress_ptr cinfo,
  162226. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162227. JDIMENSION output_row, int num_rows)
  162228. {
  162229. register JSAMPROW inptr;
  162230. register JSAMPROW outptr;
  162231. register JDIMENSION col;
  162232. register int ci;
  162233. int nc = cinfo->num_components;
  162234. JDIMENSION num_cols = cinfo->image_width;
  162235. while (--num_rows >= 0) {
  162236. /* It seems fastest to make a separate pass for each component. */
  162237. for (ci = 0; ci < nc; ci++) {
  162238. inptr = *input_buf;
  162239. outptr = output_buf[ci][output_row];
  162240. for (col = 0; col < num_cols; col++) {
  162241. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162242. inptr += nc;
  162243. }
  162244. }
  162245. input_buf++;
  162246. output_row++;
  162247. }
  162248. }
  162249. /*
  162250. * Empty method for start_pass.
  162251. */
  162252. METHODDEF(void)
  162253. null_method (j_compress_ptr)
  162254. {
  162255. /* no work needed */
  162256. }
  162257. /*
  162258. * Module initialization routine for input colorspace conversion.
  162259. */
  162260. GLOBAL(void)
  162261. jinit_color_converter (j_compress_ptr cinfo)
  162262. {
  162263. my_cconvert_ptr cconvert;
  162264. cconvert = (my_cconvert_ptr)
  162265. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162266. SIZEOF(my_color_converter));
  162267. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162268. /* set start_pass to null method until we find out differently */
  162269. cconvert->pub.start_pass = null_method;
  162270. /* Make sure input_components agrees with in_color_space */
  162271. switch (cinfo->in_color_space) {
  162272. case JCS_GRAYSCALE:
  162273. if (cinfo->input_components != 1)
  162274. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162275. break;
  162276. case JCS_RGB:
  162277. #if RGB_PIXELSIZE != 3
  162278. if (cinfo->input_components != RGB_PIXELSIZE)
  162279. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162280. break;
  162281. #endif /* else share code with YCbCr */
  162282. case JCS_YCbCr:
  162283. if (cinfo->input_components != 3)
  162284. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162285. break;
  162286. case JCS_CMYK:
  162287. case JCS_YCCK:
  162288. if (cinfo->input_components != 4)
  162289. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162290. break;
  162291. default: /* JCS_UNKNOWN can be anything */
  162292. if (cinfo->input_components < 1)
  162293. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162294. break;
  162295. }
  162296. /* Check num_components, set conversion method based on requested space */
  162297. switch (cinfo->jpeg_color_space) {
  162298. case JCS_GRAYSCALE:
  162299. if (cinfo->num_components != 1)
  162300. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162301. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162302. cconvert->pub.color_convert = grayscale_convert;
  162303. else if (cinfo->in_color_space == JCS_RGB) {
  162304. cconvert->pub.start_pass = rgb_ycc_start;
  162305. cconvert->pub.color_convert = rgb_gray_convert;
  162306. } else if (cinfo->in_color_space == JCS_YCbCr)
  162307. cconvert->pub.color_convert = grayscale_convert;
  162308. else
  162309. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162310. break;
  162311. case JCS_RGB:
  162312. if (cinfo->num_components != 3)
  162313. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162314. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162315. cconvert->pub.color_convert = null_convert;
  162316. else
  162317. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162318. break;
  162319. case JCS_YCbCr:
  162320. if (cinfo->num_components != 3)
  162321. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162322. if (cinfo->in_color_space == JCS_RGB) {
  162323. cconvert->pub.start_pass = rgb_ycc_start;
  162324. cconvert->pub.color_convert = rgb_ycc_convert;
  162325. } else if (cinfo->in_color_space == JCS_YCbCr)
  162326. cconvert->pub.color_convert = null_convert;
  162327. else
  162328. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162329. break;
  162330. case JCS_CMYK:
  162331. if (cinfo->num_components != 4)
  162332. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162333. if (cinfo->in_color_space == JCS_CMYK)
  162334. cconvert->pub.color_convert = null_convert;
  162335. else
  162336. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162337. break;
  162338. case JCS_YCCK:
  162339. if (cinfo->num_components != 4)
  162340. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162341. if (cinfo->in_color_space == JCS_CMYK) {
  162342. cconvert->pub.start_pass = rgb_ycc_start;
  162343. cconvert->pub.color_convert = cmyk_ycck_convert;
  162344. } else if (cinfo->in_color_space == JCS_YCCK)
  162345. cconvert->pub.color_convert = null_convert;
  162346. else
  162347. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162348. break;
  162349. default: /* allow null conversion of JCS_UNKNOWN */
  162350. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162351. cinfo->num_components != cinfo->input_components)
  162352. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162353. cconvert->pub.color_convert = null_convert;
  162354. break;
  162355. }
  162356. }
  162357. /*** End of inlined file: jccolor.c ***/
  162358. #undef FIX
  162359. /*** Start of inlined file: jcdctmgr.c ***/
  162360. #define JPEG_INTERNALS
  162361. /*** Start of inlined file: jdct.h ***/
  162362. /*
  162363. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162364. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162365. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162366. * implementations use an array of type FAST_FLOAT, instead.)
  162367. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162368. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162369. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162370. * convention improves accuracy in integer implementations and saves some
  162371. * work in floating-point ones.
  162372. * Quantization of the output coefficients is done by jcdctmgr.c.
  162373. */
  162374. #ifndef __jdct_h__
  162375. #define __jdct_h__
  162376. #if BITS_IN_JSAMPLE == 8
  162377. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162378. #else
  162379. typedef INT32 DCTELEM; /* must have 32 bits */
  162380. #endif
  162381. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162382. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162383. /*
  162384. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162385. * to an output sample array. The routine must dequantize the input data as
  162386. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162387. * pointed to by compptr->dct_table. The output data is to be placed into the
  162388. * sample array starting at a specified column. (Any row offset needed will
  162389. * be applied to the array pointer before it is passed to the IDCT code.)
  162390. * Note that the number of samples emitted by the IDCT routine is
  162391. * DCT_scaled_size * DCT_scaled_size.
  162392. */
  162393. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162394. /*
  162395. * Each IDCT routine has its own ideas about the best dct_table element type.
  162396. */
  162397. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162398. #if BITS_IN_JSAMPLE == 8
  162399. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162400. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162401. #else
  162402. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162403. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162404. #endif
  162405. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162406. /*
  162407. * Each IDCT routine is responsible for range-limiting its results and
  162408. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162409. * be quite far out of range if the input data is corrupt, so a bulletproof
  162410. * range-limiting step is required. We use a mask-and-table-lookup method
  162411. * to do the combined operations quickly. See the comments with
  162412. * prepare_range_limit_table (in jdmaster.c) for more info.
  162413. */
  162414. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162415. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162416. /* Short forms of external names for systems with brain-damaged linkers. */
  162417. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162418. #define jpeg_fdct_islow jFDislow
  162419. #define jpeg_fdct_ifast jFDifast
  162420. #define jpeg_fdct_float jFDfloat
  162421. #define jpeg_idct_islow jRDislow
  162422. #define jpeg_idct_ifast jRDifast
  162423. #define jpeg_idct_float jRDfloat
  162424. #define jpeg_idct_4x4 jRD4x4
  162425. #define jpeg_idct_2x2 jRD2x2
  162426. #define jpeg_idct_1x1 jRD1x1
  162427. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162428. /* Extern declarations for the forward and inverse DCT routines. */
  162429. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162430. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162431. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162432. EXTERN(void) jpeg_idct_islow
  162433. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162434. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162435. EXTERN(void) jpeg_idct_ifast
  162436. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162437. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162438. EXTERN(void) jpeg_idct_float
  162439. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162440. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162441. EXTERN(void) jpeg_idct_4x4
  162442. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162443. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162444. EXTERN(void) jpeg_idct_2x2
  162445. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162446. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162447. EXTERN(void) jpeg_idct_1x1
  162448. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162449. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162450. /*
  162451. * Macros for handling fixed-point arithmetic; these are used by many
  162452. * but not all of the DCT/IDCT modules.
  162453. *
  162454. * All values are expected to be of type INT32.
  162455. * Fractional constants are scaled left by CONST_BITS bits.
  162456. * CONST_BITS is defined within each module using these macros,
  162457. * and may differ from one module to the next.
  162458. */
  162459. #define ONE ((INT32) 1)
  162460. #define CONST_SCALE (ONE << CONST_BITS)
  162461. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162462. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162463. * thus causing a lot of useless floating-point operations at run time.
  162464. */
  162465. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162466. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162467. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162468. * the fudge factor is correct for either sign of X.
  162469. */
  162470. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162471. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162472. * This macro is used only when the two inputs will actually be no more than
  162473. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162474. * full 32x32 multiply. This provides a useful speedup on many machines.
  162475. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162476. * in C, but some C compilers will do the right thing if you provide the
  162477. * correct combination of casts.
  162478. */
  162479. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162480. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162481. #endif
  162482. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162483. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162484. #endif
  162485. #ifndef MULTIPLY16C16 /* default definition */
  162486. #define MULTIPLY16C16(var,const) ((var) * (const))
  162487. #endif
  162488. /* Same except both inputs are variables. */
  162489. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162490. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  162491. #endif
  162492. #ifndef MULTIPLY16V16 /* default definition */
  162493. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  162494. #endif
  162495. #endif
  162496. /*** End of inlined file: jdct.h ***/
  162497. /* Private declarations for DCT subsystem */
  162498. /* Private subobject for this module */
  162499. typedef struct {
  162500. struct jpeg_forward_dct pub; /* public fields */
  162501. /* Pointer to the DCT routine actually in use */
  162502. forward_DCT_method_ptr do_dct;
  162503. /* The actual post-DCT divisors --- not identical to the quant table
  162504. * entries, because of scaling (especially for an unnormalized DCT).
  162505. * Each table is given in normal array order.
  162506. */
  162507. DCTELEM * divisors[NUM_QUANT_TBLS];
  162508. #ifdef DCT_FLOAT_SUPPORTED
  162509. /* Same as above for the floating-point case. */
  162510. float_DCT_method_ptr do_float_dct;
  162511. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  162512. #endif
  162513. } my_fdct_controller;
  162514. typedef my_fdct_controller * my_fdct_ptr;
  162515. /*
  162516. * Initialize for a processing pass.
  162517. * Verify that all referenced Q-tables are present, and set up
  162518. * the divisor table for each one.
  162519. * In the current implementation, DCT of all components is done during
  162520. * the first pass, even if only some components will be output in the
  162521. * first scan. Hence all components should be examined here.
  162522. */
  162523. METHODDEF(void)
  162524. start_pass_fdctmgr (j_compress_ptr cinfo)
  162525. {
  162526. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162527. int ci, qtblno, i;
  162528. jpeg_component_info *compptr;
  162529. JQUANT_TBL * qtbl;
  162530. DCTELEM * dtbl;
  162531. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162532. ci++, compptr++) {
  162533. qtblno = compptr->quant_tbl_no;
  162534. /* Make sure specified quantization table is present */
  162535. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  162536. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  162537. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  162538. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  162539. /* Compute divisors for this quant table */
  162540. /* We may do this more than once for same table, but it's not a big deal */
  162541. switch (cinfo->dct_method) {
  162542. #ifdef DCT_ISLOW_SUPPORTED
  162543. case JDCT_ISLOW:
  162544. /* For LL&M IDCT method, divisors are equal to raw quantization
  162545. * coefficients multiplied by 8 (to counteract scaling).
  162546. */
  162547. if (fdct->divisors[qtblno] == NULL) {
  162548. fdct->divisors[qtblno] = (DCTELEM *)
  162549. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162550. DCTSIZE2 * SIZEOF(DCTELEM));
  162551. }
  162552. dtbl = fdct->divisors[qtblno];
  162553. for (i = 0; i < DCTSIZE2; i++) {
  162554. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  162555. }
  162556. break;
  162557. #endif
  162558. #ifdef DCT_IFAST_SUPPORTED
  162559. case JDCT_IFAST:
  162560. {
  162561. /* For AA&N IDCT method, divisors are equal to quantization
  162562. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162563. * scalefactor[0] = 1
  162564. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162565. * We apply a further scale factor of 8.
  162566. */
  162567. #define CONST_BITS 14
  162568. static const INT16 aanscales[DCTSIZE2] = {
  162569. /* precomputed values scaled up by 14 bits */
  162570. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162571. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162572. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162573. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162574. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162575. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162576. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162577. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162578. };
  162579. SHIFT_TEMPS
  162580. if (fdct->divisors[qtblno] == NULL) {
  162581. fdct->divisors[qtblno] = (DCTELEM *)
  162582. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162583. DCTSIZE2 * SIZEOF(DCTELEM));
  162584. }
  162585. dtbl = fdct->divisors[qtblno];
  162586. for (i = 0; i < DCTSIZE2; i++) {
  162587. dtbl[i] = (DCTELEM)
  162588. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162589. (INT32) aanscales[i]),
  162590. CONST_BITS-3);
  162591. }
  162592. }
  162593. break;
  162594. #endif
  162595. #ifdef DCT_FLOAT_SUPPORTED
  162596. case JDCT_FLOAT:
  162597. {
  162598. /* For float AA&N IDCT method, divisors are equal to quantization
  162599. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162600. * scalefactor[0] = 1
  162601. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162602. * We apply a further scale factor of 8.
  162603. * What's actually stored is 1/divisor so that the inner loop can
  162604. * use a multiplication rather than a division.
  162605. */
  162606. FAST_FLOAT * fdtbl;
  162607. int row, col;
  162608. static const double aanscalefactor[DCTSIZE] = {
  162609. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162610. 1.0, 0.785694958, 0.541196100, 0.275899379
  162611. };
  162612. if (fdct->float_divisors[qtblno] == NULL) {
  162613. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  162614. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162615. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  162616. }
  162617. fdtbl = fdct->float_divisors[qtblno];
  162618. i = 0;
  162619. for (row = 0; row < DCTSIZE; row++) {
  162620. for (col = 0; col < DCTSIZE; col++) {
  162621. fdtbl[i] = (FAST_FLOAT)
  162622. (1.0 / (((double) qtbl->quantval[i] *
  162623. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  162624. i++;
  162625. }
  162626. }
  162627. }
  162628. break;
  162629. #endif
  162630. default:
  162631. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162632. break;
  162633. }
  162634. }
  162635. }
  162636. /*
  162637. * Perform forward DCT on one or more blocks of a component.
  162638. *
  162639. * The input samples are taken from the sample_data[] array starting at
  162640. * position start_row/start_col, and moving to the right for any additional
  162641. * blocks. The quantized coefficients are returned in coef_blocks[].
  162642. */
  162643. METHODDEF(void)
  162644. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162645. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162646. JDIMENSION start_row, JDIMENSION start_col,
  162647. JDIMENSION num_blocks)
  162648. /* This version is used for integer DCT implementations. */
  162649. {
  162650. /* This routine is heavily used, so it's worth coding it tightly. */
  162651. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162652. forward_DCT_method_ptr do_dct = fdct->do_dct;
  162653. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  162654. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162655. JDIMENSION bi;
  162656. sample_data += start_row; /* fold in the vertical offset once */
  162657. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162658. /* Load data into workspace, applying unsigned->signed conversion */
  162659. { register DCTELEM *workspaceptr;
  162660. register JSAMPROW elemptr;
  162661. register int elemr;
  162662. workspaceptr = workspace;
  162663. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162664. elemptr = sample_data[elemr] + start_col;
  162665. #if DCTSIZE == 8 /* unroll the inner loop */
  162666. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162667. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162668. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162669. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162670. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162671. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162672. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162673. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162674. #else
  162675. { register int elemc;
  162676. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162677. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162678. }
  162679. }
  162680. #endif
  162681. }
  162682. }
  162683. /* Perform the DCT */
  162684. (*do_dct) (workspace);
  162685. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162686. { register DCTELEM temp, qval;
  162687. register int i;
  162688. register JCOEFPTR output_ptr = coef_blocks[bi];
  162689. for (i = 0; i < DCTSIZE2; i++) {
  162690. qval = divisors[i];
  162691. temp = workspace[i];
  162692. /* Divide the coefficient value by qval, ensuring proper rounding.
  162693. * Since C does not specify the direction of rounding for negative
  162694. * quotients, we have to force the dividend positive for portability.
  162695. *
  162696. * In most files, at least half of the output values will be zero
  162697. * (at default quantization settings, more like three-quarters...)
  162698. * so we should ensure that this case is fast. On many machines,
  162699. * a comparison is enough cheaper than a divide to make a special test
  162700. * a win. Since both inputs will be nonnegative, we need only test
  162701. * for a < b to discover whether a/b is 0.
  162702. * If your machine's division is fast enough, define FAST_DIVIDE.
  162703. */
  162704. #ifdef FAST_DIVIDE
  162705. #define DIVIDE_BY(a,b) a /= b
  162706. #else
  162707. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  162708. #endif
  162709. if (temp < 0) {
  162710. temp = -temp;
  162711. temp += qval>>1; /* for rounding */
  162712. DIVIDE_BY(temp, qval);
  162713. temp = -temp;
  162714. } else {
  162715. temp += qval>>1; /* for rounding */
  162716. DIVIDE_BY(temp, qval);
  162717. }
  162718. output_ptr[i] = (JCOEF) temp;
  162719. }
  162720. }
  162721. }
  162722. }
  162723. #ifdef DCT_FLOAT_SUPPORTED
  162724. METHODDEF(void)
  162725. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162726. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162727. JDIMENSION start_row, JDIMENSION start_col,
  162728. JDIMENSION num_blocks)
  162729. /* This version is used for floating-point DCT implementations. */
  162730. {
  162731. /* This routine is heavily used, so it's worth coding it tightly. */
  162732. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162733. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  162734. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  162735. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162736. JDIMENSION bi;
  162737. sample_data += start_row; /* fold in the vertical offset once */
  162738. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162739. /* Load data into workspace, applying unsigned->signed conversion */
  162740. { register FAST_FLOAT *workspaceptr;
  162741. register JSAMPROW elemptr;
  162742. register int elemr;
  162743. workspaceptr = workspace;
  162744. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162745. elemptr = sample_data[elemr] + start_col;
  162746. #if DCTSIZE == 8 /* unroll the inner loop */
  162747. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162748. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162749. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162750. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162751. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162752. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162753. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162754. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162755. #else
  162756. { register int elemc;
  162757. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162758. *workspaceptr++ = (FAST_FLOAT)
  162759. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162760. }
  162761. }
  162762. #endif
  162763. }
  162764. }
  162765. /* Perform the DCT */
  162766. (*do_dct) (workspace);
  162767. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162768. { register FAST_FLOAT temp;
  162769. register int i;
  162770. register JCOEFPTR output_ptr = coef_blocks[bi];
  162771. for (i = 0; i < DCTSIZE2; i++) {
  162772. /* Apply the quantization and scaling factor */
  162773. temp = workspace[i] * divisors[i];
  162774. /* Round to nearest integer.
  162775. * Since C does not specify the direction of rounding for negative
  162776. * quotients, we have to force the dividend positive for portability.
  162777. * The maximum coefficient size is +-16K (for 12-bit data), so this
  162778. * code should work for either 16-bit or 32-bit ints.
  162779. */
  162780. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  162781. }
  162782. }
  162783. }
  162784. }
  162785. #endif /* DCT_FLOAT_SUPPORTED */
  162786. /*
  162787. * Initialize FDCT manager.
  162788. */
  162789. GLOBAL(void)
  162790. jinit_forward_dct (j_compress_ptr cinfo)
  162791. {
  162792. my_fdct_ptr fdct;
  162793. int i;
  162794. fdct = (my_fdct_ptr)
  162795. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162796. SIZEOF(my_fdct_controller));
  162797. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  162798. fdct->pub.start_pass = start_pass_fdctmgr;
  162799. switch (cinfo->dct_method) {
  162800. #ifdef DCT_ISLOW_SUPPORTED
  162801. case JDCT_ISLOW:
  162802. fdct->pub.forward_DCT = forward_DCT;
  162803. fdct->do_dct = jpeg_fdct_islow;
  162804. break;
  162805. #endif
  162806. #ifdef DCT_IFAST_SUPPORTED
  162807. case JDCT_IFAST:
  162808. fdct->pub.forward_DCT = forward_DCT;
  162809. fdct->do_dct = jpeg_fdct_ifast;
  162810. break;
  162811. #endif
  162812. #ifdef DCT_FLOAT_SUPPORTED
  162813. case JDCT_FLOAT:
  162814. fdct->pub.forward_DCT = forward_DCT_float;
  162815. fdct->do_float_dct = jpeg_fdct_float;
  162816. break;
  162817. #endif
  162818. default:
  162819. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162820. break;
  162821. }
  162822. /* Mark divisor tables unallocated */
  162823. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  162824. fdct->divisors[i] = NULL;
  162825. #ifdef DCT_FLOAT_SUPPORTED
  162826. fdct->float_divisors[i] = NULL;
  162827. #endif
  162828. }
  162829. }
  162830. /*** End of inlined file: jcdctmgr.c ***/
  162831. #undef CONST_BITS
  162832. /*** Start of inlined file: jchuff.c ***/
  162833. #define JPEG_INTERNALS
  162834. /*** Start of inlined file: jchuff.h ***/
  162835. /* The legal range of a DCT coefficient is
  162836. * -1024 .. +1023 for 8-bit data;
  162837. * -16384 .. +16383 for 12-bit data.
  162838. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  162839. */
  162840. #ifndef _jchuff_h_
  162841. #define _jchuff_h_
  162842. #if BITS_IN_JSAMPLE == 8
  162843. #define MAX_COEF_BITS 10
  162844. #else
  162845. #define MAX_COEF_BITS 14
  162846. #endif
  162847. /* Derived data constructed for each Huffman table */
  162848. typedef struct {
  162849. unsigned int ehufco[256]; /* code for each symbol */
  162850. char ehufsi[256]; /* length of code for each symbol */
  162851. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  162852. } c_derived_tbl;
  162853. /* Short forms of external names for systems with brain-damaged linkers. */
  162854. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162855. #define jpeg_make_c_derived_tbl jMkCDerived
  162856. #define jpeg_gen_optimal_table jGenOptTbl
  162857. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162858. /* Expand a Huffman table definition into the derived format */
  162859. EXTERN(void) jpeg_make_c_derived_tbl
  162860. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  162861. c_derived_tbl ** pdtbl));
  162862. /* Generate an optimal table definition given the specified counts */
  162863. EXTERN(void) jpeg_gen_optimal_table
  162864. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  162865. #endif
  162866. /*** End of inlined file: jchuff.h ***/
  162867. /* Declarations shared with jcphuff.c */
  162868. /* Expanded entropy encoder object for Huffman encoding.
  162869. *
  162870. * The savable_state subrecord contains fields that change within an MCU,
  162871. * but must not be updated permanently until we complete the MCU.
  162872. */
  162873. typedef struct {
  162874. INT32 put_buffer; /* current bit-accumulation buffer */
  162875. int put_bits; /* # of bits now in it */
  162876. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  162877. } savable_state;
  162878. /* This macro is to work around compilers with missing or broken
  162879. * structure assignment. You'll need to fix this code if you have
  162880. * such a compiler and you change MAX_COMPS_IN_SCAN.
  162881. */
  162882. #ifndef NO_STRUCT_ASSIGN
  162883. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  162884. #else
  162885. #if MAX_COMPS_IN_SCAN == 4
  162886. #define ASSIGN_STATE(dest,src) \
  162887. ((dest).put_buffer = (src).put_buffer, \
  162888. (dest).put_bits = (src).put_bits, \
  162889. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  162890. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  162891. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  162892. (dest).last_dc_val[3] = (src).last_dc_val[3])
  162893. #endif
  162894. #endif
  162895. typedef struct {
  162896. struct jpeg_entropy_encoder pub; /* public fields */
  162897. savable_state saved; /* Bit buffer & DC state at start of MCU */
  162898. /* These fields are NOT loaded into local working state. */
  162899. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  162900. int next_restart_num; /* next restart number to write (0-7) */
  162901. /* Pointers to derived tables (these workspaces have image lifespan) */
  162902. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  162903. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  162904. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  162905. long * dc_count_ptrs[NUM_HUFF_TBLS];
  162906. long * ac_count_ptrs[NUM_HUFF_TBLS];
  162907. #endif
  162908. } huff_entropy_encoder;
  162909. typedef huff_entropy_encoder * huff_entropy_ptr;
  162910. /* Working state while writing an MCU.
  162911. * This struct contains all the fields that are needed by subroutines.
  162912. */
  162913. typedef struct {
  162914. JOCTET * next_output_byte; /* => next byte to write in buffer */
  162915. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  162916. savable_state cur; /* Current bit buffer & DC state */
  162917. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  162918. } working_state;
  162919. /* Forward declarations */
  162920. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  162921. JBLOCKROW *MCU_data));
  162922. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  162923. #ifdef ENTROPY_OPT_SUPPORTED
  162924. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  162925. JBLOCKROW *MCU_data));
  162926. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  162927. #endif
  162928. /*
  162929. * Initialize for a Huffman-compressed scan.
  162930. * If gather_statistics is TRUE, we do not output anything during the scan,
  162931. * just count the Huffman symbols used and generate Huffman code tables.
  162932. */
  162933. METHODDEF(void)
  162934. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  162935. {
  162936. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162937. int ci, dctbl, actbl;
  162938. jpeg_component_info * compptr;
  162939. if (gather_statistics) {
  162940. #ifdef ENTROPY_OPT_SUPPORTED
  162941. entropy->pub.encode_mcu = encode_mcu_gather;
  162942. entropy->pub.finish_pass = finish_pass_gather;
  162943. #else
  162944. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162945. #endif
  162946. } else {
  162947. entropy->pub.encode_mcu = encode_mcu_huff;
  162948. entropy->pub.finish_pass = finish_pass_huff;
  162949. }
  162950. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162951. compptr = cinfo->cur_comp_info[ci];
  162952. dctbl = compptr->dc_tbl_no;
  162953. actbl = compptr->ac_tbl_no;
  162954. if (gather_statistics) {
  162955. #ifdef ENTROPY_OPT_SUPPORTED
  162956. /* Check for invalid table indexes */
  162957. /* (make_c_derived_tbl does this in the other path) */
  162958. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  162959. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  162960. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  162961. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  162962. /* Allocate and zero the statistics tables */
  162963. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  162964. if (entropy->dc_count_ptrs[dctbl] == NULL)
  162965. entropy->dc_count_ptrs[dctbl] = (long *)
  162966. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162967. 257 * SIZEOF(long));
  162968. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  162969. if (entropy->ac_count_ptrs[actbl] == NULL)
  162970. entropy->ac_count_ptrs[actbl] = (long *)
  162971. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162972. 257 * SIZEOF(long));
  162973. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  162974. #endif
  162975. } else {
  162976. /* Compute derived values for Huffman tables */
  162977. /* We may do this more than once for a table, but it's not expensive */
  162978. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  162979. & entropy->dc_derived_tbls[dctbl]);
  162980. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  162981. & entropy->ac_derived_tbls[actbl]);
  162982. }
  162983. /* Initialize DC predictions to 0 */
  162984. entropy->saved.last_dc_val[ci] = 0;
  162985. }
  162986. /* Initialize bit buffer to empty */
  162987. entropy->saved.put_buffer = 0;
  162988. entropy->saved.put_bits = 0;
  162989. /* Initialize restart stuff */
  162990. entropy->restarts_to_go = cinfo->restart_interval;
  162991. entropy->next_restart_num = 0;
  162992. }
  162993. /*
  162994. * Compute the derived values for a Huffman table.
  162995. * This routine also performs some validation checks on the table.
  162996. *
  162997. * Note this is also used by jcphuff.c.
  162998. */
  162999. GLOBAL(void)
  163000. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  163001. c_derived_tbl ** pdtbl)
  163002. {
  163003. JHUFF_TBL *htbl;
  163004. c_derived_tbl *dtbl;
  163005. int p, i, l, lastp, si, maxsymbol;
  163006. char huffsize[257];
  163007. unsigned int huffcode[257];
  163008. unsigned int code;
  163009. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163010. * paralleling the order of the symbols themselves in htbl->huffval[].
  163011. */
  163012. /* Find the input Huffman table */
  163013. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163014. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163015. htbl =
  163016. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163017. if (htbl == NULL)
  163018. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163019. /* Allocate a workspace if we haven't already done so. */
  163020. if (*pdtbl == NULL)
  163021. *pdtbl = (c_derived_tbl *)
  163022. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163023. SIZEOF(c_derived_tbl));
  163024. dtbl = *pdtbl;
  163025. /* Figure C.1: make table of Huffman code length for each symbol */
  163026. p = 0;
  163027. for (l = 1; l <= 16; l++) {
  163028. i = (int) htbl->bits[l];
  163029. if (i < 0 || p + i > 256) /* protect against table overrun */
  163030. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163031. while (i--)
  163032. huffsize[p++] = (char) l;
  163033. }
  163034. huffsize[p] = 0;
  163035. lastp = p;
  163036. /* Figure C.2: generate the codes themselves */
  163037. /* We also validate that the counts represent a legal Huffman code tree. */
  163038. code = 0;
  163039. si = huffsize[0];
  163040. p = 0;
  163041. while (huffsize[p]) {
  163042. while (((int) huffsize[p]) == si) {
  163043. huffcode[p++] = code;
  163044. code++;
  163045. }
  163046. /* code is now 1 more than the last code used for codelength si; but
  163047. * it must still fit in si bits, since no code is allowed to be all ones.
  163048. */
  163049. if (((INT32) code) >= (((INT32) 1) << si))
  163050. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163051. code <<= 1;
  163052. si++;
  163053. }
  163054. /* Figure C.3: generate encoding tables */
  163055. /* These are code and size indexed by symbol value */
  163056. /* Set all codeless symbols to have code length 0;
  163057. * this lets us detect duplicate VAL entries here, and later
  163058. * allows emit_bits to detect any attempt to emit such symbols.
  163059. */
  163060. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163061. /* This is also a convenient place to check for out-of-range
  163062. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163063. * but only 0..15 for DC. (We could constrain them further
  163064. * based on data depth and mode, but this seems enough.)
  163065. */
  163066. maxsymbol = isDC ? 15 : 255;
  163067. for (p = 0; p < lastp; p++) {
  163068. i = htbl->huffval[p];
  163069. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163070. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163071. dtbl->ehufco[i] = huffcode[p];
  163072. dtbl->ehufsi[i] = huffsize[p];
  163073. }
  163074. }
  163075. /* Outputting bytes to the file */
  163076. /* Emit a byte, taking 'action' if must suspend. */
  163077. #define emit_byte(state,val,action) \
  163078. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163079. if (--(state)->free_in_buffer == 0) \
  163080. if (! dump_buffer(state)) \
  163081. { action; } }
  163082. LOCAL(boolean)
  163083. dump_buffer (working_state * state)
  163084. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163085. {
  163086. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163087. if (! (*dest->empty_output_buffer) (state->cinfo))
  163088. return FALSE;
  163089. /* After a successful buffer dump, must reset buffer pointers */
  163090. state->next_output_byte = dest->next_output_byte;
  163091. state->free_in_buffer = dest->free_in_buffer;
  163092. return TRUE;
  163093. }
  163094. /* Outputting bits to the file */
  163095. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163096. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163097. * in one call, and we never retain more than 7 bits in put_buffer
  163098. * between calls, so 24 bits are sufficient.
  163099. */
  163100. INLINE
  163101. LOCAL(boolean)
  163102. emit_bits (working_state * state, unsigned int code, int size)
  163103. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163104. {
  163105. /* This routine is heavily used, so it's worth coding tightly. */
  163106. register INT32 put_buffer = (INT32) code;
  163107. register int put_bits = state->cur.put_bits;
  163108. /* if size is 0, caller used an invalid Huffman table entry */
  163109. if (size == 0)
  163110. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163111. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163112. put_bits += size; /* new number of bits in buffer */
  163113. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163114. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163115. while (put_bits >= 8) {
  163116. int c = (int) ((put_buffer >> 16) & 0xFF);
  163117. emit_byte(state, c, return FALSE);
  163118. if (c == 0xFF) { /* need to stuff a zero byte? */
  163119. emit_byte(state, 0, return FALSE);
  163120. }
  163121. put_buffer <<= 8;
  163122. put_bits -= 8;
  163123. }
  163124. state->cur.put_buffer = put_buffer; /* update state variables */
  163125. state->cur.put_bits = put_bits;
  163126. return TRUE;
  163127. }
  163128. LOCAL(boolean)
  163129. flush_bits (working_state * state)
  163130. {
  163131. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163132. return FALSE;
  163133. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163134. state->cur.put_bits = 0;
  163135. return TRUE;
  163136. }
  163137. /* Encode a single block's worth of coefficients */
  163138. LOCAL(boolean)
  163139. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163140. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163141. {
  163142. register int temp, temp2;
  163143. register int nbits;
  163144. register int k, r, i;
  163145. /* Encode the DC coefficient difference per section F.1.2.1 */
  163146. temp = temp2 = block[0] - last_dc_val;
  163147. if (temp < 0) {
  163148. temp = -temp; /* temp is abs value of input */
  163149. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163150. /* This code assumes we are on a two's complement machine */
  163151. temp2--;
  163152. }
  163153. /* Find the number of bits needed for the magnitude of the coefficient */
  163154. nbits = 0;
  163155. while (temp) {
  163156. nbits++;
  163157. temp >>= 1;
  163158. }
  163159. /* Check for out-of-range coefficient values.
  163160. * Since we're encoding a difference, the range limit is twice as much.
  163161. */
  163162. if (nbits > MAX_COEF_BITS+1)
  163163. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163164. /* Emit the Huffman-coded symbol for the number of bits */
  163165. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163166. return FALSE;
  163167. /* Emit that number of bits of the value, if positive, */
  163168. /* or the complement of its magnitude, if negative. */
  163169. if (nbits) /* emit_bits rejects calls with size 0 */
  163170. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163171. return FALSE;
  163172. /* Encode the AC coefficients per section F.1.2.2 */
  163173. r = 0; /* r = run length of zeros */
  163174. for (k = 1; k < DCTSIZE2; k++) {
  163175. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163176. r++;
  163177. } else {
  163178. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163179. while (r > 15) {
  163180. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163181. return FALSE;
  163182. r -= 16;
  163183. }
  163184. temp2 = temp;
  163185. if (temp < 0) {
  163186. temp = -temp; /* temp is abs value of input */
  163187. /* This code assumes we are on a two's complement machine */
  163188. temp2--;
  163189. }
  163190. /* Find the number of bits needed for the magnitude of the coefficient */
  163191. nbits = 1; /* there must be at least one 1 bit */
  163192. while ((temp >>= 1))
  163193. nbits++;
  163194. /* Check for out-of-range coefficient values */
  163195. if (nbits > MAX_COEF_BITS)
  163196. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163197. /* Emit Huffman symbol for run length / number of bits */
  163198. i = (r << 4) + nbits;
  163199. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163200. return FALSE;
  163201. /* Emit that number of bits of the value, if positive, */
  163202. /* or the complement of its magnitude, if negative. */
  163203. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163204. return FALSE;
  163205. r = 0;
  163206. }
  163207. }
  163208. /* If the last coef(s) were zero, emit an end-of-block code */
  163209. if (r > 0)
  163210. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163211. return FALSE;
  163212. return TRUE;
  163213. }
  163214. /*
  163215. * Emit a restart marker & resynchronize predictions.
  163216. */
  163217. LOCAL(boolean)
  163218. emit_restart (working_state * state, int restart_num)
  163219. {
  163220. int ci;
  163221. if (! flush_bits(state))
  163222. return FALSE;
  163223. emit_byte(state, 0xFF, return FALSE);
  163224. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163225. /* Re-initialize DC predictions to 0 */
  163226. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163227. state->cur.last_dc_val[ci] = 0;
  163228. /* The restart counter is not updated until we successfully write the MCU. */
  163229. return TRUE;
  163230. }
  163231. /*
  163232. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163233. */
  163234. METHODDEF(boolean)
  163235. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163236. {
  163237. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163238. working_state state;
  163239. int blkn, ci;
  163240. jpeg_component_info * compptr;
  163241. /* Load up working state */
  163242. state.next_output_byte = cinfo->dest->next_output_byte;
  163243. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163244. ASSIGN_STATE(state.cur, entropy->saved);
  163245. state.cinfo = cinfo;
  163246. /* Emit restart marker if needed */
  163247. if (cinfo->restart_interval) {
  163248. if (entropy->restarts_to_go == 0)
  163249. if (! emit_restart(&state, entropy->next_restart_num))
  163250. return FALSE;
  163251. }
  163252. /* Encode the MCU data blocks */
  163253. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163254. ci = cinfo->MCU_membership[blkn];
  163255. compptr = cinfo->cur_comp_info[ci];
  163256. if (! encode_one_block(&state,
  163257. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163258. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163259. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163260. return FALSE;
  163261. /* Update last_dc_val */
  163262. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163263. }
  163264. /* Completed MCU, so update state */
  163265. cinfo->dest->next_output_byte = state.next_output_byte;
  163266. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163267. ASSIGN_STATE(entropy->saved, state.cur);
  163268. /* Update restart-interval state too */
  163269. if (cinfo->restart_interval) {
  163270. if (entropy->restarts_to_go == 0) {
  163271. entropy->restarts_to_go = cinfo->restart_interval;
  163272. entropy->next_restart_num++;
  163273. entropy->next_restart_num &= 7;
  163274. }
  163275. entropy->restarts_to_go--;
  163276. }
  163277. return TRUE;
  163278. }
  163279. /*
  163280. * Finish up at the end of a Huffman-compressed scan.
  163281. */
  163282. METHODDEF(void)
  163283. finish_pass_huff (j_compress_ptr cinfo)
  163284. {
  163285. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163286. working_state state;
  163287. /* Load up working state ... flush_bits needs it */
  163288. state.next_output_byte = cinfo->dest->next_output_byte;
  163289. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163290. ASSIGN_STATE(state.cur, entropy->saved);
  163291. state.cinfo = cinfo;
  163292. /* Flush out the last data */
  163293. if (! flush_bits(&state))
  163294. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163295. /* Update state */
  163296. cinfo->dest->next_output_byte = state.next_output_byte;
  163297. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163298. ASSIGN_STATE(entropy->saved, state.cur);
  163299. }
  163300. /*
  163301. * Huffman coding optimization.
  163302. *
  163303. * We first scan the supplied data and count the number of uses of each symbol
  163304. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163305. * Then we build a Huffman coding tree for the observed counts.
  163306. * Symbols which are not needed at all for the particular image are not
  163307. * assigned any code, which saves space in the DHT marker as well as in
  163308. * the compressed data.
  163309. */
  163310. #ifdef ENTROPY_OPT_SUPPORTED
  163311. /* Process a single block's worth of coefficients */
  163312. LOCAL(void)
  163313. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163314. long dc_counts[], long ac_counts[])
  163315. {
  163316. register int temp;
  163317. register int nbits;
  163318. register int k, r;
  163319. /* Encode the DC coefficient difference per section F.1.2.1 */
  163320. temp = block[0] - last_dc_val;
  163321. if (temp < 0)
  163322. temp = -temp;
  163323. /* Find the number of bits needed for the magnitude of the coefficient */
  163324. nbits = 0;
  163325. while (temp) {
  163326. nbits++;
  163327. temp >>= 1;
  163328. }
  163329. /* Check for out-of-range coefficient values.
  163330. * Since we're encoding a difference, the range limit is twice as much.
  163331. */
  163332. if (nbits > MAX_COEF_BITS+1)
  163333. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163334. /* Count the Huffman symbol for the number of bits */
  163335. dc_counts[nbits]++;
  163336. /* Encode the AC coefficients per section F.1.2.2 */
  163337. r = 0; /* r = run length of zeros */
  163338. for (k = 1; k < DCTSIZE2; k++) {
  163339. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163340. r++;
  163341. } else {
  163342. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163343. while (r > 15) {
  163344. ac_counts[0xF0]++;
  163345. r -= 16;
  163346. }
  163347. /* Find the number of bits needed for the magnitude of the coefficient */
  163348. if (temp < 0)
  163349. temp = -temp;
  163350. /* Find the number of bits needed for the magnitude of the coefficient */
  163351. nbits = 1; /* there must be at least one 1 bit */
  163352. while ((temp >>= 1))
  163353. nbits++;
  163354. /* Check for out-of-range coefficient values */
  163355. if (nbits > MAX_COEF_BITS)
  163356. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163357. /* Count Huffman symbol for run length / number of bits */
  163358. ac_counts[(r << 4) + nbits]++;
  163359. r = 0;
  163360. }
  163361. }
  163362. /* If the last coef(s) were zero, emit an end-of-block code */
  163363. if (r > 0)
  163364. ac_counts[0]++;
  163365. }
  163366. /*
  163367. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163368. * No data is actually output, so no suspension return is possible.
  163369. */
  163370. METHODDEF(boolean)
  163371. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163372. {
  163373. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163374. int blkn, ci;
  163375. jpeg_component_info * compptr;
  163376. /* Take care of restart intervals if needed */
  163377. if (cinfo->restart_interval) {
  163378. if (entropy->restarts_to_go == 0) {
  163379. /* Re-initialize DC predictions to 0 */
  163380. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163381. entropy->saved.last_dc_val[ci] = 0;
  163382. /* Update restart state */
  163383. entropy->restarts_to_go = cinfo->restart_interval;
  163384. }
  163385. entropy->restarts_to_go--;
  163386. }
  163387. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163388. ci = cinfo->MCU_membership[blkn];
  163389. compptr = cinfo->cur_comp_info[ci];
  163390. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163391. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163392. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163393. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163394. }
  163395. return TRUE;
  163396. }
  163397. /*
  163398. * Generate the best Huffman code table for the given counts, fill htbl.
  163399. * Note this is also used by jcphuff.c.
  163400. *
  163401. * The JPEG standard requires that no symbol be assigned a codeword of all
  163402. * one bits (so that padding bits added at the end of a compressed segment
  163403. * can't look like a valid code). Because of the canonical ordering of
  163404. * codewords, this just means that there must be an unused slot in the
  163405. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163406. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163407. * with count 1. In theory that's not optimal; giving it count zero but
  163408. * including it in the symbol set anyway should give a better Huffman code.
  163409. * But the theoretically better code actually seems to come out worse in
  163410. * practice, because it produces more all-ones bytes (which incur stuffed
  163411. * zero bytes in the final file). In any case the difference is tiny.
  163412. *
  163413. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163414. * If some symbols have a very small but nonzero probability, the Huffman tree
  163415. * must be adjusted to meet the code length restriction. We currently use
  163416. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163417. * optimal; it may not choose the best possible limited-length code. But
  163418. * typically only very-low-frequency symbols will be given less-than-optimal
  163419. * lengths, so the code is almost optimal. Experimental comparisons against
  163420. * an optimal limited-length-code algorithm indicate that the difference is
  163421. * microscopic --- usually less than a hundredth of a percent of total size.
  163422. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163423. */
  163424. GLOBAL(void)
  163425. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163426. {
  163427. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163428. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163429. int codesize[257]; /* codesize[k] = code length of symbol k */
  163430. int others[257]; /* next symbol in current branch of tree */
  163431. int c1, c2;
  163432. int p, i, j;
  163433. long v;
  163434. /* This algorithm is explained in section K.2 of the JPEG standard */
  163435. MEMZERO(bits, SIZEOF(bits));
  163436. MEMZERO(codesize, SIZEOF(codesize));
  163437. for (i = 0; i < 257; i++)
  163438. others[i] = -1; /* init links to empty */
  163439. freq[256] = 1; /* make sure 256 has a nonzero count */
  163440. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163441. * that no real symbol is given code-value of all ones, because 256
  163442. * will be placed last in the largest codeword category.
  163443. */
  163444. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163445. for (;;) {
  163446. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163447. /* In case of ties, take the larger symbol number */
  163448. c1 = -1;
  163449. v = 1000000000L;
  163450. for (i = 0; i <= 256; i++) {
  163451. if (freq[i] && freq[i] <= v) {
  163452. v = freq[i];
  163453. c1 = i;
  163454. }
  163455. }
  163456. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163457. /* In case of ties, take the larger symbol number */
  163458. c2 = -1;
  163459. v = 1000000000L;
  163460. for (i = 0; i <= 256; i++) {
  163461. if (freq[i] && freq[i] <= v && i != c1) {
  163462. v = freq[i];
  163463. c2 = i;
  163464. }
  163465. }
  163466. /* Done if we've merged everything into one frequency */
  163467. if (c2 < 0)
  163468. break;
  163469. /* Else merge the two counts/trees */
  163470. freq[c1] += freq[c2];
  163471. freq[c2] = 0;
  163472. /* Increment the codesize of everything in c1's tree branch */
  163473. codesize[c1]++;
  163474. while (others[c1] >= 0) {
  163475. c1 = others[c1];
  163476. codesize[c1]++;
  163477. }
  163478. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163479. /* Increment the codesize of everything in c2's tree branch */
  163480. codesize[c2]++;
  163481. while (others[c2] >= 0) {
  163482. c2 = others[c2];
  163483. codesize[c2]++;
  163484. }
  163485. }
  163486. /* Now count the number of symbols of each code length */
  163487. for (i = 0; i <= 256; i++) {
  163488. if (codesize[i]) {
  163489. /* The JPEG standard seems to think that this can't happen, */
  163490. /* but I'm paranoid... */
  163491. if (codesize[i] > MAX_CLEN)
  163492. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  163493. bits[codesize[i]]++;
  163494. }
  163495. }
  163496. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  163497. * Huffman procedure assigned any such lengths, we must adjust the coding.
  163498. * Here is what the JPEG spec says about how this next bit works:
  163499. * Since symbols are paired for the longest Huffman code, the symbols are
  163500. * removed from this length category two at a time. The prefix for the pair
  163501. * (which is one bit shorter) is allocated to one of the pair; then,
  163502. * skipping the BITS entry for that prefix length, a code word from the next
  163503. * shortest nonzero BITS entry is converted into a prefix for two code words
  163504. * one bit longer.
  163505. */
  163506. for (i = MAX_CLEN; i > 16; i--) {
  163507. while (bits[i] > 0) {
  163508. j = i - 2; /* find length of new prefix to be used */
  163509. while (bits[j] == 0)
  163510. j--;
  163511. bits[i] -= 2; /* remove two symbols */
  163512. bits[i-1]++; /* one goes in this length */
  163513. bits[j+1] += 2; /* two new symbols in this length */
  163514. bits[j]--; /* symbol of this length is now a prefix */
  163515. }
  163516. }
  163517. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  163518. while (bits[i] == 0) /* find largest codelength still in use */
  163519. i--;
  163520. bits[i]--;
  163521. /* Return final symbol counts (only for lengths 0..16) */
  163522. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  163523. /* Return a list of the symbols sorted by code length */
  163524. /* It's not real clear to me why we don't need to consider the codelength
  163525. * changes made above, but the JPEG spec seems to think this works.
  163526. */
  163527. p = 0;
  163528. for (i = 1; i <= MAX_CLEN; i++) {
  163529. for (j = 0; j <= 255; j++) {
  163530. if (codesize[j] == i) {
  163531. htbl->huffval[p] = (UINT8) j;
  163532. p++;
  163533. }
  163534. }
  163535. }
  163536. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  163537. htbl->sent_table = FALSE;
  163538. }
  163539. /*
  163540. * Finish up a statistics-gathering pass and create the new Huffman tables.
  163541. */
  163542. METHODDEF(void)
  163543. finish_pass_gather (j_compress_ptr cinfo)
  163544. {
  163545. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163546. int ci, dctbl, actbl;
  163547. jpeg_component_info * compptr;
  163548. JHUFF_TBL **htblptr;
  163549. boolean did_dc[NUM_HUFF_TBLS];
  163550. boolean did_ac[NUM_HUFF_TBLS];
  163551. /* It's important not to apply jpeg_gen_optimal_table more than once
  163552. * per table, because it clobbers the input frequency counts!
  163553. */
  163554. MEMZERO(did_dc, SIZEOF(did_dc));
  163555. MEMZERO(did_ac, SIZEOF(did_ac));
  163556. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163557. compptr = cinfo->cur_comp_info[ci];
  163558. dctbl = compptr->dc_tbl_no;
  163559. actbl = compptr->ac_tbl_no;
  163560. if (! did_dc[dctbl]) {
  163561. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  163562. if (*htblptr == NULL)
  163563. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163564. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  163565. did_dc[dctbl] = TRUE;
  163566. }
  163567. if (! did_ac[actbl]) {
  163568. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  163569. if (*htblptr == NULL)
  163570. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163571. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  163572. did_ac[actbl] = TRUE;
  163573. }
  163574. }
  163575. }
  163576. #endif /* ENTROPY_OPT_SUPPORTED */
  163577. /*
  163578. * Module initialization routine for Huffman entropy encoding.
  163579. */
  163580. GLOBAL(void)
  163581. jinit_huff_encoder (j_compress_ptr cinfo)
  163582. {
  163583. huff_entropy_ptr entropy;
  163584. int i;
  163585. entropy = (huff_entropy_ptr)
  163586. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163587. SIZEOF(huff_entropy_encoder));
  163588. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163589. entropy->pub.start_pass = start_pass_huff;
  163590. /* Mark tables unallocated */
  163591. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163592. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163593. #ifdef ENTROPY_OPT_SUPPORTED
  163594. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  163595. #endif
  163596. }
  163597. }
  163598. /*** End of inlined file: jchuff.c ***/
  163599. #undef emit_byte
  163600. /*** Start of inlined file: jcinit.c ***/
  163601. #define JPEG_INTERNALS
  163602. /*
  163603. * Master selection of compression modules.
  163604. * This is done once at the start of processing an image. We determine
  163605. * which modules will be used and give them appropriate initialization calls.
  163606. */
  163607. GLOBAL(void)
  163608. jinit_compress_master (j_compress_ptr cinfo)
  163609. {
  163610. /* Initialize master control (includes parameter checking/processing) */
  163611. jinit_c_master_control(cinfo, FALSE /* full compression */);
  163612. /* Preprocessing */
  163613. if (! cinfo->raw_data_in) {
  163614. jinit_color_converter(cinfo);
  163615. jinit_downsampler(cinfo);
  163616. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  163617. }
  163618. /* Forward DCT */
  163619. jinit_forward_dct(cinfo);
  163620. /* Entropy encoding: either Huffman or arithmetic coding. */
  163621. if (cinfo->arith_code) {
  163622. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163623. } else {
  163624. if (cinfo->progressive_mode) {
  163625. #ifdef C_PROGRESSIVE_SUPPORTED
  163626. jinit_phuff_encoder(cinfo);
  163627. #else
  163628. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163629. #endif
  163630. } else
  163631. jinit_huff_encoder(cinfo);
  163632. }
  163633. /* Need a full-image coefficient buffer in any multi-pass mode. */
  163634. jinit_c_coef_controller(cinfo,
  163635. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  163636. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  163637. jinit_marker_writer(cinfo);
  163638. /* We can now tell the memory manager to allocate virtual arrays. */
  163639. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163640. /* Write the datastream header (SOI) immediately.
  163641. * Frame and scan headers are postponed till later.
  163642. * This lets application insert special markers after the SOI.
  163643. */
  163644. (*cinfo->marker->write_file_header) (cinfo);
  163645. }
  163646. /*** End of inlined file: jcinit.c ***/
  163647. /*** Start of inlined file: jcmainct.c ***/
  163648. #define JPEG_INTERNALS
  163649. /* Note: currently, there is no operating mode in which a full-image buffer
  163650. * is needed at this step. If there were, that mode could not be used with
  163651. * "raw data" input, since this module is bypassed in that case. However,
  163652. * we've left the code here for possible use in special applications.
  163653. */
  163654. #undef FULL_MAIN_BUFFER_SUPPORTED
  163655. /* Private buffer controller object */
  163656. typedef struct {
  163657. struct jpeg_c_main_controller pub; /* public fields */
  163658. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  163659. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  163660. boolean suspended; /* remember if we suspended output */
  163661. J_BUF_MODE pass_mode; /* current operating mode */
  163662. /* If using just a strip buffer, this points to the entire set of buffers
  163663. * (we allocate one for each component). In the full-image case, this
  163664. * points to the currently accessible strips of the virtual arrays.
  163665. */
  163666. JSAMPARRAY buffer[MAX_COMPONENTS];
  163667. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163668. /* If using full-image storage, this array holds pointers to virtual-array
  163669. * control blocks for each component. Unused if not full-image storage.
  163670. */
  163671. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  163672. #endif
  163673. } my_main_controller;
  163674. typedef my_main_controller * my_main_ptr;
  163675. /* Forward declarations */
  163676. METHODDEF(void) process_data_simple_main
  163677. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163678. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163679. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163680. METHODDEF(void) process_data_buffer_main
  163681. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163682. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163683. #endif
  163684. /*
  163685. * Initialize for a processing pass.
  163686. */
  163687. METHODDEF(void)
  163688. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163689. {
  163690. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163691. /* Do nothing in raw-data mode. */
  163692. if (cinfo->raw_data_in)
  163693. return;
  163694. main_->cur_iMCU_row = 0; /* initialize counters */
  163695. main_->rowgroup_ctr = 0;
  163696. main_->suspended = FALSE;
  163697. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  163698. switch (pass_mode) {
  163699. case JBUF_PASS_THRU:
  163700. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163701. if (main_->whole_image[0] != NULL)
  163702. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163703. #endif
  163704. main_->pub.process_data = process_data_simple_main;
  163705. break;
  163706. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163707. case JBUF_SAVE_SOURCE:
  163708. case JBUF_CRANK_DEST:
  163709. case JBUF_SAVE_AND_PASS:
  163710. if (main_->whole_image[0] == NULL)
  163711. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163712. main_->pub.process_data = process_data_buffer_main;
  163713. break;
  163714. #endif
  163715. default:
  163716. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163717. break;
  163718. }
  163719. }
  163720. /*
  163721. * Process some data.
  163722. * This routine handles the simple pass-through mode,
  163723. * where we have only a strip buffer.
  163724. */
  163725. METHODDEF(void)
  163726. process_data_simple_main (j_compress_ptr cinfo,
  163727. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163728. JDIMENSION in_rows_avail)
  163729. {
  163730. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163731. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163732. /* Read input data if we haven't filled the main buffer yet */
  163733. if (main_->rowgroup_ctr < DCTSIZE)
  163734. (*cinfo->prep->pre_process_data) (cinfo,
  163735. input_buf, in_row_ctr, in_rows_avail,
  163736. main_->buffer, &main_->rowgroup_ctr,
  163737. (JDIMENSION) DCTSIZE);
  163738. /* If we don't have a full iMCU row buffered, return to application for
  163739. * more data. Note that preprocessor will always pad to fill the iMCU row
  163740. * at the bottom of the image.
  163741. */
  163742. if (main_->rowgroup_ctr != DCTSIZE)
  163743. return;
  163744. /* Send the completed row to the compressor */
  163745. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  163746. /* If compressor did not consume the whole row, then we must need to
  163747. * suspend processing and return to the application. In this situation
  163748. * we pretend we didn't yet consume the last input row; otherwise, if
  163749. * it happened to be the last row of the image, the application would
  163750. * think we were done.
  163751. */
  163752. if (! main_->suspended) {
  163753. (*in_row_ctr)--;
  163754. main_->suspended = TRUE;
  163755. }
  163756. return;
  163757. }
  163758. /* We did finish the row. Undo our little suspension hack if a previous
  163759. * call suspended; then mark the main buffer empty.
  163760. */
  163761. if (main_->suspended) {
  163762. (*in_row_ctr)++;
  163763. main_->suspended = FALSE;
  163764. }
  163765. main_->rowgroup_ctr = 0;
  163766. main_->cur_iMCU_row++;
  163767. }
  163768. }
  163769. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163770. /*
  163771. * Process some data.
  163772. * This routine handles all of the modes that use a full-size buffer.
  163773. */
  163774. METHODDEF(void)
  163775. process_data_buffer_main (j_compress_ptr cinfo,
  163776. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163777. JDIMENSION in_rows_avail)
  163778. {
  163779. my_main_ptr main = (my_main_ptr) cinfo->main;
  163780. int ci;
  163781. jpeg_component_info *compptr;
  163782. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  163783. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163784. /* Realign the virtual buffers if at the start of an iMCU row. */
  163785. if (main->rowgroup_ctr == 0) {
  163786. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163787. ci++, compptr++) {
  163788. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  163789. ((j_common_ptr) cinfo, main->whole_image[ci],
  163790. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  163791. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  163792. }
  163793. /* In a read pass, pretend we just read some source data. */
  163794. if (! writing) {
  163795. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  163796. main->rowgroup_ctr = DCTSIZE;
  163797. }
  163798. }
  163799. /* If a write pass, read input data until the current iMCU row is full. */
  163800. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  163801. if (writing) {
  163802. (*cinfo->prep->pre_process_data) (cinfo,
  163803. input_buf, in_row_ctr, in_rows_avail,
  163804. main->buffer, &main->rowgroup_ctr,
  163805. (JDIMENSION) DCTSIZE);
  163806. /* Return to application if we need more data to fill the iMCU row. */
  163807. if (main->rowgroup_ctr < DCTSIZE)
  163808. return;
  163809. }
  163810. /* Emit data, unless this is a sink-only pass. */
  163811. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  163812. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  163813. /* If compressor did not consume the whole row, then we must need to
  163814. * suspend processing and return to the application. In this situation
  163815. * we pretend we didn't yet consume the last input row; otherwise, if
  163816. * it happened to be the last row of the image, the application would
  163817. * think we were done.
  163818. */
  163819. if (! main->suspended) {
  163820. (*in_row_ctr)--;
  163821. main->suspended = TRUE;
  163822. }
  163823. return;
  163824. }
  163825. /* We did finish the row. Undo our little suspension hack if a previous
  163826. * call suspended; then mark the main buffer empty.
  163827. */
  163828. if (main->suspended) {
  163829. (*in_row_ctr)++;
  163830. main->suspended = FALSE;
  163831. }
  163832. }
  163833. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  163834. main->rowgroup_ctr = 0;
  163835. main->cur_iMCU_row++;
  163836. }
  163837. }
  163838. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  163839. /*
  163840. * Initialize main buffer controller.
  163841. */
  163842. GLOBAL(void)
  163843. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  163844. {
  163845. my_main_ptr main_;
  163846. int ci;
  163847. jpeg_component_info *compptr;
  163848. main_ = (my_main_ptr)
  163849. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163850. SIZEOF(my_main_controller));
  163851. cinfo->main = (struct jpeg_c_main_controller *) main_;
  163852. main_->pub.start_pass = start_pass_main;
  163853. /* We don't need to create a buffer in raw-data mode. */
  163854. if (cinfo->raw_data_in)
  163855. return;
  163856. /* Create the buffer. It holds downsampled data, so each component
  163857. * may be of a different size.
  163858. */
  163859. if (need_full_buffer) {
  163860. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163861. /* Allocate a full-image virtual array for each component */
  163862. /* Note we pad the bottom to a multiple of the iMCU height */
  163863. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163864. ci++, compptr++) {
  163865. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  163866. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  163867. compptr->width_in_blocks * DCTSIZE,
  163868. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  163869. (long) compptr->v_samp_factor) * DCTSIZE,
  163870. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163871. }
  163872. #else
  163873. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163874. #endif
  163875. } else {
  163876. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163877. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  163878. #endif
  163879. /* Allocate a strip buffer for each component */
  163880. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163881. ci++, compptr++) {
  163882. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  163883. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163884. compptr->width_in_blocks * DCTSIZE,
  163885. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163886. }
  163887. }
  163888. }
  163889. /*** End of inlined file: jcmainct.c ***/
  163890. /*** Start of inlined file: jcmarker.c ***/
  163891. #define JPEG_INTERNALS
  163892. /* Private state */
  163893. typedef struct {
  163894. struct jpeg_marker_writer pub; /* public fields */
  163895. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  163896. } my_marker_writer;
  163897. typedef my_marker_writer * my_marker_ptr;
  163898. /*
  163899. * Basic output routines.
  163900. *
  163901. * Note that we do not support suspension while writing a marker.
  163902. * Therefore, an application using suspension must ensure that there is
  163903. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  163904. * calling jpeg_start_compress, and enough space to write the trailing EOI
  163905. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  163906. * modes are not supported at all with suspension, so those two are the only
  163907. * points where markers will be written.
  163908. */
  163909. LOCAL(void)
  163910. emit_byte (j_compress_ptr cinfo, int val)
  163911. /* Emit a byte */
  163912. {
  163913. struct jpeg_destination_mgr * dest = cinfo->dest;
  163914. *(dest->next_output_byte)++ = (JOCTET) val;
  163915. if (--dest->free_in_buffer == 0) {
  163916. if (! (*dest->empty_output_buffer) (cinfo))
  163917. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163918. }
  163919. }
  163920. LOCAL(void)
  163921. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  163922. /* Emit a marker code */
  163923. {
  163924. emit_byte(cinfo, 0xFF);
  163925. emit_byte(cinfo, (int) mark);
  163926. }
  163927. LOCAL(void)
  163928. emit_2bytes (j_compress_ptr cinfo, int value)
  163929. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  163930. {
  163931. emit_byte(cinfo, (value >> 8) & 0xFF);
  163932. emit_byte(cinfo, value & 0xFF);
  163933. }
  163934. /*
  163935. * Routines to write specific marker types.
  163936. */
  163937. LOCAL(int)
  163938. emit_dqt (j_compress_ptr cinfo, int index)
  163939. /* Emit a DQT marker */
  163940. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  163941. {
  163942. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  163943. int prec;
  163944. int i;
  163945. if (qtbl == NULL)
  163946. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  163947. prec = 0;
  163948. for (i = 0; i < DCTSIZE2; i++) {
  163949. if (qtbl->quantval[i] > 255)
  163950. prec = 1;
  163951. }
  163952. if (! qtbl->sent_table) {
  163953. emit_marker(cinfo, M_DQT);
  163954. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  163955. emit_byte(cinfo, index + (prec<<4));
  163956. for (i = 0; i < DCTSIZE2; i++) {
  163957. /* The table entries must be emitted in zigzag order. */
  163958. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  163959. if (prec)
  163960. emit_byte(cinfo, (int) (qval >> 8));
  163961. emit_byte(cinfo, (int) (qval & 0xFF));
  163962. }
  163963. qtbl->sent_table = TRUE;
  163964. }
  163965. return prec;
  163966. }
  163967. LOCAL(void)
  163968. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  163969. /* Emit a DHT marker */
  163970. {
  163971. JHUFF_TBL * htbl;
  163972. int length, i;
  163973. if (is_ac) {
  163974. htbl = cinfo->ac_huff_tbl_ptrs[index];
  163975. index += 0x10; /* output index has AC bit set */
  163976. } else {
  163977. htbl = cinfo->dc_huff_tbl_ptrs[index];
  163978. }
  163979. if (htbl == NULL)
  163980. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  163981. if (! htbl->sent_table) {
  163982. emit_marker(cinfo, M_DHT);
  163983. length = 0;
  163984. for (i = 1; i <= 16; i++)
  163985. length += htbl->bits[i];
  163986. emit_2bytes(cinfo, length + 2 + 1 + 16);
  163987. emit_byte(cinfo, index);
  163988. for (i = 1; i <= 16; i++)
  163989. emit_byte(cinfo, htbl->bits[i]);
  163990. for (i = 0; i < length; i++)
  163991. emit_byte(cinfo, htbl->huffval[i]);
  163992. htbl->sent_table = TRUE;
  163993. }
  163994. }
  163995. LOCAL(void)
  163996. emit_dac (j_compress_ptr)
  163997. /* Emit a DAC marker */
  163998. /* Since the useful info is so small, we want to emit all the tables in */
  163999. /* one DAC marker. Therefore this routine does its own scan of the table. */
  164000. {
  164001. #ifdef C_ARITH_CODING_SUPPORTED
  164002. char dc_in_use[NUM_ARITH_TBLS];
  164003. char ac_in_use[NUM_ARITH_TBLS];
  164004. int length, i;
  164005. jpeg_component_info *compptr;
  164006. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164007. dc_in_use[i] = ac_in_use[i] = 0;
  164008. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164009. compptr = cinfo->cur_comp_info[i];
  164010. dc_in_use[compptr->dc_tbl_no] = 1;
  164011. ac_in_use[compptr->ac_tbl_no] = 1;
  164012. }
  164013. length = 0;
  164014. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164015. length += dc_in_use[i] + ac_in_use[i];
  164016. emit_marker(cinfo, M_DAC);
  164017. emit_2bytes(cinfo, length*2 + 2);
  164018. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164019. if (dc_in_use[i]) {
  164020. emit_byte(cinfo, i);
  164021. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164022. }
  164023. if (ac_in_use[i]) {
  164024. emit_byte(cinfo, i + 0x10);
  164025. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164026. }
  164027. }
  164028. #endif /* C_ARITH_CODING_SUPPORTED */
  164029. }
  164030. LOCAL(void)
  164031. emit_dri (j_compress_ptr cinfo)
  164032. /* Emit a DRI marker */
  164033. {
  164034. emit_marker(cinfo, M_DRI);
  164035. emit_2bytes(cinfo, 4); /* fixed length */
  164036. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164037. }
  164038. LOCAL(void)
  164039. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164040. /* Emit a SOF marker */
  164041. {
  164042. int ci;
  164043. jpeg_component_info *compptr;
  164044. emit_marker(cinfo, code);
  164045. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164046. /* Make sure image isn't bigger than SOF field can handle */
  164047. if ((long) cinfo->image_height > 65535L ||
  164048. (long) cinfo->image_width > 65535L)
  164049. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164050. emit_byte(cinfo, cinfo->data_precision);
  164051. emit_2bytes(cinfo, (int) cinfo->image_height);
  164052. emit_2bytes(cinfo, (int) cinfo->image_width);
  164053. emit_byte(cinfo, cinfo->num_components);
  164054. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164055. ci++, compptr++) {
  164056. emit_byte(cinfo, compptr->component_id);
  164057. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164058. emit_byte(cinfo, compptr->quant_tbl_no);
  164059. }
  164060. }
  164061. LOCAL(void)
  164062. emit_sos (j_compress_ptr cinfo)
  164063. /* Emit a SOS marker */
  164064. {
  164065. int i, td, ta;
  164066. jpeg_component_info *compptr;
  164067. emit_marker(cinfo, M_SOS);
  164068. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164069. emit_byte(cinfo, cinfo->comps_in_scan);
  164070. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164071. compptr = cinfo->cur_comp_info[i];
  164072. emit_byte(cinfo, compptr->component_id);
  164073. td = compptr->dc_tbl_no;
  164074. ta = compptr->ac_tbl_no;
  164075. if (cinfo->progressive_mode) {
  164076. /* Progressive mode: only DC or only AC tables are used in one scan;
  164077. * furthermore, Huffman coding of DC refinement uses no table at all.
  164078. * We emit 0 for unused field(s); this is recommended by the P&M text
  164079. * but does not seem to be specified in the standard.
  164080. */
  164081. if (cinfo->Ss == 0) {
  164082. ta = 0; /* DC scan */
  164083. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164084. td = 0; /* no DC table either */
  164085. } else {
  164086. td = 0; /* AC scan */
  164087. }
  164088. }
  164089. emit_byte(cinfo, (td << 4) + ta);
  164090. }
  164091. emit_byte(cinfo, cinfo->Ss);
  164092. emit_byte(cinfo, cinfo->Se);
  164093. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164094. }
  164095. LOCAL(void)
  164096. emit_jfif_app0 (j_compress_ptr cinfo)
  164097. /* Emit a JFIF-compliant APP0 marker */
  164098. {
  164099. /*
  164100. * Length of APP0 block (2 bytes)
  164101. * Block ID (4 bytes - ASCII "JFIF")
  164102. * Zero byte (1 byte to terminate the ID string)
  164103. * Version Major, Minor (2 bytes - major first)
  164104. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164105. * Xdpu (2 bytes - dots per unit horizontal)
  164106. * Ydpu (2 bytes - dots per unit vertical)
  164107. * Thumbnail X size (1 byte)
  164108. * Thumbnail Y size (1 byte)
  164109. */
  164110. emit_marker(cinfo, M_APP0);
  164111. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164112. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164113. emit_byte(cinfo, 0x46);
  164114. emit_byte(cinfo, 0x49);
  164115. emit_byte(cinfo, 0x46);
  164116. emit_byte(cinfo, 0);
  164117. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164118. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164119. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164120. emit_2bytes(cinfo, (int) cinfo->X_density);
  164121. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164122. emit_byte(cinfo, 0); /* No thumbnail image */
  164123. emit_byte(cinfo, 0);
  164124. }
  164125. LOCAL(void)
  164126. emit_adobe_app14 (j_compress_ptr cinfo)
  164127. /* Emit an Adobe APP14 marker */
  164128. {
  164129. /*
  164130. * Length of APP14 block (2 bytes)
  164131. * Block ID (5 bytes - ASCII "Adobe")
  164132. * Version Number (2 bytes - currently 100)
  164133. * Flags0 (2 bytes - currently 0)
  164134. * Flags1 (2 bytes - currently 0)
  164135. * Color transform (1 byte)
  164136. *
  164137. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164138. * now in circulation seem to use Version = 100, so that's what we write.
  164139. *
  164140. * We write the color transform byte as 1 if the JPEG color space is
  164141. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164142. * whether the encoder performed a transformation, which is pretty useless.
  164143. */
  164144. emit_marker(cinfo, M_APP14);
  164145. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164146. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164147. emit_byte(cinfo, 0x64);
  164148. emit_byte(cinfo, 0x6F);
  164149. emit_byte(cinfo, 0x62);
  164150. emit_byte(cinfo, 0x65);
  164151. emit_2bytes(cinfo, 100); /* Version */
  164152. emit_2bytes(cinfo, 0); /* Flags0 */
  164153. emit_2bytes(cinfo, 0); /* Flags1 */
  164154. switch (cinfo->jpeg_color_space) {
  164155. case JCS_YCbCr:
  164156. emit_byte(cinfo, 1); /* Color transform = 1 */
  164157. break;
  164158. case JCS_YCCK:
  164159. emit_byte(cinfo, 2); /* Color transform = 2 */
  164160. break;
  164161. default:
  164162. emit_byte(cinfo, 0); /* Color transform = 0 */
  164163. break;
  164164. }
  164165. }
  164166. /*
  164167. * These routines allow writing an arbitrary marker with parameters.
  164168. * The only intended use is to emit COM or APPn markers after calling
  164169. * write_file_header and before calling write_frame_header.
  164170. * Other uses are not guaranteed to produce desirable results.
  164171. * Counting the parameter bytes properly is the caller's responsibility.
  164172. */
  164173. METHODDEF(void)
  164174. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164175. /* Emit an arbitrary marker header */
  164176. {
  164177. if (datalen > (unsigned int) 65533) /* safety check */
  164178. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164179. emit_marker(cinfo, (JPEG_MARKER) marker);
  164180. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164181. }
  164182. METHODDEF(void)
  164183. write_marker_byte (j_compress_ptr cinfo, int val)
  164184. /* Emit one byte of marker parameters following write_marker_header */
  164185. {
  164186. emit_byte(cinfo, val);
  164187. }
  164188. /*
  164189. * Write datastream header.
  164190. * This consists of an SOI and optional APPn markers.
  164191. * We recommend use of the JFIF marker, but not the Adobe marker,
  164192. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164193. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164194. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164195. * Note that an application can write additional header markers after
  164196. * jpeg_start_compress returns.
  164197. */
  164198. METHODDEF(void)
  164199. write_file_header (j_compress_ptr cinfo)
  164200. {
  164201. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164202. emit_marker(cinfo, M_SOI); /* first the SOI */
  164203. /* SOI is defined to reset restart interval to 0 */
  164204. marker->last_restart_interval = 0;
  164205. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164206. emit_jfif_app0(cinfo);
  164207. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164208. emit_adobe_app14(cinfo);
  164209. }
  164210. /*
  164211. * Write frame header.
  164212. * This consists of DQT and SOFn markers.
  164213. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164214. * This avoids compatibility problems with incorrect implementations that
  164215. * try to error-check the quant table numbers as soon as they see the SOF.
  164216. */
  164217. METHODDEF(void)
  164218. write_frame_header (j_compress_ptr cinfo)
  164219. {
  164220. int ci, prec;
  164221. boolean is_baseline;
  164222. jpeg_component_info *compptr;
  164223. /* Emit DQT for each quantization table.
  164224. * Note that emit_dqt() suppresses any duplicate tables.
  164225. */
  164226. prec = 0;
  164227. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164228. ci++, compptr++) {
  164229. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164230. }
  164231. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164232. /* Check for a non-baseline specification.
  164233. * Note we assume that Huffman table numbers won't be changed later.
  164234. */
  164235. if (cinfo->arith_code || cinfo->progressive_mode ||
  164236. cinfo->data_precision != 8) {
  164237. is_baseline = FALSE;
  164238. } else {
  164239. is_baseline = TRUE;
  164240. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164241. ci++, compptr++) {
  164242. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164243. is_baseline = FALSE;
  164244. }
  164245. if (prec && is_baseline) {
  164246. is_baseline = FALSE;
  164247. /* If it's baseline except for quantizer size, warn the user */
  164248. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164249. }
  164250. }
  164251. /* Emit the proper SOF marker */
  164252. if (cinfo->arith_code) {
  164253. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164254. } else {
  164255. if (cinfo->progressive_mode)
  164256. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164257. else if (is_baseline)
  164258. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164259. else
  164260. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164261. }
  164262. }
  164263. /*
  164264. * Write scan header.
  164265. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164266. * Compressed data will be written following the SOS.
  164267. */
  164268. METHODDEF(void)
  164269. write_scan_header (j_compress_ptr cinfo)
  164270. {
  164271. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164272. int i;
  164273. jpeg_component_info *compptr;
  164274. if (cinfo->arith_code) {
  164275. /* Emit arith conditioning info. We may have some duplication
  164276. * if the file has multiple scans, but it's so small it's hardly
  164277. * worth worrying about.
  164278. */
  164279. emit_dac(cinfo);
  164280. } else {
  164281. /* Emit Huffman tables.
  164282. * Note that emit_dht() suppresses any duplicate tables.
  164283. */
  164284. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164285. compptr = cinfo->cur_comp_info[i];
  164286. if (cinfo->progressive_mode) {
  164287. /* Progressive mode: only DC or only AC tables are used in one scan */
  164288. if (cinfo->Ss == 0) {
  164289. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164290. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164291. } else {
  164292. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164293. }
  164294. } else {
  164295. /* Sequential mode: need both DC and AC tables */
  164296. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164297. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164298. }
  164299. }
  164300. }
  164301. /* Emit DRI if required --- note that DRI value could change for each scan.
  164302. * We avoid wasting space with unnecessary DRIs, however.
  164303. */
  164304. if (cinfo->restart_interval != marker->last_restart_interval) {
  164305. emit_dri(cinfo);
  164306. marker->last_restart_interval = cinfo->restart_interval;
  164307. }
  164308. emit_sos(cinfo);
  164309. }
  164310. /*
  164311. * Write datastream trailer.
  164312. */
  164313. METHODDEF(void)
  164314. write_file_trailer (j_compress_ptr cinfo)
  164315. {
  164316. emit_marker(cinfo, M_EOI);
  164317. }
  164318. /*
  164319. * Write an abbreviated table-specification datastream.
  164320. * This consists of SOI, DQT and DHT tables, and EOI.
  164321. * Any table that is defined and not marked sent_table = TRUE will be
  164322. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164323. */
  164324. METHODDEF(void)
  164325. write_tables_only (j_compress_ptr cinfo)
  164326. {
  164327. int i;
  164328. emit_marker(cinfo, M_SOI);
  164329. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164330. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164331. (void) emit_dqt(cinfo, i);
  164332. }
  164333. if (! cinfo->arith_code) {
  164334. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164335. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164336. emit_dht(cinfo, i, FALSE);
  164337. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164338. emit_dht(cinfo, i, TRUE);
  164339. }
  164340. }
  164341. emit_marker(cinfo, M_EOI);
  164342. }
  164343. /*
  164344. * Initialize the marker writer module.
  164345. */
  164346. GLOBAL(void)
  164347. jinit_marker_writer (j_compress_ptr cinfo)
  164348. {
  164349. my_marker_ptr marker;
  164350. /* Create the subobject */
  164351. marker = (my_marker_ptr)
  164352. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164353. SIZEOF(my_marker_writer));
  164354. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164355. /* Initialize method pointers */
  164356. marker->pub.write_file_header = write_file_header;
  164357. marker->pub.write_frame_header = write_frame_header;
  164358. marker->pub.write_scan_header = write_scan_header;
  164359. marker->pub.write_file_trailer = write_file_trailer;
  164360. marker->pub.write_tables_only = write_tables_only;
  164361. marker->pub.write_marker_header = write_marker_header;
  164362. marker->pub.write_marker_byte = write_marker_byte;
  164363. /* Initialize private state */
  164364. marker->last_restart_interval = 0;
  164365. }
  164366. /*** End of inlined file: jcmarker.c ***/
  164367. /*** Start of inlined file: jcmaster.c ***/
  164368. #define JPEG_INTERNALS
  164369. /* Private state */
  164370. typedef enum {
  164371. main_pass, /* input data, also do first output step */
  164372. huff_opt_pass, /* Huffman code optimization pass */
  164373. output_pass /* data output pass */
  164374. } c_pass_type;
  164375. typedef struct {
  164376. struct jpeg_comp_master pub; /* public fields */
  164377. c_pass_type pass_type; /* the type of the current pass */
  164378. int pass_number; /* # of passes completed */
  164379. int total_passes; /* total # of passes needed */
  164380. int scan_number; /* current index in scan_info[] */
  164381. } my_comp_master;
  164382. typedef my_comp_master * my_master_ptr;
  164383. /*
  164384. * Support routines that do various essential calculations.
  164385. */
  164386. LOCAL(void)
  164387. initial_setup (j_compress_ptr cinfo)
  164388. /* Do computations that are needed before master selection phase */
  164389. {
  164390. int ci;
  164391. jpeg_component_info *compptr;
  164392. long samplesperrow;
  164393. JDIMENSION jd_samplesperrow;
  164394. /* Sanity check on image dimensions */
  164395. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164396. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164397. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164398. /* Make sure image isn't bigger than I can handle */
  164399. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164400. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164401. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164402. /* Width of an input scanline must be representable as JDIMENSION. */
  164403. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164404. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164405. if ((long) jd_samplesperrow != samplesperrow)
  164406. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164407. /* For now, precision must match compiled-in value... */
  164408. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164409. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164410. /* Check that number of components won't exceed internal array sizes */
  164411. if (cinfo->num_components > MAX_COMPONENTS)
  164412. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164413. MAX_COMPONENTS);
  164414. /* Compute maximum sampling factors; check factor validity */
  164415. cinfo->max_h_samp_factor = 1;
  164416. cinfo->max_v_samp_factor = 1;
  164417. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164418. ci++, compptr++) {
  164419. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164420. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164421. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164422. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164423. compptr->h_samp_factor);
  164424. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164425. compptr->v_samp_factor);
  164426. }
  164427. /* Compute dimensions of components */
  164428. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164429. ci++, compptr++) {
  164430. /* Fill in the correct component_index value; don't rely on application */
  164431. compptr->component_index = ci;
  164432. /* For compression, we never do DCT scaling. */
  164433. compptr->DCT_scaled_size = DCTSIZE;
  164434. /* Size in DCT blocks */
  164435. compptr->width_in_blocks = (JDIMENSION)
  164436. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164437. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164438. compptr->height_in_blocks = (JDIMENSION)
  164439. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164440. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164441. /* Size in samples */
  164442. compptr->downsampled_width = (JDIMENSION)
  164443. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164444. (long) cinfo->max_h_samp_factor);
  164445. compptr->downsampled_height = (JDIMENSION)
  164446. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164447. (long) cinfo->max_v_samp_factor);
  164448. /* Mark component needed (this flag isn't actually used for compression) */
  164449. compptr->component_needed = TRUE;
  164450. }
  164451. /* Compute number of fully interleaved MCU rows (number of times that
  164452. * main controller will call coefficient controller).
  164453. */
  164454. cinfo->total_iMCU_rows = (JDIMENSION)
  164455. jdiv_round_up((long) cinfo->image_height,
  164456. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164457. }
  164458. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164459. LOCAL(void)
  164460. validate_script (j_compress_ptr cinfo)
  164461. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164462. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164463. */
  164464. {
  164465. const jpeg_scan_info * scanptr;
  164466. int scanno, ncomps, ci, coefi, thisi;
  164467. int Ss, Se, Ah, Al;
  164468. boolean component_sent[MAX_COMPONENTS];
  164469. #ifdef C_PROGRESSIVE_SUPPORTED
  164470. int * last_bitpos_ptr;
  164471. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164472. /* -1 until that coefficient has been seen; then last Al for it */
  164473. #endif
  164474. if (cinfo->num_scans <= 0)
  164475. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164476. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164477. * for progressive JPEG, no scan can have this.
  164478. */
  164479. scanptr = cinfo->scan_info;
  164480. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164481. #ifdef C_PROGRESSIVE_SUPPORTED
  164482. cinfo->progressive_mode = TRUE;
  164483. last_bitpos_ptr = & last_bitpos[0][0];
  164484. for (ci = 0; ci < cinfo->num_components; ci++)
  164485. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164486. *last_bitpos_ptr++ = -1;
  164487. #else
  164488. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164489. #endif
  164490. } else {
  164491. cinfo->progressive_mode = FALSE;
  164492. for (ci = 0; ci < cinfo->num_components; ci++)
  164493. component_sent[ci] = FALSE;
  164494. }
  164495. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  164496. /* Validate component indexes */
  164497. ncomps = scanptr->comps_in_scan;
  164498. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  164499. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  164500. for (ci = 0; ci < ncomps; ci++) {
  164501. thisi = scanptr->component_index[ci];
  164502. if (thisi < 0 || thisi >= cinfo->num_components)
  164503. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164504. /* Components must appear in SOF order within each scan */
  164505. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  164506. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164507. }
  164508. /* Validate progression parameters */
  164509. Ss = scanptr->Ss;
  164510. Se = scanptr->Se;
  164511. Ah = scanptr->Ah;
  164512. Al = scanptr->Al;
  164513. if (cinfo->progressive_mode) {
  164514. #ifdef C_PROGRESSIVE_SUPPORTED
  164515. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  164516. * seems wrong: the upper bound ought to depend on data precision.
  164517. * Perhaps they really meant 0..N+1 for N-bit precision.
  164518. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  164519. * out-of-range reconstructed DC values during the first DC scan,
  164520. * which might cause problems for some decoders.
  164521. */
  164522. #if BITS_IN_JSAMPLE == 8
  164523. #define MAX_AH_AL 10
  164524. #else
  164525. #define MAX_AH_AL 13
  164526. #endif
  164527. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  164528. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  164529. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164530. if (Ss == 0) {
  164531. if (Se != 0) /* DC and AC together not OK */
  164532. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164533. } else {
  164534. if (ncomps != 1) /* AC scans must be for only one component */
  164535. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164536. }
  164537. for (ci = 0; ci < ncomps; ci++) {
  164538. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  164539. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  164540. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164541. for (coefi = Ss; coefi <= Se; coefi++) {
  164542. if (last_bitpos_ptr[coefi] < 0) {
  164543. /* first scan of this coefficient */
  164544. if (Ah != 0)
  164545. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164546. } else {
  164547. /* not first scan */
  164548. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  164549. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164550. }
  164551. last_bitpos_ptr[coefi] = Al;
  164552. }
  164553. }
  164554. #endif
  164555. } else {
  164556. /* For sequential JPEG, all progression parameters must be these: */
  164557. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  164558. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164559. /* Make sure components are not sent twice */
  164560. for (ci = 0; ci < ncomps; ci++) {
  164561. thisi = scanptr->component_index[ci];
  164562. if (component_sent[thisi])
  164563. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164564. component_sent[thisi] = TRUE;
  164565. }
  164566. }
  164567. }
  164568. /* Now verify that everything got sent. */
  164569. if (cinfo->progressive_mode) {
  164570. #ifdef C_PROGRESSIVE_SUPPORTED
  164571. /* For progressive mode, we only check that at least some DC data
  164572. * got sent for each component; the spec does not require that all bits
  164573. * of all coefficients be transmitted. Would it be wiser to enforce
  164574. * transmission of all coefficient bits??
  164575. */
  164576. for (ci = 0; ci < cinfo->num_components; ci++) {
  164577. if (last_bitpos[ci][0] < 0)
  164578. ERREXIT(cinfo, JERR_MISSING_DATA);
  164579. }
  164580. #endif
  164581. } else {
  164582. for (ci = 0; ci < cinfo->num_components; ci++) {
  164583. if (! component_sent[ci])
  164584. ERREXIT(cinfo, JERR_MISSING_DATA);
  164585. }
  164586. }
  164587. }
  164588. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  164589. LOCAL(void)
  164590. select_scan_parameters (j_compress_ptr cinfo)
  164591. /* Set up the scan parameters for the current scan */
  164592. {
  164593. int ci;
  164594. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164595. if (cinfo->scan_info != NULL) {
  164596. /* Prepare for current scan --- the script is already validated */
  164597. my_master_ptr master = (my_master_ptr) cinfo->master;
  164598. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  164599. cinfo->comps_in_scan = scanptr->comps_in_scan;
  164600. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  164601. cinfo->cur_comp_info[ci] =
  164602. &cinfo->comp_info[scanptr->component_index[ci]];
  164603. }
  164604. cinfo->Ss = scanptr->Ss;
  164605. cinfo->Se = scanptr->Se;
  164606. cinfo->Ah = scanptr->Ah;
  164607. cinfo->Al = scanptr->Al;
  164608. }
  164609. else
  164610. #endif
  164611. {
  164612. /* Prepare for single sequential-JPEG scan containing all components */
  164613. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  164614. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164615. MAX_COMPS_IN_SCAN);
  164616. cinfo->comps_in_scan = cinfo->num_components;
  164617. for (ci = 0; ci < cinfo->num_components; ci++) {
  164618. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  164619. }
  164620. cinfo->Ss = 0;
  164621. cinfo->Se = DCTSIZE2-1;
  164622. cinfo->Ah = 0;
  164623. cinfo->Al = 0;
  164624. }
  164625. }
  164626. LOCAL(void)
  164627. per_scan_setup (j_compress_ptr cinfo)
  164628. /* Do computations that are needed before processing a JPEG scan */
  164629. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  164630. {
  164631. int ci, mcublks, tmp;
  164632. jpeg_component_info *compptr;
  164633. if (cinfo->comps_in_scan == 1) {
  164634. /* Noninterleaved (single-component) scan */
  164635. compptr = cinfo->cur_comp_info[0];
  164636. /* Overall image size in MCUs */
  164637. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164638. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164639. /* For noninterleaved scan, always one block per MCU */
  164640. compptr->MCU_width = 1;
  164641. compptr->MCU_height = 1;
  164642. compptr->MCU_blocks = 1;
  164643. compptr->MCU_sample_width = DCTSIZE;
  164644. compptr->last_col_width = 1;
  164645. /* For noninterleaved scans, it is convenient to define last_row_height
  164646. * as the number of block rows present in the last iMCU row.
  164647. */
  164648. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164649. if (tmp == 0) tmp = compptr->v_samp_factor;
  164650. compptr->last_row_height = tmp;
  164651. /* Prepare array describing MCU composition */
  164652. cinfo->blocks_in_MCU = 1;
  164653. cinfo->MCU_membership[0] = 0;
  164654. } else {
  164655. /* Interleaved (multi-component) scan */
  164656. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  164657. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  164658. MAX_COMPS_IN_SCAN);
  164659. /* Overall image size in MCUs */
  164660. cinfo->MCUs_per_row = (JDIMENSION)
  164661. jdiv_round_up((long) cinfo->image_width,
  164662. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  164663. cinfo->MCU_rows_in_scan = (JDIMENSION)
  164664. jdiv_round_up((long) cinfo->image_height,
  164665. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164666. cinfo->blocks_in_MCU = 0;
  164667. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164668. compptr = cinfo->cur_comp_info[ci];
  164669. /* Sampling factors give # of blocks of component in each MCU */
  164670. compptr->MCU_width = compptr->h_samp_factor;
  164671. compptr->MCU_height = compptr->v_samp_factor;
  164672. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  164673. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  164674. /* Figure number of non-dummy blocks in last MCU column & row */
  164675. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  164676. if (tmp == 0) tmp = compptr->MCU_width;
  164677. compptr->last_col_width = tmp;
  164678. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  164679. if (tmp == 0) tmp = compptr->MCU_height;
  164680. compptr->last_row_height = tmp;
  164681. /* Prepare array describing MCU composition */
  164682. mcublks = compptr->MCU_blocks;
  164683. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  164684. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  164685. while (mcublks-- > 0) {
  164686. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  164687. }
  164688. }
  164689. }
  164690. /* Convert restart specified in rows to actual MCU count. */
  164691. /* Note that count must fit in 16 bits, so we provide limiting. */
  164692. if (cinfo->restart_in_rows > 0) {
  164693. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  164694. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  164695. }
  164696. }
  164697. /*
  164698. * Per-pass setup.
  164699. * This is called at the beginning of each pass. We determine which modules
  164700. * will be active during this pass and give them appropriate start_pass calls.
  164701. * We also set is_last_pass to indicate whether any more passes will be
  164702. * required.
  164703. */
  164704. METHODDEF(void)
  164705. prepare_for_pass (j_compress_ptr cinfo)
  164706. {
  164707. my_master_ptr master = (my_master_ptr) cinfo->master;
  164708. switch (master->pass_type) {
  164709. case main_pass:
  164710. /* Initial pass: will collect input data, and do either Huffman
  164711. * optimization or data output for the first scan.
  164712. */
  164713. select_scan_parameters(cinfo);
  164714. per_scan_setup(cinfo);
  164715. if (! cinfo->raw_data_in) {
  164716. (*cinfo->cconvert->start_pass) (cinfo);
  164717. (*cinfo->downsample->start_pass) (cinfo);
  164718. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  164719. }
  164720. (*cinfo->fdct->start_pass) (cinfo);
  164721. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  164722. (*cinfo->coef->start_pass) (cinfo,
  164723. (master->total_passes > 1 ?
  164724. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  164725. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  164726. if (cinfo->optimize_coding) {
  164727. /* No immediate data output; postpone writing frame/scan headers */
  164728. master->pub.call_pass_startup = FALSE;
  164729. } else {
  164730. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  164731. master->pub.call_pass_startup = TRUE;
  164732. }
  164733. break;
  164734. #ifdef ENTROPY_OPT_SUPPORTED
  164735. case huff_opt_pass:
  164736. /* Do Huffman optimization for a scan after the first one. */
  164737. select_scan_parameters(cinfo);
  164738. per_scan_setup(cinfo);
  164739. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  164740. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  164741. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164742. master->pub.call_pass_startup = FALSE;
  164743. break;
  164744. }
  164745. /* Special case: Huffman DC refinement scans need no Huffman table
  164746. * and therefore we can skip the optimization pass for them.
  164747. */
  164748. master->pass_type = output_pass;
  164749. master->pass_number++;
  164750. /*FALLTHROUGH*/
  164751. #endif
  164752. case output_pass:
  164753. /* Do a data-output pass. */
  164754. /* We need not repeat per-scan setup if prior optimization pass did it. */
  164755. if (! cinfo->optimize_coding) {
  164756. select_scan_parameters(cinfo);
  164757. per_scan_setup(cinfo);
  164758. }
  164759. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  164760. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164761. /* We emit frame/scan headers now */
  164762. if (master->scan_number == 0)
  164763. (*cinfo->marker->write_frame_header) (cinfo);
  164764. (*cinfo->marker->write_scan_header) (cinfo);
  164765. master->pub.call_pass_startup = FALSE;
  164766. break;
  164767. default:
  164768. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164769. }
  164770. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  164771. /* Set up progress monitor's pass info if present */
  164772. if (cinfo->progress != NULL) {
  164773. cinfo->progress->completed_passes = master->pass_number;
  164774. cinfo->progress->total_passes = master->total_passes;
  164775. }
  164776. }
  164777. /*
  164778. * Special start-of-pass hook.
  164779. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  164780. * In single-pass processing, we need this hook because we don't want to
  164781. * write frame/scan headers during jpeg_start_compress; we want to let the
  164782. * application write COM markers etc. between jpeg_start_compress and the
  164783. * jpeg_write_scanlines loop.
  164784. * In multi-pass processing, this routine is not used.
  164785. */
  164786. METHODDEF(void)
  164787. pass_startup (j_compress_ptr cinfo)
  164788. {
  164789. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  164790. (*cinfo->marker->write_frame_header) (cinfo);
  164791. (*cinfo->marker->write_scan_header) (cinfo);
  164792. }
  164793. /*
  164794. * Finish up at end of pass.
  164795. */
  164796. METHODDEF(void)
  164797. finish_pass_master (j_compress_ptr cinfo)
  164798. {
  164799. my_master_ptr master = (my_master_ptr) cinfo->master;
  164800. /* The entropy coder always needs an end-of-pass call,
  164801. * either to analyze statistics or to flush its output buffer.
  164802. */
  164803. (*cinfo->entropy->finish_pass) (cinfo);
  164804. /* Update state for next pass */
  164805. switch (master->pass_type) {
  164806. case main_pass:
  164807. /* next pass is either output of scan 0 (after optimization)
  164808. * or output of scan 1 (if no optimization).
  164809. */
  164810. master->pass_type = output_pass;
  164811. if (! cinfo->optimize_coding)
  164812. master->scan_number++;
  164813. break;
  164814. case huff_opt_pass:
  164815. /* next pass is always output of current scan */
  164816. master->pass_type = output_pass;
  164817. break;
  164818. case output_pass:
  164819. /* next pass is either optimization or output of next scan */
  164820. if (cinfo->optimize_coding)
  164821. master->pass_type = huff_opt_pass;
  164822. master->scan_number++;
  164823. break;
  164824. }
  164825. master->pass_number++;
  164826. }
  164827. /*
  164828. * Initialize master compression control.
  164829. */
  164830. GLOBAL(void)
  164831. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  164832. {
  164833. my_master_ptr master;
  164834. master = (my_master_ptr)
  164835. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164836. SIZEOF(my_comp_master));
  164837. cinfo->master = (struct jpeg_comp_master *) master;
  164838. master->pub.prepare_for_pass = prepare_for_pass;
  164839. master->pub.pass_startup = pass_startup;
  164840. master->pub.finish_pass = finish_pass_master;
  164841. master->pub.is_last_pass = FALSE;
  164842. /* Validate parameters, determine derived values */
  164843. initial_setup(cinfo);
  164844. if (cinfo->scan_info != NULL) {
  164845. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164846. validate_script(cinfo);
  164847. #else
  164848. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164849. #endif
  164850. } else {
  164851. cinfo->progressive_mode = FALSE;
  164852. cinfo->num_scans = 1;
  164853. }
  164854. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  164855. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  164856. /* Initialize my private state */
  164857. if (transcode_only) {
  164858. /* no main pass in transcoding */
  164859. if (cinfo->optimize_coding)
  164860. master->pass_type = huff_opt_pass;
  164861. else
  164862. master->pass_type = output_pass;
  164863. } else {
  164864. /* for normal compression, first pass is always this type: */
  164865. master->pass_type = main_pass;
  164866. }
  164867. master->scan_number = 0;
  164868. master->pass_number = 0;
  164869. if (cinfo->optimize_coding)
  164870. master->total_passes = cinfo->num_scans * 2;
  164871. else
  164872. master->total_passes = cinfo->num_scans;
  164873. }
  164874. /*** End of inlined file: jcmaster.c ***/
  164875. /*** Start of inlined file: jcomapi.c ***/
  164876. #define JPEG_INTERNALS
  164877. /*
  164878. * Abort processing of a JPEG compression or decompression operation,
  164879. * but don't destroy the object itself.
  164880. *
  164881. * For this, we merely clean up all the nonpermanent memory pools.
  164882. * Note that temp files (virtual arrays) are not allowed to belong to
  164883. * the permanent pool, so we will be able to close all temp files here.
  164884. * Closing a data source or destination, if necessary, is the application's
  164885. * responsibility.
  164886. */
  164887. GLOBAL(void)
  164888. jpeg_abort (j_common_ptr cinfo)
  164889. {
  164890. int pool;
  164891. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  164892. if (cinfo->mem == NULL)
  164893. return;
  164894. /* Releasing pools in reverse order might help avoid fragmentation
  164895. * with some (brain-damaged) malloc libraries.
  164896. */
  164897. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  164898. (*cinfo->mem->free_pool) (cinfo, pool);
  164899. }
  164900. /* Reset overall state for possible reuse of object */
  164901. if (cinfo->is_decompressor) {
  164902. cinfo->global_state = DSTATE_START;
  164903. /* Try to keep application from accessing now-deleted marker list.
  164904. * A bit kludgy to do it here, but this is the most central place.
  164905. */
  164906. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  164907. } else {
  164908. cinfo->global_state = CSTATE_START;
  164909. }
  164910. }
  164911. /*
  164912. * Destruction of a JPEG object.
  164913. *
  164914. * Everything gets deallocated except the master jpeg_compress_struct itself
  164915. * and the error manager struct. Both of these are supplied by the application
  164916. * and must be freed, if necessary, by the application. (Often they are on
  164917. * the stack and so don't need to be freed anyway.)
  164918. * Closing a data source or destination, if necessary, is the application's
  164919. * responsibility.
  164920. */
  164921. GLOBAL(void)
  164922. jpeg_destroy (j_common_ptr cinfo)
  164923. {
  164924. /* We need only tell the memory manager to release everything. */
  164925. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  164926. if (cinfo->mem != NULL)
  164927. (*cinfo->mem->self_destruct) (cinfo);
  164928. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  164929. cinfo->global_state = 0; /* mark it destroyed */
  164930. }
  164931. /*
  164932. * Convenience routines for allocating quantization and Huffman tables.
  164933. * (Would jutils.c be a more reasonable place to put these?)
  164934. */
  164935. GLOBAL(JQUANT_TBL *)
  164936. jpeg_alloc_quant_table (j_common_ptr cinfo)
  164937. {
  164938. JQUANT_TBL *tbl;
  164939. tbl = (JQUANT_TBL *)
  164940. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  164941. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164942. return tbl;
  164943. }
  164944. GLOBAL(JHUFF_TBL *)
  164945. jpeg_alloc_huff_table (j_common_ptr cinfo)
  164946. {
  164947. JHUFF_TBL *tbl;
  164948. tbl = (JHUFF_TBL *)
  164949. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  164950. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164951. return tbl;
  164952. }
  164953. /*** End of inlined file: jcomapi.c ***/
  164954. /*** Start of inlined file: jcparam.c ***/
  164955. #define JPEG_INTERNALS
  164956. /*
  164957. * Quantization table setup routines
  164958. */
  164959. GLOBAL(void)
  164960. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  164961. const unsigned int *basic_table,
  164962. int scale_factor, boolean force_baseline)
  164963. /* Define a quantization table equal to the basic_table times
  164964. * a scale factor (given as a percentage).
  164965. * If force_baseline is TRUE, the computed quantization table entries
  164966. * are limited to 1..255 for JPEG baseline compatibility.
  164967. */
  164968. {
  164969. JQUANT_TBL ** qtblptr;
  164970. int i;
  164971. long temp;
  164972. /* Safety check to ensure start_compress not called yet. */
  164973. if (cinfo->global_state != CSTATE_START)
  164974. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164975. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  164976. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  164977. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  164978. if (*qtblptr == NULL)
  164979. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  164980. for (i = 0; i < DCTSIZE2; i++) {
  164981. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  164982. /* limit the values to the valid range */
  164983. if (temp <= 0L) temp = 1L;
  164984. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  164985. if (force_baseline && temp > 255L)
  164986. temp = 255L; /* limit to baseline range if requested */
  164987. (*qtblptr)->quantval[i] = (UINT16) temp;
  164988. }
  164989. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  164990. (*qtblptr)->sent_table = FALSE;
  164991. }
  164992. GLOBAL(void)
  164993. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  164994. boolean force_baseline)
  164995. /* Set or change the 'quality' (quantization) setting, using default tables
  164996. * and a straight percentage-scaling quality scale. In most cases it's better
  164997. * to use jpeg_set_quality (below); this entry point is provided for
  164998. * applications that insist on a linear percentage scaling.
  164999. */
  165000. {
  165001. /* These are the sample quantization tables given in JPEG spec section K.1.
  165002. * The spec says that the values given produce "good" quality, and
  165003. * when divided by 2, "very good" quality.
  165004. */
  165005. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  165006. 16, 11, 10, 16, 24, 40, 51, 61,
  165007. 12, 12, 14, 19, 26, 58, 60, 55,
  165008. 14, 13, 16, 24, 40, 57, 69, 56,
  165009. 14, 17, 22, 29, 51, 87, 80, 62,
  165010. 18, 22, 37, 56, 68, 109, 103, 77,
  165011. 24, 35, 55, 64, 81, 104, 113, 92,
  165012. 49, 64, 78, 87, 103, 121, 120, 101,
  165013. 72, 92, 95, 98, 112, 100, 103, 99
  165014. };
  165015. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  165016. 17, 18, 24, 47, 99, 99, 99, 99,
  165017. 18, 21, 26, 66, 99, 99, 99, 99,
  165018. 24, 26, 56, 99, 99, 99, 99, 99,
  165019. 47, 66, 99, 99, 99, 99, 99, 99,
  165020. 99, 99, 99, 99, 99, 99, 99, 99,
  165021. 99, 99, 99, 99, 99, 99, 99, 99,
  165022. 99, 99, 99, 99, 99, 99, 99, 99,
  165023. 99, 99, 99, 99, 99, 99, 99, 99
  165024. };
  165025. /* Set up two quantization tables using the specified scaling */
  165026. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165027. scale_factor, force_baseline);
  165028. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165029. scale_factor, force_baseline);
  165030. }
  165031. GLOBAL(int)
  165032. jpeg_quality_scaling (int quality)
  165033. /* Convert a user-specified quality rating to a percentage scaling factor
  165034. * for an underlying quantization table, using our recommended scaling curve.
  165035. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165036. */
  165037. {
  165038. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165039. if (quality <= 0) quality = 1;
  165040. if (quality > 100) quality = 100;
  165041. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165042. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165043. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165044. * to make all the table entries 1 (hence, minimum quantization loss).
  165045. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165046. */
  165047. if (quality < 50)
  165048. quality = 5000 / quality;
  165049. else
  165050. quality = 200 - quality*2;
  165051. return quality;
  165052. }
  165053. GLOBAL(void)
  165054. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165055. /* Set or change the 'quality' (quantization) setting, using default tables.
  165056. * This is the standard quality-adjusting entry point for typical user
  165057. * interfaces; only those who want detailed control over quantization tables
  165058. * would use the preceding three routines directly.
  165059. */
  165060. {
  165061. /* Convert user 0-100 rating to percentage scaling */
  165062. quality = jpeg_quality_scaling(quality);
  165063. /* Set up standard quality tables */
  165064. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165065. }
  165066. /*
  165067. * Huffman table setup routines
  165068. */
  165069. LOCAL(void)
  165070. add_huff_table (j_compress_ptr cinfo,
  165071. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165072. /* Define a Huffman table */
  165073. {
  165074. int nsymbols, len;
  165075. if (*htblptr == NULL)
  165076. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165077. /* Copy the number-of-symbols-of-each-code-length counts */
  165078. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165079. /* Validate the counts. We do this here mainly so we can copy the right
  165080. * number of symbols from the val[] array, without risking marching off
  165081. * the end of memory. jchuff.c will do a more thorough test later.
  165082. */
  165083. nsymbols = 0;
  165084. for (len = 1; len <= 16; len++)
  165085. nsymbols += bits[len];
  165086. if (nsymbols < 1 || nsymbols > 256)
  165087. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165088. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165089. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165090. (*htblptr)->sent_table = FALSE;
  165091. }
  165092. LOCAL(void)
  165093. std_huff_tables (j_compress_ptr cinfo)
  165094. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165095. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165096. {
  165097. static const UINT8 bits_dc_luminance[17] =
  165098. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165099. static const UINT8 val_dc_luminance[] =
  165100. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165101. static const UINT8 bits_dc_chrominance[17] =
  165102. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165103. static const UINT8 val_dc_chrominance[] =
  165104. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165105. static const UINT8 bits_ac_luminance[17] =
  165106. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165107. static const UINT8 val_ac_luminance[] =
  165108. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165109. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165110. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165111. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165112. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165113. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165114. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165115. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165116. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165117. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165118. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165119. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165120. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165121. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165122. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165123. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165124. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165125. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165126. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165127. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165128. 0xf9, 0xfa };
  165129. static const UINT8 bits_ac_chrominance[17] =
  165130. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165131. static const UINT8 val_ac_chrominance[] =
  165132. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165133. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165134. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165135. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165136. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165137. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165138. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165139. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165140. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165141. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165142. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165143. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165144. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165145. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165146. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165147. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165148. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165149. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165150. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165151. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165152. 0xf9, 0xfa };
  165153. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165154. bits_dc_luminance, val_dc_luminance);
  165155. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165156. bits_ac_luminance, val_ac_luminance);
  165157. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165158. bits_dc_chrominance, val_dc_chrominance);
  165159. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165160. bits_ac_chrominance, val_ac_chrominance);
  165161. }
  165162. /*
  165163. * Default parameter setup for compression.
  165164. *
  165165. * Applications that don't choose to use this routine must do their
  165166. * own setup of all these parameters. Alternately, you can call this
  165167. * to establish defaults and then alter parameters selectively. This
  165168. * is the recommended approach since, if we add any new parameters,
  165169. * your code will still work (they'll be set to reasonable defaults).
  165170. */
  165171. GLOBAL(void)
  165172. jpeg_set_defaults (j_compress_ptr cinfo)
  165173. {
  165174. int i;
  165175. /* Safety check to ensure start_compress not called yet. */
  165176. if (cinfo->global_state != CSTATE_START)
  165177. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165178. /* Allocate comp_info array large enough for maximum component count.
  165179. * Array is made permanent in case application wants to compress
  165180. * multiple images at same param settings.
  165181. */
  165182. if (cinfo->comp_info == NULL)
  165183. cinfo->comp_info = (jpeg_component_info *)
  165184. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165185. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165186. /* Initialize everything not dependent on the color space */
  165187. cinfo->data_precision = BITS_IN_JSAMPLE;
  165188. /* Set up two quantization tables using default quality of 75 */
  165189. jpeg_set_quality(cinfo, 75, TRUE);
  165190. /* Set up two Huffman tables */
  165191. std_huff_tables(cinfo);
  165192. /* Initialize default arithmetic coding conditioning */
  165193. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165194. cinfo->arith_dc_L[i] = 0;
  165195. cinfo->arith_dc_U[i] = 1;
  165196. cinfo->arith_ac_K[i] = 5;
  165197. }
  165198. /* Default is no multiple-scan output */
  165199. cinfo->scan_info = NULL;
  165200. cinfo->num_scans = 0;
  165201. /* Expect normal source image, not raw downsampled data */
  165202. cinfo->raw_data_in = FALSE;
  165203. /* Use Huffman coding, not arithmetic coding, by default */
  165204. cinfo->arith_code = FALSE;
  165205. /* By default, don't do extra passes to optimize entropy coding */
  165206. cinfo->optimize_coding = FALSE;
  165207. /* The standard Huffman tables are only valid for 8-bit data precision.
  165208. * If the precision is higher, force optimization on so that usable
  165209. * tables will be computed. This test can be removed if default tables
  165210. * are supplied that are valid for the desired precision.
  165211. */
  165212. if (cinfo->data_precision > 8)
  165213. cinfo->optimize_coding = TRUE;
  165214. /* By default, use the simpler non-cosited sampling alignment */
  165215. cinfo->CCIR601_sampling = FALSE;
  165216. /* No input smoothing */
  165217. cinfo->smoothing_factor = 0;
  165218. /* DCT algorithm preference */
  165219. cinfo->dct_method = JDCT_DEFAULT;
  165220. /* No restart markers */
  165221. cinfo->restart_interval = 0;
  165222. cinfo->restart_in_rows = 0;
  165223. /* Fill in default JFIF marker parameters. Note that whether the marker
  165224. * will actually be written is determined by jpeg_set_colorspace.
  165225. *
  165226. * By default, the library emits JFIF version code 1.01.
  165227. * An application that wants to emit JFIF 1.02 extension markers should set
  165228. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165229. * to 1.02, but there may still be some decoders in use that will complain
  165230. * about that; saying 1.01 should minimize compatibility problems.
  165231. */
  165232. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165233. cinfo->JFIF_minor_version = 1;
  165234. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165235. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165236. cinfo->Y_density = 1;
  165237. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165238. jpeg_default_colorspace(cinfo);
  165239. }
  165240. /*
  165241. * Select an appropriate JPEG colorspace for in_color_space.
  165242. */
  165243. GLOBAL(void)
  165244. jpeg_default_colorspace (j_compress_ptr cinfo)
  165245. {
  165246. switch (cinfo->in_color_space) {
  165247. case JCS_GRAYSCALE:
  165248. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165249. break;
  165250. case JCS_RGB:
  165251. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165252. break;
  165253. case JCS_YCbCr:
  165254. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165255. break;
  165256. case JCS_CMYK:
  165257. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165258. break;
  165259. case JCS_YCCK:
  165260. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165261. break;
  165262. case JCS_UNKNOWN:
  165263. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165264. break;
  165265. default:
  165266. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165267. }
  165268. }
  165269. /*
  165270. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165271. */
  165272. GLOBAL(void)
  165273. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165274. {
  165275. jpeg_component_info * compptr;
  165276. int ci;
  165277. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165278. (compptr = &cinfo->comp_info[index], \
  165279. compptr->component_id = (id), \
  165280. compptr->h_samp_factor = (hsamp), \
  165281. compptr->v_samp_factor = (vsamp), \
  165282. compptr->quant_tbl_no = (quant), \
  165283. compptr->dc_tbl_no = (dctbl), \
  165284. compptr->ac_tbl_no = (actbl) )
  165285. /* Safety check to ensure start_compress not called yet. */
  165286. if (cinfo->global_state != CSTATE_START)
  165287. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165288. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165289. * tables 1 for chrominance components.
  165290. */
  165291. cinfo->jpeg_color_space = colorspace;
  165292. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165293. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165294. switch (colorspace) {
  165295. case JCS_GRAYSCALE:
  165296. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165297. cinfo->num_components = 1;
  165298. /* JFIF specifies component ID 1 */
  165299. SET_COMP(0, 1, 1,1, 0, 0,0);
  165300. break;
  165301. case JCS_RGB:
  165302. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165303. cinfo->num_components = 3;
  165304. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165305. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165306. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165307. break;
  165308. case JCS_YCbCr:
  165309. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165310. cinfo->num_components = 3;
  165311. /* JFIF specifies component IDs 1,2,3 */
  165312. /* We default to 2x2 subsamples of chrominance */
  165313. SET_COMP(0, 1, 2,2, 0, 0,0);
  165314. SET_COMP(1, 2, 1,1, 1, 1,1);
  165315. SET_COMP(2, 3, 1,1, 1, 1,1);
  165316. break;
  165317. case JCS_CMYK:
  165318. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165319. cinfo->num_components = 4;
  165320. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165321. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165322. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165323. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165324. break;
  165325. case JCS_YCCK:
  165326. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165327. cinfo->num_components = 4;
  165328. SET_COMP(0, 1, 2,2, 0, 0,0);
  165329. SET_COMP(1, 2, 1,1, 1, 1,1);
  165330. SET_COMP(2, 3, 1,1, 1, 1,1);
  165331. SET_COMP(3, 4, 2,2, 0, 0,0);
  165332. break;
  165333. case JCS_UNKNOWN:
  165334. cinfo->num_components = cinfo->input_components;
  165335. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165336. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165337. MAX_COMPONENTS);
  165338. for (ci = 0; ci < cinfo->num_components; ci++) {
  165339. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165340. }
  165341. break;
  165342. default:
  165343. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165344. }
  165345. }
  165346. #ifdef C_PROGRESSIVE_SUPPORTED
  165347. LOCAL(jpeg_scan_info *)
  165348. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165349. int Ss, int Se, int Ah, int Al)
  165350. /* Support routine: generate one scan for specified component */
  165351. {
  165352. scanptr->comps_in_scan = 1;
  165353. scanptr->component_index[0] = ci;
  165354. scanptr->Ss = Ss;
  165355. scanptr->Se = Se;
  165356. scanptr->Ah = Ah;
  165357. scanptr->Al = Al;
  165358. scanptr++;
  165359. return scanptr;
  165360. }
  165361. LOCAL(jpeg_scan_info *)
  165362. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165363. int Ss, int Se, int Ah, int Al)
  165364. /* Support routine: generate one scan for each component */
  165365. {
  165366. int ci;
  165367. for (ci = 0; ci < ncomps; ci++) {
  165368. scanptr->comps_in_scan = 1;
  165369. scanptr->component_index[0] = ci;
  165370. scanptr->Ss = Ss;
  165371. scanptr->Se = Se;
  165372. scanptr->Ah = Ah;
  165373. scanptr->Al = Al;
  165374. scanptr++;
  165375. }
  165376. return scanptr;
  165377. }
  165378. LOCAL(jpeg_scan_info *)
  165379. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165380. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165381. {
  165382. int ci;
  165383. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165384. /* Single interleaved DC scan */
  165385. scanptr->comps_in_scan = ncomps;
  165386. for (ci = 0; ci < ncomps; ci++)
  165387. scanptr->component_index[ci] = ci;
  165388. scanptr->Ss = scanptr->Se = 0;
  165389. scanptr->Ah = Ah;
  165390. scanptr->Al = Al;
  165391. scanptr++;
  165392. } else {
  165393. /* Noninterleaved DC scan for each component */
  165394. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165395. }
  165396. return scanptr;
  165397. }
  165398. /*
  165399. * Create a recommended progressive-JPEG script.
  165400. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165401. */
  165402. GLOBAL(void)
  165403. jpeg_simple_progression (j_compress_ptr cinfo)
  165404. {
  165405. int ncomps = cinfo->num_components;
  165406. int nscans;
  165407. jpeg_scan_info * scanptr;
  165408. /* Safety check to ensure start_compress not called yet. */
  165409. if (cinfo->global_state != CSTATE_START)
  165410. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165411. /* Figure space needed for script. Calculation must match code below! */
  165412. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165413. /* Custom script for YCbCr color images. */
  165414. nscans = 10;
  165415. } else {
  165416. /* All-purpose script for other color spaces. */
  165417. if (ncomps > MAX_COMPS_IN_SCAN)
  165418. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165419. else
  165420. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165421. }
  165422. /* Allocate space for script.
  165423. * We need to put it in the permanent pool in case the application performs
  165424. * multiple compressions without changing the settings. To avoid a memory
  165425. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165426. * object, we try to re-use previously allocated space, and we allocate
  165427. * enough space to handle YCbCr even if initially asked for grayscale.
  165428. */
  165429. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165430. cinfo->script_space_size = MAX(nscans, 10);
  165431. cinfo->script_space = (jpeg_scan_info *)
  165432. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165433. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165434. }
  165435. scanptr = cinfo->script_space;
  165436. cinfo->scan_info = scanptr;
  165437. cinfo->num_scans = nscans;
  165438. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165439. /* Custom script for YCbCr color images. */
  165440. /* Initial DC scan */
  165441. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165442. /* Initial AC scan: get some luma data out in a hurry */
  165443. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165444. /* Chroma data is too small to be worth expending many scans on */
  165445. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165446. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165447. /* Complete spectral selection for luma AC */
  165448. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165449. /* Refine next bit of luma AC */
  165450. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165451. /* Finish DC successive approximation */
  165452. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165453. /* Finish AC successive approximation */
  165454. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165455. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165456. /* Luma bottom bit comes last since it's usually largest scan */
  165457. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165458. } else {
  165459. /* All-purpose script for other color spaces. */
  165460. /* Successive approximation first pass */
  165461. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165462. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165463. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165464. /* Successive approximation second pass */
  165465. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165466. /* Successive approximation final pass */
  165467. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165468. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165469. }
  165470. }
  165471. #endif /* C_PROGRESSIVE_SUPPORTED */
  165472. /*** End of inlined file: jcparam.c ***/
  165473. /*** Start of inlined file: jcphuff.c ***/
  165474. #define JPEG_INTERNALS
  165475. #ifdef C_PROGRESSIVE_SUPPORTED
  165476. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165477. typedef struct {
  165478. struct jpeg_entropy_encoder pub; /* public fields */
  165479. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165480. boolean gather_statistics;
  165481. /* Bit-level coding status.
  165482. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165483. */
  165484. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165485. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165486. INT32 put_buffer; /* current bit-accumulation buffer */
  165487. int put_bits; /* # of bits now in it */
  165488. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  165489. /* Coding status for DC components */
  165490. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165491. /* Coding status for AC components */
  165492. int ac_tbl_no; /* the table number of the single component */
  165493. unsigned int EOBRUN; /* run length of EOBs */
  165494. unsigned int BE; /* # of buffered correction bits before MCU */
  165495. char * bit_buffer; /* buffer for correction bits (1 per char) */
  165496. /* packing correction bits tightly would save some space but cost time... */
  165497. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165498. int next_restart_num; /* next restart number to write (0-7) */
  165499. /* Pointers to derived tables (these workspaces have image lifespan).
  165500. * Since any one scan codes only DC or only AC, we only need one set
  165501. * of tables, not one for DC and one for AC.
  165502. */
  165503. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  165504. /* Statistics tables for optimization; again, one set is enough */
  165505. long * count_ptrs[NUM_HUFF_TBLS];
  165506. } phuff_entropy_encoder;
  165507. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  165508. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  165509. * buffer can hold. Larger sizes may slightly improve compression, but
  165510. * 1000 is already well into the realm of overkill.
  165511. * The minimum safe size is 64 bits.
  165512. */
  165513. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  165514. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  165515. * We assume that int right shift is unsigned if INT32 right shift is,
  165516. * which should be safe.
  165517. */
  165518. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  165519. #define ISHIFT_TEMPS int ishift_temp;
  165520. #define IRIGHT_SHIFT(x,shft) \
  165521. ((ishift_temp = (x)) < 0 ? \
  165522. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  165523. (ishift_temp >> (shft)))
  165524. #else
  165525. #define ISHIFT_TEMPS
  165526. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  165527. #endif
  165528. /* Forward declarations */
  165529. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  165530. JBLOCKROW *MCU_data));
  165531. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  165532. JBLOCKROW *MCU_data));
  165533. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  165534. JBLOCKROW *MCU_data));
  165535. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  165536. JBLOCKROW *MCU_data));
  165537. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  165538. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  165539. /*
  165540. * Initialize for a Huffman-compressed scan using progressive JPEG.
  165541. */
  165542. METHODDEF(void)
  165543. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  165544. {
  165545. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165546. boolean is_DC_band;
  165547. int ci, tbl;
  165548. jpeg_component_info * compptr;
  165549. entropy->cinfo = cinfo;
  165550. entropy->gather_statistics = gather_statistics;
  165551. is_DC_band = (cinfo->Ss == 0);
  165552. /* We assume jcmaster.c already validated the scan parameters. */
  165553. /* Select execution routines */
  165554. if (cinfo->Ah == 0) {
  165555. if (is_DC_band)
  165556. entropy->pub.encode_mcu = encode_mcu_DC_first;
  165557. else
  165558. entropy->pub.encode_mcu = encode_mcu_AC_first;
  165559. } else {
  165560. if (is_DC_band)
  165561. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  165562. else {
  165563. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  165564. /* AC refinement needs a correction bit buffer */
  165565. if (entropy->bit_buffer == NULL)
  165566. entropy->bit_buffer = (char *)
  165567. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165568. MAX_CORR_BITS * SIZEOF(char));
  165569. }
  165570. }
  165571. if (gather_statistics)
  165572. entropy->pub.finish_pass = finish_pass_gather_phuff;
  165573. else
  165574. entropy->pub.finish_pass = finish_pass_phuff;
  165575. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  165576. * for AC coefficients.
  165577. */
  165578. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165579. compptr = cinfo->cur_comp_info[ci];
  165580. /* Initialize DC predictions to 0 */
  165581. entropy->last_dc_val[ci] = 0;
  165582. /* Get table index */
  165583. if (is_DC_band) {
  165584. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165585. continue;
  165586. tbl = compptr->dc_tbl_no;
  165587. } else {
  165588. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  165589. }
  165590. if (gather_statistics) {
  165591. /* Check for invalid table index */
  165592. /* (make_c_derived_tbl does this in the other path) */
  165593. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  165594. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  165595. /* Allocate and zero the statistics tables */
  165596. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  165597. if (entropy->count_ptrs[tbl] == NULL)
  165598. entropy->count_ptrs[tbl] = (long *)
  165599. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165600. 257 * SIZEOF(long));
  165601. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  165602. } else {
  165603. /* Compute derived values for Huffman table */
  165604. /* We may do this more than once for a table, but it's not expensive */
  165605. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  165606. & entropy->derived_tbls[tbl]);
  165607. }
  165608. }
  165609. /* Initialize AC stuff */
  165610. entropy->EOBRUN = 0;
  165611. entropy->BE = 0;
  165612. /* Initialize bit buffer to empty */
  165613. entropy->put_buffer = 0;
  165614. entropy->put_bits = 0;
  165615. /* Initialize restart stuff */
  165616. entropy->restarts_to_go = cinfo->restart_interval;
  165617. entropy->next_restart_num = 0;
  165618. }
  165619. /* Outputting bytes to the file.
  165620. * NB: these must be called only when actually outputting,
  165621. * that is, entropy->gather_statistics == FALSE.
  165622. */
  165623. /* Emit a byte */
  165624. #define emit_byte(entropy,val) \
  165625. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  165626. if (--(entropy)->free_in_buffer == 0) \
  165627. dump_buffer_p(entropy); }
  165628. LOCAL(void)
  165629. dump_buffer_p (phuff_entropy_ptr entropy)
  165630. /* Empty the output buffer; we do not support suspension in this module. */
  165631. {
  165632. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  165633. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  165634. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  165635. /* After a successful buffer dump, must reset buffer pointers */
  165636. entropy->next_output_byte = dest->next_output_byte;
  165637. entropy->free_in_buffer = dest->free_in_buffer;
  165638. }
  165639. /* Outputting bits to the file */
  165640. /* Only the right 24 bits of put_buffer are used; the valid bits are
  165641. * left-justified in this part. At most 16 bits can be passed to emit_bits
  165642. * in one call, and we never retain more than 7 bits in put_buffer
  165643. * between calls, so 24 bits are sufficient.
  165644. */
  165645. INLINE
  165646. LOCAL(void)
  165647. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  165648. /* Emit some bits, unless we are in gather mode */
  165649. {
  165650. /* This routine is heavily used, so it's worth coding tightly. */
  165651. register INT32 put_buffer = (INT32) code;
  165652. register int put_bits = entropy->put_bits;
  165653. /* if size is 0, caller used an invalid Huffman table entry */
  165654. if (size == 0)
  165655. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165656. if (entropy->gather_statistics)
  165657. return; /* do nothing if we're only getting stats */
  165658. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  165659. put_bits += size; /* new number of bits in buffer */
  165660. put_buffer <<= 24 - put_bits; /* align incoming bits */
  165661. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  165662. while (put_bits >= 8) {
  165663. int c = (int) ((put_buffer >> 16) & 0xFF);
  165664. emit_byte(entropy, c);
  165665. if (c == 0xFF) { /* need to stuff a zero byte? */
  165666. emit_byte(entropy, 0);
  165667. }
  165668. put_buffer <<= 8;
  165669. put_bits -= 8;
  165670. }
  165671. entropy->put_buffer = put_buffer; /* update variables */
  165672. entropy->put_bits = put_bits;
  165673. }
  165674. LOCAL(void)
  165675. flush_bits_p (phuff_entropy_ptr entropy)
  165676. {
  165677. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  165678. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  165679. entropy->put_bits = 0;
  165680. }
  165681. /*
  165682. * Emit (or just count) a Huffman symbol.
  165683. */
  165684. INLINE
  165685. LOCAL(void)
  165686. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  165687. {
  165688. if (entropy->gather_statistics)
  165689. entropy->count_ptrs[tbl_no][symbol]++;
  165690. else {
  165691. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  165692. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  165693. }
  165694. }
  165695. /*
  165696. * Emit bits from a correction bit buffer.
  165697. */
  165698. LOCAL(void)
  165699. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  165700. unsigned int nbits)
  165701. {
  165702. if (entropy->gather_statistics)
  165703. return; /* no real work */
  165704. while (nbits > 0) {
  165705. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  165706. bufstart++;
  165707. nbits--;
  165708. }
  165709. }
  165710. /*
  165711. * Emit any pending EOBRUN symbol.
  165712. */
  165713. LOCAL(void)
  165714. emit_eobrun (phuff_entropy_ptr entropy)
  165715. {
  165716. register int temp, nbits;
  165717. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  165718. temp = entropy->EOBRUN;
  165719. nbits = 0;
  165720. while ((temp >>= 1))
  165721. nbits++;
  165722. /* safety check: shouldn't happen given limited correction-bit buffer */
  165723. if (nbits > 14)
  165724. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165725. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  165726. if (nbits)
  165727. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  165728. entropy->EOBRUN = 0;
  165729. /* Emit any buffered correction bits */
  165730. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  165731. entropy->BE = 0;
  165732. }
  165733. }
  165734. /*
  165735. * Emit a restart marker & resynchronize predictions.
  165736. */
  165737. LOCAL(void)
  165738. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  165739. {
  165740. int ci;
  165741. emit_eobrun(entropy);
  165742. if (! entropy->gather_statistics) {
  165743. flush_bits_p(entropy);
  165744. emit_byte(entropy, 0xFF);
  165745. emit_byte(entropy, JPEG_RST0 + restart_num);
  165746. }
  165747. if (entropy->cinfo->Ss == 0) {
  165748. /* Re-initialize DC predictions to 0 */
  165749. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  165750. entropy->last_dc_val[ci] = 0;
  165751. } else {
  165752. /* Re-initialize all AC-related fields to 0 */
  165753. entropy->EOBRUN = 0;
  165754. entropy->BE = 0;
  165755. }
  165756. }
  165757. /*
  165758. * MCU encoding for DC initial scan (either spectral selection,
  165759. * or first pass of successive approximation).
  165760. */
  165761. METHODDEF(boolean)
  165762. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165763. {
  165764. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165765. register int temp, temp2;
  165766. register int nbits;
  165767. int blkn, ci;
  165768. int Al = cinfo->Al;
  165769. JBLOCKROW block;
  165770. jpeg_component_info * compptr;
  165771. ISHIFT_TEMPS
  165772. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165773. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165774. /* Emit restart marker if needed */
  165775. if (cinfo->restart_interval)
  165776. if (entropy->restarts_to_go == 0)
  165777. emit_restart_p(entropy, entropy->next_restart_num);
  165778. /* Encode the MCU data blocks */
  165779. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165780. block = MCU_data[blkn];
  165781. ci = cinfo->MCU_membership[blkn];
  165782. compptr = cinfo->cur_comp_info[ci];
  165783. /* Compute the DC value after the required point transform by Al.
  165784. * This is simply an arithmetic right shift.
  165785. */
  165786. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  165787. /* DC differences are figured on the point-transformed values. */
  165788. temp = temp2 - entropy->last_dc_val[ci];
  165789. entropy->last_dc_val[ci] = temp2;
  165790. /* Encode the DC coefficient difference per section G.1.2.1 */
  165791. temp2 = temp;
  165792. if (temp < 0) {
  165793. temp = -temp; /* temp is abs value of input */
  165794. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  165795. /* This code assumes we are on a two's complement machine */
  165796. temp2--;
  165797. }
  165798. /* Find the number of bits needed for the magnitude of the coefficient */
  165799. nbits = 0;
  165800. while (temp) {
  165801. nbits++;
  165802. temp >>= 1;
  165803. }
  165804. /* Check for out-of-range coefficient values.
  165805. * Since we're encoding a difference, the range limit is twice as much.
  165806. */
  165807. if (nbits > MAX_COEF_BITS+1)
  165808. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165809. /* Count/emit the Huffman-coded symbol for the number of bits */
  165810. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  165811. /* Emit that number of bits of the value, if positive, */
  165812. /* or the complement of its magnitude, if negative. */
  165813. if (nbits) /* emit_bits rejects calls with size 0 */
  165814. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165815. }
  165816. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165817. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165818. /* Update restart-interval state too */
  165819. if (cinfo->restart_interval) {
  165820. if (entropy->restarts_to_go == 0) {
  165821. entropy->restarts_to_go = cinfo->restart_interval;
  165822. entropy->next_restart_num++;
  165823. entropy->next_restart_num &= 7;
  165824. }
  165825. entropy->restarts_to_go--;
  165826. }
  165827. return TRUE;
  165828. }
  165829. /*
  165830. * MCU encoding for AC initial scan (either spectral selection,
  165831. * or first pass of successive approximation).
  165832. */
  165833. METHODDEF(boolean)
  165834. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165835. {
  165836. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165837. register int temp, temp2;
  165838. register int nbits;
  165839. register int r, k;
  165840. int Se = cinfo->Se;
  165841. int Al = cinfo->Al;
  165842. JBLOCKROW block;
  165843. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165844. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165845. /* Emit restart marker if needed */
  165846. if (cinfo->restart_interval)
  165847. if (entropy->restarts_to_go == 0)
  165848. emit_restart_p(entropy, entropy->next_restart_num);
  165849. /* Encode the MCU data block */
  165850. block = MCU_data[0];
  165851. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  165852. r = 0; /* r = run length of zeros */
  165853. for (k = cinfo->Ss; k <= Se; k++) {
  165854. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  165855. r++;
  165856. continue;
  165857. }
  165858. /* We must apply the point transform by Al. For AC coefficients this
  165859. * is an integer division with rounding towards 0. To do this portably
  165860. * in C, we shift after obtaining the absolute value; so the code is
  165861. * interwoven with finding the abs value (temp) and output bits (temp2).
  165862. */
  165863. if (temp < 0) {
  165864. temp = -temp; /* temp is abs value of input */
  165865. temp >>= Al; /* apply the point transform */
  165866. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  165867. temp2 = ~temp;
  165868. } else {
  165869. temp >>= Al; /* apply the point transform */
  165870. temp2 = temp;
  165871. }
  165872. /* Watch out for case that nonzero coef is zero after point transform */
  165873. if (temp == 0) {
  165874. r++;
  165875. continue;
  165876. }
  165877. /* Emit any pending EOBRUN */
  165878. if (entropy->EOBRUN > 0)
  165879. emit_eobrun(entropy);
  165880. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  165881. while (r > 15) {
  165882. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165883. r -= 16;
  165884. }
  165885. /* Find the number of bits needed for the magnitude of the coefficient */
  165886. nbits = 1; /* there must be at least one 1 bit */
  165887. while ((temp >>= 1))
  165888. nbits++;
  165889. /* Check for out-of-range coefficient values */
  165890. if (nbits > MAX_COEF_BITS)
  165891. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165892. /* Count/emit Huffman symbol for run length / number of bits */
  165893. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  165894. /* Emit that number of bits of the value, if positive, */
  165895. /* or the complement of its magnitude, if negative. */
  165896. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165897. r = 0; /* reset zero run length */
  165898. }
  165899. if (r > 0) { /* If there are trailing zeroes, */
  165900. entropy->EOBRUN++; /* count an EOB */
  165901. if (entropy->EOBRUN == 0x7FFF)
  165902. emit_eobrun(entropy); /* force it out to avoid overflow */
  165903. }
  165904. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165905. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165906. /* Update restart-interval state too */
  165907. if (cinfo->restart_interval) {
  165908. if (entropy->restarts_to_go == 0) {
  165909. entropy->restarts_to_go = cinfo->restart_interval;
  165910. entropy->next_restart_num++;
  165911. entropy->next_restart_num &= 7;
  165912. }
  165913. entropy->restarts_to_go--;
  165914. }
  165915. return TRUE;
  165916. }
  165917. /*
  165918. * MCU encoding for DC successive approximation refinement scan.
  165919. * Note: we assume such scans can be multi-component, although the spec
  165920. * is not very clear on the point.
  165921. */
  165922. METHODDEF(boolean)
  165923. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165924. {
  165925. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165926. register int temp;
  165927. int blkn;
  165928. int Al = cinfo->Al;
  165929. JBLOCKROW block;
  165930. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165931. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165932. /* Emit restart marker if needed */
  165933. if (cinfo->restart_interval)
  165934. if (entropy->restarts_to_go == 0)
  165935. emit_restart_p(entropy, entropy->next_restart_num);
  165936. /* Encode the MCU data blocks */
  165937. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165938. block = MCU_data[blkn];
  165939. /* We simply emit the Al'th bit of the DC coefficient value. */
  165940. temp = (*block)[0];
  165941. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  165942. }
  165943. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165944. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165945. /* Update restart-interval state too */
  165946. if (cinfo->restart_interval) {
  165947. if (entropy->restarts_to_go == 0) {
  165948. entropy->restarts_to_go = cinfo->restart_interval;
  165949. entropy->next_restart_num++;
  165950. entropy->next_restart_num &= 7;
  165951. }
  165952. entropy->restarts_to_go--;
  165953. }
  165954. return TRUE;
  165955. }
  165956. /*
  165957. * MCU encoding for AC successive approximation refinement scan.
  165958. */
  165959. METHODDEF(boolean)
  165960. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165961. {
  165962. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165963. register int temp;
  165964. register int r, k;
  165965. int EOB;
  165966. char *BR_buffer;
  165967. unsigned int BR;
  165968. int Se = cinfo->Se;
  165969. int Al = cinfo->Al;
  165970. JBLOCKROW block;
  165971. int absvalues[DCTSIZE2];
  165972. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165973. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165974. /* Emit restart marker if needed */
  165975. if (cinfo->restart_interval)
  165976. if (entropy->restarts_to_go == 0)
  165977. emit_restart_p(entropy, entropy->next_restart_num);
  165978. /* Encode the MCU data block */
  165979. block = MCU_data[0];
  165980. /* It is convenient to make a pre-pass to determine the transformed
  165981. * coefficients' absolute values and the EOB position.
  165982. */
  165983. EOB = 0;
  165984. for (k = cinfo->Ss; k <= Se; k++) {
  165985. temp = (*block)[jpeg_natural_order[k]];
  165986. /* We must apply the point transform by Al. For AC coefficients this
  165987. * is an integer division with rounding towards 0. To do this portably
  165988. * in C, we shift after obtaining the absolute value.
  165989. */
  165990. if (temp < 0)
  165991. temp = -temp; /* temp is abs value of input */
  165992. temp >>= Al; /* apply the point transform */
  165993. absvalues[k] = temp; /* save abs value for main pass */
  165994. if (temp == 1)
  165995. EOB = k; /* EOB = index of last newly-nonzero coef */
  165996. }
  165997. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  165998. r = 0; /* r = run length of zeros */
  165999. BR = 0; /* BR = count of buffered bits added now */
  166000. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  166001. for (k = cinfo->Ss; k <= Se; k++) {
  166002. if ((temp = absvalues[k]) == 0) {
  166003. r++;
  166004. continue;
  166005. }
  166006. /* Emit any required ZRLs, but not if they can be folded into EOB */
  166007. while (r > 15 && k <= EOB) {
  166008. /* emit any pending EOBRUN and the BE correction bits */
  166009. emit_eobrun(entropy);
  166010. /* Emit ZRL */
  166011. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166012. r -= 16;
  166013. /* Emit buffered correction bits that must be associated with ZRL */
  166014. emit_buffered_bits(entropy, BR_buffer, BR);
  166015. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166016. BR = 0;
  166017. }
  166018. /* If the coef was previously nonzero, it only needs a correction bit.
  166019. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166020. * that we also need to test r > 15. But if r > 15, we can only get here
  166021. * if k > EOB, which implies that this coefficient is not 1.
  166022. */
  166023. if (temp > 1) {
  166024. /* The correction bit is the next bit of the absolute value. */
  166025. BR_buffer[BR++] = (char) (temp & 1);
  166026. continue;
  166027. }
  166028. /* Emit any pending EOBRUN and the BE correction bits */
  166029. emit_eobrun(entropy);
  166030. /* Count/emit Huffman symbol for run length / number of bits */
  166031. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166032. /* Emit output bit for newly-nonzero coef */
  166033. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166034. emit_bits_p(entropy, (unsigned int) temp, 1);
  166035. /* Emit buffered correction bits that must be associated with this code */
  166036. emit_buffered_bits(entropy, BR_buffer, BR);
  166037. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166038. BR = 0;
  166039. r = 0; /* reset zero run length */
  166040. }
  166041. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166042. entropy->EOBRUN++; /* count an EOB */
  166043. entropy->BE += BR; /* concat my correction bits to older ones */
  166044. /* We force out the EOB if we risk either:
  166045. * 1. overflow of the EOB counter;
  166046. * 2. overflow of the correction bit buffer during the next MCU.
  166047. */
  166048. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166049. emit_eobrun(entropy);
  166050. }
  166051. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166052. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166053. /* Update restart-interval state too */
  166054. if (cinfo->restart_interval) {
  166055. if (entropy->restarts_to_go == 0) {
  166056. entropy->restarts_to_go = cinfo->restart_interval;
  166057. entropy->next_restart_num++;
  166058. entropy->next_restart_num &= 7;
  166059. }
  166060. entropy->restarts_to_go--;
  166061. }
  166062. return TRUE;
  166063. }
  166064. /*
  166065. * Finish up at the end of a Huffman-compressed progressive scan.
  166066. */
  166067. METHODDEF(void)
  166068. finish_pass_phuff (j_compress_ptr cinfo)
  166069. {
  166070. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166071. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166072. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166073. /* Flush out any buffered data */
  166074. emit_eobrun(entropy);
  166075. flush_bits_p(entropy);
  166076. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166077. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166078. }
  166079. /*
  166080. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166081. */
  166082. METHODDEF(void)
  166083. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166084. {
  166085. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166086. boolean is_DC_band;
  166087. int ci, tbl;
  166088. jpeg_component_info * compptr;
  166089. JHUFF_TBL **htblptr;
  166090. boolean did[NUM_HUFF_TBLS];
  166091. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166092. emit_eobrun(entropy);
  166093. is_DC_band = (cinfo->Ss == 0);
  166094. /* It's important not to apply jpeg_gen_optimal_table more than once
  166095. * per table, because it clobbers the input frequency counts!
  166096. */
  166097. MEMZERO(did, SIZEOF(did));
  166098. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166099. compptr = cinfo->cur_comp_info[ci];
  166100. if (is_DC_band) {
  166101. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166102. continue;
  166103. tbl = compptr->dc_tbl_no;
  166104. } else {
  166105. tbl = compptr->ac_tbl_no;
  166106. }
  166107. if (! did[tbl]) {
  166108. if (is_DC_band)
  166109. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166110. else
  166111. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166112. if (*htblptr == NULL)
  166113. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166114. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166115. did[tbl] = TRUE;
  166116. }
  166117. }
  166118. }
  166119. /*
  166120. * Module initialization routine for progressive Huffman entropy encoding.
  166121. */
  166122. GLOBAL(void)
  166123. jinit_phuff_encoder (j_compress_ptr cinfo)
  166124. {
  166125. phuff_entropy_ptr entropy;
  166126. int i;
  166127. entropy = (phuff_entropy_ptr)
  166128. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166129. SIZEOF(phuff_entropy_encoder));
  166130. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166131. entropy->pub.start_pass = start_pass_phuff;
  166132. /* Mark tables unallocated */
  166133. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166134. entropy->derived_tbls[i] = NULL;
  166135. entropy->count_ptrs[i] = NULL;
  166136. }
  166137. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166138. }
  166139. #endif /* C_PROGRESSIVE_SUPPORTED */
  166140. /*** End of inlined file: jcphuff.c ***/
  166141. /*** Start of inlined file: jcprepct.c ***/
  166142. #define JPEG_INTERNALS
  166143. /* At present, jcsample.c can request context rows only for smoothing.
  166144. * In the future, we might also need context rows for CCIR601 sampling
  166145. * or other more-complex downsampling procedures. The code to support
  166146. * context rows should be compiled only if needed.
  166147. */
  166148. #ifdef INPUT_SMOOTHING_SUPPORTED
  166149. #define CONTEXT_ROWS_SUPPORTED
  166150. #endif
  166151. /*
  166152. * For the simple (no-context-row) case, we just need to buffer one
  166153. * row group's worth of pixels for the downsampling step. At the bottom of
  166154. * the image, we pad to a full row group by replicating the last pixel row.
  166155. * The downsampler's last output row is then replicated if needed to pad
  166156. * out to a full iMCU row.
  166157. *
  166158. * When providing context rows, we must buffer three row groups' worth of
  166159. * pixels. Three row groups are physically allocated, but the row pointer
  166160. * arrays are made five row groups high, with the extra pointers above and
  166161. * below "wrapping around" to point to the last and first real row groups.
  166162. * This allows the downsampler to access the proper context rows.
  166163. * At the top and bottom of the image, we create dummy context rows by
  166164. * copying the first or last real pixel row. This copying could be avoided
  166165. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166166. * trouble on the compression side.
  166167. */
  166168. /* Private buffer controller object */
  166169. typedef struct {
  166170. struct jpeg_c_prep_controller pub; /* public fields */
  166171. /* Downsampling input buffer. This buffer holds color-converted data
  166172. * until we have enough to do a downsample step.
  166173. */
  166174. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166175. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166176. int next_buf_row; /* index of next row to store in color_buf */
  166177. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166178. int this_row_group; /* starting row index of group to process */
  166179. int next_buf_stop; /* downsample when we reach this index */
  166180. #endif
  166181. } my_prep_controller;
  166182. typedef my_prep_controller * my_prep_ptr;
  166183. /*
  166184. * Initialize for a processing pass.
  166185. */
  166186. METHODDEF(void)
  166187. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166188. {
  166189. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166190. if (pass_mode != JBUF_PASS_THRU)
  166191. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166192. /* Initialize total-height counter for detecting bottom of image */
  166193. prep->rows_to_go = cinfo->image_height;
  166194. /* Mark the conversion buffer empty */
  166195. prep->next_buf_row = 0;
  166196. #ifdef CONTEXT_ROWS_SUPPORTED
  166197. /* Preset additional state variables for context mode.
  166198. * These aren't used in non-context mode, so we needn't test which mode.
  166199. */
  166200. prep->this_row_group = 0;
  166201. /* Set next_buf_stop to stop after two row groups have been read in. */
  166202. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166203. #endif
  166204. }
  166205. /*
  166206. * Expand an image vertically from height input_rows to height output_rows,
  166207. * by duplicating the bottom row.
  166208. */
  166209. LOCAL(void)
  166210. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166211. int input_rows, int output_rows)
  166212. {
  166213. register int row;
  166214. for (row = input_rows; row < output_rows; row++) {
  166215. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166216. 1, num_cols);
  166217. }
  166218. }
  166219. /*
  166220. * Process some data in the simple no-context case.
  166221. *
  166222. * Preprocessor output data is counted in "row groups". A row group
  166223. * is defined to be v_samp_factor sample rows of each component.
  166224. * Downsampling will produce this much data from each max_v_samp_factor
  166225. * input rows.
  166226. */
  166227. METHODDEF(void)
  166228. pre_process_data (j_compress_ptr cinfo,
  166229. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166230. JDIMENSION in_rows_avail,
  166231. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166232. JDIMENSION out_row_groups_avail)
  166233. {
  166234. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166235. int numrows, ci;
  166236. JDIMENSION inrows;
  166237. jpeg_component_info * compptr;
  166238. while (*in_row_ctr < in_rows_avail &&
  166239. *out_row_group_ctr < out_row_groups_avail) {
  166240. /* Do color conversion to fill the conversion buffer. */
  166241. inrows = in_rows_avail - *in_row_ctr;
  166242. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166243. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166244. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166245. prep->color_buf,
  166246. (JDIMENSION) prep->next_buf_row,
  166247. numrows);
  166248. *in_row_ctr += numrows;
  166249. prep->next_buf_row += numrows;
  166250. prep->rows_to_go -= numrows;
  166251. /* If at bottom of image, pad to fill the conversion buffer. */
  166252. if (prep->rows_to_go == 0 &&
  166253. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166254. for (ci = 0; ci < cinfo->num_components; ci++) {
  166255. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166256. prep->next_buf_row, cinfo->max_v_samp_factor);
  166257. }
  166258. prep->next_buf_row = cinfo->max_v_samp_factor;
  166259. }
  166260. /* If we've filled the conversion buffer, empty it. */
  166261. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166262. (*cinfo->downsample->downsample) (cinfo,
  166263. prep->color_buf, (JDIMENSION) 0,
  166264. output_buf, *out_row_group_ctr);
  166265. prep->next_buf_row = 0;
  166266. (*out_row_group_ctr)++;
  166267. }
  166268. /* If at bottom of image, pad the output to a full iMCU height.
  166269. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166270. */
  166271. if (prep->rows_to_go == 0 &&
  166272. *out_row_group_ctr < out_row_groups_avail) {
  166273. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166274. ci++, compptr++) {
  166275. expand_bottom_edge(output_buf[ci],
  166276. compptr->width_in_blocks * DCTSIZE,
  166277. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166278. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166279. }
  166280. *out_row_group_ctr = out_row_groups_avail;
  166281. break; /* can exit outer loop without test */
  166282. }
  166283. }
  166284. }
  166285. #ifdef CONTEXT_ROWS_SUPPORTED
  166286. /*
  166287. * Process some data in the context case.
  166288. */
  166289. METHODDEF(void)
  166290. pre_process_context (j_compress_ptr cinfo,
  166291. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166292. JDIMENSION in_rows_avail,
  166293. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166294. JDIMENSION out_row_groups_avail)
  166295. {
  166296. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166297. int numrows, ci;
  166298. int buf_height = cinfo->max_v_samp_factor * 3;
  166299. JDIMENSION inrows;
  166300. while (*out_row_group_ctr < out_row_groups_avail) {
  166301. if (*in_row_ctr < in_rows_avail) {
  166302. /* Do color conversion to fill the conversion buffer. */
  166303. inrows = in_rows_avail - *in_row_ctr;
  166304. numrows = prep->next_buf_stop - prep->next_buf_row;
  166305. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166306. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166307. prep->color_buf,
  166308. (JDIMENSION) prep->next_buf_row,
  166309. numrows);
  166310. /* Pad at top of image, if first time through */
  166311. if (prep->rows_to_go == cinfo->image_height) {
  166312. for (ci = 0; ci < cinfo->num_components; ci++) {
  166313. int row;
  166314. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166315. jcopy_sample_rows(prep->color_buf[ci], 0,
  166316. prep->color_buf[ci], -row,
  166317. 1, cinfo->image_width);
  166318. }
  166319. }
  166320. }
  166321. *in_row_ctr += numrows;
  166322. prep->next_buf_row += numrows;
  166323. prep->rows_to_go -= numrows;
  166324. } else {
  166325. /* Return for more data, unless we are at the bottom of the image. */
  166326. if (prep->rows_to_go != 0)
  166327. break;
  166328. /* When at bottom of image, pad to fill the conversion buffer. */
  166329. if (prep->next_buf_row < prep->next_buf_stop) {
  166330. for (ci = 0; ci < cinfo->num_components; ci++) {
  166331. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166332. prep->next_buf_row, prep->next_buf_stop);
  166333. }
  166334. prep->next_buf_row = prep->next_buf_stop;
  166335. }
  166336. }
  166337. /* If we've gotten enough data, downsample a row group. */
  166338. if (prep->next_buf_row == prep->next_buf_stop) {
  166339. (*cinfo->downsample->downsample) (cinfo,
  166340. prep->color_buf,
  166341. (JDIMENSION) prep->this_row_group,
  166342. output_buf, *out_row_group_ctr);
  166343. (*out_row_group_ctr)++;
  166344. /* Advance pointers with wraparound as necessary. */
  166345. prep->this_row_group += cinfo->max_v_samp_factor;
  166346. if (prep->this_row_group >= buf_height)
  166347. prep->this_row_group = 0;
  166348. if (prep->next_buf_row >= buf_height)
  166349. prep->next_buf_row = 0;
  166350. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166351. }
  166352. }
  166353. }
  166354. /*
  166355. * Create the wrapped-around downsampling input buffer needed for context mode.
  166356. */
  166357. LOCAL(void)
  166358. create_context_buffer (j_compress_ptr cinfo)
  166359. {
  166360. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166361. int rgroup_height = cinfo->max_v_samp_factor;
  166362. int ci, i;
  166363. jpeg_component_info * compptr;
  166364. JSAMPARRAY true_buffer, fake_buffer;
  166365. /* Grab enough space for fake row pointers for all the components;
  166366. * we need five row groups' worth of pointers for each component.
  166367. */
  166368. fake_buffer = (JSAMPARRAY)
  166369. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166370. (cinfo->num_components * 5 * rgroup_height) *
  166371. SIZEOF(JSAMPROW));
  166372. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166373. ci++, compptr++) {
  166374. /* Allocate the actual buffer space (3 row groups) for this component.
  166375. * We make the buffer wide enough to allow the downsampler to edge-expand
  166376. * horizontally within the buffer, if it so chooses.
  166377. */
  166378. true_buffer = (*cinfo->mem->alloc_sarray)
  166379. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166380. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166381. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166382. (JDIMENSION) (3 * rgroup_height));
  166383. /* Copy true buffer row pointers into the middle of the fake row array */
  166384. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166385. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166386. /* Fill in the above and below wraparound pointers */
  166387. for (i = 0; i < rgroup_height; i++) {
  166388. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166389. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166390. }
  166391. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166392. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166393. }
  166394. }
  166395. #endif /* CONTEXT_ROWS_SUPPORTED */
  166396. /*
  166397. * Initialize preprocessing controller.
  166398. */
  166399. GLOBAL(void)
  166400. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166401. {
  166402. my_prep_ptr prep;
  166403. int ci;
  166404. jpeg_component_info * compptr;
  166405. if (need_full_buffer) /* safety check */
  166406. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166407. prep = (my_prep_ptr)
  166408. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166409. SIZEOF(my_prep_controller));
  166410. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166411. prep->pub.start_pass = start_pass_prep;
  166412. /* Allocate the color conversion buffer.
  166413. * We make the buffer wide enough to allow the downsampler to edge-expand
  166414. * horizontally within the buffer, if it so chooses.
  166415. */
  166416. if (cinfo->downsample->need_context_rows) {
  166417. /* Set up to provide context rows */
  166418. #ifdef CONTEXT_ROWS_SUPPORTED
  166419. prep->pub.pre_process_data = pre_process_context;
  166420. create_context_buffer(cinfo);
  166421. #else
  166422. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166423. #endif
  166424. } else {
  166425. /* No context, just make it tall enough for one row group */
  166426. prep->pub.pre_process_data = pre_process_data;
  166427. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166428. ci++, compptr++) {
  166429. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166430. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166431. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166432. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166433. (JDIMENSION) cinfo->max_v_samp_factor);
  166434. }
  166435. }
  166436. }
  166437. /*** End of inlined file: jcprepct.c ***/
  166438. /*** Start of inlined file: jcsample.c ***/
  166439. #define JPEG_INTERNALS
  166440. /* Pointer to routine to downsample a single component */
  166441. typedef JMETHOD(void, downsample1_ptr,
  166442. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166443. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166444. /* Private subobject */
  166445. typedef struct {
  166446. struct jpeg_downsampler pub; /* public fields */
  166447. /* Downsampling method pointers, one per component */
  166448. downsample1_ptr methods[MAX_COMPONENTS];
  166449. } my_downsampler;
  166450. typedef my_downsampler * my_downsample_ptr;
  166451. /*
  166452. * Initialize for a downsampling pass.
  166453. */
  166454. METHODDEF(void)
  166455. start_pass_downsample (j_compress_ptr)
  166456. {
  166457. /* no work for now */
  166458. }
  166459. /*
  166460. * Expand a component horizontally from width input_cols to width output_cols,
  166461. * by duplicating the rightmost samples.
  166462. */
  166463. LOCAL(void)
  166464. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166465. JDIMENSION input_cols, JDIMENSION output_cols)
  166466. {
  166467. register JSAMPROW ptr;
  166468. register JSAMPLE pixval;
  166469. register int count;
  166470. int row;
  166471. int numcols = (int) (output_cols - input_cols);
  166472. if (numcols > 0) {
  166473. for (row = 0; row < num_rows; row++) {
  166474. ptr = image_data[row] + input_cols;
  166475. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166476. for (count = numcols; count > 0; count--)
  166477. *ptr++ = pixval;
  166478. }
  166479. }
  166480. }
  166481. /*
  166482. * Do downsampling for a whole row group (all components).
  166483. *
  166484. * In this version we simply downsample each component independently.
  166485. */
  166486. METHODDEF(void)
  166487. sep_downsample (j_compress_ptr cinfo,
  166488. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  166489. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  166490. {
  166491. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  166492. int ci;
  166493. jpeg_component_info * compptr;
  166494. JSAMPARRAY in_ptr, out_ptr;
  166495. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166496. ci++, compptr++) {
  166497. in_ptr = input_buf[ci] + in_row_index;
  166498. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  166499. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  166500. }
  166501. }
  166502. /*
  166503. * Downsample pixel values of a single component.
  166504. * One row group is processed per call.
  166505. * This version handles arbitrary integral sampling ratios, without smoothing.
  166506. * Note that this version is not actually used for customary sampling ratios.
  166507. */
  166508. METHODDEF(void)
  166509. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166510. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166511. {
  166512. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  166513. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  166514. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166515. JSAMPROW inptr, outptr;
  166516. INT32 outvalue;
  166517. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  166518. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  166519. numpix = h_expand * v_expand;
  166520. numpix2 = numpix/2;
  166521. /* Expand input data enough to let all the output samples be generated
  166522. * by the standard loop. Special-casing padded output would be more
  166523. * efficient.
  166524. */
  166525. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166526. cinfo->image_width, output_cols * h_expand);
  166527. inrow = 0;
  166528. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166529. outptr = output_data[outrow];
  166530. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  166531. outcol++, outcol_h += h_expand) {
  166532. outvalue = 0;
  166533. for (v = 0; v < v_expand; v++) {
  166534. inptr = input_data[inrow+v] + outcol_h;
  166535. for (h = 0; h < h_expand; h++) {
  166536. outvalue += (INT32) GETJSAMPLE(*inptr++);
  166537. }
  166538. }
  166539. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  166540. }
  166541. inrow += v_expand;
  166542. }
  166543. }
  166544. /*
  166545. * Downsample pixel values of a single component.
  166546. * This version handles the special case of a full-size component,
  166547. * without smoothing.
  166548. */
  166549. METHODDEF(void)
  166550. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166551. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166552. {
  166553. /* Copy the data */
  166554. jcopy_sample_rows(input_data, 0, output_data, 0,
  166555. cinfo->max_v_samp_factor, cinfo->image_width);
  166556. /* Edge-expand */
  166557. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  166558. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  166559. }
  166560. /*
  166561. * Downsample pixel values of a single component.
  166562. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  166563. * without smoothing.
  166564. *
  166565. * A note about the "bias" calculations: when rounding fractional values to
  166566. * integer, we do not want to always round 0.5 up to the next integer.
  166567. * If we did that, we'd introduce a noticeable bias towards larger values.
  166568. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  166569. * alternate pixel locations (a simple ordered dither pattern).
  166570. */
  166571. METHODDEF(void)
  166572. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166573. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166574. {
  166575. int outrow;
  166576. JDIMENSION outcol;
  166577. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166578. register JSAMPROW inptr, outptr;
  166579. register int bias;
  166580. /* Expand input data enough to let all the output samples be generated
  166581. * by the standard loop. Special-casing padded output would be more
  166582. * efficient.
  166583. */
  166584. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166585. cinfo->image_width, output_cols * 2);
  166586. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166587. outptr = output_data[outrow];
  166588. inptr = input_data[outrow];
  166589. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  166590. for (outcol = 0; outcol < output_cols; outcol++) {
  166591. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  166592. + bias) >> 1);
  166593. bias ^= 1; /* 0=>1, 1=>0 */
  166594. inptr += 2;
  166595. }
  166596. }
  166597. }
  166598. /*
  166599. * Downsample pixel values of a single component.
  166600. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166601. * without smoothing.
  166602. */
  166603. METHODDEF(void)
  166604. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166605. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166606. {
  166607. int inrow, outrow;
  166608. JDIMENSION outcol;
  166609. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166610. register JSAMPROW inptr0, inptr1, outptr;
  166611. register int bias;
  166612. /* Expand input data enough to let all the output samples be generated
  166613. * by the standard loop. Special-casing padded output would be more
  166614. * efficient.
  166615. */
  166616. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166617. cinfo->image_width, output_cols * 2);
  166618. inrow = 0;
  166619. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166620. outptr = output_data[outrow];
  166621. inptr0 = input_data[inrow];
  166622. inptr1 = input_data[inrow+1];
  166623. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  166624. for (outcol = 0; outcol < output_cols; outcol++) {
  166625. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166626. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  166627. + bias) >> 2);
  166628. bias ^= 3; /* 1=>2, 2=>1 */
  166629. inptr0 += 2; inptr1 += 2;
  166630. }
  166631. inrow += 2;
  166632. }
  166633. }
  166634. #ifdef INPUT_SMOOTHING_SUPPORTED
  166635. /*
  166636. * Downsample pixel values of a single component.
  166637. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166638. * with smoothing. One row of context is required.
  166639. */
  166640. METHODDEF(void)
  166641. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166642. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166643. {
  166644. int inrow, outrow;
  166645. JDIMENSION colctr;
  166646. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166647. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  166648. INT32 membersum, neighsum, memberscale, neighscale;
  166649. /* Expand input data enough to let all the output samples be generated
  166650. * by the standard loop. Special-casing padded output would be more
  166651. * efficient.
  166652. */
  166653. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166654. cinfo->image_width, output_cols * 2);
  166655. /* We don't bother to form the individual "smoothed" input pixel values;
  166656. * we can directly compute the output which is the average of the four
  166657. * smoothed values. Each of the four member pixels contributes a fraction
  166658. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  166659. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  166660. * output. The four corner-adjacent neighbor pixels contribute a fraction
  166661. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  166662. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  166663. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  166664. * factors are scaled by 2^16 = 65536.
  166665. * Also recall that SF = smoothing_factor / 1024.
  166666. */
  166667. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  166668. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  166669. inrow = 0;
  166670. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166671. outptr = output_data[outrow];
  166672. inptr0 = input_data[inrow];
  166673. inptr1 = input_data[inrow+1];
  166674. above_ptr = input_data[inrow-1];
  166675. below_ptr = input_data[inrow+2];
  166676. /* Special case for first column: pretend column -1 is same as column 0 */
  166677. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166678. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166679. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166680. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166681. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  166682. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  166683. neighsum += neighsum;
  166684. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  166685. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  166686. membersum = membersum * memberscale + neighsum * neighscale;
  166687. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166688. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166689. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166690. /* sum of pixels directly mapped to this output element */
  166691. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166692. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166693. /* sum of edge-neighbor pixels */
  166694. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166695. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166696. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  166697. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  166698. /* The edge-neighbors count twice as much as corner-neighbors */
  166699. neighsum += neighsum;
  166700. /* Add in the corner-neighbors */
  166701. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  166702. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  166703. /* form final output scaled up by 2^16 */
  166704. membersum = membersum * memberscale + neighsum * neighscale;
  166705. /* round, descale and output it */
  166706. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166707. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166708. }
  166709. /* Special case for last column */
  166710. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166711. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166712. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166713. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166714. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  166715. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  166716. neighsum += neighsum;
  166717. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  166718. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  166719. membersum = membersum * memberscale + neighsum * neighscale;
  166720. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166721. inrow += 2;
  166722. }
  166723. }
  166724. /*
  166725. * Downsample pixel values of a single component.
  166726. * This version handles the special case of a full-size component,
  166727. * with smoothing. One row of context is required.
  166728. */
  166729. METHODDEF(void)
  166730. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  166731. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166732. {
  166733. int outrow;
  166734. JDIMENSION colctr;
  166735. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166736. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  166737. INT32 membersum, neighsum, memberscale, neighscale;
  166738. int colsum, lastcolsum, nextcolsum;
  166739. /* Expand input data enough to let all the output samples be generated
  166740. * by the standard loop. Special-casing padded output would be more
  166741. * efficient.
  166742. */
  166743. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166744. cinfo->image_width, output_cols);
  166745. /* Each of the eight neighbor pixels contributes a fraction SF to the
  166746. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  166747. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  166748. * Also recall that SF = smoothing_factor / 1024.
  166749. */
  166750. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  166751. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  166752. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166753. outptr = output_data[outrow];
  166754. inptr = input_data[outrow];
  166755. above_ptr = input_data[outrow-1];
  166756. below_ptr = input_data[outrow+1];
  166757. /* Special case for first column */
  166758. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  166759. GETJSAMPLE(*inptr);
  166760. membersum = GETJSAMPLE(*inptr++);
  166761. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166762. GETJSAMPLE(*inptr);
  166763. neighsum = colsum + (colsum - membersum) + nextcolsum;
  166764. membersum = membersum * memberscale + neighsum * neighscale;
  166765. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166766. lastcolsum = colsum; colsum = nextcolsum;
  166767. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166768. membersum = GETJSAMPLE(*inptr++);
  166769. above_ptr++; below_ptr++;
  166770. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166771. GETJSAMPLE(*inptr);
  166772. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  166773. membersum = membersum * memberscale + neighsum * neighscale;
  166774. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166775. lastcolsum = colsum; colsum = nextcolsum;
  166776. }
  166777. /* Special case for last column */
  166778. membersum = GETJSAMPLE(*inptr);
  166779. neighsum = lastcolsum + (colsum - membersum) + colsum;
  166780. membersum = membersum * memberscale + neighsum * neighscale;
  166781. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166782. }
  166783. }
  166784. #endif /* INPUT_SMOOTHING_SUPPORTED */
  166785. /*
  166786. * Module initialization routine for downsampling.
  166787. * Note that we must select a routine for each component.
  166788. */
  166789. GLOBAL(void)
  166790. jinit_downsampler (j_compress_ptr cinfo)
  166791. {
  166792. my_downsample_ptr downsample;
  166793. int ci;
  166794. jpeg_component_info * compptr;
  166795. boolean smoothok = TRUE;
  166796. downsample = (my_downsample_ptr)
  166797. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166798. SIZEOF(my_downsampler));
  166799. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  166800. downsample->pub.start_pass = start_pass_downsample;
  166801. downsample->pub.downsample = sep_downsample;
  166802. downsample->pub.need_context_rows = FALSE;
  166803. if (cinfo->CCIR601_sampling)
  166804. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  166805. /* Verify we can handle the sampling factors, and set up method pointers */
  166806. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166807. ci++, compptr++) {
  166808. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  166809. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166810. #ifdef INPUT_SMOOTHING_SUPPORTED
  166811. if (cinfo->smoothing_factor) {
  166812. downsample->methods[ci] = fullsize_smooth_downsample;
  166813. downsample->pub.need_context_rows = TRUE;
  166814. } else
  166815. #endif
  166816. downsample->methods[ci] = fullsize_downsample;
  166817. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166818. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166819. smoothok = FALSE;
  166820. downsample->methods[ci] = h2v1_downsample;
  166821. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166822. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  166823. #ifdef INPUT_SMOOTHING_SUPPORTED
  166824. if (cinfo->smoothing_factor) {
  166825. downsample->methods[ci] = h2v2_smooth_downsample;
  166826. downsample->pub.need_context_rows = TRUE;
  166827. } else
  166828. #endif
  166829. downsample->methods[ci] = h2v2_downsample;
  166830. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  166831. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  166832. smoothok = FALSE;
  166833. downsample->methods[ci] = int_downsample;
  166834. } else
  166835. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  166836. }
  166837. #ifdef INPUT_SMOOTHING_SUPPORTED
  166838. if (cinfo->smoothing_factor && !smoothok)
  166839. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  166840. #endif
  166841. }
  166842. /*** End of inlined file: jcsample.c ***/
  166843. /*** Start of inlined file: jctrans.c ***/
  166844. #define JPEG_INTERNALS
  166845. /* Forward declarations */
  166846. LOCAL(void) transencode_master_selection
  166847. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166848. LOCAL(void) transencode_coef_controller
  166849. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166850. /*
  166851. * Compression initialization for writing raw-coefficient data.
  166852. * Before calling this, all parameters and a data destination must be set up.
  166853. * Call jpeg_finish_compress() to actually write the data.
  166854. *
  166855. * The number of passed virtual arrays must match cinfo->num_components.
  166856. * Note that the virtual arrays need not be filled or even realized at
  166857. * the time write_coefficients is called; indeed, if the virtual arrays
  166858. * were requested from this compression object's memory manager, they
  166859. * typically will be realized during this routine and filled afterwards.
  166860. */
  166861. GLOBAL(void)
  166862. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  166863. {
  166864. if (cinfo->global_state != CSTATE_START)
  166865. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166866. /* Mark all tables to be written */
  166867. jpeg_suppress_tables(cinfo, FALSE);
  166868. /* (Re)initialize error mgr and destination modules */
  166869. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  166870. (*cinfo->dest->init_destination) (cinfo);
  166871. /* Perform master selection of active modules */
  166872. transencode_master_selection(cinfo, coef_arrays);
  166873. /* Wait for jpeg_finish_compress() call */
  166874. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  166875. cinfo->global_state = CSTATE_WRCOEFS;
  166876. }
  166877. /*
  166878. * Initialize the compression object with default parameters,
  166879. * then copy from the source object all parameters needed for lossless
  166880. * transcoding. Parameters that can be varied without loss (such as
  166881. * scan script and Huffman optimization) are left in their default states.
  166882. */
  166883. GLOBAL(void)
  166884. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  166885. j_compress_ptr dstinfo)
  166886. {
  166887. JQUANT_TBL ** qtblptr;
  166888. jpeg_component_info *incomp, *outcomp;
  166889. JQUANT_TBL *c_quant, *slot_quant;
  166890. int tblno, ci, coefi;
  166891. /* Safety check to ensure start_compress not called yet. */
  166892. if (dstinfo->global_state != CSTATE_START)
  166893. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  166894. /* Copy fundamental image dimensions */
  166895. dstinfo->image_width = srcinfo->image_width;
  166896. dstinfo->image_height = srcinfo->image_height;
  166897. dstinfo->input_components = srcinfo->num_components;
  166898. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  166899. /* Initialize all parameters to default values */
  166900. jpeg_set_defaults(dstinfo);
  166901. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  166902. * Fix it to get the right header markers for the image colorspace.
  166903. */
  166904. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  166905. dstinfo->data_precision = srcinfo->data_precision;
  166906. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  166907. /* Copy the source's quantization tables. */
  166908. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  166909. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  166910. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  166911. if (*qtblptr == NULL)
  166912. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  166913. MEMCOPY((*qtblptr)->quantval,
  166914. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  166915. SIZEOF((*qtblptr)->quantval));
  166916. (*qtblptr)->sent_table = FALSE;
  166917. }
  166918. }
  166919. /* Copy the source's per-component info.
  166920. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  166921. */
  166922. dstinfo->num_components = srcinfo->num_components;
  166923. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  166924. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  166925. MAX_COMPONENTS);
  166926. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  166927. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  166928. outcomp->component_id = incomp->component_id;
  166929. outcomp->h_samp_factor = incomp->h_samp_factor;
  166930. outcomp->v_samp_factor = incomp->v_samp_factor;
  166931. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  166932. /* Make sure saved quantization table for component matches the qtable
  166933. * slot. If not, the input file re-used this qtable slot.
  166934. * IJG encoder currently cannot duplicate this.
  166935. */
  166936. tblno = outcomp->quant_tbl_no;
  166937. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  166938. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  166939. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  166940. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  166941. c_quant = incomp->quant_table;
  166942. if (c_quant != NULL) {
  166943. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  166944. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  166945. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  166946. }
  166947. }
  166948. /* Note: we do not copy the source's Huffman table assignments;
  166949. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  166950. */
  166951. }
  166952. /* Also copy JFIF version and resolution information, if available.
  166953. * Strictly speaking this isn't "critical" info, but it's nearly
  166954. * always appropriate to copy it if available. In particular,
  166955. * if the application chooses to copy JFIF 1.02 extension markers from
  166956. * the source file, we need to copy the version to make sure we don't
  166957. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  166958. * We will *not*, however, copy version info from mislabeled "2.01" files.
  166959. */
  166960. if (srcinfo->saw_JFIF_marker) {
  166961. if (srcinfo->JFIF_major_version == 1) {
  166962. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  166963. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  166964. }
  166965. dstinfo->density_unit = srcinfo->density_unit;
  166966. dstinfo->X_density = srcinfo->X_density;
  166967. dstinfo->Y_density = srcinfo->Y_density;
  166968. }
  166969. }
  166970. /*
  166971. * Master selection of compression modules for transcoding.
  166972. * This substitutes for jcinit.c's initialization of the full compressor.
  166973. */
  166974. LOCAL(void)
  166975. transencode_master_selection (j_compress_ptr cinfo,
  166976. jvirt_barray_ptr * coef_arrays)
  166977. {
  166978. /* Although we don't actually use input_components for transcoding,
  166979. * jcmaster.c's initial_setup will complain if input_components is 0.
  166980. */
  166981. cinfo->input_components = 1;
  166982. /* Initialize master control (includes parameter checking/processing) */
  166983. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  166984. /* Entropy encoding: either Huffman or arithmetic coding. */
  166985. if (cinfo->arith_code) {
  166986. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  166987. } else {
  166988. if (cinfo->progressive_mode) {
  166989. #ifdef C_PROGRESSIVE_SUPPORTED
  166990. jinit_phuff_encoder(cinfo);
  166991. #else
  166992. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166993. #endif
  166994. } else
  166995. jinit_huff_encoder(cinfo);
  166996. }
  166997. /* We need a special coefficient buffer controller. */
  166998. transencode_coef_controller(cinfo, coef_arrays);
  166999. jinit_marker_writer(cinfo);
  167000. /* We can now tell the memory manager to allocate virtual arrays. */
  167001. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167002. /* Write the datastream header (SOI, JFIF) immediately.
  167003. * Frame and scan headers are postponed till later.
  167004. * This lets application insert special markers after the SOI.
  167005. */
  167006. (*cinfo->marker->write_file_header) (cinfo);
  167007. }
  167008. /*
  167009. * The rest of this file is a special implementation of the coefficient
  167010. * buffer controller. This is similar to jccoefct.c, but it handles only
  167011. * output from presupplied virtual arrays. Furthermore, we generate any
  167012. * dummy padding blocks on-the-fly rather than expecting them to be present
  167013. * in the arrays.
  167014. */
  167015. /* Private buffer controller object */
  167016. typedef struct {
  167017. struct jpeg_c_coef_controller pub; /* public fields */
  167018. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167019. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167020. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167021. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167022. /* Virtual block array for each component. */
  167023. jvirt_barray_ptr * whole_image;
  167024. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167025. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167026. } my_coef_controller2;
  167027. typedef my_coef_controller2 * my_coef_ptr2;
  167028. LOCAL(void)
  167029. start_iMCU_row2 (j_compress_ptr cinfo)
  167030. /* Reset within-iMCU-row counters for a new row */
  167031. {
  167032. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167033. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167034. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167035. * But at the bottom of the image, process only what's left.
  167036. */
  167037. if (cinfo->comps_in_scan > 1) {
  167038. coef->MCU_rows_per_iMCU_row = 1;
  167039. } else {
  167040. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167041. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167042. else
  167043. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167044. }
  167045. coef->mcu_ctr = 0;
  167046. coef->MCU_vert_offset = 0;
  167047. }
  167048. /*
  167049. * Initialize for a processing pass.
  167050. */
  167051. METHODDEF(void)
  167052. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167053. {
  167054. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167055. if (pass_mode != JBUF_CRANK_DEST)
  167056. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167057. coef->iMCU_row_num = 0;
  167058. start_iMCU_row2(cinfo);
  167059. }
  167060. /*
  167061. * Process some data.
  167062. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167063. * per call, ie, v_samp_factor block rows for each component in the scan.
  167064. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167065. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167066. *
  167067. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167068. */
  167069. METHODDEF(boolean)
  167070. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167071. {
  167072. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167073. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167074. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167075. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167076. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167077. JDIMENSION start_col;
  167078. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167079. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167080. JBLOCKROW buffer_ptr;
  167081. jpeg_component_info *compptr;
  167082. /* Align the virtual buffers for the components used in this scan. */
  167083. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167084. compptr = cinfo->cur_comp_info[ci];
  167085. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167086. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167087. coef->iMCU_row_num * compptr->v_samp_factor,
  167088. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167089. }
  167090. /* Loop to process one whole iMCU row */
  167091. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167092. yoffset++) {
  167093. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167094. MCU_col_num++) {
  167095. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167096. blkn = 0; /* index of current DCT block within MCU */
  167097. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167098. compptr = cinfo->cur_comp_info[ci];
  167099. start_col = MCU_col_num * compptr->MCU_width;
  167100. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167101. : compptr->last_col_width;
  167102. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167103. if (coef->iMCU_row_num < last_iMCU_row ||
  167104. yindex+yoffset < compptr->last_row_height) {
  167105. /* Fill in pointers to real blocks in this row */
  167106. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167107. for (xindex = 0; xindex < blockcnt; xindex++)
  167108. MCU_buffer[blkn++] = buffer_ptr++;
  167109. } else {
  167110. /* At bottom of image, need a whole row of dummy blocks */
  167111. xindex = 0;
  167112. }
  167113. /* Fill in any dummy blocks needed in this row.
  167114. * Dummy blocks are filled in the same way as in jccoefct.c:
  167115. * all zeroes in the AC entries, DC entries equal to previous
  167116. * block's DC value. The init routine has already zeroed the
  167117. * AC entries, so we need only set the DC entries correctly.
  167118. */
  167119. for (; xindex < compptr->MCU_width; xindex++) {
  167120. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167121. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167122. blkn++;
  167123. }
  167124. }
  167125. }
  167126. /* Try to write the MCU. */
  167127. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167128. /* Suspension forced; update state counters and exit */
  167129. coef->MCU_vert_offset = yoffset;
  167130. coef->mcu_ctr = MCU_col_num;
  167131. return FALSE;
  167132. }
  167133. }
  167134. /* Completed an MCU row, but perhaps not an iMCU row */
  167135. coef->mcu_ctr = 0;
  167136. }
  167137. /* Completed the iMCU row, advance counters for next one */
  167138. coef->iMCU_row_num++;
  167139. start_iMCU_row2(cinfo);
  167140. return TRUE;
  167141. }
  167142. /*
  167143. * Initialize coefficient buffer controller.
  167144. *
  167145. * Each passed coefficient array must be the right size for that
  167146. * coefficient: width_in_blocks wide and height_in_blocks high,
  167147. * with unitheight at least v_samp_factor.
  167148. */
  167149. LOCAL(void)
  167150. transencode_coef_controller (j_compress_ptr cinfo,
  167151. jvirt_barray_ptr * coef_arrays)
  167152. {
  167153. my_coef_ptr2 coef;
  167154. JBLOCKROW buffer;
  167155. int i;
  167156. coef = (my_coef_ptr2)
  167157. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167158. SIZEOF(my_coef_controller2));
  167159. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167160. coef->pub.start_pass = start_pass_coef2;
  167161. coef->pub.compress_data = compress_output2;
  167162. /* Save pointer to virtual arrays */
  167163. coef->whole_image = coef_arrays;
  167164. /* Allocate and pre-zero space for dummy DCT blocks. */
  167165. buffer = (JBLOCKROW)
  167166. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167167. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167168. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167169. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167170. coef->dummy_buffer[i] = buffer + i;
  167171. }
  167172. }
  167173. /*** End of inlined file: jctrans.c ***/
  167174. /*** Start of inlined file: jdapistd.c ***/
  167175. #define JPEG_INTERNALS
  167176. /* Forward declarations */
  167177. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167178. /*
  167179. * Decompression initialization.
  167180. * jpeg_read_header must be completed before calling this.
  167181. *
  167182. * If a multipass operating mode was selected, this will do all but the
  167183. * last pass, and thus may take a great deal of time.
  167184. *
  167185. * Returns FALSE if suspended. The return value need be inspected only if
  167186. * a suspending data source is used.
  167187. */
  167188. GLOBAL(boolean)
  167189. jpeg_start_decompress (j_decompress_ptr cinfo)
  167190. {
  167191. if (cinfo->global_state == DSTATE_READY) {
  167192. /* First call: initialize master control, select active modules */
  167193. jinit_master_decompress(cinfo);
  167194. if (cinfo->buffered_image) {
  167195. /* No more work here; expecting jpeg_start_output next */
  167196. cinfo->global_state = DSTATE_BUFIMAGE;
  167197. return TRUE;
  167198. }
  167199. cinfo->global_state = DSTATE_PRELOAD;
  167200. }
  167201. if (cinfo->global_state == DSTATE_PRELOAD) {
  167202. /* If file has multiple scans, absorb them all into the coef buffer */
  167203. if (cinfo->inputctl->has_multiple_scans) {
  167204. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167205. for (;;) {
  167206. int retcode;
  167207. /* Call progress monitor hook if present */
  167208. if (cinfo->progress != NULL)
  167209. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167210. /* Absorb some more input */
  167211. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167212. if (retcode == JPEG_SUSPENDED)
  167213. return FALSE;
  167214. if (retcode == JPEG_REACHED_EOI)
  167215. break;
  167216. /* Advance progress counter if appropriate */
  167217. if (cinfo->progress != NULL &&
  167218. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167219. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167220. /* jdmaster underestimated number of scans; ratchet up one scan */
  167221. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167222. }
  167223. }
  167224. }
  167225. #else
  167226. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167227. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167228. }
  167229. cinfo->output_scan_number = cinfo->input_scan_number;
  167230. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167231. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167232. /* Perform any dummy output passes, and set up for the final pass */
  167233. return output_pass_setup(cinfo);
  167234. }
  167235. /*
  167236. * Set up for an output pass, and perform any dummy pass(es) needed.
  167237. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167238. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167239. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167240. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167241. */
  167242. LOCAL(boolean)
  167243. output_pass_setup (j_decompress_ptr cinfo)
  167244. {
  167245. if (cinfo->global_state != DSTATE_PRESCAN) {
  167246. /* First call: do pass setup */
  167247. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167248. cinfo->output_scanline = 0;
  167249. cinfo->global_state = DSTATE_PRESCAN;
  167250. }
  167251. /* Loop over any required dummy passes */
  167252. while (cinfo->master->is_dummy_pass) {
  167253. #ifdef QUANT_2PASS_SUPPORTED
  167254. /* Crank through the dummy pass */
  167255. while (cinfo->output_scanline < cinfo->output_height) {
  167256. JDIMENSION last_scanline;
  167257. /* Call progress monitor hook if present */
  167258. if (cinfo->progress != NULL) {
  167259. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167260. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167261. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167262. }
  167263. /* Process some data */
  167264. last_scanline = cinfo->output_scanline;
  167265. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167266. &cinfo->output_scanline, (JDIMENSION) 0);
  167267. if (cinfo->output_scanline == last_scanline)
  167268. return FALSE; /* No progress made, must suspend */
  167269. }
  167270. /* Finish up dummy pass, and set up for another one */
  167271. (*cinfo->master->finish_output_pass) (cinfo);
  167272. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167273. cinfo->output_scanline = 0;
  167274. #else
  167275. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167276. #endif /* QUANT_2PASS_SUPPORTED */
  167277. }
  167278. /* Ready for application to drive output pass through
  167279. * jpeg_read_scanlines or jpeg_read_raw_data.
  167280. */
  167281. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167282. return TRUE;
  167283. }
  167284. /*
  167285. * Read some scanlines of data from the JPEG decompressor.
  167286. *
  167287. * The return value will be the number of lines actually read.
  167288. * This may be less than the number requested in several cases,
  167289. * including bottom of image, data source suspension, and operating
  167290. * modes that emit multiple scanlines at a time.
  167291. *
  167292. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167293. * this likely signals an application programmer error. However,
  167294. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167295. */
  167296. GLOBAL(JDIMENSION)
  167297. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167298. JDIMENSION max_lines)
  167299. {
  167300. JDIMENSION row_ctr;
  167301. if (cinfo->global_state != DSTATE_SCANNING)
  167302. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167303. if (cinfo->output_scanline >= cinfo->output_height) {
  167304. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167305. return 0;
  167306. }
  167307. /* Call progress monitor hook if present */
  167308. if (cinfo->progress != NULL) {
  167309. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167310. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167311. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167312. }
  167313. /* Process some data */
  167314. row_ctr = 0;
  167315. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167316. cinfo->output_scanline += row_ctr;
  167317. return row_ctr;
  167318. }
  167319. /*
  167320. * Alternate entry point to read raw data.
  167321. * Processes exactly one iMCU row per call, unless suspended.
  167322. */
  167323. GLOBAL(JDIMENSION)
  167324. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167325. JDIMENSION max_lines)
  167326. {
  167327. JDIMENSION lines_per_iMCU_row;
  167328. if (cinfo->global_state != DSTATE_RAW_OK)
  167329. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167330. if (cinfo->output_scanline >= cinfo->output_height) {
  167331. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167332. return 0;
  167333. }
  167334. /* Call progress monitor hook if present */
  167335. if (cinfo->progress != NULL) {
  167336. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167337. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167338. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167339. }
  167340. /* Verify that at least one iMCU row can be returned. */
  167341. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167342. if (max_lines < lines_per_iMCU_row)
  167343. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167344. /* Decompress directly into user's buffer. */
  167345. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167346. return 0; /* suspension forced, can do nothing more */
  167347. /* OK, we processed one iMCU row. */
  167348. cinfo->output_scanline += lines_per_iMCU_row;
  167349. return lines_per_iMCU_row;
  167350. }
  167351. /* Additional entry points for buffered-image mode. */
  167352. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167353. /*
  167354. * Initialize for an output pass in buffered-image mode.
  167355. */
  167356. GLOBAL(boolean)
  167357. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167358. {
  167359. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167360. cinfo->global_state != DSTATE_PRESCAN)
  167361. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167362. /* Limit scan number to valid range */
  167363. if (scan_number <= 0)
  167364. scan_number = 1;
  167365. if (cinfo->inputctl->eoi_reached &&
  167366. scan_number > cinfo->input_scan_number)
  167367. scan_number = cinfo->input_scan_number;
  167368. cinfo->output_scan_number = scan_number;
  167369. /* Perform any dummy output passes, and set up for the real pass */
  167370. return output_pass_setup(cinfo);
  167371. }
  167372. /*
  167373. * Finish up after an output pass in buffered-image mode.
  167374. *
  167375. * Returns FALSE if suspended. The return value need be inspected only if
  167376. * a suspending data source is used.
  167377. */
  167378. GLOBAL(boolean)
  167379. jpeg_finish_output (j_decompress_ptr cinfo)
  167380. {
  167381. if ((cinfo->global_state == DSTATE_SCANNING ||
  167382. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167383. /* Terminate this pass. */
  167384. /* We do not require the whole pass to have been completed. */
  167385. (*cinfo->master->finish_output_pass) (cinfo);
  167386. cinfo->global_state = DSTATE_BUFPOST;
  167387. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167388. /* BUFPOST = repeat call after a suspension, anything else is error */
  167389. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167390. }
  167391. /* Read markers looking for SOS or EOI */
  167392. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167393. ! cinfo->inputctl->eoi_reached) {
  167394. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167395. return FALSE; /* Suspend, come back later */
  167396. }
  167397. cinfo->global_state = DSTATE_BUFIMAGE;
  167398. return TRUE;
  167399. }
  167400. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167401. /*** End of inlined file: jdapistd.c ***/
  167402. /*** Start of inlined file: jdapimin.c ***/
  167403. #define JPEG_INTERNALS
  167404. /*
  167405. * Initialization of a JPEG decompression object.
  167406. * The error manager must already be set up (in case memory manager fails).
  167407. */
  167408. GLOBAL(void)
  167409. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167410. {
  167411. int i;
  167412. /* Guard against version mismatches between library and caller. */
  167413. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167414. if (version != JPEG_LIB_VERSION)
  167415. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167416. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167417. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167418. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167419. /* For debugging purposes, we zero the whole master structure.
  167420. * But the application has already set the err pointer, and may have set
  167421. * client_data, so we have to save and restore those fields.
  167422. * Note: if application hasn't set client_data, tools like Purify may
  167423. * complain here.
  167424. */
  167425. {
  167426. struct jpeg_error_mgr * err = cinfo->err;
  167427. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167428. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167429. cinfo->err = err;
  167430. cinfo->client_data = client_data;
  167431. }
  167432. cinfo->is_decompressor = TRUE;
  167433. /* Initialize a memory manager instance for this object */
  167434. jinit_memory_mgr((j_common_ptr) cinfo);
  167435. /* Zero out pointers to permanent structures. */
  167436. cinfo->progress = NULL;
  167437. cinfo->src = NULL;
  167438. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167439. cinfo->quant_tbl_ptrs[i] = NULL;
  167440. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167441. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167442. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167443. }
  167444. /* Initialize marker processor so application can override methods
  167445. * for COM, APPn markers before calling jpeg_read_header.
  167446. */
  167447. cinfo->marker_list = NULL;
  167448. jinit_marker_reader(cinfo);
  167449. /* And initialize the overall input controller. */
  167450. jinit_input_controller(cinfo);
  167451. /* OK, I'm ready */
  167452. cinfo->global_state = DSTATE_START;
  167453. }
  167454. /*
  167455. * Destruction of a JPEG decompression object
  167456. */
  167457. GLOBAL(void)
  167458. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167459. {
  167460. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167461. }
  167462. /*
  167463. * Abort processing of a JPEG decompression operation,
  167464. * but don't destroy the object itself.
  167465. */
  167466. GLOBAL(void)
  167467. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167468. {
  167469. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167470. }
  167471. /*
  167472. * Set default decompression parameters.
  167473. */
  167474. LOCAL(void)
  167475. default_decompress_parms (j_decompress_ptr cinfo)
  167476. {
  167477. /* Guess the input colorspace, and set output colorspace accordingly. */
  167478. /* (Wish JPEG committee had provided a real way to specify this...) */
  167479. /* Note application may override our guesses. */
  167480. switch (cinfo->num_components) {
  167481. case 1:
  167482. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167483. cinfo->out_color_space = JCS_GRAYSCALE;
  167484. break;
  167485. case 3:
  167486. if (cinfo->saw_JFIF_marker) {
  167487. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  167488. } else if (cinfo->saw_Adobe_marker) {
  167489. switch (cinfo->Adobe_transform) {
  167490. case 0:
  167491. cinfo->jpeg_color_space = JCS_RGB;
  167492. break;
  167493. case 1:
  167494. cinfo->jpeg_color_space = JCS_YCbCr;
  167495. break;
  167496. default:
  167497. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167498. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167499. break;
  167500. }
  167501. } else {
  167502. /* Saw no special markers, try to guess from the component IDs */
  167503. int cid0 = cinfo->comp_info[0].component_id;
  167504. int cid1 = cinfo->comp_info[1].component_id;
  167505. int cid2 = cinfo->comp_info[2].component_id;
  167506. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  167507. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  167508. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  167509. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  167510. else {
  167511. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  167512. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167513. }
  167514. }
  167515. /* Always guess RGB is proper output colorspace. */
  167516. cinfo->out_color_space = JCS_RGB;
  167517. break;
  167518. case 4:
  167519. if (cinfo->saw_Adobe_marker) {
  167520. switch (cinfo->Adobe_transform) {
  167521. case 0:
  167522. cinfo->jpeg_color_space = JCS_CMYK;
  167523. break;
  167524. case 2:
  167525. cinfo->jpeg_color_space = JCS_YCCK;
  167526. break;
  167527. default:
  167528. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167529. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  167530. break;
  167531. }
  167532. } else {
  167533. /* No special markers, assume straight CMYK. */
  167534. cinfo->jpeg_color_space = JCS_CMYK;
  167535. }
  167536. cinfo->out_color_space = JCS_CMYK;
  167537. break;
  167538. default:
  167539. cinfo->jpeg_color_space = JCS_UNKNOWN;
  167540. cinfo->out_color_space = JCS_UNKNOWN;
  167541. break;
  167542. }
  167543. /* Set defaults for other decompression parameters. */
  167544. cinfo->scale_num = 1; /* 1:1 scaling */
  167545. cinfo->scale_denom = 1;
  167546. cinfo->output_gamma = 1.0;
  167547. cinfo->buffered_image = FALSE;
  167548. cinfo->raw_data_out = FALSE;
  167549. cinfo->dct_method = JDCT_DEFAULT;
  167550. cinfo->do_fancy_upsampling = TRUE;
  167551. cinfo->do_block_smoothing = TRUE;
  167552. cinfo->quantize_colors = FALSE;
  167553. /* We set these in case application only sets quantize_colors. */
  167554. cinfo->dither_mode = JDITHER_FS;
  167555. #ifdef QUANT_2PASS_SUPPORTED
  167556. cinfo->two_pass_quantize = TRUE;
  167557. #else
  167558. cinfo->two_pass_quantize = FALSE;
  167559. #endif
  167560. cinfo->desired_number_of_colors = 256;
  167561. cinfo->colormap = NULL;
  167562. /* Initialize for no mode change in buffered-image mode. */
  167563. cinfo->enable_1pass_quant = FALSE;
  167564. cinfo->enable_external_quant = FALSE;
  167565. cinfo->enable_2pass_quant = FALSE;
  167566. }
  167567. /*
  167568. * Decompression startup: read start of JPEG datastream to see what's there.
  167569. * Need only initialize JPEG object and supply a data source before calling.
  167570. *
  167571. * This routine will read as far as the first SOS marker (ie, actual start of
  167572. * compressed data), and will save all tables and parameters in the JPEG
  167573. * object. It will also initialize the decompression parameters to default
  167574. * values, and finally return JPEG_HEADER_OK. On return, the application may
  167575. * adjust the decompression parameters and then call jpeg_start_decompress.
  167576. * (Or, if the application only wanted to determine the image parameters,
  167577. * the data need not be decompressed. In that case, call jpeg_abort or
  167578. * jpeg_destroy to release any temporary space.)
  167579. * If an abbreviated (tables only) datastream is presented, the routine will
  167580. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  167581. * re-use the JPEG object to read the abbreviated image datastream(s).
  167582. * It is unnecessary (but OK) to call jpeg_abort in this case.
  167583. * The JPEG_SUSPENDED return code only occurs if the data source module
  167584. * requests suspension of the decompressor. In this case the application
  167585. * should load more source data and then re-call jpeg_read_header to resume
  167586. * processing.
  167587. * If a non-suspending data source is used and require_image is TRUE, then the
  167588. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  167589. *
  167590. * This routine is now just a front end to jpeg_consume_input, with some
  167591. * extra error checking.
  167592. */
  167593. GLOBAL(int)
  167594. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  167595. {
  167596. int retcode;
  167597. if (cinfo->global_state != DSTATE_START &&
  167598. cinfo->global_state != DSTATE_INHEADER)
  167599. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167600. retcode = jpeg_consume_input(cinfo);
  167601. switch (retcode) {
  167602. case JPEG_REACHED_SOS:
  167603. retcode = JPEG_HEADER_OK;
  167604. break;
  167605. case JPEG_REACHED_EOI:
  167606. if (require_image) /* Complain if application wanted an image */
  167607. ERREXIT(cinfo, JERR_NO_IMAGE);
  167608. /* Reset to start state; it would be safer to require the application to
  167609. * call jpeg_abort, but we can't change it now for compatibility reasons.
  167610. * A side effect is to free any temporary memory (there shouldn't be any).
  167611. */
  167612. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  167613. retcode = JPEG_HEADER_TABLES_ONLY;
  167614. break;
  167615. case JPEG_SUSPENDED:
  167616. /* no work */
  167617. break;
  167618. }
  167619. return retcode;
  167620. }
  167621. /*
  167622. * Consume data in advance of what the decompressor requires.
  167623. * This can be called at any time once the decompressor object has
  167624. * been created and a data source has been set up.
  167625. *
  167626. * This routine is essentially a state machine that handles a couple
  167627. * of critical state-transition actions, namely initial setup and
  167628. * transition from header scanning to ready-for-start_decompress.
  167629. * All the actual input is done via the input controller's consume_input
  167630. * method.
  167631. */
  167632. GLOBAL(int)
  167633. jpeg_consume_input (j_decompress_ptr cinfo)
  167634. {
  167635. int retcode = JPEG_SUSPENDED;
  167636. /* NB: every possible DSTATE value should be listed in this switch */
  167637. switch (cinfo->global_state) {
  167638. case DSTATE_START:
  167639. /* Start-of-datastream actions: reset appropriate modules */
  167640. (*cinfo->inputctl->reset_input_controller) (cinfo);
  167641. /* Initialize application's data source module */
  167642. (*cinfo->src->init_source) (cinfo);
  167643. cinfo->global_state = DSTATE_INHEADER;
  167644. /*FALLTHROUGH*/
  167645. case DSTATE_INHEADER:
  167646. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167647. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  167648. /* Set up default parameters based on header data */
  167649. default_decompress_parms(cinfo);
  167650. /* Set global state: ready for start_decompress */
  167651. cinfo->global_state = DSTATE_READY;
  167652. }
  167653. break;
  167654. case DSTATE_READY:
  167655. /* Can't advance past first SOS until start_decompress is called */
  167656. retcode = JPEG_REACHED_SOS;
  167657. break;
  167658. case DSTATE_PRELOAD:
  167659. case DSTATE_PRESCAN:
  167660. case DSTATE_SCANNING:
  167661. case DSTATE_RAW_OK:
  167662. case DSTATE_BUFIMAGE:
  167663. case DSTATE_BUFPOST:
  167664. case DSTATE_STOPPING:
  167665. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167666. break;
  167667. default:
  167668. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167669. }
  167670. return retcode;
  167671. }
  167672. /*
  167673. * Have we finished reading the input file?
  167674. */
  167675. GLOBAL(boolean)
  167676. jpeg_input_complete (j_decompress_ptr cinfo)
  167677. {
  167678. /* Check for valid jpeg object */
  167679. if (cinfo->global_state < DSTATE_START ||
  167680. cinfo->global_state > DSTATE_STOPPING)
  167681. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167682. return cinfo->inputctl->eoi_reached;
  167683. }
  167684. /*
  167685. * Is there more than one scan?
  167686. */
  167687. GLOBAL(boolean)
  167688. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  167689. {
  167690. /* Only valid after jpeg_read_header completes */
  167691. if (cinfo->global_state < DSTATE_READY ||
  167692. cinfo->global_state > DSTATE_STOPPING)
  167693. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167694. return cinfo->inputctl->has_multiple_scans;
  167695. }
  167696. /*
  167697. * Finish JPEG decompression.
  167698. *
  167699. * This will normally just verify the file trailer and release temp storage.
  167700. *
  167701. * Returns FALSE if suspended. The return value need be inspected only if
  167702. * a suspending data source is used.
  167703. */
  167704. GLOBAL(boolean)
  167705. jpeg_finish_decompress (j_decompress_ptr cinfo)
  167706. {
  167707. if ((cinfo->global_state == DSTATE_SCANNING ||
  167708. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  167709. /* Terminate final pass of non-buffered mode */
  167710. if (cinfo->output_scanline < cinfo->output_height)
  167711. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  167712. (*cinfo->master->finish_output_pass) (cinfo);
  167713. cinfo->global_state = DSTATE_STOPPING;
  167714. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  167715. /* Finishing after a buffered-image operation */
  167716. cinfo->global_state = DSTATE_STOPPING;
  167717. } else if (cinfo->global_state != DSTATE_STOPPING) {
  167718. /* STOPPING = repeat call after a suspension, anything else is error */
  167719. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167720. }
  167721. /* Read until EOI */
  167722. while (! cinfo->inputctl->eoi_reached) {
  167723. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167724. return FALSE; /* Suspend, come back later */
  167725. }
  167726. /* Do final cleanup */
  167727. (*cinfo->src->term_source) (cinfo);
  167728. /* We can use jpeg_abort to release memory and reset global_state */
  167729. jpeg_abort((j_common_ptr) cinfo);
  167730. return TRUE;
  167731. }
  167732. /*** End of inlined file: jdapimin.c ***/
  167733. /*** Start of inlined file: jdatasrc.c ***/
  167734. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  167735. /*** Start of inlined file: jerror.h ***/
  167736. /*
  167737. * To define the enum list of message codes, include this file without
  167738. * defining macro JMESSAGE. To create a message string table, include it
  167739. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  167740. */
  167741. #ifndef JMESSAGE
  167742. #ifndef JERROR_H
  167743. /* First time through, define the enum list */
  167744. #define JMAKE_ENUM_LIST
  167745. #else
  167746. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  167747. #define JMESSAGE(code,string)
  167748. #endif /* JERROR_H */
  167749. #endif /* JMESSAGE */
  167750. #ifdef JMAKE_ENUM_LIST
  167751. typedef enum {
  167752. #define JMESSAGE(code,string) code ,
  167753. #endif /* JMAKE_ENUM_LIST */
  167754. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  167755. /* For maintenance convenience, list is alphabetical by message code name */
  167756. JMESSAGE(JERR_ARITH_NOTIMPL,
  167757. "Sorry, there are legal restrictions on arithmetic coding")
  167758. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  167759. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  167760. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  167761. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  167762. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  167763. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  167764. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  167765. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  167766. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  167767. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  167768. JMESSAGE(JERR_BAD_LIB_VERSION,
  167769. "Wrong JPEG library version: library is %d, caller expects %d")
  167770. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  167771. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  167772. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  167773. JMESSAGE(JERR_BAD_PROGRESSION,
  167774. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  167775. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  167776. "Invalid progressive parameters at scan script entry %d")
  167777. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  167778. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  167779. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  167780. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  167781. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  167782. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  167783. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  167784. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  167785. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  167786. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  167787. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  167788. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  167789. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  167790. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  167791. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  167792. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  167793. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  167794. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  167795. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  167796. JMESSAGE(JERR_FILE_READ, "Input file read error")
  167797. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  167798. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  167799. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  167800. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  167801. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  167802. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  167803. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  167804. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  167805. "Cannot transcode due to multiple use of quantization table %d")
  167806. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  167807. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  167808. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  167809. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  167810. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  167811. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  167812. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  167813. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  167814. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  167815. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  167816. JMESSAGE(JERR_QUANT_COMPONENTS,
  167817. "Cannot quantize more than %d color components")
  167818. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  167819. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  167820. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  167821. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  167822. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  167823. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  167824. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  167825. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  167826. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  167827. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  167828. JMESSAGE(JERR_TFILE_WRITE,
  167829. "Write failed on temporary file --- out of disk space?")
  167830. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  167831. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  167832. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  167833. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  167834. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  167835. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  167836. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  167837. JMESSAGE(JMSG_VERSION, JVERSION)
  167838. JMESSAGE(JTRC_16BIT_TABLES,
  167839. "Caution: quantization tables are too coarse for baseline JPEG")
  167840. JMESSAGE(JTRC_ADOBE,
  167841. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  167842. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  167843. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  167844. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  167845. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  167846. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  167847. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  167848. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  167849. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  167850. JMESSAGE(JTRC_EOI, "End Of Image")
  167851. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  167852. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  167853. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  167854. "Warning: thumbnail image size does not match data length %u")
  167855. JMESSAGE(JTRC_JFIF_EXTENSION,
  167856. "JFIF extension marker: type 0x%02x, length %u")
  167857. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  167858. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  167859. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  167860. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  167861. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  167862. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  167863. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  167864. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  167865. JMESSAGE(JTRC_RST, "RST%d")
  167866. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  167867. "Smoothing not supported with nonstandard sampling ratios")
  167868. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  167869. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  167870. JMESSAGE(JTRC_SOI, "Start of Image")
  167871. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  167872. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  167873. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  167874. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  167875. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  167876. JMESSAGE(JTRC_THUMB_JPEG,
  167877. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  167878. JMESSAGE(JTRC_THUMB_PALETTE,
  167879. "JFIF extension marker: palette thumbnail image, length %u")
  167880. JMESSAGE(JTRC_THUMB_RGB,
  167881. "JFIF extension marker: RGB thumbnail image, length %u")
  167882. JMESSAGE(JTRC_UNKNOWN_IDS,
  167883. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  167884. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  167885. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  167886. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  167887. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  167888. "Inconsistent progression sequence for component %d coefficient %d")
  167889. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  167890. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  167891. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  167892. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  167893. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  167894. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  167895. JMESSAGE(JWRN_MUST_RESYNC,
  167896. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  167897. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  167898. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  167899. #ifdef JMAKE_ENUM_LIST
  167900. JMSG_LASTMSGCODE
  167901. } J_MESSAGE_CODE;
  167902. #undef JMAKE_ENUM_LIST
  167903. #endif /* JMAKE_ENUM_LIST */
  167904. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  167905. #undef JMESSAGE
  167906. #ifndef JERROR_H
  167907. #define JERROR_H
  167908. /* Macros to simplify using the error and trace message stuff */
  167909. /* The first parameter is either type of cinfo pointer */
  167910. /* Fatal errors (print message and exit) */
  167911. #define ERREXIT(cinfo,code) \
  167912. ((cinfo)->err->msg_code = (code), \
  167913. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167914. #define ERREXIT1(cinfo,code,p1) \
  167915. ((cinfo)->err->msg_code = (code), \
  167916. (cinfo)->err->msg_parm.i[0] = (p1), \
  167917. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167918. #define ERREXIT2(cinfo,code,p1,p2) \
  167919. ((cinfo)->err->msg_code = (code), \
  167920. (cinfo)->err->msg_parm.i[0] = (p1), \
  167921. (cinfo)->err->msg_parm.i[1] = (p2), \
  167922. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167923. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  167924. ((cinfo)->err->msg_code = (code), \
  167925. (cinfo)->err->msg_parm.i[0] = (p1), \
  167926. (cinfo)->err->msg_parm.i[1] = (p2), \
  167927. (cinfo)->err->msg_parm.i[2] = (p3), \
  167928. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167929. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  167930. ((cinfo)->err->msg_code = (code), \
  167931. (cinfo)->err->msg_parm.i[0] = (p1), \
  167932. (cinfo)->err->msg_parm.i[1] = (p2), \
  167933. (cinfo)->err->msg_parm.i[2] = (p3), \
  167934. (cinfo)->err->msg_parm.i[3] = (p4), \
  167935. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167936. #define ERREXITS(cinfo,code,str) \
  167937. ((cinfo)->err->msg_code = (code), \
  167938. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167939. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167940. #define MAKESTMT(stuff) do { stuff } while (0)
  167941. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  167942. #define WARNMS(cinfo,code) \
  167943. ((cinfo)->err->msg_code = (code), \
  167944. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167945. #define WARNMS1(cinfo,code,p1) \
  167946. ((cinfo)->err->msg_code = (code), \
  167947. (cinfo)->err->msg_parm.i[0] = (p1), \
  167948. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167949. #define WARNMS2(cinfo,code,p1,p2) \
  167950. ((cinfo)->err->msg_code = (code), \
  167951. (cinfo)->err->msg_parm.i[0] = (p1), \
  167952. (cinfo)->err->msg_parm.i[1] = (p2), \
  167953. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167954. /* Informational/debugging messages */
  167955. #define TRACEMS(cinfo,lvl,code) \
  167956. ((cinfo)->err->msg_code = (code), \
  167957. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167958. #define TRACEMS1(cinfo,lvl,code,p1) \
  167959. ((cinfo)->err->msg_code = (code), \
  167960. (cinfo)->err->msg_parm.i[0] = (p1), \
  167961. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167962. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  167963. ((cinfo)->err->msg_code = (code), \
  167964. (cinfo)->err->msg_parm.i[0] = (p1), \
  167965. (cinfo)->err->msg_parm.i[1] = (p2), \
  167966. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167967. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  167968. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167969. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  167970. (cinfo)->err->msg_code = (code); \
  167971. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167972. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  167973. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167974. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167975. (cinfo)->err->msg_code = (code); \
  167976. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167977. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  167978. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167979. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167980. _mp[4] = (p5); \
  167981. (cinfo)->err->msg_code = (code); \
  167982. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167983. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  167984. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167985. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167986. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  167987. (cinfo)->err->msg_code = (code); \
  167988. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167989. #define TRACEMSS(cinfo,lvl,code,str) \
  167990. ((cinfo)->err->msg_code = (code), \
  167991. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167992. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167993. #endif /* JERROR_H */
  167994. /*** End of inlined file: jerror.h ***/
  167995. /* Expanded data source object for stdio input */
  167996. typedef struct {
  167997. struct jpeg_source_mgr pub; /* public fields */
  167998. FILE * infile; /* source stream */
  167999. JOCTET * buffer; /* start of buffer */
  168000. boolean start_of_file; /* have we gotten any data yet? */
  168001. } my_source_mgr;
  168002. typedef my_source_mgr * my_src_ptr;
  168003. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  168004. /*
  168005. * Initialize source --- called by jpeg_read_header
  168006. * before any data is actually read.
  168007. */
  168008. METHODDEF(void)
  168009. init_source (j_decompress_ptr cinfo)
  168010. {
  168011. my_src_ptr src = (my_src_ptr) cinfo->src;
  168012. /* We reset the empty-input-file flag for each image,
  168013. * but we don't clear the input buffer.
  168014. * This is correct behavior for reading a series of images from one source.
  168015. */
  168016. src->start_of_file = TRUE;
  168017. }
  168018. /*
  168019. * Fill the input buffer --- called whenever buffer is emptied.
  168020. *
  168021. * In typical applications, this should read fresh data into the buffer
  168022. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168023. * reset the pointer & count to the start of the buffer, and return TRUE
  168024. * indicating that the buffer has been reloaded. It is not necessary to
  168025. * fill the buffer entirely, only to obtain at least one more byte.
  168026. *
  168027. * There is no such thing as an EOF return. If the end of the file has been
  168028. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168029. * the buffer. In most cases, generating a warning message and inserting a
  168030. * fake EOI marker is the best course of action --- this will allow the
  168031. * decompressor to output however much of the image is there. However,
  168032. * the resulting error message is misleading if the real problem is an empty
  168033. * input file, so we handle that case specially.
  168034. *
  168035. * In applications that need to be able to suspend compression due to input
  168036. * not being available yet, a FALSE return indicates that no more data can be
  168037. * obtained right now, but more may be forthcoming later. In this situation,
  168038. * the decompressor will return to its caller (with an indication of the
  168039. * number of scanlines it has read, if any). The application should resume
  168040. * decompression after it has loaded more data into the input buffer. Note
  168041. * that there are substantial restrictions on the use of suspension --- see
  168042. * the documentation.
  168043. *
  168044. * When suspending, the decompressor will back up to a convenient restart point
  168045. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168046. * indicate where the restart point will be if the current call returns FALSE.
  168047. * Data beyond this point must be rescanned after resumption, so move it to
  168048. * the front of the buffer rather than discarding it.
  168049. */
  168050. METHODDEF(boolean)
  168051. fill_input_buffer (j_decompress_ptr cinfo)
  168052. {
  168053. my_src_ptr src = (my_src_ptr) cinfo->src;
  168054. size_t nbytes;
  168055. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168056. if (nbytes <= 0) {
  168057. if (src->start_of_file) /* Treat empty input file as fatal error */
  168058. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168059. WARNMS(cinfo, JWRN_JPEG_EOF);
  168060. /* Insert a fake EOI marker */
  168061. src->buffer[0] = (JOCTET) 0xFF;
  168062. src->buffer[1] = (JOCTET) JPEG_EOI;
  168063. nbytes = 2;
  168064. }
  168065. src->pub.next_input_byte = src->buffer;
  168066. src->pub.bytes_in_buffer = nbytes;
  168067. src->start_of_file = FALSE;
  168068. return TRUE;
  168069. }
  168070. /*
  168071. * Skip data --- used to skip over a potentially large amount of
  168072. * uninteresting data (such as an APPn marker).
  168073. *
  168074. * Writers of suspendable-input applications must note that skip_input_data
  168075. * is not granted the right to give a suspension return. If the skip extends
  168076. * beyond the data currently in the buffer, the buffer can be marked empty so
  168077. * that the next read will cause a fill_input_buffer call that can suspend.
  168078. * Arranging for additional bytes to be discarded before reloading the input
  168079. * buffer is the application writer's problem.
  168080. */
  168081. METHODDEF(void)
  168082. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168083. {
  168084. my_src_ptr src = (my_src_ptr) cinfo->src;
  168085. /* Just a dumb implementation for now. Could use fseek() except
  168086. * it doesn't work on pipes. Not clear that being smart is worth
  168087. * any trouble anyway --- large skips are infrequent.
  168088. */
  168089. if (num_bytes > 0) {
  168090. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168091. num_bytes -= (long) src->pub.bytes_in_buffer;
  168092. (void) fill_input_buffer(cinfo);
  168093. /* note we assume that fill_input_buffer will never return FALSE,
  168094. * so suspension need not be handled.
  168095. */
  168096. }
  168097. src->pub.next_input_byte += (size_t) num_bytes;
  168098. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168099. }
  168100. }
  168101. /*
  168102. * An additional method that can be provided by data source modules is the
  168103. * resync_to_restart method for error recovery in the presence of RST markers.
  168104. * For the moment, this source module just uses the default resync method
  168105. * provided by the JPEG library. That method assumes that no backtracking
  168106. * is possible.
  168107. */
  168108. /*
  168109. * Terminate source --- called by jpeg_finish_decompress
  168110. * after all data has been read. Often a no-op.
  168111. *
  168112. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168113. * application must deal with any cleanup that should happen even
  168114. * for error exit.
  168115. */
  168116. METHODDEF(void)
  168117. term_source (j_decompress_ptr)
  168118. {
  168119. /* no work necessary here */
  168120. }
  168121. /*
  168122. * Prepare for input from a stdio stream.
  168123. * The caller must have already opened the stream, and is responsible
  168124. * for closing it after finishing decompression.
  168125. */
  168126. GLOBAL(void)
  168127. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168128. {
  168129. my_src_ptr src;
  168130. /* The source object and input buffer are made permanent so that a series
  168131. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168132. * only before the first one. (If we discarded the buffer at the end of
  168133. * one image, we'd likely lose the start of the next one.)
  168134. * This makes it unsafe to use this manager and a different source
  168135. * manager serially with the same JPEG object. Caveat programmer.
  168136. */
  168137. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168138. cinfo->src = (struct jpeg_source_mgr *)
  168139. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168140. SIZEOF(my_source_mgr));
  168141. src = (my_src_ptr) cinfo->src;
  168142. src->buffer = (JOCTET *)
  168143. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168144. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168145. }
  168146. src = (my_src_ptr) cinfo->src;
  168147. src->pub.init_source = init_source;
  168148. src->pub.fill_input_buffer = fill_input_buffer;
  168149. src->pub.skip_input_data = skip_input_data;
  168150. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168151. src->pub.term_source = term_source;
  168152. src->infile = infile;
  168153. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168154. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168155. }
  168156. /*** End of inlined file: jdatasrc.c ***/
  168157. /*** Start of inlined file: jdcoefct.c ***/
  168158. #define JPEG_INTERNALS
  168159. /* Block smoothing is only applicable for progressive JPEG, so: */
  168160. #ifndef D_PROGRESSIVE_SUPPORTED
  168161. #undef BLOCK_SMOOTHING_SUPPORTED
  168162. #endif
  168163. /* Private buffer controller object */
  168164. typedef struct {
  168165. struct jpeg_d_coef_controller pub; /* public fields */
  168166. /* These variables keep track of the current location of the input side. */
  168167. /* cinfo->input_iMCU_row is also used for this. */
  168168. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168169. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168170. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168171. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168172. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168173. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168174. * and let the entropy decoder write into that workspace each time.
  168175. * (On 80x86, the workspace is FAR even though it's not really very big;
  168176. * this is to keep the module interfaces unchanged when a large coefficient
  168177. * buffer is necessary.)
  168178. * In multi-pass modes, this array points to the current MCU's blocks
  168179. * within the virtual arrays; it is used only by the input side.
  168180. */
  168181. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168182. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168183. /* In multi-pass modes, we need a virtual block array for each component. */
  168184. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168185. #endif
  168186. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168187. /* When doing block smoothing, we latch coefficient Al values here */
  168188. int * coef_bits_latch;
  168189. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168190. #endif
  168191. } my_coef_controller3;
  168192. typedef my_coef_controller3 * my_coef_ptr3;
  168193. /* Forward declarations */
  168194. METHODDEF(int) decompress_onepass
  168195. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168196. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168197. METHODDEF(int) decompress_data
  168198. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168199. #endif
  168200. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168201. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168202. METHODDEF(int) decompress_smooth_data
  168203. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168204. #endif
  168205. LOCAL(void)
  168206. start_iMCU_row3 (j_decompress_ptr cinfo)
  168207. /* Reset within-iMCU-row counters for a new row (input side) */
  168208. {
  168209. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168210. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168211. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168212. * But at the bottom of the image, process only what's left.
  168213. */
  168214. if (cinfo->comps_in_scan > 1) {
  168215. coef->MCU_rows_per_iMCU_row = 1;
  168216. } else {
  168217. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168218. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168219. else
  168220. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168221. }
  168222. coef->MCU_ctr = 0;
  168223. coef->MCU_vert_offset = 0;
  168224. }
  168225. /*
  168226. * Initialize for an input processing pass.
  168227. */
  168228. METHODDEF(void)
  168229. start_input_pass (j_decompress_ptr cinfo)
  168230. {
  168231. cinfo->input_iMCU_row = 0;
  168232. start_iMCU_row3(cinfo);
  168233. }
  168234. /*
  168235. * Initialize for an output processing pass.
  168236. */
  168237. METHODDEF(void)
  168238. start_output_pass (j_decompress_ptr cinfo)
  168239. {
  168240. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168241. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168242. /* If multipass, check to see whether to use block smoothing on this pass */
  168243. if (coef->pub.coef_arrays != NULL) {
  168244. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168245. coef->pub.decompress_data = decompress_smooth_data;
  168246. else
  168247. coef->pub.decompress_data = decompress_data;
  168248. }
  168249. #endif
  168250. cinfo->output_iMCU_row = 0;
  168251. }
  168252. /*
  168253. * Decompress and return some data in the single-pass case.
  168254. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168255. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168256. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168257. *
  168258. * NB: output_buf contains a plane for each component in image,
  168259. * which we index according to the component's SOF position.
  168260. */
  168261. METHODDEF(int)
  168262. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168263. {
  168264. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168265. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168266. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168267. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168268. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168269. JSAMPARRAY output_ptr;
  168270. JDIMENSION start_col, output_col;
  168271. jpeg_component_info *compptr;
  168272. inverse_DCT_method_ptr inverse_DCT;
  168273. /* Loop to process as much as one whole iMCU row */
  168274. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168275. yoffset++) {
  168276. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168277. MCU_col_num++) {
  168278. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168279. jzero_far((void FAR *) coef->MCU_buffer[0],
  168280. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168281. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168282. /* Suspension forced; update state counters and exit */
  168283. coef->MCU_vert_offset = yoffset;
  168284. coef->MCU_ctr = MCU_col_num;
  168285. return JPEG_SUSPENDED;
  168286. }
  168287. /* Determine where data should go in output_buf and do the IDCT thing.
  168288. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168289. * incremented past them!). Note the inner loop relies on having
  168290. * allocated the MCU_buffer[] blocks sequentially.
  168291. */
  168292. blkn = 0; /* index of current DCT block within MCU */
  168293. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168294. compptr = cinfo->cur_comp_info[ci];
  168295. /* Don't bother to IDCT an uninteresting component. */
  168296. if (! compptr->component_needed) {
  168297. blkn += compptr->MCU_blocks;
  168298. continue;
  168299. }
  168300. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168301. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168302. : compptr->last_col_width;
  168303. output_ptr = output_buf[compptr->component_index] +
  168304. yoffset * compptr->DCT_scaled_size;
  168305. start_col = MCU_col_num * compptr->MCU_sample_width;
  168306. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168307. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168308. yoffset+yindex < compptr->last_row_height) {
  168309. output_col = start_col;
  168310. for (xindex = 0; xindex < useful_width; xindex++) {
  168311. (*inverse_DCT) (cinfo, compptr,
  168312. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168313. output_ptr, output_col);
  168314. output_col += compptr->DCT_scaled_size;
  168315. }
  168316. }
  168317. blkn += compptr->MCU_width;
  168318. output_ptr += compptr->DCT_scaled_size;
  168319. }
  168320. }
  168321. }
  168322. /* Completed an MCU row, but perhaps not an iMCU row */
  168323. coef->MCU_ctr = 0;
  168324. }
  168325. /* Completed the iMCU row, advance counters for next one */
  168326. cinfo->output_iMCU_row++;
  168327. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168328. start_iMCU_row3(cinfo);
  168329. return JPEG_ROW_COMPLETED;
  168330. }
  168331. /* Completed the scan */
  168332. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168333. return JPEG_SCAN_COMPLETED;
  168334. }
  168335. /*
  168336. * Dummy consume-input routine for single-pass operation.
  168337. */
  168338. METHODDEF(int)
  168339. dummy_consume_data (j_decompress_ptr)
  168340. {
  168341. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168342. }
  168343. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168344. /*
  168345. * Consume input data and store it in the full-image coefficient buffer.
  168346. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168347. * ie, v_samp_factor block rows for each component in the scan.
  168348. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168349. */
  168350. METHODDEF(int)
  168351. consume_data (j_decompress_ptr cinfo)
  168352. {
  168353. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168354. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168355. int blkn, ci, xindex, yindex, yoffset;
  168356. JDIMENSION start_col;
  168357. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168358. JBLOCKROW buffer_ptr;
  168359. jpeg_component_info *compptr;
  168360. /* Align the virtual buffers for the components used in this scan. */
  168361. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168362. compptr = cinfo->cur_comp_info[ci];
  168363. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168364. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168365. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168366. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168367. /* Note: entropy decoder expects buffer to be zeroed,
  168368. * but this is handled automatically by the memory manager
  168369. * because we requested a pre-zeroed array.
  168370. */
  168371. }
  168372. /* Loop to process one whole iMCU row */
  168373. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168374. yoffset++) {
  168375. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168376. MCU_col_num++) {
  168377. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168378. blkn = 0; /* index of current DCT block within MCU */
  168379. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168380. compptr = cinfo->cur_comp_info[ci];
  168381. start_col = MCU_col_num * compptr->MCU_width;
  168382. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168383. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168384. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168385. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168386. }
  168387. }
  168388. }
  168389. /* Try to fetch the MCU. */
  168390. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168391. /* Suspension forced; update state counters and exit */
  168392. coef->MCU_vert_offset = yoffset;
  168393. coef->MCU_ctr = MCU_col_num;
  168394. return JPEG_SUSPENDED;
  168395. }
  168396. }
  168397. /* Completed an MCU row, but perhaps not an iMCU row */
  168398. coef->MCU_ctr = 0;
  168399. }
  168400. /* Completed the iMCU row, advance counters for next one */
  168401. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168402. start_iMCU_row3(cinfo);
  168403. return JPEG_ROW_COMPLETED;
  168404. }
  168405. /* Completed the scan */
  168406. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168407. return JPEG_SCAN_COMPLETED;
  168408. }
  168409. /*
  168410. * Decompress and return some data in the multi-pass case.
  168411. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168412. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168413. *
  168414. * NB: output_buf contains a plane for each component in image.
  168415. */
  168416. METHODDEF(int)
  168417. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168418. {
  168419. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168420. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168421. JDIMENSION block_num;
  168422. int ci, block_row, block_rows;
  168423. JBLOCKARRAY buffer;
  168424. JBLOCKROW buffer_ptr;
  168425. JSAMPARRAY output_ptr;
  168426. JDIMENSION output_col;
  168427. jpeg_component_info *compptr;
  168428. inverse_DCT_method_ptr inverse_DCT;
  168429. /* Force some input to be done if we are getting ahead of the input. */
  168430. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168431. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168432. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168433. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168434. return JPEG_SUSPENDED;
  168435. }
  168436. /* OK, output from the virtual arrays. */
  168437. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168438. ci++, compptr++) {
  168439. /* Don't bother to IDCT an uninteresting component. */
  168440. if (! compptr->component_needed)
  168441. continue;
  168442. /* Align the virtual buffer for this component. */
  168443. buffer = (*cinfo->mem->access_virt_barray)
  168444. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168445. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168446. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168447. /* Count non-dummy DCT block rows in this iMCU row. */
  168448. if (cinfo->output_iMCU_row < last_iMCU_row)
  168449. block_rows = compptr->v_samp_factor;
  168450. else {
  168451. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168452. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168453. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168454. }
  168455. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168456. output_ptr = output_buf[ci];
  168457. /* Loop over all DCT blocks to be processed. */
  168458. for (block_row = 0; block_row < block_rows; block_row++) {
  168459. buffer_ptr = buffer[block_row];
  168460. output_col = 0;
  168461. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168462. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168463. output_ptr, output_col);
  168464. buffer_ptr++;
  168465. output_col += compptr->DCT_scaled_size;
  168466. }
  168467. output_ptr += compptr->DCT_scaled_size;
  168468. }
  168469. }
  168470. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168471. return JPEG_ROW_COMPLETED;
  168472. return JPEG_SCAN_COMPLETED;
  168473. }
  168474. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168475. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168476. /*
  168477. * This code applies interblock smoothing as described by section K.8
  168478. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168479. * the DC values of a DCT block and its 8 neighboring blocks.
  168480. * We apply smoothing only for progressive JPEG decoding, and only if
  168481. * the coefficients it can estimate are not yet known to full precision.
  168482. */
  168483. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168484. #define Q01_POS 1
  168485. #define Q10_POS 8
  168486. #define Q20_POS 16
  168487. #define Q11_POS 9
  168488. #define Q02_POS 2
  168489. /*
  168490. * Determine whether block smoothing is applicable and safe.
  168491. * We also latch the current states of the coef_bits[] entries for the
  168492. * AC coefficients; otherwise, if the input side of the decompressor
  168493. * advances into a new scan, we might think the coefficients are known
  168494. * more accurately than they really are.
  168495. */
  168496. LOCAL(boolean)
  168497. smoothing_ok (j_decompress_ptr cinfo)
  168498. {
  168499. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168500. boolean smoothing_useful = FALSE;
  168501. int ci, coefi;
  168502. jpeg_component_info *compptr;
  168503. JQUANT_TBL * qtable;
  168504. int * coef_bits;
  168505. int * coef_bits_latch;
  168506. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  168507. return FALSE;
  168508. /* Allocate latch area if not already done */
  168509. if (coef->coef_bits_latch == NULL)
  168510. coef->coef_bits_latch = (int *)
  168511. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168512. cinfo->num_components *
  168513. (SAVED_COEFS * SIZEOF(int)));
  168514. coef_bits_latch = coef->coef_bits_latch;
  168515. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168516. ci++, compptr++) {
  168517. /* All components' quantization values must already be latched. */
  168518. if ((qtable = compptr->quant_table) == NULL)
  168519. return FALSE;
  168520. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  168521. if (qtable->quantval[0] == 0 ||
  168522. qtable->quantval[Q01_POS] == 0 ||
  168523. qtable->quantval[Q10_POS] == 0 ||
  168524. qtable->quantval[Q20_POS] == 0 ||
  168525. qtable->quantval[Q11_POS] == 0 ||
  168526. qtable->quantval[Q02_POS] == 0)
  168527. return FALSE;
  168528. /* DC values must be at least partly known for all components. */
  168529. coef_bits = cinfo->coef_bits[ci];
  168530. if (coef_bits[0] < 0)
  168531. return FALSE;
  168532. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  168533. for (coefi = 1; coefi <= 5; coefi++) {
  168534. coef_bits_latch[coefi] = coef_bits[coefi];
  168535. if (coef_bits[coefi] != 0)
  168536. smoothing_useful = TRUE;
  168537. }
  168538. coef_bits_latch += SAVED_COEFS;
  168539. }
  168540. return smoothing_useful;
  168541. }
  168542. /*
  168543. * Variant of decompress_data for use when doing block smoothing.
  168544. */
  168545. METHODDEF(int)
  168546. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168547. {
  168548. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168549. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168550. JDIMENSION block_num, last_block_column;
  168551. int ci, block_row, block_rows, access_rows;
  168552. JBLOCKARRAY buffer;
  168553. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  168554. JSAMPARRAY output_ptr;
  168555. JDIMENSION output_col;
  168556. jpeg_component_info *compptr;
  168557. inverse_DCT_method_ptr inverse_DCT;
  168558. boolean first_row, last_row;
  168559. JBLOCK workspace;
  168560. int *coef_bits;
  168561. JQUANT_TBL *quanttbl;
  168562. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  168563. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  168564. int Al, pred;
  168565. /* Force some input to be done if we are getting ahead of the input. */
  168566. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168567. ! cinfo->inputctl->eoi_reached) {
  168568. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  168569. /* If input is working on current scan, we ordinarily want it to
  168570. * have completed the current row. But if input scan is DC,
  168571. * we want it to keep one row ahead so that next block row's DC
  168572. * values are up to date.
  168573. */
  168574. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  168575. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  168576. break;
  168577. }
  168578. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168579. return JPEG_SUSPENDED;
  168580. }
  168581. /* OK, output from the virtual arrays. */
  168582. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168583. ci++, compptr++) {
  168584. /* Don't bother to IDCT an uninteresting component. */
  168585. if (! compptr->component_needed)
  168586. continue;
  168587. /* Count non-dummy DCT block rows in this iMCU row. */
  168588. if (cinfo->output_iMCU_row < last_iMCU_row) {
  168589. block_rows = compptr->v_samp_factor;
  168590. access_rows = block_rows * 2; /* this and next iMCU row */
  168591. last_row = FALSE;
  168592. } else {
  168593. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168594. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168595. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168596. access_rows = block_rows; /* this iMCU row only */
  168597. last_row = TRUE;
  168598. }
  168599. /* Align the virtual buffer for this component. */
  168600. if (cinfo->output_iMCU_row > 0) {
  168601. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  168602. buffer = (*cinfo->mem->access_virt_barray)
  168603. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168604. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  168605. (JDIMENSION) access_rows, FALSE);
  168606. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  168607. first_row = FALSE;
  168608. } else {
  168609. buffer = (*cinfo->mem->access_virt_barray)
  168610. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168611. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  168612. first_row = TRUE;
  168613. }
  168614. /* Fetch component-dependent info */
  168615. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  168616. quanttbl = compptr->quant_table;
  168617. Q00 = quanttbl->quantval[0];
  168618. Q01 = quanttbl->quantval[Q01_POS];
  168619. Q10 = quanttbl->quantval[Q10_POS];
  168620. Q20 = quanttbl->quantval[Q20_POS];
  168621. Q11 = quanttbl->quantval[Q11_POS];
  168622. Q02 = quanttbl->quantval[Q02_POS];
  168623. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168624. output_ptr = output_buf[ci];
  168625. /* Loop over all DCT blocks to be processed. */
  168626. for (block_row = 0; block_row < block_rows; block_row++) {
  168627. buffer_ptr = buffer[block_row];
  168628. if (first_row && block_row == 0)
  168629. prev_block_row = buffer_ptr;
  168630. else
  168631. prev_block_row = buffer[block_row-1];
  168632. if (last_row && block_row == block_rows-1)
  168633. next_block_row = buffer_ptr;
  168634. else
  168635. next_block_row = buffer[block_row+1];
  168636. /* We fetch the surrounding DC values using a sliding-register approach.
  168637. * Initialize all nine here so as to do the right thing on narrow pics.
  168638. */
  168639. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  168640. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  168641. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  168642. output_col = 0;
  168643. last_block_column = compptr->width_in_blocks - 1;
  168644. for (block_num = 0; block_num <= last_block_column; block_num++) {
  168645. /* Fetch current DCT block into workspace so we can modify it. */
  168646. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  168647. /* Update DC values */
  168648. if (block_num < last_block_column) {
  168649. DC3 = (int) prev_block_row[1][0];
  168650. DC6 = (int) buffer_ptr[1][0];
  168651. DC9 = (int) next_block_row[1][0];
  168652. }
  168653. /* Compute coefficient estimates per K.8.
  168654. * An estimate is applied only if coefficient is still zero,
  168655. * and is not known to be fully accurate.
  168656. */
  168657. /* AC01 */
  168658. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  168659. num = 36 * Q00 * (DC4 - DC6);
  168660. if (num >= 0) {
  168661. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  168662. if (Al > 0 && pred >= (1<<Al))
  168663. pred = (1<<Al)-1;
  168664. } else {
  168665. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  168666. if (Al > 0 && pred >= (1<<Al))
  168667. pred = (1<<Al)-1;
  168668. pred = -pred;
  168669. }
  168670. workspace[1] = (JCOEF) pred;
  168671. }
  168672. /* AC10 */
  168673. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  168674. num = 36 * Q00 * (DC2 - DC8);
  168675. if (num >= 0) {
  168676. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  168677. if (Al > 0 && pred >= (1<<Al))
  168678. pred = (1<<Al)-1;
  168679. } else {
  168680. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  168681. if (Al > 0 && pred >= (1<<Al))
  168682. pred = (1<<Al)-1;
  168683. pred = -pred;
  168684. }
  168685. workspace[8] = (JCOEF) pred;
  168686. }
  168687. /* AC20 */
  168688. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  168689. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  168690. if (num >= 0) {
  168691. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  168692. if (Al > 0 && pred >= (1<<Al))
  168693. pred = (1<<Al)-1;
  168694. } else {
  168695. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  168696. if (Al > 0 && pred >= (1<<Al))
  168697. pred = (1<<Al)-1;
  168698. pred = -pred;
  168699. }
  168700. workspace[16] = (JCOEF) pred;
  168701. }
  168702. /* AC11 */
  168703. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  168704. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  168705. if (num >= 0) {
  168706. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  168707. if (Al > 0 && pred >= (1<<Al))
  168708. pred = (1<<Al)-1;
  168709. } else {
  168710. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  168711. if (Al > 0 && pred >= (1<<Al))
  168712. pred = (1<<Al)-1;
  168713. pred = -pred;
  168714. }
  168715. workspace[9] = (JCOEF) pred;
  168716. }
  168717. /* AC02 */
  168718. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  168719. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  168720. if (num >= 0) {
  168721. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  168722. if (Al > 0 && pred >= (1<<Al))
  168723. pred = (1<<Al)-1;
  168724. } else {
  168725. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  168726. if (Al > 0 && pred >= (1<<Al))
  168727. pred = (1<<Al)-1;
  168728. pred = -pred;
  168729. }
  168730. workspace[2] = (JCOEF) pred;
  168731. }
  168732. /* OK, do the IDCT */
  168733. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  168734. output_ptr, output_col);
  168735. /* Advance for next column */
  168736. DC1 = DC2; DC2 = DC3;
  168737. DC4 = DC5; DC5 = DC6;
  168738. DC7 = DC8; DC8 = DC9;
  168739. buffer_ptr++, prev_block_row++, next_block_row++;
  168740. output_col += compptr->DCT_scaled_size;
  168741. }
  168742. output_ptr += compptr->DCT_scaled_size;
  168743. }
  168744. }
  168745. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168746. return JPEG_ROW_COMPLETED;
  168747. return JPEG_SCAN_COMPLETED;
  168748. }
  168749. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  168750. /*
  168751. * Initialize coefficient buffer controller.
  168752. */
  168753. GLOBAL(void)
  168754. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  168755. {
  168756. my_coef_ptr3 coef;
  168757. coef = (my_coef_ptr3)
  168758. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168759. SIZEOF(my_coef_controller3));
  168760. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  168761. coef->pub.start_input_pass = start_input_pass;
  168762. coef->pub.start_output_pass = start_output_pass;
  168763. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168764. coef->coef_bits_latch = NULL;
  168765. #endif
  168766. /* Create the coefficient buffer. */
  168767. if (need_full_buffer) {
  168768. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168769. /* Allocate a full-image virtual array for each component, */
  168770. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  168771. /* Note we ask for a pre-zeroed array. */
  168772. int ci, access_rows;
  168773. jpeg_component_info *compptr;
  168774. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168775. ci++, compptr++) {
  168776. access_rows = compptr->v_samp_factor;
  168777. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168778. /* If block smoothing could be used, need a bigger window */
  168779. if (cinfo->progressive_mode)
  168780. access_rows *= 3;
  168781. #endif
  168782. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  168783. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  168784. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  168785. (long) compptr->h_samp_factor),
  168786. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  168787. (long) compptr->v_samp_factor),
  168788. (JDIMENSION) access_rows);
  168789. }
  168790. coef->pub.consume_data = consume_data;
  168791. coef->pub.decompress_data = decompress_data;
  168792. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  168793. #else
  168794. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168795. #endif
  168796. } else {
  168797. /* We only need a single-MCU buffer. */
  168798. JBLOCKROW buffer;
  168799. int i;
  168800. buffer = (JBLOCKROW)
  168801. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168802. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  168803. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  168804. coef->MCU_buffer[i] = buffer + i;
  168805. }
  168806. coef->pub.consume_data = dummy_consume_data;
  168807. coef->pub.decompress_data = decompress_onepass;
  168808. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  168809. }
  168810. }
  168811. /*** End of inlined file: jdcoefct.c ***/
  168812. #undef FIX
  168813. /*** Start of inlined file: jdcolor.c ***/
  168814. #define JPEG_INTERNALS
  168815. /* Private subobject */
  168816. typedef struct {
  168817. struct jpeg_color_deconverter pub; /* public fields */
  168818. /* Private state for YCC->RGB conversion */
  168819. int * Cr_r_tab; /* => table for Cr to R conversion */
  168820. int * Cb_b_tab; /* => table for Cb to B conversion */
  168821. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  168822. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  168823. } my_color_deconverter2;
  168824. typedef my_color_deconverter2 * my_cconvert_ptr2;
  168825. /**************** YCbCr -> RGB conversion: most common case **************/
  168826. /*
  168827. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  168828. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  168829. * The conversion equations to be implemented are therefore
  168830. * R = Y + 1.40200 * Cr
  168831. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  168832. * B = Y + 1.77200 * Cb
  168833. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  168834. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  168835. *
  168836. * To avoid floating-point arithmetic, we represent the fractional constants
  168837. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  168838. * the products by 2^16, with appropriate rounding, to get the correct answer.
  168839. * Notice that Y, being an integral input, does not contribute any fraction
  168840. * so it need not participate in the rounding.
  168841. *
  168842. * For even more speed, we avoid doing any multiplications in the inner loop
  168843. * by precalculating the constants times Cb and Cr for all possible values.
  168844. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  168845. * for 12-bit samples it is still acceptable. It's not very reasonable for
  168846. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  168847. * colorspace anyway.
  168848. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  168849. * values for the G calculation are left scaled up, since we must add them
  168850. * together before rounding.
  168851. */
  168852. #define SCALEBITS 16 /* speediest right-shift on some machines */
  168853. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  168854. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  168855. /*
  168856. * Initialize tables for YCC->RGB colorspace conversion.
  168857. */
  168858. LOCAL(void)
  168859. build_ycc_rgb_table (j_decompress_ptr cinfo)
  168860. {
  168861. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168862. int i;
  168863. INT32 x;
  168864. SHIFT_TEMPS
  168865. cconvert->Cr_r_tab = (int *)
  168866. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168867. (MAXJSAMPLE+1) * SIZEOF(int));
  168868. cconvert->Cb_b_tab = (int *)
  168869. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168870. (MAXJSAMPLE+1) * SIZEOF(int));
  168871. cconvert->Cr_g_tab = (INT32 *)
  168872. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168873. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168874. cconvert->Cb_g_tab = (INT32 *)
  168875. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168876. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168877. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  168878. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  168879. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  168880. /* Cr=>R value is nearest int to 1.40200 * x */
  168881. cconvert->Cr_r_tab[i] = (int)
  168882. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  168883. /* Cb=>B value is nearest int to 1.77200 * x */
  168884. cconvert->Cb_b_tab[i] = (int)
  168885. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  168886. /* Cr=>G value is scaled-up -0.71414 * x */
  168887. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  168888. /* Cb=>G value is scaled-up -0.34414 * x */
  168889. /* We also add in ONE_HALF so that need not do it in inner loop */
  168890. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  168891. }
  168892. }
  168893. /*
  168894. * Convert some rows of samples to the output colorspace.
  168895. *
  168896. * Note that we change from noninterleaved, one-plane-per-component format
  168897. * to interleaved-pixel format. The output buffer is therefore three times
  168898. * as wide as the input buffer.
  168899. * A starting row offset is provided only for the input buffer. The caller
  168900. * can easily adjust the passed output_buf value to accommodate any row
  168901. * offset required on that side.
  168902. */
  168903. METHODDEF(void)
  168904. ycc_rgb_convert (j_decompress_ptr cinfo,
  168905. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168906. JSAMPARRAY output_buf, int num_rows)
  168907. {
  168908. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168909. register int y, cb, cr;
  168910. register JSAMPROW outptr;
  168911. register JSAMPROW inptr0, inptr1, inptr2;
  168912. register JDIMENSION col;
  168913. JDIMENSION num_cols = cinfo->output_width;
  168914. /* copy these pointers into registers if possible */
  168915. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168916. register int * Crrtab = cconvert->Cr_r_tab;
  168917. register int * Cbbtab = cconvert->Cb_b_tab;
  168918. register INT32 * Crgtab = cconvert->Cr_g_tab;
  168919. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  168920. SHIFT_TEMPS
  168921. while (--num_rows >= 0) {
  168922. inptr0 = input_buf[0][input_row];
  168923. inptr1 = input_buf[1][input_row];
  168924. inptr2 = input_buf[2][input_row];
  168925. input_row++;
  168926. outptr = *output_buf++;
  168927. for (col = 0; col < num_cols; col++) {
  168928. y = GETJSAMPLE(inptr0[col]);
  168929. cb = GETJSAMPLE(inptr1[col]);
  168930. cr = GETJSAMPLE(inptr2[col]);
  168931. /* Range-limiting is essential due to noise introduced by DCT losses. */
  168932. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  168933. outptr[RGB_GREEN] = range_limit[y +
  168934. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  168935. SCALEBITS))];
  168936. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  168937. outptr += RGB_PIXELSIZE;
  168938. }
  168939. }
  168940. }
  168941. /**************** Cases other than YCbCr -> RGB **************/
  168942. /*
  168943. * Color conversion for no colorspace change: just copy the data,
  168944. * converting from separate-planes to interleaved representation.
  168945. */
  168946. METHODDEF(void)
  168947. null_convert2 (j_decompress_ptr cinfo,
  168948. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168949. JSAMPARRAY output_buf, int num_rows)
  168950. {
  168951. register JSAMPROW inptr, outptr;
  168952. register JDIMENSION count;
  168953. register int num_components = cinfo->num_components;
  168954. JDIMENSION num_cols = cinfo->output_width;
  168955. int ci;
  168956. while (--num_rows >= 0) {
  168957. for (ci = 0; ci < num_components; ci++) {
  168958. inptr = input_buf[ci][input_row];
  168959. outptr = output_buf[0] + ci;
  168960. for (count = num_cols; count > 0; count--) {
  168961. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  168962. outptr += num_components;
  168963. }
  168964. }
  168965. input_row++;
  168966. output_buf++;
  168967. }
  168968. }
  168969. /*
  168970. * Color conversion for grayscale: just copy the data.
  168971. * This also works for YCbCr -> grayscale conversion, in which
  168972. * we just copy the Y (luminance) component and ignore chrominance.
  168973. */
  168974. METHODDEF(void)
  168975. grayscale_convert2 (j_decompress_ptr cinfo,
  168976. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168977. JSAMPARRAY output_buf, int num_rows)
  168978. {
  168979. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  168980. num_rows, cinfo->output_width);
  168981. }
  168982. /*
  168983. * Convert grayscale to RGB: just duplicate the graylevel three times.
  168984. * This is provided to support applications that don't want to cope
  168985. * with grayscale as a separate case.
  168986. */
  168987. METHODDEF(void)
  168988. gray_rgb_convert (j_decompress_ptr cinfo,
  168989. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168990. JSAMPARRAY output_buf, int num_rows)
  168991. {
  168992. register JSAMPROW inptr, outptr;
  168993. register JDIMENSION col;
  168994. JDIMENSION num_cols = cinfo->output_width;
  168995. while (--num_rows >= 0) {
  168996. inptr = input_buf[0][input_row++];
  168997. outptr = *output_buf++;
  168998. for (col = 0; col < num_cols; col++) {
  168999. /* We can dispense with GETJSAMPLE() here */
  169000. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  169001. outptr += RGB_PIXELSIZE;
  169002. }
  169003. }
  169004. }
  169005. /*
  169006. * Adobe-style YCCK->CMYK conversion.
  169007. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  169008. * conversion as above, while passing K (black) unchanged.
  169009. * We assume build_ycc_rgb_table has been called.
  169010. */
  169011. METHODDEF(void)
  169012. ycck_cmyk_convert (j_decompress_ptr cinfo,
  169013. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169014. JSAMPARRAY output_buf, int num_rows)
  169015. {
  169016. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169017. register int y, cb, cr;
  169018. register JSAMPROW outptr;
  169019. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169020. register JDIMENSION col;
  169021. JDIMENSION num_cols = cinfo->output_width;
  169022. /* copy these pointers into registers if possible */
  169023. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169024. register int * Crrtab = cconvert->Cr_r_tab;
  169025. register int * Cbbtab = cconvert->Cb_b_tab;
  169026. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169027. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169028. SHIFT_TEMPS
  169029. while (--num_rows >= 0) {
  169030. inptr0 = input_buf[0][input_row];
  169031. inptr1 = input_buf[1][input_row];
  169032. inptr2 = input_buf[2][input_row];
  169033. inptr3 = input_buf[3][input_row];
  169034. input_row++;
  169035. outptr = *output_buf++;
  169036. for (col = 0; col < num_cols; col++) {
  169037. y = GETJSAMPLE(inptr0[col]);
  169038. cb = GETJSAMPLE(inptr1[col]);
  169039. cr = GETJSAMPLE(inptr2[col]);
  169040. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169041. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169042. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169043. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169044. SCALEBITS)))];
  169045. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169046. /* K passes through unchanged */
  169047. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169048. outptr += 4;
  169049. }
  169050. }
  169051. }
  169052. /*
  169053. * Empty method for start_pass.
  169054. */
  169055. METHODDEF(void)
  169056. start_pass_dcolor (j_decompress_ptr)
  169057. {
  169058. /* no work needed */
  169059. }
  169060. /*
  169061. * Module initialization routine for output colorspace conversion.
  169062. */
  169063. GLOBAL(void)
  169064. jinit_color_deconverter (j_decompress_ptr cinfo)
  169065. {
  169066. my_cconvert_ptr2 cconvert;
  169067. int ci;
  169068. cconvert = (my_cconvert_ptr2)
  169069. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169070. SIZEOF(my_color_deconverter2));
  169071. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169072. cconvert->pub.start_pass = start_pass_dcolor;
  169073. /* Make sure num_components agrees with jpeg_color_space */
  169074. switch (cinfo->jpeg_color_space) {
  169075. case JCS_GRAYSCALE:
  169076. if (cinfo->num_components != 1)
  169077. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169078. break;
  169079. case JCS_RGB:
  169080. case JCS_YCbCr:
  169081. if (cinfo->num_components != 3)
  169082. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169083. break;
  169084. case JCS_CMYK:
  169085. case JCS_YCCK:
  169086. if (cinfo->num_components != 4)
  169087. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169088. break;
  169089. default: /* JCS_UNKNOWN can be anything */
  169090. if (cinfo->num_components < 1)
  169091. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169092. break;
  169093. }
  169094. /* Set out_color_components and conversion method based on requested space.
  169095. * Also clear the component_needed flags for any unused components,
  169096. * so that earlier pipeline stages can avoid useless computation.
  169097. */
  169098. switch (cinfo->out_color_space) {
  169099. case JCS_GRAYSCALE:
  169100. cinfo->out_color_components = 1;
  169101. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169102. cinfo->jpeg_color_space == JCS_YCbCr) {
  169103. cconvert->pub.color_convert = grayscale_convert2;
  169104. /* For color->grayscale conversion, only the Y (0) component is needed */
  169105. for (ci = 1; ci < cinfo->num_components; ci++)
  169106. cinfo->comp_info[ci].component_needed = FALSE;
  169107. } else
  169108. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169109. break;
  169110. case JCS_RGB:
  169111. cinfo->out_color_components = RGB_PIXELSIZE;
  169112. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169113. cconvert->pub.color_convert = ycc_rgb_convert;
  169114. build_ycc_rgb_table(cinfo);
  169115. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169116. cconvert->pub.color_convert = gray_rgb_convert;
  169117. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169118. cconvert->pub.color_convert = null_convert2;
  169119. } else
  169120. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169121. break;
  169122. case JCS_CMYK:
  169123. cinfo->out_color_components = 4;
  169124. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169125. cconvert->pub.color_convert = ycck_cmyk_convert;
  169126. build_ycc_rgb_table(cinfo);
  169127. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169128. cconvert->pub.color_convert = null_convert2;
  169129. } else
  169130. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169131. break;
  169132. default:
  169133. /* Permit null conversion to same output space */
  169134. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169135. cinfo->out_color_components = cinfo->num_components;
  169136. cconvert->pub.color_convert = null_convert2;
  169137. } else /* unsupported non-null conversion */
  169138. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169139. break;
  169140. }
  169141. if (cinfo->quantize_colors)
  169142. cinfo->output_components = 1; /* single colormapped output component */
  169143. else
  169144. cinfo->output_components = cinfo->out_color_components;
  169145. }
  169146. /*** End of inlined file: jdcolor.c ***/
  169147. #undef FIX
  169148. /*** Start of inlined file: jddctmgr.c ***/
  169149. #define JPEG_INTERNALS
  169150. /*
  169151. * The decompressor input side (jdinput.c) saves away the appropriate
  169152. * quantization table for each component at the start of the first scan
  169153. * involving that component. (This is necessary in order to correctly
  169154. * decode files that reuse Q-table slots.)
  169155. * When we are ready to make an output pass, the saved Q-table is converted
  169156. * to a multiplier table that will actually be used by the IDCT routine.
  169157. * The multiplier table contents are IDCT-method-dependent. To support
  169158. * application changes in IDCT method between scans, we can remake the
  169159. * multiplier tables if necessary.
  169160. * In buffered-image mode, the first output pass may occur before any data
  169161. * has been seen for some components, and thus before their Q-tables have
  169162. * been saved away. To handle this case, multiplier tables are preset
  169163. * to zeroes; the result of the IDCT will be a neutral gray level.
  169164. */
  169165. /* Private subobject for this module */
  169166. typedef struct {
  169167. struct jpeg_inverse_dct pub; /* public fields */
  169168. /* This array contains the IDCT method code that each multiplier table
  169169. * is currently set up for, or -1 if it's not yet set up.
  169170. * The actual multiplier tables are pointed to by dct_table in the
  169171. * per-component comp_info structures.
  169172. */
  169173. int cur_method[MAX_COMPONENTS];
  169174. } my_idct_controller;
  169175. typedef my_idct_controller * my_idct_ptr;
  169176. /* Allocated multiplier tables: big enough for any supported variant */
  169177. typedef union {
  169178. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169179. #ifdef DCT_IFAST_SUPPORTED
  169180. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169181. #endif
  169182. #ifdef DCT_FLOAT_SUPPORTED
  169183. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169184. #endif
  169185. } multiplier_table;
  169186. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169187. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169188. */
  169189. #ifdef DCT_ISLOW_SUPPORTED
  169190. #define PROVIDE_ISLOW_TABLES
  169191. #else
  169192. #ifdef IDCT_SCALING_SUPPORTED
  169193. #define PROVIDE_ISLOW_TABLES
  169194. #endif
  169195. #endif
  169196. /*
  169197. * Prepare for an output pass.
  169198. * Here we select the proper IDCT routine for each component and build
  169199. * a matching multiplier table.
  169200. */
  169201. METHODDEF(void)
  169202. start_pass (j_decompress_ptr cinfo)
  169203. {
  169204. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169205. int ci, i;
  169206. jpeg_component_info *compptr;
  169207. int method = 0;
  169208. inverse_DCT_method_ptr method_ptr = NULL;
  169209. JQUANT_TBL * qtbl;
  169210. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169211. ci++, compptr++) {
  169212. /* Select the proper IDCT routine for this component's scaling */
  169213. switch (compptr->DCT_scaled_size) {
  169214. #ifdef IDCT_SCALING_SUPPORTED
  169215. case 1:
  169216. method_ptr = jpeg_idct_1x1;
  169217. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169218. break;
  169219. case 2:
  169220. method_ptr = jpeg_idct_2x2;
  169221. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169222. break;
  169223. case 4:
  169224. method_ptr = jpeg_idct_4x4;
  169225. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169226. break;
  169227. #endif
  169228. case DCTSIZE:
  169229. switch (cinfo->dct_method) {
  169230. #ifdef DCT_ISLOW_SUPPORTED
  169231. case JDCT_ISLOW:
  169232. method_ptr = jpeg_idct_islow;
  169233. method = JDCT_ISLOW;
  169234. break;
  169235. #endif
  169236. #ifdef DCT_IFAST_SUPPORTED
  169237. case JDCT_IFAST:
  169238. method_ptr = jpeg_idct_ifast;
  169239. method = JDCT_IFAST;
  169240. break;
  169241. #endif
  169242. #ifdef DCT_FLOAT_SUPPORTED
  169243. case JDCT_FLOAT:
  169244. method_ptr = jpeg_idct_float;
  169245. method = JDCT_FLOAT;
  169246. break;
  169247. #endif
  169248. default:
  169249. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169250. break;
  169251. }
  169252. break;
  169253. default:
  169254. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169255. break;
  169256. }
  169257. idct->pub.inverse_DCT[ci] = method_ptr;
  169258. /* Create multiplier table from quant table.
  169259. * However, we can skip this if the component is uninteresting
  169260. * or if we already built the table. Also, if no quant table
  169261. * has yet been saved for the component, we leave the
  169262. * multiplier table all-zero; we'll be reading zeroes from the
  169263. * coefficient controller's buffer anyway.
  169264. */
  169265. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169266. continue;
  169267. qtbl = compptr->quant_table;
  169268. if (qtbl == NULL) /* happens if no data yet for component */
  169269. continue;
  169270. idct->cur_method[ci] = method;
  169271. switch (method) {
  169272. #ifdef PROVIDE_ISLOW_TABLES
  169273. case JDCT_ISLOW:
  169274. {
  169275. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169276. * coefficients, but are stored as ints to ensure access efficiency.
  169277. */
  169278. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169279. for (i = 0; i < DCTSIZE2; i++) {
  169280. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169281. }
  169282. }
  169283. break;
  169284. #endif
  169285. #ifdef DCT_IFAST_SUPPORTED
  169286. case JDCT_IFAST:
  169287. {
  169288. /* For AA&N IDCT method, multipliers are equal to quantization
  169289. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169290. * scalefactor[0] = 1
  169291. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169292. * For integer operation, the multiplier table is to be scaled by
  169293. * IFAST_SCALE_BITS.
  169294. */
  169295. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169296. #define CONST_BITS 14
  169297. static const INT16 aanscales[DCTSIZE2] = {
  169298. /* precomputed values scaled up by 14 bits */
  169299. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169300. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169301. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169302. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169303. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169304. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169305. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169306. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169307. };
  169308. SHIFT_TEMPS
  169309. for (i = 0; i < DCTSIZE2; i++) {
  169310. ifmtbl[i] = (IFAST_MULT_TYPE)
  169311. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169312. (INT32) aanscales[i]),
  169313. CONST_BITS-IFAST_SCALE_BITS);
  169314. }
  169315. }
  169316. break;
  169317. #endif
  169318. #ifdef DCT_FLOAT_SUPPORTED
  169319. case JDCT_FLOAT:
  169320. {
  169321. /* For float AA&N IDCT method, multipliers are equal to quantization
  169322. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169323. * scalefactor[0] = 1
  169324. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169325. */
  169326. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169327. int row, col;
  169328. static const double aanscalefactor[DCTSIZE] = {
  169329. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169330. 1.0, 0.785694958, 0.541196100, 0.275899379
  169331. };
  169332. i = 0;
  169333. for (row = 0; row < DCTSIZE; row++) {
  169334. for (col = 0; col < DCTSIZE; col++) {
  169335. fmtbl[i] = (FLOAT_MULT_TYPE)
  169336. ((double) qtbl->quantval[i] *
  169337. aanscalefactor[row] * aanscalefactor[col]);
  169338. i++;
  169339. }
  169340. }
  169341. }
  169342. break;
  169343. #endif
  169344. default:
  169345. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169346. break;
  169347. }
  169348. }
  169349. }
  169350. /*
  169351. * Initialize IDCT manager.
  169352. */
  169353. GLOBAL(void)
  169354. jinit_inverse_dct (j_decompress_ptr cinfo)
  169355. {
  169356. my_idct_ptr idct;
  169357. int ci;
  169358. jpeg_component_info *compptr;
  169359. idct = (my_idct_ptr)
  169360. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169361. SIZEOF(my_idct_controller));
  169362. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169363. idct->pub.start_pass = start_pass;
  169364. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169365. ci++, compptr++) {
  169366. /* Allocate and pre-zero a multiplier table for each component */
  169367. compptr->dct_table =
  169368. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169369. SIZEOF(multiplier_table));
  169370. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169371. /* Mark multiplier table not yet set up for any method */
  169372. idct->cur_method[ci] = -1;
  169373. }
  169374. }
  169375. /*** End of inlined file: jddctmgr.c ***/
  169376. #undef CONST_BITS
  169377. #undef ASSIGN_STATE
  169378. /*** Start of inlined file: jdhuff.c ***/
  169379. #define JPEG_INTERNALS
  169380. /*** Start of inlined file: jdhuff.h ***/
  169381. /* Short forms of external names for systems with brain-damaged linkers. */
  169382. #ifndef __jdhuff_h__
  169383. #define __jdhuff_h__
  169384. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169385. #define jpeg_make_d_derived_tbl jMkDDerived
  169386. #define jpeg_fill_bit_buffer jFilBitBuf
  169387. #define jpeg_huff_decode jHufDecode
  169388. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169389. /* Derived data constructed for each Huffman table */
  169390. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169391. typedef struct {
  169392. /* Basic tables: (element [0] of each array is unused) */
  169393. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169394. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169395. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169396. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169397. * the smallest code of length k; so given a code of length k, the
  169398. * corresponding symbol is huffval[code + valoffset[k]]
  169399. */
  169400. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169401. JHUFF_TBL *pub;
  169402. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169403. * the input data stream. If the next Huffman code is no more
  169404. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169405. * the corresponding symbol directly from these tables.
  169406. */
  169407. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169408. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169409. } d_derived_tbl;
  169410. /* Expand a Huffman table definition into the derived format */
  169411. EXTERN(void) jpeg_make_d_derived_tbl
  169412. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169413. d_derived_tbl ** pdtbl));
  169414. /*
  169415. * Fetching the next N bits from the input stream is a time-critical operation
  169416. * for the Huffman decoders. We implement it with a combination of inline
  169417. * macros and out-of-line subroutines. Note that N (the number of bits
  169418. * demanded at one time) never exceeds 15 for JPEG use.
  169419. *
  169420. * We read source bytes into get_buffer and dole out bits as needed.
  169421. * If get_buffer already contains enough bits, they are fetched in-line
  169422. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169423. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169424. * as full as possible (not just to the number of bits needed; this
  169425. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169426. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169427. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169428. * at least the requested number of bits --- dummy zeroes are inserted if
  169429. * necessary.
  169430. */
  169431. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169432. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169433. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169434. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169435. * appropriately should be a win. Unfortunately we can't define the size
  169436. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169437. * because not all machines measure sizeof in 8-bit bytes.
  169438. */
  169439. typedef struct { /* Bitreading state saved across MCUs */
  169440. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169441. int bits_left; /* # of unused bits in it */
  169442. } bitread_perm_state;
  169443. typedef struct { /* Bitreading working state within an MCU */
  169444. /* Current data source location */
  169445. /* We need a copy, rather than munging the original, in case of suspension */
  169446. const JOCTET * next_input_byte; /* => next byte to read from source */
  169447. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169448. /* Bit input buffer --- note these values are kept in register variables,
  169449. * not in this struct, inside the inner loops.
  169450. */
  169451. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169452. int bits_left; /* # of unused bits in it */
  169453. /* Pointer needed by jpeg_fill_bit_buffer. */
  169454. j_decompress_ptr cinfo; /* back link to decompress master record */
  169455. } bitread_working_state;
  169456. /* Macros to declare and load/save bitread local variables. */
  169457. #define BITREAD_STATE_VARS \
  169458. register bit_buf_type get_buffer; \
  169459. register int bits_left; \
  169460. bitread_working_state br_state
  169461. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169462. br_state.cinfo = cinfop; \
  169463. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169464. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169465. get_buffer = permstate.get_buffer; \
  169466. bits_left = permstate.bits_left;
  169467. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169468. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169469. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169470. permstate.get_buffer = get_buffer; \
  169471. permstate.bits_left = bits_left
  169472. /*
  169473. * These macros provide the in-line portion of bit fetching.
  169474. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169475. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169476. * The variables get_buffer and bits_left are assumed to be locals,
  169477. * but the state struct might not be (jpeg_huff_decode needs this).
  169478. * CHECK_BIT_BUFFER(state,n,action);
  169479. * Ensure there are N bits in get_buffer; if suspend, take action.
  169480. * val = GET_BITS(n);
  169481. * Fetch next N bits.
  169482. * val = PEEK_BITS(n);
  169483. * Fetch next N bits without removing them from the buffer.
  169484. * DROP_BITS(n);
  169485. * Discard next N bits.
  169486. * The value N should be a simple variable, not an expression, because it
  169487. * is evaluated multiple times.
  169488. */
  169489. #define CHECK_BIT_BUFFER(state,nbits,action) \
  169490. { if (bits_left < (nbits)) { \
  169491. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  169492. { action; } \
  169493. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  169494. #define GET_BITS(nbits) \
  169495. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  169496. #define PEEK_BITS(nbits) \
  169497. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  169498. #define DROP_BITS(nbits) \
  169499. (bits_left -= (nbits))
  169500. /* Load up the bit buffer to a depth of at least nbits */
  169501. EXTERN(boolean) jpeg_fill_bit_buffer
  169502. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169503. register int bits_left, int nbits));
  169504. /*
  169505. * Code for extracting next Huffman-coded symbol from input bit stream.
  169506. * Again, this is time-critical and we make the main paths be macros.
  169507. *
  169508. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  169509. * without looping. Usually, more than 95% of the Huffman codes will be 8
  169510. * or fewer bits long. The few overlength codes are handled with a loop,
  169511. * which need not be inline code.
  169512. *
  169513. * Notes about the HUFF_DECODE macro:
  169514. * 1. Near the end of the data segment, we may fail to get enough bits
  169515. * for a lookahead. In that case, we do it the hard way.
  169516. * 2. If the lookahead table contains no entry, the next code must be
  169517. * more than HUFF_LOOKAHEAD bits long.
  169518. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  169519. */
  169520. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  169521. { register int nb, look; \
  169522. if (bits_left < HUFF_LOOKAHEAD) { \
  169523. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  169524. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169525. if (bits_left < HUFF_LOOKAHEAD) { \
  169526. nb = 1; goto slowlabel; \
  169527. } \
  169528. } \
  169529. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  169530. if ((nb = htbl->look_nbits[look]) != 0) { \
  169531. DROP_BITS(nb); \
  169532. result = htbl->look_sym[look]; \
  169533. } else { \
  169534. nb = HUFF_LOOKAHEAD+1; \
  169535. slowlabel: \
  169536. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  169537. { failaction; } \
  169538. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169539. } \
  169540. }
  169541. /* Out-of-line case for Huffman code fetching */
  169542. EXTERN(int) jpeg_huff_decode
  169543. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169544. register int bits_left, d_derived_tbl * htbl, int min_bits));
  169545. #endif
  169546. /*** End of inlined file: jdhuff.h ***/
  169547. /* Declarations shared with jdphuff.c */
  169548. /*
  169549. * Expanded entropy decoder object for Huffman decoding.
  169550. *
  169551. * The savable_state subrecord contains fields that change within an MCU,
  169552. * but must not be updated permanently until we complete the MCU.
  169553. */
  169554. typedef struct {
  169555. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169556. } savable_state2;
  169557. /* This macro is to work around compilers with missing or broken
  169558. * structure assignment. You'll need to fix this code if you have
  169559. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169560. */
  169561. #ifndef NO_STRUCT_ASSIGN
  169562. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169563. #else
  169564. #if MAX_COMPS_IN_SCAN == 4
  169565. #define ASSIGN_STATE(dest,src) \
  169566. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  169567. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169568. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169569. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169570. #endif
  169571. #endif
  169572. typedef struct {
  169573. struct jpeg_entropy_decoder pub; /* public fields */
  169574. /* These fields are loaded into local variables at start of each MCU.
  169575. * In case of suspension, we exit WITHOUT updating them.
  169576. */
  169577. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169578. savable_state2 saved; /* Other state at start of MCU */
  169579. /* These fields are NOT loaded into local working state. */
  169580. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169581. /* Pointers to derived tables (these workspaces have image lifespan) */
  169582. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  169583. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  169584. /* Precalculated info set up by start_pass for use in decode_mcu: */
  169585. /* Pointers to derived tables to be used for each block within an MCU */
  169586. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169587. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169588. /* Whether we care about the DC and AC coefficient values for each block */
  169589. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  169590. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  169591. } huff_entropy_decoder2;
  169592. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  169593. /*
  169594. * Initialize for a Huffman-compressed scan.
  169595. */
  169596. METHODDEF(void)
  169597. start_pass_huff_decoder (j_decompress_ptr cinfo)
  169598. {
  169599. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169600. int ci, blkn, dctbl, actbl;
  169601. jpeg_component_info * compptr;
  169602. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  169603. * This ought to be an error condition, but we make it a warning because
  169604. * there are some baseline files out there with all zeroes in these bytes.
  169605. */
  169606. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  169607. cinfo->Ah != 0 || cinfo->Al != 0)
  169608. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  169609. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169610. compptr = cinfo->cur_comp_info[ci];
  169611. dctbl = compptr->dc_tbl_no;
  169612. actbl = compptr->ac_tbl_no;
  169613. /* Compute derived values for Huffman tables */
  169614. /* We may do this more than once for a table, but it's not expensive */
  169615. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  169616. & entropy->dc_derived_tbls[dctbl]);
  169617. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  169618. & entropy->ac_derived_tbls[actbl]);
  169619. /* Initialize DC predictions to 0 */
  169620. entropy->saved.last_dc_val[ci] = 0;
  169621. }
  169622. /* Precalculate decoding info for each block in an MCU of this scan */
  169623. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169624. ci = cinfo->MCU_membership[blkn];
  169625. compptr = cinfo->cur_comp_info[ci];
  169626. /* Precalculate which table to use for each block */
  169627. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  169628. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  169629. /* Decide whether we really care about the coefficient values */
  169630. if (compptr->component_needed) {
  169631. entropy->dc_needed[blkn] = TRUE;
  169632. /* we don't need the ACs if producing a 1/8th-size image */
  169633. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  169634. } else {
  169635. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  169636. }
  169637. }
  169638. /* Initialize bitread state variables */
  169639. entropy->bitstate.bits_left = 0;
  169640. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  169641. entropy->pub.insufficient_data = FALSE;
  169642. /* Initialize restart counter */
  169643. entropy->restarts_to_go = cinfo->restart_interval;
  169644. }
  169645. /*
  169646. * Compute the derived values for a Huffman table.
  169647. * This routine also performs some validation checks on the table.
  169648. *
  169649. * Note this is also used by jdphuff.c.
  169650. */
  169651. GLOBAL(void)
  169652. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  169653. d_derived_tbl ** pdtbl)
  169654. {
  169655. JHUFF_TBL *htbl;
  169656. d_derived_tbl *dtbl;
  169657. int p, i, l, si, numsymbols;
  169658. int lookbits, ctr;
  169659. char huffsize[257];
  169660. unsigned int huffcode[257];
  169661. unsigned int code;
  169662. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  169663. * paralleling the order of the symbols themselves in htbl->huffval[].
  169664. */
  169665. /* Find the input Huffman table */
  169666. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  169667. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169668. htbl =
  169669. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  169670. if (htbl == NULL)
  169671. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169672. /* Allocate a workspace if we haven't already done so. */
  169673. if (*pdtbl == NULL)
  169674. *pdtbl = (d_derived_tbl *)
  169675. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169676. SIZEOF(d_derived_tbl));
  169677. dtbl = *pdtbl;
  169678. dtbl->pub = htbl; /* fill in back link */
  169679. /* Figure C.1: make table of Huffman code length for each symbol */
  169680. p = 0;
  169681. for (l = 1; l <= 16; l++) {
  169682. i = (int) htbl->bits[l];
  169683. if (i < 0 || p + i > 256) /* protect against table overrun */
  169684. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169685. while (i--)
  169686. huffsize[p++] = (char) l;
  169687. }
  169688. huffsize[p] = 0;
  169689. numsymbols = p;
  169690. /* Figure C.2: generate the codes themselves */
  169691. /* We also validate that the counts represent a legal Huffman code tree. */
  169692. code = 0;
  169693. si = huffsize[0];
  169694. p = 0;
  169695. while (huffsize[p]) {
  169696. while (((int) huffsize[p]) == si) {
  169697. huffcode[p++] = code;
  169698. code++;
  169699. }
  169700. /* code is now 1 more than the last code used for codelength si; but
  169701. * it must still fit in si bits, since no code is allowed to be all ones.
  169702. */
  169703. if (((INT32) code) >= (((INT32) 1) << si))
  169704. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169705. code <<= 1;
  169706. si++;
  169707. }
  169708. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  169709. p = 0;
  169710. for (l = 1; l <= 16; l++) {
  169711. if (htbl->bits[l]) {
  169712. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  169713. * minus the minimum code of length l
  169714. */
  169715. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  169716. p += htbl->bits[l];
  169717. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  169718. } else {
  169719. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  169720. }
  169721. }
  169722. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  169723. /* Compute lookahead tables to speed up decoding.
  169724. * First we set all the table entries to 0, indicating "too long";
  169725. * then we iterate through the Huffman codes that are short enough and
  169726. * fill in all the entries that correspond to bit sequences starting
  169727. * with that code.
  169728. */
  169729. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  169730. p = 0;
  169731. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  169732. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  169733. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  169734. /* Generate left-justified code followed by all possible bit sequences */
  169735. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  169736. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  169737. dtbl->look_nbits[lookbits] = l;
  169738. dtbl->look_sym[lookbits] = htbl->huffval[p];
  169739. lookbits++;
  169740. }
  169741. }
  169742. }
  169743. /* Validate symbols as being reasonable.
  169744. * For AC tables, we make no check, but accept all byte values 0..255.
  169745. * For DC tables, we require the symbols to be in range 0..15.
  169746. * (Tighter bounds could be applied depending on the data depth and mode,
  169747. * but this is sufficient to ensure safe decoding.)
  169748. */
  169749. if (isDC) {
  169750. for (i = 0; i < numsymbols; i++) {
  169751. int sym = htbl->huffval[i];
  169752. if (sym < 0 || sym > 15)
  169753. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169754. }
  169755. }
  169756. }
  169757. /*
  169758. * Out-of-line code for bit fetching (shared with jdphuff.c).
  169759. * See jdhuff.h for info about usage.
  169760. * Note: current values of get_buffer and bits_left are passed as parameters,
  169761. * but are returned in the corresponding fields of the state struct.
  169762. *
  169763. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  169764. * of get_buffer to be used. (On machines with wider words, an even larger
  169765. * buffer could be used.) However, on some machines 32-bit shifts are
  169766. * quite slow and take time proportional to the number of places shifted.
  169767. * (This is true with most PC compilers, for instance.) In this case it may
  169768. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  169769. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  169770. */
  169771. #ifdef SLOW_SHIFT_32
  169772. #define MIN_GET_BITS 15 /* minimum allowable value */
  169773. #else
  169774. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  169775. #endif
  169776. GLOBAL(boolean)
  169777. jpeg_fill_bit_buffer (bitread_working_state * state,
  169778. register bit_buf_type get_buffer, register int bits_left,
  169779. int nbits)
  169780. /* Load up the bit buffer to a depth of at least nbits */
  169781. {
  169782. /* Copy heavily used state fields into locals (hopefully registers) */
  169783. register const JOCTET * next_input_byte = state->next_input_byte;
  169784. register size_t bytes_in_buffer = state->bytes_in_buffer;
  169785. j_decompress_ptr cinfo = state->cinfo;
  169786. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  169787. /* (It is assumed that no request will be for more than that many bits.) */
  169788. /* We fail to do so only if we hit a marker or are forced to suspend. */
  169789. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  169790. while (bits_left < MIN_GET_BITS) {
  169791. register int c;
  169792. /* Attempt to read a byte */
  169793. if (bytes_in_buffer == 0) {
  169794. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169795. return FALSE;
  169796. next_input_byte = cinfo->src->next_input_byte;
  169797. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169798. }
  169799. bytes_in_buffer--;
  169800. c = GETJOCTET(*next_input_byte++);
  169801. /* If it's 0xFF, check and discard stuffed zero byte */
  169802. if (c == 0xFF) {
  169803. /* Loop here to discard any padding FF's on terminating marker,
  169804. * so that we can save a valid unread_marker value. NOTE: we will
  169805. * accept multiple FF's followed by a 0 as meaning a single FF data
  169806. * byte. This data pattern is not valid according to the standard.
  169807. */
  169808. do {
  169809. if (bytes_in_buffer == 0) {
  169810. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169811. return FALSE;
  169812. next_input_byte = cinfo->src->next_input_byte;
  169813. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169814. }
  169815. bytes_in_buffer--;
  169816. c = GETJOCTET(*next_input_byte++);
  169817. } while (c == 0xFF);
  169818. if (c == 0) {
  169819. /* Found FF/00, which represents an FF data byte */
  169820. c = 0xFF;
  169821. } else {
  169822. /* Oops, it's actually a marker indicating end of compressed data.
  169823. * Save the marker code for later use.
  169824. * Fine point: it might appear that we should save the marker into
  169825. * bitread working state, not straight into permanent state. But
  169826. * once we have hit a marker, we cannot need to suspend within the
  169827. * current MCU, because we will read no more bytes from the data
  169828. * source. So it is OK to update permanent state right away.
  169829. */
  169830. cinfo->unread_marker = c;
  169831. /* See if we need to insert some fake zero bits. */
  169832. goto no_more_bytes;
  169833. }
  169834. }
  169835. /* OK, load c into get_buffer */
  169836. get_buffer = (get_buffer << 8) | c;
  169837. bits_left += 8;
  169838. } /* end while */
  169839. } else {
  169840. no_more_bytes:
  169841. /* We get here if we've read the marker that terminates the compressed
  169842. * data segment. There should be enough bits in the buffer register
  169843. * to satisfy the request; if so, no problem.
  169844. */
  169845. if (nbits > bits_left) {
  169846. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  169847. * the data stream, so that we can produce some kind of image.
  169848. * We use a nonvolatile flag to ensure that only one warning message
  169849. * appears per data segment.
  169850. */
  169851. if (! cinfo->entropy->insufficient_data) {
  169852. WARNMS(cinfo, JWRN_HIT_MARKER);
  169853. cinfo->entropy->insufficient_data = TRUE;
  169854. }
  169855. /* Fill the buffer with zero bits */
  169856. get_buffer <<= MIN_GET_BITS - bits_left;
  169857. bits_left = MIN_GET_BITS;
  169858. }
  169859. }
  169860. /* Unload the local registers */
  169861. state->next_input_byte = next_input_byte;
  169862. state->bytes_in_buffer = bytes_in_buffer;
  169863. state->get_buffer = get_buffer;
  169864. state->bits_left = bits_left;
  169865. return TRUE;
  169866. }
  169867. /*
  169868. * Out-of-line code for Huffman code decoding.
  169869. * See jdhuff.h for info about usage.
  169870. */
  169871. GLOBAL(int)
  169872. jpeg_huff_decode (bitread_working_state * state,
  169873. register bit_buf_type get_buffer, register int bits_left,
  169874. d_derived_tbl * htbl, int min_bits)
  169875. {
  169876. register int l = min_bits;
  169877. register INT32 code;
  169878. /* HUFF_DECODE has determined that the code is at least min_bits */
  169879. /* bits long, so fetch that many bits in one swoop. */
  169880. CHECK_BIT_BUFFER(*state, l, return -1);
  169881. code = GET_BITS(l);
  169882. /* Collect the rest of the Huffman code one bit at a time. */
  169883. /* This is per Figure F.16 in the JPEG spec. */
  169884. while (code > htbl->maxcode[l]) {
  169885. code <<= 1;
  169886. CHECK_BIT_BUFFER(*state, 1, return -1);
  169887. code |= GET_BITS(1);
  169888. l++;
  169889. }
  169890. /* Unload the local registers */
  169891. state->get_buffer = get_buffer;
  169892. state->bits_left = bits_left;
  169893. /* With garbage input we may reach the sentinel value l = 17. */
  169894. if (l > 16) {
  169895. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  169896. return 0; /* fake a zero as the safest result */
  169897. }
  169898. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  169899. }
  169900. /*
  169901. * Check for a restart marker & resynchronize decoder.
  169902. * Returns FALSE if must suspend.
  169903. */
  169904. LOCAL(boolean)
  169905. process_restart (j_decompress_ptr cinfo)
  169906. {
  169907. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169908. int ci;
  169909. /* Throw away any unused bits remaining in bit buffer; */
  169910. /* include any full bytes in next_marker's count of discarded bytes */
  169911. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  169912. entropy->bitstate.bits_left = 0;
  169913. /* Advance past the RSTn marker */
  169914. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  169915. return FALSE;
  169916. /* Re-initialize DC predictions to 0 */
  169917. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  169918. entropy->saved.last_dc_val[ci] = 0;
  169919. /* Reset restart counter */
  169920. entropy->restarts_to_go = cinfo->restart_interval;
  169921. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  169922. * against a marker. In that case we will end up treating the next data
  169923. * segment as empty, and we can avoid producing bogus output pixels by
  169924. * leaving the flag set.
  169925. */
  169926. if (cinfo->unread_marker == 0)
  169927. entropy->pub.insufficient_data = FALSE;
  169928. return TRUE;
  169929. }
  169930. /*
  169931. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  169932. * The coefficients are reordered from zigzag order into natural array order,
  169933. * but are not dequantized.
  169934. *
  169935. * The i'th block of the MCU is stored into the block pointed to by
  169936. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  169937. * (Wholesale zeroing is usually a little faster than retail...)
  169938. *
  169939. * Returns FALSE if data source requested suspension. In that case no
  169940. * changes have been made to permanent state. (Exception: some output
  169941. * coefficients may already have been assigned. This is harmless for
  169942. * this module, since we'll just re-assign them on the next call.)
  169943. */
  169944. METHODDEF(boolean)
  169945. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169946. {
  169947. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169948. int blkn;
  169949. BITREAD_STATE_VARS;
  169950. savable_state2 state;
  169951. /* Process restart marker if needed; may have to suspend */
  169952. if (cinfo->restart_interval) {
  169953. if (entropy->restarts_to_go == 0)
  169954. if (! process_restart(cinfo))
  169955. return FALSE;
  169956. }
  169957. /* If we've run out of data, just leave the MCU set to zeroes.
  169958. * This way, we return uniform gray for the remainder of the segment.
  169959. */
  169960. if (! entropy->pub.insufficient_data) {
  169961. /* Load up working state */
  169962. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169963. ASSIGN_STATE(state, entropy->saved);
  169964. /* Outer loop handles each block in the MCU */
  169965. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169966. JBLOCKROW block = MCU_data[blkn];
  169967. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  169968. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  169969. register int s, k, r;
  169970. /* Decode a single block's worth of coefficients */
  169971. /* Section F.2.2.1: decode the DC coefficient difference */
  169972. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  169973. if (s) {
  169974. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169975. r = GET_BITS(s);
  169976. s = HUFF_EXTEND(r, s);
  169977. }
  169978. if (entropy->dc_needed[blkn]) {
  169979. /* Convert DC difference to actual value, update last_dc_val */
  169980. int ci = cinfo->MCU_membership[blkn];
  169981. s += state.last_dc_val[ci];
  169982. state.last_dc_val[ci] = s;
  169983. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  169984. (*block)[0] = (JCOEF) s;
  169985. }
  169986. if (entropy->ac_needed[blkn]) {
  169987. /* Section F.2.2.2: decode the AC coefficients */
  169988. /* Since zeroes are skipped, output area must be cleared beforehand */
  169989. for (k = 1; k < DCTSIZE2; k++) {
  169990. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  169991. r = s >> 4;
  169992. s &= 15;
  169993. if (s) {
  169994. k += r;
  169995. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169996. r = GET_BITS(s);
  169997. s = HUFF_EXTEND(r, s);
  169998. /* Output coefficient in natural (dezigzagged) order.
  169999. * Note: the extra entries in jpeg_natural_order[] will save us
  170000. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  170001. */
  170002. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  170003. } else {
  170004. if (r != 15)
  170005. break;
  170006. k += 15;
  170007. }
  170008. }
  170009. } else {
  170010. /* Section F.2.2.2: decode the AC coefficients */
  170011. /* In this path we just discard the values */
  170012. for (k = 1; k < DCTSIZE2; k++) {
  170013. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  170014. r = s >> 4;
  170015. s &= 15;
  170016. if (s) {
  170017. k += r;
  170018. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170019. DROP_BITS(s);
  170020. } else {
  170021. if (r != 15)
  170022. break;
  170023. k += 15;
  170024. }
  170025. }
  170026. }
  170027. }
  170028. /* Completed MCU, so update state */
  170029. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170030. ASSIGN_STATE(entropy->saved, state);
  170031. }
  170032. /* Account for restart interval (no-op if not using restarts) */
  170033. entropy->restarts_to_go--;
  170034. return TRUE;
  170035. }
  170036. /*
  170037. * Module initialization routine for Huffman entropy decoding.
  170038. */
  170039. GLOBAL(void)
  170040. jinit_huff_decoder (j_decompress_ptr cinfo)
  170041. {
  170042. huff_entropy_ptr2 entropy;
  170043. int i;
  170044. entropy = (huff_entropy_ptr2)
  170045. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170046. SIZEOF(huff_entropy_decoder2));
  170047. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170048. entropy->pub.start_pass = start_pass_huff_decoder;
  170049. entropy->pub.decode_mcu = decode_mcu;
  170050. /* Mark tables unallocated */
  170051. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170052. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170053. }
  170054. }
  170055. /*** End of inlined file: jdhuff.c ***/
  170056. /*** Start of inlined file: jdinput.c ***/
  170057. #define JPEG_INTERNALS
  170058. /* Private state */
  170059. typedef struct {
  170060. struct jpeg_input_controller pub; /* public fields */
  170061. boolean inheaders; /* TRUE until first SOS is reached */
  170062. } my_input_controller;
  170063. typedef my_input_controller * my_inputctl_ptr;
  170064. /* Forward declarations */
  170065. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170066. /*
  170067. * Routines to calculate various quantities related to the size of the image.
  170068. */
  170069. LOCAL(void)
  170070. initial_setup2 (j_decompress_ptr cinfo)
  170071. /* Called once, when first SOS marker is reached */
  170072. {
  170073. int ci;
  170074. jpeg_component_info *compptr;
  170075. /* Make sure image isn't bigger than I can handle */
  170076. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170077. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170078. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170079. /* For now, precision must match compiled-in value... */
  170080. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170081. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170082. /* Check that number of components won't exceed internal array sizes */
  170083. if (cinfo->num_components > MAX_COMPONENTS)
  170084. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170085. MAX_COMPONENTS);
  170086. /* Compute maximum sampling factors; check factor validity */
  170087. cinfo->max_h_samp_factor = 1;
  170088. cinfo->max_v_samp_factor = 1;
  170089. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170090. ci++, compptr++) {
  170091. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170092. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170093. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170094. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170095. compptr->h_samp_factor);
  170096. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170097. compptr->v_samp_factor);
  170098. }
  170099. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170100. * In the full decompressor, this will be overridden by jdmaster.c;
  170101. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170102. */
  170103. cinfo->min_DCT_scaled_size = DCTSIZE;
  170104. /* Compute dimensions of components */
  170105. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170106. ci++, compptr++) {
  170107. compptr->DCT_scaled_size = DCTSIZE;
  170108. /* Size in DCT blocks */
  170109. compptr->width_in_blocks = (JDIMENSION)
  170110. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170111. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170112. compptr->height_in_blocks = (JDIMENSION)
  170113. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170114. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170115. /* downsampled_width and downsampled_height will also be overridden by
  170116. * jdmaster.c if we are doing full decompression. The transcoder library
  170117. * doesn't use these values, but the calling application might.
  170118. */
  170119. /* Size in samples */
  170120. compptr->downsampled_width = (JDIMENSION)
  170121. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170122. (long) cinfo->max_h_samp_factor);
  170123. compptr->downsampled_height = (JDIMENSION)
  170124. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170125. (long) cinfo->max_v_samp_factor);
  170126. /* Mark component needed, until color conversion says otherwise */
  170127. compptr->component_needed = TRUE;
  170128. /* Mark no quantization table yet saved for component */
  170129. compptr->quant_table = NULL;
  170130. }
  170131. /* Compute number of fully interleaved MCU rows. */
  170132. cinfo->total_iMCU_rows = (JDIMENSION)
  170133. jdiv_round_up((long) cinfo->image_height,
  170134. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170135. /* Decide whether file contains multiple scans */
  170136. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170137. cinfo->inputctl->has_multiple_scans = TRUE;
  170138. else
  170139. cinfo->inputctl->has_multiple_scans = FALSE;
  170140. }
  170141. LOCAL(void)
  170142. per_scan_setup2 (j_decompress_ptr cinfo)
  170143. /* Do computations that are needed before processing a JPEG scan */
  170144. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170145. {
  170146. int ci, mcublks, tmp;
  170147. jpeg_component_info *compptr;
  170148. if (cinfo->comps_in_scan == 1) {
  170149. /* Noninterleaved (single-component) scan */
  170150. compptr = cinfo->cur_comp_info[0];
  170151. /* Overall image size in MCUs */
  170152. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170153. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170154. /* For noninterleaved scan, always one block per MCU */
  170155. compptr->MCU_width = 1;
  170156. compptr->MCU_height = 1;
  170157. compptr->MCU_blocks = 1;
  170158. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170159. compptr->last_col_width = 1;
  170160. /* For noninterleaved scans, it is convenient to define last_row_height
  170161. * as the number of block rows present in the last iMCU row.
  170162. */
  170163. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170164. if (tmp == 0) tmp = compptr->v_samp_factor;
  170165. compptr->last_row_height = tmp;
  170166. /* Prepare array describing MCU composition */
  170167. cinfo->blocks_in_MCU = 1;
  170168. cinfo->MCU_membership[0] = 0;
  170169. } else {
  170170. /* Interleaved (multi-component) scan */
  170171. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170172. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170173. MAX_COMPS_IN_SCAN);
  170174. /* Overall image size in MCUs */
  170175. cinfo->MCUs_per_row = (JDIMENSION)
  170176. jdiv_round_up((long) cinfo->image_width,
  170177. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170178. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170179. jdiv_round_up((long) cinfo->image_height,
  170180. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170181. cinfo->blocks_in_MCU = 0;
  170182. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170183. compptr = cinfo->cur_comp_info[ci];
  170184. /* Sampling factors give # of blocks of component in each MCU */
  170185. compptr->MCU_width = compptr->h_samp_factor;
  170186. compptr->MCU_height = compptr->v_samp_factor;
  170187. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170188. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170189. /* Figure number of non-dummy blocks in last MCU column & row */
  170190. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170191. if (tmp == 0) tmp = compptr->MCU_width;
  170192. compptr->last_col_width = tmp;
  170193. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170194. if (tmp == 0) tmp = compptr->MCU_height;
  170195. compptr->last_row_height = tmp;
  170196. /* Prepare array describing MCU composition */
  170197. mcublks = compptr->MCU_blocks;
  170198. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170199. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170200. while (mcublks-- > 0) {
  170201. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170202. }
  170203. }
  170204. }
  170205. }
  170206. /*
  170207. * Save away a copy of the Q-table referenced by each component present
  170208. * in the current scan, unless already saved during a prior scan.
  170209. *
  170210. * In a multiple-scan JPEG file, the encoder could assign different components
  170211. * the same Q-table slot number, but change table definitions between scans
  170212. * so that each component uses a different Q-table. (The IJG encoder is not
  170213. * currently capable of doing this, but other encoders might.) Since we want
  170214. * to be able to dequantize all the components at the end of the file, this
  170215. * means that we have to save away the table actually used for each component.
  170216. * We do this by copying the table at the start of the first scan containing
  170217. * the component.
  170218. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170219. * slot between scans of a component using that slot. If the encoder does so
  170220. * anyway, this decoder will simply use the Q-table values that were current
  170221. * at the start of the first scan for the component.
  170222. *
  170223. * The decompressor output side looks only at the saved quant tables,
  170224. * not at the current Q-table slots.
  170225. */
  170226. LOCAL(void)
  170227. latch_quant_tables (j_decompress_ptr cinfo)
  170228. {
  170229. int ci, qtblno;
  170230. jpeg_component_info *compptr;
  170231. JQUANT_TBL * qtbl;
  170232. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170233. compptr = cinfo->cur_comp_info[ci];
  170234. /* No work if we already saved Q-table for this component */
  170235. if (compptr->quant_table != NULL)
  170236. continue;
  170237. /* Make sure specified quantization table is present */
  170238. qtblno = compptr->quant_tbl_no;
  170239. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170240. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170241. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170242. /* OK, save away the quantization table */
  170243. qtbl = (JQUANT_TBL *)
  170244. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170245. SIZEOF(JQUANT_TBL));
  170246. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170247. compptr->quant_table = qtbl;
  170248. }
  170249. }
  170250. /*
  170251. * Initialize the input modules to read a scan of compressed data.
  170252. * The first call to this is done by jdmaster.c after initializing
  170253. * the entire decompressor (during jpeg_start_decompress).
  170254. * Subsequent calls come from consume_markers, below.
  170255. */
  170256. METHODDEF(void)
  170257. start_input_pass2 (j_decompress_ptr cinfo)
  170258. {
  170259. per_scan_setup2(cinfo);
  170260. latch_quant_tables(cinfo);
  170261. (*cinfo->entropy->start_pass) (cinfo);
  170262. (*cinfo->coef->start_input_pass) (cinfo);
  170263. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170264. }
  170265. /*
  170266. * Finish up after inputting a compressed-data scan.
  170267. * This is called by the coefficient controller after it's read all
  170268. * the expected data of the scan.
  170269. */
  170270. METHODDEF(void)
  170271. finish_input_pass (j_decompress_ptr cinfo)
  170272. {
  170273. cinfo->inputctl->consume_input = consume_markers;
  170274. }
  170275. /*
  170276. * Read JPEG markers before, between, or after compressed-data scans.
  170277. * Change state as necessary when a new scan is reached.
  170278. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170279. *
  170280. * The consume_input method pointer points either here or to the
  170281. * coefficient controller's consume_data routine, depending on whether
  170282. * we are reading a compressed data segment or inter-segment markers.
  170283. */
  170284. METHODDEF(int)
  170285. consume_markers (j_decompress_ptr cinfo)
  170286. {
  170287. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170288. int val;
  170289. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170290. return JPEG_REACHED_EOI;
  170291. val = (*cinfo->marker->read_markers) (cinfo);
  170292. switch (val) {
  170293. case JPEG_REACHED_SOS: /* Found SOS */
  170294. if (inputctl->inheaders) { /* 1st SOS */
  170295. initial_setup2(cinfo);
  170296. inputctl->inheaders = FALSE;
  170297. /* Note: start_input_pass must be called by jdmaster.c
  170298. * before any more input can be consumed. jdapimin.c is
  170299. * responsible for enforcing this sequencing.
  170300. */
  170301. } else { /* 2nd or later SOS marker */
  170302. if (! inputctl->pub.has_multiple_scans)
  170303. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170304. start_input_pass2(cinfo);
  170305. }
  170306. break;
  170307. case JPEG_REACHED_EOI: /* Found EOI */
  170308. inputctl->pub.eoi_reached = TRUE;
  170309. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170310. if (cinfo->marker->saw_SOF)
  170311. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170312. } else {
  170313. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170314. * if user set output_scan_number larger than number of scans.
  170315. */
  170316. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170317. cinfo->output_scan_number = cinfo->input_scan_number;
  170318. }
  170319. break;
  170320. case JPEG_SUSPENDED:
  170321. break;
  170322. }
  170323. return val;
  170324. }
  170325. /*
  170326. * Reset state to begin a fresh datastream.
  170327. */
  170328. METHODDEF(void)
  170329. reset_input_controller (j_decompress_ptr cinfo)
  170330. {
  170331. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170332. inputctl->pub.consume_input = consume_markers;
  170333. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170334. inputctl->pub.eoi_reached = FALSE;
  170335. inputctl->inheaders = TRUE;
  170336. /* Reset other modules */
  170337. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170338. (*cinfo->marker->reset_marker_reader) (cinfo);
  170339. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170340. cinfo->coef_bits = NULL;
  170341. }
  170342. /*
  170343. * Initialize the input controller module.
  170344. * This is called only once, when the decompression object is created.
  170345. */
  170346. GLOBAL(void)
  170347. jinit_input_controller (j_decompress_ptr cinfo)
  170348. {
  170349. my_inputctl_ptr inputctl;
  170350. /* Create subobject in permanent pool */
  170351. inputctl = (my_inputctl_ptr)
  170352. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170353. SIZEOF(my_input_controller));
  170354. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170355. /* Initialize method pointers */
  170356. inputctl->pub.consume_input = consume_markers;
  170357. inputctl->pub.reset_input_controller = reset_input_controller;
  170358. inputctl->pub.start_input_pass = start_input_pass2;
  170359. inputctl->pub.finish_input_pass = finish_input_pass;
  170360. /* Initialize state: can't use reset_input_controller since we don't
  170361. * want to try to reset other modules yet.
  170362. */
  170363. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170364. inputctl->pub.eoi_reached = FALSE;
  170365. inputctl->inheaders = TRUE;
  170366. }
  170367. /*** End of inlined file: jdinput.c ***/
  170368. /*** Start of inlined file: jdmainct.c ***/
  170369. #define JPEG_INTERNALS
  170370. /*
  170371. * In the current system design, the main buffer need never be a full-image
  170372. * buffer; any full-height buffers will be found inside the coefficient or
  170373. * postprocessing controllers. Nonetheless, the main controller is not
  170374. * trivial. Its responsibility is to provide context rows for upsampling/
  170375. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170376. *
  170377. * Postprocessor input data is counted in "row groups". A row group
  170378. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170379. * sample rows of each component. (We require DCT_scaled_size values to be
  170380. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170381. * values will likely be powers of two, so we actually have the stronger
  170382. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170383. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170384. * row group (times any additional scale factor that the upsampler is
  170385. * applying).
  170386. *
  170387. * The coefficient controller will deliver data to us one iMCU row at a time;
  170388. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170389. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170390. * to one row of MCUs when the image is fully interleaved.) Note that the
  170391. * number of sample rows varies across components, but the number of row
  170392. * groups does not. Some garbage sample rows may be included in the last iMCU
  170393. * row at the bottom of the image.
  170394. *
  170395. * Depending on the vertical scaling algorithm used, the upsampler may need
  170396. * access to the sample row(s) above and below its current input row group.
  170397. * The upsampler is required to set need_context_rows TRUE at global selection
  170398. * time if so. When need_context_rows is FALSE, this controller can simply
  170399. * obtain one iMCU row at a time from the coefficient controller and dole it
  170400. * out as row groups to the postprocessor.
  170401. *
  170402. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170403. * passed to postprocessing contains at least one row group's worth of samples
  170404. * above and below the row group(s) being processed. Note that the context
  170405. * rows "above" the first passed row group appear at negative row offsets in
  170406. * the passed buffer. At the top and bottom of the image, the required
  170407. * context rows are manufactured by duplicating the first or last real sample
  170408. * row; this avoids having special cases in the upsampling inner loops.
  170409. *
  170410. * The amount of context is fixed at one row group just because that's a
  170411. * convenient number for this controller to work with. The existing
  170412. * upsamplers really only need one sample row of context. An upsampler
  170413. * supporting arbitrary output rescaling might wish for more than one row
  170414. * group of context when shrinking the image; tough, we don't handle that.
  170415. * (This is justified by the assumption that downsizing will be handled mostly
  170416. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170417. * the upsample step needn't be much less than one.)
  170418. *
  170419. * To provide the desired context, we have to retain the last two row groups
  170420. * of one iMCU row while reading in the next iMCU row. (The last row group
  170421. * can't be processed until we have another row group for its below-context,
  170422. * and so we have to save the next-to-last group too for its above-context.)
  170423. * We could do this most simply by copying data around in our buffer, but
  170424. * that'd be very slow. We can avoid copying any data by creating a rather
  170425. * strange pointer structure. Here's how it works. We allocate a workspace
  170426. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170427. * of row groups per iMCU row). We create two sets of redundant pointers to
  170428. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170429. * pointer lists look like this:
  170430. * M+1 M-1
  170431. * master pointer --> 0 master pointer --> 0
  170432. * 1 1
  170433. * ... ...
  170434. * M-3 M-3
  170435. * M-2 M
  170436. * M-1 M+1
  170437. * M M-2
  170438. * M+1 M-1
  170439. * 0 0
  170440. * We read alternate iMCU rows using each master pointer; thus the last two
  170441. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170442. * The pointer lists are set up so that the required context rows appear to
  170443. * be adjacent to the proper places when we pass the pointer lists to the
  170444. * upsampler.
  170445. *
  170446. * The above pictures describe the normal state of the pointer lists.
  170447. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170448. * the first or last sample row as necessary (this is cheaper than copying
  170449. * sample rows around).
  170450. *
  170451. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170452. * situation each iMCU row provides only one row group so the buffering logic
  170453. * must be different (eg, we must read two iMCU rows before we can emit the
  170454. * first row group). For now, we simply do not support providing context
  170455. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170456. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170457. * want it quick and dirty, so a context-free upsampler is sufficient.
  170458. */
  170459. /* Private buffer controller object */
  170460. typedef struct {
  170461. struct jpeg_d_main_controller pub; /* public fields */
  170462. /* Pointer to allocated workspace (M or M+2 row groups). */
  170463. JSAMPARRAY buffer[MAX_COMPONENTS];
  170464. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170465. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170466. /* Remaining fields are only used in the context case. */
  170467. /* These are the master pointers to the funny-order pointer lists. */
  170468. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170469. int whichptr; /* indicates which pointer set is now in use */
  170470. int context_state; /* process_data state machine status */
  170471. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170472. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170473. } my_main_controller4;
  170474. typedef my_main_controller4 * my_main_ptr4;
  170475. /* context_state values: */
  170476. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170477. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170478. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170479. /* Forward declarations */
  170480. METHODDEF(void) process_data_simple_main2
  170481. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170482. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170483. METHODDEF(void) process_data_context_main
  170484. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170485. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170486. #ifdef QUANT_2PASS_SUPPORTED
  170487. METHODDEF(void) process_data_crank_post
  170488. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170489. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170490. #endif
  170491. LOCAL(void)
  170492. alloc_funny_pointers (j_decompress_ptr cinfo)
  170493. /* Allocate space for the funny pointer lists.
  170494. * This is done only once, not once per pass.
  170495. */
  170496. {
  170497. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170498. int ci, rgroup;
  170499. int M = cinfo->min_DCT_scaled_size;
  170500. jpeg_component_info *compptr;
  170501. JSAMPARRAY xbuf;
  170502. /* Get top-level space for component array pointers.
  170503. * We alloc both arrays with one call to save a few cycles.
  170504. */
  170505. main_->xbuffer[0] = (JSAMPIMAGE)
  170506. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170507. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  170508. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  170509. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170510. ci++, compptr++) {
  170511. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170512. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170513. /* Get space for pointer lists --- M+4 row groups in each list.
  170514. * We alloc both pointer lists with one call to save a few cycles.
  170515. */
  170516. xbuf = (JSAMPARRAY)
  170517. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170518. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  170519. xbuf += rgroup; /* want one row group at negative offsets */
  170520. main_->xbuffer[0][ci] = xbuf;
  170521. xbuf += rgroup * (M + 4);
  170522. main_->xbuffer[1][ci] = xbuf;
  170523. }
  170524. }
  170525. LOCAL(void)
  170526. make_funny_pointers (j_decompress_ptr cinfo)
  170527. /* Create the funny pointer lists discussed in the comments above.
  170528. * The actual workspace is already allocated (in main->buffer),
  170529. * and the space for the pointer lists is allocated too.
  170530. * This routine just fills in the curiously ordered lists.
  170531. * This will be repeated at the beginning of each pass.
  170532. */
  170533. {
  170534. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170535. int ci, i, rgroup;
  170536. int M = cinfo->min_DCT_scaled_size;
  170537. jpeg_component_info *compptr;
  170538. JSAMPARRAY buf, xbuf0, xbuf1;
  170539. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170540. ci++, compptr++) {
  170541. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170542. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170543. xbuf0 = main_->xbuffer[0][ci];
  170544. xbuf1 = main_->xbuffer[1][ci];
  170545. /* First copy the workspace pointers as-is */
  170546. buf = main_->buffer[ci];
  170547. for (i = 0; i < rgroup * (M + 2); i++) {
  170548. xbuf0[i] = xbuf1[i] = buf[i];
  170549. }
  170550. /* In the second list, put the last four row groups in swapped order */
  170551. for (i = 0; i < rgroup * 2; i++) {
  170552. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  170553. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  170554. }
  170555. /* The wraparound pointers at top and bottom will be filled later
  170556. * (see set_wraparound_pointers, below). Initially we want the "above"
  170557. * pointers to duplicate the first actual data line. This only needs
  170558. * to happen in xbuffer[0].
  170559. */
  170560. for (i = 0; i < rgroup; i++) {
  170561. xbuf0[i - rgroup] = xbuf0[0];
  170562. }
  170563. }
  170564. }
  170565. LOCAL(void)
  170566. set_wraparound_pointers (j_decompress_ptr cinfo)
  170567. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  170568. * This changes the pointer list state from top-of-image to the normal state.
  170569. */
  170570. {
  170571. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170572. int ci, i, rgroup;
  170573. int M = cinfo->min_DCT_scaled_size;
  170574. jpeg_component_info *compptr;
  170575. JSAMPARRAY xbuf0, xbuf1;
  170576. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170577. ci++, compptr++) {
  170578. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170579. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170580. xbuf0 = main_->xbuffer[0][ci];
  170581. xbuf1 = main_->xbuffer[1][ci];
  170582. for (i = 0; i < rgroup; i++) {
  170583. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  170584. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  170585. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  170586. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  170587. }
  170588. }
  170589. }
  170590. LOCAL(void)
  170591. set_bottom_pointers (j_decompress_ptr cinfo)
  170592. /* Change the pointer lists to duplicate the last sample row at the bottom
  170593. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  170594. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  170595. */
  170596. {
  170597. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170598. int ci, i, rgroup, iMCUheight, rows_left;
  170599. jpeg_component_info *compptr;
  170600. JSAMPARRAY xbuf;
  170601. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170602. ci++, compptr++) {
  170603. /* Count sample rows in one iMCU row and in one row group */
  170604. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  170605. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  170606. /* Count nondummy sample rows remaining for this component */
  170607. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  170608. if (rows_left == 0) rows_left = iMCUheight;
  170609. /* Count nondummy row groups. Should get same answer for each component,
  170610. * so we need only do it once.
  170611. */
  170612. if (ci == 0) {
  170613. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  170614. }
  170615. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  170616. * last partial rowgroup and ensures at least one full rowgroup of context.
  170617. */
  170618. xbuf = main_->xbuffer[main_->whichptr][ci];
  170619. for (i = 0; i < rgroup * 2; i++) {
  170620. xbuf[rows_left + i] = xbuf[rows_left-1];
  170621. }
  170622. }
  170623. }
  170624. /*
  170625. * Initialize for a processing pass.
  170626. */
  170627. METHODDEF(void)
  170628. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170629. {
  170630. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170631. switch (pass_mode) {
  170632. case JBUF_PASS_THRU:
  170633. if (cinfo->upsample->need_context_rows) {
  170634. main_->pub.process_data = process_data_context_main;
  170635. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  170636. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  170637. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170638. main_->iMCU_row_ctr = 0;
  170639. } else {
  170640. /* Simple case with no context needed */
  170641. main_->pub.process_data = process_data_simple_main2;
  170642. }
  170643. main_->buffer_full = FALSE; /* Mark buffer empty */
  170644. main_->rowgroup_ctr = 0;
  170645. break;
  170646. #ifdef QUANT_2PASS_SUPPORTED
  170647. case JBUF_CRANK_DEST:
  170648. /* For last pass of 2-pass quantization, just crank the postprocessor */
  170649. main_->pub.process_data = process_data_crank_post;
  170650. break;
  170651. #endif
  170652. default:
  170653. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170654. break;
  170655. }
  170656. }
  170657. /*
  170658. * Process some data.
  170659. * This handles the simple case where no context is required.
  170660. */
  170661. METHODDEF(void)
  170662. process_data_simple_main2 (j_decompress_ptr cinfo,
  170663. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170664. JDIMENSION out_rows_avail)
  170665. {
  170666. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170667. JDIMENSION rowgroups_avail;
  170668. /* Read input data if we haven't filled the main buffer yet */
  170669. if (! main_->buffer_full) {
  170670. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  170671. return; /* suspension forced, can do nothing more */
  170672. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170673. }
  170674. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  170675. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  170676. /* Note: at the bottom of the image, we may pass extra garbage row groups
  170677. * to the postprocessor. The postprocessor has to check for bottom
  170678. * of image anyway (at row resolution), so no point in us doing it too.
  170679. */
  170680. /* Feed the postprocessor */
  170681. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  170682. &main_->rowgroup_ctr, rowgroups_avail,
  170683. output_buf, out_row_ctr, out_rows_avail);
  170684. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  170685. if (main_->rowgroup_ctr >= rowgroups_avail) {
  170686. main_->buffer_full = FALSE;
  170687. main_->rowgroup_ctr = 0;
  170688. }
  170689. }
  170690. /*
  170691. * Process some data.
  170692. * This handles the case where context rows must be provided.
  170693. */
  170694. METHODDEF(void)
  170695. process_data_context_main (j_decompress_ptr cinfo,
  170696. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170697. JDIMENSION out_rows_avail)
  170698. {
  170699. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170700. /* Read input data if we haven't filled the main buffer yet */
  170701. if (! main_->buffer_full) {
  170702. if (! (*cinfo->coef->decompress_data) (cinfo,
  170703. main_->xbuffer[main_->whichptr]))
  170704. return; /* suspension forced, can do nothing more */
  170705. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170706. main_->iMCU_row_ctr++; /* count rows received */
  170707. }
  170708. /* Postprocessor typically will not swallow all the input data it is handed
  170709. * in one call (due to filling the output buffer first). Must be prepared
  170710. * to exit and restart. This switch lets us keep track of how far we got.
  170711. * Note that each case falls through to the next on successful completion.
  170712. */
  170713. switch (main_->context_state) {
  170714. case CTX_POSTPONED_ROW:
  170715. /* Call postprocessor using previously set pointers for postponed row */
  170716. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170717. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170718. output_buf, out_row_ctr, out_rows_avail);
  170719. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170720. return; /* Need to suspend */
  170721. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170722. if (*out_row_ctr >= out_rows_avail)
  170723. return; /* Postprocessor exactly filled output buf */
  170724. /*FALLTHROUGH*/
  170725. case CTX_PREPARE_FOR_IMCU:
  170726. /* Prepare to process first M-1 row groups of this iMCU row */
  170727. main_->rowgroup_ctr = 0;
  170728. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  170729. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  170730. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  170731. */
  170732. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  170733. set_bottom_pointers(cinfo);
  170734. main_->context_state = CTX_PROCESS_IMCU;
  170735. /*FALLTHROUGH*/
  170736. case CTX_PROCESS_IMCU:
  170737. /* Call postprocessor using previously set pointers */
  170738. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170739. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170740. output_buf, out_row_ctr, out_rows_avail);
  170741. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170742. return; /* Need to suspend */
  170743. /* After the first iMCU, change wraparound pointers to normal state */
  170744. if (main_->iMCU_row_ctr == 1)
  170745. set_wraparound_pointers(cinfo);
  170746. /* Prepare to load new iMCU row using other xbuffer list */
  170747. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  170748. main_->buffer_full = FALSE;
  170749. /* Still need to process last row group of this iMCU row, */
  170750. /* which is saved at index M+1 of the other xbuffer */
  170751. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  170752. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  170753. main_->context_state = CTX_POSTPONED_ROW;
  170754. }
  170755. }
  170756. /*
  170757. * Process some data.
  170758. * Final pass of two-pass quantization: just call the postprocessor.
  170759. * Source data will be the postprocessor controller's internal buffer.
  170760. */
  170761. #ifdef QUANT_2PASS_SUPPORTED
  170762. METHODDEF(void)
  170763. process_data_crank_post (j_decompress_ptr cinfo,
  170764. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170765. JDIMENSION out_rows_avail)
  170766. {
  170767. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  170768. (JDIMENSION *) NULL, (JDIMENSION) 0,
  170769. output_buf, out_row_ctr, out_rows_avail);
  170770. }
  170771. #endif /* QUANT_2PASS_SUPPORTED */
  170772. /*
  170773. * Initialize main buffer controller.
  170774. */
  170775. GLOBAL(void)
  170776. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  170777. {
  170778. my_main_ptr4 main_;
  170779. int ci, rgroup, ngroups;
  170780. jpeg_component_info *compptr;
  170781. main_ = (my_main_ptr4)
  170782. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170783. SIZEOF(my_main_controller4));
  170784. cinfo->main = (struct jpeg_d_main_controller *) main_;
  170785. main_->pub.start_pass = start_pass_main2;
  170786. if (need_full_buffer) /* shouldn't happen */
  170787. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170788. /* Allocate the workspace.
  170789. * ngroups is the number of row groups we need.
  170790. */
  170791. if (cinfo->upsample->need_context_rows) {
  170792. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  170793. ERREXIT(cinfo, JERR_NOTIMPL);
  170794. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  170795. ngroups = cinfo->min_DCT_scaled_size + 2;
  170796. } else {
  170797. ngroups = cinfo->min_DCT_scaled_size;
  170798. }
  170799. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170800. ci++, compptr++) {
  170801. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170802. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170803. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  170804. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170805. compptr->width_in_blocks * compptr->DCT_scaled_size,
  170806. (JDIMENSION) (rgroup * ngroups));
  170807. }
  170808. }
  170809. /*** End of inlined file: jdmainct.c ***/
  170810. /*** Start of inlined file: jdmarker.c ***/
  170811. #define JPEG_INTERNALS
  170812. /* Private state */
  170813. typedef struct {
  170814. struct jpeg_marker_reader pub; /* public fields */
  170815. /* Application-overridable marker processing methods */
  170816. jpeg_marker_parser_method process_COM;
  170817. jpeg_marker_parser_method process_APPn[16];
  170818. /* Limit on marker data length to save for each marker type */
  170819. unsigned int length_limit_COM;
  170820. unsigned int length_limit_APPn[16];
  170821. /* Status of COM/APPn marker saving */
  170822. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  170823. unsigned int bytes_read; /* data bytes read so far in marker */
  170824. /* Note: cur_marker is not linked into marker_list until it's all read. */
  170825. } my_marker_reader;
  170826. typedef my_marker_reader * my_marker_ptr2;
  170827. /*
  170828. * Macros for fetching data from the data source module.
  170829. *
  170830. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  170831. * the current restart point; we update them only when we have reached a
  170832. * suitable place to restart if a suspension occurs.
  170833. */
  170834. /* Declare and initialize local copies of input pointer/count */
  170835. #define INPUT_VARS(cinfo) \
  170836. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  170837. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  170838. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  170839. /* Unload the local copies --- do this only at a restart boundary */
  170840. #define INPUT_SYNC(cinfo) \
  170841. ( datasrc->next_input_byte = next_input_byte, \
  170842. datasrc->bytes_in_buffer = bytes_in_buffer )
  170843. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  170844. #define INPUT_RELOAD(cinfo) \
  170845. ( next_input_byte = datasrc->next_input_byte, \
  170846. bytes_in_buffer = datasrc->bytes_in_buffer )
  170847. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  170848. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  170849. * but we must reload the local copies after a successful fill.
  170850. */
  170851. #define MAKE_BYTE_AVAIL(cinfo,action) \
  170852. if (bytes_in_buffer == 0) { \
  170853. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  170854. { action; } \
  170855. INPUT_RELOAD(cinfo); \
  170856. }
  170857. /* Read a byte into variable V.
  170858. * If must suspend, take the specified action (typically "return FALSE").
  170859. */
  170860. #define INPUT_BYTE(cinfo,V,action) \
  170861. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170862. bytes_in_buffer--; \
  170863. V = GETJOCTET(*next_input_byte++); )
  170864. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  170865. * V should be declared unsigned int or perhaps INT32.
  170866. */
  170867. #define INPUT_2BYTES(cinfo,V,action) \
  170868. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170869. bytes_in_buffer--; \
  170870. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  170871. MAKE_BYTE_AVAIL(cinfo,action); \
  170872. bytes_in_buffer--; \
  170873. V += GETJOCTET(*next_input_byte++); )
  170874. /*
  170875. * Routines to process JPEG markers.
  170876. *
  170877. * Entry condition: JPEG marker itself has been read and its code saved
  170878. * in cinfo->unread_marker; input restart point is just after the marker.
  170879. *
  170880. * Exit: if return TRUE, have read and processed any parameters, and have
  170881. * updated the restart point to point after the parameters.
  170882. * If return FALSE, was forced to suspend before reaching end of
  170883. * marker parameters; restart point has not been moved. Same routine
  170884. * will be called again after application supplies more input data.
  170885. *
  170886. * This approach to suspension assumes that all of a marker's parameters
  170887. * can fit into a single input bufferload. This should hold for "normal"
  170888. * markers. Some COM/APPn markers might have large parameter segments
  170889. * that might not fit. If we are simply dropping such a marker, we use
  170890. * skip_input_data to get past it, and thereby put the problem on the
  170891. * source manager's shoulders. If we are saving the marker's contents
  170892. * into memory, we use a slightly different convention: when forced to
  170893. * suspend, the marker processor updates the restart point to the end of
  170894. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  170895. * On resumption, cinfo->unread_marker still contains the marker code,
  170896. * but the data source will point to the next chunk of marker data.
  170897. * The marker processor must retain internal state to deal with this.
  170898. *
  170899. * Note that we don't bother to avoid duplicate trace messages if a
  170900. * suspension occurs within marker parameters. Other side effects
  170901. * require more care.
  170902. */
  170903. LOCAL(boolean)
  170904. get_soi (j_decompress_ptr cinfo)
  170905. /* Process an SOI marker */
  170906. {
  170907. int i;
  170908. TRACEMS(cinfo, 1, JTRC_SOI);
  170909. if (cinfo->marker->saw_SOI)
  170910. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  170911. /* Reset all parameters that are defined to be reset by SOI */
  170912. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  170913. cinfo->arith_dc_L[i] = 0;
  170914. cinfo->arith_dc_U[i] = 1;
  170915. cinfo->arith_ac_K[i] = 5;
  170916. }
  170917. cinfo->restart_interval = 0;
  170918. /* Set initial assumptions for colorspace etc */
  170919. cinfo->jpeg_color_space = JCS_UNKNOWN;
  170920. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  170921. cinfo->saw_JFIF_marker = FALSE;
  170922. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  170923. cinfo->JFIF_minor_version = 1;
  170924. cinfo->density_unit = 0;
  170925. cinfo->X_density = 1;
  170926. cinfo->Y_density = 1;
  170927. cinfo->saw_Adobe_marker = FALSE;
  170928. cinfo->Adobe_transform = 0;
  170929. cinfo->marker->saw_SOI = TRUE;
  170930. return TRUE;
  170931. }
  170932. LOCAL(boolean)
  170933. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  170934. /* Process a SOFn marker */
  170935. {
  170936. INT32 length;
  170937. int c, ci;
  170938. jpeg_component_info * compptr;
  170939. INPUT_VARS(cinfo);
  170940. cinfo->progressive_mode = is_prog;
  170941. cinfo->arith_code = is_arith;
  170942. INPUT_2BYTES(cinfo, length, return FALSE);
  170943. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  170944. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  170945. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  170946. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  170947. length -= 8;
  170948. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  170949. (int) cinfo->image_width, (int) cinfo->image_height,
  170950. cinfo->num_components);
  170951. if (cinfo->marker->saw_SOF)
  170952. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  170953. /* We don't support files in which the image height is initially specified */
  170954. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  170955. /* might as well have a general sanity check. */
  170956. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  170957. || cinfo->num_components <= 0)
  170958. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  170959. if (length != (cinfo->num_components * 3))
  170960. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170961. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  170962. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  170963. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170964. cinfo->num_components * SIZEOF(jpeg_component_info));
  170965. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170966. ci++, compptr++) {
  170967. compptr->component_index = ci;
  170968. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  170969. INPUT_BYTE(cinfo, c, return FALSE);
  170970. compptr->h_samp_factor = (c >> 4) & 15;
  170971. compptr->v_samp_factor = (c ) & 15;
  170972. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  170973. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  170974. compptr->component_id, compptr->h_samp_factor,
  170975. compptr->v_samp_factor, compptr->quant_tbl_no);
  170976. }
  170977. cinfo->marker->saw_SOF = TRUE;
  170978. INPUT_SYNC(cinfo);
  170979. return TRUE;
  170980. }
  170981. LOCAL(boolean)
  170982. get_sos (j_decompress_ptr cinfo)
  170983. /* Process a SOS marker */
  170984. {
  170985. INT32 length;
  170986. int i, ci, n, c, cc;
  170987. jpeg_component_info * compptr;
  170988. INPUT_VARS(cinfo);
  170989. if (! cinfo->marker->saw_SOF)
  170990. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  170991. INPUT_2BYTES(cinfo, length, return FALSE);
  170992. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  170993. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  170994. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  170995. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170996. cinfo->comps_in_scan = n;
  170997. /* Collect the component-spec parameters */
  170998. for (i = 0; i < n; i++) {
  170999. INPUT_BYTE(cinfo, cc, return FALSE);
  171000. INPUT_BYTE(cinfo, c, return FALSE);
  171001. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171002. ci++, compptr++) {
  171003. if (cc == compptr->component_id)
  171004. goto id_found;
  171005. }
  171006. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  171007. id_found:
  171008. cinfo->cur_comp_info[i] = compptr;
  171009. compptr->dc_tbl_no = (c >> 4) & 15;
  171010. compptr->ac_tbl_no = (c ) & 15;
  171011. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  171012. compptr->dc_tbl_no, compptr->ac_tbl_no);
  171013. }
  171014. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  171015. INPUT_BYTE(cinfo, c, return FALSE);
  171016. cinfo->Ss = c;
  171017. INPUT_BYTE(cinfo, c, return FALSE);
  171018. cinfo->Se = c;
  171019. INPUT_BYTE(cinfo, c, return FALSE);
  171020. cinfo->Ah = (c >> 4) & 15;
  171021. cinfo->Al = (c ) & 15;
  171022. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171023. cinfo->Ah, cinfo->Al);
  171024. /* Prepare to scan data & restart markers */
  171025. cinfo->marker->next_restart_num = 0;
  171026. /* Count another SOS marker */
  171027. cinfo->input_scan_number++;
  171028. INPUT_SYNC(cinfo);
  171029. return TRUE;
  171030. }
  171031. #ifdef D_ARITH_CODING_SUPPORTED
  171032. LOCAL(boolean)
  171033. get_dac (j_decompress_ptr cinfo)
  171034. /* Process a DAC marker */
  171035. {
  171036. INT32 length;
  171037. int index, val;
  171038. INPUT_VARS(cinfo);
  171039. INPUT_2BYTES(cinfo, length, return FALSE);
  171040. length -= 2;
  171041. while (length > 0) {
  171042. INPUT_BYTE(cinfo, index, return FALSE);
  171043. INPUT_BYTE(cinfo, val, return FALSE);
  171044. length -= 2;
  171045. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171046. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171047. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171048. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171049. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171050. } else { /* define DC table */
  171051. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171052. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171053. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171054. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171055. }
  171056. }
  171057. if (length != 0)
  171058. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171059. INPUT_SYNC(cinfo);
  171060. return TRUE;
  171061. }
  171062. #else /* ! D_ARITH_CODING_SUPPORTED */
  171063. #define get_dac(cinfo) skip_variable(cinfo)
  171064. #endif /* D_ARITH_CODING_SUPPORTED */
  171065. LOCAL(boolean)
  171066. get_dht (j_decompress_ptr cinfo)
  171067. /* Process a DHT marker */
  171068. {
  171069. INT32 length;
  171070. UINT8 bits[17];
  171071. UINT8 huffval[256];
  171072. int i, index, count;
  171073. JHUFF_TBL **htblptr;
  171074. INPUT_VARS(cinfo);
  171075. INPUT_2BYTES(cinfo, length, return FALSE);
  171076. length -= 2;
  171077. while (length > 16) {
  171078. INPUT_BYTE(cinfo, index, return FALSE);
  171079. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171080. bits[0] = 0;
  171081. count = 0;
  171082. for (i = 1; i <= 16; i++) {
  171083. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171084. count += bits[i];
  171085. }
  171086. length -= 1 + 16;
  171087. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171088. bits[1], bits[2], bits[3], bits[4],
  171089. bits[5], bits[6], bits[7], bits[8]);
  171090. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171091. bits[9], bits[10], bits[11], bits[12],
  171092. bits[13], bits[14], bits[15], bits[16]);
  171093. /* Here we just do minimal validation of the counts to avoid walking
  171094. * off the end of our table space. jdhuff.c will check more carefully.
  171095. */
  171096. if (count > 256 || ((INT32) count) > length)
  171097. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171098. for (i = 0; i < count; i++)
  171099. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171100. length -= count;
  171101. if (index & 0x10) { /* AC table definition */
  171102. index -= 0x10;
  171103. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171104. } else { /* DC table definition */
  171105. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171106. }
  171107. if (index < 0 || index >= NUM_HUFF_TBLS)
  171108. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171109. if (*htblptr == NULL)
  171110. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171111. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171112. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171113. }
  171114. if (length != 0)
  171115. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171116. INPUT_SYNC(cinfo);
  171117. return TRUE;
  171118. }
  171119. LOCAL(boolean)
  171120. get_dqt (j_decompress_ptr cinfo)
  171121. /* Process a DQT marker */
  171122. {
  171123. INT32 length;
  171124. int n, i, prec;
  171125. unsigned int tmp;
  171126. JQUANT_TBL *quant_ptr;
  171127. INPUT_VARS(cinfo);
  171128. INPUT_2BYTES(cinfo, length, return FALSE);
  171129. length -= 2;
  171130. while (length > 0) {
  171131. INPUT_BYTE(cinfo, n, return FALSE);
  171132. prec = n >> 4;
  171133. n &= 0x0F;
  171134. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171135. if (n >= NUM_QUANT_TBLS)
  171136. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171137. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171138. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171139. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171140. for (i = 0; i < DCTSIZE2; i++) {
  171141. if (prec)
  171142. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171143. else
  171144. INPUT_BYTE(cinfo, tmp, return FALSE);
  171145. /* We convert the zigzag-order table to natural array order. */
  171146. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171147. }
  171148. if (cinfo->err->trace_level >= 2) {
  171149. for (i = 0; i < DCTSIZE2; i += 8) {
  171150. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171151. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171152. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171153. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171154. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171155. }
  171156. }
  171157. length -= DCTSIZE2+1;
  171158. if (prec) length -= DCTSIZE2;
  171159. }
  171160. if (length != 0)
  171161. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171162. INPUT_SYNC(cinfo);
  171163. return TRUE;
  171164. }
  171165. LOCAL(boolean)
  171166. get_dri (j_decompress_ptr cinfo)
  171167. /* Process a DRI marker */
  171168. {
  171169. INT32 length;
  171170. unsigned int tmp;
  171171. INPUT_VARS(cinfo);
  171172. INPUT_2BYTES(cinfo, length, return FALSE);
  171173. if (length != 4)
  171174. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171175. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171176. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171177. cinfo->restart_interval = tmp;
  171178. INPUT_SYNC(cinfo);
  171179. return TRUE;
  171180. }
  171181. /*
  171182. * Routines for processing APPn and COM markers.
  171183. * These are either saved in memory or discarded, per application request.
  171184. * APP0 and APP14 are specially checked to see if they are
  171185. * JFIF and Adobe markers, respectively.
  171186. */
  171187. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171188. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171189. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171190. LOCAL(void)
  171191. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171192. unsigned int datalen, INT32 remaining)
  171193. /* Examine first few bytes from an APP0.
  171194. * Take appropriate action if it is a JFIF marker.
  171195. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171196. */
  171197. {
  171198. INT32 totallen = (INT32) datalen + remaining;
  171199. if (datalen >= APP0_DATA_LEN &&
  171200. GETJOCTET(data[0]) == 0x4A &&
  171201. GETJOCTET(data[1]) == 0x46 &&
  171202. GETJOCTET(data[2]) == 0x49 &&
  171203. GETJOCTET(data[3]) == 0x46 &&
  171204. GETJOCTET(data[4]) == 0) {
  171205. /* Found JFIF APP0 marker: save info */
  171206. cinfo->saw_JFIF_marker = TRUE;
  171207. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171208. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171209. cinfo->density_unit = GETJOCTET(data[7]);
  171210. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171211. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171212. /* Check version.
  171213. * Major version must be 1, anything else signals an incompatible change.
  171214. * (We used to treat this as an error, but now it's a nonfatal warning,
  171215. * because some bozo at Hijaak couldn't read the spec.)
  171216. * Minor version should be 0..2, but process anyway if newer.
  171217. */
  171218. if (cinfo->JFIF_major_version != 1)
  171219. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171220. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171221. /* Generate trace messages */
  171222. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171223. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171224. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171225. /* Validate thumbnail dimensions and issue appropriate messages */
  171226. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171227. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171228. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171229. totallen -= APP0_DATA_LEN;
  171230. if (totallen !=
  171231. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171232. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171233. } else if (datalen >= 6 &&
  171234. GETJOCTET(data[0]) == 0x4A &&
  171235. GETJOCTET(data[1]) == 0x46 &&
  171236. GETJOCTET(data[2]) == 0x58 &&
  171237. GETJOCTET(data[3]) == 0x58 &&
  171238. GETJOCTET(data[4]) == 0) {
  171239. /* Found JFIF "JFXX" extension APP0 marker */
  171240. /* The library doesn't actually do anything with these,
  171241. * but we try to produce a helpful trace message.
  171242. */
  171243. switch (GETJOCTET(data[5])) {
  171244. case 0x10:
  171245. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171246. break;
  171247. case 0x11:
  171248. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171249. break;
  171250. case 0x13:
  171251. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171252. break;
  171253. default:
  171254. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171255. GETJOCTET(data[5]), (int) totallen);
  171256. break;
  171257. }
  171258. } else {
  171259. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171260. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171261. }
  171262. }
  171263. LOCAL(void)
  171264. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171265. unsigned int datalen, INT32 remaining)
  171266. /* Examine first few bytes from an APP14.
  171267. * Take appropriate action if it is an Adobe marker.
  171268. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171269. */
  171270. {
  171271. unsigned int version, flags0, flags1, transform;
  171272. if (datalen >= APP14_DATA_LEN &&
  171273. GETJOCTET(data[0]) == 0x41 &&
  171274. GETJOCTET(data[1]) == 0x64 &&
  171275. GETJOCTET(data[2]) == 0x6F &&
  171276. GETJOCTET(data[3]) == 0x62 &&
  171277. GETJOCTET(data[4]) == 0x65) {
  171278. /* Found Adobe APP14 marker */
  171279. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171280. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171281. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171282. transform = GETJOCTET(data[11]);
  171283. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171284. cinfo->saw_Adobe_marker = TRUE;
  171285. cinfo->Adobe_transform = (UINT8) transform;
  171286. } else {
  171287. /* Start of APP14 does not match "Adobe", or too short */
  171288. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171289. }
  171290. }
  171291. METHODDEF(boolean)
  171292. get_interesting_appn (j_decompress_ptr cinfo)
  171293. /* Process an APP0 or APP14 marker without saving it */
  171294. {
  171295. INT32 length;
  171296. JOCTET b[APPN_DATA_LEN];
  171297. unsigned int i, numtoread;
  171298. INPUT_VARS(cinfo);
  171299. INPUT_2BYTES(cinfo, length, return FALSE);
  171300. length -= 2;
  171301. /* get the interesting part of the marker data */
  171302. if (length >= APPN_DATA_LEN)
  171303. numtoread = APPN_DATA_LEN;
  171304. else if (length > 0)
  171305. numtoread = (unsigned int) length;
  171306. else
  171307. numtoread = 0;
  171308. for (i = 0; i < numtoread; i++)
  171309. INPUT_BYTE(cinfo, b[i], return FALSE);
  171310. length -= numtoread;
  171311. /* process it */
  171312. switch (cinfo->unread_marker) {
  171313. case M_APP0:
  171314. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171315. break;
  171316. case M_APP14:
  171317. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171318. break;
  171319. default:
  171320. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171321. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171322. break;
  171323. }
  171324. /* skip any remaining data -- could be lots */
  171325. INPUT_SYNC(cinfo);
  171326. if (length > 0)
  171327. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171328. return TRUE;
  171329. }
  171330. #ifdef SAVE_MARKERS_SUPPORTED
  171331. METHODDEF(boolean)
  171332. save_marker (j_decompress_ptr cinfo)
  171333. /* Save an APPn or COM marker into the marker list */
  171334. {
  171335. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171336. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171337. unsigned int bytes_read, data_length;
  171338. JOCTET FAR * data;
  171339. INT32 length = 0;
  171340. INPUT_VARS(cinfo);
  171341. if (cur_marker == NULL) {
  171342. /* begin reading a marker */
  171343. INPUT_2BYTES(cinfo, length, return FALSE);
  171344. length -= 2;
  171345. if (length >= 0) { /* watch out for bogus length word */
  171346. /* figure out how much we want to save */
  171347. unsigned int limit;
  171348. if (cinfo->unread_marker == (int) M_COM)
  171349. limit = marker->length_limit_COM;
  171350. else
  171351. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171352. if ((unsigned int) length < limit)
  171353. limit = (unsigned int) length;
  171354. /* allocate and initialize the marker item */
  171355. cur_marker = (jpeg_saved_marker_ptr)
  171356. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171357. SIZEOF(struct jpeg_marker_struct) + limit);
  171358. cur_marker->next = NULL;
  171359. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171360. cur_marker->original_length = (unsigned int) length;
  171361. cur_marker->data_length = limit;
  171362. /* data area is just beyond the jpeg_marker_struct */
  171363. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171364. marker->cur_marker = cur_marker;
  171365. marker->bytes_read = 0;
  171366. bytes_read = 0;
  171367. data_length = limit;
  171368. } else {
  171369. /* deal with bogus length word */
  171370. bytes_read = data_length = 0;
  171371. data = NULL;
  171372. }
  171373. } else {
  171374. /* resume reading a marker */
  171375. bytes_read = marker->bytes_read;
  171376. data_length = cur_marker->data_length;
  171377. data = cur_marker->data + bytes_read;
  171378. }
  171379. while (bytes_read < data_length) {
  171380. INPUT_SYNC(cinfo); /* move the restart point to here */
  171381. marker->bytes_read = bytes_read;
  171382. /* If there's not at least one byte in buffer, suspend */
  171383. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171384. /* Copy bytes with reasonable rapidity */
  171385. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171386. *data++ = *next_input_byte++;
  171387. bytes_in_buffer--;
  171388. bytes_read++;
  171389. }
  171390. }
  171391. /* Done reading what we want to read */
  171392. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171393. /* Add new marker to end of list */
  171394. if (cinfo->marker_list == NULL) {
  171395. cinfo->marker_list = cur_marker;
  171396. } else {
  171397. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171398. while (prev->next != NULL)
  171399. prev = prev->next;
  171400. prev->next = cur_marker;
  171401. }
  171402. /* Reset pointer & calc remaining data length */
  171403. data = cur_marker->data;
  171404. length = cur_marker->original_length - data_length;
  171405. }
  171406. /* Reset to initial state for next marker */
  171407. marker->cur_marker = NULL;
  171408. /* Process the marker if interesting; else just make a generic trace msg */
  171409. switch (cinfo->unread_marker) {
  171410. case M_APP0:
  171411. examine_app0(cinfo, data, data_length, length);
  171412. break;
  171413. case M_APP14:
  171414. examine_app14(cinfo, data, data_length, length);
  171415. break;
  171416. default:
  171417. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171418. (int) (data_length + length));
  171419. break;
  171420. }
  171421. /* skip any remaining data -- could be lots */
  171422. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171423. if (length > 0)
  171424. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171425. return TRUE;
  171426. }
  171427. #endif /* SAVE_MARKERS_SUPPORTED */
  171428. METHODDEF(boolean)
  171429. skip_variable (j_decompress_ptr cinfo)
  171430. /* Skip over an unknown or uninteresting variable-length marker */
  171431. {
  171432. INT32 length;
  171433. INPUT_VARS(cinfo);
  171434. INPUT_2BYTES(cinfo, length, return FALSE);
  171435. length -= 2;
  171436. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171437. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171438. if (length > 0)
  171439. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171440. return TRUE;
  171441. }
  171442. /*
  171443. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171444. * Returns FALSE if had to suspend before reaching a marker;
  171445. * in that case cinfo->unread_marker is unchanged.
  171446. *
  171447. * Note that the result might not be a valid marker code,
  171448. * but it will never be 0 or FF.
  171449. */
  171450. LOCAL(boolean)
  171451. next_marker (j_decompress_ptr cinfo)
  171452. {
  171453. int c;
  171454. INPUT_VARS(cinfo);
  171455. for (;;) {
  171456. INPUT_BYTE(cinfo, c, return FALSE);
  171457. /* Skip any non-FF bytes.
  171458. * This may look a bit inefficient, but it will not occur in a valid file.
  171459. * We sync after each discarded byte so that a suspending data source
  171460. * can discard the byte from its buffer.
  171461. */
  171462. while (c != 0xFF) {
  171463. cinfo->marker->discarded_bytes++;
  171464. INPUT_SYNC(cinfo);
  171465. INPUT_BYTE(cinfo, c, return FALSE);
  171466. }
  171467. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171468. * pad bytes, so don't count them in discarded_bytes. We assume there
  171469. * will not be so many consecutive FF bytes as to overflow a suspending
  171470. * data source's input buffer.
  171471. */
  171472. do {
  171473. INPUT_BYTE(cinfo, c, return FALSE);
  171474. } while (c == 0xFF);
  171475. if (c != 0)
  171476. break; /* found a valid marker, exit loop */
  171477. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171478. * Discard it and loop back to try again.
  171479. */
  171480. cinfo->marker->discarded_bytes += 2;
  171481. INPUT_SYNC(cinfo);
  171482. }
  171483. if (cinfo->marker->discarded_bytes != 0) {
  171484. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171485. cinfo->marker->discarded_bytes = 0;
  171486. }
  171487. cinfo->unread_marker = c;
  171488. INPUT_SYNC(cinfo);
  171489. return TRUE;
  171490. }
  171491. LOCAL(boolean)
  171492. first_marker (j_decompress_ptr cinfo)
  171493. /* Like next_marker, but used to obtain the initial SOI marker. */
  171494. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  171495. * we might well scan an entire input file before realizing it ain't JPEG.
  171496. * If an application wants to process non-JFIF files, it must seek to the
  171497. * SOI before calling the JPEG library.
  171498. */
  171499. {
  171500. int c, c2;
  171501. INPUT_VARS(cinfo);
  171502. INPUT_BYTE(cinfo, c, return FALSE);
  171503. INPUT_BYTE(cinfo, c2, return FALSE);
  171504. if (c != 0xFF || c2 != (int) M_SOI)
  171505. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  171506. cinfo->unread_marker = c2;
  171507. INPUT_SYNC(cinfo);
  171508. return TRUE;
  171509. }
  171510. /*
  171511. * Read markers until SOS or EOI.
  171512. *
  171513. * Returns same codes as are defined for jpeg_consume_input:
  171514. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  171515. */
  171516. METHODDEF(int)
  171517. read_markers (j_decompress_ptr cinfo)
  171518. {
  171519. /* Outer loop repeats once for each marker. */
  171520. for (;;) {
  171521. /* Collect the marker proper, unless we already did. */
  171522. /* NB: first_marker() enforces the requirement that SOI appear first. */
  171523. if (cinfo->unread_marker == 0) {
  171524. if (! cinfo->marker->saw_SOI) {
  171525. if (! first_marker(cinfo))
  171526. return JPEG_SUSPENDED;
  171527. } else {
  171528. if (! next_marker(cinfo))
  171529. return JPEG_SUSPENDED;
  171530. }
  171531. }
  171532. /* At this point cinfo->unread_marker contains the marker code and the
  171533. * input point is just past the marker proper, but before any parameters.
  171534. * A suspension will cause us to return with this state still true.
  171535. */
  171536. switch (cinfo->unread_marker) {
  171537. case M_SOI:
  171538. if (! get_soi(cinfo))
  171539. return JPEG_SUSPENDED;
  171540. break;
  171541. case M_SOF0: /* Baseline */
  171542. case M_SOF1: /* Extended sequential, Huffman */
  171543. if (! get_sof(cinfo, FALSE, FALSE))
  171544. return JPEG_SUSPENDED;
  171545. break;
  171546. case M_SOF2: /* Progressive, Huffman */
  171547. if (! get_sof(cinfo, TRUE, FALSE))
  171548. return JPEG_SUSPENDED;
  171549. break;
  171550. case M_SOF9: /* Extended sequential, arithmetic */
  171551. if (! get_sof(cinfo, FALSE, TRUE))
  171552. return JPEG_SUSPENDED;
  171553. break;
  171554. case M_SOF10: /* Progressive, arithmetic */
  171555. if (! get_sof(cinfo, TRUE, TRUE))
  171556. return JPEG_SUSPENDED;
  171557. break;
  171558. /* Currently unsupported SOFn types */
  171559. case M_SOF3: /* Lossless, Huffman */
  171560. case M_SOF5: /* Differential sequential, Huffman */
  171561. case M_SOF6: /* Differential progressive, Huffman */
  171562. case M_SOF7: /* Differential lossless, Huffman */
  171563. case M_JPG: /* Reserved for JPEG extensions */
  171564. case M_SOF11: /* Lossless, arithmetic */
  171565. case M_SOF13: /* Differential sequential, arithmetic */
  171566. case M_SOF14: /* Differential progressive, arithmetic */
  171567. case M_SOF15: /* Differential lossless, arithmetic */
  171568. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  171569. break;
  171570. case M_SOS:
  171571. if (! get_sos(cinfo))
  171572. return JPEG_SUSPENDED;
  171573. cinfo->unread_marker = 0; /* processed the marker */
  171574. return JPEG_REACHED_SOS;
  171575. case M_EOI:
  171576. TRACEMS(cinfo, 1, JTRC_EOI);
  171577. cinfo->unread_marker = 0; /* processed the marker */
  171578. return JPEG_REACHED_EOI;
  171579. case M_DAC:
  171580. if (! get_dac(cinfo))
  171581. return JPEG_SUSPENDED;
  171582. break;
  171583. case M_DHT:
  171584. if (! get_dht(cinfo))
  171585. return JPEG_SUSPENDED;
  171586. break;
  171587. case M_DQT:
  171588. if (! get_dqt(cinfo))
  171589. return JPEG_SUSPENDED;
  171590. break;
  171591. case M_DRI:
  171592. if (! get_dri(cinfo))
  171593. return JPEG_SUSPENDED;
  171594. break;
  171595. case M_APP0:
  171596. case M_APP1:
  171597. case M_APP2:
  171598. case M_APP3:
  171599. case M_APP4:
  171600. case M_APP5:
  171601. case M_APP6:
  171602. case M_APP7:
  171603. case M_APP8:
  171604. case M_APP9:
  171605. case M_APP10:
  171606. case M_APP11:
  171607. case M_APP12:
  171608. case M_APP13:
  171609. case M_APP14:
  171610. case M_APP15:
  171611. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  171612. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  171613. return JPEG_SUSPENDED;
  171614. break;
  171615. case M_COM:
  171616. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  171617. return JPEG_SUSPENDED;
  171618. break;
  171619. case M_RST0: /* these are all parameterless */
  171620. case M_RST1:
  171621. case M_RST2:
  171622. case M_RST3:
  171623. case M_RST4:
  171624. case M_RST5:
  171625. case M_RST6:
  171626. case M_RST7:
  171627. case M_TEM:
  171628. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  171629. break;
  171630. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  171631. if (! skip_variable(cinfo))
  171632. return JPEG_SUSPENDED;
  171633. break;
  171634. default: /* must be DHP, EXP, JPGn, or RESn */
  171635. /* For now, we treat the reserved markers as fatal errors since they are
  171636. * likely to be used to signal incompatible JPEG Part 3 extensions.
  171637. * Once the JPEG 3 version-number marker is well defined, this code
  171638. * ought to change!
  171639. */
  171640. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171641. break;
  171642. }
  171643. /* Successfully processed marker, so reset state variable */
  171644. cinfo->unread_marker = 0;
  171645. } /* end loop */
  171646. }
  171647. /*
  171648. * Read a restart marker, which is expected to appear next in the datastream;
  171649. * if the marker is not there, take appropriate recovery action.
  171650. * Returns FALSE if suspension is required.
  171651. *
  171652. * This is called by the entropy decoder after it has read an appropriate
  171653. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  171654. * has already read a marker from the data source. Under normal conditions
  171655. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  171656. * it holds a marker which the decoder will be unable to read past.
  171657. */
  171658. METHODDEF(boolean)
  171659. read_restart_marker (j_decompress_ptr cinfo)
  171660. {
  171661. /* Obtain a marker unless we already did. */
  171662. /* Note that next_marker will complain if it skips any data. */
  171663. if (cinfo->unread_marker == 0) {
  171664. if (! next_marker(cinfo))
  171665. return FALSE;
  171666. }
  171667. if (cinfo->unread_marker ==
  171668. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  171669. /* Normal case --- swallow the marker and let entropy decoder continue */
  171670. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  171671. cinfo->unread_marker = 0;
  171672. } else {
  171673. /* Uh-oh, the restart markers have been messed up. */
  171674. /* Let the data source manager determine how to resync. */
  171675. if (! (*cinfo->src->resync_to_restart) (cinfo,
  171676. cinfo->marker->next_restart_num))
  171677. return FALSE;
  171678. }
  171679. /* Update next-restart state */
  171680. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  171681. return TRUE;
  171682. }
  171683. /*
  171684. * This is the default resync_to_restart method for data source managers
  171685. * to use if they don't have any better approach. Some data source managers
  171686. * may be able to back up, or may have additional knowledge about the data
  171687. * which permits a more intelligent recovery strategy; such managers would
  171688. * presumably supply their own resync method.
  171689. *
  171690. * read_restart_marker calls resync_to_restart if it finds a marker other than
  171691. * the restart marker it was expecting. (This code is *not* used unless
  171692. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  171693. * the marker code actually found (might be anything, except 0 or FF).
  171694. * The desired restart marker number (0..7) is passed as a parameter.
  171695. * This routine is supposed to apply whatever error recovery strategy seems
  171696. * appropriate in order to position the input stream to the next data segment.
  171697. * Note that cinfo->unread_marker is treated as a marker appearing before
  171698. * the current data-source input point; usually it should be reset to zero
  171699. * before returning.
  171700. * Returns FALSE if suspension is required.
  171701. *
  171702. * This implementation is substantially constrained by wanting to treat the
  171703. * input as a data stream; this means we can't back up. Therefore, we have
  171704. * only the following actions to work with:
  171705. * 1. Simply discard the marker and let the entropy decoder resume at next
  171706. * byte of file.
  171707. * 2. Read forward until we find another marker, discarding intervening
  171708. * data. (In theory we could look ahead within the current bufferload,
  171709. * without having to discard data if we don't find the desired marker.
  171710. * This idea is not implemented here, in part because it makes behavior
  171711. * dependent on buffer size and chance buffer-boundary positions.)
  171712. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  171713. * This will cause the entropy decoder to process an empty data segment,
  171714. * inserting dummy zeroes, and then we will reprocess the marker.
  171715. *
  171716. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  171717. * appropriate if the found marker is a future restart marker (indicating
  171718. * that we have missed the desired restart marker, probably because it got
  171719. * corrupted).
  171720. * We apply #2 or #3 if the found marker is a restart marker no more than
  171721. * two counts behind or ahead of the expected one. We also apply #2 if the
  171722. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  171723. * If the found marker is a restart marker more than 2 counts away, we do #1
  171724. * (too much risk that the marker is erroneous; with luck we will be able to
  171725. * resync at some future point).
  171726. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  171727. * overrunning the end of a scan. An implementation limited to single-scan
  171728. * files might find it better to apply #2 for markers other than EOI, since
  171729. * any other marker would have to be bogus data in that case.
  171730. */
  171731. GLOBAL(boolean)
  171732. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  171733. {
  171734. int marker = cinfo->unread_marker;
  171735. int action = 1;
  171736. /* Always put up a warning. */
  171737. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  171738. /* Outer loop handles repeated decision after scanning forward. */
  171739. for (;;) {
  171740. if (marker < (int) M_SOF0)
  171741. action = 2; /* invalid marker */
  171742. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  171743. action = 3; /* valid non-restart marker */
  171744. else {
  171745. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  171746. marker == ((int) M_RST0 + ((desired+2) & 7)))
  171747. action = 3; /* one of the next two expected restarts */
  171748. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  171749. marker == ((int) M_RST0 + ((desired-2) & 7)))
  171750. action = 2; /* a prior restart, so advance */
  171751. else
  171752. action = 1; /* desired restart or too far away */
  171753. }
  171754. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  171755. switch (action) {
  171756. case 1:
  171757. /* Discard marker and let entropy decoder resume processing. */
  171758. cinfo->unread_marker = 0;
  171759. return TRUE;
  171760. case 2:
  171761. /* Scan to the next marker, and repeat the decision loop. */
  171762. if (! next_marker(cinfo))
  171763. return FALSE;
  171764. marker = cinfo->unread_marker;
  171765. break;
  171766. case 3:
  171767. /* Return without advancing past this marker. */
  171768. /* Entropy decoder will be forced to process an empty segment. */
  171769. return TRUE;
  171770. }
  171771. } /* end loop */
  171772. }
  171773. /*
  171774. * Reset marker processing state to begin a fresh datastream.
  171775. */
  171776. METHODDEF(void)
  171777. reset_marker_reader (j_decompress_ptr cinfo)
  171778. {
  171779. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171780. cinfo->comp_info = NULL; /* until allocated by get_sof */
  171781. cinfo->input_scan_number = 0; /* no SOS seen yet */
  171782. cinfo->unread_marker = 0; /* no pending marker */
  171783. marker->pub.saw_SOI = FALSE; /* set internal state too */
  171784. marker->pub.saw_SOF = FALSE;
  171785. marker->pub.discarded_bytes = 0;
  171786. marker->cur_marker = NULL;
  171787. }
  171788. /*
  171789. * Initialize the marker reader module.
  171790. * This is called only once, when the decompression object is created.
  171791. */
  171792. GLOBAL(void)
  171793. jinit_marker_reader (j_decompress_ptr cinfo)
  171794. {
  171795. my_marker_ptr2 marker;
  171796. int i;
  171797. /* Create subobject in permanent pool */
  171798. marker = (my_marker_ptr2)
  171799. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  171800. SIZEOF(my_marker_reader));
  171801. cinfo->marker = (struct jpeg_marker_reader *) marker;
  171802. /* Initialize public method pointers */
  171803. marker->pub.reset_marker_reader = reset_marker_reader;
  171804. marker->pub.read_markers = read_markers;
  171805. marker->pub.read_restart_marker = read_restart_marker;
  171806. /* Initialize COM/APPn processing.
  171807. * By default, we examine and then discard APP0 and APP14,
  171808. * but simply discard COM and all other APPn.
  171809. */
  171810. marker->process_COM = skip_variable;
  171811. marker->length_limit_COM = 0;
  171812. for (i = 0; i < 16; i++) {
  171813. marker->process_APPn[i] = skip_variable;
  171814. marker->length_limit_APPn[i] = 0;
  171815. }
  171816. marker->process_APPn[0] = get_interesting_appn;
  171817. marker->process_APPn[14] = get_interesting_appn;
  171818. /* Reset marker processing state */
  171819. reset_marker_reader(cinfo);
  171820. }
  171821. /*
  171822. * Control saving of COM and APPn markers into marker_list.
  171823. */
  171824. #ifdef SAVE_MARKERS_SUPPORTED
  171825. GLOBAL(void)
  171826. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  171827. unsigned int length_limit)
  171828. {
  171829. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171830. long maxlength;
  171831. jpeg_marker_parser_method processor;
  171832. /* Length limit mustn't be larger than what we can allocate
  171833. * (should only be a concern in a 16-bit environment).
  171834. */
  171835. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  171836. if (((long) length_limit) > maxlength)
  171837. length_limit = (unsigned int) maxlength;
  171838. /* Choose processor routine to use.
  171839. * APP0/APP14 have special requirements.
  171840. */
  171841. if (length_limit) {
  171842. processor = save_marker;
  171843. /* If saving APP0/APP14, save at least enough for our internal use. */
  171844. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  171845. length_limit = APP0_DATA_LEN;
  171846. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  171847. length_limit = APP14_DATA_LEN;
  171848. } else {
  171849. processor = skip_variable;
  171850. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  171851. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  171852. processor = get_interesting_appn;
  171853. }
  171854. if (marker_code == (int) M_COM) {
  171855. marker->process_COM = processor;
  171856. marker->length_limit_COM = length_limit;
  171857. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  171858. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  171859. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  171860. } else
  171861. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171862. }
  171863. #endif /* SAVE_MARKERS_SUPPORTED */
  171864. /*
  171865. * Install a special processing method for COM or APPn markers.
  171866. */
  171867. GLOBAL(void)
  171868. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  171869. jpeg_marker_parser_method routine)
  171870. {
  171871. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171872. if (marker_code == (int) M_COM)
  171873. marker->process_COM = routine;
  171874. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  171875. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  171876. else
  171877. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171878. }
  171879. /*** End of inlined file: jdmarker.c ***/
  171880. /*** Start of inlined file: jdmaster.c ***/
  171881. #define JPEG_INTERNALS
  171882. /* Private state */
  171883. typedef struct {
  171884. struct jpeg_decomp_master pub; /* public fields */
  171885. int pass_number; /* # of passes completed */
  171886. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  171887. /* Saved references to initialized quantizer modules,
  171888. * in case we need to switch modes.
  171889. */
  171890. struct jpeg_color_quantizer * quantizer_1pass;
  171891. struct jpeg_color_quantizer * quantizer_2pass;
  171892. } my_decomp_master;
  171893. typedef my_decomp_master * my_master_ptr6;
  171894. /*
  171895. * Determine whether merged upsample/color conversion should be used.
  171896. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  171897. */
  171898. LOCAL(boolean)
  171899. use_merged_upsample (j_decompress_ptr cinfo)
  171900. {
  171901. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171902. /* Merging is the equivalent of plain box-filter upsampling */
  171903. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  171904. return FALSE;
  171905. /* jdmerge.c only supports YCC=>RGB color conversion */
  171906. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  171907. cinfo->out_color_space != JCS_RGB ||
  171908. cinfo->out_color_components != RGB_PIXELSIZE)
  171909. return FALSE;
  171910. /* and it only handles 2h1v or 2h2v sampling ratios */
  171911. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  171912. cinfo->comp_info[1].h_samp_factor != 1 ||
  171913. cinfo->comp_info[2].h_samp_factor != 1 ||
  171914. cinfo->comp_info[0].v_samp_factor > 2 ||
  171915. cinfo->comp_info[1].v_samp_factor != 1 ||
  171916. cinfo->comp_info[2].v_samp_factor != 1)
  171917. return FALSE;
  171918. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  171919. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171920. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171921. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  171922. return FALSE;
  171923. /* ??? also need to test for upsample-time rescaling, when & if supported */
  171924. return TRUE; /* by golly, it'll work... */
  171925. #else
  171926. return FALSE;
  171927. #endif
  171928. }
  171929. /*
  171930. * Compute output image dimensions and related values.
  171931. * NOTE: this is exported for possible use by application.
  171932. * Hence it mustn't do anything that can't be done twice.
  171933. * Also note that it may be called before the master module is initialized!
  171934. */
  171935. GLOBAL(void)
  171936. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  171937. /* Do computations that are needed before master selection phase */
  171938. {
  171939. #ifdef IDCT_SCALING_SUPPORTED
  171940. int ci;
  171941. jpeg_component_info *compptr;
  171942. #endif
  171943. /* Prevent application from calling me at wrong times */
  171944. if (cinfo->global_state != DSTATE_READY)
  171945. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  171946. #ifdef IDCT_SCALING_SUPPORTED
  171947. /* Compute actual output image dimensions and DCT scaling choices. */
  171948. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  171949. /* Provide 1/8 scaling */
  171950. cinfo->output_width = (JDIMENSION)
  171951. jdiv_round_up((long) cinfo->image_width, 8L);
  171952. cinfo->output_height = (JDIMENSION)
  171953. jdiv_round_up((long) cinfo->image_height, 8L);
  171954. cinfo->min_DCT_scaled_size = 1;
  171955. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  171956. /* Provide 1/4 scaling */
  171957. cinfo->output_width = (JDIMENSION)
  171958. jdiv_round_up((long) cinfo->image_width, 4L);
  171959. cinfo->output_height = (JDIMENSION)
  171960. jdiv_round_up((long) cinfo->image_height, 4L);
  171961. cinfo->min_DCT_scaled_size = 2;
  171962. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  171963. /* Provide 1/2 scaling */
  171964. cinfo->output_width = (JDIMENSION)
  171965. jdiv_round_up((long) cinfo->image_width, 2L);
  171966. cinfo->output_height = (JDIMENSION)
  171967. jdiv_round_up((long) cinfo->image_height, 2L);
  171968. cinfo->min_DCT_scaled_size = 4;
  171969. } else {
  171970. /* Provide 1/1 scaling */
  171971. cinfo->output_width = cinfo->image_width;
  171972. cinfo->output_height = cinfo->image_height;
  171973. cinfo->min_DCT_scaled_size = DCTSIZE;
  171974. }
  171975. /* In selecting the actual DCT scaling for each component, we try to
  171976. * scale up the chroma components via IDCT scaling rather than upsampling.
  171977. * This saves time if the upsampler gets to use 1:1 scaling.
  171978. * Note this code assumes that the supported DCT scalings are powers of 2.
  171979. */
  171980. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171981. ci++, compptr++) {
  171982. int ssize = cinfo->min_DCT_scaled_size;
  171983. while (ssize < DCTSIZE &&
  171984. (compptr->h_samp_factor * ssize * 2 <=
  171985. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  171986. (compptr->v_samp_factor * ssize * 2 <=
  171987. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  171988. ssize = ssize * 2;
  171989. }
  171990. compptr->DCT_scaled_size = ssize;
  171991. }
  171992. /* Recompute downsampled dimensions of components;
  171993. * application needs to know these if using raw downsampled data.
  171994. */
  171995. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171996. ci++, compptr++) {
  171997. /* Size in samples, after IDCT scaling */
  171998. compptr->downsampled_width = (JDIMENSION)
  171999. jdiv_round_up((long) cinfo->image_width *
  172000. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  172001. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  172002. compptr->downsampled_height = (JDIMENSION)
  172003. jdiv_round_up((long) cinfo->image_height *
  172004. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  172005. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  172006. }
  172007. #else /* !IDCT_SCALING_SUPPORTED */
  172008. /* Hardwire it to "no scaling" */
  172009. cinfo->output_width = cinfo->image_width;
  172010. cinfo->output_height = cinfo->image_height;
  172011. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  172012. * and has computed unscaled downsampled_width and downsampled_height.
  172013. */
  172014. #endif /* IDCT_SCALING_SUPPORTED */
  172015. /* Report number of components in selected colorspace. */
  172016. /* Probably this should be in the color conversion module... */
  172017. switch (cinfo->out_color_space) {
  172018. case JCS_GRAYSCALE:
  172019. cinfo->out_color_components = 1;
  172020. break;
  172021. case JCS_RGB:
  172022. #if RGB_PIXELSIZE != 3
  172023. cinfo->out_color_components = RGB_PIXELSIZE;
  172024. break;
  172025. #endif /* else share code with YCbCr */
  172026. case JCS_YCbCr:
  172027. cinfo->out_color_components = 3;
  172028. break;
  172029. case JCS_CMYK:
  172030. case JCS_YCCK:
  172031. cinfo->out_color_components = 4;
  172032. break;
  172033. default: /* else must be same colorspace as in file */
  172034. cinfo->out_color_components = cinfo->num_components;
  172035. break;
  172036. }
  172037. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172038. cinfo->out_color_components);
  172039. /* See if upsampler will want to emit more than one row at a time */
  172040. if (use_merged_upsample(cinfo))
  172041. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172042. else
  172043. cinfo->rec_outbuf_height = 1;
  172044. }
  172045. /*
  172046. * Several decompression processes need to range-limit values to the range
  172047. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172048. * due to noise introduced by quantization, roundoff error, etc. These
  172049. * processes are inner loops and need to be as fast as possible. On most
  172050. * machines, particularly CPUs with pipelines or instruction prefetch,
  172051. * a (subscript-check-less) C table lookup
  172052. * x = sample_range_limit[x];
  172053. * is faster than explicit tests
  172054. * if (x < 0) x = 0;
  172055. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172056. * These processes all use a common table prepared by the routine below.
  172057. *
  172058. * For most steps we can mathematically guarantee that the initial value
  172059. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172060. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172061. * limiting step (just after the IDCT), a wildly out-of-range value is
  172062. * possible if the input data is corrupt. To avoid any chance of indexing
  172063. * off the end of memory and getting a bad-pointer trap, we perform the
  172064. * post-IDCT limiting thus:
  172065. * x = range_limit[x & MASK];
  172066. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172067. * samples. Under normal circumstances this is more than enough range and
  172068. * a correct output will be generated; with bogus input data the mask will
  172069. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172070. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172071. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172072. * So the post-IDCT limiting table ends up looking like this:
  172073. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172074. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172075. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172076. * 0,1,...,CENTERJSAMPLE-1
  172077. * Negative inputs select values from the upper half of the table after
  172078. * masking.
  172079. *
  172080. * We can save some space by overlapping the start of the post-IDCT table
  172081. * with the simpler range limiting table. The post-IDCT table begins at
  172082. * sample_range_limit + CENTERJSAMPLE.
  172083. *
  172084. * Note that the table is allocated in near data space on PCs; it's small
  172085. * enough and used often enough to justify this.
  172086. */
  172087. LOCAL(void)
  172088. prepare_range_limit_table (j_decompress_ptr cinfo)
  172089. /* Allocate and fill in the sample_range_limit table */
  172090. {
  172091. JSAMPLE * table;
  172092. int i;
  172093. table = (JSAMPLE *)
  172094. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172095. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172096. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172097. cinfo->sample_range_limit = table;
  172098. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172099. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172100. /* Main part of "simple" table: limit[x] = x */
  172101. for (i = 0; i <= MAXJSAMPLE; i++)
  172102. table[i] = (JSAMPLE) i;
  172103. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172104. /* End of simple table, rest of first half of post-IDCT table */
  172105. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172106. table[i] = MAXJSAMPLE;
  172107. /* Second half of post-IDCT table */
  172108. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172109. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172110. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172111. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172112. }
  172113. /*
  172114. * Master selection of decompression modules.
  172115. * This is done once at jpeg_start_decompress time. We determine
  172116. * which modules will be used and give them appropriate initialization calls.
  172117. * We also initialize the decompressor input side to begin consuming data.
  172118. *
  172119. * Since jpeg_read_header has finished, we know what is in the SOF
  172120. * and (first) SOS markers. We also have all the application parameter
  172121. * settings.
  172122. */
  172123. LOCAL(void)
  172124. master_selection (j_decompress_ptr cinfo)
  172125. {
  172126. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172127. boolean use_c_buffer;
  172128. long samplesperrow;
  172129. JDIMENSION jd_samplesperrow;
  172130. /* Initialize dimensions and other stuff */
  172131. jpeg_calc_output_dimensions(cinfo);
  172132. prepare_range_limit_table(cinfo);
  172133. /* Width of an output scanline must be representable as JDIMENSION. */
  172134. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172135. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172136. if ((long) jd_samplesperrow != samplesperrow)
  172137. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172138. /* Initialize my private state */
  172139. master->pass_number = 0;
  172140. master->using_merged_upsample = use_merged_upsample(cinfo);
  172141. /* Color quantizer selection */
  172142. master->quantizer_1pass = NULL;
  172143. master->quantizer_2pass = NULL;
  172144. /* No mode changes if not using buffered-image mode. */
  172145. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172146. cinfo->enable_1pass_quant = FALSE;
  172147. cinfo->enable_external_quant = FALSE;
  172148. cinfo->enable_2pass_quant = FALSE;
  172149. }
  172150. if (cinfo->quantize_colors) {
  172151. if (cinfo->raw_data_out)
  172152. ERREXIT(cinfo, JERR_NOTIMPL);
  172153. /* 2-pass quantizer only works in 3-component color space. */
  172154. if (cinfo->out_color_components != 3) {
  172155. cinfo->enable_1pass_quant = TRUE;
  172156. cinfo->enable_external_quant = FALSE;
  172157. cinfo->enable_2pass_quant = FALSE;
  172158. cinfo->colormap = NULL;
  172159. } else if (cinfo->colormap != NULL) {
  172160. cinfo->enable_external_quant = TRUE;
  172161. } else if (cinfo->two_pass_quantize) {
  172162. cinfo->enable_2pass_quant = TRUE;
  172163. } else {
  172164. cinfo->enable_1pass_quant = TRUE;
  172165. }
  172166. if (cinfo->enable_1pass_quant) {
  172167. #ifdef QUANT_1PASS_SUPPORTED
  172168. jinit_1pass_quantizer(cinfo);
  172169. master->quantizer_1pass = cinfo->cquantize;
  172170. #else
  172171. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172172. #endif
  172173. }
  172174. /* We use the 2-pass code to map to external colormaps. */
  172175. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172176. #ifdef QUANT_2PASS_SUPPORTED
  172177. jinit_2pass_quantizer(cinfo);
  172178. master->quantizer_2pass = cinfo->cquantize;
  172179. #else
  172180. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172181. #endif
  172182. }
  172183. /* If both quantizers are initialized, the 2-pass one is left active;
  172184. * this is necessary for starting with quantization to an external map.
  172185. */
  172186. }
  172187. /* Post-processing: in particular, color conversion first */
  172188. if (! cinfo->raw_data_out) {
  172189. if (master->using_merged_upsample) {
  172190. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172191. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172192. #else
  172193. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172194. #endif
  172195. } else {
  172196. jinit_color_deconverter(cinfo);
  172197. jinit_upsampler(cinfo);
  172198. }
  172199. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172200. }
  172201. /* Inverse DCT */
  172202. jinit_inverse_dct(cinfo);
  172203. /* Entropy decoding: either Huffman or arithmetic coding. */
  172204. if (cinfo->arith_code) {
  172205. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172206. } else {
  172207. if (cinfo->progressive_mode) {
  172208. #ifdef D_PROGRESSIVE_SUPPORTED
  172209. jinit_phuff_decoder(cinfo);
  172210. #else
  172211. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172212. #endif
  172213. } else
  172214. jinit_huff_decoder(cinfo);
  172215. }
  172216. /* Initialize principal buffer controllers. */
  172217. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172218. jinit_d_coef_controller(cinfo, use_c_buffer);
  172219. if (! cinfo->raw_data_out)
  172220. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172221. /* We can now tell the memory manager to allocate virtual arrays. */
  172222. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172223. /* Initialize input side of decompressor to consume first scan. */
  172224. (*cinfo->inputctl->start_input_pass) (cinfo);
  172225. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172226. /* If jpeg_start_decompress will read the whole file, initialize
  172227. * progress monitoring appropriately. The input step is counted
  172228. * as one pass.
  172229. */
  172230. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172231. cinfo->inputctl->has_multiple_scans) {
  172232. int nscans;
  172233. /* Estimate number of scans to set pass_limit. */
  172234. if (cinfo->progressive_mode) {
  172235. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172236. nscans = 2 + 3 * cinfo->num_components;
  172237. } else {
  172238. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172239. nscans = cinfo->num_components;
  172240. }
  172241. cinfo->progress->pass_counter = 0L;
  172242. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172243. cinfo->progress->completed_passes = 0;
  172244. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172245. /* Count the input pass as done */
  172246. master->pass_number++;
  172247. }
  172248. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172249. }
  172250. /*
  172251. * Per-pass setup.
  172252. * This is called at the beginning of each output pass. We determine which
  172253. * modules will be active during this pass and give them appropriate
  172254. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172255. * is a "real" output pass or a dummy pass for color quantization.
  172256. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172257. */
  172258. METHODDEF(void)
  172259. prepare_for_output_pass (j_decompress_ptr cinfo)
  172260. {
  172261. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172262. if (master->pub.is_dummy_pass) {
  172263. #ifdef QUANT_2PASS_SUPPORTED
  172264. /* Final pass of 2-pass quantization */
  172265. master->pub.is_dummy_pass = FALSE;
  172266. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172267. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172268. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172269. #else
  172270. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172271. #endif /* QUANT_2PASS_SUPPORTED */
  172272. } else {
  172273. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172274. /* Select new quantization method */
  172275. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172276. cinfo->cquantize = master->quantizer_2pass;
  172277. master->pub.is_dummy_pass = TRUE;
  172278. } else if (cinfo->enable_1pass_quant) {
  172279. cinfo->cquantize = master->quantizer_1pass;
  172280. } else {
  172281. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172282. }
  172283. }
  172284. (*cinfo->idct->start_pass) (cinfo);
  172285. (*cinfo->coef->start_output_pass) (cinfo);
  172286. if (! cinfo->raw_data_out) {
  172287. if (! master->using_merged_upsample)
  172288. (*cinfo->cconvert->start_pass) (cinfo);
  172289. (*cinfo->upsample->start_pass) (cinfo);
  172290. if (cinfo->quantize_colors)
  172291. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172292. (*cinfo->post->start_pass) (cinfo,
  172293. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172294. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172295. }
  172296. }
  172297. /* Set up progress monitor's pass info if present */
  172298. if (cinfo->progress != NULL) {
  172299. cinfo->progress->completed_passes = master->pass_number;
  172300. cinfo->progress->total_passes = master->pass_number +
  172301. (master->pub.is_dummy_pass ? 2 : 1);
  172302. /* In buffered-image mode, we assume one more output pass if EOI not
  172303. * yet reached, but no more passes if EOI has been reached.
  172304. */
  172305. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172306. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172307. }
  172308. }
  172309. }
  172310. /*
  172311. * Finish up at end of an output pass.
  172312. */
  172313. METHODDEF(void)
  172314. finish_output_pass (j_decompress_ptr cinfo)
  172315. {
  172316. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172317. if (cinfo->quantize_colors)
  172318. (*cinfo->cquantize->finish_pass) (cinfo);
  172319. master->pass_number++;
  172320. }
  172321. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172322. /*
  172323. * Switch to a new external colormap between output passes.
  172324. */
  172325. GLOBAL(void)
  172326. jpeg_new_colormap (j_decompress_ptr cinfo)
  172327. {
  172328. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172329. /* Prevent application from calling me at wrong times */
  172330. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172331. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172332. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172333. cinfo->colormap != NULL) {
  172334. /* Select 2-pass quantizer for external colormap use */
  172335. cinfo->cquantize = master->quantizer_2pass;
  172336. /* Notify quantizer of colormap change */
  172337. (*cinfo->cquantize->new_color_map) (cinfo);
  172338. master->pub.is_dummy_pass = FALSE; /* just in case */
  172339. } else
  172340. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172341. }
  172342. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172343. /*
  172344. * Initialize master decompression control and select active modules.
  172345. * This is performed at the start of jpeg_start_decompress.
  172346. */
  172347. GLOBAL(void)
  172348. jinit_master_decompress (j_decompress_ptr cinfo)
  172349. {
  172350. my_master_ptr6 master;
  172351. master = (my_master_ptr6)
  172352. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172353. SIZEOF(my_decomp_master));
  172354. cinfo->master = (struct jpeg_decomp_master *) master;
  172355. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172356. master->pub.finish_output_pass = finish_output_pass;
  172357. master->pub.is_dummy_pass = FALSE;
  172358. master_selection(cinfo);
  172359. }
  172360. /*** End of inlined file: jdmaster.c ***/
  172361. #undef FIX
  172362. /*** Start of inlined file: jdmerge.c ***/
  172363. #define JPEG_INTERNALS
  172364. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172365. /* Private subobject */
  172366. typedef struct {
  172367. struct jpeg_upsampler pub; /* public fields */
  172368. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172369. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172370. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172371. JSAMPARRAY output_buf));
  172372. /* Private state for YCC->RGB conversion */
  172373. int * Cr_r_tab; /* => table for Cr to R conversion */
  172374. int * Cb_b_tab; /* => table for Cb to B conversion */
  172375. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172376. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172377. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172378. * We need a "spare" row buffer to hold the second output row if the
  172379. * application provides just a one-row buffer; we also use the spare
  172380. * to discard the dummy last row if the image height is odd.
  172381. */
  172382. JSAMPROW spare_row;
  172383. boolean spare_full; /* T if spare buffer is occupied */
  172384. JDIMENSION out_row_width; /* samples per output row */
  172385. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172386. } my_upsampler;
  172387. typedef my_upsampler * my_upsample_ptr;
  172388. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172389. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172390. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172391. /*
  172392. * Initialize tables for YCC->RGB colorspace conversion.
  172393. * This is taken directly from jdcolor.c; see that file for more info.
  172394. */
  172395. LOCAL(void)
  172396. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172397. {
  172398. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172399. int i;
  172400. INT32 x;
  172401. SHIFT_TEMPS
  172402. upsample->Cr_r_tab = (int *)
  172403. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172404. (MAXJSAMPLE+1) * SIZEOF(int));
  172405. upsample->Cb_b_tab = (int *)
  172406. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172407. (MAXJSAMPLE+1) * SIZEOF(int));
  172408. upsample->Cr_g_tab = (INT32 *)
  172409. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172410. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172411. upsample->Cb_g_tab = (INT32 *)
  172412. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172413. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172414. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172415. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172416. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172417. /* Cr=>R value is nearest int to 1.40200 * x */
  172418. upsample->Cr_r_tab[i] = (int)
  172419. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172420. /* Cb=>B value is nearest int to 1.77200 * x */
  172421. upsample->Cb_b_tab[i] = (int)
  172422. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172423. /* Cr=>G value is scaled-up -0.71414 * x */
  172424. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172425. /* Cb=>G value is scaled-up -0.34414 * x */
  172426. /* We also add in ONE_HALF so that need not do it in inner loop */
  172427. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172428. }
  172429. }
  172430. /*
  172431. * Initialize for an upsampling pass.
  172432. */
  172433. METHODDEF(void)
  172434. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172435. {
  172436. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172437. /* Mark the spare buffer empty */
  172438. upsample->spare_full = FALSE;
  172439. /* Initialize total-height counter for detecting bottom of image */
  172440. upsample->rows_to_go = cinfo->output_height;
  172441. }
  172442. /*
  172443. * Control routine to do upsampling (and color conversion).
  172444. *
  172445. * The control routine just handles the row buffering considerations.
  172446. */
  172447. METHODDEF(void)
  172448. merged_2v_upsample (j_decompress_ptr cinfo,
  172449. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172450. JDIMENSION,
  172451. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172452. JDIMENSION out_rows_avail)
  172453. /* 2:1 vertical sampling case: may need a spare row. */
  172454. {
  172455. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172456. JSAMPROW work_ptrs[2];
  172457. JDIMENSION num_rows; /* number of rows returned to caller */
  172458. if (upsample->spare_full) {
  172459. /* If we have a spare row saved from a previous cycle, just return it. */
  172460. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172461. 1, upsample->out_row_width);
  172462. num_rows = 1;
  172463. upsample->spare_full = FALSE;
  172464. } else {
  172465. /* Figure number of rows to return to caller. */
  172466. num_rows = 2;
  172467. /* Not more than the distance to the end of the image. */
  172468. if (num_rows > upsample->rows_to_go)
  172469. num_rows = upsample->rows_to_go;
  172470. /* And not more than what the client can accept: */
  172471. out_rows_avail -= *out_row_ctr;
  172472. if (num_rows > out_rows_avail)
  172473. num_rows = out_rows_avail;
  172474. /* Create output pointer array for upsampler. */
  172475. work_ptrs[0] = output_buf[*out_row_ctr];
  172476. if (num_rows > 1) {
  172477. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172478. } else {
  172479. work_ptrs[1] = upsample->spare_row;
  172480. upsample->spare_full = TRUE;
  172481. }
  172482. /* Now do the upsampling. */
  172483. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172484. }
  172485. /* Adjust counts */
  172486. *out_row_ctr += num_rows;
  172487. upsample->rows_to_go -= num_rows;
  172488. /* When the buffer is emptied, declare this input row group consumed */
  172489. if (! upsample->spare_full)
  172490. (*in_row_group_ctr)++;
  172491. }
  172492. METHODDEF(void)
  172493. merged_1v_upsample (j_decompress_ptr cinfo,
  172494. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172495. JDIMENSION,
  172496. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172497. JDIMENSION)
  172498. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  172499. {
  172500. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172501. /* Just do the upsampling. */
  172502. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  172503. output_buf + *out_row_ctr);
  172504. /* Adjust counts */
  172505. (*out_row_ctr)++;
  172506. (*in_row_group_ctr)++;
  172507. }
  172508. /*
  172509. * These are the routines invoked by the control routines to do
  172510. * the actual upsampling/conversion. One row group is processed per call.
  172511. *
  172512. * Note: since we may be writing directly into application-supplied buffers,
  172513. * we have to be honest about the output width; we can't assume the buffer
  172514. * has been rounded up to an even width.
  172515. */
  172516. /*
  172517. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  172518. */
  172519. METHODDEF(void)
  172520. h2v1_merged_upsample (j_decompress_ptr cinfo,
  172521. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172522. JSAMPARRAY output_buf)
  172523. {
  172524. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172525. register int y, cred, cgreen, cblue;
  172526. int cb, cr;
  172527. register JSAMPROW outptr;
  172528. JSAMPROW inptr0, inptr1, inptr2;
  172529. JDIMENSION col;
  172530. /* copy these pointers into registers if possible */
  172531. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172532. int * Crrtab = upsample->Cr_r_tab;
  172533. int * Cbbtab = upsample->Cb_b_tab;
  172534. INT32 * Crgtab = upsample->Cr_g_tab;
  172535. INT32 * Cbgtab = upsample->Cb_g_tab;
  172536. SHIFT_TEMPS
  172537. inptr0 = input_buf[0][in_row_group_ctr];
  172538. inptr1 = input_buf[1][in_row_group_ctr];
  172539. inptr2 = input_buf[2][in_row_group_ctr];
  172540. outptr = output_buf[0];
  172541. /* Loop for each pair of output pixels */
  172542. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172543. /* Do the chroma part of the calculation */
  172544. cb = GETJSAMPLE(*inptr1++);
  172545. cr = GETJSAMPLE(*inptr2++);
  172546. cred = Crrtab[cr];
  172547. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172548. cblue = Cbbtab[cb];
  172549. /* Fetch 2 Y values and emit 2 pixels */
  172550. y = GETJSAMPLE(*inptr0++);
  172551. outptr[RGB_RED] = range_limit[y + cred];
  172552. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172553. outptr[RGB_BLUE] = range_limit[y + cblue];
  172554. outptr += RGB_PIXELSIZE;
  172555. y = GETJSAMPLE(*inptr0++);
  172556. outptr[RGB_RED] = range_limit[y + cred];
  172557. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172558. outptr[RGB_BLUE] = range_limit[y + cblue];
  172559. outptr += RGB_PIXELSIZE;
  172560. }
  172561. /* If image width is odd, do the last output column separately */
  172562. if (cinfo->output_width & 1) {
  172563. cb = GETJSAMPLE(*inptr1);
  172564. cr = GETJSAMPLE(*inptr2);
  172565. cred = Crrtab[cr];
  172566. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172567. cblue = Cbbtab[cb];
  172568. y = GETJSAMPLE(*inptr0);
  172569. outptr[RGB_RED] = range_limit[y + cred];
  172570. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172571. outptr[RGB_BLUE] = range_limit[y + cblue];
  172572. }
  172573. }
  172574. /*
  172575. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  172576. */
  172577. METHODDEF(void)
  172578. h2v2_merged_upsample (j_decompress_ptr cinfo,
  172579. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172580. JSAMPARRAY output_buf)
  172581. {
  172582. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172583. register int y, cred, cgreen, cblue;
  172584. int cb, cr;
  172585. register JSAMPROW outptr0, outptr1;
  172586. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  172587. JDIMENSION col;
  172588. /* copy these pointers into registers if possible */
  172589. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172590. int * Crrtab = upsample->Cr_r_tab;
  172591. int * Cbbtab = upsample->Cb_b_tab;
  172592. INT32 * Crgtab = upsample->Cr_g_tab;
  172593. INT32 * Cbgtab = upsample->Cb_g_tab;
  172594. SHIFT_TEMPS
  172595. inptr00 = input_buf[0][in_row_group_ctr*2];
  172596. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  172597. inptr1 = input_buf[1][in_row_group_ctr];
  172598. inptr2 = input_buf[2][in_row_group_ctr];
  172599. outptr0 = output_buf[0];
  172600. outptr1 = output_buf[1];
  172601. /* Loop for each group of output pixels */
  172602. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172603. /* Do the chroma part of the calculation */
  172604. cb = GETJSAMPLE(*inptr1++);
  172605. cr = GETJSAMPLE(*inptr2++);
  172606. cred = Crrtab[cr];
  172607. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172608. cblue = Cbbtab[cb];
  172609. /* Fetch 4 Y values and emit 4 pixels */
  172610. y = GETJSAMPLE(*inptr00++);
  172611. outptr0[RGB_RED] = range_limit[y + cred];
  172612. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172613. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172614. outptr0 += RGB_PIXELSIZE;
  172615. y = GETJSAMPLE(*inptr00++);
  172616. outptr0[RGB_RED] = range_limit[y + cred];
  172617. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172618. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172619. outptr0 += RGB_PIXELSIZE;
  172620. y = GETJSAMPLE(*inptr01++);
  172621. outptr1[RGB_RED] = range_limit[y + cred];
  172622. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172623. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172624. outptr1 += RGB_PIXELSIZE;
  172625. y = GETJSAMPLE(*inptr01++);
  172626. outptr1[RGB_RED] = range_limit[y + cred];
  172627. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172628. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172629. outptr1 += RGB_PIXELSIZE;
  172630. }
  172631. /* If image width is odd, do the last output column separately */
  172632. if (cinfo->output_width & 1) {
  172633. cb = GETJSAMPLE(*inptr1);
  172634. cr = GETJSAMPLE(*inptr2);
  172635. cred = Crrtab[cr];
  172636. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172637. cblue = Cbbtab[cb];
  172638. y = GETJSAMPLE(*inptr00);
  172639. outptr0[RGB_RED] = range_limit[y + cred];
  172640. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172641. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172642. y = GETJSAMPLE(*inptr01);
  172643. outptr1[RGB_RED] = range_limit[y + cred];
  172644. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172645. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172646. }
  172647. }
  172648. /*
  172649. * Module initialization routine for merged upsampling/color conversion.
  172650. *
  172651. * NB: this is called under the conditions determined by use_merged_upsample()
  172652. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  172653. * of this module; no safety checks are made here.
  172654. */
  172655. GLOBAL(void)
  172656. jinit_merged_upsampler (j_decompress_ptr cinfo)
  172657. {
  172658. my_upsample_ptr upsample;
  172659. upsample = (my_upsample_ptr)
  172660. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172661. SIZEOF(my_upsampler));
  172662. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  172663. upsample->pub.start_pass = start_pass_merged_upsample;
  172664. upsample->pub.need_context_rows = FALSE;
  172665. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  172666. if (cinfo->max_v_samp_factor == 2) {
  172667. upsample->pub.upsample = merged_2v_upsample;
  172668. upsample->upmethod = h2v2_merged_upsample;
  172669. /* Allocate a spare row buffer */
  172670. upsample->spare_row = (JSAMPROW)
  172671. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172672. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  172673. } else {
  172674. upsample->pub.upsample = merged_1v_upsample;
  172675. upsample->upmethod = h2v1_merged_upsample;
  172676. /* No spare row needed */
  172677. upsample->spare_row = NULL;
  172678. }
  172679. build_ycc_rgb_table2(cinfo);
  172680. }
  172681. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  172682. /*** End of inlined file: jdmerge.c ***/
  172683. #undef ASSIGN_STATE
  172684. /*** Start of inlined file: jdphuff.c ***/
  172685. #define JPEG_INTERNALS
  172686. #ifdef D_PROGRESSIVE_SUPPORTED
  172687. /*
  172688. * Expanded entropy decoder object for progressive Huffman decoding.
  172689. *
  172690. * The savable_state subrecord contains fields that change within an MCU,
  172691. * but must not be updated permanently until we complete the MCU.
  172692. */
  172693. typedef struct {
  172694. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  172695. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  172696. } savable_state3;
  172697. /* This macro is to work around compilers with missing or broken
  172698. * structure assignment. You'll need to fix this code if you have
  172699. * such a compiler and you change MAX_COMPS_IN_SCAN.
  172700. */
  172701. #ifndef NO_STRUCT_ASSIGN
  172702. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  172703. #else
  172704. #if MAX_COMPS_IN_SCAN == 4
  172705. #define ASSIGN_STATE(dest,src) \
  172706. ((dest).EOBRUN = (src).EOBRUN, \
  172707. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  172708. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  172709. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  172710. (dest).last_dc_val[3] = (src).last_dc_val[3])
  172711. #endif
  172712. #endif
  172713. typedef struct {
  172714. struct jpeg_entropy_decoder pub; /* public fields */
  172715. /* These fields are loaded into local variables at start of each MCU.
  172716. * In case of suspension, we exit WITHOUT updating them.
  172717. */
  172718. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  172719. savable_state3 saved; /* Other state at start of MCU */
  172720. /* These fields are NOT loaded into local working state. */
  172721. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  172722. /* Pointers to derived tables (these workspaces have image lifespan) */
  172723. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  172724. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  172725. } phuff_entropy_decoder;
  172726. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  172727. /* Forward declarations */
  172728. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  172729. JBLOCKROW *MCU_data));
  172730. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  172731. JBLOCKROW *MCU_data));
  172732. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  172733. JBLOCKROW *MCU_data));
  172734. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  172735. JBLOCKROW *MCU_data));
  172736. /*
  172737. * Initialize for a Huffman-compressed scan.
  172738. */
  172739. METHODDEF(void)
  172740. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  172741. {
  172742. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172743. boolean is_DC_band, bad;
  172744. int ci, coefi, tbl;
  172745. int *coef_bit_ptr;
  172746. jpeg_component_info * compptr;
  172747. is_DC_band = (cinfo->Ss == 0);
  172748. /* Validate scan parameters */
  172749. bad = FALSE;
  172750. if (is_DC_band) {
  172751. if (cinfo->Se != 0)
  172752. bad = TRUE;
  172753. } else {
  172754. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  172755. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  172756. bad = TRUE;
  172757. /* AC scans may have only one component */
  172758. if (cinfo->comps_in_scan != 1)
  172759. bad = TRUE;
  172760. }
  172761. if (cinfo->Ah != 0) {
  172762. /* Successive approximation refinement scan: must have Al = Ah-1. */
  172763. if (cinfo->Al != cinfo->Ah-1)
  172764. bad = TRUE;
  172765. }
  172766. if (cinfo->Al > 13) /* need not check for < 0 */
  172767. bad = TRUE;
  172768. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  172769. * but the spec doesn't say so, and we try to be liberal about what we
  172770. * accept. Note: large Al values could result in out-of-range DC
  172771. * coefficients during early scans, leading to bizarre displays due to
  172772. * overflows in the IDCT math. But we won't crash.
  172773. */
  172774. if (bad)
  172775. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  172776. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  172777. /* Update progression status, and verify that scan order is legal.
  172778. * Note that inter-scan inconsistencies are treated as warnings
  172779. * not fatal errors ... not clear if this is right way to behave.
  172780. */
  172781. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172782. int cindex = cinfo->cur_comp_info[ci]->component_index;
  172783. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  172784. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  172785. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  172786. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  172787. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  172788. if (cinfo->Ah != expected)
  172789. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  172790. coef_bit_ptr[coefi] = cinfo->Al;
  172791. }
  172792. }
  172793. /* Select MCU decoding routine */
  172794. if (cinfo->Ah == 0) {
  172795. if (is_DC_band)
  172796. entropy->pub.decode_mcu = decode_mcu_DC_first;
  172797. else
  172798. entropy->pub.decode_mcu = decode_mcu_AC_first;
  172799. } else {
  172800. if (is_DC_band)
  172801. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  172802. else
  172803. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  172804. }
  172805. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172806. compptr = cinfo->cur_comp_info[ci];
  172807. /* Make sure requested tables are present, and compute derived tables.
  172808. * We may build same derived table more than once, but it's not expensive.
  172809. */
  172810. if (is_DC_band) {
  172811. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  172812. tbl = compptr->dc_tbl_no;
  172813. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  172814. & entropy->derived_tbls[tbl]);
  172815. }
  172816. } else {
  172817. tbl = compptr->ac_tbl_no;
  172818. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  172819. & entropy->derived_tbls[tbl]);
  172820. /* remember the single active table */
  172821. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  172822. }
  172823. /* Initialize DC predictions to 0 */
  172824. entropy->saved.last_dc_val[ci] = 0;
  172825. }
  172826. /* Initialize bitread state variables */
  172827. entropy->bitstate.bits_left = 0;
  172828. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  172829. entropy->pub.insufficient_data = FALSE;
  172830. /* Initialize private state variables */
  172831. entropy->saved.EOBRUN = 0;
  172832. /* Initialize restart counter */
  172833. entropy->restarts_to_go = cinfo->restart_interval;
  172834. }
  172835. /*
  172836. * Check for a restart marker & resynchronize decoder.
  172837. * Returns FALSE if must suspend.
  172838. */
  172839. LOCAL(boolean)
  172840. process_restartp (j_decompress_ptr cinfo)
  172841. {
  172842. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172843. int ci;
  172844. /* Throw away any unused bits remaining in bit buffer; */
  172845. /* include any full bytes in next_marker's count of discarded bytes */
  172846. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  172847. entropy->bitstate.bits_left = 0;
  172848. /* Advance past the RSTn marker */
  172849. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  172850. return FALSE;
  172851. /* Re-initialize DC predictions to 0 */
  172852. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  172853. entropy->saved.last_dc_val[ci] = 0;
  172854. /* Re-init EOB run count, too */
  172855. entropy->saved.EOBRUN = 0;
  172856. /* Reset restart counter */
  172857. entropy->restarts_to_go = cinfo->restart_interval;
  172858. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  172859. * against a marker. In that case we will end up treating the next data
  172860. * segment as empty, and we can avoid producing bogus output pixels by
  172861. * leaving the flag set.
  172862. */
  172863. if (cinfo->unread_marker == 0)
  172864. entropy->pub.insufficient_data = FALSE;
  172865. return TRUE;
  172866. }
  172867. /*
  172868. * Huffman MCU decoding.
  172869. * Each of these routines decodes and returns one MCU's worth of
  172870. * Huffman-compressed coefficients.
  172871. * The coefficients are reordered from zigzag order into natural array order,
  172872. * but are not dequantized.
  172873. *
  172874. * The i'th block of the MCU is stored into the block pointed to by
  172875. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  172876. *
  172877. * We return FALSE if data source requested suspension. In that case no
  172878. * changes have been made to permanent state. (Exception: some output
  172879. * coefficients may already have been assigned. This is harmless for
  172880. * spectral selection, since we'll just re-assign them on the next call.
  172881. * Successive approximation AC refinement has to be more careful, however.)
  172882. */
  172883. /*
  172884. * MCU decoding for DC initial scan (either spectral selection,
  172885. * or first pass of successive approximation).
  172886. */
  172887. METHODDEF(boolean)
  172888. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172889. {
  172890. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172891. int Al = cinfo->Al;
  172892. register int s, r;
  172893. int blkn, ci;
  172894. JBLOCKROW block;
  172895. BITREAD_STATE_VARS;
  172896. savable_state3 state;
  172897. d_derived_tbl * tbl;
  172898. jpeg_component_info * compptr;
  172899. /* Process restart marker if needed; may have to suspend */
  172900. if (cinfo->restart_interval) {
  172901. if (entropy->restarts_to_go == 0)
  172902. if (! process_restartp(cinfo))
  172903. return FALSE;
  172904. }
  172905. /* If we've run out of data, just leave the MCU set to zeroes.
  172906. * This way, we return uniform gray for the remainder of the segment.
  172907. */
  172908. if (! entropy->pub.insufficient_data) {
  172909. /* Load up working state */
  172910. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172911. ASSIGN_STATE(state, entropy->saved);
  172912. /* Outer loop handles each block in the MCU */
  172913. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  172914. block = MCU_data[blkn];
  172915. ci = cinfo->MCU_membership[blkn];
  172916. compptr = cinfo->cur_comp_info[ci];
  172917. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  172918. /* Decode a single block's worth of coefficients */
  172919. /* Section F.2.2.1: decode the DC coefficient difference */
  172920. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  172921. if (s) {
  172922. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172923. r = GET_BITS(s);
  172924. s = HUFF_EXTEND(r, s);
  172925. }
  172926. /* Convert DC difference to actual value, update last_dc_val */
  172927. s += state.last_dc_val[ci];
  172928. state.last_dc_val[ci] = s;
  172929. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  172930. (*block)[0] = (JCOEF) (s << Al);
  172931. }
  172932. /* Completed MCU, so update state */
  172933. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172934. ASSIGN_STATE(entropy->saved, state);
  172935. }
  172936. /* Account for restart interval (no-op if not using restarts) */
  172937. entropy->restarts_to_go--;
  172938. return TRUE;
  172939. }
  172940. /*
  172941. * MCU decoding for AC initial scan (either spectral selection,
  172942. * or first pass of successive approximation).
  172943. */
  172944. METHODDEF(boolean)
  172945. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172946. {
  172947. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172948. int Se = cinfo->Se;
  172949. int Al = cinfo->Al;
  172950. register int s, k, r;
  172951. unsigned int EOBRUN;
  172952. JBLOCKROW block;
  172953. BITREAD_STATE_VARS;
  172954. d_derived_tbl * tbl;
  172955. /* Process restart marker if needed; may have to suspend */
  172956. if (cinfo->restart_interval) {
  172957. if (entropy->restarts_to_go == 0)
  172958. if (! process_restartp(cinfo))
  172959. return FALSE;
  172960. }
  172961. /* If we've run out of data, just leave the MCU set to zeroes.
  172962. * This way, we return uniform gray for the remainder of the segment.
  172963. */
  172964. if (! entropy->pub.insufficient_data) {
  172965. /* Load up working state.
  172966. * We can avoid loading/saving bitread state if in an EOB run.
  172967. */
  172968. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  172969. /* There is always only one block per MCU */
  172970. if (EOBRUN > 0) /* if it's a band of zeroes... */
  172971. EOBRUN--; /* ...process it now (we do nothing) */
  172972. else {
  172973. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172974. block = MCU_data[0];
  172975. tbl = entropy->ac_derived_tbl;
  172976. for (k = cinfo->Ss; k <= Se; k++) {
  172977. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  172978. r = s >> 4;
  172979. s &= 15;
  172980. if (s) {
  172981. k += r;
  172982. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172983. r = GET_BITS(s);
  172984. s = HUFF_EXTEND(r, s);
  172985. /* Scale and output coefficient in natural (dezigzagged) order */
  172986. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  172987. } else {
  172988. if (r == 15) { /* ZRL */
  172989. k += 15; /* skip 15 zeroes in band */
  172990. } else { /* EOBr, run length is 2^r + appended bits */
  172991. EOBRUN = 1 << r;
  172992. if (r) { /* EOBr, r > 0 */
  172993. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  172994. r = GET_BITS(r);
  172995. EOBRUN += r;
  172996. }
  172997. EOBRUN--; /* this band is processed at this moment */
  172998. break; /* force end-of-band */
  172999. }
  173000. }
  173001. }
  173002. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173003. }
  173004. /* Completed MCU, so update state */
  173005. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173006. }
  173007. /* Account for restart interval (no-op if not using restarts) */
  173008. entropy->restarts_to_go--;
  173009. return TRUE;
  173010. }
  173011. /*
  173012. * MCU decoding for DC successive approximation refinement scan.
  173013. * Note: we assume such scans can be multi-component, although the spec
  173014. * is not very clear on the point.
  173015. */
  173016. METHODDEF(boolean)
  173017. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173018. {
  173019. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173020. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173021. int blkn;
  173022. JBLOCKROW block;
  173023. BITREAD_STATE_VARS;
  173024. /* Process restart marker if needed; may have to suspend */
  173025. if (cinfo->restart_interval) {
  173026. if (entropy->restarts_to_go == 0)
  173027. if (! process_restartp(cinfo))
  173028. return FALSE;
  173029. }
  173030. /* Not worth the cycles to check insufficient_data here,
  173031. * since we will not change the data anyway if we read zeroes.
  173032. */
  173033. /* Load up working state */
  173034. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173035. /* Outer loop handles each block in the MCU */
  173036. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173037. block = MCU_data[blkn];
  173038. /* Encoded data is simply the next bit of the two's-complement DC value */
  173039. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173040. if (GET_BITS(1))
  173041. (*block)[0] |= p1;
  173042. /* Note: since we use |=, repeating the assignment later is safe */
  173043. }
  173044. /* Completed MCU, so update state */
  173045. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173046. /* Account for restart interval (no-op if not using restarts) */
  173047. entropy->restarts_to_go--;
  173048. return TRUE;
  173049. }
  173050. /*
  173051. * MCU decoding for AC successive approximation refinement scan.
  173052. */
  173053. METHODDEF(boolean)
  173054. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173055. {
  173056. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173057. int Se = cinfo->Se;
  173058. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173059. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173060. register int s, k, r;
  173061. unsigned int EOBRUN;
  173062. JBLOCKROW block;
  173063. JCOEFPTR thiscoef;
  173064. BITREAD_STATE_VARS;
  173065. d_derived_tbl * tbl;
  173066. int num_newnz;
  173067. int newnz_pos[DCTSIZE2];
  173068. /* Process restart marker if needed; may have to suspend */
  173069. if (cinfo->restart_interval) {
  173070. if (entropy->restarts_to_go == 0)
  173071. if (! process_restartp(cinfo))
  173072. return FALSE;
  173073. }
  173074. /* If we've run out of data, don't modify the MCU.
  173075. */
  173076. if (! entropy->pub.insufficient_data) {
  173077. /* Load up working state */
  173078. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173079. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173080. /* There is always only one block per MCU */
  173081. block = MCU_data[0];
  173082. tbl = entropy->ac_derived_tbl;
  173083. /* If we are forced to suspend, we must undo the assignments to any newly
  173084. * nonzero coefficients in the block, because otherwise we'd get confused
  173085. * next time about which coefficients were already nonzero.
  173086. * But we need not undo addition of bits to already-nonzero coefficients;
  173087. * instead, we can test the current bit to see if we already did it.
  173088. */
  173089. num_newnz = 0;
  173090. /* initialize coefficient loop counter to start of band */
  173091. k = cinfo->Ss;
  173092. if (EOBRUN == 0) {
  173093. for (; k <= Se; k++) {
  173094. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173095. r = s >> 4;
  173096. s &= 15;
  173097. if (s) {
  173098. if (s != 1) /* size of new coef should always be 1 */
  173099. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173100. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173101. if (GET_BITS(1))
  173102. s = p1; /* newly nonzero coef is positive */
  173103. else
  173104. s = m1; /* newly nonzero coef is negative */
  173105. } else {
  173106. if (r != 15) {
  173107. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173108. if (r) {
  173109. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173110. r = GET_BITS(r);
  173111. EOBRUN += r;
  173112. }
  173113. break; /* rest of block is handled by EOB logic */
  173114. }
  173115. /* note s = 0 for processing ZRL */
  173116. }
  173117. /* Advance over already-nonzero coefs and r still-zero coefs,
  173118. * appending correction bits to the nonzeroes. A correction bit is 1
  173119. * if the absolute value of the coefficient must be increased.
  173120. */
  173121. do {
  173122. thiscoef = *block + jpeg_natural_order[k];
  173123. if (*thiscoef != 0) {
  173124. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173125. if (GET_BITS(1)) {
  173126. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173127. if (*thiscoef >= 0)
  173128. *thiscoef += p1;
  173129. else
  173130. *thiscoef += m1;
  173131. }
  173132. }
  173133. } else {
  173134. if (--r < 0)
  173135. break; /* reached target zero coefficient */
  173136. }
  173137. k++;
  173138. } while (k <= Se);
  173139. if (s) {
  173140. int pos = jpeg_natural_order[k];
  173141. /* Output newly nonzero coefficient */
  173142. (*block)[pos] = (JCOEF) s;
  173143. /* Remember its position in case we have to suspend */
  173144. newnz_pos[num_newnz++] = pos;
  173145. }
  173146. }
  173147. }
  173148. if (EOBRUN > 0) {
  173149. /* Scan any remaining coefficient positions after the end-of-band
  173150. * (the last newly nonzero coefficient, if any). Append a correction
  173151. * bit to each already-nonzero coefficient. A correction bit is 1
  173152. * if the absolute value of the coefficient must be increased.
  173153. */
  173154. for (; k <= Se; k++) {
  173155. thiscoef = *block + jpeg_natural_order[k];
  173156. if (*thiscoef != 0) {
  173157. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173158. if (GET_BITS(1)) {
  173159. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173160. if (*thiscoef >= 0)
  173161. *thiscoef += p1;
  173162. else
  173163. *thiscoef += m1;
  173164. }
  173165. }
  173166. }
  173167. }
  173168. /* Count one block completed in EOB run */
  173169. EOBRUN--;
  173170. }
  173171. /* Completed MCU, so update state */
  173172. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173173. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173174. }
  173175. /* Account for restart interval (no-op if not using restarts) */
  173176. entropy->restarts_to_go--;
  173177. return TRUE;
  173178. undoit:
  173179. /* Re-zero any output coefficients that we made newly nonzero */
  173180. while (num_newnz > 0)
  173181. (*block)[newnz_pos[--num_newnz]] = 0;
  173182. return FALSE;
  173183. }
  173184. /*
  173185. * Module initialization routine for progressive Huffman entropy decoding.
  173186. */
  173187. GLOBAL(void)
  173188. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173189. {
  173190. phuff_entropy_ptr2 entropy;
  173191. int *coef_bit_ptr;
  173192. int ci, i;
  173193. entropy = (phuff_entropy_ptr2)
  173194. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173195. SIZEOF(phuff_entropy_decoder));
  173196. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173197. entropy->pub.start_pass = start_pass_phuff_decoder;
  173198. /* Mark derived tables unallocated */
  173199. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173200. entropy->derived_tbls[i] = NULL;
  173201. }
  173202. /* Create progression status table */
  173203. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173204. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173205. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173206. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173207. for (ci = 0; ci < cinfo->num_components; ci++)
  173208. for (i = 0; i < DCTSIZE2; i++)
  173209. *coef_bit_ptr++ = -1;
  173210. }
  173211. #endif /* D_PROGRESSIVE_SUPPORTED */
  173212. /*** End of inlined file: jdphuff.c ***/
  173213. /*** Start of inlined file: jdpostct.c ***/
  173214. #define JPEG_INTERNALS
  173215. /* Private buffer controller object */
  173216. typedef struct {
  173217. struct jpeg_d_post_controller pub; /* public fields */
  173218. /* Color quantization source buffer: this holds output data from
  173219. * the upsample/color conversion step to be passed to the quantizer.
  173220. * For two-pass color quantization, we need a full-image buffer;
  173221. * for one-pass operation, a strip buffer is sufficient.
  173222. */
  173223. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173224. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173225. JDIMENSION strip_height; /* buffer size in rows */
  173226. /* for two-pass mode only: */
  173227. JDIMENSION starting_row; /* row # of first row in current strip */
  173228. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173229. } my_post_controller;
  173230. typedef my_post_controller * my_post_ptr;
  173231. /* Forward declarations */
  173232. METHODDEF(void) post_process_1pass
  173233. JPP((j_decompress_ptr cinfo,
  173234. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173235. JDIMENSION in_row_groups_avail,
  173236. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173237. JDIMENSION out_rows_avail));
  173238. #ifdef QUANT_2PASS_SUPPORTED
  173239. METHODDEF(void) post_process_prepass
  173240. JPP((j_decompress_ptr cinfo,
  173241. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173242. JDIMENSION in_row_groups_avail,
  173243. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173244. JDIMENSION out_rows_avail));
  173245. METHODDEF(void) post_process_2pass
  173246. JPP((j_decompress_ptr cinfo,
  173247. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173248. JDIMENSION in_row_groups_avail,
  173249. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173250. JDIMENSION out_rows_avail));
  173251. #endif
  173252. /*
  173253. * Initialize for a processing pass.
  173254. */
  173255. METHODDEF(void)
  173256. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173257. {
  173258. my_post_ptr post = (my_post_ptr) cinfo->post;
  173259. switch (pass_mode) {
  173260. case JBUF_PASS_THRU:
  173261. if (cinfo->quantize_colors) {
  173262. /* Single-pass processing with color quantization. */
  173263. post->pub.post_process_data = post_process_1pass;
  173264. /* We could be doing buffered-image output before starting a 2-pass
  173265. * color quantization; in that case, jinit_d_post_controller did not
  173266. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173267. */
  173268. if (post->buffer == NULL) {
  173269. post->buffer = (*cinfo->mem->access_virt_sarray)
  173270. ((j_common_ptr) cinfo, post->whole_image,
  173271. (JDIMENSION) 0, post->strip_height, TRUE);
  173272. }
  173273. } else {
  173274. /* For single-pass processing without color quantization,
  173275. * I have no work to do; just call the upsampler directly.
  173276. */
  173277. post->pub.post_process_data = cinfo->upsample->upsample;
  173278. }
  173279. break;
  173280. #ifdef QUANT_2PASS_SUPPORTED
  173281. case JBUF_SAVE_AND_PASS:
  173282. /* First pass of 2-pass quantization */
  173283. if (post->whole_image == NULL)
  173284. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173285. post->pub.post_process_data = post_process_prepass;
  173286. break;
  173287. case JBUF_CRANK_DEST:
  173288. /* Second pass of 2-pass quantization */
  173289. if (post->whole_image == NULL)
  173290. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173291. post->pub.post_process_data = post_process_2pass;
  173292. break;
  173293. #endif /* QUANT_2PASS_SUPPORTED */
  173294. default:
  173295. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173296. break;
  173297. }
  173298. post->starting_row = post->next_row = 0;
  173299. }
  173300. /*
  173301. * Process some data in the one-pass (strip buffer) case.
  173302. * This is used for color precision reduction as well as one-pass quantization.
  173303. */
  173304. METHODDEF(void)
  173305. post_process_1pass (j_decompress_ptr cinfo,
  173306. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173307. JDIMENSION in_row_groups_avail,
  173308. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173309. JDIMENSION out_rows_avail)
  173310. {
  173311. my_post_ptr post = (my_post_ptr) cinfo->post;
  173312. JDIMENSION num_rows, max_rows;
  173313. /* Fill the buffer, but not more than what we can dump out in one go. */
  173314. /* Note we rely on the upsampler to detect bottom of image. */
  173315. max_rows = out_rows_avail - *out_row_ctr;
  173316. if (max_rows > post->strip_height)
  173317. max_rows = post->strip_height;
  173318. num_rows = 0;
  173319. (*cinfo->upsample->upsample) (cinfo,
  173320. input_buf, in_row_group_ctr, in_row_groups_avail,
  173321. post->buffer, &num_rows, max_rows);
  173322. /* Quantize and emit data. */
  173323. (*cinfo->cquantize->color_quantize) (cinfo,
  173324. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173325. *out_row_ctr += num_rows;
  173326. }
  173327. #ifdef QUANT_2PASS_SUPPORTED
  173328. /*
  173329. * Process some data in the first pass of 2-pass quantization.
  173330. */
  173331. METHODDEF(void)
  173332. post_process_prepass (j_decompress_ptr cinfo,
  173333. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173334. JDIMENSION in_row_groups_avail,
  173335. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173336. JDIMENSION)
  173337. {
  173338. my_post_ptr post = (my_post_ptr) cinfo->post;
  173339. JDIMENSION old_next_row, num_rows;
  173340. /* Reposition virtual buffer if at start of strip. */
  173341. if (post->next_row == 0) {
  173342. post->buffer = (*cinfo->mem->access_virt_sarray)
  173343. ((j_common_ptr) cinfo, post->whole_image,
  173344. post->starting_row, post->strip_height, TRUE);
  173345. }
  173346. /* Upsample some data (up to a strip height's worth). */
  173347. old_next_row = post->next_row;
  173348. (*cinfo->upsample->upsample) (cinfo,
  173349. input_buf, in_row_group_ctr, in_row_groups_avail,
  173350. post->buffer, &post->next_row, post->strip_height);
  173351. /* Allow quantizer to scan new data. No data is emitted, */
  173352. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173353. if (post->next_row > old_next_row) {
  173354. num_rows = post->next_row - old_next_row;
  173355. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173356. (JSAMPARRAY) NULL, (int) num_rows);
  173357. *out_row_ctr += num_rows;
  173358. }
  173359. /* Advance if we filled the strip. */
  173360. if (post->next_row >= post->strip_height) {
  173361. post->starting_row += post->strip_height;
  173362. post->next_row = 0;
  173363. }
  173364. }
  173365. /*
  173366. * Process some data in the second pass of 2-pass quantization.
  173367. */
  173368. METHODDEF(void)
  173369. post_process_2pass (j_decompress_ptr cinfo,
  173370. JSAMPIMAGE, JDIMENSION *,
  173371. JDIMENSION,
  173372. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173373. JDIMENSION out_rows_avail)
  173374. {
  173375. my_post_ptr post = (my_post_ptr) cinfo->post;
  173376. JDIMENSION num_rows, max_rows;
  173377. /* Reposition virtual buffer if at start of strip. */
  173378. if (post->next_row == 0) {
  173379. post->buffer = (*cinfo->mem->access_virt_sarray)
  173380. ((j_common_ptr) cinfo, post->whole_image,
  173381. post->starting_row, post->strip_height, FALSE);
  173382. }
  173383. /* Determine number of rows to emit. */
  173384. num_rows = post->strip_height - post->next_row; /* available in strip */
  173385. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173386. if (num_rows > max_rows)
  173387. num_rows = max_rows;
  173388. /* We have to check bottom of image here, can't depend on upsampler. */
  173389. max_rows = cinfo->output_height - post->starting_row;
  173390. if (num_rows > max_rows)
  173391. num_rows = max_rows;
  173392. /* Quantize and emit data. */
  173393. (*cinfo->cquantize->color_quantize) (cinfo,
  173394. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173395. (int) num_rows);
  173396. *out_row_ctr += num_rows;
  173397. /* Advance if we filled the strip. */
  173398. post->next_row += num_rows;
  173399. if (post->next_row >= post->strip_height) {
  173400. post->starting_row += post->strip_height;
  173401. post->next_row = 0;
  173402. }
  173403. }
  173404. #endif /* QUANT_2PASS_SUPPORTED */
  173405. /*
  173406. * Initialize postprocessing controller.
  173407. */
  173408. GLOBAL(void)
  173409. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173410. {
  173411. my_post_ptr post;
  173412. post = (my_post_ptr)
  173413. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173414. SIZEOF(my_post_controller));
  173415. cinfo->post = (struct jpeg_d_post_controller *) post;
  173416. post->pub.start_pass = start_pass_dpost;
  173417. post->whole_image = NULL; /* flag for no virtual arrays */
  173418. post->buffer = NULL; /* flag for no strip buffer */
  173419. /* Create the quantization buffer, if needed */
  173420. if (cinfo->quantize_colors) {
  173421. /* The buffer strip height is max_v_samp_factor, which is typically
  173422. * an efficient number of rows for upsampling to return.
  173423. * (In the presence of output rescaling, we might want to be smarter?)
  173424. */
  173425. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173426. if (need_full_buffer) {
  173427. /* Two-pass color quantization: need full-image storage. */
  173428. /* We round up the number of rows to a multiple of the strip height. */
  173429. #ifdef QUANT_2PASS_SUPPORTED
  173430. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173431. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173432. cinfo->output_width * cinfo->out_color_components,
  173433. (JDIMENSION) jround_up((long) cinfo->output_height,
  173434. (long) post->strip_height),
  173435. post->strip_height);
  173436. #else
  173437. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173438. #endif /* QUANT_2PASS_SUPPORTED */
  173439. } else {
  173440. /* One-pass color quantization: just make a strip buffer. */
  173441. post->buffer = (*cinfo->mem->alloc_sarray)
  173442. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173443. cinfo->output_width * cinfo->out_color_components,
  173444. post->strip_height);
  173445. }
  173446. }
  173447. }
  173448. /*** End of inlined file: jdpostct.c ***/
  173449. #undef FIX
  173450. /*** Start of inlined file: jdsample.c ***/
  173451. #define JPEG_INTERNALS
  173452. /* Pointer to routine to upsample a single component */
  173453. typedef JMETHOD(void, upsample1_ptr,
  173454. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173455. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173456. /* Private subobject */
  173457. typedef struct {
  173458. struct jpeg_upsampler pub; /* public fields */
  173459. /* Color conversion buffer. When using separate upsampling and color
  173460. * conversion steps, this buffer holds one upsampled row group until it
  173461. * has been color converted and output.
  173462. * Note: we do not allocate any storage for component(s) which are full-size,
  173463. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173464. * simply set to point to the input data array, thereby avoiding copying.
  173465. */
  173466. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173467. /* Per-component upsampling method pointers */
  173468. upsample1_ptr methods[MAX_COMPONENTS];
  173469. int next_row_out; /* counts rows emitted from color_buf */
  173470. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173471. /* Height of an input row group for each component. */
  173472. int rowgroup_height[MAX_COMPONENTS];
  173473. /* These arrays save pixel expansion factors so that int_expand need not
  173474. * recompute them each time. They are unused for other upsampling methods.
  173475. */
  173476. UINT8 h_expand[MAX_COMPONENTS];
  173477. UINT8 v_expand[MAX_COMPONENTS];
  173478. } my_upsampler2;
  173479. typedef my_upsampler2 * my_upsample_ptr2;
  173480. /*
  173481. * Initialize for an upsampling pass.
  173482. */
  173483. METHODDEF(void)
  173484. start_pass_upsample (j_decompress_ptr cinfo)
  173485. {
  173486. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173487. /* Mark the conversion buffer empty */
  173488. upsample->next_row_out = cinfo->max_v_samp_factor;
  173489. /* Initialize total-height counter for detecting bottom of image */
  173490. upsample->rows_to_go = cinfo->output_height;
  173491. }
  173492. /*
  173493. * Control routine to do upsampling (and color conversion).
  173494. *
  173495. * In this version we upsample each component independently.
  173496. * We upsample one row group into the conversion buffer, then apply
  173497. * color conversion a row at a time.
  173498. */
  173499. METHODDEF(void)
  173500. sep_upsample (j_decompress_ptr cinfo,
  173501. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173502. JDIMENSION,
  173503. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173504. JDIMENSION out_rows_avail)
  173505. {
  173506. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173507. int ci;
  173508. jpeg_component_info * compptr;
  173509. JDIMENSION num_rows;
  173510. /* Fill the conversion buffer, if it's empty */
  173511. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  173512. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173513. ci++, compptr++) {
  173514. /* Invoke per-component upsample method. Notice we pass a POINTER
  173515. * to color_buf[ci], so that fullsize_upsample can change it.
  173516. */
  173517. (*upsample->methods[ci]) (cinfo, compptr,
  173518. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  173519. upsample->color_buf + ci);
  173520. }
  173521. upsample->next_row_out = 0;
  173522. }
  173523. /* Color-convert and emit rows */
  173524. /* How many we have in the buffer: */
  173525. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  173526. /* Not more than the distance to the end of the image. Need this test
  173527. * in case the image height is not a multiple of max_v_samp_factor:
  173528. */
  173529. if (num_rows > upsample->rows_to_go)
  173530. num_rows = upsample->rows_to_go;
  173531. /* And not more than what the client can accept: */
  173532. out_rows_avail -= *out_row_ctr;
  173533. if (num_rows > out_rows_avail)
  173534. num_rows = out_rows_avail;
  173535. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  173536. (JDIMENSION) upsample->next_row_out,
  173537. output_buf + *out_row_ctr,
  173538. (int) num_rows);
  173539. /* Adjust counts */
  173540. *out_row_ctr += num_rows;
  173541. upsample->rows_to_go -= num_rows;
  173542. upsample->next_row_out += num_rows;
  173543. /* When the buffer is emptied, declare this input row group consumed */
  173544. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  173545. (*in_row_group_ctr)++;
  173546. }
  173547. /*
  173548. * These are the routines invoked by sep_upsample to upsample pixel values
  173549. * of a single component. One row group is processed per call.
  173550. */
  173551. /*
  173552. * For full-size components, we just make color_buf[ci] point at the
  173553. * input buffer, and thus avoid copying any data. Note that this is
  173554. * safe only because sep_upsample doesn't declare the input row group
  173555. * "consumed" until we are done color converting and emitting it.
  173556. */
  173557. METHODDEF(void)
  173558. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  173559. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173560. {
  173561. *output_data_ptr = input_data;
  173562. }
  173563. /*
  173564. * This is a no-op version used for "uninteresting" components.
  173565. * These components will not be referenced by color conversion.
  173566. */
  173567. METHODDEF(void)
  173568. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  173569. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  173570. {
  173571. *output_data_ptr = NULL; /* safety check */
  173572. }
  173573. /*
  173574. * This version handles any integral sampling ratios.
  173575. * This is not used for typical JPEG files, so it need not be fast.
  173576. * Nor, for that matter, is it particularly accurate: the algorithm is
  173577. * simple replication of the input pixel onto the corresponding output
  173578. * pixels. The hi-falutin sampling literature refers to this as a
  173579. * "box filter". A box filter tends to introduce visible artifacts,
  173580. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  173581. * you would be well advised to improve this code.
  173582. */
  173583. METHODDEF(void)
  173584. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173585. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173586. {
  173587. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173588. JSAMPARRAY output_data = *output_data_ptr;
  173589. register JSAMPROW inptr, outptr;
  173590. register JSAMPLE invalue;
  173591. register int h;
  173592. JSAMPROW outend;
  173593. int h_expand, v_expand;
  173594. int inrow, outrow;
  173595. h_expand = upsample->h_expand[compptr->component_index];
  173596. v_expand = upsample->v_expand[compptr->component_index];
  173597. inrow = outrow = 0;
  173598. while (outrow < cinfo->max_v_samp_factor) {
  173599. /* Generate one output row with proper horizontal expansion */
  173600. inptr = input_data[inrow];
  173601. outptr = output_data[outrow];
  173602. outend = outptr + cinfo->output_width;
  173603. while (outptr < outend) {
  173604. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173605. for (h = h_expand; h > 0; h--) {
  173606. *outptr++ = invalue;
  173607. }
  173608. }
  173609. /* Generate any additional output rows by duplicating the first one */
  173610. if (v_expand > 1) {
  173611. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173612. v_expand-1, cinfo->output_width);
  173613. }
  173614. inrow++;
  173615. outrow += v_expand;
  173616. }
  173617. }
  173618. /*
  173619. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  173620. * It's still a box filter.
  173621. */
  173622. METHODDEF(void)
  173623. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173624. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173625. {
  173626. JSAMPARRAY output_data = *output_data_ptr;
  173627. register JSAMPROW inptr, outptr;
  173628. register JSAMPLE invalue;
  173629. JSAMPROW outend;
  173630. int inrow;
  173631. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173632. inptr = input_data[inrow];
  173633. outptr = output_data[inrow];
  173634. outend = outptr + cinfo->output_width;
  173635. while (outptr < outend) {
  173636. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173637. *outptr++ = invalue;
  173638. *outptr++ = invalue;
  173639. }
  173640. }
  173641. }
  173642. /*
  173643. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  173644. * It's still a box filter.
  173645. */
  173646. METHODDEF(void)
  173647. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173648. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173649. {
  173650. JSAMPARRAY output_data = *output_data_ptr;
  173651. register JSAMPROW inptr, outptr;
  173652. register JSAMPLE invalue;
  173653. JSAMPROW outend;
  173654. int inrow, outrow;
  173655. inrow = outrow = 0;
  173656. while (outrow < cinfo->max_v_samp_factor) {
  173657. inptr = input_data[inrow];
  173658. outptr = output_data[outrow];
  173659. outend = outptr + cinfo->output_width;
  173660. while (outptr < outend) {
  173661. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173662. *outptr++ = invalue;
  173663. *outptr++ = invalue;
  173664. }
  173665. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173666. 1, cinfo->output_width);
  173667. inrow++;
  173668. outrow += 2;
  173669. }
  173670. }
  173671. /*
  173672. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  173673. *
  173674. * The upsampling algorithm is linear interpolation between pixel centers,
  173675. * also known as a "triangle filter". This is a good compromise between
  173676. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  173677. * of the way between input pixel centers.
  173678. *
  173679. * A note about the "bias" calculations: when rounding fractional values to
  173680. * integer, we do not want to always round 0.5 up to the next integer.
  173681. * If we did that, we'd introduce a noticeable bias towards larger values.
  173682. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  173683. * alternate pixel locations (a simple ordered dither pattern).
  173684. */
  173685. METHODDEF(void)
  173686. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173687. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173688. {
  173689. JSAMPARRAY output_data = *output_data_ptr;
  173690. register JSAMPROW inptr, outptr;
  173691. register int invalue;
  173692. register JDIMENSION colctr;
  173693. int inrow;
  173694. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173695. inptr = input_data[inrow];
  173696. outptr = output_data[inrow];
  173697. /* Special case for first column */
  173698. invalue = GETJSAMPLE(*inptr++);
  173699. *outptr++ = (JSAMPLE) invalue;
  173700. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  173701. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173702. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  173703. invalue = GETJSAMPLE(*inptr++) * 3;
  173704. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  173705. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  173706. }
  173707. /* Special case for last column */
  173708. invalue = GETJSAMPLE(*inptr);
  173709. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  173710. *outptr++ = (JSAMPLE) invalue;
  173711. }
  173712. }
  173713. /*
  173714. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  173715. * Again a triangle filter; see comments for h2v1 case, above.
  173716. *
  173717. * It is OK for us to reference the adjacent input rows because we demanded
  173718. * context from the main buffer controller (see initialization code).
  173719. */
  173720. METHODDEF(void)
  173721. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173722. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173723. {
  173724. JSAMPARRAY output_data = *output_data_ptr;
  173725. register JSAMPROW inptr0, inptr1, outptr;
  173726. #if BITS_IN_JSAMPLE == 8
  173727. register int thiscolsum, lastcolsum, nextcolsum;
  173728. #else
  173729. register INT32 thiscolsum, lastcolsum, nextcolsum;
  173730. #endif
  173731. register JDIMENSION colctr;
  173732. int inrow, outrow, v;
  173733. inrow = outrow = 0;
  173734. while (outrow < cinfo->max_v_samp_factor) {
  173735. for (v = 0; v < 2; v++) {
  173736. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  173737. inptr0 = input_data[inrow];
  173738. if (v == 0) /* next nearest is row above */
  173739. inptr1 = input_data[inrow-1];
  173740. else /* next nearest is row below */
  173741. inptr1 = input_data[inrow+1];
  173742. outptr = output_data[outrow++];
  173743. /* Special case for first column */
  173744. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173745. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173746. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  173747. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173748. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173749. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173750. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  173751. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  173752. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173753. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173754. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173755. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173756. }
  173757. /* Special case for last column */
  173758. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173759. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  173760. }
  173761. inrow++;
  173762. }
  173763. }
  173764. /*
  173765. * Module initialization routine for upsampling.
  173766. */
  173767. GLOBAL(void)
  173768. jinit_upsampler (j_decompress_ptr cinfo)
  173769. {
  173770. my_upsample_ptr2 upsample;
  173771. int ci;
  173772. jpeg_component_info * compptr;
  173773. boolean need_buffer, do_fancy;
  173774. int h_in_group, v_in_group, h_out_group, v_out_group;
  173775. upsample = (my_upsample_ptr2)
  173776. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173777. SIZEOF(my_upsampler2));
  173778. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173779. upsample->pub.start_pass = start_pass_upsample;
  173780. upsample->pub.upsample = sep_upsample;
  173781. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  173782. if (cinfo->CCIR601_sampling) /* this isn't supported */
  173783. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  173784. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  173785. * so don't ask for it.
  173786. */
  173787. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  173788. /* Verify we can handle the sampling factors, select per-component methods,
  173789. * and create storage as needed.
  173790. */
  173791. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173792. ci++, compptr++) {
  173793. /* Compute size of an "input group" after IDCT scaling. This many samples
  173794. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  173795. */
  173796. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  173797. cinfo->min_DCT_scaled_size;
  173798. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  173799. cinfo->min_DCT_scaled_size;
  173800. h_out_group = cinfo->max_h_samp_factor;
  173801. v_out_group = cinfo->max_v_samp_factor;
  173802. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  173803. need_buffer = TRUE;
  173804. if (! compptr->component_needed) {
  173805. /* Don't bother to upsample an uninteresting component. */
  173806. upsample->methods[ci] = noop_upsample;
  173807. need_buffer = FALSE;
  173808. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  173809. /* Fullsize components can be processed without any work. */
  173810. upsample->methods[ci] = fullsize_upsample;
  173811. need_buffer = FALSE;
  173812. } else if (h_in_group * 2 == h_out_group &&
  173813. v_in_group == v_out_group) {
  173814. /* Special cases for 2h1v upsampling */
  173815. if (do_fancy && compptr->downsampled_width > 2)
  173816. upsample->methods[ci] = h2v1_fancy_upsample;
  173817. else
  173818. upsample->methods[ci] = h2v1_upsample;
  173819. } else if (h_in_group * 2 == h_out_group &&
  173820. v_in_group * 2 == v_out_group) {
  173821. /* Special cases for 2h2v upsampling */
  173822. if (do_fancy && compptr->downsampled_width > 2) {
  173823. upsample->methods[ci] = h2v2_fancy_upsample;
  173824. upsample->pub.need_context_rows = TRUE;
  173825. } else
  173826. upsample->methods[ci] = h2v2_upsample;
  173827. } else if ((h_out_group % h_in_group) == 0 &&
  173828. (v_out_group % v_in_group) == 0) {
  173829. /* Generic integral-factors upsampling method */
  173830. upsample->methods[ci] = int_upsample;
  173831. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  173832. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  173833. } else
  173834. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  173835. if (need_buffer) {
  173836. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  173837. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173838. (JDIMENSION) jround_up((long) cinfo->output_width,
  173839. (long) cinfo->max_h_samp_factor),
  173840. (JDIMENSION) cinfo->max_v_samp_factor);
  173841. }
  173842. }
  173843. }
  173844. /*** End of inlined file: jdsample.c ***/
  173845. /*** Start of inlined file: jdtrans.c ***/
  173846. #define JPEG_INTERNALS
  173847. /* Forward declarations */
  173848. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  173849. /*
  173850. * Read the coefficient arrays from a JPEG file.
  173851. * jpeg_read_header must be completed before calling this.
  173852. *
  173853. * The entire image is read into a set of virtual coefficient-block arrays,
  173854. * one per component. The return value is a pointer to the array of
  173855. * virtual-array descriptors. These can be manipulated directly via the
  173856. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  173857. * To release the memory occupied by the virtual arrays, call
  173858. * jpeg_finish_decompress() when done with the data.
  173859. *
  173860. * An alternative usage is to simply obtain access to the coefficient arrays
  173861. * during a buffered-image-mode decompression operation. This is allowed
  173862. * after any jpeg_finish_output() call. The arrays can be accessed until
  173863. * jpeg_finish_decompress() is called. (Note that any call to the library
  173864. * may reposition the arrays, so don't rely on access_virt_barray() results
  173865. * to stay valid across library calls.)
  173866. *
  173867. * Returns NULL if suspended. This case need be checked only if
  173868. * a suspending data source is used.
  173869. */
  173870. GLOBAL(jvirt_barray_ptr *)
  173871. jpeg_read_coefficients (j_decompress_ptr cinfo)
  173872. {
  173873. if (cinfo->global_state == DSTATE_READY) {
  173874. /* First call: initialize active modules */
  173875. transdecode_master_selection(cinfo);
  173876. cinfo->global_state = DSTATE_RDCOEFS;
  173877. }
  173878. if (cinfo->global_state == DSTATE_RDCOEFS) {
  173879. /* Absorb whole file into the coef buffer */
  173880. for (;;) {
  173881. int retcode;
  173882. /* Call progress monitor hook if present */
  173883. if (cinfo->progress != NULL)
  173884. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  173885. /* Absorb some more input */
  173886. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  173887. if (retcode == JPEG_SUSPENDED)
  173888. return NULL;
  173889. if (retcode == JPEG_REACHED_EOI)
  173890. break;
  173891. /* Advance progress counter if appropriate */
  173892. if (cinfo->progress != NULL &&
  173893. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  173894. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  173895. /* startup underestimated number of scans; ratchet up one scan */
  173896. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  173897. }
  173898. }
  173899. }
  173900. /* Set state so that jpeg_finish_decompress does the right thing */
  173901. cinfo->global_state = DSTATE_STOPPING;
  173902. }
  173903. /* At this point we should be in state DSTATE_STOPPING if being used
  173904. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  173905. * to the coefficients during a full buffered-image-mode decompression.
  173906. */
  173907. if ((cinfo->global_state == DSTATE_STOPPING ||
  173908. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  173909. return cinfo->coef->coef_arrays;
  173910. }
  173911. /* Oops, improper usage */
  173912. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  173913. return NULL; /* keep compiler happy */
  173914. }
  173915. /*
  173916. * Master selection of decompression modules for transcoding.
  173917. * This substitutes for jdmaster.c's initialization of the full decompressor.
  173918. */
  173919. LOCAL(void)
  173920. transdecode_master_selection (j_decompress_ptr cinfo)
  173921. {
  173922. /* This is effectively a buffered-image operation. */
  173923. cinfo->buffered_image = TRUE;
  173924. /* Entropy decoding: either Huffman or arithmetic coding. */
  173925. if (cinfo->arith_code) {
  173926. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  173927. } else {
  173928. if (cinfo->progressive_mode) {
  173929. #ifdef D_PROGRESSIVE_SUPPORTED
  173930. jinit_phuff_decoder(cinfo);
  173931. #else
  173932. ERREXIT(cinfo, JERR_NOT_COMPILED);
  173933. #endif
  173934. } else
  173935. jinit_huff_decoder(cinfo);
  173936. }
  173937. /* Always get a full-image coefficient buffer. */
  173938. jinit_d_coef_controller(cinfo, TRUE);
  173939. /* We can now tell the memory manager to allocate virtual arrays. */
  173940. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  173941. /* Initialize input side of decompressor to consume first scan. */
  173942. (*cinfo->inputctl->start_input_pass) (cinfo);
  173943. /* Initialize progress monitoring. */
  173944. if (cinfo->progress != NULL) {
  173945. int nscans;
  173946. /* Estimate number of scans to set pass_limit. */
  173947. if (cinfo->progressive_mode) {
  173948. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  173949. nscans = 2 + 3 * cinfo->num_components;
  173950. } else if (cinfo->inputctl->has_multiple_scans) {
  173951. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  173952. nscans = cinfo->num_components;
  173953. } else {
  173954. nscans = 1;
  173955. }
  173956. cinfo->progress->pass_counter = 0L;
  173957. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  173958. cinfo->progress->completed_passes = 0;
  173959. cinfo->progress->total_passes = 1;
  173960. }
  173961. }
  173962. /*** End of inlined file: jdtrans.c ***/
  173963. /*** Start of inlined file: jfdctflt.c ***/
  173964. #define JPEG_INTERNALS
  173965. #ifdef DCT_FLOAT_SUPPORTED
  173966. /*
  173967. * This module is specialized to the case DCTSIZE = 8.
  173968. */
  173969. #if DCTSIZE != 8
  173970. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173971. #endif
  173972. /*
  173973. * Perform the forward DCT on one block of samples.
  173974. */
  173975. GLOBAL(void)
  173976. jpeg_fdct_float (FAST_FLOAT * data)
  173977. {
  173978. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173979. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  173980. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  173981. FAST_FLOAT *dataptr;
  173982. int ctr;
  173983. /* Pass 1: process rows. */
  173984. dataptr = data;
  173985. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173986. tmp0 = dataptr[0] + dataptr[7];
  173987. tmp7 = dataptr[0] - dataptr[7];
  173988. tmp1 = dataptr[1] + dataptr[6];
  173989. tmp6 = dataptr[1] - dataptr[6];
  173990. tmp2 = dataptr[2] + dataptr[5];
  173991. tmp5 = dataptr[2] - dataptr[5];
  173992. tmp3 = dataptr[3] + dataptr[4];
  173993. tmp4 = dataptr[3] - dataptr[4];
  173994. /* Even part */
  173995. tmp10 = tmp0 + tmp3; /* phase 2 */
  173996. tmp13 = tmp0 - tmp3;
  173997. tmp11 = tmp1 + tmp2;
  173998. tmp12 = tmp1 - tmp2;
  173999. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174000. dataptr[4] = tmp10 - tmp11;
  174001. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174002. dataptr[2] = tmp13 + z1; /* phase 5 */
  174003. dataptr[6] = tmp13 - z1;
  174004. /* Odd part */
  174005. tmp10 = tmp4 + tmp5; /* phase 2 */
  174006. tmp11 = tmp5 + tmp6;
  174007. tmp12 = tmp6 + tmp7;
  174008. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174009. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174010. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174011. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174012. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174013. z11 = tmp7 + z3; /* phase 5 */
  174014. z13 = tmp7 - z3;
  174015. dataptr[5] = z13 + z2; /* phase 6 */
  174016. dataptr[3] = z13 - z2;
  174017. dataptr[1] = z11 + z4;
  174018. dataptr[7] = z11 - z4;
  174019. dataptr += DCTSIZE; /* advance pointer to next row */
  174020. }
  174021. /* Pass 2: process columns. */
  174022. dataptr = data;
  174023. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174024. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174025. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174026. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174027. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174028. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174029. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174030. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174031. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174032. /* Even part */
  174033. tmp10 = tmp0 + tmp3; /* phase 2 */
  174034. tmp13 = tmp0 - tmp3;
  174035. tmp11 = tmp1 + tmp2;
  174036. tmp12 = tmp1 - tmp2;
  174037. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174038. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174039. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174040. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174041. dataptr[DCTSIZE*6] = tmp13 - z1;
  174042. /* Odd part */
  174043. tmp10 = tmp4 + tmp5; /* phase 2 */
  174044. tmp11 = tmp5 + tmp6;
  174045. tmp12 = tmp6 + tmp7;
  174046. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174047. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174048. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174049. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174050. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174051. z11 = tmp7 + z3; /* phase 5 */
  174052. z13 = tmp7 - z3;
  174053. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174054. dataptr[DCTSIZE*3] = z13 - z2;
  174055. dataptr[DCTSIZE*1] = z11 + z4;
  174056. dataptr[DCTSIZE*7] = z11 - z4;
  174057. dataptr++; /* advance pointer to next column */
  174058. }
  174059. }
  174060. #endif /* DCT_FLOAT_SUPPORTED */
  174061. /*** End of inlined file: jfdctflt.c ***/
  174062. /*** Start of inlined file: jfdctint.c ***/
  174063. #define JPEG_INTERNALS
  174064. #ifdef DCT_ISLOW_SUPPORTED
  174065. /*
  174066. * This module is specialized to the case DCTSIZE = 8.
  174067. */
  174068. #if DCTSIZE != 8
  174069. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174070. #endif
  174071. /*
  174072. * The poop on this scaling stuff is as follows:
  174073. *
  174074. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174075. * larger than the true DCT outputs. The final outputs are therefore
  174076. * a factor of N larger than desired; since N=8 this can be cured by
  174077. * a simple right shift at the end of the algorithm. The advantage of
  174078. * this arrangement is that we save two multiplications per 1-D DCT,
  174079. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174080. * In the IJG code, this factor of 8 is removed by the quantization step
  174081. * (in jcdctmgr.c), NOT in this module.
  174082. *
  174083. * We have to do addition and subtraction of the integer inputs, which
  174084. * is no problem, and multiplication by fractional constants, which is
  174085. * a problem to do in integer arithmetic. We multiply all the constants
  174086. * by CONST_SCALE and convert them to integer constants (thus retaining
  174087. * CONST_BITS bits of precision in the constants). After doing a
  174088. * multiplication we have to divide the product by CONST_SCALE, with proper
  174089. * rounding, to produce the correct output. This division can be done
  174090. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174091. * as long as possible so that partial sums can be added together with
  174092. * full fractional precision.
  174093. *
  174094. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174095. * they are represented to better-than-integral precision. These outputs
  174096. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174097. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174098. * array is INT32 anyway.)
  174099. *
  174100. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174101. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174102. * shows that the values given below are the most effective.
  174103. */
  174104. #if BITS_IN_JSAMPLE == 8
  174105. #define CONST_BITS 13
  174106. #define PASS1_BITS 2
  174107. #else
  174108. #define CONST_BITS 13
  174109. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174110. #endif
  174111. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174112. * causing a lot of useless floating-point operations at run time.
  174113. * To get around this we use the following pre-calculated constants.
  174114. * If you change CONST_BITS you may want to add appropriate values.
  174115. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174116. */
  174117. #if CONST_BITS == 13
  174118. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174119. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174120. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174121. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174122. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174123. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174124. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174125. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174126. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174127. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174128. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174129. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174130. #else
  174131. #define FIX_0_298631336 FIX(0.298631336)
  174132. #define FIX_0_390180644 FIX(0.390180644)
  174133. #define FIX_0_541196100 FIX(0.541196100)
  174134. #define FIX_0_765366865 FIX(0.765366865)
  174135. #define FIX_0_899976223 FIX(0.899976223)
  174136. #define FIX_1_175875602 FIX(1.175875602)
  174137. #define FIX_1_501321110 FIX(1.501321110)
  174138. #define FIX_1_847759065 FIX(1.847759065)
  174139. #define FIX_1_961570560 FIX(1.961570560)
  174140. #define FIX_2_053119869 FIX(2.053119869)
  174141. #define FIX_2_562915447 FIX(2.562915447)
  174142. #define FIX_3_072711026 FIX(3.072711026)
  174143. #endif
  174144. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174145. * For 8-bit samples with the recommended scaling, all the variable
  174146. * and constant values involved are no more than 16 bits wide, so a
  174147. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174148. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174149. */
  174150. #if BITS_IN_JSAMPLE == 8
  174151. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174152. #else
  174153. #define MULTIPLY(var,const) ((var) * (const))
  174154. #endif
  174155. /*
  174156. * Perform the forward DCT on one block of samples.
  174157. */
  174158. GLOBAL(void)
  174159. jpeg_fdct_islow (DCTELEM * data)
  174160. {
  174161. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174162. INT32 tmp10, tmp11, tmp12, tmp13;
  174163. INT32 z1, z2, z3, z4, z5;
  174164. DCTELEM *dataptr;
  174165. int ctr;
  174166. SHIFT_TEMPS
  174167. /* Pass 1: process rows. */
  174168. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174169. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174170. dataptr = data;
  174171. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174172. tmp0 = dataptr[0] + dataptr[7];
  174173. tmp7 = dataptr[0] - dataptr[7];
  174174. tmp1 = dataptr[1] + dataptr[6];
  174175. tmp6 = dataptr[1] - dataptr[6];
  174176. tmp2 = dataptr[2] + dataptr[5];
  174177. tmp5 = dataptr[2] - dataptr[5];
  174178. tmp3 = dataptr[3] + dataptr[4];
  174179. tmp4 = dataptr[3] - dataptr[4];
  174180. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174181. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174182. */
  174183. tmp10 = tmp0 + tmp3;
  174184. tmp13 = tmp0 - tmp3;
  174185. tmp11 = tmp1 + tmp2;
  174186. tmp12 = tmp1 - tmp2;
  174187. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174188. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174189. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174190. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174191. CONST_BITS-PASS1_BITS);
  174192. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174193. CONST_BITS-PASS1_BITS);
  174194. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174195. * cK represents cos(K*pi/16).
  174196. * i0..i3 in the paper are tmp4..tmp7 here.
  174197. */
  174198. z1 = tmp4 + tmp7;
  174199. z2 = tmp5 + tmp6;
  174200. z3 = tmp4 + tmp6;
  174201. z4 = tmp5 + tmp7;
  174202. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174203. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174204. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174205. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174206. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174207. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174208. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174209. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174210. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174211. z3 += z5;
  174212. z4 += z5;
  174213. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174214. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174215. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174216. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174217. dataptr += DCTSIZE; /* advance pointer to next row */
  174218. }
  174219. /* Pass 2: process columns.
  174220. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174221. * by an overall factor of 8.
  174222. */
  174223. dataptr = data;
  174224. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174225. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174226. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174227. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174228. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174229. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174230. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174231. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174232. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174233. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174234. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174235. */
  174236. tmp10 = tmp0 + tmp3;
  174237. tmp13 = tmp0 - tmp3;
  174238. tmp11 = tmp1 + tmp2;
  174239. tmp12 = tmp1 - tmp2;
  174240. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174241. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174242. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174243. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174244. CONST_BITS+PASS1_BITS);
  174245. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174246. CONST_BITS+PASS1_BITS);
  174247. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174248. * cK represents cos(K*pi/16).
  174249. * i0..i3 in the paper are tmp4..tmp7 here.
  174250. */
  174251. z1 = tmp4 + tmp7;
  174252. z2 = tmp5 + tmp6;
  174253. z3 = tmp4 + tmp6;
  174254. z4 = tmp5 + tmp7;
  174255. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174256. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174257. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174258. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174259. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174260. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174261. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174262. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174263. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174264. z3 += z5;
  174265. z4 += z5;
  174266. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174267. CONST_BITS+PASS1_BITS);
  174268. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174269. CONST_BITS+PASS1_BITS);
  174270. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174271. CONST_BITS+PASS1_BITS);
  174272. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174273. CONST_BITS+PASS1_BITS);
  174274. dataptr++; /* advance pointer to next column */
  174275. }
  174276. }
  174277. #endif /* DCT_ISLOW_SUPPORTED */
  174278. /*** End of inlined file: jfdctint.c ***/
  174279. #undef CONST_BITS
  174280. #undef MULTIPLY
  174281. #undef FIX_0_541196100
  174282. /*** Start of inlined file: jfdctfst.c ***/
  174283. #define JPEG_INTERNALS
  174284. #ifdef DCT_IFAST_SUPPORTED
  174285. /*
  174286. * This module is specialized to the case DCTSIZE = 8.
  174287. */
  174288. #if DCTSIZE != 8
  174289. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174290. #endif
  174291. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174292. * see jfdctint.c for more details. However, we choose to descale
  174293. * (right shift) multiplication products as soon as they are formed,
  174294. * rather than carrying additional fractional bits into subsequent additions.
  174295. * This compromises accuracy slightly, but it lets us save a few shifts.
  174296. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174297. * everywhere except in the multiplications proper; this saves a good deal
  174298. * of work on 16-bit-int machines.
  174299. *
  174300. * Again to save a few shifts, the intermediate results between pass 1 and
  174301. * pass 2 are not upscaled, but are represented only to integral precision.
  174302. *
  174303. * A final compromise is to represent the multiplicative constants to only
  174304. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174305. * machines, and may also reduce the cost of multiplication (since there
  174306. * are fewer one-bits in the constants).
  174307. */
  174308. #define CONST_BITS 8
  174309. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174310. * causing a lot of useless floating-point operations at run time.
  174311. * To get around this we use the following pre-calculated constants.
  174312. * If you change CONST_BITS you may want to add appropriate values.
  174313. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174314. */
  174315. #if CONST_BITS == 8
  174316. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174317. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174318. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174319. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174320. #else
  174321. #define FIX_0_382683433 FIX(0.382683433)
  174322. #define FIX_0_541196100 FIX(0.541196100)
  174323. #define FIX_0_707106781 FIX(0.707106781)
  174324. #define FIX_1_306562965 FIX(1.306562965)
  174325. #endif
  174326. /* We can gain a little more speed, with a further compromise in accuracy,
  174327. * by omitting the addition in a descaling shift. This yields an incorrectly
  174328. * rounded result half the time...
  174329. */
  174330. #ifndef USE_ACCURATE_ROUNDING
  174331. #undef DESCALE
  174332. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174333. #endif
  174334. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174335. * descale to yield a DCTELEM result.
  174336. */
  174337. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174338. /*
  174339. * Perform the forward DCT on one block of samples.
  174340. */
  174341. GLOBAL(void)
  174342. jpeg_fdct_ifast (DCTELEM * data)
  174343. {
  174344. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174345. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174346. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174347. DCTELEM *dataptr;
  174348. int ctr;
  174349. SHIFT_TEMPS
  174350. /* Pass 1: process rows. */
  174351. dataptr = data;
  174352. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174353. tmp0 = dataptr[0] + dataptr[7];
  174354. tmp7 = dataptr[0] - dataptr[7];
  174355. tmp1 = dataptr[1] + dataptr[6];
  174356. tmp6 = dataptr[1] - dataptr[6];
  174357. tmp2 = dataptr[2] + dataptr[5];
  174358. tmp5 = dataptr[2] - dataptr[5];
  174359. tmp3 = dataptr[3] + dataptr[4];
  174360. tmp4 = dataptr[3] - dataptr[4];
  174361. /* Even part */
  174362. tmp10 = tmp0 + tmp3; /* phase 2 */
  174363. tmp13 = tmp0 - tmp3;
  174364. tmp11 = tmp1 + tmp2;
  174365. tmp12 = tmp1 - tmp2;
  174366. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174367. dataptr[4] = tmp10 - tmp11;
  174368. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174369. dataptr[2] = tmp13 + z1; /* phase 5 */
  174370. dataptr[6] = tmp13 - z1;
  174371. /* Odd part */
  174372. tmp10 = tmp4 + tmp5; /* phase 2 */
  174373. tmp11 = tmp5 + tmp6;
  174374. tmp12 = tmp6 + tmp7;
  174375. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174376. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174377. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174378. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174379. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174380. z11 = tmp7 + z3; /* phase 5 */
  174381. z13 = tmp7 - z3;
  174382. dataptr[5] = z13 + z2; /* phase 6 */
  174383. dataptr[3] = z13 - z2;
  174384. dataptr[1] = z11 + z4;
  174385. dataptr[7] = z11 - z4;
  174386. dataptr += DCTSIZE; /* advance pointer to next row */
  174387. }
  174388. /* Pass 2: process columns. */
  174389. dataptr = data;
  174390. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174391. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174392. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174393. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174394. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174395. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174396. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174397. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174398. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174399. /* Even part */
  174400. tmp10 = tmp0 + tmp3; /* phase 2 */
  174401. tmp13 = tmp0 - tmp3;
  174402. tmp11 = tmp1 + tmp2;
  174403. tmp12 = tmp1 - tmp2;
  174404. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174405. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174406. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174407. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174408. dataptr[DCTSIZE*6] = tmp13 - z1;
  174409. /* Odd part */
  174410. tmp10 = tmp4 + tmp5; /* phase 2 */
  174411. tmp11 = tmp5 + tmp6;
  174412. tmp12 = tmp6 + tmp7;
  174413. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174414. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174415. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174416. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174417. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174418. z11 = tmp7 + z3; /* phase 5 */
  174419. z13 = tmp7 - z3;
  174420. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174421. dataptr[DCTSIZE*3] = z13 - z2;
  174422. dataptr[DCTSIZE*1] = z11 + z4;
  174423. dataptr[DCTSIZE*7] = z11 - z4;
  174424. dataptr++; /* advance pointer to next column */
  174425. }
  174426. }
  174427. #endif /* DCT_IFAST_SUPPORTED */
  174428. /*** End of inlined file: jfdctfst.c ***/
  174429. #undef FIX_0_541196100
  174430. /*** Start of inlined file: jidctflt.c ***/
  174431. #define JPEG_INTERNALS
  174432. #ifdef DCT_FLOAT_SUPPORTED
  174433. /*
  174434. * This module is specialized to the case DCTSIZE = 8.
  174435. */
  174436. #if DCTSIZE != 8
  174437. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174438. #endif
  174439. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174440. * entry; produce a float result.
  174441. */
  174442. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174443. /*
  174444. * Perform dequantization and inverse DCT on one block of coefficients.
  174445. */
  174446. GLOBAL(void)
  174447. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174448. JCOEFPTR coef_block,
  174449. JSAMPARRAY output_buf, JDIMENSION output_col)
  174450. {
  174451. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174452. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174453. FAST_FLOAT z5, z10, z11, z12, z13;
  174454. JCOEFPTR inptr;
  174455. FLOAT_MULT_TYPE * quantptr;
  174456. FAST_FLOAT * wsptr;
  174457. JSAMPROW outptr;
  174458. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174459. int ctr;
  174460. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174461. SHIFT_TEMPS
  174462. /* Pass 1: process columns from input, store into work array. */
  174463. inptr = coef_block;
  174464. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174465. wsptr = workspace;
  174466. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174467. /* Due to quantization, we will usually find that many of the input
  174468. * coefficients are zero, especially the AC terms. We can exploit this
  174469. * by short-circuiting the IDCT calculation for any column in which all
  174470. * the AC terms are zero. In that case each output is equal to the
  174471. * DC coefficient (with scale factor as needed).
  174472. * With typical images and quantization tables, half or more of the
  174473. * column DCT calculations can be simplified this way.
  174474. */
  174475. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174476. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174477. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174478. inptr[DCTSIZE*7] == 0) {
  174479. /* AC terms all zero */
  174480. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174481. wsptr[DCTSIZE*0] = dcval;
  174482. wsptr[DCTSIZE*1] = dcval;
  174483. wsptr[DCTSIZE*2] = dcval;
  174484. wsptr[DCTSIZE*3] = dcval;
  174485. wsptr[DCTSIZE*4] = dcval;
  174486. wsptr[DCTSIZE*5] = dcval;
  174487. wsptr[DCTSIZE*6] = dcval;
  174488. wsptr[DCTSIZE*7] = dcval;
  174489. inptr++; /* advance pointers to next column */
  174490. quantptr++;
  174491. wsptr++;
  174492. continue;
  174493. }
  174494. /* Even part */
  174495. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174496. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174497. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174498. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174499. tmp10 = tmp0 + tmp2; /* phase 3 */
  174500. tmp11 = tmp0 - tmp2;
  174501. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174502. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  174503. tmp0 = tmp10 + tmp13; /* phase 2 */
  174504. tmp3 = tmp10 - tmp13;
  174505. tmp1 = tmp11 + tmp12;
  174506. tmp2 = tmp11 - tmp12;
  174507. /* Odd part */
  174508. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174509. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174510. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174511. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174512. z13 = tmp6 + tmp5; /* phase 6 */
  174513. z10 = tmp6 - tmp5;
  174514. z11 = tmp4 + tmp7;
  174515. z12 = tmp4 - tmp7;
  174516. tmp7 = z11 + z13; /* phase 5 */
  174517. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  174518. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174519. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174520. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174521. tmp6 = tmp12 - tmp7; /* phase 2 */
  174522. tmp5 = tmp11 - tmp6;
  174523. tmp4 = tmp10 + tmp5;
  174524. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  174525. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  174526. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  174527. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  174528. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  174529. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  174530. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  174531. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  174532. inptr++; /* advance pointers to next column */
  174533. quantptr++;
  174534. wsptr++;
  174535. }
  174536. /* Pass 2: process rows from work array, store into output array. */
  174537. /* Note that we must descale the results by a factor of 8 == 2**3. */
  174538. wsptr = workspace;
  174539. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174540. outptr = output_buf[ctr] + output_col;
  174541. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174542. * However, the column calculation has created many nonzero AC terms, so
  174543. * the simplification applies less often (typically 5% to 10% of the time).
  174544. * And testing floats for zero is relatively expensive, so we don't bother.
  174545. */
  174546. /* Even part */
  174547. tmp10 = wsptr[0] + wsptr[4];
  174548. tmp11 = wsptr[0] - wsptr[4];
  174549. tmp13 = wsptr[2] + wsptr[6];
  174550. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  174551. tmp0 = tmp10 + tmp13;
  174552. tmp3 = tmp10 - tmp13;
  174553. tmp1 = tmp11 + tmp12;
  174554. tmp2 = tmp11 - tmp12;
  174555. /* Odd part */
  174556. z13 = wsptr[5] + wsptr[3];
  174557. z10 = wsptr[5] - wsptr[3];
  174558. z11 = wsptr[1] + wsptr[7];
  174559. z12 = wsptr[1] - wsptr[7];
  174560. tmp7 = z11 + z13;
  174561. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  174562. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174563. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174564. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174565. tmp6 = tmp12 - tmp7;
  174566. tmp5 = tmp11 - tmp6;
  174567. tmp4 = tmp10 + tmp5;
  174568. /* Final output stage: scale down by a factor of 8 and range-limit */
  174569. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  174570. & RANGE_MASK];
  174571. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  174572. & RANGE_MASK];
  174573. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  174574. & RANGE_MASK];
  174575. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  174576. & RANGE_MASK];
  174577. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  174578. & RANGE_MASK];
  174579. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  174580. & RANGE_MASK];
  174581. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  174582. & RANGE_MASK];
  174583. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  174584. & RANGE_MASK];
  174585. wsptr += DCTSIZE; /* advance pointer to next row */
  174586. }
  174587. }
  174588. #endif /* DCT_FLOAT_SUPPORTED */
  174589. /*** End of inlined file: jidctflt.c ***/
  174590. #undef CONST_BITS
  174591. #undef FIX_1_847759065
  174592. #undef MULTIPLY
  174593. #undef DEQUANTIZE
  174594. #undef DESCALE
  174595. /*** Start of inlined file: jidctfst.c ***/
  174596. #define JPEG_INTERNALS
  174597. #ifdef DCT_IFAST_SUPPORTED
  174598. /*
  174599. * This module is specialized to the case DCTSIZE = 8.
  174600. */
  174601. #if DCTSIZE != 8
  174602. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174603. #endif
  174604. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174605. * see jidctint.c for more details. However, we choose to descale
  174606. * (right shift) multiplication products as soon as they are formed,
  174607. * rather than carrying additional fractional bits into subsequent additions.
  174608. * This compromises accuracy slightly, but it lets us save a few shifts.
  174609. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174610. * everywhere except in the multiplications proper; this saves a good deal
  174611. * of work on 16-bit-int machines.
  174612. *
  174613. * The dequantized coefficients are not integers because the AA&N scaling
  174614. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  174615. * so that the first and second IDCT rounds have the same input scaling.
  174616. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  174617. * avoid a descaling shift; this compromises accuracy rather drastically
  174618. * for small quantization table entries, but it saves a lot of shifts.
  174619. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  174620. * so we use a much larger scaling factor to preserve accuracy.
  174621. *
  174622. * A final compromise is to represent the multiplicative constants to only
  174623. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174624. * machines, and may also reduce the cost of multiplication (since there
  174625. * are fewer one-bits in the constants).
  174626. */
  174627. #if BITS_IN_JSAMPLE == 8
  174628. #define CONST_BITS 8
  174629. #define PASS1_BITS 2
  174630. #else
  174631. #define CONST_BITS 8
  174632. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174633. #endif
  174634. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174635. * causing a lot of useless floating-point operations at run time.
  174636. * To get around this we use the following pre-calculated constants.
  174637. * If you change CONST_BITS you may want to add appropriate values.
  174638. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174639. */
  174640. #if CONST_BITS == 8
  174641. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  174642. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  174643. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  174644. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  174645. #else
  174646. #define FIX_1_082392200 FIX(1.082392200)
  174647. #define FIX_1_414213562 FIX(1.414213562)
  174648. #define FIX_1_847759065 FIX(1.847759065)
  174649. #define FIX_2_613125930 FIX(2.613125930)
  174650. #endif
  174651. /* We can gain a little more speed, with a further compromise in accuracy,
  174652. * by omitting the addition in a descaling shift. This yields an incorrectly
  174653. * rounded result half the time...
  174654. */
  174655. #ifndef USE_ACCURATE_ROUNDING
  174656. #undef DESCALE
  174657. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174658. #endif
  174659. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174660. * descale to yield a DCTELEM result.
  174661. */
  174662. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174663. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174664. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  174665. * multiplication will do. For 12-bit data, the multiplier table is
  174666. * declared INT32, so a 32-bit multiply will be used.
  174667. */
  174668. #if BITS_IN_JSAMPLE == 8
  174669. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  174670. #else
  174671. #define DEQUANTIZE(coef,quantval) \
  174672. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  174673. #endif
  174674. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  174675. * We assume that int right shift is unsigned if INT32 right shift is.
  174676. */
  174677. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  174678. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  174679. #if BITS_IN_JSAMPLE == 8
  174680. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  174681. #else
  174682. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  174683. #endif
  174684. #define IRIGHT_SHIFT(x,shft) \
  174685. ((ishift_temp = (x)) < 0 ? \
  174686. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  174687. (ishift_temp >> (shft)))
  174688. #else
  174689. #define ISHIFT_TEMPS
  174690. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  174691. #endif
  174692. #ifdef USE_ACCURATE_ROUNDING
  174693. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  174694. #else
  174695. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  174696. #endif
  174697. /*
  174698. * Perform dequantization and inverse DCT on one block of coefficients.
  174699. */
  174700. GLOBAL(void)
  174701. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174702. JCOEFPTR coef_block,
  174703. JSAMPARRAY output_buf, JDIMENSION output_col)
  174704. {
  174705. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174706. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174707. DCTELEM z5, z10, z11, z12, z13;
  174708. JCOEFPTR inptr;
  174709. IFAST_MULT_TYPE * quantptr;
  174710. int * wsptr;
  174711. JSAMPROW outptr;
  174712. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174713. int ctr;
  174714. int workspace[DCTSIZE2]; /* buffers data between passes */
  174715. SHIFT_TEMPS /* for DESCALE */
  174716. ISHIFT_TEMPS /* for IDESCALE */
  174717. /* Pass 1: process columns from input, store into work array. */
  174718. inptr = coef_block;
  174719. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  174720. wsptr = workspace;
  174721. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174722. /* Due to quantization, we will usually find that many of the input
  174723. * coefficients are zero, especially the AC terms. We can exploit this
  174724. * by short-circuiting the IDCT calculation for any column in which all
  174725. * the AC terms are zero. In that case each output is equal to the
  174726. * DC coefficient (with scale factor as needed).
  174727. * With typical images and quantization tables, half or more of the
  174728. * column DCT calculations can be simplified this way.
  174729. */
  174730. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174731. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174732. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174733. inptr[DCTSIZE*7] == 0) {
  174734. /* AC terms all zero */
  174735. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174736. wsptr[DCTSIZE*0] = dcval;
  174737. wsptr[DCTSIZE*1] = dcval;
  174738. wsptr[DCTSIZE*2] = dcval;
  174739. wsptr[DCTSIZE*3] = dcval;
  174740. wsptr[DCTSIZE*4] = dcval;
  174741. wsptr[DCTSIZE*5] = dcval;
  174742. wsptr[DCTSIZE*6] = dcval;
  174743. wsptr[DCTSIZE*7] = dcval;
  174744. inptr++; /* advance pointers to next column */
  174745. quantptr++;
  174746. wsptr++;
  174747. continue;
  174748. }
  174749. /* Even part */
  174750. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174751. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174752. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174753. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174754. tmp10 = tmp0 + tmp2; /* phase 3 */
  174755. tmp11 = tmp0 - tmp2;
  174756. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174757. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  174758. tmp0 = tmp10 + tmp13; /* phase 2 */
  174759. tmp3 = tmp10 - tmp13;
  174760. tmp1 = tmp11 + tmp12;
  174761. tmp2 = tmp11 - tmp12;
  174762. /* Odd part */
  174763. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174764. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174765. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174766. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174767. z13 = tmp6 + tmp5; /* phase 6 */
  174768. z10 = tmp6 - tmp5;
  174769. z11 = tmp4 + tmp7;
  174770. z12 = tmp4 - tmp7;
  174771. tmp7 = z11 + z13; /* phase 5 */
  174772. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174773. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174774. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174775. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174776. tmp6 = tmp12 - tmp7; /* phase 2 */
  174777. tmp5 = tmp11 - tmp6;
  174778. tmp4 = tmp10 + tmp5;
  174779. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  174780. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  174781. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  174782. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  174783. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  174784. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  174785. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  174786. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  174787. inptr++; /* advance pointers to next column */
  174788. quantptr++;
  174789. wsptr++;
  174790. }
  174791. /* Pass 2: process rows from work array, store into output array. */
  174792. /* Note that we must descale the results by a factor of 8 == 2**3, */
  174793. /* and also undo the PASS1_BITS scaling. */
  174794. wsptr = workspace;
  174795. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174796. outptr = output_buf[ctr] + output_col;
  174797. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174798. * However, the column calculation has created many nonzero AC terms, so
  174799. * the simplification applies less often (typically 5% to 10% of the time).
  174800. * On machines with very fast multiplication, it's possible that the
  174801. * test takes more time than it's worth. In that case this section
  174802. * may be commented out.
  174803. */
  174804. #ifndef NO_ZERO_ROW_TEST
  174805. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  174806. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174807. /* AC terms all zero */
  174808. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  174809. & RANGE_MASK];
  174810. outptr[0] = dcval;
  174811. outptr[1] = dcval;
  174812. outptr[2] = dcval;
  174813. outptr[3] = dcval;
  174814. outptr[4] = dcval;
  174815. outptr[5] = dcval;
  174816. outptr[6] = dcval;
  174817. outptr[7] = dcval;
  174818. wsptr += DCTSIZE; /* advance pointer to next row */
  174819. continue;
  174820. }
  174821. #endif
  174822. /* Even part */
  174823. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  174824. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  174825. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  174826. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  174827. - tmp13;
  174828. tmp0 = tmp10 + tmp13;
  174829. tmp3 = tmp10 - tmp13;
  174830. tmp1 = tmp11 + tmp12;
  174831. tmp2 = tmp11 - tmp12;
  174832. /* Odd part */
  174833. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  174834. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  174835. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  174836. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  174837. tmp7 = z11 + z13; /* phase 5 */
  174838. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174839. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174840. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174841. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174842. tmp6 = tmp12 - tmp7; /* phase 2 */
  174843. tmp5 = tmp11 - tmp6;
  174844. tmp4 = tmp10 + tmp5;
  174845. /* Final output stage: scale down by a factor of 8 and range-limit */
  174846. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  174847. & RANGE_MASK];
  174848. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  174849. & RANGE_MASK];
  174850. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  174851. & RANGE_MASK];
  174852. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  174853. & RANGE_MASK];
  174854. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  174855. & RANGE_MASK];
  174856. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  174857. & RANGE_MASK];
  174858. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  174859. & RANGE_MASK];
  174860. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  174861. & RANGE_MASK];
  174862. wsptr += DCTSIZE; /* advance pointer to next row */
  174863. }
  174864. }
  174865. #endif /* DCT_IFAST_SUPPORTED */
  174866. /*** End of inlined file: jidctfst.c ***/
  174867. #undef CONST_BITS
  174868. #undef FIX_1_847759065
  174869. #undef MULTIPLY
  174870. #undef DEQUANTIZE
  174871. /*** Start of inlined file: jidctint.c ***/
  174872. #define JPEG_INTERNALS
  174873. #ifdef DCT_ISLOW_SUPPORTED
  174874. /*
  174875. * This module is specialized to the case DCTSIZE = 8.
  174876. */
  174877. #if DCTSIZE != 8
  174878. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174879. #endif
  174880. /*
  174881. * The poop on this scaling stuff is as follows:
  174882. *
  174883. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  174884. * larger than the true IDCT outputs. The final outputs are therefore
  174885. * a factor of N larger than desired; since N=8 this can be cured by
  174886. * a simple right shift at the end of the algorithm. The advantage of
  174887. * this arrangement is that we save two multiplications per 1-D IDCT,
  174888. * because the y0 and y4 inputs need not be divided by sqrt(N).
  174889. *
  174890. * We have to do addition and subtraction of the integer inputs, which
  174891. * is no problem, and multiplication by fractional constants, which is
  174892. * a problem to do in integer arithmetic. We multiply all the constants
  174893. * by CONST_SCALE and convert them to integer constants (thus retaining
  174894. * CONST_BITS bits of precision in the constants). After doing a
  174895. * multiplication we have to divide the product by CONST_SCALE, with proper
  174896. * rounding, to produce the correct output. This division can be done
  174897. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174898. * as long as possible so that partial sums can be added together with
  174899. * full fractional precision.
  174900. *
  174901. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174902. * they are represented to better-than-integral precision. These outputs
  174903. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174904. * with the recommended scaling. (To scale up 12-bit sample data further, an
  174905. * intermediate INT32 array would be needed.)
  174906. *
  174907. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174908. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174909. * shows that the values given below are the most effective.
  174910. */
  174911. #if BITS_IN_JSAMPLE == 8
  174912. #define CONST_BITS 13
  174913. #define PASS1_BITS 2
  174914. #else
  174915. #define CONST_BITS 13
  174916. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174917. #endif
  174918. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174919. * causing a lot of useless floating-point operations at run time.
  174920. * To get around this we use the following pre-calculated constants.
  174921. * If you change CONST_BITS you may want to add appropriate values.
  174922. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174923. */
  174924. #if CONST_BITS == 13
  174925. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174926. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174927. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174928. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174929. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174930. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174931. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174932. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174933. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174934. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174935. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174936. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174937. #else
  174938. #define FIX_0_298631336 FIX(0.298631336)
  174939. #define FIX_0_390180644 FIX(0.390180644)
  174940. #define FIX_0_541196100 FIX(0.541196100)
  174941. #define FIX_0_765366865 FIX(0.765366865)
  174942. #define FIX_0_899976223 FIX(0.899976223)
  174943. #define FIX_1_175875602 FIX(1.175875602)
  174944. #define FIX_1_501321110 FIX(1.501321110)
  174945. #define FIX_1_847759065 FIX(1.847759065)
  174946. #define FIX_1_961570560 FIX(1.961570560)
  174947. #define FIX_2_053119869 FIX(2.053119869)
  174948. #define FIX_2_562915447 FIX(2.562915447)
  174949. #define FIX_3_072711026 FIX(3.072711026)
  174950. #endif
  174951. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174952. * For 8-bit samples with the recommended scaling, all the variable
  174953. * and constant values involved are no more than 16 bits wide, so a
  174954. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174955. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174956. */
  174957. #if BITS_IN_JSAMPLE == 8
  174958. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174959. #else
  174960. #define MULTIPLY(var,const) ((var) * (const))
  174961. #endif
  174962. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174963. * entry; produce an int result. In this module, both inputs and result
  174964. * are 16 bits or less, so either int or short multiply will work.
  174965. */
  174966. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  174967. /*
  174968. * Perform dequantization and inverse DCT on one block of coefficients.
  174969. */
  174970. GLOBAL(void)
  174971. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174972. JCOEFPTR coef_block,
  174973. JSAMPARRAY output_buf, JDIMENSION output_col)
  174974. {
  174975. INT32 tmp0, tmp1, tmp2, tmp3;
  174976. INT32 tmp10, tmp11, tmp12, tmp13;
  174977. INT32 z1, z2, z3, z4, z5;
  174978. JCOEFPTR inptr;
  174979. ISLOW_MULT_TYPE * quantptr;
  174980. int * wsptr;
  174981. JSAMPROW outptr;
  174982. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174983. int ctr;
  174984. int workspace[DCTSIZE2]; /* buffers data between passes */
  174985. SHIFT_TEMPS
  174986. /* Pass 1: process columns from input, store into work array. */
  174987. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  174988. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174989. inptr = coef_block;
  174990. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174991. wsptr = workspace;
  174992. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174993. /* Due to quantization, we will usually find that many of the input
  174994. * coefficients are zero, especially the AC terms. We can exploit this
  174995. * by short-circuiting the IDCT calculation for any column in which all
  174996. * the AC terms are zero. In that case each output is equal to the
  174997. * DC coefficient (with scale factor as needed).
  174998. * With typical images and quantization tables, half or more of the
  174999. * column DCT calculations can be simplified this way.
  175000. */
  175001. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175002. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175003. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175004. inptr[DCTSIZE*7] == 0) {
  175005. /* AC terms all zero */
  175006. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175007. wsptr[DCTSIZE*0] = dcval;
  175008. wsptr[DCTSIZE*1] = dcval;
  175009. wsptr[DCTSIZE*2] = dcval;
  175010. wsptr[DCTSIZE*3] = dcval;
  175011. wsptr[DCTSIZE*4] = dcval;
  175012. wsptr[DCTSIZE*5] = dcval;
  175013. wsptr[DCTSIZE*6] = dcval;
  175014. wsptr[DCTSIZE*7] = dcval;
  175015. inptr++; /* advance pointers to next column */
  175016. quantptr++;
  175017. wsptr++;
  175018. continue;
  175019. }
  175020. /* Even part: reverse the even part of the forward DCT. */
  175021. /* The rotator is sqrt(2)*c(-6). */
  175022. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175023. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175024. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175025. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175026. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175027. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175028. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175029. tmp0 = (z2 + z3) << CONST_BITS;
  175030. tmp1 = (z2 - z3) << CONST_BITS;
  175031. tmp10 = tmp0 + tmp3;
  175032. tmp13 = tmp0 - tmp3;
  175033. tmp11 = tmp1 + tmp2;
  175034. tmp12 = tmp1 - tmp2;
  175035. /* Odd part per figure 8; the matrix is unitary and hence its
  175036. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175037. */
  175038. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175039. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175040. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175041. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175042. z1 = tmp0 + tmp3;
  175043. z2 = tmp1 + tmp2;
  175044. z3 = tmp0 + tmp2;
  175045. z4 = tmp1 + tmp3;
  175046. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175047. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175048. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175049. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175050. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175051. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175052. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175053. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175054. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175055. z3 += z5;
  175056. z4 += z5;
  175057. tmp0 += z1 + z3;
  175058. tmp1 += z2 + z4;
  175059. tmp2 += z2 + z3;
  175060. tmp3 += z1 + z4;
  175061. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175062. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175063. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175064. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175065. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175066. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175067. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175068. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175069. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175070. inptr++; /* advance pointers to next column */
  175071. quantptr++;
  175072. wsptr++;
  175073. }
  175074. /* Pass 2: process rows from work array, store into output array. */
  175075. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175076. /* and also undo the PASS1_BITS scaling. */
  175077. wsptr = workspace;
  175078. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175079. outptr = output_buf[ctr] + output_col;
  175080. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175081. * However, the column calculation has created many nonzero AC terms, so
  175082. * the simplification applies less often (typically 5% to 10% of the time).
  175083. * On machines with very fast multiplication, it's possible that the
  175084. * test takes more time than it's worth. In that case this section
  175085. * may be commented out.
  175086. */
  175087. #ifndef NO_ZERO_ROW_TEST
  175088. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175089. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175090. /* AC terms all zero */
  175091. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175092. & RANGE_MASK];
  175093. outptr[0] = dcval;
  175094. outptr[1] = dcval;
  175095. outptr[2] = dcval;
  175096. outptr[3] = dcval;
  175097. outptr[4] = dcval;
  175098. outptr[5] = dcval;
  175099. outptr[6] = dcval;
  175100. outptr[7] = dcval;
  175101. wsptr += DCTSIZE; /* advance pointer to next row */
  175102. continue;
  175103. }
  175104. #endif
  175105. /* Even part: reverse the even part of the forward DCT. */
  175106. /* The rotator is sqrt(2)*c(-6). */
  175107. z2 = (INT32) wsptr[2];
  175108. z3 = (INT32) wsptr[6];
  175109. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175110. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175111. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175112. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175113. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175114. tmp10 = tmp0 + tmp3;
  175115. tmp13 = tmp0 - tmp3;
  175116. tmp11 = tmp1 + tmp2;
  175117. tmp12 = tmp1 - tmp2;
  175118. /* Odd part per figure 8; the matrix is unitary and hence its
  175119. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175120. */
  175121. tmp0 = (INT32) wsptr[7];
  175122. tmp1 = (INT32) wsptr[5];
  175123. tmp2 = (INT32) wsptr[3];
  175124. tmp3 = (INT32) wsptr[1];
  175125. z1 = tmp0 + tmp3;
  175126. z2 = tmp1 + tmp2;
  175127. z3 = tmp0 + tmp2;
  175128. z4 = tmp1 + tmp3;
  175129. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175130. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175131. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175132. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175133. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175134. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175135. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175136. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175137. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175138. z3 += z5;
  175139. z4 += z5;
  175140. tmp0 += z1 + z3;
  175141. tmp1 += z2 + z4;
  175142. tmp2 += z2 + z3;
  175143. tmp3 += z1 + z4;
  175144. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175145. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175146. CONST_BITS+PASS1_BITS+3)
  175147. & RANGE_MASK];
  175148. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175149. CONST_BITS+PASS1_BITS+3)
  175150. & RANGE_MASK];
  175151. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175152. CONST_BITS+PASS1_BITS+3)
  175153. & RANGE_MASK];
  175154. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175155. CONST_BITS+PASS1_BITS+3)
  175156. & RANGE_MASK];
  175157. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175158. CONST_BITS+PASS1_BITS+3)
  175159. & RANGE_MASK];
  175160. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175161. CONST_BITS+PASS1_BITS+3)
  175162. & RANGE_MASK];
  175163. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175164. CONST_BITS+PASS1_BITS+3)
  175165. & RANGE_MASK];
  175166. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175167. CONST_BITS+PASS1_BITS+3)
  175168. & RANGE_MASK];
  175169. wsptr += DCTSIZE; /* advance pointer to next row */
  175170. }
  175171. }
  175172. #endif /* DCT_ISLOW_SUPPORTED */
  175173. /*** End of inlined file: jidctint.c ***/
  175174. /*** Start of inlined file: jidctred.c ***/
  175175. #define JPEG_INTERNALS
  175176. #ifdef IDCT_SCALING_SUPPORTED
  175177. /*
  175178. * This module is specialized to the case DCTSIZE = 8.
  175179. */
  175180. #if DCTSIZE != 8
  175181. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175182. #endif
  175183. /* Scaling is the same as in jidctint.c. */
  175184. #if BITS_IN_JSAMPLE == 8
  175185. #define CONST_BITS 13
  175186. #define PASS1_BITS 2
  175187. #else
  175188. #define CONST_BITS 13
  175189. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175190. #endif
  175191. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175192. * causing a lot of useless floating-point operations at run time.
  175193. * To get around this we use the following pre-calculated constants.
  175194. * If you change CONST_BITS you may want to add appropriate values.
  175195. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175196. */
  175197. #if CONST_BITS == 13
  175198. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175199. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175200. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175201. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175202. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175203. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175204. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175205. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175206. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175207. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175208. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175209. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175210. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175211. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175212. #else
  175213. #define FIX_0_211164243 FIX(0.211164243)
  175214. #define FIX_0_509795579 FIX(0.509795579)
  175215. #define FIX_0_601344887 FIX(0.601344887)
  175216. #define FIX_0_720959822 FIX(0.720959822)
  175217. #define FIX_0_765366865 FIX(0.765366865)
  175218. #define FIX_0_850430095 FIX(0.850430095)
  175219. #define FIX_0_899976223 FIX(0.899976223)
  175220. #define FIX_1_061594337 FIX(1.061594337)
  175221. #define FIX_1_272758580 FIX(1.272758580)
  175222. #define FIX_1_451774981 FIX(1.451774981)
  175223. #define FIX_1_847759065 FIX(1.847759065)
  175224. #define FIX_2_172734803 FIX(2.172734803)
  175225. #define FIX_2_562915447 FIX(2.562915447)
  175226. #define FIX_3_624509785 FIX(3.624509785)
  175227. #endif
  175228. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175229. * For 8-bit samples with the recommended scaling, all the variable
  175230. * and constant values involved are no more than 16 bits wide, so a
  175231. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175232. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175233. */
  175234. #if BITS_IN_JSAMPLE == 8
  175235. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175236. #else
  175237. #define MULTIPLY(var,const) ((var) * (const))
  175238. #endif
  175239. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175240. * entry; produce an int result. In this module, both inputs and result
  175241. * are 16 bits or less, so either int or short multiply will work.
  175242. */
  175243. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175244. /*
  175245. * Perform dequantization and inverse DCT on one block of coefficients,
  175246. * producing a reduced-size 4x4 output block.
  175247. */
  175248. GLOBAL(void)
  175249. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175250. JCOEFPTR coef_block,
  175251. JSAMPARRAY output_buf, JDIMENSION output_col)
  175252. {
  175253. INT32 tmp0, tmp2, tmp10, tmp12;
  175254. INT32 z1, z2, z3, z4;
  175255. JCOEFPTR inptr;
  175256. ISLOW_MULT_TYPE * quantptr;
  175257. int * wsptr;
  175258. JSAMPROW outptr;
  175259. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175260. int ctr;
  175261. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175262. SHIFT_TEMPS
  175263. /* Pass 1: process columns from input, store into work array. */
  175264. inptr = coef_block;
  175265. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175266. wsptr = workspace;
  175267. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175268. /* Don't bother to process column 4, because second pass won't use it */
  175269. if (ctr == DCTSIZE-4)
  175270. continue;
  175271. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175272. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175273. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175274. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175275. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175276. wsptr[DCTSIZE*0] = dcval;
  175277. wsptr[DCTSIZE*1] = dcval;
  175278. wsptr[DCTSIZE*2] = dcval;
  175279. wsptr[DCTSIZE*3] = dcval;
  175280. continue;
  175281. }
  175282. /* Even part */
  175283. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175284. tmp0 <<= (CONST_BITS+1);
  175285. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175286. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175287. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175288. tmp10 = tmp0 + tmp2;
  175289. tmp12 = tmp0 - tmp2;
  175290. /* Odd part */
  175291. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175292. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175293. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175294. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175295. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175296. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175297. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175298. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175299. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175300. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175301. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175302. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175303. /* Final output stage */
  175304. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175305. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175306. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175307. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175308. }
  175309. /* Pass 2: process 4 rows from work array, store into output array. */
  175310. wsptr = workspace;
  175311. for (ctr = 0; ctr < 4; ctr++) {
  175312. outptr = output_buf[ctr] + output_col;
  175313. /* It's not clear whether a zero row test is worthwhile here ... */
  175314. #ifndef NO_ZERO_ROW_TEST
  175315. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175316. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175317. /* AC terms all zero */
  175318. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175319. & RANGE_MASK];
  175320. outptr[0] = dcval;
  175321. outptr[1] = dcval;
  175322. outptr[2] = dcval;
  175323. outptr[3] = dcval;
  175324. wsptr += DCTSIZE; /* advance pointer to next row */
  175325. continue;
  175326. }
  175327. #endif
  175328. /* Even part */
  175329. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175330. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175331. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175332. tmp10 = tmp0 + tmp2;
  175333. tmp12 = tmp0 - tmp2;
  175334. /* Odd part */
  175335. z1 = (INT32) wsptr[7];
  175336. z2 = (INT32) wsptr[5];
  175337. z3 = (INT32) wsptr[3];
  175338. z4 = (INT32) wsptr[1];
  175339. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175340. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175341. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175342. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175343. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175344. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175345. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175346. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175347. /* Final output stage */
  175348. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175349. CONST_BITS+PASS1_BITS+3+1)
  175350. & RANGE_MASK];
  175351. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175352. CONST_BITS+PASS1_BITS+3+1)
  175353. & RANGE_MASK];
  175354. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175355. CONST_BITS+PASS1_BITS+3+1)
  175356. & RANGE_MASK];
  175357. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175358. CONST_BITS+PASS1_BITS+3+1)
  175359. & RANGE_MASK];
  175360. wsptr += DCTSIZE; /* advance pointer to next row */
  175361. }
  175362. }
  175363. /*
  175364. * Perform dequantization and inverse DCT on one block of coefficients,
  175365. * producing a reduced-size 2x2 output block.
  175366. */
  175367. GLOBAL(void)
  175368. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175369. JCOEFPTR coef_block,
  175370. JSAMPARRAY output_buf, JDIMENSION output_col)
  175371. {
  175372. INT32 tmp0, tmp10, z1;
  175373. JCOEFPTR inptr;
  175374. ISLOW_MULT_TYPE * quantptr;
  175375. int * wsptr;
  175376. JSAMPROW outptr;
  175377. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175378. int ctr;
  175379. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175380. SHIFT_TEMPS
  175381. /* Pass 1: process columns from input, store into work array. */
  175382. inptr = coef_block;
  175383. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175384. wsptr = workspace;
  175385. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175386. /* Don't bother to process columns 2,4,6 */
  175387. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175388. continue;
  175389. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175390. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175391. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175392. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175393. wsptr[DCTSIZE*0] = dcval;
  175394. wsptr[DCTSIZE*1] = dcval;
  175395. continue;
  175396. }
  175397. /* Even part */
  175398. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175399. tmp10 = z1 << (CONST_BITS+2);
  175400. /* Odd part */
  175401. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175402. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175403. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175404. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175405. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175406. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175407. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175408. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175409. /* Final output stage */
  175410. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175411. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175412. }
  175413. /* Pass 2: process 2 rows from work array, store into output array. */
  175414. wsptr = workspace;
  175415. for (ctr = 0; ctr < 2; ctr++) {
  175416. outptr = output_buf[ctr] + output_col;
  175417. /* It's not clear whether a zero row test is worthwhile here ... */
  175418. #ifndef NO_ZERO_ROW_TEST
  175419. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175420. /* AC terms all zero */
  175421. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175422. & RANGE_MASK];
  175423. outptr[0] = dcval;
  175424. outptr[1] = dcval;
  175425. wsptr += DCTSIZE; /* advance pointer to next row */
  175426. continue;
  175427. }
  175428. #endif
  175429. /* Even part */
  175430. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175431. /* Odd part */
  175432. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175433. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175434. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175435. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175436. /* Final output stage */
  175437. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175438. CONST_BITS+PASS1_BITS+3+2)
  175439. & RANGE_MASK];
  175440. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175441. CONST_BITS+PASS1_BITS+3+2)
  175442. & RANGE_MASK];
  175443. wsptr += DCTSIZE; /* advance pointer to next row */
  175444. }
  175445. }
  175446. /*
  175447. * Perform dequantization and inverse DCT on one block of coefficients,
  175448. * producing a reduced-size 1x1 output block.
  175449. */
  175450. GLOBAL(void)
  175451. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175452. JCOEFPTR coef_block,
  175453. JSAMPARRAY output_buf, JDIMENSION output_col)
  175454. {
  175455. int dcval;
  175456. ISLOW_MULT_TYPE * quantptr;
  175457. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175458. SHIFT_TEMPS
  175459. /* We hardly need an inverse DCT routine for this: just take the
  175460. * average pixel value, which is one-eighth of the DC coefficient.
  175461. */
  175462. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175463. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175464. dcval = (int) DESCALE((INT32) dcval, 3);
  175465. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175466. }
  175467. #endif /* IDCT_SCALING_SUPPORTED */
  175468. /*** End of inlined file: jidctred.c ***/
  175469. /*** Start of inlined file: jmemmgr.c ***/
  175470. #define JPEG_INTERNALS
  175471. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175472. /*** Start of inlined file: jmemsys.h ***/
  175473. #ifndef __jmemsys_h__
  175474. #define __jmemsys_h__
  175475. /* Short forms of external names for systems with brain-damaged linkers. */
  175476. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175477. #define jpeg_get_small jGetSmall
  175478. #define jpeg_free_small jFreeSmall
  175479. #define jpeg_get_large jGetLarge
  175480. #define jpeg_free_large jFreeLarge
  175481. #define jpeg_mem_available jMemAvail
  175482. #define jpeg_open_backing_store jOpenBackStore
  175483. #define jpeg_mem_init jMemInit
  175484. #define jpeg_mem_term jMemTerm
  175485. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175486. /*
  175487. * These two functions are used to allocate and release small chunks of
  175488. * memory. (Typically the total amount requested through jpeg_get_small is
  175489. * no more than 20K or so; this will be requested in chunks of a few K each.)
  175490. * Behavior should be the same as for the standard library functions malloc
  175491. * and free; in particular, jpeg_get_small must return NULL on failure.
  175492. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  175493. * size of the object being freed, just in case it's needed.
  175494. * On an 80x86 machine using small-data memory model, these manage near heap.
  175495. */
  175496. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  175497. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  175498. size_t sizeofobject));
  175499. /*
  175500. * These two functions are used to allocate and release large chunks of
  175501. * memory (up to the total free space designated by jpeg_mem_available).
  175502. * The interface is the same as above, except that on an 80x86 machine,
  175503. * far pointers are used. On most other machines these are identical to
  175504. * the jpeg_get/free_small routines; but we keep them separate anyway,
  175505. * in case a different allocation strategy is desirable for large chunks.
  175506. */
  175507. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  175508. size_t sizeofobject));
  175509. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  175510. size_t sizeofobject));
  175511. /*
  175512. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  175513. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  175514. * matter, but that case should never come into play). This macro is needed
  175515. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  175516. * On those machines, we expect that jconfig.h will provide a proper value.
  175517. * On machines with 32-bit flat address spaces, any large constant may be used.
  175518. *
  175519. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  175520. * size_t and will be a multiple of sizeof(align_type).
  175521. */
  175522. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  175523. #define MAX_ALLOC_CHUNK 1000000000L
  175524. #endif
  175525. /*
  175526. * This routine computes the total space still available for allocation by
  175527. * jpeg_get_large. If more space than this is needed, backing store will be
  175528. * used. NOTE: any memory already allocated must not be counted.
  175529. *
  175530. * There is a minimum space requirement, corresponding to the minimum
  175531. * feasible buffer sizes; jmemmgr.c will request that much space even if
  175532. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  175533. * all working storage in memory, is also passed in case it is useful.
  175534. * Finally, the total space already allocated is passed. If no better
  175535. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  175536. * is often a suitable calculation.
  175537. *
  175538. * It is OK for jpeg_mem_available to underestimate the space available
  175539. * (that'll just lead to more backing-store access than is really necessary).
  175540. * However, an overestimate will lead to failure. Hence it's wise to subtract
  175541. * a slop factor from the true available space. 5% should be enough.
  175542. *
  175543. * On machines with lots of virtual memory, any large constant may be returned.
  175544. * Conversely, zero may be returned to always use the minimum amount of memory.
  175545. */
  175546. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  175547. long min_bytes_needed,
  175548. long max_bytes_needed,
  175549. long already_allocated));
  175550. /*
  175551. * This structure holds whatever state is needed to access a single
  175552. * backing-store object. The read/write/close method pointers are called
  175553. * by jmemmgr.c to manipulate the backing-store object; all other fields
  175554. * are private to the system-dependent backing store routines.
  175555. */
  175556. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  175557. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  175558. typedef unsigned short XMSH; /* type of extended-memory handles */
  175559. typedef unsigned short EMSH; /* type of expanded-memory handles */
  175560. typedef union {
  175561. short file_handle; /* DOS file handle if it's a temp file */
  175562. XMSH xms_handle; /* handle if it's a chunk of XMS */
  175563. EMSH ems_handle; /* handle if it's a chunk of EMS */
  175564. } handle_union;
  175565. #endif /* USE_MSDOS_MEMMGR */
  175566. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  175567. #include <Files.h>
  175568. #endif /* USE_MAC_MEMMGR */
  175569. //typedef struct backing_store_struct * backing_store_ptr;
  175570. typedef struct backing_store_struct {
  175571. /* Methods for reading/writing/closing this backing-store object */
  175572. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  175573. struct backing_store_struct *info,
  175574. void FAR * buffer_address,
  175575. long file_offset, long byte_count));
  175576. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  175577. struct backing_store_struct *info,
  175578. void FAR * buffer_address,
  175579. long file_offset, long byte_count));
  175580. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  175581. struct backing_store_struct *info));
  175582. /* Private fields for system-dependent backing-store management */
  175583. #ifdef USE_MSDOS_MEMMGR
  175584. /* For the MS-DOS manager (jmemdos.c), we need: */
  175585. handle_union handle; /* reference to backing-store storage object */
  175586. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175587. #else
  175588. #ifdef USE_MAC_MEMMGR
  175589. /* For the Mac manager (jmemmac.c), we need: */
  175590. short temp_file; /* file reference number to temp file */
  175591. FSSpec tempSpec; /* the FSSpec for the temp file */
  175592. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175593. #else
  175594. /* For a typical implementation with temp files, we need: */
  175595. FILE * temp_file; /* stdio reference to temp file */
  175596. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  175597. #endif
  175598. #endif
  175599. } backing_store_info;
  175600. /*
  175601. * Initial opening of a backing-store object. This must fill in the
  175602. * read/write/close pointers in the object. The read/write routines
  175603. * may take an error exit if the specified maximum file size is exceeded.
  175604. * (If jpeg_mem_available always returns a large value, this routine can
  175605. * just take an error exit.)
  175606. */
  175607. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  175608. struct backing_store_struct *info,
  175609. long total_bytes_needed));
  175610. /*
  175611. * These routines take care of any system-dependent initialization and
  175612. * cleanup required. jpeg_mem_init will be called before anything is
  175613. * allocated (and, therefore, nothing in cinfo is of use except the error
  175614. * manager pointer). It should return a suitable default value for
  175615. * max_memory_to_use; this may subsequently be overridden by the surrounding
  175616. * application. (Note that max_memory_to_use is only important if
  175617. * jpeg_mem_available chooses to consult it ... no one else will.)
  175618. * jpeg_mem_term may assume that all requested memory has been freed and that
  175619. * all opened backing-store objects have been closed.
  175620. */
  175621. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  175622. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  175623. #endif
  175624. /*** End of inlined file: jmemsys.h ***/
  175625. /* import the system-dependent declarations */
  175626. #ifndef NO_GETENV
  175627. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  175628. extern char * getenv JPP((const char * name));
  175629. #endif
  175630. #endif
  175631. /*
  175632. * Some important notes:
  175633. * The allocation routines provided here must never return NULL.
  175634. * They should exit to error_exit if unsuccessful.
  175635. *
  175636. * It's not a good idea to try to merge the sarray and barray routines,
  175637. * even though they are textually almost the same, because samples are
  175638. * usually stored as bytes while coefficients are shorts or ints. Thus,
  175639. * in machines where byte pointers have a different representation from
  175640. * word pointers, the resulting machine code could not be the same.
  175641. */
  175642. /*
  175643. * Many machines require storage alignment: longs must start on 4-byte
  175644. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  175645. * always returns pointers that are multiples of the worst-case alignment
  175646. * requirement, and we had better do so too.
  175647. * There isn't any really portable way to determine the worst-case alignment
  175648. * requirement. This module assumes that the alignment requirement is
  175649. * multiples of sizeof(ALIGN_TYPE).
  175650. * By default, we define ALIGN_TYPE as double. This is necessary on some
  175651. * workstations (where doubles really do need 8-byte alignment) and will work
  175652. * fine on nearly everything. If your machine has lesser alignment needs,
  175653. * you can save a few bytes by making ALIGN_TYPE smaller.
  175654. * The only place I know of where this will NOT work is certain Macintosh
  175655. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  175656. * Doing 10-byte alignment is counterproductive because longwords won't be
  175657. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  175658. * such a compiler.
  175659. */
  175660. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  175661. #define ALIGN_TYPE double
  175662. #endif
  175663. /*
  175664. * We allocate objects from "pools", where each pool is gotten with a single
  175665. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  175666. * overhead within a pool, except for alignment padding. Each pool has a
  175667. * header with a link to the next pool of the same class.
  175668. * Small and large pool headers are identical except that the latter's
  175669. * link pointer must be FAR on 80x86 machines.
  175670. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  175671. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  175672. * of the alignment requirement of ALIGN_TYPE.
  175673. */
  175674. typedef union small_pool_struct * small_pool_ptr;
  175675. typedef union small_pool_struct {
  175676. struct {
  175677. small_pool_ptr next; /* next in list of pools */
  175678. size_t bytes_used; /* how many bytes already used within pool */
  175679. size_t bytes_left; /* bytes still available in this pool */
  175680. } hdr;
  175681. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175682. } small_pool_hdr;
  175683. typedef union large_pool_struct FAR * large_pool_ptr;
  175684. typedef union large_pool_struct {
  175685. struct {
  175686. large_pool_ptr next; /* next in list of pools */
  175687. size_t bytes_used; /* how many bytes already used within pool */
  175688. size_t bytes_left; /* bytes still available in this pool */
  175689. } hdr;
  175690. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175691. } large_pool_hdr;
  175692. /*
  175693. * Here is the full definition of a memory manager object.
  175694. */
  175695. typedef struct {
  175696. struct jpeg_memory_mgr pub; /* public fields */
  175697. /* Each pool identifier (lifetime class) names a linked list of pools. */
  175698. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  175699. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  175700. /* Since we only have one lifetime class of virtual arrays, only one
  175701. * linked list is necessary (for each datatype). Note that the virtual
  175702. * array control blocks being linked together are actually stored somewhere
  175703. * in the small-pool list.
  175704. */
  175705. jvirt_sarray_ptr virt_sarray_list;
  175706. jvirt_barray_ptr virt_barray_list;
  175707. /* This counts total space obtained from jpeg_get_small/large */
  175708. long total_space_allocated;
  175709. /* alloc_sarray and alloc_barray set this value for use by virtual
  175710. * array routines.
  175711. */
  175712. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  175713. } my_memory_mgr;
  175714. typedef my_memory_mgr * my_mem_ptr;
  175715. /*
  175716. * The control blocks for virtual arrays.
  175717. * Note that these blocks are allocated in the "small" pool area.
  175718. * System-dependent info for the associated backing store (if any) is hidden
  175719. * inside the backing_store_info struct.
  175720. */
  175721. struct jvirt_sarray_control {
  175722. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  175723. JDIMENSION rows_in_array; /* total virtual array height */
  175724. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  175725. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  175726. JDIMENSION rows_in_mem; /* height of memory buffer */
  175727. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175728. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175729. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175730. boolean pre_zero; /* pre-zero mode requested? */
  175731. boolean dirty; /* do current buffer contents need written? */
  175732. boolean b_s_open; /* is backing-store data valid? */
  175733. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  175734. backing_store_info b_s_info; /* System-dependent control info */
  175735. };
  175736. struct jvirt_barray_control {
  175737. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  175738. JDIMENSION rows_in_array; /* total virtual array height */
  175739. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  175740. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  175741. JDIMENSION rows_in_mem; /* height of memory buffer */
  175742. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175743. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175744. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175745. boolean pre_zero; /* pre-zero mode requested? */
  175746. boolean dirty; /* do current buffer contents need written? */
  175747. boolean b_s_open; /* is backing-store data valid? */
  175748. jvirt_barray_ptr next; /* link to next virtual barray control block */
  175749. backing_store_info b_s_info; /* System-dependent control info */
  175750. };
  175751. #ifdef MEM_STATS /* optional extra stuff for statistics */
  175752. LOCAL(void)
  175753. print_mem_stats (j_common_ptr cinfo, int pool_id)
  175754. {
  175755. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175756. small_pool_ptr shdr_ptr;
  175757. large_pool_ptr lhdr_ptr;
  175758. /* Since this is only a debugging stub, we can cheat a little by using
  175759. * fprintf directly rather than going through the trace message code.
  175760. * This is helpful because message parm array can't handle longs.
  175761. */
  175762. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  175763. pool_id, mem->total_space_allocated);
  175764. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  175765. lhdr_ptr = lhdr_ptr->hdr.next) {
  175766. fprintf(stderr, " Large chunk used %ld\n",
  175767. (long) lhdr_ptr->hdr.bytes_used);
  175768. }
  175769. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  175770. shdr_ptr = shdr_ptr->hdr.next) {
  175771. fprintf(stderr, " Small chunk used %ld free %ld\n",
  175772. (long) shdr_ptr->hdr.bytes_used,
  175773. (long) shdr_ptr->hdr.bytes_left);
  175774. }
  175775. }
  175776. #endif /* MEM_STATS */
  175777. LOCAL(void)
  175778. out_of_memory (j_common_ptr cinfo, int which)
  175779. /* Report an out-of-memory error and stop execution */
  175780. /* If we compiled MEM_STATS support, report alloc requests before dying */
  175781. {
  175782. #ifdef MEM_STATS
  175783. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  175784. #endif
  175785. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  175786. }
  175787. /*
  175788. * Allocation of "small" objects.
  175789. *
  175790. * For these, we use pooled storage. When a new pool must be created,
  175791. * we try to get enough space for the current request plus a "slop" factor,
  175792. * where the slop will be the amount of leftover space in the new pool.
  175793. * The speed vs. space tradeoff is largely determined by the slop values.
  175794. * A different slop value is provided for each pool class (lifetime),
  175795. * and we also distinguish the first pool of a class from later ones.
  175796. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  175797. * machines, but may be too small if longs are 64 bits or more.
  175798. */
  175799. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  175800. {
  175801. 1600, /* first PERMANENT pool */
  175802. 16000 /* first IMAGE pool */
  175803. };
  175804. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  175805. {
  175806. 0, /* additional PERMANENT pools */
  175807. 5000 /* additional IMAGE pools */
  175808. };
  175809. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  175810. METHODDEF(void *)
  175811. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175812. /* Allocate a "small" object */
  175813. {
  175814. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175815. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  175816. char * data_ptr;
  175817. size_t odd_bytes, min_request, slop;
  175818. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175819. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  175820. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  175821. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175822. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175823. if (odd_bytes > 0)
  175824. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175825. /* See if space is available in any existing pool */
  175826. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175827. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175828. prev_hdr_ptr = NULL;
  175829. hdr_ptr = mem->small_list[pool_id];
  175830. while (hdr_ptr != NULL) {
  175831. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  175832. break; /* found pool with enough space */
  175833. prev_hdr_ptr = hdr_ptr;
  175834. hdr_ptr = hdr_ptr->hdr.next;
  175835. }
  175836. /* Time to make a new pool? */
  175837. if (hdr_ptr == NULL) {
  175838. /* min_request is what we need now, slop is what will be leftover */
  175839. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  175840. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175841. slop = first_pool_slop[pool_id];
  175842. else
  175843. slop = extra_pool_slop[pool_id];
  175844. /* Don't ask for more than MAX_ALLOC_CHUNK */
  175845. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  175846. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  175847. /* Try to get space, if fail reduce slop and try again */
  175848. for (;;) {
  175849. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  175850. if (hdr_ptr != NULL)
  175851. break;
  175852. slop /= 2;
  175853. if (slop < MIN_SLOP) /* give up when it gets real small */
  175854. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  175855. }
  175856. mem->total_space_allocated += min_request + slop;
  175857. /* Success, initialize the new pool header and add to end of list */
  175858. hdr_ptr->hdr.next = NULL;
  175859. hdr_ptr->hdr.bytes_used = 0;
  175860. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  175861. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175862. mem->small_list[pool_id] = hdr_ptr;
  175863. else
  175864. prev_hdr_ptr->hdr.next = hdr_ptr;
  175865. }
  175866. /* OK, allocate the object from the current pool */
  175867. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  175868. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  175869. hdr_ptr->hdr.bytes_used += sizeofobject;
  175870. hdr_ptr->hdr.bytes_left -= sizeofobject;
  175871. return (void *) data_ptr;
  175872. }
  175873. /*
  175874. * Allocation of "large" objects.
  175875. *
  175876. * The external semantics of these are the same as "small" objects,
  175877. * except that FAR pointers are used on 80x86. However the pool
  175878. * management heuristics are quite different. We assume that each
  175879. * request is large enough that it may as well be passed directly to
  175880. * jpeg_get_large; the pool management just links everything together
  175881. * so that we can free it all on demand.
  175882. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  175883. * structures. The routines that create these structures (see below)
  175884. * deliberately bunch rows together to ensure a large request size.
  175885. */
  175886. METHODDEF(void FAR *)
  175887. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175888. /* Allocate a "large" object */
  175889. {
  175890. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175891. large_pool_ptr hdr_ptr;
  175892. size_t odd_bytes;
  175893. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175894. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  175895. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  175896. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175897. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175898. if (odd_bytes > 0)
  175899. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175900. /* Always make a new pool */
  175901. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175902. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175903. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  175904. SIZEOF(large_pool_hdr));
  175905. if (hdr_ptr == NULL)
  175906. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  175907. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  175908. /* Success, initialize the new pool header and add to list */
  175909. hdr_ptr->hdr.next = mem->large_list[pool_id];
  175910. /* We maintain space counts in each pool header for statistical purposes,
  175911. * even though they are not needed for allocation.
  175912. */
  175913. hdr_ptr->hdr.bytes_used = sizeofobject;
  175914. hdr_ptr->hdr.bytes_left = 0;
  175915. mem->large_list[pool_id] = hdr_ptr;
  175916. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  175917. }
  175918. /*
  175919. * Creation of 2-D sample arrays.
  175920. * The pointers are in near heap, the samples themselves in FAR heap.
  175921. *
  175922. * To minimize allocation overhead and to allow I/O of large contiguous
  175923. * blocks, we allocate the sample rows in groups of as many rows as possible
  175924. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  175925. * NB: the virtual array control routines, later in this file, know about
  175926. * this chunking of rows. The rowsperchunk value is left in the mem manager
  175927. * object so that it can be saved away if this sarray is the workspace for
  175928. * a virtual array.
  175929. */
  175930. METHODDEF(JSAMPARRAY)
  175931. alloc_sarray (j_common_ptr cinfo, int pool_id,
  175932. JDIMENSION samplesperrow, JDIMENSION numrows)
  175933. /* Allocate a 2-D sample array */
  175934. {
  175935. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175936. JSAMPARRAY result;
  175937. JSAMPROW workspace;
  175938. JDIMENSION rowsperchunk, currow, i;
  175939. long ltemp;
  175940. /* Calculate max # of rows allowed in one allocation chunk */
  175941. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175942. ((long) samplesperrow * SIZEOF(JSAMPLE));
  175943. if (ltemp <= 0)
  175944. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175945. if (ltemp < (long) numrows)
  175946. rowsperchunk = (JDIMENSION) ltemp;
  175947. else
  175948. rowsperchunk = numrows;
  175949. mem->last_rowsperchunk = rowsperchunk;
  175950. /* Get space for row pointers (small object) */
  175951. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  175952. (size_t) (numrows * SIZEOF(JSAMPROW)));
  175953. /* Get the rows themselves (large objects) */
  175954. currow = 0;
  175955. while (currow < numrows) {
  175956. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175957. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  175958. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  175959. * SIZEOF(JSAMPLE)));
  175960. for (i = rowsperchunk; i > 0; i--) {
  175961. result[currow++] = workspace;
  175962. workspace += samplesperrow;
  175963. }
  175964. }
  175965. return result;
  175966. }
  175967. /*
  175968. * Creation of 2-D coefficient-block arrays.
  175969. * This is essentially the same as the code for sample arrays, above.
  175970. */
  175971. METHODDEF(JBLOCKARRAY)
  175972. alloc_barray (j_common_ptr cinfo, int pool_id,
  175973. JDIMENSION blocksperrow, JDIMENSION numrows)
  175974. /* Allocate a 2-D coefficient-block array */
  175975. {
  175976. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175977. JBLOCKARRAY result;
  175978. JBLOCKROW workspace;
  175979. JDIMENSION rowsperchunk, currow, i;
  175980. long ltemp;
  175981. /* Calculate max # of rows allowed in one allocation chunk */
  175982. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175983. ((long) blocksperrow * SIZEOF(JBLOCK));
  175984. if (ltemp <= 0)
  175985. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175986. if (ltemp < (long) numrows)
  175987. rowsperchunk = (JDIMENSION) ltemp;
  175988. else
  175989. rowsperchunk = numrows;
  175990. mem->last_rowsperchunk = rowsperchunk;
  175991. /* Get space for row pointers (small object) */
  175992. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  175993. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  175994. /* Get the rows themselves (large objects) */
  175995. currow = 0;
  175996. while (currow < numrows) {
  175997. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175998. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  175999. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  176000. * SIZEOF(JBLOCK)));
  176001. for (i = rowsperchunk; i > 0; i--) {
  176002. result[currow++] = workspace;
  176003. workspace += blocksperrow;
  176004. }
  176005. }
  176006. return result;
  176007. }
  176008. /*
  176009. * About virtual array management:
  176010. *
  176011. * The above "normal" array routines are only used to allocate strip buffers
  176012. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  176013. * are handled as "virtual" arrays. The array is still accessed a strip at a
  176014. * time, but the memory manager must save the whole array for repeated
  176015. * accesses. The intended implementation is that there is a strip buffer in
  176016. * memory (as high as is possible given the desired memory limit), plus a
  176017. * backing file that holds the rest of the array.
  176018. *
  176019. * The request_virt_array routines are told the total size of the image and
  176020. * the maximum number of rows that will be accessed at once. The in-memory
  176021. * buffer must be at least as large as the maxaccess value.
  176022. *
  176023. * The request routines create control blocks but not the in-memory buffers.
  176024. * That is postponed until realize_virt_arrays is called. At that time the
  176025. * total amount of space needed is known (approximately, anyway), so free
  176026. * memory can be divided up fairly.
  176027. *
  176028. * The access_virt_array routines are responsible for making a specific strip
  176029. * area accessible (after reading or writing the backing file, if necessary).
  176030. * Note that the access routines are told whether the caller intends to modify
  176031. * the accessed strip; during a read-only pass this saves having to rewrite
  176032. * data to disk. The access routines are also responsible for pre-zeroing
  176033. * any newly accessed rows, if pre-zeroing was requested.
  176034. *
  176035. * In current usage, the access requests are usually for nonoverlapping
  176036. * strips; that is, successive access start_row numbers differ by exactly
  176037. * num_rows = maxaccess. This means we can get good performance with simple
  176038. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176039. * of the access height; then there will never be accesses across bufferload
  176040. * boundaries. The code will still work with overlapping access requests,
  176041. * but it doesn't handle bufferload overlaps very efficiently.
  176042. */
  176043. METHODDEF(jvirt_sarray_ptr)
  176044. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176045. JDIMENSION samplesperrow, JDIMENSION numrows,
  176046. JDIMENSION maxaccess)
  176047. /* Request a virtual 2-D sample array */
  176048. {
  176049. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176050. jvirt_sarray_ptr result;
  176051. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176052. if (pool_id != JPOOL_IMAGE)
  176053. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176054. /* get control block */
  176055. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176056. SIZEOF(struct jvirt_sarray_control));
  176057. result->mem_buffer = NULL; /* marks array not yet realized */
  176058. result->rows_in_array = numrows;
  176059. result->samplesperrow = samplesperrow;
  176060. result->maxaccess = maxaccess;
  176061. result->pre_zero = pre_zero;
  176062. result->b_s_open = FALSE; /* no associated backing-store object */
  176063. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176064. mem->virt_sarray_list = result;
  176065. return result;
  176066. }
  176067. METHODDEF(jvirt_barray_ptr)
  176068. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176069. JDIMENSION blocksperrow, JDIMENSION numrows,
  176070. JDIMENSION maxaccess)
  176071. /* Request a virtual 2-D coefficient-block array */
  176072. {
  176073. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176074. jvirt_barray_ptr result;
  176075. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176076. if (pool_id != JPOOL_IMAGE)
  176077. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176078. /* get control block */
  176079. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176080. SIZEOF(struct jvirt_barray_control));
  176081. result->mem_buffer = NULL; /* marks array not yet realized */
  176082. result->rows_in_array = numrows;
  176083. result->blocksperrow = blocksperrow;
  176084. result->maxaccess = maxaccess;
  176085. result->pre_zero = pre_zero;
  176086. result->b_s_open = FALSE; /* no associated backing-store object */
  176087. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176088. mem->virt_barray_list = result;
  176089. return result;
  176090. }
  176091. METHODDEF(void)
  176092. realize_virt_arrays (j_common_ptr cinfo)
  176093. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176094. {
  176095. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176096. long space_per_minheight, maximum_space, avail_mem;
  176097. long minheights, max_minheights;
  176098. jvirt_sarray_ptr sptr;
  176099. jvirt_barray_ptr bptr;
  176100. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176101. * and the maximum space needed (full image height in each buffer).
  176102. * These may be of use to the system-dependent jpeg_mem_available routine.
  176103. */
  176104. space_per_minheight = 0;
  176105. maximum_space = 0;
  176106. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176107. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176108. space_per_minheight += (long) sptr->maxaccess *
  176109. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176110. maximum_space += (long) sptr->rows_in_array *
  176111. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176112. }
  176113. }
  176114. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176115. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176116. space_per_minheight += (long) bptr->maxaccess *
  176117. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176118. maximum_space += (long) bptr->rows_in_array *
  176119. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176120. }
  176121. }
  176122. if (space_per_minheight <= 0)
  176123. return; /* no unrealized arrays, no work */
  176124. /* Determine amount of memory to actually use; this is system-dependent. */
  176125. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176126. mem->total_space_allocated);
  176127. /* If the maximum space needed is available, make all the buffers full
  176128. * height; otherwise parcel it out with the same number of minheights
  176129. * in each buffer.
  176130. */
  176131. if (avail_mem >= maximum_space)
  176132. max_minheights = 1000000000L;
  176133. else {
  176134. max_minheights = avail_mem / space_per_minheight;
  176135. /* If there doesn't seem to be enough space, try to get the minimum
  176136. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176137. */
  176138. if (max_minheights <= 0)
  176139. max_minheights = 1;
  176140. }
  176141. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176142. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176143. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176144. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176145. if (minheights <= max_minheights) {
  176146. /* This buffer fits in memory */
  176147. sptr->rows_in_mem = sptr->rows_in_array;
  176148. } else {
  176149. /* It doesn't fit in memory, create backing store. */
  176150. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176151. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176152. (long) sptr->rows_in_array *
  176153. (long) sptr->samplesperrow *
  176154. (long) SIZEOF(JSAMPLE));
  176155. sptr->b_s_open = TRUE;
  176156. }
  176157. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176158. sptr->samplesperrow, sptr->rows_in_mem);
  176159. sptr->rowsperchunk = mem->last_rowsperchunk;
  176160. sptr->cur_start_row = 0;
  176161. sptr->first_undef_row = 0;
  176162. sptr->dirty = FALSE;
  176163. }
  176164. }
  176165. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176166. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176167. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176168. if (minheights <= max_minheights) {
  176169. /* This buffer fits in memory */
  176170. bptr->rows_in_mem = bptr->rows_in_array;
  176171. } else {
  176172. /* It doesn't fit in memory, create backing store. */
  176173. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176174. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176175. (long) bptr->rows_in_array *
  176176. (long) bptr->blocksperrow *
  176177. (long) SIZEOF(JBLOCK));
  176178. bptr->b_s_open = TRUE;
  176179. }
  176180. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176181. bptr->blocksperrow, bptr->rows_in_mem);
  176182. bptr->rowsperchunk = mem->last_rowsperchunk;
  176183. bptr->cur_start_row = 0;
  176184. bptr->first_undef_row = 0;
  176185. bptr->dirty = FALSE;
  176186. }
  176187. }
  176188. }
  176189. LOCAL(void)
  176190. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176191. /* Do backing store read or write of a virtual sample array */
  176192. {
  176193. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176194. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176195. file_offset = ptr->cur_start_row * bytesperrow;
  176196. /* Loop to read or write each allocation chunk in mem_buffer */
  176197. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176198. /* One chunk, but check for short chunk at end of buffer */
  176199. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176200. /* Transfer no more than is currently defined */
  176201. thisrow = (long) ptr->cur_start_row + i;
  176202. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176203. /* Transfer no more than fits in file */
  176204. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176205. if (rows <= 0) /* this chunk might be past end of file! */
  176206. break;
  176207. byte_count = rows * bytesperrow;
  176208. if (writing)
  176209. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176210. (void FAR *) ptr->mem_buffer[i],
  176211. file_offset, byte_count);
  176212. else
  176213. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176214. (void FAR *) ptr->mem_buffer[i],
  176215. file_offset, byte_count);
  176216. file_offset += byte_count;
  176217. }
  176218. }
  176219. LOCAL(void)
  176220. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176221. /* Do backing store read or write of a virtual coefficient-block array */
  176222. {
  176223. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176224. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176225. file_offset = ptr->cur_start_row * bytesperrow;
  176226. /* Loop to read or write each allocation chunk in mem_buffer */
  176227. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176228. /* One chunk, but check for short chunk at end of buffer */
  176229. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176230. /* Transfer no more than is currently defined */
  176231. thisrow = (long) ptr->cur_start_row + i;
  176232. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176233. /* Transfer no more than fits in file */
  176234. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176235. if (rows <= 0) /* this chunk might be past end of file! */
  176236. break;
  176237. byte_count = rows * bytesperrow;
  176238. if (writing)
  176239. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176240. (void FAR *) ptr->mem_buffer[i],
  176241. file_offset, byte_count);
  176242. else
  176243. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176244. (void FAR *) ptr->mem_buffer[i],
  176245. file_offset, byte_count);
  176246. file_offset += byte_count;
  176247. }
  176248. }
  176249. METHODDEF(JSAMPARRAY)
  176250. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176251. JDIMENSION start_row, JDIMENSION num_rows,
  176252. boolean writable)
  176253. /* Access the part of a virtual sample array starting at start_row */
  176254. /* and extending for num_rows rows. writable is true if */
  176255. /* caller intends to modify the accessed area. */
  176256. {
  176257. JDIMENSION end_row = start_row + num_rows;
  176258. JDIMENSION undef_row;
  176259. /* debugging check */
  176260. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176261. ptr->mem_buffer == NULL)
  176262. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176263. /* Make the desired part of the virtual array accessible */
  176264. if (start_row < ptr->cur_start_row ||
  176265. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176266. if (! ptr->b_s_open)
  176267. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176268. /* Flush old buffer contents if necessary */
  176269. if (ptr->dirty) {
  176270. do_sarray_io(cinfo, ptr, TRUE);
  176271. ptr->dirty = FALSE;
  176272. }
  176273. /* Decide what part of virtual array to access.
  176274. * Algorithm: if target address > current window, assume forward scan,
  176275. * load starting at target address. If target address < current window,
  176276. * assume backward scan, load so that target area is top of window.
  176277. * Note that when switching from forward write to forward read, will have
  176278. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176279. */
  176280. if (start_row > ptr->cur_start_row) {
  176281. ptr->cur_start_row = start_row;
  176282. } else {
  176283. /* use long arithmetic here to avoid overflow & unsigned problems */
  176284. long ltemp;
  176285. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176286. if (ltemp < 0)
  176287. ltemp = 0; /* don't fall off front end of file */
  176288. ptr->cur_start_row = (JDIMENSION) ltemp;
  176289. }
  176290. /* Read in the selected part of the array.
  176291. * During the initial write pass, we will do no actual read
  176292. * because the selected part is all undefined.
  176293. */
  176294. do_sarray_io(cinfo, ptr, FALSE);
  176295. }
  176296. /* Ensure the accessed part of the array is defined; prezero if needed.
  176297. * To improve locality of access, we only prezero the part of the array
  176298. * that the caller is about to access, not the entire in-memory array.
  176299. */
  176300. if (ptr->first_undef_row < end_row) {
  176301. if (ptr->first_undef_row < start_row) {
  176302. if (writable) /* writer skipped over a section of array */
  176303. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176304. undef_row = start_row; /* but reader is allowed to read ahead */
  176305. } else {
  176306. undef_row = ptr->first_undef_row;
  176307. }
  176308. if (writable)
  176309. ptr->first_undef_row = end_row;
  176310. if (ptr->pre_zero) {
  176311. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176312. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176313. end_row -= ptr->cur_start_row;
  176314. while (undef_row < end_row) {
  176315. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176316. undef_row++;
  176317. }
  176318. } else {
  176319. if (! writable) /* reader looking at undefined data */
  176320. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176321. }
  176322. }
  176323. /* Flag the buffer dirty if caller will write in it */
  176324. if (writable)
  176325. ptr->dirty = TRUE;
  176326. /* Return address of proper part of the buffer */
  176327. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176328. }
  176329. METHODDEF(JBLOCKARRAY)
  176330. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176331. JDIMENSION start_row, JDIMENSION num_rows,
  176332. boolean writable)
  176333. /* Access the part of a virtual block array starting at start_row */
  176334. /* and extending for num_rows rows. writable is true if */
  176335. /* caller intends to modify the accessed area. */
  176336. {
  176337. JDIMENSION end_row = start_row + num_rows;
  176338. JDIMENSION undef_row;
  176339. /* debugging check */
  176340. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176341. ptr->mem_buffer == NULL)
  176342. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176343. /* Make the desired part of the virtual array accessible */
  176344. if (start_row < ptr->cur_start_row ||
  176345. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176346. if (! ptr->b_s_open)
  176347. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176348. /* Flush old buffer contents if necessary */
  176349. if (ptr->dirty) {
  176350. do_barray_io(cinfo, ptr, TRUE);
  176351. ptr->dirty = FALSE;
  176352. }
  176353. /* Decide what part of virtual array to access.
  176354. * Algorithm: if target address > current window, assume forward scan,
  176355. * load starting at target address. If target address < current window,
  176356. * assume backward scan, load so that target area is top of window.
  176357. * Note that when switching from forward write to forward read, will have
  176358. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176359. */
  176360. if (start_row > ptr->cur_start_row) {
  176361. ptr->cur_start_row = start_row;
  176362. } else {
  176363. /* use long arithmetic here to avoid overflow & unsigned problems */
  176364. long ltemp;
  176365. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176366. if (ltemp < 0)
  176367. ltemp = 0; /* don't fall off front end of file */
  176368. ptr->cur_start_row = (JDIMENSION) ltemp;
  176369. }
  176370. /* Read in the selected part of the array.
  176371. * During the initial write pass, we will do no actual read
  176372. * because the selected part is all undefined.
  176373. */
  176374. do_barray_io(cinfo, ptr, FALSE);
  176375. }
  176376. /* Ensure the accessed part of the array is defined; prezero if needed.
  176377. * To improve locality of access, we only prezero the part of the array
  176378. * that the caller is about to access, not the entire in-memory array.
  176379. */
  176380. if (ptr->first_undef_row < end_row) {
  176381. if (ptr->first_undef_row < start_row) {
  176382. if (writable) /* writer skipped over a section of array */
  176383. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176384. undef_row = start_row; /* but reader is allowed to read ahead */
  176385. } else {
  176386. undef_row = ptr->first_undef_row;
  176387. }
  176388. if (writable)
  176389. ptr->first_undef_row = end_row;
  176390. if (ptr->pre_zero) {
  176391. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176392. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176393. end_row -= ptr->cur_start_row;
  176394. while (undef_row < end_row) {
  176395. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176396. undef_row++;
  176397. }
  176398. } else {
  176399. if (! writable) /* reader looking at undefined data */
  176400. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176401. }
  176402. }
  176403. /* Flag the buffer dirty if caller will write in it */
  176404. if (writable)
  176405. ptr->dirty = TRUE;
  176406. /* Return address of proper part of the buffer */
  176407. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176408. }
  176409. /*
  176410. * Release all objects belonging to a specified pool.
  176411. */
  176412. METHODDEF(void)
  176413. free_pool (j_common_ptr cinfo, int pool_id)
  176414. {
  176415. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176416. small_pool_ptr shdr_ptr;
  176417. large_pool_ptr lhdr_ptr;
  176418. size_t space_freed;
  176419. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176420. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176421. #ifdef MEM_STATS
  176422. if (cinfo->err->trace_level > 1)
  176423. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176424. #endif
  176425. /* If freeing IMAGE pool, close any virtual arrays first */
  176426. if (pool_id == JPOOL_IMAGE) {
  176427. jvirt_sarray_ptr sptr;
  176428. jvirt_barray_ptr bptr;
  176429. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176430. if (sptr->b_s_open) { /* there may be no backing store */
  176431. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176432. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176433. }
  176434. }
  176435. mem->virt_sarray_list = NULL;
  176436. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176437. if (bptr->b_s_open) { /* there may be no backing store */
  176438. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176439. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176440. }
  176441. }
  176442. mem->virt_barray_list = NULL;
  176443. }
  176444. /* Release large objects */
  176445. lhdr_ptr = mem->large_list[pool_id];
  176446. mem->large_list[pool_id] = NULL;
  176447. while (lhdr_ptr != NULL) {
  176448. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176449. space_freed = lhdr_ptr->hdr.bytes_used +
  176450. lhdr_ptr->hdr.bytes_left +
  176451. SIZEOF(large_pool_hdr);
  176452. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176453. mem->total_space_allocated -= space_freed;
  176454. lhdr_ptr = next_lhdr_ptr;
  176455. }
  176456. /* Release small objects */
  176457. shdr_ptr = mem->small_list[pool_id];
  176458. mem->small_list[pool_id] = NULL;
  176459. while (shdr_ptr != NULL) {
  176460. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176461. space_freed = shdr_ptr->hdr.bytes_used +
  176462. shdr_ptr->hdr.bytes_left +
  176463. SIZEOF(small_pool_hdr);
  176464. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176465. mem->total_space_allocated -= space_freed;
  176466. shdr_ptr = next_shdr_ptr;
  176467. }
  176468. }
  176469. /*
  176470. * Close up shop entirely.
  176471. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176472. */
  176473. METHODDEF(void)
  176474. self_destruct (j_common_ptr cinfo)
  176475. {
  176476. int pool;
  176477. /* Close all backing store, release all memory.
  176478. * Releasing pools in reverse order might help avoid fragmentation
  176479. * with some (brain-damaged) malloc libraries.
  176480. */
  176481. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176482. free_pool(cinfo, pool);
  176483. }
  176484. /* Release the memory manager control block too. */
  176485. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176486. cinfo->mem = NULL; /* ensures I will be called only once */
  176487. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176488. }
  176489. /*
  176490. * Memory manager initialization.
  176491. * When this is called, only the error manager pointer is valid in cinfo!
  176492. */
  176493. GLOBAL(void)
  176494. jinit_memory_mgr (j_common_ptr cinfo)
  176495. {
  176496. my_mem_ptr mem;
  176497. long max_to_use;
  176498. int pool;
  176499. size_t test_mac;
  176500. cinfo->mem = NULL; /* for safety if init fails */
  176501. /* Check for configuration errors.
  176502. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  176503. * doesn't reflect any real hardware alignment requirement.
  176504. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  176505. * in common if and only if X is a power of 2, ie has only one one-bit.
  176506. * Some compilers may give an "unreachable code" warning here; ignore it.
  176507. */
  176508. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  176509. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  176510. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  176511. * a multiple of SIZEOF(ALIGN_TYPE).
  176512. * Again, an "unreachable code" warning may be ignored here.
  176513. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  176514. */
  176515. test_mac = (size_t) MAX_ALLOC_CHUNK;
  176516. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  176517. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  176518. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  176519. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  176520. /* Attempt to allocate memory manager's control block */
  176521. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  176522. if (mem == NULL) {
  176523. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176524. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  176525. }
  176526. /* OK, fill in the method pointers */
  176527. mem->pub.alloc_small = alloc_small;
  176528. mem->pub.alloc_large = alloc_large;
  176529. mem->pub.alloc_sarray = alloc_sarray;
  176530. mem->pub.alloc_barray = alloc_barray;
  176531. mem->pub.request_virt_sarray = request_virt_sarray;
  176532. mem->pub.request_virt_barray = request_virt_barray;
  176533. mem->pub.realize_virt_arrays = realize_virt_arrays;
  176534. mem->pub.access_virt_sarray = access_virt_sarray;
  176535. mem->pub.access_virt_barray = access_virt_barray;
  176536. mem->pub.free_pool = free_pool;
  176537. mem->pub.self_destruct = self_destruct;
  176538. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  176539. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  176540. /* Initialize working state */
  176541. mem->pub.max_memory_to_use = max_to_use;
  176542. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176543. mem->small_list[pool] = NULL;
  176544. mem->large_list[pool] = NULL;
  176545. }
  176546. mem->virt_sarray_list = NULL;
  176547. mem->virt_barray_list = NULL;
  176548. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  176549. /* Declare ourselves open for business */
  176550. cinfo->mem = & mem->pub;
  176551. /* Check for an environment variable JPEGMEM; if found, override the
  176552. * default max_memory setting from jpeg_mem_init. Note that the
  176553. * surrounding application may again override this value.
  176554. * If your system doesn't support getenv(), define NO_GETENV to disable
  176555. * this feature.
  176556. */
  176557. #ifndef NO_GETENV
  176558. { char * memenv;
  176559. if ((memenv = getenv("JPEGMEM")) != NULL) {
  176560. char ch = 'x';
  176561. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  176562. if (ch == 'm' || ch == 'M')
  176563. max_to_use *= 1000L;
  176564. mem->pub.max_memory_to_use = max_to_use * 1000L;
  176565. }
  176566. }
  176567. }
  176568. #endif
  176569. }
  176570. /*** End of inlined file: jmemmgr.c ***/
  176571. /*** Start of inlined file: jmemnobs.c ***/
  176572. #define JPEG_INTERNALS
  176573. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  176574. extern void * malloc JPP((size_t size));
  176575. extern void free JPP((void *ptr));
  176576. #endif
  176577. /*
  176578. * Memory allocation and freeing are controlled by the regular library
  176579. * routines malloc() and free().
  176580. */
  176581. GLOBAL(void *)
  176582. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  176583. {
  176584. return (void *) malloc(sizeofobject);
  176585. }
  176586. GLOBAL(void)
  176587. jpeg_free_small (j_common_ptr , void * object, size_t)
  176588. {
  176589. free(object);
  176590. }
  176591. /*
  176592. * "Large" objects are treated the same as "small" ones.
  176593. * NB: although we include FAR keywords in the routine declarations,
  176594. * this file won't actually work in 80x86 small/medium model; at least,
  176595. * you probably won't be able to process useful-size images in only 64KB.
  176596. */
  176597. GLOBAL(void FAR *)
  176598. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  176599. {
  176600. return (void FAR *) malloc(sizeofobject);
  176601. }
  176602. GLOBAL(void)
  176603. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  176604. {
  176605. free(object);
  176606. }
  176607. /*
  176608. * This routine computes the total memory space available for allocation.
  176609. * Here we always say, "we got all you want bud!"
  176610. */
  176611. GLOBAL(long)
  176612. jpeg_mem_available (j_common_ptr, long,
  176613. long max_bytes_needed, long)
  176614. {
  176615. return max_bytes_needed;
  176616. }
  176617. /*
  176618. * Backing store (temporary file) management.
  176619. * Since jpeg_mem_available always promised the moon,
  176620. * this should never be called and we can just error out.
  176621. */
  176622. GLOBAL(void)
  176623. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  176624. long )
  176625. {
  176626. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  176627. }
  176628. /*
  176629. * These routines take care of any system-dependent initialization and
  176630. * cleanup required. Here, there isn't any.
  176631. */
  176632. GLOBAL(long)
  176633. jpeg_mem_init (j_common_ptr)
  176634. {
  176635. return 0; /* just set max_memory_to_use to 0 */
  176636. }
  176637. GLOBAL(void)
  176638. jpeg_mem_term (j_common_ptr)
  176639. {
  176640. /* no work */
  176641. }
  176642. /*** End of inlined file: jmemnobs.c ***/
  176643. /*** Start of inlined file: jquant1.c ***/
  176644. #define JPEG_INTERNALS
  176645. #ifdef QUANT_1PASS_SUPPORTED
  176646. /*
  176647. * The main purpose of 1-pass quantization is to provide a fast, if not very
  176648. * high quality, colormapped output capability. A 2-pass quantizer usually
  176649. * gives better visual quality; however, for quantized grayscale output this
  176650. * quantizer is perfectly adequate. Dithering is highly recommended with this
  176651. * quantizer, though you can turn it off if you really want to.
  176652. *
  176653. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  176654. * image. We use a map consisting of all combinations of Ncolors[i] color
  176655. * values for the i'th component. The Ncolors[] values are chosen so that
  176656. * their product, the total number of colors, is no more than that requested.
  176657. * (In most cases, the product will be somewhat less.)
  176658. *
  176659. * Since the colormap is orthogonal, the representative value for each color
  176660. * component can be determined without considering the other components;
  176661. * then these indexes can be combined into a colormap index by a standard
  176662. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  176663. * can be precalculated and stored in the lookup table colorindex[].
  176664. * colorindex[i][j] maps pixel value j in component i to the nearest
  176665. * representative value (grid plane) for that component; this index is
  176666. * multiplied by the array stride for component i, so that the
  176667. * index of the colormap entry closest to a given pixel value is just
  176668. * sum( colorindex[component-number][pixel-component-value] )
  176669. * Aside from being fast, this scheme allows for variable spacing between
  176670. * representative values with no additional lookup cost.
  176671. *
  176672. * If gamma correction has been applied in color conversion, it might be wise
  176673. * to adjust the color grid spacing so that the representative colors are
  176674. * equidistant in linear space. At this writing, gamma correction is not
  176675. * implemented by jdcolor, so nothing is done here.
  176676. */
  176677. /* Declarations for ordered dithering.
  176678. *
  176679. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  176680. * dithering is described in many references, for instance Dale Schumacher's
  176681. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  176682. * In place of Schumacher's comparisons against a "threshold" value, we add a
  176683. * "dither" value to the input pixel and then round the result to the nearest
  176684. * output value. The dither value is equivalent to (0.5 - threshold) times
  176685. * the distance between output values. For ordered dithering, we assume that
  176686. * the output colors are equally spaced; if not, results will probably be
  176687. * worse, since the dither may be too much or too little at a given point.
  176688. *
  176689. * The normal calculation would be to form pixel value + dither, range-limit
  176690. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  176691. * We can skip the separate range-limiting step by extending the colorindex
  176692. * table in both directions.
  176693. */
  176694. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  176695. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  176696. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  176697. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  176698. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  176699. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  176700. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  176701. /* Bayer's order-4 dither array. Generated by the code given in
  176702. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  176703. * The values in this array must range from 0 to ODITHER_CELLS-1.
  176704. */
  176705. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  176706. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  176707. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  176708. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  176709. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  176710. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  176711. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  176712. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  176713. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  176714. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  176715. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  176716. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  176717. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  176718. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  176719. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  176720. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  176721. };
  176722. /* Declarations for Floyd-Steinberg dithering.
  176723. *
  176724. * Errors are accumulated into the array fserrors[], at a resolution of
  176725. * 1/16th of a pixel count. The error at a given pixel is propagated
  176726. * to its not-yet-processed neighbors using the standard F-S fractions,
  176727. * ... (here) 7/16
  176728. * 3/16 5/16 1/16
  176729. * We work left-to-right on even rows, right-to-left on odd rows.
  176730. *
  176731. * We can get away with a single array (holding one row's worth of errors)
  176732. * by using it to store the current row's errors at pixel columns not yet
  176733. * processed, but the next row's errors at columns already processed. We
  176734. * need only a few extra variables to hold the errors immediately around the
  176735. * current column. (If we are lucky, those variables are in registers, but
  176736. * even if not, they're probably cheaper to access than array elements are.)
  176737. *
  176738. * The fserrors[] array is indexed [component#][position].
  176739. * We provide (#columns + 2) entries per component; the extra entry at each
  176740. * end saves us from special-casing the first and last pixels.
  176741. *
  176742. * Note: on a wide image, we might not have enough room in a PC's near data
  176743. * segment to hold the error array; so it is allocated with alloc_large.
  176744. */
  176745. #if BITS_IN_JSAMPLE == 8
  176746. typedef INT16 FSERROR; /* 16 bits should be enough */
  176747. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  176748. #else
  176749. typedef INT32 FSERROR; /* may need more than 16 bits */
  176750. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  176751. #endif
  176752. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  176753. /* Private subobject */
  176754. #define MAX_Q_COMPS 4 /* max components I can handle */
  176755. typedef struct {
  176756. struct jpeg_color_quantizer pub; /* public fields */
  176757. /* Initially allocated colormap is saved here */
  176758. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  176759. int sv_actual; /* number of entries in use */
  176760. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  176761. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  176762. * premultiplied as described above. Since colormap indexes must fit into
  176763. * JSAMPLEs, the entries of this array will too.
  176764. */
  176765. boolean is_padded; /* is the colorindex padded for odither? */
  176766. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  176767. /* Variables for ordered dithering */
  176768. int row_index; /* cur row's vertical index in dither matrix */
  176769. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  176770. /* Variables for Floyd-Steinberg dithering */
  176771. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  176772. boolean on_odd_row; /* flag to remember which row we are on */
  176773. } my_cquantizer;
  176774. typedef my_cquantizer * my_cquantize_ptr;
  176775. /*
  176776. * Policy-making subroutines for create_colormap and create_colorindex.
  176777. * These routines determine the colormap to be used. The rest of the module
  176778. * only assumes that the colormap is orthogonal.
  176779. *
  176780. * * select_ncolors decides how to divvy up the available colors
  176781. * among the components.
  176782. * * output_value defines the set of representative values for a component.
  176783. * * largest_input_value defines the mapping from input values to
  176784. * representative values for a component.
  176785. * Note that the latter two routines may impose different policies for
  176786. * different components, though this is not currently done.
  176787. */
  176788. LOCAL(int)
  176789. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  176790. /* Determine allocation of desired colors to components, */
  176791. /* and fill in Ncolors[] array to indicate choice. */
  176792. /* Return value is total number of colors (product of Ncolors[] values). */
  176793. {
  176794. int nc = cinfo->out_color_components; /* number of color components */
  176795. int max_colors = cinfo->desired_number_of_colors;
  176796. int total_colors, iroot, i, j;
  176797. boolean changed;
  176798. long temp;
  176799. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  176800. /* We can allocate at least the nc'th root of max_colors per component. */
  176801. /* Compute floor(nc'th root of max_colors). */
  176802. iroot = 1;
  176803. do {
  176804. iroot++;
  176805. temp = iroot; /* set temp = iroot ** nc */
  176806. for (i = 1; i < nc; i++)
  176807. temp *= iroot;
  176808. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  176809. iroot--; /* now iroot = floor(root) */
  176810. /* Must have at least 2 color values per component */
  176811. if (iroot < 2)
  176812. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  176813. /* Initialize to iroot color values for each component */
  176814. total_colors = 1;
  176815. for (i = 0; i < nc; i++) {
  176816. Ncolors[i] = iroot;
  176817. total_colors *= iroot;
  176818. }
  176819. /* We may be able to increment the count for one or more components without
  176820. * exceeding max_colors, though we know not all can be incremented.
  176821. * Sometimes, the first component can be incremented more than once!
  176822. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  176823. * In RGB colorspace, try to increment G first, then R, then B.
  176824. */
  176825. do {
  176826. changed = FALSE;
  176827. for (i = 0; i < nc; i++) {
  176828. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  176829. /* calculate new total_colors if Ncolors[j] is incremented */
  176830. temp = total_colors / Ncolors[j];
  176831. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  176832. if (temp > (long) max_colors)
  176833. break; /* won't fit, done with this pass */
  176834. Ncolors[j]++; /* OK, apply the increment */
  176835. total_colors = (int) temp;
  176836. changed = TRUE;
  176837. }
  176838. } while (changed);
  176839. return total_colors;
  176840. }
  176841. LOCAL(int)
  176842. output_value (j_decompress_ptr, int, int j, int maxj)
  176843. /* Return j'th output value, where j will range from 0 to maxj */
  176844. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  176845. {
  176846. /* We always provide values 0 and MAXJSAMPLE for each component;
  176847. * any additional values are equally spaced between these limits.
  176848. * (Forcing the upper and lower values to the limits ensures that
  176849. * dithering can't produce a color outside the selected gamut.)
  176850. */
  176851. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  176852. }
  176853. LOCAL(int)
  176854. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  176855. /* Return largest input value that should map to j'th output value */
  176856. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  176857. {
  176858. /* Breakpoints are halfway between values returned by output_value */
  176859. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  176860. }
  176861. /*
  176862. * Create the colormap.
  176863. */
  176864. LOCAL(void)
  176865. create_colormap (j_decompress_ptr cinfo)
  176866. {
  176867. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176868. JSAMPARRAY colormap; /* Created colormap */
  176869. int total_colors; /* Number of distinct output colors */
  176870. int i,j,k, nci, blksize, blkdist, ptr, val;
  176871. /* Select number of colors for each component */
  176872. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  176873. /* Report selected color counts */
  176874. if (cinfo->out_color_components == 3)
  176875. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  176876. total_colors, cquantize->Ncolors[0],
  176877. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  176878. else
  176879. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  176880. /* Allocate and fill in the colormap. */
  176881. /* The colors are ordered in the map in standard row-major order, */
  176882. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  176883. colormap = (*cinfo->mem->alloc_sarray)
  176884. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176885. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  176886. /* blksize is number of adjacent repeated entries for a component */
  176887. /* blkdist is distance between groups of identical entries for a component */
  176888. blkdist = total_colors;
  176889. for (i = 0; i < cinfo->out_color_components; i++) {
  176890. /* fill in colormap entries for i'th color component */
  176891. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176892. blksize = blkdist / nci;
  176893. for (j = 0; j < nci; j++) {
  176894. /* Compute j'th output value (out of nci) for component */
  176895. val = output_value(cinfo, i, j, nci-1);
  176896. /* Fill in all colormap entries that have this value of this component */
  176897. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  176898. /* fill in blksize entries beginning at ptr */
  176899. for (k = 0; k < blksize; k++)
  176900. colormap[i][ptr+k] = (JSAMPLE) val;
  176901. }
  176902. }
  176903. blkdist = blksize; /* blksize of this color is blkdist of next */
  176904. }
  176905. /* Save the colormap in private storage,
  176906. * where it will survive color quantization mode changes.
  176907. */
  176908. cquantize->sv_colormap = colormap;
  176909. cquantize->sv_actual = total_colors;
  176910. }
  176911. /*
  176912. * Create the color index table.
  176913. */
  176914. LOCAL(void)
  176915. create_colorindex (j_decompress_ptr cinfo)
  176916. {
  176917. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176918. JSAMPROW indexptr;
  176919. int i,j,k, nci, blksize, val, pad;
  176920. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  176921. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  176922. * This is not necessary in the other dithering modes. However, we
  176923. * flag whether it was done in case user changes dithering mode.
  176924. */
  176925. if (cinfo->dither_mode == JDITHER_ORDERED) {
  176926. pad = MAXJSAMPLE*2;
  176927. cquantize->is_padded = TRUE;
  176928. } else {
  176929. pad = 0;
  176930. cquantize->is_padded = FALSE;
  176931. }
  176932. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  176933. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176934. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  176935. (JDIMENSION) cinfo->out_color_components);
  176936. /* blksize is number of adjacent repeated entries for a component */
  176937. blksize = cquantize->sv_actual;
  176938. for (i = 0; i < cinfo->out_color_components; i++) {
  176939. /* fill in colorindex entries for i'th color component */
  176940. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176941. blksize = blksize / nci;
  176942. /* adjust colorindex pointers to provide padding at negative indexes. */
  176943. if (pad)
  176944. cquantize->colorindex[i] += MAXJSAMPLE;
  176945. /* in loop, val = index of current output value, */
  176946. /* and k = largest j that maps to current val */
  176947. indexptr = cquantize->colorindex[i];
  176948. val = 0;
  176949. k = largest_input_value(cinfo, i, 0, nci-1);
  176950. for (j = 0; j <= MAXJSAMPLE; j++) {
  176951. while (j > k) /* advance val if past boundary */
  176952. k = largest_input_value(cinfo, i, ++val, nci-1);
  176953. /* premultiply so that no multiplication needed in main processing */
  176954. indexptr[j] = (JSAMPLE) (val * blksize);
  176955. }
  176956. /* Pad at both ends if necessary */
  176957. if (pad)
  176958. for (j = 1; j <= MAXJSAMPLE; j++) {
  176959. indexptr[-j] = indexptr[0];
  176960. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  176961. }
  176962. }
  176963. }
  176964. /*
  176965. * Create an ordered-dither array for a component having ncolors
  176966. * distinct output values.
  176967. */
  176968. LOCAL(ODITHER_MATRIX_PTR)
  176969. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  176970. {
  176971. ODITHER_MATRIX_PTR odither;
  176972. int j,k;
  176973. INT32 num,den;
  176974. odither = (ODITHER_MATRIX_PTR)
  176975. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176976. SIZEOF(ODITHER_MATRIX));
  176977. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  176978. * Hence the dither value for the matrix cell with fill order f
  176979. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  176980. * On 16-bit-int machine, be careful to avoid overflow.
  176981. */
  176982. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  176983. for (j = 0; j < ODITHER_SIZE; j++) {
  176984. for (k = 0; k < ODITHER_SIZE; k++) {
  176985. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  176986. * MAXJSAMPLE;
  176987. /* Ensure round towards zero despite C's lack of consistency
  176988. * about rounding negative values in integer division...
  176989. */
  176990. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  176991. }
  176992. }
  176993. return odither;
  176994. }
  176995. /*
  176996. * Create the ordered-dither tables.
  176997. * Components having the same number of representative colors may
  176998. * share a dither table.
  176999. */
  177000. LOCAL(void)
  177001. create_odither_tables (j_decompress_ptr cinfo)
  177002. {
  177003. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177004. ODITHER_MATRIX_PTR odither;
  177005. int i, j, nci;
  177006. for (i = 0; i < cinfo->out_color_components; i++) {
  177007. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177008. odither = NULL; /* search for matching prior component */
  177009. for (j = 0; j < i; j++) {
  177010. if (nci == cquantize->Ncolors[j]) {
  177011. odither = cquantize->odither[j];
  177012. break;
  177013. }
  177014. }
  177015. if (odither == NULL) /* need a new table? */
  177016. odither = make_odither_array(cinfo, nci);
  177017. cquantize->odither[i] = odither;
  177018. }
  177019. }
  177020. /*
  177021. * Map some rows of pixels to the output colormapped representation.
  177022. */
  177023. METHODDEF(void)
  177024. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177025. JSAMPARRAY output_buf, int num_rows)
  177026. /* General case, no dithering */
  177027. {
  177028. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177029. JSAMPARRAY colorindex = cquantize->colorindex;
  177030. register int pixcode, ci;
  177031. register JSAMPROW ptrin, ptrout;
  177032. int row;
  177033. JDIMENSION col;
  177034. JDIMENSION width = cinfo->output_width;
  177035. register int nc = cinfo->out_color_components;
  177036. for (row = 0; row < num_rows; row++) {
  177037. ptrin = input_buf[row];
  177038. ptrout = output_buf[row];
  177039. for (col = width; col > 0; col--) {
  177040. pixcode = 0;
  177041. for (ci = 0; ci < nc; ci++) {
  177042. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177043. }
  177044. *ptrout++ = (JSAMPLE) pixcode;
  177045. }
  177046. }
  177047. }
  177048. METHODDEF(void)
  177049. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177050. JSAMPARRAY output_buf, int num_rows)
  177051. /* Fast path for out_color_components==3, no dithering */
  177052. {
  177053. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177054. register int pixcode;
  177055. register JSAMPROW ptrin, ptrout;
  177056. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177057. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177058. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177059. int row;
  177060. JDIMENSION col;
  177061. JDIMENSION width = cinfo->output_width;
  177062. for (row = 0; row < num_rows; row++) {
  177063. ptrin = input_buf[row];
  177064. ptrout = output_buf[row];
  177065. for (col = width; col > 0; col--) {
  177066. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177067. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177068. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177069. *ptrout++ = (JSAMPLE) pixcode;
  177070. }
  177071. }
  177072. }
  177073. METHODDEF(void)
  177074. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177075. JSAMPARRAY output_buf, int num_rows)
  177076. /* General case, with ordered dithering */
  177077. {
  177078. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177079. register JSAMPROW input_ptr;
  177080. register JSAMPROW output_ptr;
  177081. JSAMPROW colorindex_ci;
  177082. int * dither; /* points to active row of dither matrix */
  177083. int row_index, col_index; /* current indexes into dither matrix */
  177084. int nc = cinfo->out_color_components;
  177085. int ci;
  177086. int row;
  177087. JDIMENSION col;
  177088. JDIMENSION width = cinfo->output_width;
  177089. for (row = 0; row < num_rows; row++) {
  177090. /* Initialize output values to 0 so can process components separately */
  177091. jzero_far((void FAR *) output_buf[row],
  177092. (size_t) (width * SIZEOF(JSAMPLE)));
  177093. row_index = cquantize->row_index;
  177094. for (ci = 0; ci < nc; ci++) {
  177095. input_ptr = input_buf[row] + ci;
  177096. output_ptr = output_buf[row];
  177097. colorindex_ci = cquantize->colorindex[ci];
  177098. dither = cquantize->odither[ci][row_index];
  177099. col_index = 0;
  177100. for (col = width; col > 0; col--) {
  177101. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177102. * select output value, accumulate into output code for this pixel.
  177103. * Range-limiting need not be done explicitly, as we have extended
  177104. * the colorindex table to produce the right answers for out-of-range
  177105. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177106. * required amount of padding.
  177107. */
  177108. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177109. input_ptr += nc;
  177110. output_ptr++;
  177111. col_index = (col_index + 1) & ODITHER_MASK;
  177112. }
  177113. }
  177114. /* Advance row index for next row */
  177115. row_index = (row_index + 1) & ODITHER_MASK;
  177116. cquantize->row_index = row_index;
  177117. }
  177118. }
  177119. METHODDEF(void)
  177120. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177121. JSAMPARRAY output_buf, int num_rows)
  177122. /* Fast path for out_color_components==3, with ordered dithering */
  177123. {
  177124. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177125. register int pixcode;
  177126. register JSAMPROW input_ptr;
  177127. register JSAMPROW output_ptr;
  177128. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177129. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177130. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177131. int * dither0; /* points to active row of dither matrix */
  177132. int * dither1;
  177133. int * dither2;
  177134. int row_index, col_index; /* current indexes into dither matrix */
  177135. int row;
  177136. JDIMENSION col;
  177137. JDIMENSION width = cinfo->output_width;
  177138. for (row = 0; row < num_rows; row++) {
  177139. row_index = cquantize->row_index;
  177140. input_ptr = input_buf[row];
  177141. output_ptr = output_buf[row];
  177142. dither0 = cquantize->odither[0][row_index];
  177143. dither1 = cquantize->odither[1][row_index];
  177144. dither2 = cquantize->odither[2][row_index];
  177145. col_index = 0;
  177146. for (col = width; col > 0; col--) {
  177147. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177148. dither0[col_index]]);
  177149. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177150. dither1[col_index]]);
  177151. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177152. dither2[col_index]]);
  177153. *output_ptr++ = (JSAMPLE) pixcode;
  177154. col_index = (col_index + 1) & ODITHER_MASK;
  177155. }
  177156. row_index = (row_index + 1) & ODITHER_MASK;
  177157. cquantize->row_index = row_index;
  177158. }
  177159. }
  177160. METHODDEF(void)
  177161. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177162. JSAMPARRAY output_buf, int num_rows)
  177163. /* General case, with Floyd-Steinberg dithering */
  177164. {
  177165. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177166. register LOCFSERROR cur; /* current error or pixel value */
  177167. LOCFSERROR belowerr; /* error for pixel below cur */
  177168. LOCFSERROR bpreverr; /* error for below/prev col */
  177169. LOCFSERROR bnexterr; /* error for below/next col */
  177170. LOCFSERROR delta;
  177171. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177172. register JSAMPROW input_ptr;
  177173. register JSAMPROW output_ptr;
  177174. JSAMPROW colorindex_ci;
  177175. JSAMPROW colormap_ci;
  177176. int pixcode;
  177177. int nc = cinfo->out_color_components;
  177178. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177179. int dirnc; /* dir * nc */
  177180. int ci;
  177181. int row;
  177182. JDIMENSION col;
  177183. JDIMENSION width = cinfo->output_width;
  177184. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177185. SHIFT_TEMPS
  177186. for (row = 0; row < num_rows; row++) {
  177187. /* Initialize output values to 0 so can process components separately */
  177188. jzero_far((void FAR *) output_buf[row],
  177189. (size_t) (width * SIZEOF(JSAMPLE)));
  177190. for (ci = 0; ci < nc; ci++) {
  177191. input_ptr = input_buf[row] + ci;
  177192. output_ptr = output_buf[row];
  177193. if (cquantize->on_odd_row) {
  177194. /* work right to left in this row */
  177195. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177196. output_ptr += width-1;
  177197. dir = -1;
  177198. dirnc = -nc;
  177199. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177200. } else {
  177201. /* work left to right in this row */
  177202. dir = 1;
  177203. dirnc = nc;
  177204. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177205. }
  177206. colorindex_ci = cquantize->colorindex[ci];
  177207. colormap_ci = cquantize->sv_colormap[ci];
  177208. /* Preset error values: no error propagated to first pixel from left */
  177209. cur = 0;
  177210. /* and no error propagated to row below yet */
  177211. belowerr = bpreverr = 0;
  177212. for (col = width; col > 0; col--) {
  177213. /* cur holds the error propagated from the previous pixel on the
  177214. * current line. Add the error propagated from the previous line
  177215. * to form the complete error correction term for this pixel, and
  177216. * round the error term (which is expressed * 16) to an integer.
  177217. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177218. * for either sign of the error value.
  177219. * Note: errorptr points to *previous* column's array entry.
  177220. */
  177221. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177222. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177223. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177224. * of the range_limit array.
  177225. */
  177226. cur += GETJSAMPLE(*input_ptr);
  177227. cur = GETJSAMPLE(range_limit[cur]);
  177228. /* Select output value, accumulate into output code for this pixel */
  177229. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177230. *output_ptr += (JSAMPLE) pixcode;
  177231. /* Compute actual representation error at this pixel */
  177232. /* Note: we can do this even though we don't have the final */
  177233. /* pixel code, because the colormap is orthogonal. */
  177234. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177235. /* Compute error fractions to be propagated to adjacent pixels.
  177236. * Add these into the running sums, and simultaneously shift the
  177237. * next-line error sums left by 1 column.
  177238. */
  177239. bnexterr = cur;
  177240. delta = cur * 2;
  177241. cur += delta; /* form error * 3 */
  177242. errorptr[0] = (FSERROR) (bpreverr + cur);
  177243. cur += delta; /* form error * 5 */
  177244. bpreverr = belowerr + cur;
  177245. belowerr = bnexterr;
  177246. cur += delta; /* form error * 7 */
  177247. /* At this point cur contains the 7/16 error value to be propagated
  177248. * to the next pixel on the current line, and all the errors for the
  177249. * next line have been shifted over. We are therefore ready to move on.
  177250. */
  177251. input_ptr += dirnc; /* advance input ptr to next column */
  177252. output_ptr += dir; /* advance output ptr to next column */
  177253. errorptr += dir; /* advance errorptr to current column */
  177254. }
  177255. /* Post-loop cleanup: we must unload the final error value into the
  177256. * final fserrors[] entry. Note we need not unload belowerr because
  177257. * it is for the dummy column before or after the actual array.
  177258. */
  177259. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177260. }
  177261. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177262. }
  177263. }
  177264. /*
  177265. * Allocate workspace for Floyd-Steinberg errors.
  177266. */
  177267. LOCAL(void)
  177268. alloc_fs_workspace (j_decompress_ptr cinfo)
  177269. {
  177270. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177271. size_t arraysize;
  177272. int i;
  177273. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177274. for (i = 0; i < cinfo->out_color_components; i++) {
  177275. cquantize->fserrors[i] = (FSERRPTR)
  177276. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177277. }
  177278. }
  177279. /*
  177280. * Initialize for one-pass color quantization.
  177281. */
  177282. METHODDEF(void)
  177283. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177284. {
  177285. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177286. size_t arraysize;
  177287. int i;
  177288. /* Install my colormap. */
  177289. cinfo->colormap = cquantize->sv_colormap;
  177290. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177291. /* Initialize for desired dithering mode. */
  177292. switch (cinfo->dither_mode) {
  177293. case JDITHER_NONE:
  177294. if (cinfo->out_color_components == 3)
  177295. cquantize->pub.color_quantize = color_quantize3;
  177296. else
  177297. cquantize->pub.color_quantize = color_quantize;
  177298. break;
  177299. case JDITHER_ORDERED:
  177300. if (cinfo->out_color_components == 3)
  177301. cquantize->pub.color_quantize = quantize3_ord_dither;
  177302. else
  177303. cquantize->pub.color_quantize = quantize_ord_dither;
  177304. cquantize->row_index = 0; /* initialize state for ordered dither */
  177305. /* If user changed to ordered dither from another mode,
  177306. * we must recreate the color index table with padding.
  177307. * This will cost extra space, but probably isn't very likely.
  177308. */
  177309. if (! cquantize->is_padded)
  177310. create_colorindex(cinfo);
  177311. /* Create ordered-dither tables if we didn't already. */
  177312. if (cquantize->odither[0] == NULL)
  177313. create_odither_tables(cinfo);
  177314. break;
  177315. case JDITHER_FS:
  177316. cquantize->pub.color_quantize = quantize_fs_dither;
  177317. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177318. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177319. if (cquantize->fserrors[0] == NULL)
  177320. alloc_fs_workspace(cinfo);
  177321. /* Initialize the propagated errors to zero. */
  177322. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177323. for (i = 0; i < cinfo->out_color_components; i++)
  177324. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177325. break;
  177326. default:
  177327. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177328. break;
  177329. }
  177330. }
  177331. /*
  177332. * Finish up at the end of the pass.
  177333. */
  177334. METHODDEF(void)
  177335. finish_pass_1_quant (j_decompress_ptr)
  177336. {
  177337. /* no work in 1-pass case */
  177338. }
  177339. /*
  177340. * Switch to a new external colormap between output passes.
  177341. * Shouldn't get to this module!
  177342. */
  177343. METHODDEF(void)
  177344. new_color_map_1_quant (j_decompress_ptr cinfo)
  177345. {
  177346. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177347. }
  177348. /*
  177349. * Module initialization routine for 1-pass color quantization.
  177350. */
  177351. GLOBAL(void)
  177352. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177353. {
  177354. my_cquantize_ptr cquantize;
  177355. cquantize = (my_cquantize_ptr)
  177356. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177357. SIZEOF(my_cquantizer));
  177358. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177359. cquantize->pub.start_pass = start_pass_1_quant;
  177360. cquantize->pub.finish_pass = finish_pass_1_quant;
  177361. cquantize->pub.new_color_map = new_color_map_1_quant;
  177362. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177363. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177364. /* Make sure my internal arrays won't overflow */
  177365. if (cinfo->out_color_components > MAX_Q_COMPS)
  177366. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177367. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177368. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177369. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177370. /* Create the colormap and color index table. */
  177371. create_colormap(cinfo);
  177372. create_colorindex(cinfo);
  177373. /* Allocate Floyd-Steinberg workspace now if requested.
  177374. * We do this now since it is FAR storage and may affect the memory
  177375. * manager's space calculations. If the user changes to FS dither
  177376. * mode in a later pass, we will allocate the space then, and will
  177377. * possibly overrun the max_memory_to_use setting.
  177378. */
  177379. if (cinfo->dither_mode == JDITHER_FS)
  177380. alloc_fs_workspace(cinfo);
  177381. }
  177382. #endif /* QUANT_1PASS_SUPPORTED */
  177383. /*** End of inlined file: jquant1.c ***/
  177384. /*** Start of inlined file: jquant2.c ***/
  177385. #define JPEG_INTERNALS
  177386. #ifdef QUANT_2PASS_SUPPORTED
  177387. /*
  177388. * This module implements the well-known Heckbert paradigm for color
  177389. * quantization. Most of the ideas used here can be traced back to
  177390. * Heckbert's seminal paper
  177391. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177392. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177393. *
  177394. * In the first pass over the image, we accumulate a histogram showing the
  177395. * usage count of each possible color. To keep the histogram to a reasonable
  177396. * size, we reduce the precision of the input; typical practice is to retain
  177397. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177398. * in the same histogram cell.
  177399. *
  177400. * Next, the color-selection step begins with a box representing the whole
  177401. * color space, and repeatedly splits the "largest" remaining box until we
  177402. * have as many boxes as desired colors. Then the mean color in each
  177403. * remaining box becomes one of the possible output colors.
  177404. *
  177405. * The second pass over the image maps each input pixel to the closest output
  177406. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177407. * This mapping is logically trivial, but making it go fast enough requires
  177408. * considerable care.
  177409. *
  177410. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177411. * the "largest" box and deciding where to cut it. The particular policies
  177412. * used here have proved out well in experimental comparisons, but better ones
  177413. * may yet be found.
  177414. *
  177415. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177416. * space, processing the raw upsampled data without a color conversion step.
  177417. * This allowed the color conversion math to be done only once per colormap
  177418. * entry, not once per pixel. However, that optimization precluded other
  177419. * useful optimizations (such as merging color conversion with upsampling)
  177420. * and it also interfered with desired capabilities such as quantizing to an
  177421. * externally-supplied colormap. We have therefore abandoned that approach.
  177422. * The present code works in the post-conversion color space, typically RGB.
  177423. *
  177424. * To improve the visual quality of the results, we actually work in scaled
  177425. * RGB space, giving G distances more weight than R, and R in turn more than
  177426. * B. To do everything in integer math, we must use integer scale factors.
  177427. * The 2/3/1 scale factors used here correspond loosely to the relative
  177428. * weights of the colors in the NTSC grayscale equation.
  177429. * If you want to use this code to quantize a non-RGB color space, you'll
  177430. * probably need to change these scale factors.
  177431. */
  177432. #define R_SCALE 2 /* scale R distances by this much */
  177433. #define G_SCALE 3 /* scale G distances by this much */
  177434. #define B_SCALE 1 /* and B by this much */
  177435. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177436. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177437. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177438. * you'll get compile errors until you extend this logic. In that case
  177439. * you'll probably want to tweak the histogram sizes too.
  177440. */
  177441. #if RGB_RED == 0
  177442. #define C0_SCALE R_SCALE
  177443. #endif
  177444. #if RGB_BLUE == 0
  177445. #define C0_SCALE B_SCALE
  177446. #endif
  177447. #if RGB_GREEN == 1
  177448. #define C1_SCALE G_SCALE
  177449. #endif
  177450. #if RGB_RED == 2
  177451. #define C2_SCALE R_SCALE
  177452. #endif
  177453. #if RGB_BLUE == 2
  177454. #define C2_SCALE B_SCALE
  177455. #endif
  177456. /*
  177457. * First we have the histogram data structure and routines for creating it.
  177458. *
  177459. * The number of bits of precision can be adjusted by changing these symbols.
  177460. * We recommend keeping 6 bits for G and 5 each for R and B.
  177461. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177462. * better results; if you are short of memory, 5 bits all around will save
  177463. * some space but degrade the results.
  177464. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177465. * (preferably unsigned long) for each cell. In practice this is overkill;
  177466. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177467. * and clamping those that do overflow to the maximum value will give close-
  177468. * enough results. This reduces the recommended histogram size from 256Kb
  177469. * to 128Kb, which is a useful savings on PC-class machines.
  177470. * (In the second pass the histogram space is re-used for pixel mapping data;
  177471. * in that capacity, each cell must be able to store zero to the number of
  177472. * desired colors. 16 bits/cell is plenty for that too.)
  177473. * Since the JPEG code is intended to run in small memory model on 80x86
  177474. * machines, we can't just allocate the histogram in one chunk. Instead
  177475. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177476. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177477. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177478. * on 80x86 machines, the pointer row is in near memory but the actual
  177479. * arrays are in far memory (same arrangement as we use for image arrays).
  177480. */
  177481. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177482. /* These will do the right thing for either R,G,B or B,G,R color order,
  177483. * but you may not like the results for other color orders.
  177484. */
  177485. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177486. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177487. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  177488. /* Number of elements along histogram axes. */
  177489. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  177490. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  177491. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  177492. /* These are the amounts to shift an input value to get a histogram index. */
  177493. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  177494. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  177495. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  177496. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  177497. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  177498. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  177499. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  177500. typedef hist2d * hist3d; /* type for top-level pointer */
  177501. /* Declarations for Floyd-Steinberg dithering.
  177502. *
  177503. * Errors are accumulated into the array fserrors[], at a resolution of
  177504. * 1/16th of a pixel count. The error at a given pixel is propagated
  177505. * to its not-yet-processed neighbors using the standard F-S fractions,
  177506. * ... (here) 7/16
  177507. * 3/16 5/16 1/16
  177508. * We work left-to-right on even rows, right-to-left on odd rows.
  177509. *
  177510. * We can get away with a single array (holding one row's worth of errors)
  177511. * by using it to store the current row's errors at pixel columns not yet
  177512. * processed, but the next row's errors at columns already processed. We
  177513. * need only a few extra variables to hold the errors immediately around the
  177514. * current column. (If we are lucky, those variables are in registers, but
  177515. * even if not, they're probably cheaper to access than array elements are.)
  177516. *
  177517. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  177518. * each end saves us from special-casing the first and last pixels.
  177519. * Each entry is three values long, one value for each color component.
  177520. *
  177521. * Note: on a wide image, we might not have enough room in a PC's near data
  177522. * segment to hold the error array; so it is allocated with alloc_large.
  177523. */
  177524. #if BITS_IN_JSAMPLE == 8
  177525. typedef INT16 FSERROR; /* 16 bits should be enough */
  177526. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177527. #else
  177528. typedef INT32 FSERROR; /* may need more than 16 bits */
  177529. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177530. #endif
  177531. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177532. /* Private subobject */
  177533. typedef struct {
  177534. struct jpeg_color_quantizer pub; /* public fields */
  177535. /* Space for the eventually created colormap is stashed here */
  177536. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  177537. int desired; /* desired # of colors = size of colormap */
  177538. /* Variables for accumulating image statistics */
  177539. hist3d histogram; /* pointer to the histogram */
  177540. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  177541. /* Variables for Floyd-Steinberg dithering */
  177542. FSERRPTR fserrors; /* accumulated errors */
  177543. boolean on_odd_row; /* flag to remember which row we are on */
  177544. int * error_limiter; /* table for clamping the applied error */
  177545. } my_cquantizer2;
  177546. typedef my_cquantizer2 * my_cquantize_ptr2;
  177547. /*
  177548. * Prescan some rows of pixels.
  177549. * In this module the prescan simply updates the histogram, which has been
  177550. * initialized to zeroes by start_pass.
  177551. * An output_buf parameter is required by the method signature, but no data
  177552. * is actually output (in fact the buffer controller is probably passing a
  177553. * NULL pointer).
  177554. */
  177555. METHODDEF(void)
  177556. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177557. JSAMPARRAY, int num_rows)
  177558. {
  177559. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177560. register JSAMPROW ptr;
  177561. register histptr histp;
  177562. register hist3d histogram = cquantize->histogram;
  177563. int row;
  177564. JDIMENSION col;
  177565. JDIMENSION width = cinfo->output_width;
  177566. for (row = 0; row < num_rows; row++) {
  177567. ptr = input_buf[row];
  177568. for (col = width; col > 0; col--) {
  177569. /* get pixel value and index into the histogram */
  177570. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  177571. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  177572. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  177573. /* increment, check for overflow and undo increment if so. */
  177574. if (++(*histp) <= 0)
  177575. (*histp)--;
  177576. ptr += 3;
  177577. }
  177578. }
  177579. }
  177580. /*
  177581. * Next we have the really interesting routines: selection of a colormap
  177582. * given the completed histogram.
  177583. * These routines work with a list of "boxes", each representing a rectangular
  177584. * subset of the input color space (to histogram precision).
  177585. */
  177586. typedef struct {
  177587. /* The bounds of the box (inclusive); expressed as histogram indexes */
  177588. int c0min, c0max;
  177589. int c1min, c1max;
  177590. int c2min, c2max;
  177591. /* The volume (actually 2-norm) of the box */
  177592. INT32 volume;
  177593. /* The number of nonzero histogram cells within this box */
  177594. long colorcount;
  177595. } box;
  177596. typedef box * boxptr;
  177597. LOCAL(boxptr)
  177598. find_biggest_color_pop (boxptr boxlist, int numboxes)
  177599. /* Find the splittable box with the largest color population */
  177600. /* Returns NULL if no splittable boxes remain */
  177601. {
  177602. register boxptr boxp;
  177603. register int i;
  177604. register long maxc = 0;
  177605. boxptr which = NULL;
  177606. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177607. if (boxp->colorcount > maxc && boxp->volume > 0) {
  177608. which = boxp;
  177609. maxc = boxp->colorcount;
  177610. }
  177611. }
  177612. return which;
  177613. }
  177614. LOCAL(boxptr)
  177615. find_biggest_volume (boxptr boxlist, int numboxes)
  177616. /* Find the splittable box with the largest (scaled) volume */
  177617. /* Returns NULL if no splittable boxes remain */
  177618. {
  177619. register boxptr boxp;
  177620. register int i;
  177621. register INT32 maxv = 0;
  177622. boxptr which = NULL;
  177623. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177624. if (boxp->volume > maxv) {
  177625. which = boxp;
  177626. maxv = boxp->volume;
  177627. }
  177628. }
  177629. return which;
  177630. }
  177631. LOCAL(void)
  177632. update_box (j_decompress_ptr cinfo, boxptr boxp)
  177633. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  177634. /* and recompute its volume and population */
  177635. {
  177636. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177637. hist3d histogram = cquantize->histogram;
  177638. histptr histp;
  177639. int c0,c1,c2;
  177640. int c0min,c0max,c1min,c1max,c2min,c2max;
  177641. INT32 dist0,dist1,dist2;
  177642. long ccount;
  177643. c0min = boxp->c0min; c0max = boxp->c0max;
  177644. c1min = boxp->c1min; c1max = boxp->c1max;
  177645. c2min = boxp->c2min; c2max = boxp->c2max;
  177646. if (c0max > c0min)
  177647. for (c0 = c0min; c0 <= c0max; c0++)
  177648. for (c1 = c1min; c1 <= c1max; c1++) {
  177649. histp = & histogram[c0][c1][c2min];
  177650. for (c2 = c2min; c2 <= c2max; c2++)
  177651. if (*histp++ != 0) {
  177652. boxp->c0min = c0min = c0;
  177653. goto have_c0min;
  177654. }
  177655. }
  177656. have_c0min:
  177657. if (c0max > c0min)
  177658. for (c0 = c0max; c0 >= c0min; c0--)
  177659. for (c1 = c1min; c1 <= c1max; c1++) {
  177660. histp = & histogram[c0][c1][c2min];
  177661. for (c2 = c2min; c2 <= c2max; c2++)
  177662. if (*histp++ != 0) {
  177663. boxp->c0max = c0max = c0;
  177664. goto have_c0max;
  177665. }
  177666. }
  177667. have_c0max:
  177668. if (c1max > c1min)
  177669. for (c1 = c1min; c1 <= c1max; c1++)
  177670. for (c0 = c0min; c0 <= c0max; c0++) {
  177671. histp = & histogram[c0][c1][c2min];
  177672. for (c2 = c2min; c2 <= c2max; c2++)
  177673. if (*histp++ != 0) {
  177674. boxp->c1min = c1min = c1;
  177675. goto have_c1min;
  177676. }
  177677. }
  177678. have_c1min:
  177679. if (c1max > c1min)
  177680. for (c1 = c1max; c1 >= c1min; c1--)
  177681. for (c0 = c0min; c0 <= c0max; c0++) {
  177682. histp = & histogram[c0][c1][c2min];
  177683. for (c2 = c2min; c2 <= c2max; c2++)
  177684. if (*histp++ != 0) {
  177685. boxp->c1max = c1max = c1;
  177686. goto have_c1max;
  177687. }
  177688. }
  177689. have_c1max:
  177690. if (c2max > c2min)
  177691. for (c2 = c2min; c2 <= c2max; c2++)
  177692. for (c0 = c0min; c0 <= c0max; c0++) {
  177693. histp = & histogram[c0][c1min][c2];
  177694. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177695. if (*histp != 0) {
  177696. boxp->c2min = c2min = c2;
  177697. goto have_c2min;
  177698. }
  177699. }
  177700. have_c2min:
  177701. if (c2max > c2min)
  177702. for (c2 = c2max; c2 >= c2min; c2--)
  177703. for (c0 = c0min; c0 <= c0max; c0++) {
  177704. histp = & histogram[c0][c1min][c2];
  177705. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177706. if (*histp != 0) {
  177707. boxp->c2max = c2max = c2;
  177708. goto have_c2max;
  177709. }
  177710. }
  177711. have_c2max:
  177712. /* Update box volume.
  177713. * We use 2-norm rather than real volume here; this biases the method
  177714. * against making long narrow boxes, and it has the side benefit that
  177715. * a box is splittable iff norm > 0.
  177716. * Since the differences are expressed in histogram-cell units,
  177717. * we have to shift back to JSAMPLE units to get consistent distances;
  177718. * after which, we scale according to the selected distance scale factors.
  177719. */
  177720. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  177721. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  177722. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  177723. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  177724. /* Now scan remaining volume of box and compute population */
  177725. ccount = 0;
  177726. for (c0 = c0min; c0 <= c0max; c0++)
  177727. for (c1 = c1min; c1 <= c1max; c1++) {
  177728. histp = & histogram[c0][c1][c2min];
  177729. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  177730. if (*histp != 0) {
  177731. ccount++;
  177732. }
  177733. }
  177734. boxp->colorcount = ccount;
  177735. }
  177736. LOCAL(int)
  177737. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  177738. int desired_colors)
  177739. /* Repeatedly select and split the largest box until we have enough boxes */
  177740. {
  177741. int n,lb;
  177742. int c0,c1,c2,cmax;
  177743. register boxptr b1,b2;
  177744. while (numboxes < desired_colors) {
  177745. /* Select box to split.
  177746. * Current algorithm: by population for first half, then by volume.
  177747. */
  177748. if (numboxes*2 <= desired_colors) {
  177749. b1 = find_biggest_color_pop(boxlist, numboxes);
  177750. } else {
  177751. b1 = find_biggest_volume(boxlist, numboxes);
  177752. }
  177753. if (b1 == NULL) /* no splittable boxes left! */
  177754. break;
  177755. b2 = &boxlist[numboxes]; /* where new box will go */
  177756. /* Copy the color bounds to the new box. */
  177757. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  177758. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  177759. /* Choose which axis to split the box on.
  177760. * Current algorithm: longest scaled axis.
  177761. * See notes in update_box about scaling distances.
  177762. */
  177763. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  177764. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  177765. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  177766. /* We want to break any ties in favor of green, then red, blue last.
  177767. * This code does the right thing for R,G,B or B,G,R color orders only.
  177768. */
  177769. #if RGB_RED == 0
  177770. cmax = c1; n = 1;
  177771. if (c0 > cmax) { cmax = c0; n = 0; }
  177772. if (c2 > cmax) { n = 2; }
  177773. #else
  177774. cmax = c1; n = 1;
  177775. if (c2 > cmax) { cmax = c2; n = 2; }
  177776. if (c0 > cmax) { n = 0; }
  177777. #endif
  177778. /* Choose split point along selected axis, and update box bounds.
  177779. * Current algorithm: split at halfway point.
  177780. * (Since the box has been shrunk to minimum volume,
  177781. * any split will produce two nonempty subboxes.)
  177782. * Note that lb value is max for lower box, so must be < old max.
  177783. */
  177784. switch (n) {
  177785. case 0:
  177786. lb = (b1->c0max + b1->c0min) / 2;
  177787. b1->c0max = lb;
  177788. b2->c0min = lb+1;
  177789. break;
  177790. case 1:
  177791. lb = (b1->c1max + b1->c1min) / 2;
  177792. b1->c1max = lb;
  177793. b2->c1min = lb+1;
  177794. break;
  177795. case 2:
  177796. lb = (b1->c2max + b1->c2min) / 2;
  177797. b1->c2max = lb;
  177798. b2->c2min = lb+1;
  177799. break;
  177800. }
  177801. /* Update stats for boxes */
  177802. update_box(cinfo, b1);
  177803. update_box(cinfo, b2);
  177804. numboxes++;
  177805. }
  177806. return numboxes;
  177807. }
  177808. LOCAL(void)
  177809. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  177810. /* Compute representative color for a box, put it in colormap[icolor] */
  177811. {
  177812. /* Current algorithm: mean weighted by pixels (not colors) */
  177813. /* Note it is important to get the rounding correct! */
  177814. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177815. hist3d histogram = cquantize->histogram;
  177816. histptr histp;
  177817. int c0,c1,c2;
  177818. int c0min,c0max,c1min,c1max,c2min,c2max;
  177819. long count;
  177820. long total = 0;
  177821. long c0total = 0;
  177822. long c1total = 0;
  177823. long c2total = 0;
  177824. c0min = boxp->c0min; c0max = boxp->c0max;
  177825. c1min = boxp->c1min; c1max = boxp->c1max;
  177826. c2min = boxp->c2min; c2max = boxp->c2max;
  177827. for (c0 = c0min; c0 <= c0max; c0++)
  177828. for (c1 = c1min; c1 <= c1max; c1++) {
  177829. histp = & histogram[c0][c1][c2min];
  177830. for (c2 = c2min; c2 <= c2max; c2++) {
  177831. if ((count = *histp++) != 0) {
  177832. total += count;
  177833. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  177834. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  177835. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  177836. }
  177837. }
  177838. }
  177839. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  177840. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  177841. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  177842. }
  177843. LOCAL(void)
  177844. select_colors (j_decompress_ptr cinfo, int desired_colors)
  177845. /* Master routine for color selection */
  177846. {
  177847. boxptr boxlist;
  177848. int numboxes;
  177849. int i;
  177850. /* Allocate workspace for box list */
  177851. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  177852. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  177853. /* Initialize one box containing whole space */
  177854. numboxes = 1;
  177855. boxlist[0].c0min = 0;
  177856. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  177857. boxlist[0].c1min = 0;
  177858. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  177859. boxlist[0].c2min = 0;
  177860. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  177861. /* Shrink it to actually-used volume and set its statistics */
  177862. update_box(cinfo, & boxlist[0]);
  177863. /* Perform median-cut to produce final box list */
  177864. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  177865. /* Compute the representative color for each box, fill colormap */
  177866. for (i = 0; i < numboxes; i++)
  177867. compute_color(cinfo, & boxlist[i], i);
  177868. cinfo->actual_number_of_colors = numboxes;
  177869. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  177870. }
  177871. /*
  177872. * These routines are concerned with the time-critical task of mapping input
  177873. * colors to the nearest color in the selected colormap.
  177874. *
  177875. * We re-use the histogram space as an "inverse color map", essentially a
  177876. * cache for the results of nearest-color searches. All colors within a
  177877. * histogram cell will be mapped to the same colormap entry, namely the one
  177878. * closest to the cell's center. This may not be quite the closest entry to
  177879. * the actual input color, but it's almost as good. A zero in the cache
  177880. * indicates we haven't found the nearest color for that cell yet; the array
  177881. * is cleared to zeroes before starting the mapping pass. When we find the
  177882. * nearest color for a cell, its colormap index plus one is recorded in the
  177883. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  177884. * when they need to use an unfilled entry in the cache.
  177885. *
  177886. * Our method of efficiently finding nearest colors is based on the "locally
  177887. * sorted search" idea described by Heckbert and on the incremental distance
  177888. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  177889. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  177890. * the distances from a given colormap entry to each cell of the histogram can
  177891. * be computed quickly using an incremental method: the differences between
  177892. * distances to adjacent cells themselves differ by a constant. This allows a
  177893. * fairly fast implementation of the "brute force" approach of computing the
  177894. * distance from every colormap entry to every histogram cell. Unfortunately,
  177895. * it needs a work array to hold the best-distance-so-far for each histogram
  177896. * cell (because the inner loop has to be over cells, not colormap entries).
  177897. * The work array elements have to be INT32s, so the work array would need
  177898. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  177899. *
  177900. * To get around these problems, we apply Thomas' method to compute the
  177901. * nearest colors for only the cells within a small subbox of the histogram.
  177902. * The work array need be only as big as the subbox, so the memory usage
  177903. * problem is solved. Furthermore, we need not fill subboxes that are never
  177904. * referenced in pass2; many images use only part of the color gamut, so a
  177905. * fair amount of work is saved. An additional advantage of this
  177906. * approach is that we can apply Heckbert's locality criterion to quickly
  177907. * eliminate colormap entries that are far away from the subbox; typically
  177908. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  177909. * and we need not compute their distances to individual cells in the subbox.
  177910. * The speed of this approach is heavily influenced by the subbox size: too
  177911. * small means too much overhead, too big loses because Heckbert's criterion
  177912. * can't eliminate as many colormap entries. Empirically the best subbox
  177913. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  177914. *
  177915. * Thomas' article also describes a refined method which is asymptotically
  177916. * faster than the brute-force method, but it is also far more complex and
  177917. * cannot efficiently be applied to small subboxes. It is therefore not
  177918. * useful for programs intended to be portable to DOS machines. On machines
  177919. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  177920. * refined method might be faster than the present code --- but then again,
  177921. * it might not be any faster, and it's certainly more complicated.
  177922. */
  177923. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  177924. #define BOX_C0_LOG (HIST_C0_BITS-3)
  177925. #define BOX_C1_LOG (HIST_C1_BITS-3)
  177926. #define BOX_C2_LOG (HIST_C2_BITS-3)
  177927. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  177928. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  177929. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  177930. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  177931. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  177932. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  177933. /*
  177934. * The next three routines implement inverse colormap filling. They could
  177935. * all be folded into one big routine, but splitting them up this way saves
  177936. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  177937. * and may allow some compilers to produce better code by registerizing more
  177938. * inner-loop variables.
  177939. */
  177940. LOCAL(int)
  177941. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  177942. JSAMPLE colorlist[])
  177943. /* Locate the colormap entries close enough to an update box to be candidates
  177944. * for the nearest entry to some cell(s) in the update box. The update box
  177945. * is specified by the center coordinates of its first cell. The number of
  177946. * candidate colormap entries is returned, and their colormap indexes are
  177947. * placed in colorlist[].
  177948. * This routine uses Heckbert's "locally sorted search" criterion to select
  177949. * the colors that need further consideration.
  177950. */
  177951. {
  177952. int numcolors = cinfo->actual_number_of_colors;
  177953. int maxc0, maxc1, maxc2;
  177954. int centerc0, centerc1, centerc2;
  177955. int i, x, ncolors;
  177956. INT32 minmaxdist, min_dist, max_dist, tdist;
  177957. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  177958. /* Compute true coordinates of update box's upper corner and center.
  177959. * Actually we compute the coordinates of the center of the upper-corner
  177960. * histogram cell, which are the upper bounds of the volume we care about.
  177961. * Note that since ">>" rounds down, the "center" values may be closer to
  177962. * min than to max; hence comparisons to them must be "<=", not "<".
  177963. */
  177964. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  177965. centerc0 = (minc0 + maxc0) >> 1;
  177966. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  177967. centerc1 = (minc1 + maxc1) >> 1;
  177968. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  177969. centerc2 = (minc2 + maxc2) >> 1;
  177970. /* For each color in colormap, find:
  177971. * 1. its minimum squared-distance to any point in the update box
  177972. * (zero if color is within update box);
  177973. * 2. its maximum squared-distance to any point in the update box.
  177974. * Both of these can be found by considering only the corners of the box.
  177975. * We save the minimum distance for each color in mindist[];
  177976. * only the smallest maximum distance is of interest.
  177977. */
  177978. minmaxdist = 0x7FFFFFFFL;
  177979. for (i = 0; i < numcolors; i++) {
  177980. /* We compute the squared-c0-distance term, then add in the other two. */
  177981. x = GETJSAMPLE(cinfo->colormap[0][i]);
  177982. if (x < minc0) {
  177983. tdist = (x - minc0) * C0_SCALE;
  177984. min_dist = tdist*tdist;
  177985. tdist = (x - maxc0) * C0_SCALE;
  177986. max_dist = tdist*tdist;
  177987. } else if (x > maxc0) {
  177988. tdist = (x - maxc0) * C0_SCALE;
  177989. min_dist = tdist*tdist;
  177990. tdist = (x - minc0) * C0_SCALE;
  177991. max_dist = tdist*tdist;
  177992. } else {
  177993. /* within cell range so no contribution to min_dist */
  177994. min_dist = 0;
  177995. if (x <= centerc0) {
  177996. tdist = (x - maxc0) * C0_SCALE;
  177997. max_dist = tdist*tdist;
  177998. } else {
  177999. tdist = (x - minc0) * C0_SCALE;
  178000. max_dist = tdist*tdist;
  178001. }
  178002. }
  178003. x = GETJSAMPLE(cinfo->colormap[1][i]);
  178004. if (x < minc1) {
  178005. tdist = (x - minc1) * C1_SCALE;
  178006. min_dist += tdist*tdist;
  178007. tdist = (x - maxc1) * C1_SCALE;
  178008. max_dist += tdist*tdist;
  178009. } else if (x > maxc1) {
  178010. tdist = (x - maxc1) * C1_SCALE;
  178011. min_dist += tdist*tdist;
  178012. tdist = (x - minc1) * C1_SCALE;
  178013. max_dist += tdist*tdist;
  178014. } else {
  178015. /* within cell range so no contribution to min_dist */
  178016. if (x <= centerc1) {
  178017. tdist = (x - maxc1) * C1_SCALE;
  178018. max_dist += tdist*tdist;
  178019. } else {
  178020. tdist = (x - minc1) * C1_SCALE;
  178021. max_dist += tdist*tdist;
  178022. }
  178023. }
  178024. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178025. if (x < minc2) {
  178026. tdist = (x - minc2) * C2_SCALE;
  178027. min_dist += tdist*tdist;
  178028. tdist = (x - maxc2) * C2_SCALE;
  178029. max_dist += tdist*tdist;
  178030. } else if (x > maxc2) {
  178031. tdist = (x - maxc2) * C2_SCALE;
  178032. min_dist += tdist*tdist;
  178033. tdist = (x - minc2) * C2_SCALE;
  178034. max_dist += tdist*tdist;
  178035. } else {
  178036. /* within cell range so no contribution to min_dist */
  178037. if (x <= centerc2) {
  178038. tdist = (x - maxc2) * C2_SCALE;
  178039. max_dist += tdist*tdist;
  178040. } else {
  178041. tdist = (x - minc2) * C2_SCALE;
  178042. max_dist += tdist*tdist;
  178043. }
  178044. }
  178045. mindist[i] = min_dist; /* save away the results */
  178046. if (max_dist < minmaxdist)
  178047. minmaxdist = max_dist;
  178048. }
  178049. /* Now we know that no cell in the update box is more than minmaxdist
  178050. * away from some colormap entry. Therefore, only colors that are
  178051. * within minmaxdist of some part of the box need be considered.
  178052. */
  178053. ncolors = 0;
  178054. for (i = 0; i < numcolors; i++) {
  178055. if (mindist[i] <= minmaxdist)
  178056. colorlist[ncolors++] = (JSAMPLE) i;
  178057. }
  178058. return ncolors;
  178059. }
  178060. LOCAL(void)
  178061. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178062. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178063. /* Find the closest colormap entry for each cell in the update box,
  178064. * given the list of candidate colors prepared by find_nearby_colors.
  178065. * Return the indexes of the closest entries in the bestcolor[] array.
  178066. * This routine uses Thomas' incremental distance calculation method to
  178067. * find the distance from a colormap entry to successive cells in the box.
  178068. */
  178069. {
  178070. int ic0, ic1, ic2;
  178071. int i, icolor;
  178072. register INT32 * bptr; /* pointer into bestdist[] array */
  178073. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178074. INT32 dist0, dist1; /* initial distance values */
  178075. register INT32 dist2; /* current distance in inner loop */
  178076. INT32 xx0, xx1; /* distance increments */
  178077. register INT32 xx2;
  178078. INT32 inc0, inc1, inc2; /* initial values for increments */
  178079. /* This array holds the distance to the nearest-so-far color for each cell */
  178080. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178081. /* Initialize best-distance for each cell of the update box */
  178082. bptr = bestdist;
  178083. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178084. *bptr++ = 0x7FFFFFFFL;
  178085. /* For each color selected by find_nearby_colors,
  178086. * compute its distance to the center of each cell in the box.
  178087. * If that's less than best-so-far, update best distance and color number.
  178088. */
  178089. /* Nominal steps between cell centers ("x" in Thomas article) */
  178090. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178091. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178092. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178093. for (i = 0; i < numcolors; i++) {
  178094. icolor = GETJSAMPLE(colorlist[i]);
  178095. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178096. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178097. dist0 = inc0*inc0;
  178098. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178099. dist0 += inc1*inc1;
  178100. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178101. dist0 += inc2*inc2;
  178102. /* Form the initial difference increments */
  178103. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178104. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178105. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178106. /* Now loop over all cells in box, updating distance per Thomas method */
  178107. bptr = bestdist;
  178108. cptr = bestcolor;
  178109. xx0 = inc0;
  178110. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178111. dist1 = dist0;
  178112. xx1 = inc1;
  178113. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178114. dist2 = dist1;
  178115. xx2 = inc2;
  178116. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178117. if (dist2 < *bptr) {
  178118. *bptr = dist2;
  178119. *cptr = (JSAMPLE) icolor;
  178120. }
  178121. dist2 += xx2;
  178122. xx2 += 2 * STEP_C2 * STEP_C2;
  178123. bptr++;
  178124. cptr++;
  178125. }
  178126. dist1 += xx1;
  178127. xx1 += 2 * STEP_C1 * STEP_C1;
  178128. }
  178129. dist0 += xx0;
  178130. xx0 += 2 * STEP_C0 * STEP_C0;
  178131. }
  178132. }
  178133. }
  178134. LOCAL(void)
  178135. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178136. /* Fill the inverse-colormap entries in the update box that contains */
  178137. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178138. /* we can fill as many others as we wish.) */
  178139. {
  178140. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178141. hist3d histogram = cquantize->histogram;
  178142. int minc0, minc1, minc2; /* lower left corner of update box */
  178143. int ic0, ic1, ic2;
  178144. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178145. register histptr cachep; /* pointer into main cache array */
  178146. /* This array lists the candidate colormap indexes. */
  178147. JSAMPLE colorlist[MAXNUMCOLORS];
  178148. int numcolors; /* number of candidate colors */
  178149. /* This array holds the actually closest colormap index for each cell. */
  178150. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178151. /* Convert cell coordinates to update box ID */
  178152. c0 >>= BOX_C0_LOG;
  178153. c1 >>= BOX_C1_LOG;
  178154. c2 >>= BOX_C2_LOG;
  178155. /* Compute true coordinates of update box's origin corner.
  178156. * Actually we compute the coordinates of the center of the corner
  178157. * histogram cell, which are the lower bounds of the volume we care about.
  178158. */
  178159. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178160. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178161. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178162. /* Determine which colormap entries are close enough to be candidates
  178163. * for the nearest entry to some cell in the update box.
  178164. */
  178165. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178166. /* Determine the actually nearest colors. */
  178167. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178168. bestcolor);
  178169. /* Save the best color numbers (plus 1) in the main cache array */
  178170. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178171. c1 <<= BOX_C1_LOG;
  178172. c2 <<= BOX_C2_LOG;
  178173. cptr = bestcolor;
  178174. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178175. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178176. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178177. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178178. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178179. }
  178180. }
  178181. }
  178182. }
  178183. /*
  178184. * Map some rows of pixels to the output colormapped representation.
  178185. */
  178186. METHODDEF(void)
  178187. pass2_no_dither (j_decompress_ptr cinfo,
  178188. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178189. /* This version performs no dithering */
  178190. {
  178191. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178192. hist3d histogram = cquantize->histogram;
  178193. register JSAMPROW inptr, outptr;
  178194. register histptr cachep;
  178195. register int c0, c1, c2;
  178196. int row;
  178197. JDIMENSION col;
  178198. JDIMENSION width = cinfo->output_width;
  178199. for (row = 0; row < num_rows; row++) {
  178200. inptr = input_buf[row];
  178201. outptr = output_buf[row];
  178202. for (col = width; col > 0; col--) {
  178203. /* get pixel value and index into the cache */
  178204. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178205. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178206. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178207. cachep = & histogram[c0][c1][c2];
  178208. /* If we have not seen this color before, find nearest colormap entry */
  178209. /* and update the cache */
  178210. if (*cachep == 0)
  178211. fill_inverse_cmap(cinfo, c0,c1,c2);
  178212. /* Now emit the colormap index for this cell */
  178213. *outptr++ = (JSAMPLE) (*cachep - 1);
  178214. }
  178215. }
  178216. }
  178217. METHODDEF(void)
  178218. pass2_fs_dither (j_decompress_ptr cinfo,
  178219. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178220. /* This version performs Floyd-Steinberg dithering */
  178221. {
  178222. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178223. hist3d histogram = cquantize->histogram;
  178224. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178225. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178226. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178227. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178228. JSAMPROW inptr; /* => current input pixel */
  178229. JSAMPROW outptr; /* => current output pixel */
  178230. histptr cachep;
  178231. int dir; /* +1 or -1 depending on direction */
  178232. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178233. int row;
  178234. JDIMENSION col;
  178235. JDIMENSION width = cinfo->output_width;
  178236. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178237. int *error_limit = cquantize->error_limiter;
  178238. JSAMPROW colormap0 = cinfo->colormap[0];
  178239. JSAMPROW colormap1 = cinfo->colormap[1];
  178240. JSAMPROW colormap2 = cinfo->colormap[2];
  178241. SHIFT_TEMPS
  178242. for (row = 0; row < num_rows; row++) {
  178243. inptr = input_buf[row];
  178244. outptr = output_buf[row];
  178245. if (cquantize->on_odd_row) {
  178246. /* work right to left in this row */
  178247. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178248. outptr += width-1;
  178249. dir = -1;
  178250. dir3 = -3;
  178251. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178252. cquantize->on_odd_row = FALSE; /* flip for next time */
  178253. } else {
  178254. /* work left to right in this row */
  178255. dir = 1;
  178256. dir3 = 3;
  178257. errorptr = cquantize->fserrors; /* => entry before first real column */
  178258. cquantize->on_odd_row = TRUE; /* flip for next time */
  178259. }
  178260. /* Preset error values: no error propagated to first pixel from left */
  178261. cur0 = cur1 = cur2 = 0;
  178262. /* and no error propagated to row below yet */
  178263. belowerr0 = belowerr1 = belowerr2 = 0;
  178264. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178265. for (col = width; col > 0; col--) {
  178266. /* curN holds the error propagated from the previous pixel on the
  178267. * current line. Add the error propagated from the previous line
  178268. * to form the complete error correction term for this pixel, and
  178269. * round the error term (which is expressed * 16) to an integer.
  178270. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178271. * for either sign of the error value.
  178272. * Note: errorptr points to *previous* column's array entry.
  178273. */
  178274. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178275. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178276. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178277. /* Limit the error using transfer function set by init_error_limit.
  178278. * See comments with init_error_limit for rationale.
  178279. */
  178280. cur0 = error_limit[cur0];
  178281. cur1 = error_limit[cur1];
  178282. cur2 = error_limit[cur2];
  178283. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178284. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178285. * this sets the required size of the range_limit array.
  178286. */
  178287. cur0 += GETJSAMPLE(inptr[0]);
  178288. cur1 += GETJSAMPLE(inptr[1]);
  178289. cur2 += GETJSAMPLE(inptr[2]);
  178290. cur0 = GETJSAMPLE(range_limit[cur0]);
  178291. cur1 = GETJSAMPLE(range_limit[cur1]);
  178292. cur2 = GETJSAMPLE(range_limit[cur2]);
  178293. /* Index into the cache with adjusted pixel value */
  178294. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178295. /* If we have not seen this color before, find nearest colormap */
  178296. /* entry and update the cache */
  178297. if (*cachep == 0)
  178298. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178299. /* Now emit the colormap index for this cell */
  178300. { register int pixcode = *cachep - 1;
  178301. *outptr = (JSAMPLE) pixcode;
  178302. /* Compute representation error for this pixel */
  178303. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178304. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178305. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178306. }
  178307. /* Compute error fractions to be propagated to adjacent pixels.
  178308. * Add these into the running sums, and simultaneously shift the
  178309. * next-line error sums left by 1 column.
  178310. */
  178311. { register LOCFSERROR bnexterr, delta;
  178312. bnexterr = cur0; /* Process component 0 */
  178313. delta = cur0 * 2;
  178314. cur0 += delta; /* form error * 3 */
  178315. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178316. cur0 += delta; /* form error * 5 */
  178317. bpreverr0 = belowerr0 + cur0;
  178318. belowerr0 = bnexterr;
  178319. cur0 += delta; /* form error * 7 */
  178320. bnexterr = cur1; /* Process component 1 */
  178321. delta = cur1 * 2;
  178322. cur1 += delta; /* form error * 3 */
  178323. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178324. cur1 += delta; /* form error * 5 */
  178325. bpreverr1 = belowerr1 + cur1;
  178326. belowerr1 = bnexterr;
  178327. cur1 += delta; /* form error * 7 */
  178328. bnexterr = cur2; /* Process component 2 */
  178329. delta = cur2 * 2;
  178330. cur2 += delta; /* form error * 3 */
  178331. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178332. cur2 += delta; /* form error * 5 */
  178333. bpreverr2 = belowerr2 + cur2;
  178334. belowerr2 = bnexterr;
  178335. cur2 += delta; /* form error * 7 */
  178336. }
  178337. /* At this point curN contains the 7/16 error value to be propagated
  178338. * to the next pixel on the current line, and all the errors for the
  178339. * next line have been shifted over. We are therefore ready to move on.
  178340. */
  178341. inptr += dir3; /* Advance pixel pointers to next column */
  178342. outptr += dir;
  178343. errorptr += dir3; /* advance errorptr to current column */
  178344. }
  178345. /* Post-loop cleanup: we must unload the final error values into the
  178346. * final fserrors[] entry. Note we need not unload belowerrN because
  178347. * it is for the dummy column before or after the actual array.
  178348. */
  178349. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178350. errorptr[1] = (FSERROR) bpreverr1;
  178351. errorptr[2] = (FSERROR) bpreverr2;
  178352. }
  178353. }
  178354. /*
  178355. * Initialize the error-limiting transfer function (lookup table).
  178356. * The raw F-S error computation can potentially compute error values of up to
  178357. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178358. * much less, otherwise obviously wrong pixels will be created. (Typical
  178359. * effects include weird fringes at color-area boundaries, isolated bright
  178360. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178361. * is to ensure that the "corners" of the color cube are allocated as output
  178362. * colors; then repeated errors in the same direction cannot cause cascading
  178363. * error buildup. However, that only prevents the error from getting
  178364. * completely out of hand; Aaron Giles reports that error limiting improves
  178365. * the results even with corner colors allocated.
  178366. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178367. * well, but the smoother transfer function used below is even better. Thanks
  178368. * to Aaron Giles for this idea.
  178369. */
  178370. LOCAL(void)
  178371. init_error_limit (j_decompress_ptr cinfo)
  178372. /* Allocate and fill in the error_limiter table */
  178373. {
  178374. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178375. int * table;
  178376. int in, out;
  178377. table = (int *) (*cinfo->mem->alloc_small)
  178378. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178379. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178380. cquantize->error_limiter = table;
  178381. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178382. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178383. out = 0;
  178384. for (in = 0; in < STEPSIZE; in++, out++) {
  178385. table[in] = out; table[-in] = -out;
  178386. }
  178387. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178388. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178389. table[in] = out; table[-in] = -out;
  178390. }
  178391. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178392. for (; in <= MAXJSAMPLE; in++) {
  178393. table[in] = out; table[-in] = -out;
  178394. }
  178395. #undef STEPSIZE
  178396. }
  178397. /*
  178398. * Finish up at the end of each pass.
  178399. */
  178400. METHODDEF(void)
  178401. finish_pass1 (j_decompress_ptr cinfo)
  178402. {
  178403. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178404. /* Select the representative colors and fill in cinfo->colormap */
  178405. cinfo->colormap = cquantize->sv_colormap;
  178406. select_colors(cinfo, cquantize->desired);
  178407. /* Force next pass to zero the color index table */
  178408. cquantize->needs_zeroed = TRUE;
  178409. }
  178410. METHODDEF(void)
  178411. finish_pass2 (j_decompress_ptr)
  178412. {
  178413. /* no work */
  178414. }
  178415. /*
  178416. * Initialize for each processing pass.
  178417. */
  178418. METHODDEF(void)
  178419. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178420. {
  178421. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178422. hist3d histogram = cquantize->histogram;
  178423. int i;
  178424. /* Only F-S dithering or no dithering is supported. */
  178425. /* If user asks for ordered dither, give him F-S. */
  178426. if (cinfo->dither_mode != JDITHER_NONE)
  178427. cinfo->dither_mode = JDITHER_FS;
  178428. if (is_pre_scan) {
  178429. /* Set up method pointers */
  178430. cquantize->pub.color_quantize = prescan_quantize;
  178431. cquantize->pub.finish_pass = finish_pass1;
  178432. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178433. } else {
  178434. /* Set up method pointers */
  178435. if (cinfo->dither_mode == JDITHER_FS)
  178436. cquantize->pub.color_quantize = pass2_fs_dither;
  178437. else
  178438. cquantize->pub.color_quantize = pass2_no_dither;
  178439. cquantize->pub.finish_pass = finish_pass2;
  178440. /* Make sure color count is acceptable */
  178441. i = cinfo->actual_number_of_colors;
  178442. if (i < 1)
  178443. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178444. if (i > MAXNUMCOLORS)
  178445. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178446. if (cinfo->dither_mode == JDITHER_FS) {
  178447. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178448. (3 * SIZEOF(FSERROR)));
  178449. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178450. if (cquantize->fserrors == NULL)
  178451. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178452. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178453. /* Initialize the propagated errors to zero. */
  178454. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178455. /* Make the error-limit table if we didn't already. */
  178456. if (cquantize->error_limiter == NULL)
  178457. init_error_limit(cinfo);
  178458. cquantize->on_odd_row = FALSE;
  178459. }
  178460. }
  178461. /* Zero the histogram or inverse color map, if necessary */
  178462. if (cquantize->needs_zeroed) {
  178463. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178464. jzero_far((void FAR *) histogram[i],
  178465. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178466. }
  178467. cquantize->needs_zeroed = FALSE;
  178468. }
  178469. }
  178470. /*
  178471. * Switch to a new external colormap between output passes.
  178472. */
  178473. METHODDEF(void)
  178474. new_color_map_2_quant (j_decompress_ptr cinfo)
  178475. {
  178476. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178477. /* Reset the inverse color map */
  178478. cquantize->needs_zeroed = TRUE;
  178479. }
  178480. /*
  178481. * Module initialization routine for 2-pass color quantization.
  178482. */
  178483. GLOBAL(void)
  178484. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178485. {
  178486. my_cquantize_ptr2 cquantize;
  178487. int i;
  178488. cquantize = (my_cquantize_ptr2)
  178489. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178490. SIZEOF(my_cquantizer2));
  178491. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178492. cquantize->pub.start_pass = start_pass_2_quant;
  178493. cquantize->pub.new_color_map = new_color_map_2_quant;
  178494. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  178495. cquantize->error_limiter = NULL;
  178496. /* Make sure jdmaster didn't give me a case I can't handle */
  178497. if (cinfo->out_color_components != 3)
  178498. ERREXIT(cinfo, JERR_NOTIMPL);
  178499. /* Allocate the histogram/inverse colormap storage */
  178500. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  178501. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  178502. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178503. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  178504. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178505. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178506. }
  178507. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  178508. /* Allocate storage for the completed colormap, if required.
  178509. * We do this now since it is FAR storage and may affect
  178510. * the memory manager's space calculations.
  178511. */
  178512. if (cinfo->enable_2pass_quant) {
  178513. /* Make sure color count is acceptable */
  178514. int desired = cinfo->desired_number_of_colors;
  178515. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  178516. if (desired < 8)
  178517. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  178518. /* Make sure colormap indexes can be represented by JSAMPLEs */
  178519. if (desired > MAXNUMCOLORS)
  178520. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178521. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  178522. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  178523. cquantize->desired = desired;
  178524. } else
  178525. cquantize->sv_colormap = NULL;
  178526. /* Only F-S dithering or no dithering is supported. */
  178527. /* If user asks for ordered dither, give him F-S. */
  178528. if (cinfo->dither_mode != JDITHER_NONE)
  178529. cinfo->dither_mode = JDITHER_FS;
  178530. /* Allocate Floyd-Steinberg workspace if necessary.
  178531. * This isn't really needed until pass 2, but again it is FAR storage.
  178532. * Although we will cope with a later change in dither_mode,
  178533. * we do not promise to honor max_memory_to_use if dither_mode changes.
  178534. */
  178535. if (cinfo->dither_mode == JDITHER_FS) {
  178536. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178537. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178538. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  178539. /* Might as well create the error-limiting table too. */
  178540. init_error_limit(cinfo);
  178541. }
  178542. }
  178543. #endif /* QUANT_2PASS_SUPPORTED */
  178544. /*** End of inlined file: jquant2.c ***/
  178545. /*** Start of inlined file: jutils.c ***/
  178546. #define JPEG_INTERNALS
  178547. /*
  178548. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  178549. * of a DCT block read in natural order (left to right, top to bottom).
  178550. */
  178551. #if 0 /* This table is not actually needed in v6a */
  178552. const int jpeg_zigzag_order[DCTSIZE2] = {
  178553. 0, 1, 5, 6, 14, 15, 27, 28,
  178554. 2, 4, 7, 13, 16, 26, 29, 42,
  178555. 3, 8, 12, 17, 25, 30, 41, 43,
  178556. 9, 11, 18, 24, 31, 40, 44, 53,
  178557. 10, 19, 23, 32, 39, 45, 52, 54,
  178558. 20, 22, 33, 38, 46, 51, 55, 60,
  178559. 21, 34, 37, 47, 50, 56, 59, 61,
  178560. 35, 36, 48, 49, 57, 58, 62, 63
  178561. };
  178562. #endif
  178563. /*
  178564. * jpeg_natural_order[i] is the natural-order position of the i'th element
  178565. * of zigzag order.
  178566. *
  178567. * When reading corrupted data, the Huffman decoders could attempt
  178568. * to reference an entry beyond the end of this array (if the decoded
  178569. * zero run length reaches past the end of the block). To prevent
  178570. * wild stores without adding an inner-loop test, we put some extra
  178571. * "63"s after the real entries. This will cause the extra coefficient
  178572. * to be stored in location 63 of the block, not somewhere random.
  178573. * The worst case would be a run-length of 15, which means we need 16
  178574. * fake entries.
  178575. */
  178576. const int jpeg_natural_order[DCTSIZE2+16] = {
  178577. 0, 1, 8, 16, 9, 2, 3, 10,
  178578. 17, 24, 32, 25, 18, 11, 4, 5,
  178579. 12, 19, 26, 33, 40, 48, 41, 34,
  178580. 27, 20, 13, 6, 7, 14, 21, 28,
  178581. 35, 42, 49, 56, 57, 50, 43, 36,
  178582. 29, 22, 15, 23, 30, 37, 44, 51,
  178583. 58, 59, 52, 45, 38, 31, 39, 46,
  178584. 53, 60, 61, 54, 47, 55, 62, 63,
  178585. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  178586. 63, 63, 63, 63, 63, 63, 63, 63
  178587. };
  178588. /*
  178589. * Arithmetic utilities
  178590. */
  178591. GLOBAL(long)
  178592. jdiv_round_up (long a, long b)
  178593. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  178594. /* Assumes a >= 0, b > 0 */
  178595. {
  178596. return (a + b - 1L) / b;
  178597. }
  178598. GLOBAL(long)
  178599. jround_up (long a, long b)
  178600. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  178601. /* Assumes a >= 0, b > 0 */
  178602. {
  178603. a += b - 1L;
  178604. return a - (a % b);
  178605. }
  178606. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  178607. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  178608. * are FAR and we're assuming a small-pointer memory model. However, some
  178609. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  178610. * in the small-model libraries. These will be used if USE_FMEM is defined.
  178611. * Otherwise, the routines below do it the hard way. (The performance cost
  178612. * is not all that great, because these routines aren't very heavily used.)
  178613. */
  178614. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  178615. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  178616. #define FMEMZERO(target,size) MEMZERO(target,size)
  178617. #else /* 80x86 case, define if we can */
  178618. #ifdef USE_FMEM
  178619. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  178620. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  178621. #endif
  178622. #endif
  178623. GLOBAL(void)
  178624. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  178625. JSAMPARRAY output_array, int dest_row,
  178626. int num_rows, JDIMENSION num_cols)
  178627. /* Copy some rows of samples from one place to another.
  178628. * num_rows rows are copied from input_array[source_row++]
  178629. * to output_array[dest_row++]; these areas may overlap for duplication.
  178630. * The source and destination arrays must be at least as wide as num_cols.
  178631. */
  178632. {
  178633. register JSAMPROW inptr, outptr;
  178634. #ifdef FMEMCOPY
  178635. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  178636. #else
  178637. register JDIMENSION count;
  178638. #endif
  178639. register int row;
  178640. input_array += source_row;
  178641. output_array += dest_row;
  178642. for (row = num_rows; row > 0; row--) {
  178643. inptr = *input_array++;
  178644. outptr = *output_array++;
  178645. #ifdef FMEMCOPY
  178646. FMEMCOPY(outptr, inptr, count);
  178647. #else
  178648. for (count = num_cols; count > 0; count--)
  178649. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  178650. #endif
  178651. }
  178652. }
  178653. GLOBAL(void)
  178654. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  178655. JDIMENSION num_blocks)
  178656. /* Copy a row of coefficient blocks from one place to another. */
  178657. {
  178658. #ifdef FMEMCOPY
  178659. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  178660. #else
  178661. register JCOEFPTR inptr, outptr;
  178662. register long count;
  178663. inptr = (JCOEFPTR) input_row;
  178664. outptr = (JCOEFPTR) output_row;
  178665. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  178666. *outptr++ = *inptr++;
  178667. }
  178668. #endif
  178669. }
  178670. GLOBAL(void)
  178671. jzero_far (void FAR * target, size_t bytestozero)
  178672. /* Zero out a chunk of FAR memory. */
  178673. /* This might be sample-array data, block-array data, or alloc_large data. */
  178674. {
  178675. #ifdef FMEMZERO
  178676. FMEMZERO(target, bytestozero);
  178677. #else
  178678. register char FAR * ptr = (char FAR *) target;
  178679. register size_t count;
  178680. for (count = bytestozero; count > 0; count--) {
  178681. *ptr++ = 0;
  178682. }
  178683. #endif
  178684. }
  178685. /*** End of inlined file: jutils.c ***/
  178686. /*** Start of inlined file: transupp.c ***/
  178687. /* Although this file really shouldn't have access to the library internals,
  178688. * it's helpful to let it call jround_up() and jcopy_block_row().
  178689. */
  178690. #define JPEG_INTERNALS
  178691. /*** Start of inlined file: transupp.h ***/
  178692. /* If you happen not to want the image transform support, disable it here */
  178693. #ifndef TRANSFORMS_SUPPORTED
  178694. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  178695. #endif
  178696. /* Short forms of external names for systems with brain-damaged linkers. */
  178697. #ifdef NEED_SHORT_EXTERNAL_NAMES
  178698. #define jtransform_request_workspace jTrRequest
  178699. #define jtransform_adjust_parameters jTrAdjust
  178700. #define jtransform_execute_transformation jTrExec
  178701. #define jcopy_markers_setup jCMrkSetup
  178702. #define jcopy_markers_execute jCMrkExec
  178703. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  178704. /*
  178705. * Codes for supported types of image transformations.
  178706. */
  178707. typedef enum {
  178708. JXFORM_NONE, /* no transformation */
  178709. JXFORM_FLIP_H, /* horizontal flip */
  178710. JXFORM_FLIP_V, /* vertical flip */
  178711. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  178712. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  178713. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  178714. JXFORM_ROT_180, /* 180-degree rotation */
  178715. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  178716. } JXFORM_CODE;
  178717. /*
  178718. * Although rotating and flipping data expressed as DCT coefficients is not
  178719. * hard, there is an asymmetry in the JPEG format specification for images
  178720. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  178721. * image edges are padded out to the next iMCU boundary with junk data; but
  178722. * no padding is possible at the top and left edges. If we were to flip
  178723. * the whole image including the pad data, then pad garbage would become
  178724. * visible at the top and/or left, and real pixels would disappear into the
  178725. * pad margins --- perhaps permanently, since encoders & decoders may not
  178726. * bother to preserve DCT blocks that appear to be completely outside the
  178727. * nominal image area. So, we have to exclude any partial iMCUs from the
  178728. * basic transformation.
  178729. *
  178730. * Transpose is the only transformation that can handle partial iMCUs at the
  178731. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  178732. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  178733. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  178734. * The other transforms are defined as combinations of these basic transforms
  178735. * and process edge blocks in a way that preserves the equivalence.
  178736. *
  178737. * The "trim" option causes untransformable partial iMCUs to be dropped;
  178738. * this is not strictly lossless, but it usually gives the best-looking
  178739. * result for odd-size images. Note that when this option is active,
  178740. * the expected mathematical equivalences between the transforms may not hold.
  178741. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  178742. * followed by -rot 180 -trim trims both edges.)
  178743. *
  178744. * We also offer a "force to grayscale" option, which simply discards the
  178745. * chrominance channels of a YCbCr image. This is lossless in the sense that
  178746. * the luminance channel is preserved exactly. It's not the same kind of
  178747. * thing as the rotate/flip transformations, but it's convenient to handle it
  178748. * as part of this package, mainly because the transformation routines have to
  178749. * be aware of the option to know how many components to work on.
  178750. */
  178751. typedef struct {
  178752. /* Options: set by caller */
  178753. JXFORM_CODE transform; /* image transform operator */
  178754. boolean trim; /* if TRUE, trim partial MCUs as needed */
  178755. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  178756. /* Internal workspace: caller should not touch these */
  178757. int num_components; /* # of components in workspace */
  178758. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  178759. } jpeg_transform_info;
  178760. #if TRANSFORMS_SUPPORTED
  178761. /* Request any required workspace */
  178762. EXTERN(void) jtransform_request_workspace
  178763. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  178764. /* Adjust output image parameters */
  178765. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  178766. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178767. jvirt_barray_ptr *src_coef_arrays,
  178768. jpeg_transform_info *info));
  178769. /* Execute the actual transformation, if any */
  178770. EXTERN(void) jtransform_execute_transformation
  178771. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178772. jvirt_barray_ptr *src_coef_arrays,
  178773. jpeg_transform_info *info));
  178774. #endif /* TRANSFORMS_SUPPORTED */
  178775. /*
  178776. * Support for copying optional markers from source to destination file.
  178777. */
  178778. typedef enum {
  178779. JCOPYOPT_NONE, /* copy no optional markers */
  178780. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  178781. JCOPYOPT_ALL /* copy all optional markers */
  178782. } JCOPY_OPTION;
  178783. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  178784. /* Setup decompression object to save desired markers in memory */
  178785. EXTERN(void) jcopy_markers_setup
  178786. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  178787. /* Copy markers saved in the given source object to the destination object */
  178788. EXTERN(void) jcopy_markers_execute
  178789. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178790. JCOPY_OPTION option));
  178791. /*** End of inlined file: transupp.h ***/
  178792. /* My own external interface */
  178793. #if TRANSFORMS_SUPPORTED
  178794. /*
  178795. * Lossless image transformation routines. These routines work on DCT
  178796. * coefficient arrays and thus do not require any lossy decompression
  178797. * or recompression of the image.
  178798. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  178799. *
  178800. * Horizontal flipping is done in-place, using a single top-to-bottom
  178801. * pass through the virtual source array. It will thus be much the
  178802. * fastest option for images larger than main memory.
  178803. *
  178804. * The other routines require a set of destination virtual arrays, so they
  178805. * need twice as much memory as jpegtran normally does. The destination
  178806. * arrays are always written in normal scan order (top to bottom) because
  178807. * the virtual array manager expects this. The source arrays will be scanned
  178808. * in the corresponding order, which means multiple passes through the source
  178809. * arrays for most of the transforms. That could result in much thrashing
  178810. * if the image is larger than main memory.
  178811. *
  178812. * Some notes about the operating environment of the individual transform
  178813. * routines:
  178814. * 1. Both the source and destination virtual arrays are allocated from the
  178815. * source JPEG object, and therefore should be manipulated by calling the
  178816. * source's memory manager.
  178817. * 2. The destination's component count should be used. It may be smaller
  178818. * than the source's when forcing to grayscale.
  178819. * 3. Likewise the destination's sampling factors should be used. When
  178820. * forcing to grayscale the destination's sampling factors will be all 1,
  178821. * and we may as well take that as the effective iMCU size.
  178822. * 4. When "trim" is in effect, the destination's dimensions will be the
  178823. * trimmed values but the source's will be untrimmed.
  178824. * 5. All the routines assume that the source and destination buffers are
  178825. * padded out to a full iMCU boundary. This is true, although for the
  178826. * source buffer it is an undocumented property of jdcoefct.c.
  178827. * Notes 2,3,4 boil down to this: generally we should use the destination's
  178828. * dimensions and ignore the source's.
  178829. */
  178830. LOCAL(void)
  178831. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178832. jvirt_barray_ptr *src_coef_arrays)
  178833. /* Horizontal flip; done in-place, so no separate dest array is required */
  178834. {
  178835. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  178836. int ci, k, offset_y;
  178837. JBLOCKARRAY buffer;
  178838. JCOEFPTR ptr1, ptr2;
  178839. JCOEF temp1, temp2;
  178840. jpeg_component_info *compptr;
  178841. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  178842. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  178843. * mirroring by changing the signs of odd-numbered columns.
  178844. * Partial iMCUs at the right edge are left untouched.
  178845. */
  178846. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178847. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178848. compptr = dstinfo->comp_info + ci;
  178849. comp_width = MCU_cols * compptr->h_samp_factor;
  178850. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  178851. blk_y += compptr->v_samp_factor) {
  178852. buffer = (*srcinfo->mem->access_virt_barray)
  178853. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  178854. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178855. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178856. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  178857. ptr1 = buffer[offset_y][blk_x];
  178858. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  178859. /* this unrolled loop doesn't need to know which row it's on... */
  178860. for (k = 0; k < DCTSIZE2; k += 2) {
  178861. temp1 = *ptr1; /* swap even column */
  178862. temp2 = *ptr2;
  178863. *ptr1++ = temp2;
  178864. *ptr2++ = temp1;
  178865. temp1 = *ptr1; /* swap odd column with sign change */
  178866. temp2 = *ptr2;
  178867. *ptr1++ = -temp2;
  178868. *ptr2++ = -temp1;
  178869. }
  178870. }
  178871. }
  178872. }
  178873. }
  178874. }
  178875. LOCAL(void)
  178876. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178877. jvirt_barray_ptr *src_coef_arrays,
  178878. jvirt_barray_ptr *dst_coef_arrays)
  178879. /* Vertical flip */
  178880. {
  178881. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  178882. int ci, i, j, offset_y;
  178883. JBLOCKARRAY src_buffer, dst_buffer;
  178884. JBLOCKROW src_row_ptr, dst_row_ptr;
  178885. JCOEFPTR src_ptr, dst_ptr;
  178886. jpeg_component_info *compptr;
  178887. /* We output into a separate array because we can't touch different
  178888. * rows of the source virtual array simultaneously. Otherwise, this
  178889. * is a pretty straightforward analog of horizontal flip.
  178890. * Within a DCT block, vertical mirroring is done by changing the signs
  178891. * of odd-numbered rows.
  178892. * Partial iMCUs at the bottom edge are copied verbatim.
  178893. */
  178894. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178895. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178896. compptr = dstinfo->comp_info + ci;
  178897. comp_height = MCU_rows * compptr->v_samp_factor;
  178898. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178899. dst_blk_y += compptr->v_samp_factor) {
  178900. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178901. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178902. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178903. if (dst_blk_y < comp_height) {
  178904. /* Row is within the mirrorable area. */
  178905. src_buffer = (*srcinfo->mem->access_virt_barray)
  178906. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  178907. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  178908. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178909. } else {
  178910. /* Bottom-edge blocks will be copied verbatim. */
  178911. src_buffer = (*srcinfo->mem->access_virt_barray)
  178912. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  178913. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178914. }
  178915. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178916. if (dst_blk_y < comp_height) {
  178917. /* Row is within the mirrorable area. */
  178918. dst_row_ptr = dst_buffer[offset_y];
  178919. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  178920. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178921. dst_blk_x++) {
  178922. dst_ptr = dst_row_ptr[dst_blk_x];
  178923. src_ptr = src_row_ptr[dst_blk_x];
  178924. for (i = 0; i < DCTSIZE; i += 2) {
  178925. /* copy even row */
  178926. for (j = 0; j < DCTSIZE; j++)
  178927. *dst_ptr++ = *src_ptr++;
  178928. /* copy odd row with sign change */
  178929. for (j = 0; j < DCTSIZE; j++)
  178930. *dst_ptr++ = - *src_ptr++;
  178931. }
  178932. }
  178933. } else {
  178934. /* Just copy row verbatim. */
  178935. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  178936. compptr->width_in_blocks);
  178937. }
  178938. }
  178939. }
  178940. }
  178941. }
  178942. LOCAL(void)
  178943. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178944. jvirt_barray_ptr *src_coef_arrays,
  178945. jvirt_barray_ptr *dst_coef_arrays)
  178946. /* Transpose source into destination */
  178947. {
  178948. JDIMENSION dst_blk_x, dst_blk_y;
  178949. int ci, i, j, offset_x, offset_y;
  178950. JBLOCKARRAY src_buffer, dst_buffer;
  178951. JCOEFPTR src_ptr, dst_ptr;
  178952. jpeg_component_info *compptr;
  178953. /* Transposing pixels within a block just requires transposing the
  178954. * DCT coefficients.
  178955. * Partial iMCUs at the edges require no special treatment; we simply
  178956. * process all the available DCT blocks for every component.
  178957. */
  178958. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178959. compptr = dstinfo->comp_info + ci;
  178960. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178961. dst_blk_y += compptr->v_samp_factor) {
  178962. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178963. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178964. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178965. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178966. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178967. dst_blk_x += compptr->h_samp_factor) {
  178968. src_buffer = (*srcinfo->mem->access_virt_barray)
  178969. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178970. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178971. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178972. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178973. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178974. for (i = 0; i < DCTSIZE; i++)
  178975. for (j = 0; j < DCTSIZE; j++)
  178976. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178977. }
  178978. }
  178979. }
  178980. }
  178981. }
  178982. }
  178983. LOCAL(void)
  178984. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178985. jvirt_barray_ptr *src_coef_arrays,
  178986. jvirt_barray_ptr *dst_coef_arrays)
  178987. /* 90 degree rotation is equivalent to
  178988. * 1. Transposing the image;
  178989. * 2. Horizontal mirroring.
  178990. * These two steps are merged into a single processing routine.
  178991. */
  178992. {
  178993. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  178994. int ci, i, j, offset_x, offset_y;
  178995. JBLOCKARRAY src_buffer, dst_buffer;
  178996. JCOEFPTR src_ptr, dst_ptr;
  178997. jpeg_component_info *compptr;
  178998. /* Because of the horizontal mirror step, we can't process partial iMCUs
  178999. * at the (output) right edge properly. They just get transposed and
  179000. * not mirrored.
  179001. */
  179002. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179003. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179004. compptr = dstinfo->comp_info + ci;
  179005. comp_width = MCU_cols * compptr->h_samp_factor;
  179006. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179007. dst_blk_y += compptr->v_samp_factor) {
  179008. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179009. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179010. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179011. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179012. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179013. dst_blk_x += compptr->h_samp_factor) {
  179014. src_buffer = (*srcinfo->mem->access_virt_barray)
  179015. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179016. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179017. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179018. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179019. if (dst_blk_x < comp_width) {
  179020. /* Block is within the mirrorable area. */
  179021. dst_ptr = dst_buffer[offset_y]
  179022. [comp_width - dst_blk_x - offset_x - 1];
  179023. for (i = 0; i < DCTSIZE; i++) {
  179024. for (j = 0; j < DCTSIZE; j++)
  179025. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179026. i++;
  179027. for (j = 0; j < DCTSIZE; j++)
  179028. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179029. }
  179030. } else {
  179031. /* Edge blocks are transposed but not mirrored. */
  179032. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179033. for (i = 0; i < DCTSIZE; i++)
  179034. for (j = 0; j < DCTSIZE; j++)
  179035. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179036. }
  179037. }
  179038. }
  179039. }
  179040. }
  179041. }
  179042. }
  179043. LOCAL(void)
  179044. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179045. jvirt_barray_ptr *src_coef_arrays,
  179046. jvirt_barray_ptr *dst_coef_arrays)
  179047. /* 270 degree rotation is equivalent to
  179048. * 1. Horizontal mirroring;
  179049. * 2. Transposing the image.
  179050. * These two steps are merged into a single processing routine.
  179051. */
  179052. {
  179053. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179054. int ci, i, j, offset_x, offset_y;
  179055. JBLOCKARRAY src_buffer, dst_buffer;
  179056. JCOEFPTR src_ptr, dst_ptr;
  179057. jpeg_component_info *compptr;
  179058. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179059. * at the (output) bottom edge properly. They just get transposed and
  179060. * not mirrored.
  179061. */
  179062. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179063. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179064. compptr = dstinfo->comp_info + ci;
  179065. comp_height = MCU_rows * compptr->v_samp_factor;
  179066. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179067. dst_blk_y += compptr->v_samp_factor) {
  179068. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179069. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179070. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179071. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179072. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179073. dst_blk_x += compptr->h_samp_factor) {
  179074. src_buffer = (*srcinfo->mem->access_virt_barray)
  179075. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179076. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179077. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179078. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179079. if (dst_blk_y < comp_height) {
  179080. /* Block is within the mirrorable area. */
  179081. src_ptr = src_buffer[offset_x]
  179082. [comp_height - dst_blk_y - offset_y - 1];
  179083. for (i = 0; i < DCTSIZE; i++) {
  179084. for (j = 0; j < DCTSIZE; j++) {
  179085. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179086. j++;
  179087. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179088. }
  179089. }
  179090. } else {
  179091. /* Edge blocks are transposed but not mirrored. */
  179092. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179093. for (i = 0; i < DCTSIZE; i++)
  179094. for (j = 0; j < DCTSIZE; j++)
  179095. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179096. }
  179097. }
  179098. }
  179099. }
  179100. }
  179101. }
  179102. }
  179103. LOCAL(void)
  179104. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179105. jvirt_barray_ptr *src_coef_arrays,
  179106. jvirt_barray_ptr *dst_coef_arrays)
  179107. /* 180 degree rotation is equivalent to
  179108. * 1. Vertical mirroring;
  179109. * 2. Horizontal mirroring.
  179110. * These two steps are merged into a single processing routine.
  179111. */
  179112. {
  179113. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179114. int ci, i, j, offset_y;
  179115. JBLOCKARRAY src_buffer, dst_buffer;
  179116. JBLOCKROW src_row_ptr, dst_row_ptr;
  179117. JCOEFPTR src_ptr, dst_ptr;
  179118. jpeg_component_info *compptr;
  179119. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179120. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179121. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179122. compptr = dstinfo->comp_info + ci;
  179123. comp_width = MCU_cols * compptr->h_samp_factor;
  179124. comp_height = MCU_rows * compptr->v_samp_factor;
  179125. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179126. dst_blk_y += compptr->v_samp_factor) {
  179127. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179128. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179129. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179130. if (dst_blk_y < comp_height) {
  179131. /* Row is within the vertically mirrorable area. */
  179132. src_buffer = (*srcinfo->mem->access_virt_barray)
  179133. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179134. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179135. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179136. } else {
  179137. /* Bottom-edge rows are only mirrored horizontally. */
  179138. src_buffer = (*srcinfo->mem->access_virt_barray)
  179139. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179140. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179141. }
  179142. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179143. if (dst_blk_y < comp_height) {
  179144. /* Row is within the mirrorable area. */
  179145. dst_row_ptr = dst_buffer[offset_y];
  179146. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179147. /* Process the blocks that can be mirrored both ways. */
  179148. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179149. dst_ptr = dst_row_ptr[dst_blk_x];
  179150. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179151. for (i = 0; i < DCTSIZE; i += 2) {
  179152. /* For even row, negate every odd column. */
  179153. for (j = 0; j < DCTSIZE; j += 2) {
  179154. *dst_ptr++ = *src_ptr++;
  179155. *dst_ptr++ = - *src_ptr++;
  179156. }
  179157. /* For odd row, negate every even column. */
  179158. for (j = 0; j < DCTSIZE; j += 2) {
  179159. *dst_ptr++ = - *src_ptr++;
  179160. *dst_ptr++ = *src_ptr++;
  179161. }
  179162. }
  179163. }
  179164. /* Any remaining right-edge blocks are only mirrored vertically. */
  179165. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179166. dst_ptr = dst_row_ptr[dst_blk_x];
  179167. src_ptr = src_row_ptr[dst_blk_x];
  179168. for (i = 0; i < DCTSIZE; i += 2) {
  179169. for (j = 0; j < DCTSIZE; j++)
  179170. *dst_ptr++ = *src_ptr++;
  179171. for (j = 0; j < DCTSIZE; j++)
  179172. *dst_ptr++ = - *src_ptr++;
  179173. }
  179174. }
  179175. } else {
  179176. /* Remaining rows are just mirrored horizontally. */
  179177. dst_row_ptr = dst_buffer[offset_y];
  179178. src_row_ptr = src_buffer[offset_y];
  179179. /* Process the blocks that can be mirrored. */
  179180. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179181. dst_ptr = dst_row_ptr[dst_blk_x];
  179182. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179183. for (i = 0; i < DCTSIZE2; i += 2) {
  179184. *dst_ptr++ = *src_ptr++;
  179185. *dst_ptr++ = - *src_ptr++;
  179186. }
  179187. }
  179188. /* Any remaining right-edge blocks are only copied. */
  179189. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179190. dst_ptr = dst_row_ptr[dst_blk_x];
  179191. src_ptr = src_row_ptr[dst_blk_x];
  179192. for (i = 0; i < DCTSIZE2; i++)
  179193. *dst_ptr++ = *src_ptr++;
  179194. }
  179195. }
  179196. }
  179197. }
  179198. }
  179199. }
  179200. LOCAL(void)
  179201. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179202. jvirt_barray_ptr *src_coef_arrays,
  179203. jvirt_barray_ptr *dst_coef_arrays)
  179204. /* Transverse transpose is equivalent to
  179205. * 1. 180 degree rotation;
  179206. * 2. Transposition;
  179207. * or
  179208. * 1. Horizontal mirroring;
  179209. * 2. Transposition;
  179210. * 3. Horizontal mirroring.
  179211. * These steps are merged into a single processing routine.
  179212. */
  179213. {
  179214. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179215. int ci, i, j, offset_x, offset_y;
  179216. JBLOCKARRAY src_buffer, dst_buffer;
  179217. JCOEFPTR src_ptr, dst_ptr;
  179218. jpeg_component_info *compptr;
  179219. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179220. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179221. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179222. compptr = dstinfo->comp_info + ci;
  179223. comp_width = MCU_cols * compptr->h_samp_factor;
  179224. comp_height = MCU_rows * compptr->v_samp_factor;
  179225. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179226. dst_blk_y += compptr->v_samp_factor) {
  179227. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179228. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179229. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179230. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179231. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179232. dst_blk_x += compptr->h_samp_factor) {
  179233. src_buffer = (*srcinfo->mem->access_virt_barray)
  179234. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179235. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179236. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179237. if (dst_blk_y < comp_height) {
  179238. src_ptr = src_buffer[offset_x]
  179239. [comp_height - dst_blk_y - offset_y - 1];
  179240. if (dst_blk_x < comp_width) {
  179241. /* Block is within the mirrorable area. */
  179242. dst_ptr = dst_buffer[offset_y]
  179243. [comp_width - dst_blk_x - offset_x - 1];
  179244. for (i = 0; i < DCTSIZE; i++) {
  179245. for (j = 0; j < DCTSIZE; j++) {
  179246. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179247. j++;
  179248. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179249. }
  179250. i++;
  179251. for (j = 0; j < DCTSIZE; j++) {
  179252. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179253. j++;
  179254. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179255. }
  179256. }
  179257. } else {
  179258. /* Right-edge blocks are mirrored in y only */
  179259. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179260. for (i = 0; i < DCTSIZE; i++) {
  179261. for (j = 0; j < DCTSIZE; j++) {
  179262. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179263. j++;
  179264. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179265. }
  179266. }
  179267. }
  179268. } else {
  179269. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179270. if (dst_blk_x < comp_width) {
  179271. /* Bottom-edge blocks are mirrored in x only */
  179272. dst_ptr = dst_buffer[offset_y]
  179273. [comp_width - dst_blk_x - offset_x - 1];
  179274. for (i = 0; i < DCTSIZE; i++) {
  179275. for (j = 0; j < DCTSIZE; j++)
  179276. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179277. i++;
  179278. for (j = 0; j < DCTSIZE; j++)
  179279. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179280. }
  179281. } else {
  179282. /* At lower right corner, just transpose, no mirroring */
  179283. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179284. for (i = 0; i < DCTSIZE; i++)
  179285. for (j = 0; j < DCTSIZE; j++)
  179286. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179287. }
  179288. }
  179289. }
  179290. }
  179291. }
  179292. }
  179293. }
  179294. }
  179295. /* Request any required workspace.
  179296. *
  179297. * We allocate the workspace virtual arrays from the source decompression
  179298. * object, so that all the arrays (both the original data and the workspace)
  179299. * will be taken into account while making memory management decisions.
  179300. * Hence, this routine must be called after jpeg_read_header (which reads
  179301. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179302. * the source's virtual arrays).
  179303. */
  179304. GLOBAL(void)
  179305. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179306. jpeg_transform_info *info)
  179307. {
  179308. jvirt_barray_ptr *coef_arrays = NULL;
  179309. jpeg_component_info *compptr;
  179310. int ci;
  179311. if (info->force_grayscale &&
  179312. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179313. srcinfo->num_components == 3) {
  179314. /* We'll only process the first component */
  179315. info->num_components = 1;
  179316. } else {
  179317. /* Process all the components */
  179318. info->num_components = srcinfo->num_components;
  179319. }
  179320. switch (info->transform) {
  179321. case JXFORM_NONE:
  179322. case JXFORM_FLIP_H:
  179323. /* Don't need a workspace array */
  179324. break;
  179325. case JXFORM_FLIP_V:
  179326. case JXFORM_ROT_180:
  179327. /* Need workspace arrays having same dimensions as source image.
  179328. * Note that we allocate arrays padded out to the next iMCU boundary,
  179329. * so that transform routines need not worry about missing edge blocks.
  179330. */
  179331. coef_arrays = (jvirt_barray_ptr *)
  179332. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179333. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179334. for (ci = 0; ci < info->num_components; ci++) {
  179335. compptr = srcinfo->comp_info + ci;
  179336. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179337. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179338. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179339. (long) compptr->h_samp_factor),
  179340. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179341. (long) compptr->v_samp_factor),
  179342. (JDIMENSION) compptr->v_samp_factor);
  179343. }
  179344. break;
  179345. case JXFORM_TRANSPOSE:
  179346. case JXFORM_TRANSVERSE:
  179347. case JXFORM_ROT_90:
  179348. case JXFORM_ROT_270:
  179349. /* Need workspace arrays having transposed dimensions.
  179350. * Note that we allocate arrays padded out to the next iMCU boundary,
  179351. * so that transform routines need not worry about missing edge blocks.
  179352. */
  179353. coef_arrays = (jvirt_barray_ptr *)
  179354. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179355. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179356. for (ci = 0; ci < info->num_components; ci++) {
  179357. compptr = srcinfo->comp_info + ci;
  179358. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179359. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179360. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179361. (long) compptr->v_samp_factor),
  179362. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179363. (long) compptr->h_samp_factor),
  179364. (JDIMENSION) compptr->h_samp_factor);
  179365. }
  179366. break;
  179367. }
  179368. info->workspace_coef_arrays = coef_arrays;
  179369. }
  179370. /* Transpose destination image parameters */
  179371. LOCAL(void)
  179372. transpose_critical_parameters (j_compress_ptr dstinfo)
  179373. {
  179374. int tblno, i, j, ci, itemp;
  179375. jpeg_component_info *compptr;
  179376. JQUANT_TBL *qtblptr;
  179377. JDIMENSION dtemp;
  179378. UINT16 qtemp;
  179379. /* Transpose basic image dimensions */
  179380. dtemp = dstinfo->image_width;
  179381. dstinfo->image_width = dstinfo->image_height;
  179382. dstinfo->image_height = dtemp;
  179383. /* Transpose sampling factors */
  179384. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179385. compptr = dstinfo->comp_info + ci;
  179386. itemp = compptr->h_samp_factor;
  179387. compptr->h_samp_factor = compptr->v_samp_factor;
  179388. compptr->v_samp_factor = itemp;
  179389. }
  179390. /* Transpose quantization tables */
  179391. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179392. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179393. if (qtblptr != NULL) {
  179394. for (i = 0; i < DCTSIZE; i++) {
  179395. for (j = 0; j < i; j++) {
  179396. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179397. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179398. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179399. }
  179400. }
  179401. }
  179402. }
  179403. }
  179404. /* Trim off any partial iMCUs on the indicated destination edge */
  179405. LOCAL(void)
  179406. trim_right_edge (j_compress_ptr dstinfo)
  179407. {
  179408. int ci, max_h_samp_factor;
  179409. JDIMENSION MCU_cols;
  179410. /* We have to compute max_h_samp_factor ourselves,
  179411. * because it hasn't been set yet in the destination
  179412. * (and we don't want to use the source's value).
  179413. */
  179414. max_h_samp_factor = 1;
  179415. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179416. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179417. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179418. }
  179419. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179420. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179421. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179422. }
  179423. LOCAL(void)
  179424. trim_bottom_edge (j_compress_ptr dstinfo)
  179425. {
  179426. int ci, max_v_samp_factor;
  179427. JDIMENSION MCU_rows;
  179428. /* We have to compute max_v_samp_factor ourselves,
  179429. * because it hasn't been set yet in the destination
  179430. * (and we don't want to use the source's value).
  179431. */
  179432. max_v_samp_factor = 1;
  179433. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179434. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179435. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179436. }
  179437. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179438. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179439. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179440. }
  179441. /* Adjust output image parameters as needed.
  179442. *
  179443. * This must be called after jpeg_copy_critical_parameters()
  179444. * and before jpeg_write_coefficients().
  179445. *
  179446. * The return value is the set of virtual coefficient arrays to be written
  179447. * (either the ones allocated by jtransform_request_workspace, or the
  179448. * original source data arrays). The caller will need to pass this value
  179449. * to jpeg_write_coefficients().
  179450. */
  179451. GLOBAL(jvirt_barray_ptr *)
  179452. jtransform_adjust_parameters (j_decompress_ptr,
  179453. j_compress_ptr dstinfo,
  179454. jvirt_barray_ptr *src_coef_arrays,
  179455. jpeg_transform_info *info)
  179456. {
  179457. /* If force-to-grayscale is requested, adjust destination parameters */
  179458. if (info->force_grayscale) {
  179459. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179460. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179461. * will get set to 1, which typically won't match the source.
  179462. * In fact we do this even if the source is already grayscale; that
  179463. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179464. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179465. */
  179466. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179467. dstinfo->num_components == 3) ||
  179468. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179469. dstinfo->num_components == 1)) {
  179470. /* We have to preserve the source's quantization table number. */
  179471. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179472. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179473. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179474. } else {
  179475. /* Sorry, can't do it */
  179476. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179477. }
  179478. }
  179479. /* Correct the destination's image dimensions etc if necessary */
  179480. switch (info->transform) {
  179481. case JXFORM_NONE:
  179482. /* Nothing to do */
  179483. break;
  179484. case JXFORM_FLIP_H:
  179485. if (info->trim)
  179486. trim_right_edge(dstinfo);
  179487. break;
  179488. case JXFORM_FLIP_V:
  179489. if (info->trim)
  179490. trim_bottom_edge(dstinfo);
  179491. break;
  179492. case JXFORM_TRANSPOSE:
  179493. transpose_critical_parameters(dstinfo);
  179494. /* transpose does NOT have to trim anything */
  179495. break;
  179496. case JXFORM_TRANSVERSE:
  179497. transpose_critical_parameters(dstinfo);
  179498. if (info->trim) {
  179499. trim_right_edge(dstinfo);
  179500. trim_bottom_edge(dstinfo);
  179501. }
  179502. break;
  179503. case JXFORM_ROT_90:
  179504. transpose_critical_parameters(dstinfo);
  179505. if (info->trim)
  179506. trim_right_edge(dstinfo);
  179507. break;
  179508. case JXFORM_ROT_180:
  179509. if (info->trim) {
  179510. trim_right_edge(dstinfo);
  179511. trim_bottom_edge(dstinfo);
  179512. }
  179513. break;
  179514. case JXFORM_ROT_270:
  179515. transpose_critical_parameters(dstinfo);
  179516. if (info->trim)
  179517. trim_bottom_edge(dstinfo);
  179518. break;
  179519. }
  179520. /* Return the appropriate output data set */
  179521. if (info->workspace_coef_arrays != NULL)
  179522. return info->workspace_coef_arrays;
  179523. return src_coef_arrays;
  179524. }
  179525. /* Execute the actual transformation, if any.
  179526. *
  179527. * This must be called *after* jpeg_write_coefficients, because it depends
  179528. * on jpeg_write_coefficients to have computed subsidiary values such as
  179529. * the per-component width and height fields in the destination object.
  179530. *
  179531. * Note that some transformations will modify the source data arrays!
  179532. */
  179533. GLOBAL(void)
  179534. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  179535. j_compress_ptr dstinfo,
  179536. jvirt_barray_ptr *src_coef_arrays,
  179537. jpeg_transform_info *info)
  179538. {
  179539. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  179540. switch (info->transform) {
  179541. case JXFORM_NONE:
  179542. break;
  179543. case JXFORM_FLIP_H:
  179544. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  179545. break;
  179546. case JXFORM_FLIP_V:
  179547. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179548. break;
  179549. case JXFORM_TRANSPOSE:
  179550. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179551. break;
  179552. case JXFORM_TRANSVERSE:
  179553. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179554. break;
  179555. case JXFORM_ROT_90:
  179556. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179557. break;
  179558. case JXFORM_ROT_180:
  179559. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179560. break;
  179561. case JXFORM_ROT_270:
  179562. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179563. break;
  179564. }
  179565. }
  179566. #endif /* TRANSFORMS_SUPPORTED */
  179567. /* Setup decompression object to save desired markers in memory.
  179568. * This must be called before jpeg_read_header() to have the desired effect.
  179569. */
  179570. GLOBAL(void)
  179571. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  179572. {
  179573. #ifdef SAVE_MARKERS_SUPPORTED
  179574. int m;
  179575. /* Save comments except under NONE option */
  179576. if (option != JCOPYOPT_NONE) {
  179577. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  179578. }
  179579. /* Save all types of APPn markers iff ALL option */
  179580. if (option == JCOPYOPT_ALL) {
  179581. for (m = 0; m < 16; m++)
  179582. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  179583. }
  179584. #endif /* SAVE_MARKERS_SUPPORTED */
  179585. }
  179586. /* Copy markers saved in the given source object to the destination object.
  179587. * This should be called just after jpeg_start_compress() or
  179588. * jpeg_write_coefficients().
  179589. * Note that those routines will have written the SOI, and also the
  179590. * JFIF APP0 or Adobe APP14 markers if selected.
  179591. */
  179592. GLOBAL(void)
  179593. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179594. JCOPY_OPTION)
  179595. {
  179596. jpeg_saved_marker_ptr marker;
  179597. /* In the current implementation, we don't actually need to examine the
  179598. * option flag here; we just copy everything that got saved.
  179599. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  179600. * if the encoder library already wrote one.
  179601. */
  179602. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  179603. if (dstinfo->write_JFIF_header &&
  179604. marker->marker == JPEG_APP0 &&
  179605. marker->data_length >= 5 &&
  179606. GETJOCTET(marker->data[0]) == 0x4A &&
  179607. GETJOCTET(marker->data[1]) == 0x46 &&
  179608. GETJOCTET(marker->data[2]) == 0x49 &&
  179609. GETJOCTET(marker->data[3]) == 0x46 &&
  179610. GETJOCTET(marker->data[4]) == 0)
  179611. continue; /* reject duplicate JFIF */
  179612. if (dstinfo->write_Adobe_marker &&
  179613. marker->marker == JPEG_APP0+14 &&
  179614. marker->data_length >= 5 &&
  179615. GETJOCTET(marker->data[0]) == 0x41 &&
  179616. GETJOCTET(marker->data[1]) == 0x64 &&
  179617. GETJOCTET(marker->data[2]) == 0x6F &&
  179618. GETJOCTET(marker->data[3]) == 0x62 &&
  179619. GETJOCTET(marker->data[4]) == 0x65)
  179620. continue; /* reject duplicate Adobe */
  179621. #ifdef NEED_FAR_POINTERS
  179622. /* We could use jpeg_write_marker if the data weren't FAR... */
  179623. {
  179624. unsigned int i;
  179625. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  179626. for (i = 0; i < marker->data_length; i++)
  179627. jpeg_write_m_byte(dstinfo, marker->data[i]);
  179628. }
  179629. #else
  179630. jpeg_write_marker(dstinfo, marker->marker,
  179631. marker->data, marker->data_length);
  179632. #endif
  179633. }
  179634. }
  179635. /*** End of inlined file: transupp.c ***/
  179636. #else
  179637. #define JPEG_INTERNALS
  179638. #undef FAR
  179639. #include <jpeglib.h>
  179640. #endif
  179641. }
  179642. #undef max
  179643. #undef min
  179644. #if JUCE_MSVC
  179645. #pragma warning (pop)
  179646. #endif
  179647. BEGIN_JUCE_NAMESPACE
  179648. namespace JPEGHelpers
  179649. {
  179650. using namespace jpeglibNamespace;
  179651. #if ! JUCE_MSVC
  179652. using jpeglibNamespace::boolean;
  179653. #endif
  179654. struct JPEGDecodingFailure {};
  179655. void fatalErrorHandler (j_common_ptr)
  179656. {
  179657. throw JPEGDecodingFailure();
  179658. }
  179659. void silentErrorCallback1 (j_common_ptr) {}
  179660. void silentErrorCallback2 (j_common_ptr, int) {}
  179661. void silentErrorCallback3 (j_common_ptr, char*) {}
  179662. void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  179663. {
  179664. zerostruct (err);
  179665. err.error_exit = fatalErrorHandler;
  179666. err.emit_message = silentErrorCallback2;
  179667. err.output_message = silentErrorCallback1;
  179668. err.format_message = silentErrorCallback3;
  179669. err.reset_error_mgr = silentErrorCallback1;
  179670. }
  179671. void dummyCallback1 (j_decompress_ptr)
  179672. {
  179673. }
  179674. void jpegSkip (j_decompress_ptr decompStruct, long num)
  179675. {
  179676. decompStruct->src->next_input_byte += num;
  179677. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  179678. decompStruct->src->bytes_in_buffer -= num;
  179679. }
  179680. boolean jpegFill (j_decompress_ptr)
  179681. {
  179682. return 0;
  179683. }
  179684. const int jpegBufferSize = 512;
  179685. struct JuceJpegDest : public jpeg_destination_mgr
  179686. {
  179687. OutputStream* output;
  179688. char* buffer;
  179689. };
  179690. void jpegWriteInit (j_compress_ptr)
  179691. {
  179692. }
  179693. void jpegWriteTerminate (j_compress_ptr cinfo)
  179694. {
  179695. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179696. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  179697. dest->output->write (dest->buffer, (int) numToWrite);
  179698. }
  179699. boolean jpegWriteFlush (j_compress_ptr cinfo)
  179700. {
  179701. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179702. const int numToWrite = jpegBufferSize;
  179703. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  179704. dest->free_in_buffer = jpegBufferSize;
  179705. return dest->output->write (dest->buffer, numToWrite);
  179706. }
  179707. }
  179708. JPEGImageFormat::JPEGImageFormat()
  179709. : quality (-1.0f)
  179710. {
  179711. }
  179712. JPEGImageFormat::~JPEGImageFormat() {}
  179713. void JPEGImageFormat::setQuality (const float newQuality)
  179714. {
  179715. quality = newQuality;
  179716. }
  179717. const String JPEGImageFormat::getFormatName()
  179718. {
  179719. return "JPEG";
  179720. }
  179721. bool JPEGImageFormat::canUnderstand (InputStream& in)
  179722. {
  179723. const int bytesNeeded = 10;
  179724. uint8 header [bytesNeeded];
  179725. if (in.read (header, bytesNeeded) == bytesNeeded)
  179726. {
  179727. return header[0] == 0xff
  179728. && header[1] == 0xd8
  179729. && header[2] == 0xff
  179730. && (header[3] == 0xe0 || header[3] == 0xe1);
  179731. }
  179732. return false;
  179733. }
  179734. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  179735. const Image juce_loadWithCoreImage (InputStream& input);
  179736. #endif
  179737. const Image JPEGImageFormat::decodeImage (InputStream& in)
  179738. {
  179739. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  179740. return juce_loadWithCoreImage (in);
  179741. #else
  179742. using namespace jpeglibNamespace;
  179743. using namespace JPEGHelpers;
  179744. MemoryOutputStream mb;
  179745. mb.writeFromInputStream (in, -1);
  179746. Image image;
  179747. if (mb.getDataSize() > 16)
  179748. {
  179749. struct jpeg_decompress_struct jpegDecompStruct;
  179750. struct jpeg_error_mgr jerr;
  179751. setupSilentErrorHandler (jerr);
  179752. jpegDecompStruct.err = &jerr;
  179753. jpeg_create_decompress (&jpegDecompStruct);
  179754. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  179755. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  179756. jpegDecompStruct.src->init_source = dummyCallback1;
  179757. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  179758. jpegDecompStruct.src->skip_input_data = jpegSkip;
  179759. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  179760. jpegDecompStruct.src->term_source = dummyCallback1;
  179761. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  179762. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  179763. try
  179764. {
  179765. jpeg_read_header (&jpegDecompStruct, TRUE);
  179766. jpeg_calc_output_dimensions (&jpegDecompStruct);
  179767. const int width = jpegDecompStruct.output_width;
  179768. const int height = jpegDecompStruct.output_height;
  179769. jpegDecompStruct.out_color_space = JCS_RGB;
  179770. JSAMPARRAY buffer
  179771. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  179772. JPOOL_IMAGE,
  179773. width * 3, 1);
  179774. if (jpeg_start_decompress (&jpegDecompStruct))
  179775. {
  179776. image = Image (Image::RGB, width, height, false);
  179777. image.getProperties()->set ("originalImageHadAlpha", false);
  179778. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  179779. const Image::BitmapData destData (image, true);
  179780. for (int y = 0; y < height; ++y)
  179781. {
  179782. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  179783. const uint8* src = *buffer;
  179784. uint8* dest = destData.getLinePointer (y);
  179785. if (hasAlphaChan)
  179786. {
  179787. for (int i = width; --i >= 0;)
  179788. {
  179789. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179790. ((PixelARGB*) dest)->premultiply();
  179791. dest += destData.pixelStride;
  179792. src += 3;
  179793. }
  179794. }
  179795. else
  179796. {
  179797. for (int i = width; --i >= 0;)
  179798. {
  179799. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179800. dest += destData.pixelStride;
  179801. src += 3;
  179802. }
  179803. }
  179804. }
  179805. jpeg_finish_decompress (&jpegDecompStruct);
  179806. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  179807. }
  179808. jpeg_destroy_decompress (&jpegDecompStruct);
  179809. }
  179810. catch (...)
  179811. {}
  179812. }
  179813. return image;
  179814. #endif
  179815. }
  179816. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  179817. {
  179818. using namespace jpeglibNamespace;
  179819. using namespace JPEGHelpers;
  179820. if (image.hasAlphaChannel())
  179821. {
  179822. // this method could fill the background in white and still save the image..
  179823. jassertfalse;
  179824. return true;
  179825. }
  179826. struct jpeg_compress_struct jpegCompStruct;
  179827. struct jpeg_error_mgr jerr;
  179828. setupSilentErrorHandler (jerr);
  179829. jpegCompStruct.err = &jerr;
  179830. jpeg_create_compress (&jpegCompStruct);
  179831. JuceJpegDest dest;
  179832. jpegCompStruct.dest = &dest;
  179833. dest.output = &out;
  179834. HeapBlock <char> tempBuffer (jpegBufferSize);
  179835. dest.buffer = tempBuffer;
  179836. dest.next_output_byte = (JOCTET*) dest.buffer;
  179837. dest.free_in_buffer = jpegBufferSize;
  179838. dest.init_destination = jpegWriteInit;
  179839. dest.empty_output_buffer = jpegWriteFlush;
  179840. dest.term_destination = jpegWriteTerminate;
  179841. jpegCompStruct.image_width = image.getWidth();
  179842. jpegCompStruct.image_height = image.getHeight();
  179843. jpegCompStruct.input_components = 3;
  179844. jpegCompStruct.in_color_space = JCS_RGB;
  179845. jpegCompStruct.write_JFIF_header = 1;
  179846. jpegCompStruct.X_density = 72;
  179847. jpegCompStruct.Y_density = 72;
  179848. jpeg_set_defaults (&jpegCompStruct);
  179849. jpegCompStruct.dct_method = JDCT_FLOAT;
  179850. jpegCompStruct.optimize_coding = 1;
  179851. //jpegCompStruct.smoothing_factor = 10;
  179852. if (quality < 0.0f)
  179853. quality = 0.85f;
  179854. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  179855. jpeg_start_compress (&jpegCompStruct, TRUE);
  179856. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  179857. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  179858. JPOOL_IMAGE, strideBytes, 1);
  179859. const Image::BitmapData srcData (image, false);
  179860. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  179861. {
  179862. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  179863. uint8* dst = *buffer;
  179864. for (int i = jpegCompStruct.image_width; --i >= 0;)
  179865. {
  179866. *dst++ = ((const PixelRGB*) src)->getRed();
  179867. *dst++ = ((const PixelRGB*) src)->getGreen();
  179868. *dst++ = ((const PixelRGB*) src)->getBlue();
  179869. src += srcData.pixelStride;
  179870. }
  179871. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  179872. }
  179873. jpeg_finish_compress (&jpegCompStruct);
  179874. jpeg_destroy_compress (&jpegCompStruct);
  179875. out.flush();
  179876. return true;
  179877. }
  179878. END_JUCE_NAMESPACE
  179879. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  179880. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  179881. #if JUCE_MSVC
  179882. #pragma warning (push)
  179883. #pragma warning (disable: 4390 4611)
  179884. #ifdef __INTEL_COMPILER
  179885. #pragma warning (disable: 2544 2545)
  179886. #endif
  179887. #endif
  179888. namespace zlibNamespace
  179889. {
  179890. #if JUCE_INCLUDE_ZLIB_CODE
  179891. #undef OS_CODE
  179892. #undef fdopen
  179893. #undef OS_CODE
  179894. #else
  179895. #include <zlib.h>
  179896. #endif
  179897. }
  179898. namespace pnglibNamespace
  179899. {
  179900. using namespace zlibNamespace;
  179901. #if JUCE_INCLUDE_PNGLIB_CODE
  179902. #if _MSC_VER != 1310
  179903. using ::calloc; // (causes conflict in VS.NET 2003)
  179904. using ::malloc;
  179905. using ::free;
  179906. #endif
  179907. using ::abs;
  179908. #define PNG_INTERNAL
  179909. #define NO_DUMMY_DECL
  179910. #define PNG_SETJMP_NOT_SUPPORTED
  179911. /*** Start of inlined file: png.h ***/
  179912. /* png.h - header file for PNG reference library
  179913. *
  179914. * libpng version 1.2.21 - October 4, 2007
  179915. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179916. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179917. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179918. *
  179919. * Authors and maintainers:
  179920. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  179921. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  179922. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  179923. * See also "Contributing Authors", below.
  179924. *
  179925. * Note about libpng version numbers:
  179926. *
  179927. * Due to various miscommunications, unforeseen code incompatibilities
  179928. * and occasional factors outside the authors' control, version numbering
  179929. * on the library has not always been consistent and straightforward.
  179930. * The following table summarizes matters since version 0.89c, which was
  179931. * the first widely used release:
  179932. *
  179933. * source png.h png.h shared-lib
  179934. * version string int version
  179935. * ------- ------ ----- ----------
  179936. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  179937. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  179938. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  179939. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  179940. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  179941. * 0.97c 0.97 97 2.0.97
  179942. * 0.98 0.98 98 2.0.98
  179943. * 0.99 0.99 98 2.0.99
  179944. * 0.99a-m 0.99 99 2.0.99
  179945. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  179946. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  179947. * 1.0.1 png.h string is 10001 2.1.0
  179948. * 1.0.1a-e identical to the 10002 from here on, the shared library
  179949. * 1.0.2 source version) 10002 is 2.V where V is the source code
  179950. * 1.0.2a-b 10003 version, except as noted.
  179951. * 1.0.3 10003
  179952. * 1.0.3a-d 10004
  179953. * 1.0.4 10004
  179954. * 1.0.4a-f 10005
  179955. * 1.0.5 (+ 2 patches) 10005
  179956. * 1.0.5a-d 10006
  179957. * 1.0.5e-r 10100 (not source compatible)
  179958. * 1.0.5s-v 10006 (not binary compatible)
  179959. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  179960. * 1.0.6d-f 10007 (still binary incompatible)
  179961. * 1.0.6g 10007
  179962. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  179963. * 1.0.6i 10007 10.6i
  179964. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  179965. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  179966. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  179967. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  179968. * 1.0.7 1 10007 (still compatible)
  179969. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  179970. * 1.0.8rc1 1 10008 2.1.0.8rc1
  179971. * 1.0.8 1 10008 2.1.0.8
  179972. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  179973. * 1.0.9rc1 1 10009 2.1.0.9rc1
  179974. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  179975. * 1.0.9rc2 1 10009 2.1.0.9rc2
  179976. * 1.0.9 1 10009 2.1.0.9
  179977. * 1.0.10beta1 1 10010 2.1.0.10beta1
  179978. * 1.0.10rc1 1 10010 2.1.0.10rc1
  179979. * 1.0.10 1 10010 2.1.0.10
  179980. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  179981. * 1.0.11rc1 1 10011 2.1.0.11rc1
  179982. * 1.0.11 1 10011 2.1.0.11
  179983. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  179984. * 1.0.12rc1 2 10012 2.1.0.12rc1
  179985. * 1.0.12 2 10012 2.1.0.12
  179986. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  179987. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  179988. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  179989. * 1.2.0rc1 3 10200 3.1.2.0rc1
  179990. * 1.2.0 3 10200 3.1.2.0
  179991. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  179992. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  179993. * 1.2.1 3 10201 3.1.2.1
  179994. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  179995. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  179996. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  179997. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  179998. * 1.0.13 10 10013 10.so.0.1.0.13
  179999. * 1.2.2 12 10202 12.so.0.1.2.2
  180000. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  180001. * 1.2.3 12 10203 12.so.0.1.2.3
  180002. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  180003. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  180004. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  180005. * 1.0.14 10 10014 10.so.0.1.0.14
  180006. * 1.2.4 13 10204 12.so.0.1.2.4
  180007. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  180008. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  180009. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  180010. * 1.0.15 10 10015 10.so.0.1.0.15
  180011. * 1.2.5 13 10205 12.so.0.1.2.5
  180012. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  180013. * 1.0.16 10 10016 10.so.0.1.0.16
  180014. * 1.2.6 13 10206 12.so.0.1.2.6
  180015. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  180016. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  180017. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  180018. * 1.0.17 10 10017 10.so.0.1.0.17
  180019. * 1.2.7 13 10207 12.so.0.1.2.7
  180020. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180021. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180022. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180023. * 1.0.18 10 10018 10.so.0.1.0.18
  180024. * 1.2.8 13 10208 12.so.0.1.2.8
  180025. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180026. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180027. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180028. * 1.2.9 13 10209 12.so.0.9[.0]
  180029. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180030. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180031. * 1.2.10 13 10210 12.so.0.10[.0]
  180032. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180033. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180034. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180035. * 1.0.19 10 10019 10.so.0.19[.0]
  180036. * 1.2.11 13 10211 12.so.0.11[.0]
  180037. * 1.0.20 10 10020 10.so.0.20[.0]
  180038. * 1.2.12 13 10212 12.so.0.12[.0]
  180039. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180040. * 1.0.21 10 10021 10.so.0.21[.0]
  180041. * 1.2.13 13 10213 12.so.0.13[.0]
  180042. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180043. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180044. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180045. * 1.0.22 10 10022 10.so.0.22[.0]
  180046. * 1.2.14 13 10214 12.so.0.14[.0]
  180047. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180048. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180049. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180050. * 1.0.23 10 10023 10.so.0.23[.0]
  180051. * 1.2.15 13 10215 12.so.0.15[.0]
  180052. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180053. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180054. * 1.0.24 10 10024 10.so.0.24[.0]
  180055. * 1.2.16 13 10216 12.so.0.16[.0]
  180056. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180057. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180058. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180059. * 1.0.25 10 10025 10.so.0.25[.0]
  180060. * 1.2.17 13 10217 12.so.0.17[.0]
  180061. * 1.0.26 10 10026 10.so.0.26[.0]
  180062. * 1.2.18 13 10218 12.so.0.18[.0]
  180063. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180064. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180065. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180066. * 1.0.27 10 10027 10.so.0.27[.0]
  180067. * 1.2.19 13 10219 12.so.0.19[.0]
  180068. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180069. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180070. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180071. * 1.0.28 10 10028 10.so.0.28[.0]
  180072. * 1.2.20 13 10220 12.so.0.20[.0]
  180073. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180074. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180075. * 1.0.29 10 10029 10.so.0.29[.0]
  180076. * 1.2.21 13 10221 12.so.0.21[.0]
  180077. *
  180078. * Henceforth the source version will match the shared-library major
  180079. * and minor numbers; the shared-library major version number will be
  180080. * used for changes in backward compatibility, as it is intended. The
  180081. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180082. * for applications, is an unsigned integer of the form xyyzz corresponding
  180083. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180084. * were given the previous public release number plus a letter, until
  180085. * version 1.0.6j; from then on they were given the upcoming public
  180086. * release number plus "betaNN" or "rcN".
  180087. *
  180088. * Binary incompatibility exists only when applications make direct access
  180089. * to the info_ptr or png_ptr members through png.h, and the compiled
  180090. * application is loaded with a different version of the library.
  180091. *
  180092. * DLLNUM will change each time there are forward or backward changes
  180093. * in binary compatibility (e.g., when a new feature is added).
  180094. *
  180095. * See libpng.txt or libpng.3 for more information. The PNG specification
  180096. * is available as a W3C Recommendation and as an ISO Specification,
  180097. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180098. */
  180099. /*
  180100. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180101. *
  180102. * If you modify libpng you may insert additional notices immediately following
  180103. * this sentence.
  180104. *
  180105. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180106. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180107. * distributed according to the same disclaimer and license as libpng-1.2.5
  180108. * with the following individual added to the list of Contributing Authors:
  180109. *
  180110. * Cosmin Truta
  180111. *
  180112. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180113. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180114. * distributed according to the same disclaimer and license as libpng-1.0.6
  180115. * with the following individuals added to the list of Contributing Authors:
  180116. *
  180117. * Simon-Pierre Cadieux
  180118. * Eric S. Raymond
  180119. * Gilles Vollant
  180120. *
  180121. * and with the following additions to the disclaimer:
  180122. *
  180123. * There is no warranty against interference with your enjoyment of the
  180124. * library or against infringement. There is no warranty that our
  180125. * efforts or the library will fulfill any of your particular purposes
  180126. * or needs. This library is provided with all faults, and the entire
  180127. * risk of satisfactory quality, performance, accuracy, and effort is with
  180128. * the user.
  180129. *
  180130. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180131. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180132. * distributed according to the same disclaimer and license as libpng-0.96,
  180133. * with the following individuals added to the list of Contributing Authors:
  180134. *
  180135. * Tom Lane
  180136. * Glenn Randers-Pehrson
  180137. * Willem van Schaik
  180138. *
  180139. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180140. * Copyright (c) 1996, 1997 Andreas Dilger
  180141. * Distributed according to the same disclaimer and license as libpng-0.88,
  180142. * with the following individuals added to the list of Contributing Authors:
  180143. *
  180144. * John Bowler
  180145. * Kevin Bracey
  180146. * Sam Bushell
  180147. * Magnus Holmgren
  180148. * Greg Roelofs
  180149. * Tom Tanner
  180150. *
  180151. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180152. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180153. *
  180154. * For the purposes of this copyright and license, "Contributing Authors"
  180155. * is defined as the following set of individuals:
  180156. *
  180157. * Andreas Dilger
  180158. * Dave Martindale
  180159. * Guy Eric Schalnat
  180160. * Paul Schmidt
  180161. * Tim Wegner
  180162. *
  180163. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180164. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180165. * including, without limitation, the warranties of merchantability and of
  180166. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180167. * assume no liability for direct, indirect, incidental, special, exemplary,
  180168. * or consequential damages, which may result from the use of the PNG
  180169. * Reference Library, even if advised of the possibility of such damage.
  180170. *
  180171. * Permission is hereby granted to use, copy, modify, and distribute this
  180172. * source code, or portions hereof, for any purpose, without fee, subject
  180173. * to the following restrictions:
  180174. *
  180175. * 1. The origin of this source code must not be misrepresented.
  180176. *
  180177. * 2. Altered versions must be plainly marked as such and
  180178. * must not be misrepresented as being the original source.
  180179. *
  180180. * 3. This Copyright notice may not be removed or altered from
  180181. * any source or altered source distribution.
  180182. *
  180183. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180184. * fee, and encourage the use of this source code as a component to
  180185. * supporting the PNG file format in commercial products. If you use this
  180186. * source code in a product, acknowledgment is not required but would be
  180187. * appreciated.
  180188. */
  180189. /*
  180190. * A "png_get_copyright" function is available, for convenient use in "about"
  180191. * boxes and the like:
  180192. *
  180193. * printf("%s",png_get_copyright(NULL));
  180194. *
  180195. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180196. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180197. */
  180198. /*
  180199. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180200. * certification mark of the Open Source Initiative.
  180201. */
  180202. /*
  180203. * The contributing authors would like to thank all those who helped
  180204. * with testing, bug fixes, and patience. This wouldn't have been
  180205. * possible without all of you.
  180206. *
  180207. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180208. */
  180209. /*
  180210. * Y2K compliance in libpng:
  180211. * =========================
  180212. *
  180213. * October 4, 2007
  180214. *
  180215. * Since the PNG Development group is an ad-hoc body, we can't make
  180216. * an official declaration.
  180217. *
  180218. * This is your unofficial assurance that libpng from version 0.71 and
  180219. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180220. * versions were also Y2K compliant.
  180221. *
  180222. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180223. * that will hold years up to 65535. The other two hold the date in text
  180224. * format, and will hold years up to 9999.
  180225. *
  180226. * The integer is
  180227. * "png_uint_16 year" in png_time_struct.
  180228. *
  180229. * The strings are
  180230. * "png_charp time_buffer" in png_struct and
  180231. * "near_time_buffer", which is a local character string in png.c.
  180232. *
  180233. * There are seven time-related functions:
  180234. * png.c: png_convert_to_rfc_1123() in png.c
  180235. * (formerly png_convert_to_rfc_1152() in error)
  180236. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180237. * png_convert_from_time_t() in pngwrite.c
  180238. * png_get_tIME() in pngget.c
  180239. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180240. * png_set_tIME() in pngset.c
  180241. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180242. *
  180243. * All handle dates properly in a Y2K environment. The
  180244. * png_convert_from_time_t() function calls gmtime() to convert from system
  180245. * clock time, which returns (year - 1900), which we properly convert to
  180246. * the full 4-digit year. There is a possibility that applications using
  180247. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180248. * function, or that they are incorrectly passing only a 2-digit year
  180249. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180250. * but this is not under our control. The libpng documentation has always
  180251. * stated that it works with 4-digit years, and the APIs have been
  180252. * documented as such.
  180253. *
  180254. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180255. * integer to hold the year, and can hold years as large as 65535.
  180256. *
  180257. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180258. * no date-related code.
  180259. *
  180260. * Glenn Randers-Pehrson
  180261. * libpng maintainer
  180262. * PNG Development Group
  180263. */
  180264. #ifndef PNG_H
  180265. #define PNG_H
  180266. /* This is not the place to learn how to use libpng. The file libpng.txt
  180267. * describes how to use libpng, and the file example.c summarizes it
  180268. * with some code on which to build. This file is useful for looking
  180269. * at the actual function definitions and structure components.
  180270. */
  180271. /* Version information for png.h - this should match the version in png.c */
  180272. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180273. #define PNG_HEADER_VERSION_STRING \
  180274. " libpng version 1.2.21 - October 4, 2007\n"
  180275. #define PNG_LIBPNG_VER_SONUM 0
  180276. #define PNG_LIBPNG_VER_DLLNUM 13
  180277. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180278. #define PNG_LIBPNG_VER_MAJOR 1
  180279. #define PNG_LIBPNG_VER_MINOR 2
  180280. #define PNG_LIBPNG_VER_RELEASE 21
  180281. /* This should match the numeric part of the final component of
  180282. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180283. #define PNG_LIBPNG_VER_BUILD 0
  180284. /* Release Status */
  180285. #define PNG_LIBPNG_BUILD_ALPHA 1
  180286. #define PNG_LIBPNG_BUILD_BETA 2
  180287. #define PNG_LIBPNG_BUILD_RC 3
  180288. #define PNG_LIBPNG_BUILD_STABLE 4
  180289. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180290. /* Release-Specific Flags */
  180291. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180292. PNG_LIBPNG_BUILD_STABLE only */
  180293. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180294. PNG_LIBPNG_BUILD_SPECIAL */
  180295. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180296. PNG_LIBPNG_BUILD_PRIVATE */
  180297. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180298. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180299. * We must not include leading zeros.
  180300. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180301. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180302. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180303. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180304. #ifndef PNG_VERSION_INFO_ONLY
  180305. /* include the compression library's header */
  180306. #endif
  180307. /* include all user configurable info, including optional assembler routines */
  180308. /*** Start of inlined file: pngconf.h ***/
  180309. /* pngconf.h - machine configurable file for libpng
  180310. *
  180311. * libpng version 1.2.21 - October 4, 2007
  180312. * For conditions of distribution and use, see copyright notice in png.h
  180313. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180314. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180315. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180316. */
  180317. /* Any machine specific code is near the front of this file, so if you
  180318. * are configuring libpng for a machine, you may want to read the section
  180319. * starting here down to where it starts to typedef png_color, png_text,
  180320. * and png_info.
  180321. */
  180322. #ifndef PNGCONF_H
  180323. #define PNGCONF_H
  180324. #define PNG_1_2_X
  180325. // These are some Juce config settings that should remove any unnecessary code bloat..
  180326. #define PNG_NO_STDIO 1
  180327. #define PNG_DEBUG 0
  180328. #define PNG_NO_WARNINGS 1
  180329. #define PNG_NO_ERROR_TEXT 1
  180330. #define PNG_NO_ERROR_NUMBERS 1
  180331. #define PNG_NO_USER_MEM 1
  180332. #define PNG_NO_READ_iCCP 1
  180333. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180334. #define PNG_NO_READ_USER_CHUNKS 1
  180335. #define PNG_NO_READ_iTXt 1
  180336. #define PNG_NO_READ_sCAL 1
  180337. #define PNG_NO_READ_sPLT 1
  180338. #define png_error(a, b) png_err(a)
  180339. #define png_warning(a, b)
  180340. #define png_chunk_error(a, b) png_err(a)
  180341. #define png_chunk_warning(a, b)
  180342. /*
  180343. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180344. * includes the resource compiler for Windows DLL configurations.
  180345. */
  180346. #ifdef PNG_USER_CONFIG
  180347. # ifndef PNG_USER_PRIVATEBUILD
  180348. # define PNG_USER_PRIVATEBUILD
  180349. # endif
  180350. #include "pngusr.h"
  180351. #endif
  180352. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180353. #ifdef PNG_CONFIGURE_LIBPNG
  180354. #ifdef HAVE_CONFIG_H
  180355. #include "config.h"
  180356. #endif
  180357. #endif
  180358. /*
  180359. * Added at libpng-1.2.8
  180360. *
  180361. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180362. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180363. * the DLL was built>
  180364. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180365. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180366. * distinguish your DLL from those of the official release. These
  180367. * correspond to the trailing letters that come after the version
  180368. * number and must match your private DLL name>
  180369. * e.g. // private DLL "libpng13gx.dll"
  180370. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180371. *
  180372. * The following macros are also at your disposal if you want to complete the
  180373. * DLL VERSIONINFO structure.
  180374. * - PNG_USER_VERSIONINFO_COMMENTS
  180375. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180376. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180377. */
  180378. #ifdef __STDC__
  180379. #ifdef SPECIALBUILD
  180380. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180381. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180382. #endif
  180383. #ifdef PRIVATEBUILD
  180384. # pragma message("PRIVATEBUILD is deprecated.\
  180385. Use PNG_USER_PRIVATEBUILD instead.")
  180386. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180387. #endif
  180388. #endif /* __STDC__ */
  180389. #ifndef PNG_VERSION_INFO_ONLY
  180390. /* End of material added to libpng-1.2.8 */
  180391. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180392. Restored at libpng-1.2.21 */
  180393. # define PNG_WARN_UNINITIALIZED_ROW 1
  180394. /* End of material added at libpng-1.2.19/1.2.21 */
  180395. /* This is the size of the compression buffer, and thus the size of
  180396. * an IDAT chunk. Make this whatever size you feel is best for your
  180397. * machine. One of these will be allocated per png_struct. When this
  180398. * is full, it writes the data to the disk, and does some other
  180399. * calculations. Making this an extremely small size will slow
  180400. * the library down, but you may want to experiment to determine
  180401. * where it becomes significant, if you are concerned with memory
  180402. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180403. * this describes the size of the buffer available to read the data in.
  180404. * Unless this gets smaller than the size of a row (compressed),
  180405. * it should not make much difference how big this is.
  180406. */
  180407. #ifndef PNG_ZBUF_SIZE
  180408. # define PNG_ZBUF_SIZE 8192
  180409. #endif
  180410. /* Enable if you want a write-only libpng */
  180411. #ifndef PNG_NO_READ_SUPPORTED
  180412. # define PNG_READ_SUPPORTED
  180413. #endif
  180414. /* Enable if you want a read-only libpng */
  180415. #ifndef PNG_NO_WRITE_SUPPORTED
  180416. # define PNG_WRITE_SUPPORTED
  180417. #endif
  180418. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180419. support PNGs that are embedded in MNG datastreams */
  180420. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180421. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180422. # define PNG_MNG_FEATURES_SUPPORTED
  180423. # endif
  180424. #endif
  180425. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180426. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180427. # define PNG_FLOATING_POINT_SUPPORTED
  180428. # endif
  180429. #endif
  180430. /* If you are running on a machine where you cannot allocate more
  180431. * than 64K of memory at once, uncomment this. While libpng will not
  180432. * normally need that much memory in a chunk (unless you load up a very
  180433. * large file), zlib needs to know how big of a chunk it can use, and
  180434. * libpng thus makes sure to check any memory allocation to verify it
  180435. * will fit into memory.
  180436. #define PNG_MAX_MALLOC_64K
  180437. */
  180438. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180439. # define PNG_MAX_MALLOC_64K
  180440. #endif
  180441. /* Special munging to support doing things the 'cygwin' way:
  180442. * 'Normal' png-on-win32 defines/defaults:
  180443. * PNG_BUILD_DLL -- building dll
  180444. * PNG_USE_DLL -- building an application, linking to dll
  180445. * (no define) -- building static library, or building an
  180446. * application and linking to the static lib
  180447. * 'Cygwin' defines/defaults:
  180448. * PNG_BUILD_DLL -- (ignored) building the dll
  180449. * (no define) -- (ignored) building an application, linking to the dll
  180450. * PNG_STATIC -- (ignored) building the static lib, or building an
  180451. * application that links to the static lib.
  180452. * ALL_STATIC -- (ignored) building various static libs, or building an
  180453. * application that links to the static libs.
  180454. * Thus,
  180455. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180456. * this bit of #ifdefs will define the 'correct' config variables based on
  180457. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180458. * unnecessary.
  180459. *
  180460. * Also, the precedence order is:
  180461. * ALL_STATIC (since we can't #undef something outside our namespace)
  180462. * PNG_BUILD_DLL
  180463. * PNG_STATIC
  180464. * (nothing) == PNG_USE_DLL
  180465. *
  180466. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180467. * of auto-import in binutils, we no longer need to worry about
  180468. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180469. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180470. * to __declspec() stuff. However, we DO need to worry about
  180471. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180472. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180473. */
  180474. #if defined(__CYGWIN__)
  180475. # if defined(ALL_STATIC)
  180476. # if defined(PNG_BUILD_DLL)
  180477. # undef PNG_BUILD_DLL
  180478. # endif
  180479. # if defined(PNG_USE_DLL)
  180480. # undef PNG_USE_DLL
  180481. # endif
  180482. # if defined(PNG_DLL)
  180483. # undef PNG_DLL
  180484. # endif
  180485. # if !defined(PNG_STATIC)
  180486. # define PNG_STATIC
  180487. # endif
  180488. # else
  180489. # if defined (PNG_BUILD_DLL)
  180490. # if defined(PNG_STATIC)
  180491. # undef PNG_STATIC
  180492. # endif
  180493. # if defined(PNG_USE_DLL)
  180494. # undef PNG_USE_DLL
  180495. # endif
  180496. # if !defined(PNG_DLL)
  180497. # define PNG_DLL
  180498. # endif
  180499. # else
  180500. # if defined(PNG_STATIC)
  180501. # if defined(PNG_USE_DLL)
  180502. # undef PNG_USE_DLL
  180503. # endif
  180504. # if defined(PNG_DLL)
  180505. # undef PNG_DLL
  180506. # endif
  180507. # else
  180508. # if !defined(PNG_USE_DLL)
  180509. # define PNG_USE_DLL
  180510. # endif
  180511. # if !defined(PNG_DLL)
  180512. # define PNG_DLL
  180513. # endif
  180514. # endif
  180515. # endif
  180516. # endif
  180517. #endif
  180518. /* This protects us against compilers that run on a windowing system
  180519. * and thus don't have or would rather us not use the stdio types:
  180520. * stdin, stdout, and stderr. The only one currently used is stderr
  180521. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  180522. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  180523. * will also prevent these, plus will prevent the entire set of stdio
  180524. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  180525. * unless (PNG_DEBUG > 0) has been #defined.
  180526. *
  180527. * #define PNG_NO_CONSOLE_IO
  180528. * #define PNG_NO_STDIO
  180529. */
  180530. #if defined(_WIN32_WCE)
  180531. # include <windows.h>
  180532. /* Console I/O functions are not supported on WindowsCE */
  180533. # define PNG_NO_CONSOLE_IO
  180534. # ifdef PNG_DEBUG
  180535. # undef PNG_DEBUG
  180536. # endif
  180537. #endif
  180538. #ifdef PNG_BUILD_DLL
  180539. # ifndef PNG_CONSOLE_IO_SUPPORTED
  180540. # ifndef PNG_NO_CONSOLE_IO
  180541. # define PNG_NO_CONSOLE_IO
  180542. # endif
  180543. # endif
  180544. #endif
  180545. # ifdef PNG_NO_STDIO
  180546. # ifndef PNG_NO_CONSOLE_IO
  180547. # define PNG_NO_CONSOLE_IO
  180548. # endif
  180549. # ifdef PNG_DEBUG
  180550. # if (PNG_DEBUG > 0)
  180551. # include <stdio.h>
  180552. # endif
  180553. # endif
  180554. # else
  180555. # if !defined(_WIN32_WCE)
  180556. /* "stdio.h" functions are not supported on WindowsCE */
  180557. # include <stdio.h>
  180558. # endif
  180559. # endif
  180560. /* This macro protects us against machines that don't have function
  180561. * prototypes (ie K&R style headers). If your compiler does not handle
  180562. * function prototypes, define this macro and use the included ansi2knr.
  180563. * I've always been able to use _NO_PROTO as the indicator, but you may
  180564. * need to drag the empty declaration out in front of here, or change the
  180565. * ifdef to suit your own needs.
  180566. */
  180567. #ifndef PNGARG
  180568. #ifdef OF /* zlib prototype munger */
  180569. # define PNGARG(arglist) OF(arglist)
  180570. #else
  180571. #ifdef _NO_PROTO
  180572. # define PNGARG(arglist) ()
  180573. # ifndef PNG_TYPECAST_NULL
  180574. # define PNG_TYPECAST_NULL
  180575. # endif
  180576. #else
  180577. # define PNGARG(arglist) arglist
  180578. #endif /* _NO_PROTO */
  180579. #endif /* OF */
  180580. #endif /* PNGARG */
  180581. /* Try to determine if we are compiling on a Mac. Note that testing for
  180582. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  180583. * on non-Mac platforms.
  180584. */
  180585. #ifndef MACOS
  180586. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  180587. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  180588. # define MACOS
  180589. # endif
  180590. #endif
  180591. /* enough people need this for various reasons to include it here */
  180592. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  180593. # include <sys/types.h>
  180594. #endif
  180595. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  180596. # define PNG_SETJMP_SUPPORTED
  180597. #endif
  180598. #ifdef PNG_SETJMP_SUPPORTED
  180599. /* This is an attempt to force a single setjmp behaviour on Linux. If
  180600. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  180601. */
  180602. # ifdef __linux__
  180603. # ifdef _BSD_SOURCE
  180604. # define PNG_SAVE_BSD_SOURCE
  180605. # undef _BSD_SOURCE
  180606. # endif
  180607. # ifdef _SETJMP_H
  180608. /* If you encounter a compiler error here, see the explanation
  180609. * near the end of INSTALL.
  180610. */
  180611. __png.h__ already includes setjmp.h;
  180612. __dont__ include it again.;
  180613. # endif
  180614. # endif /* __linux__ */
  180615. /* include setjmp.h for error handling */
  180616. # include <setjmp.h>
  180617. # ifdef __linux__
  180618. # ifdef PNG_SAVE_BSD_SOURCE
  180619. # define _BSD_SOURCE
  180620. # undef PNG_SAVE_BSD_SOURCE
  180621. # endif
  180622. # endif /* __linux__ */
  180623. #endif /* PNG_SETJMP_SUPPORTED */
  180624. #ifdef BSD
  180625. #if ! JUCE_MAC
  180626. # include <strings.h>
  180627. #endif
  180628. #else
  180629. # include <string.h>
  180630. #endif
  180631. /* Other defines for things like memory and the like can go here. */
  180632. #ifdef PNG_INTERNAL
  180633. #include <stdlib.h>
  180634. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  180635. * aren't usually used outside the library (as far as I know), so it is
  180636. * debatable if they should be exported at all. In the future, when it is
  180637. * possible to have run-time registry of chunk-handling functions, some of
  180638. * these will be made available again.
  180639. #define PNG_EXTERN extern
  180640. */
  180641. #define PNG_EXTERN
  180642. /* Other defines specific to compilers can go here. Try to keep
  180643. * them inside an appropriate ifdef/endif pair for portability.
  180644. */
  180645. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  180646. # if defined(MACOS)
  180647. /* We need to check that <math.h> hasn't already been included earlier
  180648. * as it seems it doesn't agree with <fp.h>, yet we should really use
  180649. * <fp.h> if possible.
  180650. */
  180651. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  180652. # include <fp.h>
  180653. # endif
  180654. # else
  180655. # include <math.h>
  180656. # endif
  180657. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  180658. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  180659. * MATH=68881
  180660. */
  180661. # include <m68881.h>
  180662. # endif
  180663. #endif
  180664. /* Codewarrior on NT has linking problems without this. */
  180665. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  180666. # define PNG_ALWAYS_EXTERN
  180667. #endif
  180668. /* This provides the non-ANSI (far) memory allocation routines. */
  180669. #if defined(__TURBOC__) && defined(__MSDOS__)
  180670. # include <mem.h>
  180671. # include <alloc.h>
  180672. #endif
  180673. /* I have no idea why is this necessary... */
  180674. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  180675. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  180676. # include <malloc.h>
  180677. #endif
  180678. /* This controls how fine the dithering gets. As this allocates
  180679. * a largish chunk of memory (32K), those who are not as concerned
  180680. * with dithering quality can decrease some or all of these.
  180681. */
  180682. #ifndef PNG_DITHER_RED_BITS
  180683. # define PNG_DITHER_RED_BITS 5
  180684. #endif
  180685. #ifndef PNG_DITHER_GREEN_BITS
  180686. # define PNG_DITHER_GREEN_BITS 5
  180687. #endif
  180688. #ifndef PNG_DITHER_BLUE_BITS
  180689. # define PNG_DITHER_BLUE_BITS 5
  180690. #endif
  180691. /* This controls how fine the gamma correction becomes when you
  180692. * are only interested in 8 bits anyway. Increasing this value
  180693. * results in more memory being used, and more pow() functions
  180694. * being called to fill in the gamma tables. Don't set this value
  180695. * less then 8, and even that may not work (I haven't tested it).
  180696. */
  180697. #ifndef PNG_MAX_GAMMA_8
  180698. # define PNG_MAX_GAMMA_8 11
  180699. #endif
  180700. /* This controls how much a difference in gamma we can tolerate before
  180701. * we actually start doing gamma conversion.
  180702. */
  180703. #ifndef PNG_GAMMA_THRESHOLD
  180704. # define PNG_GAMMA_THRESHOLD 0.05
  180705. #endif
  180706. #endif /* PNG_INTERNAL */
  180707. /* The following uses const char * instead of char * for error
  180708. * and warning message functions, so some compilers won't complain.
  180709. * If you do not want to use const, define PNG_NO_CONST here.
  180710. */
  180711. #ifndef PNG_NO_CONST
  180712. # define PNG_CONST const
  180713. #else
  180714. # define PNG_CONST
  180715. #endif
  180716. /* The following defines give you the ability to remove code from the
  180717. * library that you will not be using. I wish I could figure out how to
  180718. * automate this, but I can't do that without making it seriously hard
  180719. * on the users. So if you are not using an ability, change the #define
  180720. * to and #undef, and that part of the library will not be compiled. If
  180721. * your linker can't find a function, you may want to make sure the
  180722. * ability is defined here. Some of these depend upon some others being
  180723. * defined. I haven't figured out all the interactions here, so you may
  180724. * have to experiment awhile to get everything to compile. If you are
  180725. * creating or using a shared library, you probably shouldn't touch this,
  180726. * as it will affect the size of the structures, and this will cause bad
  180727. * things to happen if the library and/or application ever change.
  180728. */
  180729. /* Any features you will not be using can be undef'ed here */
  180730. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  180731. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  180732. * on the compile line, then pick and choose which ones to define without
  180733. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  180734. * if you only want to have a png-compliant reader/writer but don't need
  180735. * any of the extra transformations. This saves about 80 kbytes in a
  180736. * typical installation of the library. (PNG_NO_* form added in version
  180737. * 1.0.1c, for consistency)
  180738. */
  180739. /* The size of the png_text structure changed in libpng-1.0.6 when
  180740. * iTXt support was added. iTXt support was turned off by default through
  180741. * libpng-1.2.x, to support old apps that malloc the png_text structure
  180742. * instead of calling png_set_text() and letting libpng malloc it. It
  180743. * was turned on by default in libpng-1.3.0.
  180744. */
  180745. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180746. # ifndef PNG_NO_iTXt_SUPPORTED
  180747. # define PNG_NO_iTXt_SUPPORTED
  180748. # endif
  180749. # ifndef PNG_NO_READ_iTXt
  180750. # define PNG_NO_READ_iTXt
  180751. # endif
  180752. # ifndef PNG_NO_WRITE_iTXt
  180753. # define PNG_NO_WRITE_iTXt
  180754. # endif
  180755. #endif
  180756. #if !defined(PNG_NO_iTXt_SUPPORTED)
  180757. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  180758. # define PNG_READ_iTXt
  180759. # endif
  180760. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  180761. # define PNG_WRITE_iTXt
  180762. # endif
  180763. #endif
  180764. /* The following support, added after version 1.0.0, can be turned off here en
  180765. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  180766. * with old applications that require the length of png_struct and png_info
  180767. * to remain unchanged.
  180768. */
  180769. #ifdef PNG_LEGACY_SUPPORTED
  180770. # define PNG_NO_FREE_ME
  180771. # define PNG_NO_READ_UNKNOWN_CHUNKS
  180772. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  180773. # define PNG_NO_READ_USER_CHUNKS
  180774. # define PNG_NO_READ_iCCP
  180775. # define PNG_NO_WRITE_iCCP
  180776. # define PNG_NO_READ_iTXt
  180777. # define PNG_NO_WRITE_iTXt
  180778. # define PNG_NO_READ_sCAL
  180779. # define PNG_NO_WRITE_sCAL
  180780. # define PNG_NO_READ_sPLT
  180781. # define PNG_NO_WRITE_sPLT
  180782. # define PNG_NO_INFO_IMAGE
  180783. # define PNG_NO_READ_RGB_TO_GRAY
  180784. # define PNG_NO_READ_USER_TRANSFORM
  180785. # define PNG_NO_WRITE_USER_TRANSFORM
  180786. # define PNG_NO_USER_MEM
  180787. # define PNG_NO_READ_EMPTY_PLTE
  180788. # define PNG_NO_MNG_FEATURES
  180789. # define PNG_NO_FIXED_POINT_SUPPORTED
  180790. #endif
  180791. /* Ignore attempt to turn off both floating and fixed point support */
  180792. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  180793. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  180794. # define PNG_FIXED_POINT_SUPPORTED
  180795. #endif
  180796. #ifndef PNG_NO_FREE_ME
  180797. # define PNG_FREE_ME_SUPPORTED
  180798. #endif
  180799. #if defined(PNG_READ_SUPPORTED)
  180800. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  180801. !defined(PNG_NO_READ_TRANSFORMS)
  180802. # define PNG_READ_TRANSFORMS_SUPPORTED
  180803. #endif
  180804. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  180805. # ifndef PNG_NO_READ_EXPAND
  180806. # define PNG_READ_EXPAND_SUPPORTED
  180807. # endif
  180808. # ifndef PNG_NO_READ_SHIFT
  180809. # define PNG_READ_SHIFT_SUPPORTED
  180810. # endif
  180811. # ifndef PNG_NO_READ_PACK
  180812. # define PNG_READ_PACK_SUPPORTED
  180813. # endif
  180814. # ifndef PNG_NO_READ_BGR
  180815. # define PNG_READ_BGR_SUPPORTED
  180816. # endif
  180817. # ifndef PNG_NO_READ_SWAP
  180818. # define PNG_READ_SWAP_SUPPORTED
  180819. # endif
  180820. # ifndef PNG_NO_READ_PACKSWAP
  180821. # define PNG_READ_PACKSWAP_SUPPORTED
  180822. # endif
  180823. # ifndef PNG_NO_READ_INVERT
  180824. # define PNG_READ_INVERT_SUPPORTED
  180825. # endif
  180826. # ifndef PNG_NO_READ_DITHER
  180827. # define PNG_READ_DITHER_SUPPORTED
  180828. # endif
  180829. # ifndef PNG_NO_READ_BACKGROUND
  180830. # define PNG_READ_BACKGROUND_SUPPORTED
  180831. # endif
  180832. # ifndef PNG_NO_READ_16_TO_8
  180833. # define PNG_READ_16_TO_8_SUPPORTED
  180834. # endif
  180835. # ifndef PNG_NO_READ_FILLER
  180836. # define PNG_READ_FILLER_SUPPORTED
  180837. # endif
  180838. # ifndef PNG_NO_READ_GAMMA
  180839. # define PNG_READ_GAMMA_SUPPORTED
  180840. # endif
  180841. # ifndef PNG_NO_READ_GRAY_TO_RGB
  180842. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  180843. # endif
  180844. # ifndef PNG_NO_READ_SWAP_ALPHA
  180845. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  180846. # endif
  180847. # ifndef PNG_NO_READ_INVERT_ALPHA
  180848. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  180849. # endif
  180850. # ifndef PNG_NO_READ_STRIP_ALPHA
  180851. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  180852. # endif
  180853. # ifndef PNG_NO_READ_USER_TRANSFORM
  180854. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  180855. # endif
  180856. # ifndef PNG_NO_READ_RGB_TO_GRAY
  180857. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  180858. # endif
  180859. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  180860. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  180861. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  180862. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  180863. #endif /* about interlacing capability! You'll */
  180864. /* still have interlacing unless you change the following line: */
  180865. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  180866. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  180867. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  180868. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  180869. # endif
  180870. #endif
  180871. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180872. /* Deprecated, will be removed from version 2.0.0.
  180873. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  180874. #ifndef PNG_NO_READ_EMPTY_PLTE
  180875. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  180876. #endif
  180877. #endif
  180878. #endif /* PNG_READ_SUPPORTED */
  180879. #if defined(PNG_WRITE_SUPPORTED)
  180880. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  180881. !defined(PNG_NO_WRITE_TRANSFORMS)
  180882. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  180883. #endif
  180884. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  180885. # ifndef PNG_NO_WRITE_SHIFT
  180886. # define PNG_WRITE_SHIFT_SUPPORTED
  180887. # endif
  180888. # ifndef PNG_NO_WRITE_PACK
  180889. # define PNG_WRITE_PACK_SUPPORTED
  180890. # endif
  180891. # ifndef PNG_NO_WRITE_BGR
  180892. # define PNG_WRITE_BGR_SUPPORTED
  180893. # endif
  180894. # ifndef PNG_NO_WRITE_SWAP
  180895. # define PNG_WRITE_SWAP_SUPPORTED
  180896. # endif
  180897. # ifndef PNG_NO_WRITE_PACKSWAP
  180898. # define PNG_WRITE_PACKSWAP_SUPPORTED
  180899. # endif
  180900. # ifndef PNG_NO_WRITE_INVERT
  180901. # define PNG_WRITE_INVERT_SUPPORTED
  180902. # endif
  180903. # ifndef PNG_NO_WRITE_FILLER
  180904. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  180905. # endif
  180906. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  180907. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  180908. # endif
  180909. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  180910. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  180911. # endif
  180912. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  180913. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  180914. # endif
  180915. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  180916. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  180917. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  180918. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  180919. encoders, but can cause trouble
  180920. if left undefined */
  180921. #endif
  180922. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  180923. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  180924. defined(PNG_FLOATING_POINT_SUPPORTED)
  180925. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  180926. #endif
  180927. #ifndef PNG_NO_WRITE_FLUSH
  180928. # define PNG_WRITE_FLUSH_SUPPORTED
  180929. #endif
  180930. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180931. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  180932. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  180933. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  180934. #endif
  180935. #endif
  180936. #endif /* PNG_WRITE_SUPPORTED */
  180937. #ifndef PNG_1_0_X
  180938. # ifndef PNG_NO_ERROR_NUMBERS
  180939. # define PNG_ERROR_NUMBERS_SUPPORTED
  180940. # endif
  180941. #endif /* PNG_1_0_X */
  180942. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  180943. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  180944. # ifndef PNG_NO_USER_TRANSFORM_PTR
  180945. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  180946. # endif
  180947. #endif
  180948. #ifndef PNG_NO_STDIO
  180949. # define PNG_TIME_RFC1123_SUPPORTED
  180950. #endif
  180951. /* This adds extra functions in pngget.c for accessing data from the
  180952. * info pointer (added in version 0.99)
  180953. * png_get_image_width()
  180954. * png_get_image_height()
  180955. * png_get_bit_depth()
  180956. * png_get_color_type()
  180957. * png_get_compression_type()
  180958. * png_get_filter_type()
  180959. * png_get_interlace_type()
  180960. * png_get_pixel_aspect_ratio()
  180961. * png_get_pixels_per_meter()
  180962. * png_get_x_offset_pixels()
  180963. * png_get_y_offset_pixels()
  180964. * png_get_x_offset_microns()
  180965. * png_get_y_offset_microns()
  180966. */
  180967. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  180968. # define PNG_EASY_ACCESS_SUPPORTED
  180969. #endif
  180970. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  180971. * and removed from version 1.2.20. The following will be removed
  180972. * from libpng-1.4.0
  180973. */
  180974. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  180975. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  180976. # define PNG_OPTIMIZED_CODE_SUPPORTED
  180977. # endif
  180978. #endif
  180979. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  180980. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  180981. # define PNG_ASSEMBLER_CODE_SUPPORTED
  180982. # endif
  180983. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  180984. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  180985. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180986. # define PNG_NO_MMX_CODE
  180987. # endif
  180988. # endif
  180989. # if defined(__APPLE__)
  180990. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180991. # define PNG_NO_MMX_CODE
  180992. # endif
  180993. # endif
  180994. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  180995. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180996. # define PNG_NO_MMX_CODE
  180997. # endif
  180998. # endif
  180999. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181000. # define PNG_MMX_CODE_SUPPORTED
  181001. # endif
  181002. #endif
  181003. /* end of obsolete code to be removed from libpng-1.4.0 */
  181004. #if !defined(PNG_1_0_X)
  181005. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  181006. # define PNG_USER_MEM_SUPPORTED
  181007. #endif
  181008. #endif /* PNG_1_0_X */
  181009. /* Added at libpng-1.2.6 */
  181010. #if !defined(PNG_1_0_X)
  181011. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  181012. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  181013. # define PNG_SET_USER_LIMITS_SUPPORTED
  181014. #endif
  181015. #endif
  181016. #endif /* PNG_1_0_X */
  181017. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  181018. * how large, set these limits to 0x7fffffffL
  181019. */
  181020. #ifndef PNG_USER_WIDTH_MAX
  181021. # define PNG_USER_WIDTH_MAX 1000000L
  181022. #endif
  181023. #ifndef PNG_USER_HEIGHT_MAX
  181024. # define PNG_USER_HEIGHT_MAX 1000000L
  181025. #endif
  181026. /* These are currently experimental features, define them if you want */
  181027. /* very little testing */
  181028. /*
  181029. #ifdef PNG_READ_SUPPORTED
  181030. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181031. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181032. # endif
  181033. #endif
  181034. */
  181035. /* This is only for PowerPC big-endian and 680x0 systems */
  181036. /* some testing */
  181037. /*
  181038. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181039. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181040. #endif
  181041. */
  181042. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181043. /*
  181044. #define PNG_NO_POINTER_INDEXING
  181045. */
  181046. /* These functions are turned off by default, as they will be phased out. */
  181047. /*
  181048. #define PNG_USELESS_TESTS_SUPPORTED
  181049. #define PNG_CORRECT_PALETTE_SUPPORTED
  181050. */
  181051. /* Any chunks you are not interested in, you can undef here. The
  181052. * ones that allocate memory may be expecially important (hIST,
  181053. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181054. * a bit smaller.
  181055. */
  181056. #if defined(PNG_READ_SUPPORTED) && \
  181057. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181058. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181059. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181060. #endif
  181061. #if defined(PNG_WRITE_SUPPORTED) && \
  181062. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181063. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181064. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181065. #endif
  181066. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181067. #ifdef PNG_NO_READ_TEXT
  181068. # define PNG_NO_READ_iTXt
  181069. # define PNG_NO_READ_tEXt
  181070. # define PNG_NO_READ_zTXt
  181071. #endif
  181072. #ifndef PNG_NO_READ_bKGD
  181073. # define PNG_READ_bKGD_SUPPORTED
  181074. # define PNG_bKGD_SUPPORTED
  181075. #endif
  181076. #ifndef PNG_NO_READ_cHRM
  181077. # define PNG_READ_cHRM_SUPPORTED
  181078. # define PNG_cHRM_SUPPORTED
  181079. #endif
  181080. #ifndef PNG_NO_READ_gAMA
  181081. # define PNG_READ_gAMA_SUPPORTED
  181082. # define PNG_gAMA_SUPPORTED
  181083. #endif
  181084. #ifndef PNG_NO_READ_hIST
  181085. # define PNG_READ_hIST_SUPPORTED
  181086. # define PNG_hIST_SUPPORTED
  181087. #endif
  181088. #ifndef PNG_NO_READ_iCCP
  181089. # define PNG_READ_iCCP_SUPPORTED
  181090. # define PNG_iCCP_SUPPORTED
  181091. #endif
  181092. #ifndef PNG_NO_READ_iTXt
  181093. # ifndef PNG_READ_iTXt_SUPPORTED
  181094. # define PNG_READ_iTXt_SUPPORTED
  181095. # endif
  181096. # ifndef PNG_iTXt_SUPPORTED
  181097. # define PNG_iTXt_SUPPORTED
  181098. # endif
  181099. #endif
  181100. #ifndef PNG_NO_READ_oFFs
  181101. # define PNG_READ_oFFs_SUPPORTED
  181102. # define PNG_oFFs_SUPPORTED
  181103. #endif
  181104. #ifndef PNG_NO_READ_pCAL
  181105. # define PNG_READ_pCAL_SUPPORTED
  181106. # define PNG_pCAL_SUPPORTED
  181107. #endif
  181108. #ifndef PNG_NO_READ_sCAL
  181109. # define PNG_READ_sCAL_SUPPORTED
  181110. # define PNG_sCAL_SUPPORTED
  181111. #endif
  181112. #ifndef PNG_NO_READ_pHYs
  181113. # define PNG_READ_pHYs_SUPPORTED
  181114. # define PNG_pHYs_SUPPORTED
  181115. #endif
  181116. #ifndef PNG_NO_READ_sBIT
  181117. # define PNG_READ_sBIT_SUPPORTED
  181118. # define PNG_sBIT_SUPPORTED
  181119. #endif
  181120. #ifndef PNG_NO_READ_sPLT
  181121. # define PNG_READ_sPLT_SUPPORTED
  181122. # define PNG_sPLT_SUPPORTED
  181123. #endif
  181124. #ifndef PNG_NO_READ_sRGB
  181125. # define PNG_READ_sRGB_SUPPORTED
  181126. # define PNG_sRGB_SUPPORTED
  181127. #endif
  181128. #ifndef PNG_NO_READ_tEXt
  181129. # define PNG_READ_tEXt_SUPPORTED
  181130. # define PNG_tEXt_SUPPORTED
  181131. #endif
  181132. #ifndef PNG_NO_READ_tIME
  181133. # define PNG_READ_tIME_SUPPORTED
  181134. # define PNG_tIME_SUPPORTED
  181135. #endif
  181136. #ifndef PNG_NO_READ_tRNS
  181137. # define PNG_READ_tRNS_SUPPORTED
  181138. # define PNG_tRNS_SUPPORTED
  181139. #endif
  181140. #ifndef PNG_NO_READ_zTXt
  181141. # define PNG_READ_zTXt_SUPPORTED
  181142. # define PNG_zTXt_SUPPORTED
  181143. #endif
  181144. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181145. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181146. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181147. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181148. # endif
  181149. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181150. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181151. # endif
  181152. #endif
  181153. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181154. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181155. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181156. # define PNG_USER_CHUNKS_SUPPORTED
  181157. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181158. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181159. # endif
  181160. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181161. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181162. # endif
  181163. #endif
  181164. #ifndef PNG_NO_READ_OPT_PLTE
  181165. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181166. #endif /* optional PLTE chunk in RGB and RGBA images */
  181167. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181168. defined(PNG_READ_zTXt_SUPPORTED)
  181169. # define PNG_READ_TEXT_SUPPORTED
  181170. # define PNG_TEXT_SUPPORTED
  181171. #endif
  181172. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181173. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181174. #ifdef PNG_NO_WRITE_TEXT
  181175. # define PNG_NO_WRITE_iTXt
  181176. # define PNG_NO_WRITE_tEXt
  181177. # define PNG_NO_WRITE_zTXt
  181178. #endif
  181179. #ifndef PNG_NO_WRITE_bKGD
  181180. # define PNG_WRITE_bKGD_SUPPORTED
  181181. # ifndef PNG_bKGD_SUPPORTED
  181182. # define PNG_bKGD_SUPPORTED
  181183. # endif
  181184. #endif
  181185. #ifndef PNG_NO_WRITE_cHRM
  181186. # define PNG_WRITE_cHRM_SUPPORTED
  181187. # ifndef PNG_cHRM_SUPPORTED
  181188. # define PNG_cHRM_SUPPORTED
  181189. # endif
  181190. #endif
  181191. #ifndef PNG_NO_WRITE_gAMA
  181192. # define PNG_WRITE_gAMA_SUPPORTED
  181193. # ifndef PNG_gAMA_SUPPORTED
  181194. # define PNG_gAMA_SUPPORTED
  181195. # endif
  181196. #endif
  181197. #ifndef PNG_NO_WRITE_hIST
  181198. # define PNG_WRITE_hIST_SUPPORTED
  181199. # ifndef PNG_hIST_SUPPORTED
  181200. # define PNG_hIST_SUPPORTED
  181201. # endif
  181202. #endif
  181203. #ifndef PNG_NO_WRITE_iCCP
  181204. # define PNG_WRITE_iCCP_SUPPORTED
  181205. # ifndef PNG_iCCP_SUPPORTED
  181206. # define PNG_iCCP_SUPPORTED
  181207. # endif
  181208. #endif
  181209. #ifndef PNG_NO_WRITE_iTXt
  181210. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181211. # define PNG_WRITE_iTXt_SUPPORTED
  181212. # endif
  181213. # ifndef PNG_iTXt_SUPPORTED
  181214. # define PNG_iTXt_SUPPORTED
  181215. # endif
  181216. #endif
  181217. #ifndef PNG_NO_WRITE_oFFs
  181218. # define PNG_WRITE_oFFs_SUPPORTED
  181219. # ifndef PNG_oFFs_SUPPORTED
  181220. # define PNG_oFFs_SUPPORTED
  181221. # endif
  181222. #endif
  181223. #ifndef PNG_NO_WRITE_pCAL
  181224. # define PNG_WRITE_pCAL_SUPPORTED
  181225. # ifndef PNG_pCAL_SUPPORTED
  181226. # define PNG_pCAL_SUPPORTED
  181227. # endif
  181228. #endif
  181229. #ifndef PNG_NO_WRITE_sCAL
  181230. # define PNG_WRITE_sCAL_SUPPORTED
  181231. # ifndef PNG_sCAL_SUPPORTED
  181232. # define PNG_sCAL_SUPPORTED
  181233. # endif
  181234. #endif
  181235. #ifndef PNG_NO_WRITE_pHYs
  181236. # define PNG_WRITE_pHYs_SUPPORTED
  181237. # ifndef PNG_pHYs_SUPPORTED
  181238. # define PNG_pHYs_SUPPORTED
  181239. # endif
  181240. #endif
  181241. #ifndef PNG_NO_WRITE_sBIT
  181242. # define PNG_WRITE_sBIT_SUPPORTED
  181243. # ifndef PNG_sBIT_SUPPORTED
  181244. # define PNG_sBIT_SUPPORTED
  181245. # endif
  181246. #endif
  181247. #ifndef PNG_NO_WRITE_sPLT
  181248. # define PNG_WRITE_sPLT_SUPPORTED
  181249. # ifndef PNG_sPLT_SUPPORTED
  181250. # define PNG_sPLT_SUPPORTED
  181251. # endif
  181252. #endif
  181253. #ifndef PNG_NO_WRITE_sRGB
  181254. # define PNG_WRITE_sRGB_SUPPORTED
  181255. # ifndef PNG_sRGB_SUPPORTED
  181256. # define PNG_sRGB_SUPPORTED
  181257. # endif
  181258. #endif
  181259. #ifndef PNG_NO_WRITE_tEXt
  181260. # define PNG_WRITE_tEXt_SUPPORTED
  181261. # ifndef PNG_tEXt_SUPPORTED
  181262. # define PNG_tEXt_SUPPORTED
  181263. # endif
  181264. #endif
  181265. #ifndef PNG_NO_WRITE_tIME
  181266. # define PNG_WRITE_tIME_SUPPORTED
  181267. # ifndef PNG_tIME_SUPPORTED
  181268. # define PNG_tIME_SUPPORTED
  181269. # endif
  181270. #endif
  181271. #ifndef PNG_NO_WRITE_tRNS
  181272. # define PNG_WRITE_tRNS_SUPPORTED
  181273. # ifndef PNG_tRNS_SUPPORTED
  181274. # define PNG_tRNS_SUPPORTED
  181275. # endif
  181276. #endif
  181277. #ifndef PNG_NO_WRITE_zTXt
  181278. # define PNG_WRITE_zTXt_SUPPORTED
  181279. # ifndef PNG_zTXt_SUPPORTED
  181280. # define PNG_zTXt_SUPPORTED
  181281. # endif
  181282. #endif
  181283. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181284. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181285. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181286. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181287. # endif
  181288. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181289. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181290. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181291. # endif
  181292. # endif
  181293. #endif
  181294. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181295. defined(PNG_WRITE_zTXt_SUPPORTED)
  181296. # define PNG_WRITE_TEXT_SUPPORTED
  181297. # ifndef PNG_TEXT_SUPPORTED
  181298. # define PNG_TEXT_SUPPORTED
  181299. # endif
  181300. #endif
  181301. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181302. /* Turn this off to disable png_read_png() and
  181303. * png_write_png() and leave the row_pointers member
  181304. * out of the info structure.
  181305. */
  181306. #ifndef PNG_NO_INFO_IMAGE
  181307. # define PNG_INFO_IMAGE_SUPPORTED
  181308. #endif
  181309. /* need the time information for reading tIME chunks */
  181310. #if defined(PNG_tIME_SUPPORTED)
  181311. # if !defined(_WIN32_WCE)
  181312. /* "time.h" functions are not supported on WindowsCE */
  181313. # include <time.h>
  181314. # endif
  181315. #endif
  181316. /* Some typedefs to get us started. These should be safe on most of the
  181317. * common platforms. The typedefs should be at least as large as the
  181318. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181319. * don't have to be exactly that size. Some compilers dislike passing
  181320. * unsigned shorts as function parameters, so you may be better off using
  181321. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181322. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181323. */
  181324. typedef unsigned long png_uint_32;
  181325. typedef long png_int_32;
  181326. typedef unsigned short png_uint_16;
  181327. typedef short png_int_16;
  181328. typedef unsigned char png_byte;
  181329. /* This is usually size_t. It is typedef'ed just in case you need it to
  181330. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181331. #ifdef PNG_SIZE_T
  181332. typedef PNG_SIZE_T png_size_t;
  181333. # define png_sizeof(x) png_convert_size(sizeof (x))
  181334. #else
  181335. typedef size_t png_size_t;
  181336. # define png_sizeof(x) sizeof (x)
  181337. #endif
  181338. /* The following is needed for medium model support. It cannot be in the
  181339. * PNG_INTERNAL section. Needs modification for other compilers besides
  181340. * MSC. Model independent support declares all arrays and pointers to be
  181341. * large using the far keyword. The zlib version used must also support
  181342. * model independent data. As of version zlib 1.0.4, the necessary changes
  181343. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181344. * changes that are needed. (Tim Wegner)
  181345. */
  181346. /* Separate compiler dependencies (problem here is that zlib.h always
  181347. defines FAR. (SJT) */
  181348. #ifdef __BORLANDC__
  181349. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181350. # define LDATA 1
  181351. # else
  181352. # define LDATA 0
  181353. # endif
  181354. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181355. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181356. # define PNG_MAX_MALLOC_64K
  181357. # if (LDATA != 1)
  181358. # ifndef FAR
  181359. # define FAR __far
  181360. # endif
  181361. # define USE_FAR_KEYWORD
  181362. # endif /* LDATA != 1 */
  181363. /* Possibly useful for moving data out of default segment.
  181364. * Uncomment it if you want. Could also define FARDATA as
  181365. * const if your compiler supports it. (SJT)
  181366. # define FARDATA FAR
  181367. */
  181368. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181369. #endif /* __BORLANDC__ */
  181370. /* Suggest testing for specific compiler first before testing for
  181371. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181372. * making reliance oncertain keywords suspect. (SJT)
  181373. */
  181374. /* MSC Medium model */
  181375. #if defined(FAR)
  181376. # if defined(M_I86MM)
  181377. # define USE_FAR_KEYWORD
  181378. # define FARDATA FAR
  181379. # include <dos.h>
  181380. # endif
  181381. #endif
  181382. /* SJT: default case */
  181383. #ifndef FAR
  181384. # define FAR
  181385. #endif
  181386. /* At this point FAR is always defined */
  181387. #ifndef FARDATA
  181388. # define FARDATA
  181389. #endif
  181390. /* Typedef for floating-point numbers that are converted
  181391. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181392. typedef png_int_32 png_fixed_point;
  181393. /* Add typedefs for pointers */
  181394. typedef void FAR * png_voidp;
  181395. typedef png_byte FAR * png_bytep;
  181396. typedef png_uint_32 FAR * png_uint_32p;
  181397. typedef png_int_32 FAR * png_int_32p;
  181398. typedef png_uint_16 FAR * png_uint_16p;
  181399. typedef png_int_16 FAR * png_int_16p;
  181400. typedef PNG_CONST char FAR * png_const_charp;
  181401. typedef char FAR * png_charp;
  181402. typedef png_fixed_point FAR * png_fixed_point_p;
  181403. #ifndef PNG_NO_STDIO
  181404. #if defined(_WIN32_WCE)
  181405. typedef HANDLE png_FILE_p;
  181406. #else
  181407. typedef FILE * png_FILE_p;
  181408. #endif
  181409. #endif
  181410. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181411. typedef double FAR * png_doublep;
  181412. #endif
  181413. /* Pointers to pointers; i.e. arrays */
  181414. typedef png_byte FAR * FAR * png_bytepp;
  181415. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181416. typedef png_int_32 FAR * FAR * png_int_32pp;
  181417. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181418. typedef png_int_16 FAR * FAR * png_int_16pp;
  181419. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181420. typedef char FAR * FAR * png_charpp;
  181421. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181422. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181423. typedef double FAR * FAR * png_doublepp;
  181424. #endif
  181425. /* Pointers to pointers to pointers; i.e., pointer to array */
  181426. typedef char FAR * FAR * FAR * png_charppp;
  181427. #if 0
  181428. /* SPC - Is this stuff deprecated? */
  181429. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181430. /* libpng typedefs for types in zlib. If zlib changes
  181431. * or another compression library is used, then change these.
  181432. * Eliminates need to change all the source files.
  181433. */
  181434. typedef charf * png_zcharp;
  181435. typedef charf * FAR * png_zcharpp;
  181436. typedef z_stream FAR * png_zstreamp;
  181437. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181438. /*
  181439. * Define PNG_BUILD_DLL if the module being built is a Windows
  181440. * LIBPNG DLL.
  181441. *
  181442. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181443. * It is equivalent to Microsoft predefined macro _DLL that is
  181444. * automatically defined when you compile using the share
  181445. * version of the CRT (C Run-Time library)
  181446. *
  181447. * The cygwin mods make this behavior a little different:
  181448. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181449. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181450. * -or- if you are building an application that you want to link to the
  181451. * static library.
  181452. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181453. * the other flags is defined.
  181454. */
  181455. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181456. # define PNG_DLL
  181457. #endif
  181458. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181459. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181460. * command-line override
  181461. */
  181462. #if defined(__CYGWIN__)
  181463. # if !defined(PNG_STATIC)
  181464. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181465. # undef PNG_USE_GLOBAL_ARRAYS
  181466. # endif
  181467. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181468. # define PNG_USE_LOCAL_ARRAYS
  181469. # endif
  181470. # else
  181471. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181472. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181473. # undef PNG_USE_GLOBAL_ARRAYS
  181474. # endif
  181475. # endif
  181476. # endif
  181477. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181478. # define PNG_USE_LOCAL_ARRAYS
  181479. # endif
  181480. #endif
  181481. /* Do not use global arrays (helps with building DLL's)
  181482. * They are no longer used in libpng itself, since version 1.0.5c,
  181483. * but might be required for some pre-1.0.5c applications.
  181484. */
  181485. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181486. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181487. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181488. # define PNG_USE_LOCAL_ARRAYS
  181489. # else
  181490. # define PNG_USE_GLOBAL_ARRAYS
  181491. # endif
  181492. #endif
  181493. #if defined(__CYGWIN__)
  181494. # undef PNGAPI
  181495. # define PNGAPI __cdecl
  181496. # undef PNG_IMPEXP
  181497. # define PNG_IMPEXP
  181498. #endif
  181499. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  181500. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  181501. * Don't ignore those warnings; you must also reset the default calling
  181502. * convention in your compiler to match your PNGAPI, and you must build
  181503. * zlib and your applications the same way you build libpng.
  181504. */
  181505. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  181506. # ifndef PNG_NO_MODULEDEF
  181507. # define PNG_NO_MODULEDEF
  181508. # endif
  181509. #endif
  181510. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  181511. # define PNG_IMPEXP
  181512. #endif
  181513. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  181514. (( defined(_Windows) || defined(_WINDOWS) || \
  181515. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  181516. # ifndef PNGAPI
  181517. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  181518. # define PNGAPI __cdecl
  181519. # else
  181520. # define PNGAPI _cdecl
  181521. # endif
  181522. # endif
  181523. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  181524. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  181525. # define PNG_IMPEXP
  181526. # endif
  181527. # if !defined(PNG_IMPEXP)
  181528. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181529. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  181530. /* Borland/Microsoft */
  181531. # if defined(_MSC_VER) || defined(__BORLANDC__)
  181532. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  181533. # define PNG_EXPORT PNG_EXPORT_TYPE1
  181534. # else
  181535. # define PNG_EXPORT PNG_EXPORT_TYPE2
  181536. # if defined(PNG_BUILD_DLL)
  181537. # define PNG_IMPEXP __export
  181538. # else
  181539. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  181540. VC++ */
  181541. # endif /* Exists in Borland C++ for
  181542. C++ classes (== huge) */
  181543. # endif
  181544. # endif
  181545. # if !defined(PNG_IMPEXP)
  181546. # if defined(PNG_BUILD_DLL)
  181547. # define PNG_IMPEXP __declspec(dllexport)
  181548. # else
  181549. # define PNG_IMPEXP __declspec(dllimport)
  181550. # endif
  181551. # endif
  181552. # endif /* PNG_IMPEXP */
  181553. #else /* !(DLL || non-cygwin WINDOWS) */
  181554. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  181555. # ifndef PNGAPI
  181556. # define PNGAPI _System
  181557. # endif
  181558. # else
  181559. # if 0 /* ... other platforms, with other meanings */
  181560. # endif
  181561. # endif
  181562. #endif
  181563. #ifndef PNGAPI
  181564. # define PNGAPI
  181565. #endif
  181566. #ifndef PNG_IMPEXP
  181567. # define PNG_IMPEXP
  181568. #endif
  181569. #ifdef PNG_BUILDSYMS
  181570. # ifndef PNG_EXPORT
  181571. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  181572. # endif
  181573. # ifdef PNG_USE_GLOBAL_ARRAYS
  181574. # ifndef PNG_EXPORT_VAR
  181575. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  181576. # endif
  181577. # endif
  181578. #endif
  181579. #ifndef PNG_EXPORT
  181580. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181581. #endif
  181582. #ifdef PNG_USE_GLOBAL_ARRAYS
  181583. # ifndef PNG_EXPORT_VAR
  181584. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  181585. # endif
  181586. #endif
  181587. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  181588. * functions that are passed far data must be model independent.
  181589. */
  181590. #ifndef PNG_ABORT
  181591. # define PNG_ABORT() abort()
  181592. #endif
  181593. #ifdef PNG_SETJMP_SUPPORTED
  181594. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  181595. #else
  181596. # define png_jmpbuf(png_ptr) \
  181597. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  181598. #endif
  181599. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  181600. /* use this to make far-to-near assignments */
  181601. # define CHECK 1
  181602. # define NOCHECK 0
  181603. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  181604. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  181605. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  181606. # define png_strcpy _fstrcpy
  181607. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  181608. # define png_strlen _fstrlen
  181609. # define png_memcmp _fmemcmp /* SJT: added */
  181610. # define png_memcpy _fmemcpy
  181611. # define png_memset _fmemset
  181612. #else /* use the usual functions */
  181613. # define CVT_PTR(ptr) (ptr)
  181614. # define CVT_PTR_NOCHECK(ptr) (ptr)
  181615. # ifndef PNG_NO_SNPRINTF
  181616. # ifdef _MSC_VER
  181617. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  181618. # define png_snprintf2 _snprintf
  181619. # define png_snprintf6 _snprintf
  181620. # else
  181621. # define png_snprintf snprintf /* Added to v 1.2.19 */
  181622. # define png_snprintf2 snprintf
  181623. # define png_snprintf6 snprintf
  181624. # endif
  181625. # else
  181626. /* You don't have or don't want to use snprintf(). Caution: Using
  181627. * sprintf instead of snprintf exposes your application to accidental
  181628. * or malevolent buffer overflows. If you don't have snprintf()
  181629. * as a general rule you should provide one (you can get one from
  181630. * Portable OpenSSH). */
  181631. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  181632. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  181633. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  181634. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  181635. # endif
  181636. # define png_strcpy strcpy
  181637. # define png_strncpy strncpy /* Added to v 1.2.6 */
  181638. # define png_strlen strlen
  181639. # define png_memcmp memcmp /* SJT: added */
  181640. # define png_memcpy memcpy
  181641. # define png_memset memset
  181642. #endif
  181643. /* End of memory model independent support */
  181644. /* Just a little check that someone hasn't tried to define something
  181645. * contradictory.
  181646. */
  181647. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  181648. # undef PNG_ZBUF_SIZE
  181649. # define PNG_ZBUF_SIZE 65536L
  181650. #endif
  181651. /* Added at libpng-1.2.8 */
  181652. #endif /* PNG_VERSION_INFO_ONLY */
  181653. #endif /* PNGCONF_H */
  181654. /*** End of inlined file: pngconf.h ***/
  181655. #ifdef _MSC_VER
  181656. #pragma warning (disable: 4996 4100)
  181657. #endif
  181658. /*
  181659. * Added at libpng-1.2.8 */
  181660. /* Ref MSDN: Private as priority over Special
  181661. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  181662. * procedures. If this value is given, the StringFileInfo block must
  181663. * contain a PrivateBuild string.
  181664. *
  181665. * VS_FF_SPECIALBUILD File *was* built by the original company using
  181666. * standard release procedures but is a variation of the standard
  181667. * file of the same version number. If this value is given, the
  181668. * StringFileInfo block must contain a SpecialBuild string.
  181669. */
  181670. #if defined(PNG_USER_PRIVATEBUILD)
  181671. # define PNG_LIBPNG_BUILD_TYPE \
  181672. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  181673. #else
  181674. # if defined(PNG_LIBPNG_SPECIALBUILD)
  181675. # define PNG_LIBPNG_BUILD_TYPE \
  181676. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  181677. # else
  181678. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  181679. # endif
  181680. #endif
  181681. #ifndef PNG_VERSION_INFO_ONLY
  181682. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  181683. #ifdef __cplusplus
  181684. //extern "C" {
  181685. #endif /* __cplusplus */
  181686. /* This file is arranged in several sections. The first section contains
  181687. * structure and type definitions. The second section contains the external
  181688. * library functions, while the third has the internal library functions,
  181689. * which applications aren't expected to use directly.
  181690. */
  181691. #ifndef PNG_NO_TYPECAST_NULL
  181692. #define int_p_NULL (int *)NULL
  181693. #define png_bytep_NULL (png_bytep)NULL
  181694. #define png_bytepp_NULL (png_bytepp)NULL
  181695. #define png_doublep_NULL (png_doublep)NULL
  181696. #define png_error_ptr_NULL (png_error_ptr)NULL
  181697. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  181698. #define png_free_ptr_NULL (png_free_ptr)NULL
  181699. #define png_infopp_NULL (png_infopp)NULL
  181700. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  181701. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  181702. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  181703. #define png_structp_NULL (png_structp)NULL
  181704. #define png_uint_16p_NULL (png_uint_16p)NULL
  181705. #define png_voidp_NULL (png_voidp)NULL
  181706. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  181707. #else
  181708. #define int_p_NULL NULL
  181709. #define png_bytep_NULL NULL
  181710. #define png_bytepp_NULL NULL
  181711. #define png_doublep_NULL NULL
  181712. #define png_error_ptr_NULL NULL
  181713. #define png_flush_ptr_NULL NULL
  181714. #define png_free_ptr_NULL NULL
  181715. #define png_infopp_NULL NULL
  181716. #define png_malloc_ptr_NULL NULL
  181717. #define png_read_status_ptr_NULL NULL
  181718. #define png_rw_ptr_NULL NULL
  181719. #define png_structp_NULL NULL
  181720. #define png_uint_16p_NULL NULL
  181721. #define png_voidp_NULL NULL
  181722. #define png_write_status_ptr_NULL NULL
  181723. #endif
  181724. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  181725. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  181726. /* Version information for C files, stored in png.c. This had better match
  181727. * the version above.
  181728. */
  181729. #ifdef PNG_USE_GLOBAL_ARRAYS
  181730. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  181731. /* need room for 99.99.99beta99z */
  181732. #else
  181733. #define png_libpng_ver png_get_header_ver(NULL)
  181734. #endif
  181735. #ifdef PNG_USE_GLOBAL_ARRAYS
  181736. /* This was removed in version 1.0.5c */
  181737. /* Structures to facilitate easy interlacing. See png.c for more details */
  181738. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  181739. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  181740. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  181741. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  181742. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  181743. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  181744. /* This isn't currently used. If you need it, see png.c for more details.
  181745. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  181746. */
  181747. #endif
  181748. #endif /* PNG_NO_EXTERN */
  181749. /* Three color definitions. The order of the red, green, and blue, (and the
  181750. * exact size) is not important, although the size of the fields need to
  181751. * be png_byte or png_uint_16 (as defined below).
  181752. */
  181753. typedef struct png_color_struct
  181754. {
  181755. png_byte red;
  181756. png_byte green;
  181757. png_byte blue;
  181758. } png_color;
  181759. typedef png_color FAR * png_colorp;
  181760. typedef png_color FAR * FAR * png_colorpp;
  181761. typedef struct png_color_16_struct
  181762. {
  181763. png_byte index; /* used for palette files */
  181764. png_uint_16 red; /* for use in red green blue files */
  181765. png_uint_16 green;
  181766. png_uint_16 blue;
  181767. png_uint_16 gray; /* for use in grayscale files */
  181768. } png_color_16;
  181769. typedef png_color_16 FAR * png_color_16p;
  181770. typedef png_color_16 FAR * FAR * png_color_16pp;
  181771. typedef struct png_color_8_struct
  181772. {
  181773. png_byte red; /* for use in red green blue files */
  181774. png_byte green;
  181775. png_byte blue;
  181776. png_byte gray; /* for use in grayscale files */
  181777. png_byte alpha; /* for alpha channel files */
  181778. } png_color_8;
  181779. typedef png_color_8 FAR * png_color_8p;
  181780. typedef png_color_8 FAR * FAR * png_color_8pp;
  181781. /*
  181782. * The following two structures are used for the in-core representation
  181783. * of sPLT chunks.
  181784. */
  181785. typedef struct png_sPLT_entry_struct
  181786. {
  181787. png_uint_16 red;
  181788. png_uint_16 green;
  181789. png_uint_16 blue;
  181790. png_uint_16 alpha;
  181791. png_uint_16 frequency;
  181792. } png_sPLT_entry;
  181793. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  181794. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  181795. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  181796. * occupy the LSB of their respective members, and the MSB of each member
  181797. * is zero-filled. The frequency member always occupies the full 16 bits.
  181798. */
  181799. typedef struct png_sPLT_struct
  181800. {
  181801. png_charp name; /* palette name */
  181802. png_byte depth; /* depth of palette samples */
  181803. png_sPLT_entryp entries; /* palette entries */
  181804. png_int_32 nentries; /* number of palette entries */
  181805. } png_sPLT_t;
  181806. typedef png_sPLT_t FAR * png_sPLT_tp;
  181807. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  181808. #ifdef PNG_TEXT_SUPPORTED
  181809. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  181810. * and whether that contents is compressed or not. The "key" field
  181811. * points to a regular zero-terminated C string. The "text", "lang", and
  181812. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  181813. * However, the * structure returned by png_get_text() will always contain
  181814. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  181815. * so they can be safely used in printf() and other string-handling functions.
  181816. */
  181817. typedef struct png_text_struct
  181818. {
  181819. int compression; /* compression value:
  181820. -1: tEXt, none
  181821. 0: zTXt, deflate
  181822. 1: iTXt, none
  181823. 2: iTXt, deflate */
  181824. png_charp key; /* keyword, 1-79 character description of "text" */
  181825. png_charp text; /* comment, may be an empty string (ie "")
  181826. or a NULL pointer */
  181827. png_size_t text_length; /* length of the text string */
  181828. #ifdef PNG_iTXt_SUPPORTED
  181829. png_size_t itxt_length; /* length of the itxt string */
  181830. png_charp lang; /* language code, 0-79 characters
  181831. or a NULL pointer */
  181832. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  181833. chars or a NULL pointer */
  181834. #endif
  181835. } png_text;
  181836. typedef png_text FAR * png_textp;
  181837. typedef png_text FAR * FAR * png_textpp;
  181838. #endif
  181839. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  181840. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  181841. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  181842. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  181843. #define PNG_TEXT_COMPRESSION_NONE -1
  181844. #define PNG_TEXT_COMPRESSION_zTXt 0
  181845. #define PNG_ITXT_COMPRESSION_NONE 1
  181846. #define PNG_ITXT_COMPRESSION_zTXt 2
  181847. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  181848. /* png_time is a way to hold the time in an machine independent way.
  181849. * Two conversions are provided, both from time_t and struct tm. There
  181850. * is no portable way to convert to either of these structures, as far
  181851. * as I know. If you know of a portable way, send it to me. As a side
  181852. * note - PNG has always been Year 2000 compliant!
  181853. */
  181854. typedef struct png_time_struct
  181855. {
  181856. png_uint_16 year; /* full year, as in, 1995 */
  181857. png_byte month; /* month of year, 1 - 12 */
  181858. png_byte day; /* day of month, 1 - 31 */
  181859. png_byte hour; /* hour of day, 0 - 23 */
  181860. png_byte minute; /* minute of hour, 0 - 59 */
  181861. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  181862. } png_time;
  181863. typedef png_time FAR * png_timep;
  181864. typedef png_time FAR * FAR * png_timepp;
  181865. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181866. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  181867. * no specific support. The idea is that we can use this to queue
  181868. * up private chunks for output even though the library doesn't actually
  181869. * know about their semantics.
  181870. */
  181871. typedef struct png_unknown_chunk_t
  181872. {
  181873. png_byte name[5];
  181874. png_byte *data;
  181875. png_size_t size;
  181876. /* libpng-using applications should NOT directly modify this byte. */
  181877. png_byte location; /* mode of operation at read time */
  181878. }
  181879. png_unknown_chunk;
  181880. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  181881. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  181882. #endif
  181883. /* png_info is a structure that holds the information in a PNG file so
  181884. * that the application can find out the characteristics of the image.
  181885. * If you are reading the file, this structure will tell you what is
  181886. * in the PNG file. If you are writing the file, fill in the information
  181887. * you want to put into the PNG file, then call png_write_info().
  181888. * The names chosen should be very close to the PNG specification, so
  181889. * consult that document for information about the meaning of each field.
  181890. *
  181891. * With libpng < 0.95, it was only possible to directly set and read the
  181892. * the values in the png_info_struct, which meant that the contents and
  181893. * order of the values had to remain fixed. With libpng 0.95 and later,
  181894. * however, there are now functions that abstract the contents of
  181895. * png_info_struct from the application, so this makes it easier to use
  181896. * libpng with dynamic libraries, and even makes it possible to use
  181897. * libraries that don't have all of the libpng ancillary chunk-handing
  181898. * functionality.
  181899. *
  181900. * In any case, the order of the parameters in png_info_struct should NOT
  181901. * be changed for as long as possible to keep compatibility with applications
  181902. * that use the old direct-access method with png_info_struct.
  181903. *
  181904. * The following members may have allocated storage attached that should be
  181905. * cleaned up before the structure is discarded: palette, trans, text,
  181906. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  181907. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  181908. * are automatically freed when the info structure is deallocated, if they were
  181909. * allocated internally by libpng. This behavior can be changed by means
  181910. * of the png_data_freer() function.
  181911. *
  181912. * More allocation details: all the chunk-reading functions that
  181913. * change these members go through the corresponding png_set_*
  181914. * functions. A function to clear these members is available: see
  181915. * png_free_data(). The png_set_* functions do not depend on being
  181916. * able to point info structure members to any of the storage they are
  181917. * passed (they make their own copies), EXCEPT that the png_set_text
  181918. * functions use the same storage passed to them in the text_ptr or
  181919. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  181920. * functions do not make their own copies.
  181921. */
  181922. typedef struct png_info_struct
  181923. {
  181924. /* the following are necessary for every PNG file */
  181925. png_uint_32 width; /* width of image in pixels (from IHDR) */
  181926. png_uint_32 height; /* height of image in pixels (from IHDR) */
  181927. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  181928. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  181929. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  181930. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  181931. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  181932. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  181933. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  181934. /* The following three should have been named *_method not *_type */
  181935. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  181936. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  181937. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  181938. /* The following is informational only on read, and not used on writes. */
  181939. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  181940. png_byte pixel_depth; /* number of bits per pixel */
  181941. png_byte spare_byte; /* to align the data, and for future use */
  181942. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  181943. /* The rest of the data is optional. If you are reading, check the
  181944. * valid field to see if the information in these are valid. If you
  181945. * are writing, set the valid field to those chunks you want written,
  181946. * and initialize the appropriate fields below.
  181947. */
  181948. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  181949. /* The gAMA chunk describes the gamma characteristics of the system
  181950. * on which the image was created, normally in the range [1.0, 2.5].
  181951. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  181952. */
  181953. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  181954. #endif
  181955. #if defined(PNG_sRGB_SUPPORTED)
  181956. /* GR-P, 0.96a */
  181957. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  181958. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  181959. #endif
  181960. #if defined(PNG_TEXT_SUPPORTED)
  181961. /* The tEXt, and zTXt chunks contain human-readable textual data in
  181962. * uncompressed, compressed, and optionally compressed forms, respectively.
  181963. * The data in "text" is an array of pointers to uncompressed,
  181964. * null-terminated C strings. Each chunk has a keyword that describes the
  181965. * textual data contained in that chunk. Keywords are not required to be
  181966. * unique, and the text string may be empty. Any number of text chunks may
  181967. * be in an image.
  181968. */
  181969. int num_text; /* number of comments read/to write */
  181970. int max_text; /* current size of text array */
  181971. png_textp text; /* array of comments read/to write */
  181972. #endif /* PNG_TEXT_SUPPORTED */
  181973. #if defined(PNG_tIME_SUPPORTED)
  181974. /* The tIME chunk holds the last time the displayed image data was
  181975. * modified. See the png_time struct for the contents of this struct.
  181976. */
  181977. png_time mod_time;
  181978. #endif
  181979. #if defined(PNG_sBIT_SUPPORTED)
  181980. /* The sBIT chunk specifies the number of significant high-order bits
  181981. * in the pixel data. Values are in the range [1, bit_depth], and are
  181982. * only specified for the channels in the pixel data. The contents of
  181983. * the low-order bits is not specified. Data is valid if
  181984. * (valid & PNG_INFO_sBIT) is non-zero.
  181985. */
  181986. png_color_8 sig_bit; /* significant bits in color channels */
  181987. #endif
  181988. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  181989. defined(PNG_READ_BACKGROUND_SUPPORTED)
  181990. /* The tRNS chunk supplies transparency data for paletted images and
  181991. * other image types that don't need a full alpha channel. There are
  181992. * "num_trans" transparency values for a paletted image, stored in the
  181993. * same order as the palette colors, starting from index 0. Values
  181994. * for the data are in the range [0, 255], ranging from fully transparent
  181995. * to fully opaque, respectively. For non-paletted images, there is a
  181996. * single color specified that should be treated as fully transparent.
  181997. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  181998. */
  181999. png_bytep trans; /* transparent values for paletted image */
  182000. png_color_16 trans_values; /* transparent color for non-palette image */
  182001. #endif
  182002. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182003. /* The bKGD chunk gives the suggested image background color if the
  182004. * display program does not have its own background color and the image
  182005. * is needs to composited onto a background before display. The colors
  182006. * in "background" are normally in the same color space/depth as the
  182007. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  182008. */
  182009. png_color_16 background;
  182010. #endif
  182011. #if defined(PNG_oFFs_SUPPORTED)
  182012. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  182013. * and downwards from the top-left corner of the display, page, or other
  182014. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  182015. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  182016. */
  182017. png_int_32 x_offset; /* x offset on page */
  182018. png_int_32 y_offset; /* y offset on page */
  182019. png_byte offset_unit_type; /* offset units type */
  182020. #endif
  182021. #if defined(PNG_pHYs_SUPPORTED)
  182022. /* The pHYs chunk gives the physical pixel density of the image for
  182023. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182024. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182025. */
  182026. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182027. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182028. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182029. #endif
  182030. #if defined(PNG_hIST_SUPPORTED)
  182031. /* The hIST chunk contains the relative frequency or importance of the
  182032. * various palette entries, so that a viewer can intelligently select a
  182033. * reduced-color palette, if required. Data is an array of "num_palette"
  182034. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182035. * is non-zero.
  182036. */
  182037. png_uint_16p hist;
  182038. #endif
  182039. #ifdef PNG_cHRM_SUPPORTED
  182040. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182041. * on which the PNG was created. This data allows the viewer to do gamut
  182042. * mapping of the input image to ensure that the viewer sees the same
  182043. * colors in the image as the creator. Values are in the range
  182044. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182045. */
  182046. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182047. float x_white;
  182048. float y_white;
  182049. float x_red;
  182050. float y_red;
  182051. float x_green;
  182052. float y_green;
  182053. float x_blue;
  182054. float y_blue;
  182055. #endif
  182056. #endif
  182057. #if defined(PNG_pCAL_SUPPORTED)
  182058. /* The pCAL chunk describes a transformation between the stored pixel
  182059. * values and original physical data values used to create the image.
  182060. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182061. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182062. * (possibly non-linear) transformation function given by "pcal_type"
  182063. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182064. * defines below, and the PNG-Group's PNG extensions document for a
  182065. * complete description of the transformations and how they should be
  182066. * implemented, and for a description of the ASCII parameter strings.
  182067. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182068. */
  182069. png_charp pcal_purpose; /* pCAL chunk description string */
  182070. png_int_32 pcal_X0; /* minimum value */
  182071. png_int_32 pcal_X1; /* maximum value */
  182072. png_charp pcal_units; /* Latin-1 string giving physical units */
  182073. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182074. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182075. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182076. #endif
  182077. /* New members added in libpng-1.0.6 */
  182078. #ifdef PNG_FREE_ME_SUPPORTED
  182079. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182080. #endif
  182081. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182082. /* storage for unknown chunks that the library doesn't recognize. */
  182083. png_unknown_chunkp unknown_chunks;
  182084. png_size_t unknown_chunks_num;
  182085. #endif
  182086. #if defined(PNG_iCCP_SUPPORTED)
  182087. /* iCCP chunk data. */
  182088. png_charp iccp_name; /* profile name */
  182089. png_charp iccp_profile; /* International Color Consortium profile data */
  182090. /* Note to maintainer: should be png_bytep */
  182091. png_uint_32 iccp_proflen; /* ICC profile data length */
  182092. png_byte iccp_compression; /* Always zero */
  182093. #endif
  182094. #if defined(PNG_sPLT_SUPPORTED)
  182095. /* data on sPLT chunks (there may be more than one). */
  182096. png_sPLT_tp splt_palettes;
  182097. png_uint_32 splt_palettes_num;
  182098. #endif
  182099. #if defined(PNG_sCAL_SUPPORTED)
  182100. /* The sCAL chunk describes the actual physical dimensions of the
  182101. * subject matter of the graphic. The chunk contains a unit specification
  182102. * a byte value, and two ASCII strings representing floating-point
  182103. * values. The values are width and height corresponsing to one pixel
  182104. * in the image. This external representation is converted to double
  182105. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182106. */
  182107. png_byte scal_unit; /* unit of physical scale */
  182108. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182109. double scal_pixel_width; /* width of one pixel */
  182110. double scal_pixel_height; /* height of one pixel */
  182111. #endif
  182112. #ifdef PNG_FIXED_POINT_SUPPORTED
  182113. png_charp scal_s_width; /* string containing height */
  182114. png_charp scal_s_height; /* string containing width */
  182115. #endif
  182116. #endif
  182117. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182118. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182119. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182120. png_bytepp row_pointers; /* the image bits */
  182121. #endif
  182122. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182123. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182124. #endif
  182125. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182126. png_fixed_point int_x_white;
  182127. png_fixed_point int_y_white;
  182128. png_fixed_point int_x_red;
  182129. png_fixed_point int_y_red;
  182130. png_fixed_point int_x_green;
  182131. png_fixed_point int_y_green;
  182132. png_fixed_point int_x_blue;
  182133. png_fixed_point int_y_blue;
  182134. #endif
  182135. } png_info;
  182136. typedef png_info FAR * png_infop;
  182137. typedef png_info FAR * FAR * png_infopp;
  182138. /* Maximum positive integer used in PNG is (2^31)-1 */
  182139. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182140. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182141. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182142. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182143. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182144. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182145. #endif
  182146. /* These describe the color_type field in png_info. */
  182147. /* color type masks */
  182148. #define PNG_COLOR_MASK_PALETTE 1
  182149. #define PNG_COLOR_MASK_COLOR 2
  182150. #define PNG_COLOR_MASK_ALPHA 4
  182151. /* color types. Note that not all combinations are legal */
  182152. #define PNG_COLOR_TYPE_GRAY 0
  182153. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182154. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182155. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182156. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182157. /* aliases */
  182158. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182159. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182160. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182161. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182162. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182163. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182164. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182165. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182166. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182167. /* These are for the interlacing type. These values should NOT be changed. */
  182168. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182169. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182170. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182171. /* These are for the oFFs chunk. These values should NOT be changed. */
  182172. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182173. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182174. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182175. /* These are for the pCAL chunk. These values should NOT be changed. */
  182176. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182177. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182178. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182179. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182180. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182181. /* These are for the sCAL chunk. These values should NOT be changed. */
  182182. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182183. #define PNG_SCALE_METER 1 /* meters per pixel */
  182184. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182185. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182186. /* These are for the pHYs chunk. These values should NOT be changed. */
  182187. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182188. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182189. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182190. /* These are for the sRGB chunk. These values should NOT be changed. */
  182191. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182192. #define PNG_sRGB_INTENT_RELATIVE 1
  182193. #define PNG_sRGB_INTENT_SATURATION 2
  182194. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182195. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182196. /* This is for text chunks */
  182197. #define PNG_KEYWORD_MAX_LENGTH 79
  182198. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182199. #define PNG_MAX_PALETTE_LENGTH 256
  182200. /* These determine if an ancillary chunk's data has been successfully read
  182201. * from the PNG header, or if the application has filled in the corresponding
  182202. * data in the info_struct to be written into the output file. The values
  182203. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182204. */
  182205. #define PNG_INFO_gAMA 0x0001
  182206. #define PNG_INFO_sBIT 0x0002
  182207. #define PNG_INFO_cHRM 0x0004
  182208. #define PNG_INFO_PLTE 0x0008
  182209. #define PNG_INFO_tRNS 0x0010
  182210. #define PNG_INFO_bKGD 0x0020
  182211. #define PNG_INFO_hIST 0x0040
  182212. #define PNG_INFO_pHYs 0x0080
  182213. #define PNG_INFO_oFFs 0x0100
  182214. #define PNG_INFO_tIME 0x0200
  182215. #define PNG_INFO_pCAL 0x0400
  182216. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182217. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182218. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182219. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182220. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182221. /* This is used for the transformation routines, as some of them
  182222. * change these values for the row. It also should enable using
  182223. * the routines for other purposes.
  182224. */
  182225. typedef struct png_row_info_struct
  182226. {
  182227. png_uint_32 width; /* width of row */
  182228. png_uint_32 rowbytes; /* number of bytes in row */
  182229. png_byte color_type; /* color type of row */
  182230. png_byte bit_depth; /* bit depth of row */
  182231. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182232. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182233. } png_row_info;
  182234. typedef png_row_info FAR * png_row_infop;
  182235. typedef png_row_info FAR * FAR * png_row_infopp;
  182236. /* These are the function types for the I/O functions and for the functions
  182237. * that allow the user to override the default I/O functions with his or her
  182238. * own. The png_error_ptr type should match that of user-supplied warning
  182239. * and error functions, while the png_rw_ptr type should match that of the
  182240. * user read/write data functions.
  182241. */
  182242. typedef struct png_struct_def png_struct;
  182243. typedef png_struct FAR * png_structp;
  182244. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182245. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182246. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182247. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182248. int));
  182249. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182250. int));
  182251. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182252. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182253. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182254. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182255. png_uint_32, int));
  182256. #endif
  182257. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182258. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182259. defined(PNG_LEGACY_SUPPORTED)
  182260. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182261. png_row_infop, png_bytep));
  182262. #endif
  182263. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182264. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182265. #endif
  182266. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182267. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182268. #endif
  182269. /* Transform masks for the high-level interface */
  182270. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182271. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182272. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182273. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182274. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182275. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182276. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182277. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182278. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182279. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182280. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182281. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182282. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182283. /* Flags for MNG supported features */
  182284. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182285. #define PNG_FLAG_MNG_FILTER_64 0x04
  182286. #define PNG_ALL_MNG_FEATURES 0x05
  182287. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182288. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182289. /* The structure that holds the information to read and write PNG files.
  182290. * The only people who need to care about what is inside of this are the
  182291. * people who will be modifying the library for their own special needs.
  182292. * It should NOT be accessed directly by an application, except to store
  182293. * the jmp_buf.
  182294. */
  182295. struct png_struct_def
  182296. {
  182297. #ifdef PNG_SETJMP_SUPPORTED
  182298. jmp_buf jmpbuf; /* used in png_error */
  182299. #endif
  182300. png_error_ptr error_fn; /* function for printing errors and aborting */
  182301. png_error_ptr warning_fn; /* function for printing warnings */
  182302. png_voidp error_ptr; /* user supplied struct for error functions */
  182303. png_rw_ptr write_data_fn; /* function for writing output data */
  182304. png_rw_ptr read_data_fn; /* function for reading input data */
  182305. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182306. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182307. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182308. #endif
  182309. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182310. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182311. #endif
  182312. /* These were added in libpng-1.0.2 */
  182313. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182314. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182315. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182316. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182317. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182318. png_byte user_transform_channels; /* channels in user transformed pixels */
  182319. #endif
  182320. #endif
  182321. png_uint_32 mode; /* tells us where we are in the PNG file */
  182322. png_uint_32 flags; /* flags indicating various things to libpng */
  182323. png_uint_32 transformations; /* which transformations to perform */
  182324. z_stream zstream; /* pointer to decompression structure (below) */
  182325. png_bytep zbuf; /* buffer for zlib */
  182326. png_size_t zbuf_size; /* size of zbuf */
  182327. int zlib_level; /* holds zlib compression level */
  182328. int zlib_method; /* holds zlib compression method */
  182329. int zlib_window_bits; /* holds zlib compression window bits */
  182330. int zlib_mem_level; /* holds zlib compression memory level */
  182331. int zlib_strategy; /* holds zlib compression strategy */
  182332. png_uint_32 width; /* width of image in pixels */
  182333. png_uint_32 height; /* height of image in pixels */
  182334. png_uint_32 num_rows; /* number of rows in current pass */
  182335. png_uint_32 usr_width; /* width of row at start of write */
  182336. png_uint_32 rowbytes; /* size of row in bytes */
  182337. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182338. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182339. png_uint_32 row_number; /* current row in interlace pass */
  182340. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182341. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182342. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182343. png_bytep up_row; /* buffer to save "up" row when filtering */
  182344. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182345. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182346. png_row_info row_info; /* used for transformation routines */
  182347. png_uint_32 idat_size; /* current IDAT size for read */
  182348. png_uint_32 crc; /* current chunk CRC value */
  182349. png_colorp palette; /* palette from the input file */
  182350. png_uint_16 num_palette; /* number of color entries in palette */
  182351. png_uint_16 num_trans; /* number of transparency values */
  182352. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182353. png_byte compression; /* file compression type (always 0) */
  182354. png_byte filter; /* file filter type (always 0) */
  182355. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182356. png_byte pass; /* current interlace pass (0 - 6) */
  182357. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182358. png_byte color_type; /* color type of file */
  182359. png_byte bit_depth; /* bit depth of file */
  182360. png_byte usr_bit_depth; /* bit depth of users row */
  182361. png_byte pixel_depth; /* number of bits per pixel */
  182362. png_byte channels; /* number of channels in file */
  182363. png_byte usr_channels; /* channels at start of write */
  182364. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182365. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182366. #ifdef PNG_LEGACY_SUPPORTED
  182367. png_byte filler; /* filler byte for pixel expansion */
  182368. #else
  182369. png_uint_16 filler; /* filler bytes for pixel expansion */
  182370. #endif
  182371. #endif
  182372. #if defined(PNG_bKGD_SUPPORTED)
  182373. png_byte background_gamma_type;
  182374. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182375. float background_gamma;
  182376. # endif
  182377. png_color_16 background; /* background color in screen gamma space */
  182378. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182379. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182380. #endif
  182381. #endif /* PNG_bKGD_SUPPORTED */
  182382. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182383. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182384. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182385. png_uint_32 flush_rows; /* number of rows written since last flush */
  182386. #endif
  182387. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182388. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182389. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182390. float gamma; /* file gamma value */
  182391. float screen_gamma; /* screen gamma value (display_exponent) */
  182392. #endif
  182393. #endif
  182394. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182395. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182396. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182397. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182398. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182399. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182400. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182401. #endif
  182402. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182403. png_color_8 sig_bit; /* significant bits in each available channel */
  182404. #endif
  182405. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182406. png_color_8 shift; /* shift for significant bit tranformation */
  182407. #endif
  182408. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182409. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182410. png_bytep trans; /* transparency values for paletted files */
  182411. png_color_16 trans_values; /* transparency values for non-paletted files */
  182412. #endif
  182413. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182414. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182415. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182416. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182417. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182418. png_progressive_end_ptr end_fn; /* called after image is complete */
  182419. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182420. png_bytep save_buffer; /* buffer for previously read data */
  182421. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182422. png_bytep current_buffer; /* buffer for recently used data */
  182423. png_uint_32 push_length; /* size of current input chunk */
  182424. png_uint_32 skip_length; /* bytes to skip in input data */
  182425. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182426. png_size_t save_buffer_max; /* total size of save_buffer */
  182427. png_size_t buffer_size; /* total amount of available input data */
  182428. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182429. int process_mode; /* what push library is currently doing */
  182430. int cur_palette; /* current push library palette index */
  182431. # if defined(PNG_TEXT_SUPPORTED)
  182432. png_size_t current_text_size; /* current size of text input data */
  182433. png_size_t current_text_left; /* how much text left to read in input */
  182434. png_charp current_text; /* current text chunk buffer */
  182435. png_charp current_text_ptr; /* current location in current_text */
  182436. # endif /* PNG_TEXT_SUPPORTED */
  182437. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182438. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182439. /* for the Borland special 64K segment handler */
  182440. png_bytepp offset_table_ptr;
  182441. png_bytep offset_table;
  182442. png_uint_16 offset_table_number;
  182443. png_uint_16 offset_table_count;
  182444. png_uint_16 offset_table_count_free;
  182445. #endif
  182446. #if defined(PNG_READ_DITHER_SUPPORTED)
  182447. png_bytep palette_lookup; /* lookup table for dithering */
  182448. png_bytep dither_index; /* index translation for palette files */
  182449. #endif
  182450. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182451. png_uint_16p hist; /* histogram */
  182452. #endif
  182453. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182454. png_byte heuristic_method; /* heuristic for row filter selection */
  182455. png_byte num_prev_filters; /* number of weights for previous rows */
  182456. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182457. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182458. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182459. png_uint_16p filter_costs; /* relative filter calculation cost */
  182460. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182461. #endif
  182462. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182463. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182464. #endif
  182465. /* New members added in libpng-1.0.6 */
  182466. #ifdef PNG_FREE_ME_SUPPORTED
  182467. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182468. #endif
  182469. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182470. png_voidp user_chunk_ptr;
  182471. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182472. #endif
  182473. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182474. int num_chunk_list;
  182475. png_bytep chunk_list;
  182476. #endif
  182477. /* New members added in libpng-1.0.3 */
  182478. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182479. png_byte rgb_to_gray_status;
  182480. /* These were changed from png_byte in libpng-1.0.6 */
  182481. png_uint_16 rgb_to_gray_red_coeff;
  182482. png_uint_16 rgb_to_gray_green_coeff;
  182483. png_uint_16 rgb_to_gray_blue_coeff;
  182484. #endif
  182485. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182486. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182487. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182488. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182489. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182490. #ifdef PNG_1_0_X
  182491. png_byte mng_features_permitted;
  182492. #else
  182493. png_uint_32 mng_features_permitted;
  182494. #endif /* PNG_1_0_X */
  182495. #endif
  182496. /* New member added in libpng-1.0.7 */
  182497. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182498. png_fixed_point int_gamma;
  182499. #endif
  182500. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  182501. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182502. png_byte filter_type;
  182503. #endif
  182504. #if defined(PNG_1_0_X)
  182505. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  182506. png_uint_32 row_buf_size;
  182507. #endif
  182508. /* New members added in libpng-1.2.0 */
  182509. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182510. # if !defined(PNG_1_0_X)
  182511. # if defined(PNG_MMX_CODE_SUPPORTED)
  182512. png_byte mmx_bitdepth_threshold;
  182513. png_uint_32 mmx_rowbytes_threshold;
  182514. # endif
  182515. png_uint_32 asm_flags;
  182516. # endif
  182517. #endif
  182518. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  182519. #ifdef PNG_USER_MEM_SUPPORTED
  182520. png_voidp mem_ptr; /* user supplied struct for mem functions */
  182521. png_malloc_ptr malloc_fn; /* function for allocating memory */
  182522. png_free_ptr free_fn; /* function for freeing memory */
  182523. #endif
  182524. /* New member added in libpng-1.0.13 and 1.2.0 */
  182525. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  182526. #if defined(PNG_READ_DITHER_SUPPORTED)
  182527. /* The following three members were added at version 1.0.14 and 1.2.4 */
  182528. png_bytep dither_sort; /* working sort array */
  182529. png_bytep index_to_palette; /* where the original index currently is */
  182530. /* in the palette */
  182531. png_bytep palette_to_index; /* which original index points to this */
  182532. /* palette color */
  182533. #endif
  182534. /* New members added in libpng-1.0.16 and 1.2.6 */
  182535. png_byte compression_type;
  182536. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182537. png_uint_32 user_width_max;
  182538. png_uint_32 user_height_max;
  182539. #endif
  182540. /* New member added in libpng-1.0.25 and 1.2.17 */
  182541. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182542. /* storage for unknown chunk that the library doesn't recognize. */
  182543. png_unknown_chunk unknown_chunk;
  182544. #endif
  182545. };
  182546. /* This triggers a compiler error in png.c, if png.c and png.h
  182547. * do not agree upon the version number.
  182548. */
  182549. typedef png_structp version_1_2_21;
  182550. typedef png_struct FAR * FAR * png_structpp;
  182551. /* Here are the function definitions most commonly used. This is not
  182552. * the place to find out how to use libpng. See libpng.txt for the
  182553. * full explanation, see example.c for the summary. This just provides
  182554. * a simple one line description of the use of each function.
  182555. */
  182556. /* Returns the version number of the library */
  182557. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  182558. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  182559. * Handling more than 8 bytes from the beginning of the file is an error.
  182560. */
  182561. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  182562. int num_bytes));
  182563. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  182564. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  182565. * signature, and non-zero otherwise. Having num_to_check == 0 or
  182566. * start > 7 will always fail (ie return non-zero).
  182567. */
  182568. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  182569. png_size_t num_to_check));
  182570. /* Simple signature checking function. This is the same as calling
  182571. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  182572. */
  182573. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  182574. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  182575. extern PNG_EXPORT(png_structp,png_create_read_struct)
  182576. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182577. png_error_ptr error_fn, png_error_ptr warn_fn));
  182578. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  182579. extern PNG_EXPORT(png_structp,png_create_write_struct)
  182580. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182581. png_error_ptr error_fn, png_error_ptr warn_fn));
  182582. #ifdef PNG_WRITE_SUPPORTED
  182583. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  182584. PNGARG((png_structp png_ptr));
  182585. #endif
  182586. #ifdef PNG_WRITE_SUPPORTED
  182587. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  182588. PNGARG((png_structp png_ptr, png_uint_32 size));
  182589. #endif
  182590. /* Reset the compression stream */
  182591. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  182592. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  182593. #ifdef PNG_USER_MEM_SUPPORTED
  182594. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  182595. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182596. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182597. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182598. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  182599. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182600. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182601. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182602. #endif
  182603. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  182604. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  182605. png_bytep chunk_name, png_bytep data, png_size_t length));
  182606. /* Write the start of a PNG chunk - length and chunk name. */
  182607. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  182608. png_bytep chunk_name, png_uint_32 length));
  182609. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  182610. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  182611. png_bytep data, png_size_t length));
  182612. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  182613. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  182614. /* Allocate and initialize the info structure */
  182615. extern PNG_EXPORT(png_infop,png_create_info_struct)
  182616. PNGARG((png_structp png_ptr));
  182617. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182618. /* Initialize the info structure (old interface - DEPRECATED) */
  182619. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  182620. #undef png_info_init
  182621. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  182622. png_sizeof(png_info));
  182623. #endif
  182624. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  182625. png_size_t png_info_struct_size));
  182626. /* Writes all the PNG information before the image. */
  182627. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  182628. png_infop info_ptr));
  182629. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  182630. png_infop info_ptr));
  182631. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182632. /* read the information before the actual image data. */
  182633. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  182634. png_infop info_ptr));
  182635. #endif
  182636. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182637. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  182638. PNGARG((png_structp png_ptr, png_timep ptime));
  182639. #endif
  182640. #if !defined(_WIN32_WCE)
  182641. /* "time.h" functions are not supported on WindowsCE */
  182642. #if defined(PNG_WRITE_tIME_SUPPORTED)
  182643. /* convert from a struct tm to png_time */
  182644. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  182645. struct tm FAR * ttime));
  182646. /* convert from time_t to png_time. Uses gmtime() */
  182647. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  182648. time_t ttime));
  182649. #endif /* PNG_WRITE_tIME_SUPPORTED */
  182650. #endif /* _WIN32_WCE */
  182651. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182652. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  182653. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  182654. #if !defined(PNG_1_0_X)
  182655. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  182656. png_ptr));
  182657. #endif
  182658. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  182659. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  182660. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182661. /* Deprecated */
  182662. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  182663. #endif
  182664. #endif
  182665. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  182666. /* Use blue, green, red order for pixels. */
  182667. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  182668. #endif
  182669. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  182670. /* Expand the grayscale to 24-bit RGB if necessary. */
  182671. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  182672. #endif
  182673. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182674. /* Reduce RGB to grayscale. */
  182675. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182676. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  182677. int error_action, double red, double green ));
  182678. #endif
  182679. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  182680. int error_action, png_fixed_point red, png_fixed_point green ));
  182681. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  182682. png_ptr));
  182683. #endif
  182684. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  182685. png_colorp palette));
  182686. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  182687. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  182688. #endif
  182689. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  182690. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  182691. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  182692. #endif
  182693. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  182694. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  182695. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  182696. #endif
  182697. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182698. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  182699. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  182700. png_uint_32 filler, int flags));
  182701. /* The values of the PNG_FILLER_ defines should NOT be changed */
  182702. #define PNG_FILLER_BEFORE 0
  182703. #define PNG_FILLER_AFTER 1
  182704. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  182705. #if !defined(PNG_1_0_X)
  182706. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  182707. png_uint_32 filler, int flags));
  182708. #endif
  182709. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  182710. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  182711. /* Swap bytes in 16-bit depth files. */
  182712. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  182713. #endif
  182714. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  182715. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  182716. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  182717. #endif
  182718. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  182719. /* Swap packing order of pixels in bytes. */
  182720. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  182721. #endif
  182722. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182723. /* Converts files to legal bit depths. */
  182724. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  182725. png_color_8p true_bits));
  182726. #endif
  182727. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  182728. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  182729. /* Have the code handle the interlacing. Returns the number of passes. */
  182730. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  182731. #endif
  182732. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  182733. /* Invert monochrome files */
  182734. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  182735. #endif
  182736. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182737. /* Handle alpha and tRNS by replacing with a background color. */
  182738. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182739. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  182740. png_color_16p background_color, int background_gamma_code,
  182741. int need_expand, double background_gamma));
  182742. #endif
  182743. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  182744. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  182745. #define PNG_BACKGROUND_GAMMA_FILE 2
  182746. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  182747. #endif
  182748. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  182749. /* strip the second byte of information from a 16-bit depth file. */
  182750. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  182751. #endif
  182752. #if defined(PNG_READ_DITHER_SUPPORTED)
  182753. /* Turn on dithering, and reduce the palette to the number of colors available. */
  182754. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  182755. png_colorp palette, int num_palette, int maximum_colors,
  182756. png_uint_16p histogram, int full_dither));
  182757. #endif
  182758. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182759. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  182760. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182761. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  182762. double screen_gamma, double default_file_gamma));
  182763. #endif
  182764. #endif
  182765. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182766. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182767. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182768. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  182769. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  182770. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  182771. int empty_plte_permitted));
  182772. #endif
  182773. #endif
  182774. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182775. /* Set how many lines between output flushes - 0 for no flushing */
  182776. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  182777. /* Flush the current PNG output buffer */
  182778. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  182779. #endif
  182780. /* optional update palette with requested transformations */
  182781. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  182782. /* optional call to update the users info structure */
  182783. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  182784. png_infop info_ptr));
  182785. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182786. /* read one or more rows of image data. */
  182787. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  182788. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  182789. #endif
  182790. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182791. /* read a row of data. */
  182792. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  182793. png_bytep row,
  182794. png_bytep display_row));
  182795. #endif
  182796. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182797. /* read the whole image into memory at once. */
  182798. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  182799. png_bytepp image));
  182800. #endif
  182801. /* write a row of image data */
  182802. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  182803. png_bytep row));
  182804. /* write a few rows of image data */
  182805. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  182806. png_bytepp row, png_uint_32 num_rows));
  182807. /* write the image data */
  182808. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  182809. png_bytepp image));
  182810. /* writes the end of the PNG file. */
  182811. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  182812. png_infop info_ptr));
  182813. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182814. /* read the end of the PNG file. */
  182815. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  182816. png_infop info_ptr));
  182817. #endif
  182818. /* free any memory associated with the png_info_struct */
  182819. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  182820. png_infopp info_ptr_ptr));
  182821. /* free any memory associated with the png_struct and the png_info_structs */
  182822. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  182823. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  182824. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  182825. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  182826. png_infop end_info_ptr));
  182827. /* free any memory associated with the png_struct and the png_info_structs */
  182828. extern PNG_EXPORT(void,png_destroy_write_struct)
  182829. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  182830. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  182831. extern void png_write_destroy PNGARG((png_structp png_ptr));
  182832. /* set the libpng method of handling chunk CRC errors */
  182833. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  182834. int crit_action, int ancil_action));
  182835. /* Values for png_set_crc_action() to say how to handle CRC errors in
  182836. * ancillary and critical chunks, and whether to use the data contained
  182837. * therein. Note that it is impossible to "discard" data in a critical
  182838. * chunk. For versions prior to 0.90, the action was always error/quit,
  182839. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  182840. * chunks is warn/discard. These values should NOT be changed.
  182841. *
  182842. * value action:critical action:ancillary
  182843. */
  182844. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  182845. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  182846. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  182847. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  182848. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  182849. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  182850. /* These functions give the user control over the scan-line filtering in
  182851. * libpng and the compression methods used by zlib. These functions are
  182852. * mainly useful for testing, as the defaults should work with most users.
  182853. * Those users who are tight on memory or want faster performance at the
  182854. * expense of compression can modify them. See the compression library
  182855. * header file (zlib.h) for an explination of the compression functions.
  182856. */
  182857. /* set the filtering method(s) used by libpng. Currently, the only valid
  182858. * value for "method" is 0.
  182859. */
  182860. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  182861. int filters));
  182862. /* Flags for png_set_filter() to say which filters to use. The flags
  182863. * are chosen so that they don't conflict with real filter types
  182864. * below, in case they are supplied instead of the #defined constants.
  182865. * These values should NOT be changed.
  182866. */
  182867. #define PNG_NO_FILTERS 0x00
  182868. #define PNG_FILTER_NONE 0x08
  182869. #define PNG_FILTER_SUB 0x10
  182870. #define PNG_FILTER_UP 0x20
  182871. #define PNG_FILTER_AVG 0x40
  182872. #define PNG_FILTER_PAETH 0x80
  182873. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  182874. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  182875. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  182876. * These defines should NOT be changed.
  182877. */
  182878. #define PNG_FILTER_VALUE_NONE 0
  182879. #define PNG_FILTER_VALUE_SUB 1
  182880. #define PNG_FILTER_VALUE_UP 2
  182881. #define PNG_FILTER_VALUE_AVG 3
  182882. #define PNG_FILTER_VALUE_PAETH 4
  182883. #define PNG_FILTER_VALUE_LAST 5
  182884. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  182885. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  182886. * defines, either the default (minimum-sum-of-absolute-differences), or
  182887. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  182888. *
  182889. * Weights are factors >= 1.0, indicating how important it is to keep the
  182890. * filter type consistent between rows. Larger numbers mean the current
  182891. * filter is that many times as likely to be the same as the "num_weights"
  182892. * previous filters. This is cumulative for each previous row with a weight.
  182893. * There needs to be "num_weights" values in "filter_weights", or it can be
  182894. * NULL if the weights aren't being specified. Weights have no influence on
  182895. * the selection of the first row filter. Well chosen weights can (in theory)
  182896. * improve the compression for a given image.
  182897. *
  182898. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  182899. * filter type. Higher costs indicate more decoding expense, and are
  182900. * therefore less likely to be selected over a filter with lower computational
  182901. * costs. There needs to be a value in "filter_costs" for each valid filter
  182902. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  182903. * setting the costs. Costs try to improve the speed of decompression without
  182904. * unduly increasing the compressed image size.
  182905. *
  182906. * A negative weight or cost indicates the default value is to be used, and
  182907. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  182908. * The default values for both weights and costs are currently 1.0, but may
  182909. * change if good general weighting/cost heuristics can be found. If both
  182910. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  182911. * to the UNWEIGHTED method, but with added encoding time/computation.
  182912. */
  182913. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182914. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  182915. int heuristic_method, int num_weights, png_doublep filter_weights,
  182916. png_doublep filter_costs));
  182917. #endif
  182918. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  182919. /* Heuristic used for row filter selection. These defines should NOT be
  182920. * changed.
  182921. */
  182922. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  182923. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  182924. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  182925. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  182926. /* Set the library compression level. Currently, valid values range from
  182927. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  182928. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  182929. * shown that zlib compression levels 3-6 usually perform as well as level 9
  182930. * for PNG images, and do considerably fewer caclulations. In the future,
  182931. * these values may not correspond directly to the zlib compression levels.
  182932. */
  182933. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  182934. int level));
  182935. extern PNG_EXPORT(void,png_set_compression_mem_level)
  182936. PNGARG((png_structp png_ptr, int mem_level));
  182937. extern PNG_EXPORT(void,png_set_compression_strategy)
  182938. PNGARG((png_structp png_ptr, int strategy));
  182939. extern PNG_EXPORT(void,png_set_compression_window_bits)
  182940. PNGARG((png_structp png_ptr, int window_bits));
  182941. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  182942. int method));
  182943. /* These next functions are called for input/output, memory, and error
  182944. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  182945. * and call standard C I/O routines such as fread(), fwrite(), and
  182946. * fprintf(). These functions can be made to use other I/O routines
  182947. * at run time for those applications that need to handle I/O in a
  182948. * different manner by calling png_set_???_fn(). See libpng.txt for
  182949. * more information.
  182950. */
  182951. #if !defined(PNG_NO_STDIO)
  182952. /* Initialize the input/output for the PNG file to the default functions. */
  182953. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  182954. #endif
  182955. /* Replace the (error and abort), and warning functions with user
  182956. * supplied functions. If no messages are to be printed you must still
  182957. * write and use replacement functions. The replacement error_fn should
  182958. * still do a longjmp to the last setjmp location if you are using this
  182959. * method of error handling. If error_fn or warning_fn is NULL, the
  182960. * default function will be used.
  182961. */
  182962. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  182963. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  182964. /* Return the user pointer associated with the error functions */
  182965. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  182966. /* Replace the default data output functions with a user supplied one(s).
  182967. * If buffered output is not used, then output_flush_fn can be set to NULL.
  182968. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  182969. * output_flush_fn will be ignored (and thus can be NULL).
  182970. */
  182971. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  182972. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  182973. /* Replace the default data input function with a user supplied one. */
  182974. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  182975. png_voidp io_ptr, png_rw_ptr read_data_fn));
  182976. /* Return the user pointer associated with the I/O functions */
  182977. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  182978. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  182979. png_read_status_ptr read_row_fn));
  182980. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  182981. png_write_status_ptr write_row_fn));
  182982. #ifdef PNG_USER_MEM_SUPPORTED
  182983. /* Replace the default memory allocation functions with user supplied one(s). */
  182984. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  182985. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182986. /* Return the user pointer associated with the memory functions */
  182987. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  182988. #endif
  182989. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182990. defined(PNG_LEGACY_SUPPORTED)
  182991. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  182992. png_ptr, png_user_transform_ptr read_user_transform_fn));
  182993. #endif
  182994. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182995. defined(PNG_LEGACY_SUPPORTED)
  182996. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  182997. png_ptr, png_user_transform_ptr write_user_transform_fn));
  182998. #endif
  182999. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183000. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183001. defined(PNG_LEGACY_SUPPORTED)
  183002. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  183003. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  183004. int user_transform_channels));
  183005. /* Return the user pointer associated with the user transform functions */
  183006. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  183007. PNGARG((png_structp png_ptr));
  183008. #endif
  183009. #ifdef PNG_USER_CHUNKS_SUPPORTED
  183010. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  183011. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  183012. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  183013. png_ptr));
  183014. #endif
  183015. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183016. /* Sets the function callbacks for the push reader, and a pointer to a
  183017. * user-defined structure available to the callback functions.
  183018. */
  183019. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183020. png_voidp progressive_ptr,
  183021. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183022. png_progressive_end_ptr end_fn));
  183023. /* returns the user pointer associated with the push read functions */
  183024. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183025. PNGARG((png_structp png_ptr));
  183026. /* function to be called when data becomes available */
  183027. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183028. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183029. /* function that combines rows. Not very much different than the
  183030. * png_combine_row() call. Is this even used?????
  183031. */
  183032. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183033. png_bytep old_row, png_bytep new_row));
  183034. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183035. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183036. png_uint_32 size));
  183037. #if defined(PNG_1_0_X)
  183038. # define png_malloc_warn png_malloc
  183039. #else
  183040. /* Added at libpng version 1.2.4 */
  183041. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183042. png_uint_32 size));
  183043. #endif
  183044. /* frees a pointer allocated by png_malloc() */
  183045. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183046. #if defined(PNG_1_0_X)
  183047. /* Function to allocate memory for zlib. */
  183048. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183049. uInt size));
  183050. /* Function to free memory for zlib */
  183051. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183052. #endif
  183053. /* Free data that was allocated internally */
  183054. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183055. png_infop info_ptr, png_uint_32 free_me, int num));
  183056. #ifdef PNG_FREE_ME_SUPPORTED
  183057. /* Reassign responsibility for freeing existing data, whether allocated
  183058. * by libpng or by the application */
  183059. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183060. png_infop info_ptr, int freer, png_uint_32 mask));
  183061. #endif
  183062. /* assignments for png_data_freer */
  183063. #define PNG_DESTROY_WILL_FREE_DATA 1
  183064. #define PNG_SET_WILL_FREE_DATA 1
  183065. #define PNG_USER_WILL_FREE_DATA 2
  183066. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183067. #define PNG_FREE_HIST 0x0008
  183068. #define PNG_FREE_ICCP 0x0010
  183069. #define PNG_FREE_SPLT 0x0020
  183070. #define PNG_FREE_ROWS 0x0040
  183071. #define PNG_FREE_PCAL 0x0080
  183072. #define PNG_FREE_SCAL 0x0100
  183073. #define PNG_FREE_UNKN 0x0200
  183074. #define PNG_FREE_LIST 0x0400
  183075. #define PNG_FREE_PLTE 0x1000
  183076. #define PNG_FREE_TRNS 0x2000
  183077. #define PNG_FREE_TEXT 0x4000
  183078. #define PNG_FREE_ALL 0x7fff
  183079. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183080. #ifdef PNG_USER_MEM_SUPPORTED
  183081. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183082. png_uint_32 size));
  183083. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183084. png_voidp ptr));
  183085. #endif
  183086. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183087. png_voidp s1, png_voidp s2, png_uint_32 size));
  183088. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183089. png_voidp s1, int value, png_uint_32 size));
  183090. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183091. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183092. int check));
  183093. #endif /* USE_FAR_KEYWORD */
  183094. #ifndef PNG_NO_ERROR_TEXT
  183095. /* Fatal error in PNG image of libpng - can't continue */
  183096. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183097. png_const_charp error_message));
  183098. /* The same, but the chunk name is prepended to the error string. */
  183099. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183100. png_const_charp error_message));
  183101. #else
  183102. /* Fatal error in PNG image of libpng - can't continue */
  183103. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183104. #endif
  183105. #ifndef PNG_NO_WARNINGS
  183106. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183107. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183108. png_const_charp warning_message));
  183109. #ifdef PNG_READ_SUPPORTED
  183110. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183111. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183112. png_const_charp warning_message));
  183113. #endif /* PNG_READ_SUPPORTED */
  183114. #endif /* PNG_NO_WARNINGS */
  183115. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183116. * Similarly, the png_get_<chunk> calls are used to read values from the
  183117. * png_info_struct, either storing the parameters in the passed variables, or
  183118. * setting pointers into the png_info_struct where the data is stored. The
  183119. * png_get_<chunk> functions return a non-zero value if the data was available
  183120. * in info_ptr, or return zero and do not change any of the parameters if the
  183121. * data was not available.
  183122. *
  183123. * These functions should be used instead of directly accessing png_info
  183124. * to avoid problems with future changes in the size and internal layout of
  183125. * png_info_struct.
  183126. */
  183127. /* Returns "flag" if chunk data is valid in info_ptr. */
  183128. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183129. png_infop info_ptr, png_uint_32 flag));
  183130. /* Returns number of bytes needed to hold a transformed row. */
  183131. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183132. png_infop info_ptr));
  183133. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183134. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183135. returned from png_read_png(). */
  183136. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183137. png_infop info_ptr));
  183138. /* Set row_pointers, which is an array of pointers to scanlines for use
  183139. by png_write_png(). */
  183140. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183141. png_infop info_ptr, png_bytepp row_pointers));
  183142. #endif
  183143. /* Returns number of color channels in image. */
  183144. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183145. png_infop info_ptr));
  183146. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183147. /* Returns image width in pixels. */
  183148. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183149. png_ptr, png_infop info_ptr));
  183150. /* Returns image height in pixels. */
  183151. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183152. png_ptr, png_infop info_ptr));
  183153. /* Returns image bit_depth. */
  183154. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183155. png_ptr, png_infop info_ptr));
  183156. /* Returns image color_type. */
  183157. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183158. png_ptr, png_infop info_ptr));
  183159. /* Returns image filter_type. */
  183160. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183161. png_ptr, png_infop info_ptr));
  183162. /* Returns image interlace_type. */
  183163. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183164. png_ptr, png_infop info_ptr));
  183165. /* Returns image compression_type. */
  183166. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183167. png_ptr, png_infop info_ptr));
  183168. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183169. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183170. png_ptr, png_infop info_ptr));
  183171. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183172. png_ptr, png_infop info_ptr));
  183173. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183174. png_ptr, png_infop info_ptr));
  183175. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183176. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183177. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183178. png_ptr, png_infop info_ptr));
  183179. #endif
  183180. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183181. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183182. png_ptr, png_infop info_ptr));
  183183. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183184. png_ptr, png_infop info_ptr));
  183185. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183186. png_ptr, png_infop info_ptr));
  183187. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183188. png_ptr, png_infop info_ptr));
  183189. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183190. /* Returns pointer to signature string read from PNG header */
  183191. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183192. png_infop info_ptr));
  183193. #if defined(PNG_bKGD_SUPPORTED)
  183194. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183195. png_infop info_ptr, png_color_16p *background));
  183196. #endif
  183197. #if defined(PNG_bKGD_SUPPORTED)
  183198. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183199. png_infop info_ptr, png_color_16p background));
  183200. #endif
  183201. #if defined(PNG_cHRM_SUPPORTED)
  183202. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183203. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183204. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183205. double *red_y, double *green_x, double *green_y, double *blue_x,
  183206. double *blue_y));
  183207. #endif
  183208. #ifdef PNG_FIXED_POINT_SUPPORTED
  183209. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183210. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183211. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183212. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183213. *int_blue_x, png_fixed_point *int_blue_y));
  183214. #endif
  183215. #endif
  183216. #if defined(PNG_cHRM_SUPPORTED)
  183217. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183218. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183219. png_infop info_ptr, double white_x, double white_y, double red_x,
  183220. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183221. #endif
  183222. #ifdef PNG_FIXED_POINT_SUPPORTED
  183223. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183224. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183225. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183226. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183227. png_fixed_point int_blue_y));
  183228. #endif
  183229. #endif
  183230. #if defined(PNG_gAMA_SUPPORTED)
  183231. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183232. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183233. png_infop info_ptr, double *file_gamma));
  183234. #endif
  183235. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183236. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183237. #endif
  183238. #if defined(PNG_gAMA_SUPPORTED)
  183239. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183240. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183241. png_infop info_ptr, double file_gamma));
  183242. #endif
  183243. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183244. png_infop info_ptr, png_fixed_point int_file_gamma));
  183245. #endif
  183246. #if defined(PNG_hIST_SUPPORTED)
  183247. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183248. png_infop info_ptr, png_uint_16p *hist));
  183249. #endif
  183250. #if defined(PNG_hIST_SUPPORTED)
  183251. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183252. png_infop info_ptr, png_uint_16p hist));
  183253. #endif
  183254. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183255. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183256. int *bit_depth, int *color_type, int *interlace_method,
  183257. int *compression_method, int *filter_method));
  183258. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183259. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183260. int color_type, int interlace_method, int compression_method,
  183261. int filter_method));
  183262. #if defined(PNG_oFFs_SUPPORTED)
  183263. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183264. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183265. int *unit_type));
  183266. #endif
  183267. #if defined(PNG_oFFs_SUPPORTED)
  183268. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183269. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183270. int unit_type));
  183271. #endif
  183272. #if defined(PNG_pCAL_SUPPORTED)
  183273. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183274. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183275. int *type, int *nparams, png_charp *units, png_charpp *params));
  183276. #endif
  183277. #if defined(PNG_pCAL_SUPPORTED)
  183278. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183279. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183280. int type, int nparams, png_charp units, png_charpp params));
  183281. #endif
  183282. #if defined(PNG_pHYs_SUPPORTED)
  183283. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183284. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183285. #endif
  183286. #if defined(PNG_pHYs_SUPPORTED)
  183287. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183288. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183289. #endif
  183290. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183291. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183292. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183293. png_infop info_ptr, png_colorp palette, int num_palette));
  183294. #if defined(PNG_sBIT_SUPPORTED)
  183295. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183296. png_infop info_ptr, png_color_8p *sig_bit));
  183297. #endif
  183298. #if defined(PNG_sBIT_SUPPORTED)
  183299. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183300. png_infop info_ptr, png_color_8p sig_bit));
  183301. #endif
  183302. #if defined(PNG_sRGB_SUPPORTED)
  183303. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183304. png_infop info_ptr, int *intent));
  183305. #endif
  183306. #if defined(PNG_sRGB_SUPPORTED)
  183307. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183308. png_infop info_ptr, int intent));
  183309. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183310. png_infop info_ptr, int intent));
  183311. #endif
  183312. #if defined(PNG_iCCP_SUPPORTED)
  183313. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183314. png_infop info_ptr, png_charpp name, int *compression_type,
  183315. png_charpp profile, png_uint_32 *proflen));
  183316. /* Note to maintainer: profile should be png_bytepp */
  183317. #endif
  183318. #if defined(PNG_iCCP_SUPPORTED)
  183319. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183320. png_infop info_ptr, png_charp name, int compression_type,
  183321. png_charp profile, png_uint_32 proflen));
  183322. /* Note to maintainer: profile should be png_bytep */
  183323. #endif
  183324. #if defined(PNG_sPLT_SUPPORTED)
  183325. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183326. png_infop info_ptr, png_sPLT_tpp entries));
  183327. #endif
  183328. #if defined(PNG_sPLT_SUPPORTED)
  183329. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183330. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183331. #endif
  183332. #if defined(PNG_TEXT_SUPPORTED)
  183333. /* png_get_text also returns the number of text chunks in *num_text */
  183334. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183335. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183336. #endif
  183337. /*
  183338. * Note while png_set_text() will accept a structure whose text,
  183339. * language, and translated keywords are NULL pointers, the structure
  183340. * returned by png_get_text will always contain regular
  183341. * zero-terminated C strings. They might be empty strings but
  183342. * they will never be NULL pointers.
  183343. */
  183344. #if defined(PNG_TEXT_SUPPORTED)
  183345. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183346. png_infop info_ptr, png_textp text_ptr, int num_text));
  183347. #endif
  183348. #if defined(PNG_tIME_SUPPORTED)
  183349. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183350. png_infop info_ptr, png_timep *mod_time));
  183351. #endif
  183352. #if defined(PNG_tIME_SUPPORTED)
  183353. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183354. png_infop info_ptr, png_timep mod_time));
  183355. #endif
  183356. #if defined(PNG_tRNS_SUPPORTED)
  183357. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183358. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183359. png_color_16p *trans_values));
  183360. #endif
  183361. #if defined(PNG_tRNS_SUPPORTED)
  183362. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183363. png_infop info_ptr, png_bytep trans, int num_trans,
  183364. png_color_16p trans_values));
  183365. #endif
  183366. #if defined(PNG_tRNS_SUPPORTED)
  183367. #endif
  183368. #if defined(PNG_sCAL_SUPPORTED)
  183369. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183370. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183371. png_infop info_ptr, int *unit, double *width, double *height));
  183372. #else
  183373. #ifdef PNG_FIXED_POINT_SUPPORTED
  183374. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183375. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183376. #endif
  183377. #endif
  183378. #endif /* PNG_sCAL_SUPPORTED */
  183379. #if defined(PNG_sCAL_SUPPORTED)
  183380. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183381. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183382. png_infop info_ptr, int unit, double width, double height));
  183383. #else
  183384. #ifdef PNG_FIXED_POINT_SUPPORTED
  183385. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183386. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183387. #endif
  183388. #endif
  183389. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183390. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183391. /* provide a list of chunks and how they are to be handled, if the built-in
  183392. handling or default unknown chunk handling is not desired. Any chunks not
  183393. listed will be handled in the default manner. The IHDR and IEND chunks
  183394. must not be listed.
  183395. keep = 0: follow default behaviour
  183396. = 1: do not keep
  183397. = 2: keep only if safe-to-copy
  183398. = 3: keep even if unsafe-to-copy
  183399. */
  183400. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183401. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183402. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183403. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183404. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183405. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183406. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183407. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183408. #endif
  183409. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183410. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183411. chunk_name));
  183412. #endif
  183413. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183414. If you need to turn it off for a chunk that your application has freed,
  183415. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183416. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183417. png_infop info_ptr, int mask));
  183418. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183419. /* The "params" pointer is currently not used and is for future expansion. */
  183420. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183421. png_infop info_ptr,
  183422. int transforms,
  183423. png_voidp params));
  183424. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183425. png_infop info_ptr,
  183426. int transforms,
  183427. png_voidp params));
  183428. #endif
  183429. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183430. * numbers for PNG_DEBUG mean more debugging information. This has
  183431. * only been added since version 0.95 so it is not implemented throughout
  183432. * libpng yet, but more support will be added as needed.
  183433. */
  183434. #ifdef PNG_DEBUG
  183435. #if (PNG_DEBUG > 0)
  183436. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183437. #include <crtdbg.h>
  183438. #if (PNG_DEBUG > 1)
  183439. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183440. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183441. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183442. #endif
  183443. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183444. #ifndef PNG_DEBUG_FILE
  183445. #define PNG_DEBUG_FILE stderr
  183446. #endif /* PNG_DEBUG_FILE */
  183447. #if (PNG_DEBUG > 1)
  183448. #define png_debug(l,m) \
  183449. { \
  183450. int num_tabs=l; \
  183451. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183452. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183453. }
  183454. #define png_debug1(l,m,p1) \
  183455. { \
  183456. int num_tabs=l; \
  183457. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183458. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183459. }
  183460. #define png_debug2(l,m,p1,p2) \
  183461. { \
  183462. int num_tabs=l; \
  183463. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183464. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183465. }
  183466. #endif /* (PNG_DEBUG > 1) */
  183467. #endif /* _MSC_VER */
  183468. #endif /* (PNG_DEBUG > 0) */
  183469. #endif /* PNG_DEBUG */
  183470. #ifndef png_debug
  183471. #define png_debug(l, m)
  183472. #endif
  183473. #ifndef png_debug1
  183474. #define png_debug1(l, m, p1)
  183475. #endif
  183476. #ifndef png_debug2
  183477. #define png_debug2(l, m, p1, p2)
  183478. #endif
  183479. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183480. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183481. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183482. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183483. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183484. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183485. png_ptr, png_uint_32 mng_features_permitted));
  183486. #endif
  183487. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183488. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183489. #define PNG_HANDLE_CHUNK_NEVER 1
  183490. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  183491. #define PNG_HANDLE_CHUNK_ALWAYS 3
  183492. /* Added to version 1.2.0 */
  183493. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183494. #if defined(PNG_MMX_CODE_SUPPORTED)
  183495. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  183496. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  183497. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  183498. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  183499. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  183500. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  183501. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  183502. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  183503. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  183504. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  183505. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  183506. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  183507. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  183508. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  183509. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  183510. #define PNG_MMX_WRITE_FLAGS ( 0 )
  183511. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  183512. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  183513. | PNG_MMX_READ_FLAGS \
  183514. | PNG_MMX_WRITE_FLAGS )
  183515. #define PNG_SELECT_READ 1
  183516. #define PNG_SELECT_WRITE 2
  183517. #endif /* PNG_MMX_CODE_SUPPORTED */
  183518. #if !defined(PNG_1_0_X)
  183519. /* pngget.c */
  183520. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  183521. PNGARG((int flag_select, int *compilerID));
  183522. /* pngget.c */
  183523. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  183524. PNGARG((int flag_select));
  183525. /* pngget.c */
  183526. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  183527. PNGARG((png_structp png_ptr));
  183528. /* pngget.c */
  183529. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  183530. PNGARG((png_structp png_ptr));
  183531. /* pngget.c */
  183532. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  183533. PNGARG((png_structp png_ptr));
  183534. /* pngset.c */
  183535. extern PNG_EXPORT(void,png_set_asm_flags)
  183536. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  183537. /* pngset.c */
  183538. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  183539. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  183540. png_uint_32 mmx_rowbytes_threshold));
  183541. #endif /* PNG_1_0_X */
  183542. #if !defined(PNG_1_0_X)
  183543. /* png.c, pnggccrd.c, or pngvcrd.c */
  183544. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  183545. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  183546. /* Strip the prepended error numbers ("#nnn ") from error and warning
  183547. * messages before passing them to the error or warning handler. */
  183548. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183549. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  183550. png_ptr, png_uint_32 strip_mode));
  183551. #endif
  183552. #endif /* PNG_1_0_X */
  183553. /* Added at libpng-1.2.6 */
  183554. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183555. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  183556. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  183557. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  183558. png_ptr));
  183559. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  183560. png_ptr));
  183561. #endif
  183562. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  183563. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  183564. /* With these routines we avoid an integer divide, which will be slower on
  183565. * most machines. However, it does take more operations than the corresponding
  183566. * divide method, so it may be slower on a few RISC systems. There are two
  183567. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  183568. *
  183569. * Note that the rounding factors are NOT supposed to be the same! 128 and
  183570. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  183571. * standard method.
  183572. *
  183573. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  183574. */
  183575. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  183576. # define png_composite(composite, fg, alpha, bg) \
  183577. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  183578. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  183579. (png_uint_16)(alpha)) + (png_uint_16)128); \
  183580. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  183581. # define png_composite_16(composite, fg, alpha, bg) \
  183582. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  183583. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  183584. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  183585. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  183586. #else /* standard method using integer division */
  183587. # define png_composite(composite, fg, alpha, bg) \
  183588. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  183589. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  183590. (png_uint_16)127) / 255)
  183591. # define png_composite_16(composite, fg, alpha, bg) \
  183592. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  183593. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  183594. (png_uint_32)32767) / (png_uint_32)65535L)
  183595. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  183596. /* Inline macros to do direct reads of bytes from the input buffer. These
  183597. * require that you are using an architecture that uses PNG byte ordering
  183598. * (MSB first) and supports unaligned data storage. I think that PowerPC
  183599. * in big-endian mode and 680x0 are the only ones that will support this.
  183600. * The x86 line of processors definitely do not. The png_get_int_32()
  183601. * routine also assumes we are using two's complement format for negative
  183602. * values, which is almost certainly true.
  183603. */
  183604. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  183605. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  183606. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  183607. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  183608. #else
  183609. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  183610. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  183611. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  183612. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  183613. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  183614. PNGARG((png_structp png_ptr, png_bytep buf));
  183615. /* No png_get_int_16 -- may be added if there's a real need for it. */
  183616. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  183617. */
  183618. extern PNG_EXPORT(void,png_save_uint_32)
  183619. PNGARG((png_bytep buf, png_uint_32 i));
  183620. extern PNG_EXPORT(void,png_save_int_32)
  183621. PNGARG((png_bytep buf, png_int_32 i));
  183622. /* Place a 16-bit number into a buffer in PNG byte order.
  183623. * The parameter is declared unsigned int, not png_uint_16,
  183624. * just to avoid potential problems on pre-ANSI C compilers.
  183625. */
  183626. extern PNG_EXPORT(void,png_save_uint_16)
  183627. PNGARG((png_bytep buf, unsigned int i));
  183628. /* No png_save_int_16 -- may be added if there's a real need for it. */
  183629. /* ************************************************************************* */
  183630. /* These next functions are used internally in the code. They generally
  183631. * shouldn't be used unless you are writing code to add or replace some
  183632. * functionality in libpng. More information about most functions can
  183633. * be found in the files where the functions are located.
  183634. */
  183635. /* Various modes of operation, that are visible to applications because
  183636. * they are used for unknown chunk location.
  183637. */
  183638. #define PNG_HAVE_IHDR 0x01
  183639. #define PNG_HAVE_PLTE 0x02
  183640. #define PNG_HAVE_IDAT 0x04
  183641. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  183642. #define PNG_HAVE_IEND 0x10
  183643. #if defined(PNG_INTERNAL)
  183644. /* More modes of operation. Note that after an init, mode is set to
  183645. * zero automatically when the structure is created.
  183646. */
  183647. #define PNG_HAVE_gAMA 0x20
  183648. #define PNG_HAVE_cHRM 0x40
  183649. #define PNG_HAVE_sRGB 0x80
  183650. #define PNG_HAVE_CHUNK_HEADER 0x100
  183651. #define PNG_WROTE_tIME 0x200
  183652. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  183653. #define PNG_BACKGROUND_IS_GRAY 0x800
  183654. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  183655. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  183656. /* flags for the transformations the PNG library does on the image data */
  183657. #define PNG_BGR 0x0001
  183658. #define PNG_INTERLACE 0x0002
  183659. #define PNG_PACK 0x0004
  183660. #define PNG_SHIFT 0x0008
  183661. #define PNG_SWAP_BYTES 0x0010
  183662. #define PNG_INVERT_MONO 0x0020
  183663. #define PNG_DITHER 0x0040
  183664. #define PNG_BACKGROUND 0x0080
  183665. #define PNG_BACKGROUND_EXPAND 0x0100
  183666. /* 0x0200 unused */
  183667. #define PNG_16_TO_8 0x0400
  183668. #define PNG_RGBA 0x0800
  183669. #define PNG_EXPAND 0x1000
  183670. #define PNG_GAMMA 0x2000
  183671. #define PNG_GRAY_TO_RGB 0x4000
  183672. #define PNG_FILLER 0x8000L
  183673. #define PNG_PACKSWAP 0x10000L
  183674. #define PNG_SWAP_ALPHA 0x20000L
  183675. #define PNG_STRIP_ALPHA 0x40000L
  183676. #define PNG_INVERT_ALPHA 0x80000L
  183677. #define PNG_USER_TRANSFORM 0x100000L
  183678. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  183679. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  183680. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  183681. /* 0x800000L Unused */
  183682. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  183683. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  183684. /* 0x4000000L unused */
  183685. /* 0x8000000L unused */
  183686. /* 0x10000000L unused */
  183687. /* 0x20000000L unused */
  183688. /* 0x40000000L unused */
  183689. /* flags for png_create_struct */
  183690. #define PNG_STRUCT_PNG 0x0001
  183691. #define PNG_STRUCT_INFO 0x0002
  183692. /* Scaling factor for filter heuristic weighting calculations */
  183693. #define PNG_WEIGHT_SHIFT 8
  183694. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  183695. #define PNG_COST_SHIFT 3
  183696. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  183697. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  183698. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  183699. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  183700. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  183701. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  183702. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  183703. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  183704. #define PNG_FLAG_ROW_INIT 0x0040
  183705. #define PNG_FLAG_FILLER_AFTER 0x0080
  183706. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  183707. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  183708. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  183709. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  183710. #define PNG_FLAG_FREE_PLTE 0x1000
  183711. #define PNG_FLAG_FREE_TRNS 0x2000
  183712. #define PNG_FLAG_FREE_HIST 0x4000
  183713. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  183714. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  183715. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  183716. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  183717. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  183718. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  183719. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  183720. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  183721. /* 0x800000L unused */
  183722. /* 0x1000000L unused */
  183723. /* 0x2000000L unused */
  183724. /* 0x4000000L unused */
  183725. /* 0x8000000L unused */
  183726. /* 0x10000000L unused */
  183727. /* 0x20000000L unused */
  183728. /* 0x40000000L unused */
  183729. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  183730. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  183731. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  183732. PNG_FLAG_CRC_CRITICAL_IGNORE)
  183733. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  183734. PNG_FLAG_CRC_CRITICAL_MASK)
  183735. /* save typing and make code easier to understand */
  183736. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  183737. abs((int)((c1).green) - (int)((c2).green)) + \
  183738. abs((int)((c1).blue) - (int)((c2).blue)))
  183739. /* Added to libpng-1.2.6 JB */
  183740. #define PNG_ROWBYTES(pixel_bits, width) \
  183741. ((pixel_bits) >= 8 ? \
  183742. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  183743. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  183744. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  183745. ideal-delta..ideal+delta. Each argument is evaluated twice.
  183746. "ideal" and "delta" should be constants, normally simple
  183747. integers, "value" a variable. Added to libpng-1.2.6 JB */
  183748. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  183749. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  183750. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  183751. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  183752. /* place to hold the signature string for a PNG file. */
  183753. #ifdef PNG_USE_GLOBAL_ARRAYS
  183754. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  183755. #else
  183756. #endif
  183757. #endif /* PNG_NO_EXTERN */
  183758. /* Constant strings for known chunk types. If you need to add a chunk,
  183759. * define the name here, and add an invocation of the macro in png.c and
  183760. * wherever it's needed.
  183761. */
  183762. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  183763. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  183764. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  183765. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  183766. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  183767. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  183768. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  183769. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  183770. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  183771. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  183772. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  183773. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  183774. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  183775. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  183776. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  183777. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  183778. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  183779. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  183780. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  183781. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  183782. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  183783. #ifdef PNG_USE_GLOBAL_ARRAYS
  183784. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  183785. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  183786. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  183787. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  183788. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  183789. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  183790. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  183791. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  183792. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  183793. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  183794. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  183795. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  183796. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  183797. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  183798. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  183799. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  183800. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  183801. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  183802. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  183803. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  183804. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  183805. #endif /* PNG_USE_GLOBAL_ARRAYS */
  183806. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183807. /* Initialize png_ptr struct for reading, and allocate any other memory.
  183808. * (old interface - DEPRECATED - use png_create_read_struct instead).
  183809. */
  183810. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  183811. #undef png_read_init
  183812. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  183813. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183814. #endif
  183815. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  183816. png_const_charp user_png_ver, png_size_t png_struct_size));
  183817. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183818. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  183819. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183820. png_info_size));
  183821. #endif
  183822. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183823. /* Initialize png_ptr struct for writing, and allocate any other memory.
  183824. * (old interface - DEPRECATED - use png_create_write_struct instead).
  183825. */
  183826. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  183827. #undef png_write_init
  183828. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  183829. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183830. #endif
  183831. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  183832. png_const_charp user_png_ver, png_size_t png_struct_size));
  183833. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  183834. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183835. png_info_size));
  183836. /* Allocate memory for an internal libpng struct */
  183837. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  183838. /* Free memory from internal libpng struct */
  183839. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  183840. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  183841. malloc_fn, png_voidp mem_ptr));
  183842. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  183843. png_free_ptr free_fn, png_voidp mem_ptr));
  183844. /* Free any memory that info_ptr points to and reset struct. */
  183845. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  183846. png_infop info_ptr));
  183847. #ifndef PNG_1_0_X
  183848. /* Function to allocate memory for zlib. */
  183849. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  183850. /* Function to free memory for zlib */
  183851. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  183852. #ifdef PNG_SIZE_T
  183853. /* Function to convert a sizeof an item to png_sizeof item */
  183854. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  183855. #endif
  183856. /* Next four functions are used internally as callbacks. PNGAPI is required
  183857. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  183858. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  183859. png_bytep data, png_size_t length));
  183860. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183861. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  183862. png_bytep buffer, png_size_t length));
  183863. #endif
  183864. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  183865. png_bytep data, png_size_t length));
  183866. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183867. #if !defined(PNG_NO_STDIO)
  183868. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  183869. #endif
  183870. #endif
  183871. #else /* PNG_1_0_X */
  183872. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183873. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  183874. png_bytep buffer, png_size_t length));
  183875. #endif
  183876. #endif /* PNG_1_0_X */
  183877. /* Reset the CRC variable */
  183878. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  183879. /* Write the "data" buffer to whatever output you are using. */
  183880. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  183881. png_size_t length));
  183882. /* Read data from whatever input you are using into the "data" buffer */
  183883. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  183884. png_size_t length));
  183885. /* Read bytes into buf, and update png_ptr->crc */
  183886. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  183887. png_size_t length));
  183888. /* Decompress data in a chunk that uses compression */
  183889. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  183890. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  183891. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  183892. int comp_type, png_charp chunkdata, png_size_t chunklength,
  183893. png_size_t prefix_length, png_size_t *data_length));
  183894. #endif
  183895. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  183896. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  183897. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  183898. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  183899. /* Calculate the CRC over a section of data. Note that we are only
  183900. * passing a maximum of 64K on systems that have this as a memory limit,
  183901. * since this is the maximum buffer size we can specify.
  183902. */
  183903. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  183904. png_size_t length));
  183905. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183906. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  183907. #endif
  183908. /* simple function to write the signature */
  183909. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  183910. /* write various chunks */
  183911. /* Write the IHDR chunk, and update the png_struct with the necessary
  183912. * information.
  183913. */
  183914. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  183915. png_uint_32 height,
  183916. int bit_depth, int color_type, int compression_method, int filter_method,
  183917. int interlace_method));
  183918. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  183919. png_uint_32 num_pal));
  183920. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  183921. png_size_t length));
  183922. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  183923. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  183924. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183925. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  183926. #endif
  183927. #ifdef PNG_FIXED_POINT_SUPPORTED
  183928. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  183929. file_gamma));
  183930. #endif
  183931. #endif
  183932. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  183933. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  183934. int color_type));
  183935. #endif
  183936. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  183937. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183938. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  183939. double white_x, double white_y,
  183940. double red_x, double red_y, double green_x, double green_y,
  183941. double blue_x, double blue_y));
  183942. #endif
  183943. #ifdef PNG_FIXED_POINT_SUPPORTED
  183944. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  183945. png_fixed_point int_white_x, png_fixed_point int_white_y,
  183946. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183947. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183948. png_fixed_point int_blue_y));
  183949. #endif
  183950. #endif
  183951. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  183952. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  183953. int intent));
  183954. #endif
  183955. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  183956. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  183957. png_charp name, int compression_type,
  183958. png_charp profile, int proflen));
  183959. /* Note to maintainer: profile should be png_bytep */
  183960. #endif
  183961. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  183962. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  183963. png_sPLT_tp palette));
  183964. #endif
  183965. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  183966. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  183967. png_color_16p values, int number, int color_type));
  183968. #endif
  183969. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  183970. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  183971. png_color_16p values, int color_type));
  183972. #endif
  183973. #if defined(PNG_WRITE_hIST_SUPPORTED)
  183974. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  183975. int num_hist));
  183976. #endif
  183977. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  183978. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  183979. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  183980. png_charp key, png_charpp new_key));
  183981. #endif
  183982. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  183983. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  183984. png_charp text, png_size_t text_len));
  183985. #endif
  183986. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  183987. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  183988. png_charp text, png_size_t text_len, int compression));
  183989. #endif
  183990. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  183991. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  183992. int compression, png_charp key, png_charp lang, png_charp lang_key,
  183993. png_charp text));
  183994. #endif
  183995. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  183996. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  183997. png_infop info_ptr, png_textp text_ptr, int num_text));
  183998. #endif
  183999. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  184000. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  184001. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  184002. #endif
  184003. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  184004. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  184005. png_int_32 X0, png_int_32 X1, int type, int nparams,
  184006. png_charp units, png_charpp params));
  184007. #endif
  184008. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  184009. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  184010. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  184011. int unit_type));
  184012. #endif
  184013. #if defined(PNG_WRITE_tIME_SUPPORTED)
  184014. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  184015. png_timep mod_time));
  184016. #endif
  184017. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  184018. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184019. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184020. int unit, double width, double height));
  184021. #else
  184022. #ifdef PNG_FIXED_POINT_SUPPORTED
  184023. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184024. int unit, png_charp width, png_charp height));
  184025. #endif
  184026. #endif
  184027. #endif
  184028. /* Called when finished processing a row of data */
  184029. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184030. /* Internal use only. Called before first row of data */
  184031. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184032. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184033. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184034. #endif
  184035. /* combine a row of data, dealing with alpha, etc. if requested */
  184036. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184037. int mask));
  184038. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184039. /* expand an interlaced row */
  184040. /* OLD pre-1.0.9 interface:
  184041. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184042. png_bytep row, int pass, png_uint_32 transformations));
  184043. */
  184044. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184045. #endif
  184046. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184047. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184048. /* grab pixels out of a row for an interlaced pass */
  184049. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184050. png_bytep row, int pass));
  184051. #endif
  184052. /* unfilter a row */
  184053. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184054. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184055. /* Choose the best filter to use and filter the row data */
  184056. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184057. png_row_infop row_info));
  184058. /* Write out the filtered row. */
  184059. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184060. png_bytep filtered_row));
  184061. /* finish a row while reading, dealing with interlacing passes, etc. */
  184062. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184063. /* initialize the row buffers, etc. */
  184064. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184065. /* optional call to update the users info structure */
  184066. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184067. png_infop info_ptr));
  184068. /* these are the functions that do the transformations */
  184069. #if defined(PNG_READ_FILLER_SUPPORTED)
  184070. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184071. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184072. #endif
  184073. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184074. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184075. png_bytep row));
  184076. #endif
  184077. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184078. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184079. png_bytep row));
  184080. #endif
  184081. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184082. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184083. png_bytep row));
  184084. #endif
  184085. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184086. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184087. png_bytep row));
  184088. #endif
  184089. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184090. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184091. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184092. png_bytep row, png_uint_32 flags));
  184093. #endif
  184094. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184095. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184096. #endif
  184097. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184098. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184099. #endif
  184100. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184101. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184102. row_info, png_bytep row));
  184103. #endif
  184104. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184105. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184106. png_bytep row));
  184107. #endif
  184108. #if defined(PNG_READ_PACK_SUPPORTED)
  184109. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184110. #endif
  184111. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184112. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184113. png_color_8p sig_bits));
  184114. #endif
  184115. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184116. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184117. #endif
  184118. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184119. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184120. #endif
  184121. #if defined(PNG_READ_DITHER_SUPPORTED)
  184122. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184123. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184124. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184125. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184126. png_colorp palette, int num_palette));
  184127. # endif
  184128. #endif
  184129. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184130. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184131. #endif
  184132. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184133. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184134. png_bytep row, png_uint_32 bit_depth));
  184135. #endif
  184136. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184137. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184138. png_color_8p bit_depth));
  184139. #endif
  184140. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184141. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184142. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184143. png_color_16p trans_values, png_color_16p background,
  184144. png_color_16p background_1,
  184145. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184146. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184147. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184148. #else
  184149. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184150. png_color_16p trans_values, png_color_16p background));
  184151. #endif
  184152. #endif
  184153. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184154. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184155. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184156. int gamma_shift));
  184157. #endif
  184158. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184159. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184160. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184161. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184162. png_bytep row, png_color_16p trans_value));
  184163. #endif
  184164. /* The following decodes the appropriate chunks, and does error correction,
  184165. * then calls the appropriate callback for the chunk if it is valid.
  184166. */
  184167. /* decode the IHDR chunk */
  184168. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184169. png_uint_32 length));
  184170. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184171. png_uint_32 length));
  184172. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184173. png_uint_32 length));
  184174. #if defined(PNG_READ_bKGD_SUPPORTED)
  184175. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184176. png_uint_32 length));
  184177. #endif
  184178. #if defined(PNG_READ_cHRM_SUPPORTED)
  184179. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184180. png_uint_32 length));
  184181. #endif
  184182. #if defined(PNG_READ_gAMA_SUPPORTED)
  184183. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184184. png_uint_32 length));
  184185. #endif
  184186. #if defined(PNG_READ_hIST_SUPPORTED)
  184187. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184188. png_uint_32 length));
  184189. #endif
  184190. #if defined(PNG_READ_iCCP_SUPPORTED)
  184191. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184192. png_uint_32 length));
  184193. #endif /* PNG_READ_iCCP_SUPPORTED */
  184194. #if defined(PNG_READ_iTXt_SUPPORTED)
  184195. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184196. png_uint_32 length));
  184197. #endif
  184198. #if defined(PNG_READ_oFFs_SUPPORTED)
  184199. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184200. png_uint_32 length));
  184201. #endif
  184202. #if defined(PNG_READ_pCAL_SUPPORTED)
  184203. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184204. png_uint_32 length));
  184205. #endif
  184206. #if defined(PNG_READ_pHYs_SUPPORTED)
  184207. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184208. png_uint_32 length));
  184209. #endif
  184210. #if defined(PNG_READ_sBIT_SUPPORTED)
  184211. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184212. png_uint_32 length));
  184213. #endif
  184214. #if defined(PNG_READ_sCAL_SUPPORTED)
  184215. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184216. png_uint_32 length));
  184217. #endif
  184218. #if defined(PNG_READ_sPLT_SUPPORTED)
  184219. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184220. png_uint_32 length));
  184221. #endif /* PNG_READ_sPLT_SUPPORTED */
  184222. #if defined(PNG_READ_sRGB_SUPPORTED)
  184223. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184224. png_uint_32 length));
  184225. #endif
  184226. #if defined(PNG_READ_tEXt_SUPPORTED)
  184227. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184228. png_uint_32 length));
  184229. #endif
  184230. #if defined(PNG_READ_tIME_SUPPORTED)
  184231. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184232. png_uint_32 length));
  184233. #endif
  184234. #if defined(PNG_READ_tRNS_SUPPORTED)
  184235. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184236. png_uint_32 length));
  184237. #endif
  184238. #if defined(PNG_READ_zTXt_SUPPORTED)
  184239. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184240. png_uint_32 length));
  184241. #endif
  184242. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184243. png_infop info_ptr, png_uint_32 length));
  184244. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184245. png_bytep chunk_name));
  184246. /* handle the transformations for reading and writing */
  184247. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184248. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184249. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184250. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184251. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184252. png_infop info_ptr));
  184253. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184254. png_infop info_ptr));
  184255. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184256. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184257. png_uint_32 length));
  184258. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184259. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184260. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184261. png_bytep buffer, png_size_t buffer_length));
  184262. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184263. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184264. png_bytep buffer, png_size_t buffer_length));
  184265. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184266. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184267. png_infop info_ptr, png_uint_32 length));
  184268. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184269. png_infop info_ptr));
  184270. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184271. png_infop info_ptr));
  184272. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184273. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184274. png_infop info_ptr));
  184275. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184276. png_infop info_ptr));
  184277. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184278. #if defined(PNG_READ_tEXt_SUPPORTED)
  184279. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184280. png_infop info_ptr, png_uint_32 length));
  184281. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184282. png_infop info_ptr));
  184283. #endif
  184284. #if defined(PNG_READ_zTXt_SUPPORTED)
  184285. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184286. png_infop info_ptr, png_uint_32 length));
  184287. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184288. png_infop info_ptr));
  184289. #endif
  184290. #if defined(PNG_READ_iTXt_SUPPORTED)
  184291. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184292. png_infop info_ptr, png_uint_32 length));
  184293. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184294. png_infop info_ptr));
  184295. #endif
  184296. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184297. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184298. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184299. png_bytep row));
  184300. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184301. png_bytep row));
  184302. #endif
  184303. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184304. #if defined(PNG_MMX_CODE_SUPPORTED)
  184305. /* png.c */ /* PRIVATE */
  184306. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184307. #endif
  184308. #endif
  184309. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184310. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184311. png_infop info_ptr));
  184312. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184313. png_infop info_ptr));
  184314. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184315. png_infop info_ptr));
  184316. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184317. png_infop info_ptr));
  184318. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184319. png_infop info_ptr));
  184320. #if defined(PNG_pHYs_SUPPORTED)
  184321. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184322. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184323. #endif /* PNG_pHYs_SUPPORTED */
  184324. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184325. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184326. #endif /* PNG_INTERNAL */
  184327. #ifdef __cplusplus
  184328. //}
  184329. #endif
  184330. #endif /* PNG_VERSION_INFO_ONLY */
  184331. /* do not put anything past this line */
  184332. #endif /* PNG_H */
  184333. /*** End of inlined file: png.h ***/
  184334. #define PNG_NO_EXTERN
  184335. /*** Start of inlined file: png.c ***/
  184336. /* png.c - location for general purpose libpng functions
  184337. *
  184338. * Last changed in libpng 1.2.21 [October 4, 2007]
  184339. * For conditions of distribution and use, see copyright notice in png.h
  184340. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184341. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184342. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184343. */
  184344. #define PNG_INTERNAL
  184345. #define PNG_NO_EXTERN
  184346. /* Generate a compiler error if there is an old png.h in the search path. */
  184347. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184348. /* Version information for C files. This had better match the version
  184349. * string defined in png.h. */
  184350. #ifdef PNG_USE_GLOBAL_ARRAYS
  184351. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184352. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184353. #ifdef PNG_READ_SUPPORTED
  184354. /* png_sig was changed to a function in version 1.0.5c */
  184355. /* Place to hold the signature string for a PNG file. */
  184356. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184357. #endif /* PNG_READ_SUPPORTED */
  184358. /* Invoke global declarations for constant strings for known chunk types */
  184359. PNG_IHDR;
  184360. PNG_IDAT;
  184361. PNG_IEND;
  184362. PNG_PLTE;
  184363. PNG_bKGD;
  184364. PNG_cHRM;
  184365. PNG_gAMA;
  184366. PNG_hIST;
  184367. PNG_iCCP;
  184368. PNG_iTXt;
  184369. PNG_oFFs;
  184370. PNG_pCAL;
  184371. PNG_sCAL;
  184372. PNG_pHYs;
  184373. PNG_sBIT;
  184374. PNG_sPLT;
  184375. PNG_sRGB;
  184376. PNG_tEXt;
  184377. PNG_tIME;
  184378. PNG_tRNS;
  184379. PNG_zTXt;
  184380. #ifdef PNG_READ_SUPPORTED
  184381. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184382. /* start of interlace block */
  184383. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184384. /* offset to next interlace block */
  184385. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184386. /* start of interlace block in the y direction */
  184387. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184388. /* offset to next interlace block in the y direction */
  184389. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184390. /* Height of interlace block. This is not currently used - if you need
  184391. * it, uncomment it here and in png.h
  184392. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184393. */
  184394. /* Mask to determine which pixels are valid in a pass */
  184395. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184396. /* Mask to determine which pixels to overwrite while displaying */
  184397. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184398. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184399. #endif /* PNG_READ_SUPPORTED */
  184400. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184401. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184402. * of the PNG file signature. If the PNG data is embedded into another
  184403. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184404. * or write any of the magic bytes before it starts on the IHDR.
  184405. */
  184406. #ifdef PNG_READ_SUPPORTED
  184407. void PNGAPI
  184408. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184409. {
  184410. if(png_ptr == NULL) return;
  184411. png_debug(1, "in png_set_sig_bytes\n");
  184412. if (num_bytes > 8)
  184413. png_error(png_ptr, "Too many bytes for PNG signature.");
  184414. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184415. }
  184416. /* Checks whether the supplied bytes match the PNG signature. We allow
  184417. * checking less than the full 8-byte signature so that those apps that
  184418. * already read the first few bytes of a file to determine the file type
  184419. * can simply check the remaining bytes for extra assurance. Returns
  184420. * an integer less than, equal to, or greater than zero if sig is found,
  184421. * respectively, to be less than, to match, or be greater than the correct
  184422. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184423. */
  184424. int PNGAPI
  184425. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184426. {
  184427. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184428. if (num_to_check > 8)
  184429. num_to_check = 8;
  184430. else if (num_to_check < 1)
  184431. return (-1);
  184432. if (start > 7)
  184433. return (-1);
  184434. if (start + num_to_check > 8)
  184435. num_to_check = 8 - start;
  184436. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184437. }
  184438. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184439. /* (Obsolete) function to check signature bytes. It does not allow one
  184440. * to check a partial signature. This function might be removed in the
  184441. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184442. */
  184443. int PNGAPI
  184444. png_check_sig(png_bytep sig, int num)
  184445. {
  184446. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184447. }
  184448. #endif
  184449. #endif /* PNG_READ_SUPPORTED */
  184450. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184451. /* Function to allocate memory for zlib and clear it to 0. */
  184452. #ifdef PNG_1_0_X
  184453. voidpf PNGAPI
  184454. #else
  184455. voidpf /* private */
  184456. #endif
  184457. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184458. {
  184459. png_voidp ptr;
  184460. png_structp p=(png_structp)png_ptr;
  184461. png_uint_32 save_flags=p->flags;
  184462. png_uint_32 num_bytes;
  184463. if(png_ptr == NULL) return (NULL);
  184464. if (items > PNG_UINT_32_MAX/size)
  184465. {
  184466. png_warning (p, "Potential overflow in png_zalloc()");
  184467. return (NULL);
  184468. }
  184469. num_bytes = (png_uint_32)items * size;
  184470. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184471. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184472. p->flags=save_flags;
  184473. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184474. if (ptr == NULL)
  184475. return ((voidpf)ptr);
  184476. if (num_bytes > (png_uint_32)0x8000L)
  184477. {
  184478. png_memset(ptr, 0, (png_size_t)0x8000L);
  184479. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184480. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184481. }
  184482. else
  184483. {
  184484. png_memset(ptr, 0, (png_size_t)num_bytes);
  184485. }
  184486. #endif
  184487. return ((voidpf)ptr);
  184488. }
  184489. /* function to free memory for zlib */
  184490. #ifdef PNG_1_0_X
  184491. void PNGAPI
  184492. #else
  184493. void /* private */
  184494. #endif
  184495. png_zfree(voidpf png_ptr, voidpf ptr)
  184496. {
  184497. png_free((png_structp)png_ptr, (png_voidp)ptr);
  184498. }
  184499. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  184500. * in case CRC is > 32 bits to leave the top bits 0.
  184501. */
  184502. void /* PRIVATE */
  184503. png_reset_crc(png_structp png_ptr)
  184504. {
  184505. png_ptr->crc = crc32(0, Z_NULL, 0);
  184506. }
  184507. /* Calculate the CRC over a section of data. We can only pass as
  184508. * much data to this routine as the largest single buffer size. We
  184509. * also check that this data will actually be used before going to the
  184510. * trouble of calculating it.
  184511. */
  184512. void /* PRIVATE */
  184513. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  184514. {
  184515. int need_crc = 1;
  184516. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  184517. {
  184518. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  184519. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  184520. need_crc = 0;
  184521. }
  184522. else /* critical */
  184523. {
  184524. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  184525. need_crc = 0;
  184526. }
  184527. if (need_crc)
  184528. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  184529. }
  184530. /* Allocate the memory for an info_struct for the application. We don't
  184531. * really need the png_ptr, but it could potentially be useful in the
  184532. * future. This should be used in favour of malloc(png_sizeof(png_info))
  184533. * and png_info_init() so that applications that want to use a shared
  184534. * libpng don't have to be recompiled if png_info changes size.
  184535. */
  184536. png_infop PNGAPI
  184537. png_create_info_struct(png_structp png_ptr)
  184538. {
  184539. png_infop info_ptr;
  184540. png_debug(1, "in png_create_info_struct\n");
  184541. if(png_ptr == NULL) return (NULL);
  184542. #ifdef PNG_USER_MEM_SUPPORTED
  184543. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  184544. png_ptr->malloc_fn, png_ptr->mem_ptr);
  184545. #else
  184546. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184547. #endif
  184548. if (info_ptr != NULL)
  184549. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184550. return (info_ptr);
  184551. }
  184552. /* This function frees the memory associated with a single info struct.
  184553. * Normally, one would use either png_destroy_read_struct() or
  184554. * png_destroy_write_struct() to free an info struct, but this may be
  184555. * useful for some applications.
  184556. */
  184557. void PNGAPI
  184558. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  184559. {
  184560. png_infop info_ptr = NULL;
  184561. if(png_ptr == NULL) return;
  184562. png_debug(1, "in png_destroy_info_struct\n");
  184563. if (info_ptr_ptr != NULL)
  184564. info_ptr = *info_ptr_ptr;
  184565. if (info_ptr != NULL)
  184566. {
  184567. png_info_destroy(png_ptr, info_ptr);
  184568. #ifdef PNG_USER_MEM_SUPPORTED
  184569. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  184570. png_ptr->mem_ptr);
  184571. #else
  184572. png_destroy_struct((png_voidp)info_ptr);
  184573. #endif
  184574. *info_ptr_ptr = NULL;
  184575. }
  184576. }
  184577. /* Initialize the info structure. This is now an internal function (0.89)
  184578. * and applications using it are urged to use png_create_info_struct()
  184579. * instead.
  184580. */
  184581. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184582. #undef png_info_init
  184583. void PNGAPI
  184584. png_info_init(png_infop info_ptr)
  184585. {
  184586. /* We only come here via pre-1.0.12-compiled applications */
  184587. png_info_init_3(&info_ptr, 0);
  184588. }
  184589. #endif
  184590. void PNGAPI
  184591. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  184592. {
  184593. png_infop info_ptr = *ptr_ptr;
  184594. if(info_ptr == NULL) return;
  184595. png_debug(1, "in png_info_init_3\n");
  184596. if(png_sizeof(png_info) > png_info_struct_size)
  184597. {
  184598. png_destroy_struct(info_ptr);
  184599. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184600. *ptr_ptr = info_ptr;
  184601. }
  184602. /* set everything to 0 */
  184603. png_memset(info_ptr, 0, png_sizeof (png_info));
  184604. }
  184605. #ifdef PNG_FREE_ME_SUPPORTED
  184606. void PNGAPI
  184607. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  184608. int freer, png_uint_32 mask)
  184609. {
  184610. png_debug(1, "in png_data_freer\n");
  184611. if (png_ptr == NULL || info_ptr == NULL)
  184612. return;
  184613. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  184614. info_ptr->free_me |= mask;
  184615. else if(freer == PNG_USER_WILL_FREE_DATA)
  184616. info_ptr->free_me &= ~mask;
  184617. else
  184618. png_warning(png_ptr,
  184619. "Unknown freer parameter in png_data_freer.");
  184620. }
  184621. #endif
  184622. void PNGAPI
  184623. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  184624. int num)
  184625. {
  184626. png_debug(1, "in png_free_data\n");
  184627. if (png_ptr == NULL || info_ptr == NULL)
  184628. return;
  184629. #if defined(PNG_TEXT_SUPPORTED)
  184630. /* free text item num or (if num == -1) all text items */
  184631. #ifdef PNG_FREE_ME_SUPPORTED
  184632. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  184633. #else
  184634. if (mask & PNG_FREE_TEXT)
  184635. #endif
  184636. {
  184637. if (num != -1)
  184638. {
  184639. if (info_ptr->text && info_ptr->text[num].key)
  184640. {
  184641. png_free(png_ptr, info_ptr->text[num].key);
  184642. info_ptr->text[num].key = NULL;
  184643. }
  184644. }
  184645. else
  184646. {
  184647. int i;
  184648. for (i = 0; i < info_ptr->num_text; i++)
  184649. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  184650. png_free(png_ptr, info_ptr->text);
  184651. info_ptr->text = NULL;
  184652. info_ptr->num_text=0;
  184653. }
  184654. }
  184655. #endif
  184656. #if defined(PNG_tRNS_SUPPORTED)
  184657. /* free any tRNS entry */
  184658. #ifdef PNG_FREE_ME_SUPPORTED
  184659. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  184660. #else
  184661. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  184662. #endif
  184663. {
  184664. png_free(png_ptr, info_ptr->trans);
  184665. info_ptr->valid &= ~PNG_INFO_tRNS;
  184666. #ifndef PNG_FREE_ME_SUPPORTED
  184667. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  184668. #endif
  184669. info_ptr->trans = NULL;
  184670. }
  184671. #endif
  184672. #if defined(PNG_sCAL_SUPPORTED)
  184673. /* free any sCAL entry */
  184674. #ifdef PNG_FREE_ME_SUPPORTED
  184675. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  184676. #else
  184677. if (mask & PNG_FREE_SCAL)
  184678. #endif
  184679. {
  184680. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  184681. png_free(png_ptr, info_ptr->scal_s_width);
  184682. png_free(png_ptr, info_ptr->scal_s_height);
  184683. info_ptr->scal_s_width = NULL;
  184684. info_ptr->scal_s_height = NULL;
  184685. #endif
  184686. info_ptr->valid &= ~PNG_INFO_sCAL;
  184687. }
  184688. #endif
  184689. #if defined(PNG_pCAL_SUPPORTED)
  184690. /* free any pCAL entry */
  184691. #ifdef PNG_FREE_ME_SUPPORTED
  184692. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  184693. #else
  184694. if (mask & PNG_FREE_PCAL)
  184695. #endif
  184696. {
  184697. png_free(png_ptr, info_ptr->pcal_purpose);
  184698. png_free(png_ptr, info_ptr->pcal_units);
  184699. info_ptr->pcal_purpose = NULL;
  184700. info_ptr->pcal_units = NULL;
  184701. if (info_ptr->pcal_params != NULL)
  184702. {
  184703. int i;
  184704. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  184705. {
  184706. png_free(png_ptr, info_ptr->pcal_params[i]);
  184707. info_ptr->pcal_params[i]=NULL;
  184708. }
  184709. png_free(png_ptr, info_ptr->pcal_params);
  184710. info_ptr->pcal_params = NULL;
  184711. }
  184712. info_ptr->valid &= ~PNG_INFO_pCAL;
  184713. }
  184714. #endif
  184715. #if defined(PNG_iCCP_SUPPORTED)
  184716. /* free any iCCP entry */
  184717. #ifdef PNG_FREE_ME_SUPPORTED
  184718. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  184719. #else
  184720. if (mask & PNG_FREE_ICCP)
  184721. #endif
  184722. {
  184723. png_free(png_ptr, info_ptr->iccp_name);
  184724. png_free(png_ptr, info_ptr->iccp_profile);
  184725. info_ptr->iccp_name = NULL;
  184726. info_ptr->iccp_profile = NULL;
  184727. info_ptr->valid &= ~PNG_INFO_iCCP;
  184728. }
  184729. #endif
  184730. #if defined(PNG_sPLT_SUPPORTED)
  184731. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  184732. #ifdef PNG_FREE_ME_SUPPORTED
  184733. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  184734. #else
  184735. if (mask & PNG_FREE_SPLT)
  184736. #endif
  184737. {
  184738. if (num != -1)
  184739. {
  184740. if(info_ptr->splt_palettes)
  184741. {
  184742. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  184743. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  184744. info_ptr->splt_palettes[num].name = NULL;
  184745. info_ptr->splt_palettes[num].entries = NULL;
  184746. }
  184747. }
  184748. else
  184749. {
  184750. if(info_ptr->splt_palettes_num)
  184751. {
  184752. int i;
  184753. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  184754. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  184755. png_free(png_ptr, info_ptr->splt_palettes);
  184756. info_ptr->splt_palettes = NULL;
  184757. info_ptr->splt_palettes_num = 0;
  184758. }
  184759. info_ptr->valid &= ~PNG_INFO_sPLT;
  184760. }
  184761. }
  184762. #endif
  184763. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184764. if(png_ptr->unknown_chunk.data)
  184765. {
  184766. png_free(png_ptr, png_ptr->unknown_chunk.data);
  184767. png_ptr->unknown_chunk.data = NULL;
  184768. }
  184769. #ifdef PNG_FREE_ME_SUPPORTED
  184770. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  184771. #else
  184772. if (mask & PNG_FREE_UNKN)
  184773. #endif
  184774. {
  184775. if (num != -1)
  184776. {
  184777. if(info_ptr->unknown_chunks)
  184778. {
  184779. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  184780. info_ptr->unknown_chunks[num].data = NULL;
  184781. }
  184782. }
  184783. else
  184784. {
  184785. int i;
  184786. if(info_ptr->unknown_chunks_num)
  184787. {
  184788. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  184789. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  184790. png_free(png_ptr, info_ptr->unknown_chunks);
  184791. info_ptr->unknown_chunks = NULL;
  184792. info_ptr->unknown_chunks_num = 0;
  184793. }
  184794. }
  184795. }
  184796. #endif
  184797. #if defined(PNG_hIST_SUPPORTED)
  184798. /* free any hIST entry */
  184799. #ifdef PNG_FREE_ME_SUPPORTED
  184800. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  184801. #else
  184802. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  184803. #endif
  184804. {
  184805. png_free(png_ptr, info_ptr->hist);
  184806. info_ptr->hist = NULL;
  184807. info_ptr->valid &= ~PNG_INFO_hIST;
  184808. #ifndef PNG_FREE_ME_SUPPORTED
  184809. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  184810. #endif
  184811. }
  184812. #endif
  184813. /* free any PLTE entry that was internally allocated */
  184814. #ifdef PNG_FREE_ME_SUPPORTED
  184815. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  184816. #else
  184817. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  184818. #endif
  184819. {
  184820. png_zfree(png_ptr, info_ptr->palette);
  184821. info_ptr->palette = NULL;
  184822. info_ptr->valid &= ~PNG_INFO_PLTE;
  184823. #ifndef PNG_FREE_ME_SUPPORTED
  184824. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  184825. #endif
  184826. info_ptr->num_palette = 0;
  184827. }
  184828. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  184829. /* free any image bits attached to the info structure */
  184830. #ifdef PNG_FREE_ME_SUPPORTED
  184831. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  184832. #else
  184833. if (mask & PNG_FREE_ROWS)
  184834. #endif
  184835. {
  184836. if(info_ptr->row_pointers)
  184837. {
  184838. int row;
  184839. for (row = 0; row < (int)info_ptr->height; row++)
  184840. {
  184841. png_free(png_ptr, info_ptr->row_pointers[row]);
  184842. info_ptr->row_pointers[row]=NULL;
  184843. }
  184844. png_free(png_ptr, info_ptr->row_pointers);
  184845. info_ptr->row_pointers=NULL;
  184846. }
  184847. info_ptr->valid &= ~PNG_INFO_IDAT;
  184848. }
  184849. #endif
  184850. #ifdef PNG_FREE_ME_SUPPORTED
  184851. if(num == -1)
  184852. info_ptr->free_me &= ~mask;
  184853. else
  184854. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  184855. #endif
  184856. }
  184857. /* This is an internal routine to free any memory that the info struct is
  184858. * pointing to before re-using it or freeing the struct itself. Recall
  184859. * that png_free() checks for NULL pointers for us.
  184860. */
  184861. void /* PRIVATE */
  184862. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  184863. {
  184864. png_debug(1, "in png_info_destroy\n");
  184865. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  184866. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184867. if (png_ptr->num_chunk_list)
  184868. {
  184869. png_free(png_ptr, png_ptr->chunk_list);
  184870. png_ptr->chunk_list=NULL;
  184871. png_ptr->num_chunk_list=0;
  184872. }
  184873. #endif
  184874. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184875. }
  184876. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184877. /* This function returns a pointer to the io_ptr associated with the user
  184878. * functions. The application should free any memory associated with this
  184879. * pointer before png_write_destroy() or png_read_destroy() are called.
  184880. */
  184881. png_voidp PNGAPI
  184882. png_get_io_ptr(png_structp png_ptr)
  184883. {
  184884. if(png_ptr == NULL) return (NULL);
  184885. return (png_ptr->io_ptr);
  184886. }
  184887. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184888. #if !defined(PNG_NO_STDIO)
  184889. /* Initialize the default input/output functions for the PNG file. If you
  184890. * use your own read or write routines, you can call either png_set_read_fn()
  184891. * or png_set_write_fn() instead of png_init_io(). If you have defined
  184892. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  184893. * necessarily available.
  184894. */
  184895. void PNGAPI
  184896. png_init_io(png_structp png_ptr, png_FILE_p fp)
  184897. {
  184898. png_debug(1, "in png_init_io\n");
  184899. if(png_ptr == NULL) return;
  184900. png_ptr->io_ptr = (png_voidp)fp;
  184901. }
  184902. #endif
  184903. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  184904. /* Convert the supplied time into an RFC 1123 string suitable for use in
  184905. * a "Creation Time" or other text-based time string.
  184906. */
  184907. png_charp PNGAPI
  184908. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  184909. {
  184910. static PNG_CONST char short_months[12][4] =
  184911. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  184912. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  184913. if(png_ptr == NULL) return (NULL);
  184914. if (png_ptr->time_buffer == NULL)
  184915. {
  184916. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  184917. png_sizeof(char)));
  184918. }
  184919. #if defined(_WIN32_WCE)
  184920. {
  184921. wchar_t time_buf[29];
  184922. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  184923. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184924. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184925. ptime->second % 61);
  184926. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  184927. NULL, NULL);
  184928. }
  184929. #else
  184930. #ifdef USE_FAR_KEYWORD
  184931. {
  184932. char near_time_buf[29];
  184933. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  184934. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184935. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184936. ptime->second % 61);
  184937. png_memcpy(png_ptr->time_buffer, near_time_buf,
  184938. 29*png_sizeof(char));
  184939. }
  184940. #else
  184941. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  184942. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184943. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184944. ptime->second % 61);
  184945. #endif
  184946. #endif /* _WIN32_WCE */
  184947. return ((png_charp)png_ptr->time_buffer);
  184948. }
  184949. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  184950. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184951. png_charp PNGAPI
  184952. png_get_copyright(png_structp png_ptr)
  184953. {
  184954. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184955. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  184956. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  184957. Copyright (c) 1996-1997 Andreas Dilger\n\
  184958. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  184959. }
  184960. /* The following return the library version as a short string in the
  184961. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  184962. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  184963. * is defined in png.h.
  184964. * Note: now there is no difference between png_get_libpng_ver() and
  184965. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  184966. * it is guaranteed that png.c uses the correct version of png.h.
  184967. */
  184968. png_charp PNGAPI
  184969. png_get_libpng_ver(png_structp png_ptr)
  184970. {
  184971. /* Version of *.c files used when building libpng */
  184972. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184973. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184974. }
  184975. png_charp PNGAPI
  184976. png_get_header_ver(png_structp png_ptr)
  184977. {
  184978. /* Version of *.h files used when building libpng */
  184979. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184980. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184981. }
  184982. png_charp PNGAPI
  184983. png_get_header_version(png_structp png_ptr)
  184984. {
  184985. /* Returns longer string containing both version and date */
  184986. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184987. return ((png_charp) PNG_HEADER_VERSION_STRING
  184988. #ifndef PNG_READ_SUPPORTED
  184989. " (NO READ SUPPORT)"
  184990. #endif
  184991. "\n");
  184992. }
  184993. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184994. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184995. int PNGAPI
  184996. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  184997. {
  184998. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  184999. int i;
  185000. png_bytep p;
  185001. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  185002. return 0;
  185003. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  185004. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  185005. if (!png_memcmp(chunk_name, p, 4))
  185006. return ((int)*(p+4));
  185007. return 0;
  185008. }
  185009. #endif
  185010. /* This function, added to libpng-1.0.6g, is untested. */
  185011. int PNGAPI
  185012. png_reset_zstream(png_structp png_ptr)
  185013. {
  185014. if (png_ptr == NULL) return Z_STREAM_ERROR;
  185015. return (inflateReset(&png_ptr->zstream));
  185016. }
  185017. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185018. /* This function was added to libpng-1.0.7 */
  185019. png_uint_32 PNGAPI
  185020. png_access_version_number(void)
  185021. {
  185022. /* Version of *.c files used when building libpng */
  185023. return((png_uint_32) PNG_LIBPNG_VER);
  185024. }
  185025. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185026. #if !defined(PNG_1_0_X)
  185027. /* this function was added to libpng 1.2.0 */
  185028. int PNGAPI
  185029. png_mmx_support(void)
  185030. {
  185031. /* obsolete, to be removed from libpng-1.4.0 */
  185032. return -1;
  185033. }
  185034. #endif /* PNG_1_0_X */
  185035. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185036. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185037. #ifdef PNG_SIZE_T
  185038. /* Added at libpng version 1.2.6 */
  185039. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185040. png_size_t PNGAPI
  185041. png_convert_size(size_t size)
  185042. {
  185043. if (size > (png_size_t)-1)
  185044. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185045. return ((png_size_t)size);
  185046. }
  185047. #endif /* PNG_SIZE_T */
  185048. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185049. /*** End of inlined file: png.c ***/
  185050. /*** Start of inlined file: pngerror.c ***/
  185051. /* pngerror.c - stub functions for i/o and memory allocation
  185052. *
  185053. * Last changed in libpng 1.2.20 October 4, 2007
  185054. * For conditions of distribution and use, see copyright notice in png.h
  185055. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185056. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185057. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185058. *
  185059. * This file provides a location for all error handling. Users who
  185060. * need special error handling are expected to write replacement functions
  185061. * and use png_set_error_fn() to use those functions. See the instructions
  185062. * at each function.
  185063. */
  185064. #define PNG_INTERNAL
  185065. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185066. static void /* PRIVATE */
  185067. png_default_error PNGARG((png_structp png_ptr,
  185068. png_const_charp error_message));
  185069. #ifndef PNG_NO_WARNINGS
  185070. static void /* PRIVATE */
  185071. png_default_warning PNGARG((png_structp png_ptr,
  185072. png_const_charp warning_message));
  185073. #endif /* PNG_NO_WARNINGS */
  185074. /* This function is called whenever there is a fatal error. This function
  185075. * should not be changed. If there is a need to handle errors differently,
  185076. * you should supply a replacement error function and use png_set_error_fn()
  185077. * to replace the error function at run-time.
  185078. */
  185079. #ifndef PNG_NO_ERROR_TEXT
  185080. void PNGAPI
  185081. png_error(png_structp png_ptr, png_const_charp error_message)
  185082. {
  185083. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185084. char msg[16];
  185085. if (png_ptr != NULL)
  185086. {
  185087. if (png_ptr->flags&
  185088. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185089. {
  185090. if (*error_message == '#')
  185091. {
  185092. int offset;
  185093. for (offset=1; offset<15; offset++)
  185094. if (*(error_message+offset) == ' ')
  185095. break;
  185096. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185097. {
  185098. int i;
  185099. for (i=0; i<offset-1; i++)
  185100. msg[i]=error_message[i+1];
  185101. msg[i]='\0';
  185102. error_message=msg;
  185103. }
  185104. else
  185105. error_message+=offset;
  185106. }
  185107. else
  185108. {
  185109. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185110. {
  185111. msg[0]='0';
  185112. msg[1]='\0';
  185113. error_message=msg;
  185114. }
  185115. }
  185116. }
  185117. }
  185118. #endif
  185119. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185120. (*(png_ptr->error_fn))(png_ptr, error_message);
  185121. /* If the custom handler doesn't exist, or if it returns,
  185122. use the default handler, which will not return. */
  185123. png_default_error(png_ptr, error_message);
  185124. }
  185125. #else
  185126. void PNGAPI
  185127. png_err(png_structp png_ptr)
  185128. {
  185129. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185130. (*(png_ptr->error_fn))(png_ptr, '\0');
  185131. /* If the custom handler doesn't exist, or if it returns,
  185132. use the default handler, which will not return. */
  185133. png_default_error(png_ptr, '\0');
  185134. }
  185135. #endif /* PNG_NO_ERROR_TEXT */
  185136. #ifndef PNG_NO_WARNINGS
  185137. /* This function is called whenever there is a non-fatal error. This function
  185138. * should not be changed. If there is a need to handle warnings differently,
  185139. * you should supply a replacement warning function and use
  185140. * png_set_error_fn() to replace the warning function at run-time.
  185141. */
  185142. void PNGAPI
  185143. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185144. {
  185145. int offset = 0;
  185146. if (png_ptr != NULL)
  185147. {
  185148. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185149. if (png_ptr->flags&
  185150. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185151. #endif
  185152. {
  185153. if (*warning_message == '#')
  185154. {
  185155. for (offset=1; offset<15; offset++)
  185156. if (*(warning_message+offset) == ' ')
  185157. break;
  185158. }
  185159. }
  185160. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185161. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185162. }
  185163. else
  185164. png_default_warning(png_ptr, warning_message+offset);
  185165. }
  185166. #endif /* PNG_NO_WARNINGS */
  185167. /* These utilities are used internally to build an error message that relates
  185168. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185169. * this is used to prefix the message. The message is limited in length
  185170. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185171. * if the character is invalid.
  185172. */
  185173. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185174. /*static PNG_CONST char png_digit[16] = {
  185175. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185176. 'A', 'B', 'C', 'D', 'E', 'F'
  185177. };*/
  185178. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185179. static void /* PRIVATE */
  185180. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185181. error_message)
  185182. {
  185183. int iout = 0, iin = 0;
  185184. while (iin < 4)
  185185. {
  185186. int c = png_ptr->chunk_name[iin++];
  185187. if (isnonalpha(c))
  185188. {
  185189. buffer[iout++] = '[';
  185190. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185191. buffer[iout++] = png_digit[c & 0x0f];
  185192. buffer[iout++] = ']';
  185193. }
  185194. else
  185195. {
  185196. buffer[iout++] = (png_byte)c;
  185197. }
  185198. }
  185199. if (error_message == NULL)
  185200. buffer[iout] = 0;
  185201. else
  185202. {
  185203. buffer[iout++] = ':';
  185204. buffer[iout++] = ' ';
  185205. png_strncpy(buffer+iout, error_message, 63);
  185206. buffer[iout+63] = 0;
  185207. }
  185208. }
  185209. #ifdef PNG_READ_SUPPORTED
  185210. void PNGAPI
  185211. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185212. {
  185213. char msg[18+64];
  185214. if (png_ptr == NULL)
  185215. png_error(png_ptr, error_message);
  185216. else
  185217. {
  185218. png_format_buffer(png_ptr, msg, error_message);
  185219. png_error(png_ptr, msg);
  185220. }
  185221. }
  185222. #endif /* PNG_READ_SUPPORTED */
  185223. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185224. #ifndef PNG_NO_WARNINGS
  185225. void PNGAPI
  185226. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185227. {
  185228. char msg[18+64];
  185229. if (png_ptr == NULL)
  185230. png_warning(png_ptr, warning_message);
  185231. else
  185232. {
  185233. png_format_buffer(png_ptr, msg, warning_message);
  185234. png_warning(png_ptr, msg);
  185235. }
  185236. }
  185237. #endif /* PNG_NO_WARNINGS */
  185238. /* This is the default error handling function. Note that replacements for
  185239. * this function MUST NOT RETURN, or the program will likely crash. This
  185240. * function is used by default, or if the program supplies NULL for the
  185241. * error function pointer in png_set_error_fn().
  185242. */
  185243. static void /* PRIVATE */
  185244. png_default_error(png_structp, png_const_charp error_message)
  185245. {
  185246. #ifndef PNG_NO_CONSOLE_IO
  185247. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185248. if (*error_message == '#')
  185249. {
  185250. int offset;
  185251. char error_number[16];
  185252. for (offset=0; offset<15; offset++)
  185253. {
  185254. error_number[offset] = *(error_message+offset+1);
  185255. if (*(error_message+offset) == ' ')
  185256. break;
  185257. }
  185258. if((offset > 1) && (offset < 15))
  185259. {
  185260. error_number[offset-1]='\0';
  185261. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185262. error_message+offset);
  185263. }
  185264. else
  185265. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185266. }
  185267. else
  185268. #endif
  185269. fprintf(stderr, "libpng error: %s\n", error_message);
  185270. #endif
  185271. #ifdef PNG_SETJMP_SUPPORTED
  185272. if (png_ptr)
  185273. {
  185274. # ifdef USE_FAR_KEYWORD
  185275. {
  185276. jmp_buf jmpbuf;
  185277. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185278. longjmp(jmpbuf, 1);
  185279. }
  185280. # else
  185281. longjmp(png_ptr->jmpbuf, 1);
  185282. # endif
  185283. }
  185284. #else
  185285. PNG_ABORT();
  185286. #endif
  185287. #ifdef PNG_NO_CONSOLE_IO
  185288. error_message = error_message; /* make compiler happy */
  185289. #endif
  185290. }
  185291. #ifndef PNG_NO_WARNINGS
  185292. /* This function is called when there is a warning, but the library thinks
  185293. * it can continue anyway. Replacement functions don't have to do anything
  185294. * here if you don't want them to. In the default configuration, png_ptr is
  185295. * not used, but it is passed in case it may be useful.
  185296. */
  185297. static void /* PRIVATE */
  185298. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185299. {
  185300. #ifndef PNG_NO_CONSOLE_IO
  185301. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185302. if (*warning_message == '#')
  185303. {
  185304. int offset;
  185305. char warning_number[16];
  185306. for (offset=0; offset<15; offset++)
  185307. {
  185308. warning_number[offset]=*(warning_message+offset+1);
  185309. if (*(warning_message+offset) == ' ')
  185310. break;
  185311. }
  185312. if((offset > 1) && (offset < 15))
  185313. {
  185314. warning_number[offset-1]='\0';
  185315. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185316. warning_message+offset);
  185317. }
  185318. else
  185319. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185320. }
  185321. else
  185322. # endif
  185323. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185324. #else
  185325. warning_message = warning_message; /* make compiler happy */
  185326. #endif
  185327. png_ptr = png_ptr; /* make compiler happy */
  185328. }
  185329. #endif /* PNG_NO_WARNINGS */
  185330. /* This function is called when the application wants to use another method
  185331. * of handling errors and warnings. Note that the error function MUST NOT
  185332. * return to the calling routine or serious problems will occur. The return
  185333. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185334. */
  185335. void PNGAPI
  185336. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185337. png_error_ptr error_fn, png_error_ptr warning_fn)
  185338. {
  185339. if (png_ptr == NULL)
  185340. return;
  185341. png_ptr->error_ptr = error_ptr;
  185342. png_ptr->error_fn = error_fn;
  185343. png_ptr->warning_fn = warning_fn;
  185344. }
  185345. /* This function returns a pointer to the error_ptr associated with the user
  185346. * functions. The application should free any memory associated with this
  185347. * pointer before png_write_destroy and png_read_destroy are called.
  185348. */
  185349. png_voidp PNGAPI
  185350. png_get_error_ptr(png_structp png_ptr)
  185351. {
  185352. if (png_ptr == NULL)
  185353. return NULL;
  185354. return ((png_voidp)png_ptr->error_ptr);
  185355. }
  185356. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185357. void PNGAPI
  185358. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185359. {
  185360. if(png_ptr != NULL)
  185361. {
  185362. png_ptr->flags &=
  185363. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185364. }
  185365. }
  185366. #endif
  185367. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185368. /*** End of inlined file: pngerror.c ***/
  185369. /*** Start of inlined file: pngget.c ***/
  185370. /* pngget.c - retrieval of values from info struct
  185371. *
  185372. * Last changed in libpng 1.2.15 January 5, 2007
  185373. * For conditions of distribution and use, see copyright notice in png.h
  185374. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185375. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185376. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185377. */
  185378. #define PNG_INTERNAL
  185379. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185380. png_uint_32 PNGAPI
  185381. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185382. {
  185383. if (png_ptr != NULL && info_ptr != NULL)
  185384. return(info_ptr->valid & flag);
  185385. else
  185386. return(0);
  185387. }
  185388. png_uint_32 PNGAPI
  185389. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185390. {
  185391. if (png_ptr != NULL && info_ptr != NULL)
  185392. return(info_ptr->rowbytes);
  185393. else
  185394. return(0);
  185395. }
  185396. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185397. png_bytepp PNGAPI
  185398. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185399. {
  185400. if (png_ptr != NULL && info_ptr != NULL)
  185401. return(info_ptr->row_pointers);
  185402. else
  185403. return(0);
  185404. }
  185405. #endif
  185406. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185407. /* easy access to info, added in libpng-0.99 */
  185408. png_uint_32 PNGAPI
  185409. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185410. {
  185411. if (png_ptr != NULL && info_ptr != NULL)
  185412. {
  185413. return info_ptr->width;
  185414. }
  185415. return (0);
  185416. }
  185417. png_uint_32 PNGAPI
  185418. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185419. {
  185420. if (png_ptr != NULL && info_ptr != NULL)
  185421. {
  185422. return info_ptr->height;
  185423. }
  185424. return (0);
  185425. }
  185426. png_byte PNGAPI
  185427. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185428. {
  185429. if (png_ptr != NULL && info_ptr != NULL)
  185430. {
  185431. return info_ptr->bit_depth;
  185432. }
  185433. return (0);
  185434. }
  185435. png_byte PNGAPI
  185436. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185437. {
  185438. if (png_ptr != NULL && info_ptr != NULL)
  185439. {
  185440. return info_ptr->color_type;
  185441. }
  185442. return (0);
  185443. }
  185444. png_byte PNGAPI
  185445. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185446. {
  185447. if (png_ptr != NULL && info_ptr != NULL)
  185448. {
  185449. return info_ptr->filter_type;
  185450. }
  185451. return (0);
  185452. }
  185453. png_byte PNGAPI
  185454. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185455. {
  185456. if (png_ptr != NULL && info_ptr != NULL)
  185457. {
  185458. return info_ptr->interlace_type;
  185459. }
  185460. return (0);
  185461. }
  185462. png_byte PNGAPI
  185463. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185464. {
  185465. if (png_ptr != NULL && info_ptr != NULL)
  185466. {
  185467. return info_ptr->compression_type;
  185468. }
  185469. return (0);
  185470. }
  185471. png_uint_32 PNGAPI
  185472. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185473. {
  185474. if (png_ptr != NULL && info_ptr != NULL)
  185475. #if defined(PNG_pHYs_SUPPORTED)
  185476. if (info_ptr->valid & PNG_INFO_pHYs)
  185477. {
  185478. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185479. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185480. return (0);
  185481. else return (info_ptr->x_pixels_per_unit);
  185482. }
  185483. #else
  185484. return (0);
  185485. #endif
  185486. return (0);
  185487. }
  185488. png_uint_32 PNGAPI
  185489. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185490. {
  185491. if (png_ptr != NULL && info_ptr != NULL)
  185492. #if defined(PNG_pHYs_SUPPORTED)
  185493. if (info_ptr->valid & PNG_INFO_pHYs)
  185494. {
  185495. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  185496. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185497. return (0);
  185498. else return (info_ptr->y_pixels_per_unit);
  185499. }
  185500. #else
  185501. return (0);
  185502. #endif
  185503. return (0);
  185504. }
  185505. png_uint_32 PNGAPI
  185506. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185507. {
  185508. if (png_ptr != NULL && info_ptr != NULL)
  185509. #if defined(PNG_pHYs_SUPPORTED)
  185510. if (info_ptr->valid & PNG_INFO_pHYs)
  185511. {
  185512. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  185513. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  185514. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  185515. return (0);
  185516. else return (info_ptr->x_pixels_per_unit);
  185517. }
  185518. #else
  185519. return (0);
  185520. #endif
  185521. return (0);
  185522. }
  185523. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185524. float PNGAPI
  185525. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  185526. {
  185527. if (png_ptr != NULL && info_ptr != NULL)
  185528. #if defined(PNG_pHYs_SUPPORTED)
  185529. if (info_ptr->valid & PNG_INFO_pHYs)
  185530. {
  185531. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  185532. if (info_ptr->x_pixels_per_unit == 0)
  185533. return ((float)0.0);
  185534. else
  185535. return ((float)((float)info_ptr->y_pixels_per_unit
  185536. /(float)info_ptr->x_pixels_per_unit));
  185537. }
  185538. #else
  185539. return (0.0);
  185540. #endif
  185541. return ((float)0.0);
  185542. }
  185543. #endif
  185544. png_int_32 PNGAPI
  185545. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185546. {
  185547. if (png_ptr != NULL && info_ptr != NULL)
  185548. #if defined(PNG_oFFs_SUPPORTED)
  185549. if (info_ptr->valid & PNG_INFO_oFFs)
  185550. {
  185551. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185552. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185553. return (0);
  185554. else return (info_ptr->x_offset);
  185555. }
  185556. #else
  185557. return (0);
  185558. #endif
  185559. return (0);
  185560. }
  185561. png_int_32 PNGAPI
  185562. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185563. {
  185564. if (png_ptr != NULL && info_ptr != NULL)
  185565. #if defined(PNG_oFFs_SUPPORTED)
  185566. if (info_ptr->valid & PNG_INFO_oFFs)
  185567. {
  185568. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185569. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185570. return (0);
  185571. else return (info_ptr->y_offset);
  185572. }
  185573. #else
  185574. return (0);
  185575. #endif
  185576. return (0);
  185577. }
  185578. png_int_32 PNGAPI
  185579. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185580. {
  185581. if (png_ptr != NULL && info_ptr != NULL)
  185582. #if defined(PNG_oFFs_SUPPORTED)
  185583. if (info_ptr->valid & PNG_INFO_oFFs)
  185584. {
  185585. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185586. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185587. return (0);
  185588. else return (info_ptr->x_offset);
  185589. }
  185590. #else
  185591. return (0);
  185592. #endif
  185593. return (0);
  185594. }
  185595. png_int_32 PNGAPI
  185596. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185597. {
  185598. if (png_ptr != NULL && info_ptr != NULL)
  185599. #if defined(PNG_oFFs_SUPPORTED)
  185600. if (info_ptr->valid & PNG_INFO_oFFs)
  185601. {
  185602. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185603. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185604. return (0);
  185605. else return (info_ptr->y_offset);
  185606. }
  185607. #else
  185608. return (0);
  185609. #endif
  185610. return (0);
  185611. }
  185612. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185613. png_uint_32 PNGAPI
  185614. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185615. {
  185616. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  185617. *.0254 +.5));
  185618. }
  185619. png_uint_32 PNGAPI
  185620. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185621. {
  185622. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  185623. *.0254 +.5));
  185624. }
  185625. png_uint_32 PNGAPI
  185626. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185627. {
  185628. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  185629. *.0254 +.5));
  185630. }
  185631. float PNGAPI
  185632. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185633. {
  185634. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  185635. *.00003937);
  185636. }
  185637. float PNGAPI
  185638. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185639. {
  185640. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  185641. *.00003937);
  185642. }
  185643. #if defined(PNG_pHYs_SUPPORTED)
  185644. png_uint_32 PNGAPI
  185645. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  185646. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185647. {
  185648. png_uint_32 retval = 0;
  185649. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  185650. {
  185651. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185652. if (res_x != NULL)
  185653. {
  185654. *res_x = info_ptr->x_pixels_per_unit;
  185655. retval |= PNG_INFO_pHYs;
  185656. }
  185657. if (res_y != NULL)
  185658. {
  185659. *res_y = info_ptr->y_pixels_per_unit;
  185660. retval |= PNG_INFO_pHYs;
  185661. }
  185662. if (unit_type != NULL)
  185663. {
  185664. *unit_type = (int)info_ptr->phys_unit_type;
  185665. retval |= PNG_INFO_pHYs;
  185666. if(*unit_type == 1)
  185667. {
  185668. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  185669. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  185670. }
  185671. }
  185672. }
  185673. return (retval);
  185674. }
  185675. #endif /* PNG_pHYs_SUPPORTED */
  185676. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  185677. /* png_get_channels really belongs in here, too, but it's been around longer */
  185678. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  185679. png_byte PNGAPI
  185680. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  185681. {
  185682. if (png_ptr != NULL && info_ptr != NULL)
  185683. return(info_ptr->channels);
  185684. else
  185685. return (0);
  185686. }
  185687. png_bytep PNGAPI
  185688. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  185689. {
  185690. if (png_ptr != NULL && info_ptr != NULL)
  185691. return(info_ptr->signature);
  185692. else
  185693. return (NULL);
  185694. }
  185695. #if defined(PNG_bKGD_SUPPORTED)
  185696. png_uint_32 PNGAPI
  185697. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  185698. png_color_16p *background)
  185699. {
  185700. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  185701. && background != NULL)
  185702. {
  185703. png_debug1(1, "in %s retrieval function\n", "bKGD");
  185704. *background = &(info_ptr->background);
  185705. return (PNG_INFO_bKGD);
  185706. }
  185707. return (0);
  185708. }
  185709. #endif
  185710. #if defined(PNG_cHRM_SUPPORTED)
  185711. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185712. png_uint_32 PNGAPI
  185713. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  185714. double *white_x, double *white_y, double *red_x, double *red_y,
  185715. double *green_x, double *green_y, double *blue_x, double *blue_y)
  185716. {
  185717. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185718. {
  185719. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185720. if (white_x != NULL)
  185721. *white_x = (double)info_ptr->x_white;
  185722. if (white_y != NULL)
  185723. *white_y = (double)info_ptr->y_white;
  185724. if (red_x != NULL)
  185725. *red_x = (double)info_ptr->x_red;
  185726. if (red_y != NULL)
  185727. *red_y = (double)info_ptr->y_red;
  185728. if (green_x != NULL)
  185729. *green_x = (double)info_ptr->x_green;
  185730. if (green_y != NULL)
  185731. *green_y = (double)info_ptr->y_green;
  185732. if (blue_x != NULL)
  185733. *blue_x = (double)info_ptr->x_blue;
  185734. if (blue_y != NULL)
  185735. *blue_y = (double)info_ptr->y_blue;
  185736. return (PNG_INFO_cHRM);
  185737. }
  185738. return (0);
  185739. }
  185740. #endif
  185741. #ifdef PNG_FIXED_POINT_SUPPORTED
  185742. png_uint_32 PNGAPI
  185743. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  185744. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  185745. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  185746. png_fixed_point *blue_x, png_fixed_point *blue_y)
  185747. {
  185748. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185749. {
  185750. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185751. if (white_x != NULL)
  185752. *white_x = info_ptr->int_x_white;
  185753. if (white_y != NULL)
  185754. *white_y = info_ptr->int_y_white;
  185755. if (red_x != NULL)
  185756. *red_x = info_ptr->int_x_red;
  185757. if (red_y != NULL)
  185758. *red_y = info_ptr->int_y_red;
  185759. if (green_x != NULL)
  185760. *green_x = info_ptr->int_x_green;
  185761. if (green_y != NULL)
  185762. *green_y = info_ptr->int_y_green;
  185763. if (blue_x != NULL)
  185764. *blue_x = info_ptr->int_x_blue;
  185765. if (blue_y != NULL)
  185766. *blue_y = info_ptr->int_y_blue;
  185767. return (PNG_INFO_cHRM);
  185768. }
  185769. return (0);
  185770. }
  185771. #endif
  185772. #endif
  185773. #if defined(PNG_gAMA_SUPPORTED)
  185774. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185775. png_uint_32 PNGAPI
  185776. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  185777. {
  185778. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185779. && file_gamma != NULL)
  185780. {
  185781. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185782. *file_gamma = (double)info_ptr->gamma;
  185783. return (PNG_INFO_gAMA);
  185784. }
  185785. return (0);
  185786. }
  185787. #endif
  185788. #ifdef PNG_FIXED_POINT_SUPPORTED
  185789. png_uint_32 PNGAPI
  185790. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  185791. png_fixed_point *int_file_gamma)
  185792. {
  185793. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185794. && int_file_gamma != NULL)
  185795. {
  185796. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185797. *int_file_gamma = info_ptr->int_gamma;
  185798. return (PNG_INFO_gAMA);
  185799. }
  185800. return (0);
  185801. }
  185802. #endif
  185803. #endif
  185804. #if defined(PNG_sRGB_SUPPORTED)
  185805. png_uint_32 PNGAPI
  185806. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  185807. {
  185808. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  185809. && file_srgb_intent != NULL)
  185810. {
  185811. png_debug1(1, "in %s retrieval function\n", "sRGB");
  185812. *file_srgb_intent = (int)info_ptr->srgb_intent;
  185813. return (PNG_INFO_sRGB);
  185814. }
  185815. return (0);
  185816. }
  185817. #endif
  185818. #if defined(PNG_iCCP_SUPPORTED)
  185819. png_uint_32 PNGAPI
  185820. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  185821. png_charpp name, int *compression_type,
  185822. png_charpp profile, png_uint_32 *proflen)
  185823. {
  185824. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  185825. && name != NULL && profile != NULL && proflen != NULL)
  185826. {
  185827. png_debug1(1, "in %s retrieval function\n", "iCCP");
  185828. *name = info_ptr->iccp_name;
  185829. *profile = info_ptr->iccp_profile;
  185830. /* compression_type is a dummy so the API won't have to change
  185831. if we introduce multiple compression types later. */
  185832. *proflen = (int)info_ptr->iccp_proflen;
  185833. *compression_type = (int)info_ptr->iccp_compression;
  185834. return (PNG_INFO_iCCP);
  185835. }
  185836. return (0);
  185837. }
  185838. #endif
  185839. #if defined(PNG_sPLT_SUPPORTED)
  185840. png_uint_32 PNGAPI
  185841. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  185842. png_sPLT_tpp spalettes)
  185843. {
  185844. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  185845. {
  185846. *spalettes = info_ptr->splt_palettes;
  185847. return ((png_uint_32)info_ptr->splt_palettes_num);
  185848. }
  185849. return (0);
  185850. }
  185851. #endif
  185852. #if defined(PNG_hIST_SUPPORTED)
  185853. png_uint_32 PNGAPI
  185854. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  185855. {
  185856. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  185857. && hist != NULL)
  185858. {
  185859. png_debug1(1, "in %s retrieval function\n", "hIST");
  185860. *hist = info_ptr->hist;
  185861. return (PNG_INFO_hIST);
  185862. }
  185863. return (0);
  185864. }
  185865. #endif
  185866. png_uint_32 PNGAPI
  185867. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  185868. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  185869. int *color_type, int *interlace_type, int *compression_type,
  185870. int *filter_type)
  185871. {
  185872. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  185873. bit_depth != NULL && color_type != NULL)
  185874. {
  185875. png_debug1(1, "in %s retrieval function\n", "IHDR");
  185876. *width = info_ptr->width;
  185877. *height = info_ptr->height;
  185878. *bit_depth = info_ptr->bit_depth;
  185879. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  185880. png_error(png_ptr, "Invalid bit depth");
  185881. *color_type = info_ptr->color_type;
  185882. if (info_ptr->color_type > 6)
  185883. png_error(png_ptr, "Invalid color type");
  185884. if (compression_type != NULL)
  185885. *compression_type = info_ptr->compression_type;
  185886. if (filter_type != NULL)
  185887. *filter_type = info_ptr->filter_type;
  185888. if (interlace_type != NULL)
  185889. *interlace_type = info_ptr->interlace_type;
  185890. /* check for potential overflow of rowbytes */
  185891. if (*width == 0 || *width > PNG_UINT_31_MAX)
  185892. png_error(png_ptr, "Invalid image width");
  185893. if (*height == 0 || *height > PNG_UINT_31_MAX)
  185894. png_error(png_ptr, "Invalid image height");
  185895. if (info_ptr->width > (PNG_UINT_32_MAX
  185896. >> 3) /* 8-byte RGBA pixels */
  185897. - 64 /* bigrowbuf hack */
  185898. - 1 /* filter byte */
  185899. - 7*8 /* rounding of width to multiple of 8 pixels */
  185900. - 8) /* extra max_pixel_depth pad */
  185901. {
  185902. png_warning(png_ptr,
  185903. "Width too large for libpng to process image data.");
  185904. }
  185905. return (1);
  185906. }
  185907. return (0);
  185908. }
  185909. #if defined(PNG_oFFs_SUPPORTED)
  185910. png_uint_32 PNGAPI
  185911. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  185912. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  185913. {
  185914. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  185915. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  185916. {
  185917. png_debug1(1, "in %s retrieval function\n", "oFFs");
  185918. *offset_x = info_ptr->x_offset;
  185919. *offset_y = info_ptr->y_offset;
  185920. *unit_type = (int)info_ptr->offset_unit_type;
  185921. return (PNG_INFO_oFFs);
  185922. }
  185923. return (0);
  185924. }
  185925. #endif
  185926. #if defined(PNG_pCAL_SUPPORTED)
  185927. png_uint_32 PNGAPI
  185928. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  185929. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  185930. png_charp *units, png_charpp *params)
  185931. {
  185932. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  185933. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  185934. nparams != NULL && units != NULL && params != NULL)
  185935. {
  185936. png_debug1(1, "in %s retrieval function\n", "pCAL");
  185937. *purpose = info_ptr->pcal_purpose;
  185938. *X0 = info_ptr->pcal_X0;
  185939. *X1 = info_ptr->pcal_X1;
  185940. *type = (int)info_ptr->pcal_type;
  185941. *nparams = (int)info_ptr->pcal_nparams;
  185942. *units = info_ptr->pcal_units;
  185943. *params = info_ptr->pcal_params;
  185944. return (PNG_INFO_pCAL);
  185945. }
  185946. return (0);
  185947. }
  185948. #endif
  185949. #if defined(PNG_sCAL_SUPPORTED)
  185950. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185951. png_uint_32 PNGAPI
  185952. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  185953. int *unit, double *width, double *height)
  185954. {
  185955. if (png_ptr != NULL && info_ptr != NULL &&
  185956. (info_ptr->valid & PNG_INFO_sCAL))
  185957. {
  185958. *unit = info_ptr->scal_unit;
  185959. *width = info_ptr->scal_pixel_width;
  185960. *height = info_ptr->scal_pixel_height;
  185961. return (PNG_INFO_sCAL);
  185962. }
  185963. return(0);
  185964. }
  185965. #else
  185966. #ifdef PNG_FIXED_POINT_SUPPORTED
  185967. png_uint_32 PNGAPI
  185968. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  185969. int *unit, png_charpp width, png_charpp height)
  185970. {
  185971. if (png_ptr != NULL && info_ptr != NULL &&
  185972. (info_ptr->valid & PNG_INFO_sCAL))
  185973. {
  185974. *unit = info_ptr->scal_unit;
  185975. *width = info_ptr->scal_s_width;
  185976. *height = info_ptr->scal_s_height;
  185977. return (PNG_INFO_sCAL);
  185978. }
  185979. return(0);
  185980. }
  185981. #endif
  185982. #endif
  185983. #endif
  185984. #if defined(PNG_pHYs_SUPPORTED)
  185985. png_uint_32 PNGAPI
  185986. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  185987. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185988. {
  185989. png_uint_32 retval = 0;
  185990. if (png_ptr != NULL && info_ptr != NULL &&
  185991. (info_ptr->valid & PNG_INFO_pHYs))
  185992. {
  185993. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185994. if (res_x != NULL)
  185995. {
  185996. *res_x = info_ptr->x_pixels_per_unit;
  185997. retval |= PNG_INFO_pHYs;
  185998. }
  185999. if (res_y != NULL)
  186000. {
  186001. *res_y = info_ptr->y_pixels_per_unit;
  186002. retval |= PNG_INFO_pHYs;
  186003. }
  186004. if (unit_type != NULL)
  186005. {
  186006. *unit_type = (int)info_ptr->phys_unit_type;
  186007. retval |= PNG_INFO_pHYs;
  186008. }
  186009. }
  186010. return (retval);
  186011. }
  186012. #endif
  186013. png_uint_32 PNGAPI
  186014. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  186015. int *num_palette)
  186016. {
  186017. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  186018. && palette != NULL)
  186019. {
  186020. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186021. *palette = info_ptr->palette;
  186022. *num_palette = info_ptr->num_palette;
  186023. png_debug1(3, "num_palette = %d\n", *num_palette);
  186024. return (PNG_INFO_PLTE);
  186025. }
  186026. return (0);
  186027. }
  186028. #if defined(PNG_sBIT_SUPPORTED)
  186029. png_uint_32 PNGAPI
  186030. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186031. {
  186032. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186033. && sig_bit != NULL)
  186034. {
  186035. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186036. *sig_bit = &(info_ptr->sig_bit);
  186037. return (PNG_INFO_sBIT);
  186038. }
  186039. return (0);
  186040. }
  186041. #endif
  186042. #if defined(PNG_TEXT_SUPPORTED)
  186043. png_uint_32 PNGAPI
  186044. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186045. int *num_text)
  186046. {
  186047. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186048. {
  186049. png_debug1(1, "in %s retrieval function\n",
  186050. (png_ptr->chunk_name[0] == '\0' ? "text"
  186051. : (png_const_charp)png_ptr->chunk_name));
  186052. if (text_ptr != NULL)
  186053. *text_ptr = info_ptr->text;
  186054. if (num_text != NULL)
  186055. *num_text = info_ptr->num_text;
  186056. return ((png_uint_32)info_ptr->num_text);
  186057. }
  186058. if (num_text != NULL)
  186059. *num_text = 0;
  186060. return(0);
  186061. }
  186062. #endif
  186063. #if defined(PNG_tIME_SUPPORTED)
  186064. png_uint_32 PNGAPI
  186065. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186066. {
  186067. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186068. && mod_time != NULL)
  186069. {
  186070. png_debug1(1, "in %s retrieval function\n", "tIME");
  186071. *mod_time = &(info_ptr->mod_time);
  186072. return (PNG_INFO_tIME);
  186073. }
  186074. return (0);
  186075. }
  186076. #endif
  186077. #if defined(PNG_tRNS_SUPPORTED)
  186078. png_uint_32 PNGAPI
  186079. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186080. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186081. {
  186082. png_uint_32 retval = 0;
  186083. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186084. {
  186085. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186086. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186087. {
  186088. if (trans != NULL)
  186089. {
  186090. *trans = info_ptr->trans;
  186091. retval |= PNG_INFO_tRNS;
  186092. }
  186093. if (trans_values != NULL)
  186094. *trans_values = &(info_ptr->trans_values);
  186095. }
  186096. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186097. {
  186098. if (trans_values != NULL)
  186099. {
  186100. *trans_values = &(info_ptr->trans_values);
  186101. retval |= PNG_INFO_tRNS;
  186102. }
  186103. if(trans != NULL)
  186104. *trans = NULL;
  186105. }
  186106. if(num_trans != NULL)
  186107. {
  186108. *num_trans = info_ptr->num_trans;
  186109. retval |= PNG_INFO_tRNS;
  186110. }
  186111. }
  186112. return (retval);
  186113. }
  186114. #endif
  186115. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186116. png_uint_32 PNGAPI
  186117. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186118. png_unknown_chunkpp unknowns)
  186119. {
  186120. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186121. {
  186122. *unknowns = info_ptr->unknown_chunks;
  186123. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186124. }
  186125. return (0);
  186126. }
  186127. #endif
  186128. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186129. png_byte PNGAPI
  186130. png_get_rgb_to_gray_status (png_structp png_ptr)
  186131. {
  186132. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186133. }
  186134. #endif
  186135. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186136. png_voidp PNGAPI
  186137. png_get_user_chunk_ptr(png_structp png_ptr)
  186138. {
  186139. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186140. }
  186141. #endif
  186142. #ifdef PNG_WRITE_SUPPORTED
  186143. png_uint_32 PNGAPI
  186144. png_get_compression_buffer_size(png_structp png_ptr)
  186145. {
  186146. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186147. }
  186148. #endif
  186149. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186150. #ifndef PNG_1_0_X
  186151. /* this function was added to libpng 1.2.0 and should exist by default */
  186152. png_uint_32 PNGAPI
  186153. png_get_asm_flags (png_structp png_ptr)
  186154. {
  186155. /* obsolete, to be removed from libpng-1.4.0 */
  186156. return (png_ptr? 0L: 0L);
  186157. }
  186158. /* this function was added to libpng 1.2.0 and should exist by default */
  186159. png_uint_32 PNGAPI
  186160. png_get_asm_flagmask (int flag_select)
  186161. {
  186162. /* obsolete, to be removed from libpng-1.4.0 */
  186163. flag_select=flag_select;
  186164. return 0L;
  186165. }
  186166. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186167. /* this function was added to libpng 1.2.0 */
  186168. png_uint_32 PNGAPI
  186169. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186170. {
  186171. /* obsolete, to be removed from libpng-1.4.0 */
  186172. flag_select=flag_select;
  186173. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186174. return 0L;
  186175. }
  186176. /* this function was added to libpng 1.2.0 */
  186177. png_byte PNGAPI
  186178. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186179. {
  186180. /* obsolete, to be removed from libpng-1.4.0 */
  186181. return (png_ptr? 0: 0);
  186182. }
  186183. /* this function was added to libpng 1.2.0 */
  186184. png_uint_32 PNGAPI
  186185. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186186. {
  186187. /* obsolete, to be removed from libpng-1.4.0 */
  186188. return (png_ptr? 0L: 0L);
  186189. }
  186190. #endif /* ?PNG_1_0_X */
  186191. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186192. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186193. /* these functions were added to libpng 1.2.6 */
  186194. png_uint_32 PNGAPI
  186195. png_get_user_width_max (png_structp png_ptr)
  186196. {
  186197. return (png_ptr? png_ptr->user_width_max : 0);
  186198. }
  186199. png_uint_32 PNGAPI
  186200. png_get_user_height_max (png_structp png_ptr)
  186201. {
  186202. return (png_ptr? png_ptr->user_height_max : 0);
  186203. }
  186204. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186205. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186206. /*** End of inlined file: pngget.c ***/
  186207. /*** Start of inlined file: pngmem.c ***/
  186208. /* pngmem.c - stub functions for memory allocation
  186209. *
  186210. * Last changed in libpng 1.2.13 November 13, 2006
  186211. * For conditions of distribution and use, see copyright notice in png.h
  186212. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186213. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186214. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186215. *
  186216. * This file provides a location for all memory allocation. Users who
  186217. * need special memory handling are expected to supply replacement
  186218. * functions for png_malloc() and png_free(), and to use
  186219. * png_create_read_struct_2() and png_create_write_struct_2() to
  186220. * identify the replacement functions.
  186221. */
  186222. #define PNG_INTERNAL
  186223. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186224. /* Borland DOS special memory handler */
  186225. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186226. /* if you change this, be sure to change the one in png.h also */
  186227. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186228. by a single call to calloc() if this is thought to improve performance. */
  186229. png_voidp /* PRIVATE */
  186230. png_create_struct(int type)
  186231. {
  186232. #ifdef PNG_USER_MEM_SUPPORTED
  186233. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186234. }
  186235. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186236. png_voidp /* PRIVATE */
  186237. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186238. {
  186239. #endif /* PNG_USER_MEM_SUPPORTED */
  186240. png_size_t size;
  186241. png_voidp struct_ptr;
  186242. if (type == PNG_STRUCT_INFO)
  186243. size = png_sizeof(png_info);
  186244. else if (type == PNG_STRUCT_PNG)
  186245. size = png_sizeof(png_struct);
  186246. else
  186247. return (png_get_copyright(NULL));
  186248. #ifdef PNG_USER_MEM_SUPPORTED
  186249. if(malloc_fn != NULL)
  186250. {
  186251. png_struct dummy_struct;
  186252. png_structp png_ptr = &dummy_struct;
  186253. png_ptr->mem_ptr=mem_ptr;
  186254. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186255. }
  186256. else
  186257. #endif /* PNG_USER_MEM_SUPPORTED */
  186258. struct_ptr = (png_voidp)farmalloc(size);
  186259. if (struct_ptr != NULL)
  186260. png_memset(struct_ptr, 0, size);
  186261. return (struct_ptr);
  186262. }
  186263. /* Free memory allocated by a png_create_struct() call */
  186264. void /* PRIVATE */
  186265. png_destroy_struct(png_voidp struct_ptr)
  186266. {
  186267. #ifdef PNG_USER_MEM_SUPPORTED
  186268. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186269. }
  186270. /* Free memory allocated by a png_create_struct() call */
  186271. void /* PRIVATE */
  186272. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186273. png_voidp mem_ptr)
  186274. {
  186275. #endif
  186276. if (struct_ptr != NULL)
  186277. {
  186278. #ifdef PNG_USER_MEM_SUPPORTED
  186279. if(free_fn != NULL)
  186280. {
  186281. png_struct dummy_struct;
  186282. png_structp png_ptr = &dummy_struct;
  186283. png_ptr->mem_ptr=mem_ptr;
  186284. (*(free_fn))(png_ptr, struct_ptr);
  186285. return;
  186286. }
  186287. #endif /* PNG_USER_MEM_SUPPORTED */
  186288. farfree (struct_ptr);
  186289. }
  186290. }
  186291. /* Allocate memory. For reasonable files, size should never exceed
  186292. * 64K. However, zlib may allocate more then 64K if you don't tell
  186293. * it not to. See zconf.h and png.h for more information. zlib does
  186294. * need to allocate exactly 64K, so whatever you call here must
  186295. * have the ability to do that.
  186296. *
  186297. * Borland seems to have a problem in DOS mode for exactly 64K.
  186298. * It gives you a segment with an offset of 8 (perhaps to store its
  186299. * memory stuff). zlib doesn't like this at all, so we have to
  186300. * detect and deal with it. This code should not be needed in
  186301. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186302. * been updated by Alexander Lehmann for version 0.89 to waste less
  186303. * memory.
  186304. *
  186305. * Note that we can't use png_size_t for the "size" declaration,
  186306. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186307. * result, we would be truncating potentially larger memory requests
  186308. * (which should cause a fatal error) and introducing major problems.
  186309. */
  186310. png_voidp PNGAPI
  186311. png_malloc(png_structp png_ptr, png_uint_32 size)
  186312. {
  186313. png_voidp ret;
  186314. if (png_ptr == NULL || size == 0)
  186315. return (NULL);
  186316. #ifdef PNG_USER_MEM_SUPPORTED
  186317. if(png_ptr->malloc_fn != NULL)
  186318. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186319. else
  186320. ret = (png_malloc_default(png_ptr, size));
  186321. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186322. png_error(png_ptr, "Out of memory!");
  186323. return (ret);
  186324. }
  186325. png_voidp PNGAPI
  186326. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186327. {
  186328. png_voidp ret;
  186329. #endif /* PNG_USER_MEM_SUPPORTED */
  186330. if (png_ptr == NULL || size == 0)
  186331. return (NULL);
  186332. #ifdef PNG_MAX_MALLOC_64K
  186333. if (size > (png_uint_32)65536L)
  186334. {
  186335. png_warning(png_ptr, "Cannot Allocate > 64K");
  186336. ret = NULL;
  186337. }
  186338. else
  186339. #endif
  186340. if (size != (size_t)size)
  186341. ret = NULL;
  186342. else if (size == (png_uint_32)65536L)
  186343. {
  186344. if (png_ptr->offset_table == NULL)
  186345. {
  186346. /* try to see if we need to do any of this fancy stuff */
  186347. ret = farmalloc(size);
  186348. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186349. {
  186350. int num_blocks;
  186351. png_uint_32 total_size;
  186352. png_bytep table;
  186353. int i;
  186354. png_byte huge * hptr;
  186355. if (ret != NULL)
  186356. {
  186357. farfree(ret);
  186358. ret = NULL;
  186359. }
  186360. if(png_ptr->zlib_window_bits > 14)
  186361. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186362. else
  186363. num_blocks = 1;
  186364. if (png_ptr->zlib_mem_level >= 7)
  186365. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186366. else
  186367. num_blocks++;
  186368. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186369. table = farmalloc(total_size);
  186370. if (table == NULL)
  186371. {
  186372. #ifndef PNG_USER_MEM_SUPPORTED
  186373. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186374. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186375. else
  186376. png_warning(png_ptr, "Out Of Memory.");
  186377. #endif
  186378. return (NULL);
  186379. }
  186380. if ((png_size_t)table & 0xfff0)
  186381. {
  186382. #ifndef PNG_USER_MEM_SUPPORTED
  186383. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186384. png_error(png_ptr,
  186385. "Farmalloc didn't return normalized pointer");
  186386. else
  186387. png_warning(png_ptr,
  186388. "Farmalloc didn't return normalized pointer");
  186389. #endif
  186390. return (NULL);
  186391. }
  186392. png_ptr->offset_table = table;
  186393. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186394. png_sizeof (png_bytep));
  186395. if (png_ptr->offset_table_ptr == NULL)
  186396. {
  186397. #ifndef PNG_USER_MEM_SUPPORTED
  186398. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186399. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186400. else
  186401. png_warning(png_ptr, "Out Of memory.");
  186402. #endif
  186403. return (NULL);
  186404. }
  186405. hptr = (png_byte huge *)table;
  186406. if ((png_size_t)hptr & 0xf)
  186407. {
  186408. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186409. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186410. }
  186411. for (i = 0; i < num_blocks; i++)
  186412. {
  186413. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186414. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186415. }
  186416. png_ptr->offset_table_number = num_blocks;
  186417. png_ptr->offset_table_count = 0;
  186418. png_ptr->offset_table_count_free = 0;
  186419. }
  186420. }
  186421. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186422. {
  186423. #ifndef PNG_USER_MEM_SUPPORTED
  186424. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186425. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186426. else
  186427. png_warning(png_ptr, "Out of Memory.");
  186428. #endif
  186429. return (NULL);
  186430. }
  186431. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186432. }
  186433. else
  186434. ret = farmalloc(size);
  186435. #ifndef PNG_USER_MEM_SUPPORTED
  186436. if (ret == NULL)
  186437. {
  186438. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186439. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186440. else
  186441. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186442. }
  186443. #endif
  186444. return (ret);
  186445. }
  186446. /* free a pointer allocated by png_malloc(). In the default
  186447. configuration, png_ptr is not used, but is passed in case it
  186448. is needed. If ptr is NULL, return without taking any action. */
  186449. void PNGAPI
  186450. png_free(png_structp png_ptr, png_voidp ptr)
  186451. {
  186452. if (png_ptr == NULL || ptr == NULL)
  186453. return;
  186454. #ifdef PNG_USER_MEM_SUPPORTED
  186455. if (png_ptr->free_fn != NULL)
  186456. {
  186457. (*(png_ptr->free_fn))(png_ptr, ptr);
  186458. return;
  186459. }
  186460. else png_free_default(png_ptr, ptr);
  186461. }
  186462. void PNGAPI
  186463. png_free_default(png_structp png_ptr, png_voidp ptr)
  186464. {
  186465. #endif /* PNG_USER_MEM_SUPPORTED */
  186466. if(png_ptr == NULL) return;
  186467. if (png_ptr->offset_table != NULL)
  186468. {
  186469. int i;
  186470. for (i = 0; i < png_ptr->offset_table_count; i++)
  186471. {
  186472. if (ptr == png_ptr->offset_table_ptr[i])
  186473. {
  186474. ptr = NULL;
  186475. png_ptr->offset_table_count_free++;
  186476. break;
  186477. }
  186478. }
  186479. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186480. {
  186481. farfree(png_ptr->offset_table);
  186482. farfree(png_ptr->offset_table_ptr);
  186483. png_ptr->offset_table = NULL;
  186484. png_ptr->offset_table_ptr = NULL;
  186485. }
  186486. }
  186487. if (ptr != NULL)
  186488. {
  186489. farfree(ptr);
  186490. }
  186491. }
  186492. #else /* Not the Borland DOS special memory handler */
  186493. /* Allocate memory for a png_struct or a png_info. The malloc and
  186494. memset can be replaced by a single call to calloc() if this is thought
  186495. to improve performance noticably. */
  186496. png_voidp /* PRIVATE */
  186497. png_create_struct(int type)
  186498. {
  186499. #ifdef PNG_USER_MEM_SUPPORTED
  186500. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186501. }
  186502. /* Allocate memory for a png_struct or a png_info. The malloc and
  186503. memset can be replaced by a single call to calloc() if this is thought
  186504. to improve performance noticably. */
  186505. png_voidp /* PRIVATE */
  186506. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186507. {
  186508. #endif /* PNG_USER_MEM_SUPPORTED */
  186509. png_size_t size;
  186510. png_voidp struct_ptr;
  186511. if (type == PNG_STRUCT_INFO)
  186512. size = png_sizeof(png_info);
  186513. else if (type == PNG_STRUCT_PNG)
  186514. size = png_sizeof(png_struct);
  186515. else
  186516. return (NULL);
  186517. #ifdef PNG_USER_MEM_SUPPORTED
  186518. if(malloc_fn != NULL)
  186519. {
  186520. png_struct dummy_struct;
  186521. png_structp png_ptr = &dummy_struct;
  186522. png_ptr->mem_ptr=mem_ptr;
  186523. struct_ptr = (*(malloc_fn))(png_ptr, size);
  186524. if (struct_ptr != NULL)
  186525. png_memset(struct_ptr, 0, size);
  186526. return (struct_ptr);
  186527. }
  186528. #endif /* PNG_USER_MEM_SUPPORTED */
  186529. #if defined(__TURBOC__) && !defined(__FLAT__)
  186530. struct_ptr = (png_voidp)farmalloc(size);
  186531. #else
  186532. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186533. struct_ptr = (png_voidp)halloc(size,1);
  186534. # else
  186535. struct_ptr = (png_voidp)malloc(size);
  186536. # endif
  186537. #endif
  186538. if (struct_ptr != NULL)
  186539. png_memset(struct_ptr, 0, size);
  186540. return (struct_ptr);
  186541. }
  186542. /* Free memory allocated by a png_create_struct() call */
  186543. void /* PRIVATE */
  186544. png_destroy_struct(png_voidp struct_ptr)
  186545. {
  186546. #ifdef PNG_USER_MEM_SUPPORTED
  186547. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186548. }
  186549. /* Free memory allocated by a png_create_struct() call */
  186550. void /* PRIVATE */
  186551. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186552. png_voidp mem_ptr)
  186553. {
  186554. #endif /* PNG_USER_MEM_SUPPORTED */
  186555. if (struct_ptr != NULL)
  186556. {
  186557. #ifdef PNG_USER_MEM_SUPPORTED
  186558. if(free_fn != NULL)
  186559. {
  186560. png_struct dummy_struct;
  186561. png_structp png_ptr = &dummy_struct;
  186562. png_ptr->mem_ptr=mem_ptr;
  186563. (*(free_fn))(png_ptr, struct_ptr);
  186564. return;
  186565. }
  186566. #endif /* PNG_USER_MEM_SUPPORTED */
  186567. #if defined(__TURBOC__) && !defined(__FLAT__)
  186568. farfree(struct_ptr);
  186569. #else
  186570. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186571. hfree(struct_ptr);
  186572. # else
  186573. free(struct_ptr);
  186574. # endif
  186575. #endif
  186576. }
  186577. }
  186578. /* Allocate memory. For reasonable files, size should never exceed
  186579. 64K. However, zlib may allocate more then 64K if you don't tell
  186580. it not to. See zconf.h and png.h for more information. zlib does
  186581. need to allocate exactly 64K, so whatever you call here must
  186582. have the ability to do that. */
  186583. png_voidp PNGAPI
  186584. png_malloc(png_structp png_ptr, png_uint_32 size)
  186585. {
  186586. png_voidp ret;
  186587. #ifdef PNG_USER_MEM_SUPPORTED
  186588. if (png_ptr == NULL || size == 0)
  186589. return (NULL);
  186590. if(png_ptr->malloc_fn != NULL)
  186591. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186592. else
  186593. ret = (png_malloc_default(png_ptr, size));
  186594. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186595. png_error(png_ptr, "Out of Memory!");
  186596. return (ret);
  186597. }
  186598. png_voidp PNGAPI
  186599. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186600. {
  186601. png_voidp ret;
  186602. #endif /* PNG_USER_MEM_SUPPORTED */
  186603. if (png_ptr == NULL || size == 0)
  186604. return (NULL);
  186605. #ifdef PNG_MAX_MALLOC_64K
  186606. if (size > (png_uint_32)65536L)
  186607. {
  186608. #ifndef PNG_USER_MEM_SUPPORTED
  186609. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186610. png_error(png_ptr, "Cannot Allocate > 64K");
  186611. else
  186612. #endif
  186613. return NULL;
  186614. }
  186615. #endif
  186616. /* Check for overflow */
  186617. #if defined(__TURBOC__) && !defined(__FLAT__)
  186618. if (size != (unsigned long)size)
  186619. ret = NULL;
  186620. else
  186621. ret = farmalloc(size);
  186622. #else
  186623. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186624. if (size != (unsigned long)size)
  186625. ret = NULL;
  186626. else
  186627. ret = halloc(size, 1);
  186628. # else
  186629. if (size != (size_t)size)
  186630. ret = NULL;
  186631. else
  186632. ret = malloc((size_t)size);
  186633. # endif
  186634. #endif
  186635. #ifndef PNG_USER_MEM_SUPPORTED
  186636. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186637. png_error(png_ptr, "Out of Memory");
  186638. #endif
  186639. return (ret);
  186640. }
  186641. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  186642. without taking any action. */
  186643. void PNGAPI
  186644. png_free(png_structp png_ptr, png_voidp ptr)
  186645. {
  186646. if (png_ptr == NULL || ptr == NULL)
  186647. return;
  186648. #ifdef PNG_USER_MEM_SUPPORTED
  186649. if (png_ptr->free_fn != NULL)
  186650. {
  186651. (*(png_ptr->free_fn))(png_ptr, ptr);
  186652. return;
  186653. }
  186654. else png_free_default(png_ptr, ptr);
  186655. }
  186656. void PNGAPI
  186657. png_free_default(png_structp png_ptr, png_voidp ptr)
  186658. {
  186659. if (png_ptr == NULL || ptr == NULL)
  186660. return;
  186661. #endif /* PNG_USER_MEM_SUPPORTED */
  186662. #if defined(__TURBOC__) && !defined(__FLAT__)
  186663. farfree(ptr);
  186664. #else
  186665. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186666. hfree(ptr);
  186667. # else
  186668. free(ptr);
  186669. # endif
  186670. #endif
  186671. }
  186672. #endif /* Not Borland DOS special memory handler */
  186673. #if defined(PNG_1_0_X)
  186674. # define png_malloc_warn png_malloc
  186675. #else
  186676. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  186677. * function will set up png_malloc() to issue a png_warning and return NULL
  186678. * instead of issuing a png_error, if it fails to allocate the requested
  186679. * memory.
  186680. */
  186681. png_voidp PNGAPI
  186682. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  186683. {
  186684. png_voidp ptr;
  186685. png_uint_32 save_flags;
  186686. if(png_ptr == NULL) return (NULL);
  186687. save_flags=png_ptr->flags;
  186688. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  186689. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  186690. png_ptr->flags=save_flags;
  186691. return(ptr);
  186692. }
  186693. #endif
  186694. png_voidp PNGAPI
  186695. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  186696. png_uint_32 length)
  186697. {
  186698. png_size_t size;
  186699. size = (png_size_t)length;
  186700. if ((png_uint_32)size != length)
  186701. png_error(png_ptr,"Overflow in png_memcpy_check.");
  186702. return(png_memcpy (s1, s2, size));
  186703. }
  186704. png_voidp PNGAPI
  186705. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  186706. png_uint_32 length)
  186707. {
  186708. png_size_t size;
  186709. size = (png_size_t)length;
  186710. if ((png_uint_32)size != length)
  186711. png_error(png_ptr,"Overflow in png_memset_check.");
  186712. return (png_memset (s1, value, size));
  186713. }
  186714. #ifdef PNG_USER_MEM_SUPPORTED
  186715. /* This function is called when the application wants to use another method
  186716. * of allocating and freeing memory.
  186717. */
  186718. void PNGAPI
  186719. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  186720. malloc_fn, png_free_ptr free_fn)
  186721. {
  186722. if(png_ptr != NULL) {
  186723. png_ptr->mem_ptr = mem_ptr;
  186724. png_ptr->malloc_fn = malloc_fn;
  186725. png_ptr->free_fn = free_fn;
  186726. }
  186727. }
  186728. /* This function returns a pointer to the mem_ptr associated with the user
  186729. * functions. The application should free any memory associated with this
  186730. * pointer before png_write_destroy and png_read_destroy are called.
  186731. */
  186732. png_voidp PNGAPI
  186733. png_get_mem_ptr(png_structp png_ptr)
  186734. {
  186735. if(png_ptr == NULL) return (NULL);
  186736. return ((png_voidp)png_ptr->mem_ptr);
  186737. }
  186738. #endif /* PNG_USER_MEM_SUPPORTED */
  186739. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186740. /*** End of inlined file: pngmem.c ***/
  186741. /*** Start of inlined file: pngread.c ***/
  186742. /* pngread.c - read a PNG file
  186743. *
  186744. * Last changed in libpng 1.2.20 September 7, 2007
  186745. * For conditions of distribution and use, see copyright notice in png.h
  186746. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  186747. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186748. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186749. *
  186750. * This file contains routines that an application calls directly to
  186751. * read a PNG file or stream.
  186752. */
  186753. #define PNG_INTERNAL
  186754. #if defined(PNG_READ_SUPPORTED)
  186755. /* Create a PNG structure for reading, and allocate any memory needed. */
  186756. png_structp PNGAPI
  186757. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  186758. png_error_ptr error_fn, png_error_ptr warn_fn)
  186759. {
  186760. #ifdef PNG_USER_MEM_SUPPORTED
  186761. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  186762. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  186763. }
  186764. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  186765. png_structp PNGAPI
  186766. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  186767. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  186768. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  186769. {
  186770. #endif /* PNG_USER_MEM_SUPPORTED */
  186771. png_structp png_ptr;
  186772. #ifdef PNG_SETJMP_SUPPORTED
  186773. #ifdef USE_FAR_KEYWORD
  186774. jmp_buf jmpbuf;
  186775. #endif
  186776. #endif
  186777. int i;
  186778. png_debug(1, "in png_create_read_struct\n");
  186779. #ifdef PNG_USER_MEM_SUPPORTED
  186780. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  186781. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  186782. #else
  186783. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186784. #endif
  186785. if (png_ptr == NULL)
  186786. return (NULL);
  186787. /* added at libpng-1.2.6 */
  186788. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186789. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186790. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186791. #endif
  186792. #ifdef PNG_SETJMP_SUPPORTED
  186793. #ifdef USE_FAR_KEYWORD
  186794. if (setjmp(jmpbuf))
  186795. #else
  186796. if (setjmp(png_ptr->jmpbuf))
  186797. #endif
  186798. {
  186799. png_free(png_ptr, png_ptr->zbuf);
  186800. png_ptr->zbuf=NULL;
  186801. #ifdef PNG_USER_MEM_SUPPORTED
  186802. png_destroy_struct_2((png_voidp)png_ptr,
  186803. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  186804. #else
  186805. png_destroy_struct((png_voidp)png_ptr);
  186806. #endif
  186807. return (NULL);
  186808. }
  186809. #ifdef USE_FAR_KEYWORD
  186810. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186811. #endif
  186812. #endif
  186813. #ifdef PNG_USER_MEM_SUPPORTED
  186814. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  186815. #endif
  186816. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  186817. i=0;
  186818. do
  186819. {
  186820. if(user_png_ver[i] != png_libpng_ver[i])
  186821. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186822. } while (png_libpng_ver[i++]);
  186823. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  186824. {
  186825. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  186826. * we must recompile any applications that use any older library version.
  186827. * For versions after libpng 1.0, we will be compatible, so we need
  186828. * only check the first digit.
  186829. */
  186830. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  186831. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  186832. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  186833. {
  186834. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186835. char msg[80];
  186836. if (user_png_ver)
  186837. {
  186838. png_snprintf(msg, 80,
  186839. "Application was compiled with png.h from libpng-%.20s",
  186840. user_png_ver);
  186841. png_warning(png_ptr, msg);
  186842. }
  186843. png_snprintf(msg, 80,
  186844. "Application is running with png.c from libpng-%.20s",
  186845. png_libpng_ver);
  186846. png_warning(png_ptr, msg);
  186847. #endif
  186848. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186849. png_ptr->flags=0;
  186850. #endif
  186851. png_error(png_ptr,
  186852. "Incompatible libpng version in application and library");
  186853. }
  186854. }
  186855. /* initialize zbuf - compression buffer */
  186856. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186857. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186858. (png_uint_32)png_ptr->zbuf_size);
  186859. png_ptr->zstream.zalloc = png_zalloc;
  186860. png_ptr->zstream.zfree = png_zfree;
  186861. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186862. switch (inflateInit(&png_ptr->zstream))
  186863. {
  186864. case Z_OK: /* Do nothing */ break;
  186865. case Z_MEM_ERROR:
  186866. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  186867. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  186868. default: png_error(png_ptr, "Unknown zlib error");
  186869. }
  186870. png_ptr->zstream.next_out = png_ptr->zbuf;
  186871. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186872. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  186873. #ifdef PNG_SETJMP_SUPPORTED
  186874. /* Applications that neglect to set up their own setjmp() and then encounter
  186875. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  186876. abort instead of returning. */
  186877. #ifdef USE_FAR_KEYWORD
  186878. if (setjmp(jmpbuf))
  186879. PNG_ABORT();
  186880. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186881. #else
  186882. if (setjmp(png_ptr->jmpbuf))
  186883. PNG_ABORT();
  186884. #endif
  186885. #endif
  186886. return (png_ptr);
  186887. }
  186888. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  186889. /* Initialize PNG structure for reading, and allocate any memory needed.
  186890. This interface is deprecated in favour of the png_create_read_struct(),
  186891. and it will disappear as of libpng-1.3.0. */
  186892. #undef png_read_init
  186893. void PNGAPI
  186894. png_read_init(png_structp png_ptr)
  186895. {
  186896. /* We only come here via pre-1.0.7-compiled applications */
  186897. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  186898. }
  186899. void PNGAPI
  186900. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  186901. png_size_t png_struct_size, png_size_t png_info_size)
  186902. {
  186903. /* We only come here via pre-1.0.12-compiled applications */
  186904. if(png_ptr == NULL) return;
  186905. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186906. if(png_sizeof(png_struct) > png_struct_size ||
  186907. png_sizeof(png_info) > png_info_size)
  186908. {
  186909. char msg[80];
  186910. png_ptr->warning_fn=NULL;
  186911. if (user_png_ver)
  186912. {
  186913. png_snprintf(msg, 80,
  186914. "Application was compiled with png.h from libpng-%.20s",
  186915. user_png_ver);
  186916. png_warning(png_ptr, msg);
  186917. }
  186918. png_snprintf(msg, 80,
  186919. "Application is running with png.c from libpng-%.20s",
  186920. png_libpng_ver);
  186921. png_warning(png_ptr, msg);
  186922. }
  186923. #endif
  186924. if(png_sizeof(png_struct) > png_struct_size)
  186925. {
  186926. png_ptr->error_fn=NULL;
  186927. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186928. png_ptr->flags=0;
  186929. #endif
  186930. png_error(png_ptr,
  186931. "The png struct allocated by the application for reading is too small.");
  186932. }
  186933. if(png_sizeof(png_info) > png_info_size)
  186934. {
  186935. png_ptr->error_fn=NULL;
  186936. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186937. png_ptr->flags=0;
  186938. #endif
  186939. png_error(png_ptr,
  186940. "The info struct allocated by application for reading is too small.");
  186941. }
  186942. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  186943. }
  186944. #endif /* PNG_1_0_X || PNG_1_2_X */
  186945. void PNGAPI
  186946. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  186947. png_size_t png_struct_size)
  186948. {
  186949. #ifdef PNG_SETJMP_SUPPORTED
  186950. jmp_buf tmp_jmp; /* to save current jump buffer */
  186951. #endif
  186952. int i=0;
  186953. png_structp png_ptr=*ptr_ptr;
  186954. if(png_ptr == NULL) return;
  186955. do
  186956. {
  186957. if(user_png_ver[i] != png_libpng_ver[i])
  186958. {
  186959. #ifdef PNG_LEGACY_SUPPORTED
  186960. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186961. #else
  186962. png_ptr->warning_fn=NULL;
  186963. png_warning(png_ptr,
  186964. "Application uses deprecated png_read_init() and should be recompiled.");
  186965. break;
  186966. #endif
  186967. }
  186968. } while (png_libpng_ver[i++]);
  186969. png_debug(1, "in png_read_init_3\n");
  186970. #ifdef PNG_SETJMP_SUPPORTED
  186971. /* save jump buffer and error functions */
  186972. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  186973. #endif
  186974. if(png_sizeof(png_struct) > png_struct_size)
  186975. {
  186976. png_destroy_struct(png_ptr);
  186977. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186978. png_ptr = *ptr_ptr;
  186979. }
  186980. /* reset all variables to 0 */
  186981. png_memset(png_ptr, 0, png_sizeof (png_struct));
  186982. #ifdef PNG_SETJMP_SUPPORTED
  186983. /* restore jump buffer */
  186984. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  186985. #endif
  186986. /* added at libpng-1.2.6 */
  186987. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186988. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186989. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186990. #endif
  186991. /* initialize zbuf - compression buffer */
  186992. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186993. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186994. (png_uint_32)png_ptr->zbuf_size);
  186995. png_ptr->zstream.zalloc = png_zalloc;
  186996. png_ptr->zstream.zfree = png_zfree;
  186997. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186998. switch (inflateInit(&png_ptr->zstream))
  186999. {
  187000. case Z_OK: /* Do nothing */ break;
  187001. case Z_MEM_ERROR:
  187002. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  187003. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  187004. default: png_error(png_ptr, "Unknown zlib error");
  187005. }
  187006. png_ptr->zstream.next_out = png_ptr->zbuf;
  187007. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187008. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187009. }
  187010. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187011. /* Read the information before the actual image data. This has been
  187012. * changed in v0.90 to allow reading a file that already has the magic
  187013. * bytes read from the stream. You can tell libpng how many bytes have
  187014. * been read from the beginning of the stream (up to the maximum of 8)
  187015. * via png_set_sig_bytes(), and we will only check the remaining bytes
  187016. * here. The application can then have access to the signature bytes we
  187017. * read if it is determined that this isn't a valid PNG file.
  187018. */
  187019. void PNGAPI
  187020. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187021. {
  187022. if(png_ptr == NULL) return;
  187023. png_debug(1, "in png_read_info\n");
  187024. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187025. if (png_ptr->sig_bytes < 8)
  187026. {
  187027. png_size_t num_checked = png_ptr->sig_bytes,
  187028. num_to_check = 8 - num_checked;
  187029. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187030. png_ptr->sig_bytes = 8;
  187031. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187032. {
  187033. if (num_checked < 4 &&
  187034. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187035. png_error(png_ptr, "Not a PNG file");
  187036. else
  187037. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187038. }
  187039. if (num_checked < 3)
  187040. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187041. }
  187042. for(;;)
  187043. {
  187044. #ifdef PNG_USE_LOCAL_ARRAYS
  187045. PNG_CONST PNG_IHDR;
  187046. PNG_CONST PNG_IDAT;
  187047. PNG_CONST PNG_IEND;
  187048. PNG_CONST PNG_PLTE;
  187049. #if defined(PNG_READ_bKGD_SUPPORTED)
  187050. PNG_CONST PNG_bKGD;
  187051. #endif
  187052. #if defined(PNG_READ_cHRM_SUPPORTED)
  187053. PNG_CONST PNG_cHRM;
  187054. #endif
  187055. #if defined(PNG_READ_gAMA_SUPPORTED)
  187056. PNG_CONST PNG_gAMA;
  187057. #endif
  187058. #if defined(PNG_READ_hIST_SUPPORTED)
  187059. PNG_CONST PNG_hIST;
  187060. #endif
  187061. #if defined(PNG_READ_iCCP_SUPPORTED)
  187062. PNG_CONST PNG_iCCP;
  187063. #endif
  187064. #if defined(PNG_READ_iTXt_SUPPORTED)
  187065. PNG_CONST PNG_iTXt;
  187066. #endif
  187067. #if defined(PNG_READ_oFFs_SUPPORTED)
  187068. PNG_CONST PNG_oFFs;
  187069. #endif
  187070. #if defined(PNG_READ_pCAL_SUPPORTED)
  187071. PNG_CONST PNG_pCAL;
  187072. #endif
  187073. #if defined(PNG_READ_pHYs_SUPPORTED)
  187074. PNG_CONST PNG_pHYs;
  187075. #endif
  187076. #if defined(PNG_READ_sBIT_SUPPORTED)
  187077. PNG_CONST PNG_sBIT;
  187078. #endif
  187079. #if defined(PNG_READ_sCAL_SUPPORTED)
  187080. PNG_CONST PNG_sCAL;
  187081. #endif
  187082. #if defined(PNG_READ_sPLT_SUPPORTED)
  187083. PNG_CONST PNG_sPLT;
  187084. #endif
  187085. #if defined(PNG_READ_sRGB_SUPPORTED)
  187086. PNG_CONST PNG_sRGB;
  187087. #endif
  187088. #if defined(PNG_READ_tEXt_SUPPORTED)
  187089. PNG_CONST PNG_tEXt;
  187090. #endif
  187091. #if defined(PNG_READ_tIME_SUPPORTED)
  187092. PNG_CONST PNG_tIME;
  187093. #endif
  187094. #if defined(PNG_READ_tRNS_SUPPORTED)
  187095. PNG_CONST PNG_tRNS;
  187096. #endif
  187097. #if defined(PNG_READ_zTXt_SUPPORTED)
  187098. PNG_CONST PNG_zTXt;
  187099. #endif
  187100. #endif /* PNG_USE_LOCAL_ARRAYS */
  187101. png_byte chunk_length[4];
  187102. png_uint_32 length;
  187103. png_read_data(png_ptr, chunk_length, 4);
  187104. length = png_get_uint_31(png_ptr,chunk_length);
  187105. png_reset_crc(png_ptr);
  187106. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187107. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187108. length);
  187109. /* This should be a binary subdivision search or a hash for
  187110. * matching the chunk name rather than a linear search.
  187111. */
  187112. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187113. if(png_ptr->mode & PNG_AFTER_IDAT)
  187114. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187115. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187116. png_handle_IHDR(png_ptr, info_ptr, length);
  187117. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187118. png_handle_IEND(png_ptr, info_ptr, length);
  187119. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187120. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187121. {
  187122. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187123. png_ptr->mode |= PNG_HAVE_IDAT;
  187124. png_handle_unknown(png_ptr, info_ptr, length);
  187125. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187126. png_ptr->mode |= PNG_HAVE_PLTE;
  187127. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187128. {
  187129. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187130. png_error(png_ptr, "Missing IHDR before IDAT");
  187131. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187132. !(png_ptr->mode & PNG_HAVE_PLTE))
  187133. png_error(png_ptr, "Missing PLTE before IDAT");
  187134. break;
  187135. }
  187136. }
  187137. #endif
  187138. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187139. png_handle_PLTE(png_ptr, info_ptr, length);
  187140. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187141. {
  187142. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187143. png_error(png_ptr, "Missing IHDR before IDAT");
  187144. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187145. !(png_ptr->mode & PNG_HAVE_PLTE))
  187146. png_error(png_ptr, "Missing PLTE before IDAT");
  187147. png_ptr->idat_size = length;
  187148. png_ptr->mode |= PNG_HAVE_IDAT;
  187149. break;
  187150. }
  187151. #if defined(PNG_READ_bKGD_SUPPORTED)
  187152. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187153. png_handle_bKGD(png_ptr, info_ptr, length);
  187154. #endif
  187155. #if defined(PNG_READ_cHRM_SUPPORTED)
  187156. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187157. png_handle_cHRM(png_ptr, info_ptr, length);
  187158. #endif
  187159. #if defined(PNG_READ_gAMA_SUPPORTED)
  187160. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187161. png_handle_gAMA(png_ptr, info_ptr, length);
  187162. #endif
  187163. #if defined(PNG_READ_hIST_SUPPORTED)
  187164. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187165. png_handle_hIST(png_ptr, info_ptr, length);
  187166. #endif
  187167. #if defined(PNG_READ_oFFs_SUPPORTED)
  187168. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187169. png_handle_oFFs(png_ptr, info_ptr, length);
  187170. #endif
  187171. #if defined(PNG_READ_pCAL_SUPPORTED)
  187172. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187173. png_handle_pCAL(png_ptr, info_ptr, length);
  187174. #endif
  187175. #if defined(PNG_READ_sCAL_SUPPORTED)
  187176. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187177. png_handle_sCAL(png_ptr, info_ptr, length);
  187178. #endif
  187179. #if defined(PNG_READ_pHYs_SUPPORTED)
  187180. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187181. png_handle_pHYs(png_ptr, info_ptr, length);
  187182. #endif
  187183. #if defined(PNG_READ_sBIT_SUPPORTED)
  187184. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187185. png_handle_sBIT(png_ptr, info_ptr, length);
  187186. #endif
  187187. #if defined(PNG_READ_sRGB_SUPPORTED)
  187188. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187189. png_handle_sRGB(png_ptr, info_ptr, length);
  187190. #endif
  187191. #if defined(PNG_READ_iCCP_SUPPORTED)
  187192. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187193. png_handle_iCCP(png_ptr, info_ptr, length);
  187194. #endif
  187195. #if defined(PNG_READ_sPLT_SUPPORTED)
  187196. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187197. png_handle_sPLT(png_ptr, info_ptr, length);
  187198. #endif
  187199. #if defined(PNG_READ_tEXt_SUPPORTED)
  187200. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187201. png_handle_tEXt(png_ptr, info_ptr, length);
  187202. #endif
  187203. #if defined(PNG_READ_tIME_SUPPORTED)
  187204. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187205. png_handle_tIME(png_ptr, info_ptr, length);
  187206. #endif
  187207. #if defined(PNG_READ_tRNS_SUPPORTED)
  187208. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187209. png_handle_tRNS(png_ptr, info_ptr, length);
  187210. #endif
  187211. #if defined(PNG_READ_zTXt_SUPPORTED)
  187212. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187213. png_handle_zTXt(png_ptr, info_ptr, length);
  187214. #endif
  187215. #if defined(PNG_READ_iTXt_SUPPORTED)
  187216. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187217. png_handle_iTXt(png_ptr, info_ptr, length);
  187218. #endif
  187219. else
  187220. png_handle_unknown(png_ptr, info_ptr, length);
  187221. }
  187222. }
  187223. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187224. /* optional call to update the users info_ptr structure */
  187225. void PNGAPI
  187226. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187227. {
  187228. png_debug(1, "in png_read_update_info\n");
  187229. if(png_ptr == NULL) return;
  187230. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187231. png_read_start_row(png_ptr);
  187232. else
  187233. png_warning(png_ptr,
  187234. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187235. png_read_transform_info(png_ptr, info_ptr);
  187236. }
  187237. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187238. /* Initialize palette, background, etc, after transformations
  187239. * are set, but before any reading takes place. This allows
  187240. * the user to obtain a gamma-corrected palette, for example.
  187241. * If the user doesn't call this, we will do it ourselves.
  187242. */
  187243. void PNGAPI
  187244. png_start_read_image(png_structp png_ptr)
  187245. {
  187246. png_debug(1, "in png_start_read_image\n");
  187247. if(png_ptr == NULL) return;
  187248. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187249. png_read_start_row(png_ptr);
  187250. }
  187251. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187252. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187253. void PNGAPI
  187254. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187255. {
  187256. #ifdef PNG_USE_LOCAL_ARRAYS
  187257. PNG_CONST PNG_IDAT;
  187258. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187259. 0xff};
  187260. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187261. #endif
  187262. int ret;
  187263. if(png_ptr == NULL) return;
  187264. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187265. png_ptr->row_number, png_ptr->pass);
  187266. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187267. png_read_start_row(png_ptr);
  187268. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187269. {
  187270. /* check for transforms that have been set but were defined out */
  187271. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187272. if (png_ptr->transformations & PNG_INVERT_MONO)
  187273. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187274. #endif
  187275. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187276. if (png_ptr->transformations & PNG_FILLER)
  187277. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187278. #endif
  187279. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187280. if (png_ptr->transformations & PNG_PACKSWAP)
  187281. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187282. #endif
  187283. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187284. if (png_ptr->transformations & PNG_PACK)
  187285. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187286. #endif
  187287. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187288. if (png_ptr->transformations & PNG_SHIFT)
  187289. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187290. #endif
  187291. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187292. if (png_ptr->transformations & PNG_BGR)
  187293. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187294. #endif
  187295. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187296. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187297. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187298. #endif
  187299. }
  187300. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187301. /* if interlaced and we do not need a new row, combine row and return */
  187302. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187303. {
  187304. switch (png_ptr->pass)
  187305. {
  187306. case 0:
  187307. if (png_ptr->row_number & 0x07)
  187308. {
  187309. if (dsp_row != NULL)
  187310. png_combine_row(png_ptr, dsp_row,
  187311. png_pass_dsp_mask[png_ptr->pass]);
  187312. png_read_finish_row(png_ptr);
  187313. return;
  187314. }
  187315. break;
  187316. case 1:
  187317. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187318. {
  187319. if (dsp_row != NULL)
  187320. png_combine_row(png_ptr, dsp_row,
  187321. png_pass_dsp_mask[png_ptr->pass]);
  187322. png_read_finish_row(png_ptr);
  187323. return;
  187324. }
  187325. break;
  187326. case 2:
  187327. if ((png_ptr->row_number & 0x07) != 4)
  187328. {
  187329. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187330. png_combine_row(png_ptr, dsp_row,
  187331. png_pass_dsp_mask[png_ptr->pass]);
  187332. png_read_finish_row(png_ptr);
  187333. return;
  187334. }
  187335. break;
  187336. case 3:
  187337. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187338. {
  187339. if (dsp_row != NULL)
  187340. png_combine_row(png_ptr, dsp_row,
  187341. png_pass_dsp_mask[png_ptr->pass]);
  187342. png_read_finish_row(png_ptr);
  187343. return;
  187344. }
  187345. break;
  187346. case 4:
  187347. if ((png_ptr->row_number & 3) != 2)
  187348. {
  187349. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187350. png_combine_row(png_ptr, dsp_row,
  187351. png_pass_dsp_mask[png_ptr->pass]);
  187352. png_read_finish_row(png_ptr);
  187353. return;
  187354. }
  187355. break;
  187356. case 5:
  187357. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187358. {
  187359. if (dsp_row != NULL)
  187360. png_combine_row(png_ptr, dsp_row,
  187361. png_pass_dsp_mask[png_ptr->pass]);
  187362. png_read_finish_row(png_ptr);
  187363. return;
  187364. }
  187365. break;
  187366. case 6:
  187367. if (!(png_ptr->row_number & 1))
  187368. {
  187369. png_read_finish_row(png_ptr);
  187370. return;
  187371. }
  187372. break;
  187373. }
  187374. }
  187375. #endif
  187376. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187377. png_error(png_ptr, "Invalid attempt to read row data");
  187378. png_ptr->zstream.next_out = png_ptr->row_buf;
  187379. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187380. do
  187381. {
  187382. if (!(png_ptr->zstream.avail_in))
  187383. {
  187384. while (!png_ptr->idat_size)
  187385. {
  187386. png_byte chunk_length[4];
  187387. png_crc_finish(png_ptr, 0);
  187388. png_read_data(png_ptr, chunk_length, 4);
  187389. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187390. png_reset_crc(png_ptr);
  187391. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187392. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187393. png_error(png_ptr, "Not enough image data");
  187394. }
  187395. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187396. png_ptr->zstream.next_in = png_ptr->zbuf;
  187397. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187398. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187399. png_crc_read(png_ptr, png_ptr->zbuf,
  187400. (png_size_t)png_ptr->zstream.avail_in);
  187401. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187402. }
  187403. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187404. if (ret == Z_STREAM_END)
  187405. {
  187406. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187407. png_ptr->idat_size)
  187408. png_error(png_ptr, "Extra compressed data");
  187409. png_ptr->mode |= PNG_AFTER_IDAT;
  187410. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187411. break;
  187412. }
  187413. if (ret != Z_OK)
  187414. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187415. "Decompression error");
  187416. } while (png_ptr->zstream.avail_out);
  187417. png_ptr->row_info.color_type = png_ptr->color_type;
  187418. png_ptr->row_info.width = png_ptr->iwidth;
  187419. png_ptr->row_info.channels = png_ptr->channels;
  187420. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187421. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187422. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187423. png_ptr->row_info.width);
  187424. if(png_ptr->row_buf[0])
  187425. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187426. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187427. (int)(png_ptr->row_buf[0]));
  187428. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187429. png_ptr->rowbytes + 1);
  187430. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187431. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187432. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187433. {
  187434. /* Intrapixel differencing */
  187435. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187436. }
  187437. #endif
  187438. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187439. png_do_read_transformations(png_ptr);
  187440. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187441. /* blow up interlaced rows to full size */
  187442. if (png_ptr->interlaced &&
  187443. (png_ptr->transformations & PNG_INTERLACE))
  187444. {
  187445. if (png_ptr->pass < 6)
  187446. /* old interface (pre-1.0.9):
  187447. png_do_read_interlace(&(png_ptr->row_info),
  187448. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187449. */
  187450. png_do_read_interlace(png_ptr);
  187451. if (dsp_row != NULL)
  187452. png_combine_row(png_ptr, dsp_row,
  187453. png_pass_dsp_mask[png_ptr->pass]);
  187454. if (row != NULL)
  187455. png_combine_row(png_ptr, row,
  187456. png_pass_mask[png_ptr->pass]);
  187457. }
  187458. else
  187459. #endif
  187460. {
  187461. if (row != NULL)
  187462. png_combine_row(png_ptr, row, 0xff);
  187463. if (dsp_row != NULL)
  187464. png_combine_row(png_ptr, dsp_row, 0xff);
  187465. }
  187466. png_read_finish_row(png_ptr);
  187467. if (png_ptr->read_row_fn != NULL)
  187468. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187469. }
  187470. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187471. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187472. /* Read one or more rows of image data. If the image is interlaced,
  187473. * and png_set_interlace_handling() has been called, the rows need to
  187474. * contain the contents of the rows from the previous pass. If the
  187475. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187476. * called, the rows contents must be initialized to the contents of the
  187477. * screen.
  187478. *
  187479. * "row" holds the actual image, and pixels are placed in it
  187480. * as they arrive. If the image is displayed after each pass, it will
  187481. * appear to "sparkle" in. "display_row" can be used to display a
  187482. * "chunky" progressive image, with finer detail added as it becomes
  187483. * available. If you do not want this "chunky" display, you may pass
  187484. * NULL for display_row. If you do not want the sparkle display, and
  187485. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187486. * If you have called png_handle_alpha(), and the image has either an
  187487. * alpha channel or a transparency chunk, you must provide a buffer for
  187488. * rows. In this case, you do not have to provide a display_row buffer
  187489. * also, but you may. If the image is not interlaced, or if you have
  187490. * not called png_set_interlace_handling(), the display_row buffer will
  187491. * be ignored, so pass NULL to it.
  187492. *
  187493. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187494. */
  187495. void PNGAPI
  187496. png_read_rows(png_structp png_ptr, png_bytepp row,
  187497. png_bytepp display_row, png_uint_32 num_rows)
  187498. {
  187499. png_uint_32 i;
  187500. png_bytepp rp;
  187501. png_bytepp dp;
  187502. png_debug(1, "in png_read_rows\n");
  187503. if(png_ptr == NULL) return;
  187504. rp = row;
  187505. dp = display_row;
  187506. if (rp != NULL && dp != NULL)
  187507. for (i = 0; i < num_rows; i++)
  187508. {
  187509. png_bytep rptr = *rp++;
  187510. png_bytep dptr = *dp++;
  187511. png_read_row(png_ptr, rptr, dptr);
  187512. }
  187513. else if(rp != NULL)
  187514. for (i = 0; i < num_rows; i++)
  187515. {
  187516. png_bytep rptr = *rp;
  187517. png_read_row(png_ptr, rptr, png_bytep_NULL);
  187518. rp++;
  187519. }
  187520. else if(dp != NULL)
  187521. for (i = 0; i < num_rows; i++)
  187522. {
  187523. png_bytep dptr = *dp;
  187524. png_read_row(png_ptr, png_bytep_NULL, dptr);
  187525. dp++;
  187526. }
  187527. }
  187528. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187529. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187530. /* Read the entire image. If the image has an alpha channel or a tRNS
  187531. * chunk, and you have called png_handle_alpha()[*], you will need to
  187532. * initialize the image to the current image that PNG will be overlaying.
  187533. * We set the num_rows again here, in case it was incorrectly set in
  187534. * png_read_start_row() by a call to png_read_update_info() or
  187535. * png_start_read_image() if png_set_interlace_handling() wasn't called
  187536. * prior to either of these functions like it should have been. You can
  187537. * only call this function once. If you desire to have an image for
  187538. * each pass of a interlaced image, use png_read_rows() instead.
  187539. *
  187540. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187541. */
  187542. void PNGAPI
  187543. png_read_image(png_structp png_ptr, png_bytepp image)
  187544. {
  187545. png_uint_32 i,image_height;
  187546. int pass, j;
  187547. png_bytepp rp;
  187548. png_debug(1, "in png_read_image\n");
  187549. if(png_ptr == NULL) return;
  187550. #ifdef PNG_READ_INTERLACING_SUPPORTED
  187551. pass = png_set_interlace_handling(png_ptr);
  187552. #else
  187553. if (png_ptr->interlaced)
  187554. png_error(png_ptr,
  187555. "Cannot read interlaced image -- interlace handler disabled.");
  187556. pass = 1;
  187557. #endif
  187558. image_height=png_ptr->height;
  187559. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  187560. for (j = 0; j < pass; j++)
  187561. {
  187562. rp = image;
  187563. for (i = 0; i < image_height; i++)
  187564. {
  187565. png_read_row(png_ptr, *rp, png_bytep_NULL);
  187566. rp++;
  187567. }
  187568. }
  187569. }
  187570. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187571. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187572. /* Read the end of the PNG file. Will not read past the end of the
  187573. * file, will verify the end is accurate, and will read any comments
  187574. * or time information at the end of the file, if info is not NULL.
  187575. */
  187576. void PNGAPI
  187577. png_read_end(png_structp png_ptr, png_infop info_ptr)
  187578. {
  187579. png_byte chunk_length[4];
  187580. png_uint_32 length;
  187581. png_debug(1, "in png_read_end\n");
  187582. if(png_ptr == NULL) return;
  187583. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  187584. do
  187585. {
  187586. #ifdef PNG_USE_LOCAL_ARRAYS
  187587. PNG_CONST PNG_IHDR;
  187588. PNG_CONST PNG_IDAT;
  187589. PNG_CONST PNG_IEND;
  187590. PNG_CONST PNG_PLTE;
  187591. #if defined(PNG_READ_bKGD_SUPPORTED)
  187592. PNG_CONST PNG_bKGD;
  187593. #endif
  187594. #if defined(PNG_READ_cHRM_SUPPORTED)
  187595. PNG_CONST PNG_cHRM;
  187596. #endif
  187597. #if defined(PNG_READ_gAMA_SUPPORTED)
  187598. PNG_CONST PNG_gAMA;
  187599. #endif
  187600. #if defined(PNG_READ_hIST_SUPPORTED)
  187601. PNG_CONST PNG_hIST;
  187602. #endif
  187603. #if defined(PNG_READ_iCCP_SUPPORTED)
  187604. PNG_CONST PNG_iCCP;
  187605. #endif
  187606. #if defined(PNG_READ_iTXt_SUPPORTED)
  187607. PNG_CONST PNG_iTXt;
  187608. #endif
  187609. #if defined(PNG_READ_oFFs_SUPPORTED)
  187610. PNG_CONST PNG_oFFs;
  187611. #endif
  187612. #if defined(PNG_READ_pCAL_SUPPORTED)
  187613. PNG_CONST PNG_pCAL;
  187614. #endif
  187615. #if defined(PNG_READ_pHYs_SUPPORTED)
  187616. PNG_CONST PNG_pHYs;
  187617. #endif
  187618. #if defined(PNG_READ_sBIT_SUPPORTED)
  187619. PNG_CONST PNG_sBIT;
  187620. #endif
  187621. #if defined(PNG_READ_sCAL_SUPPORTED)
  187622. PNG_CONST PNG_sCAL;
  187623. #endif
  187624. #if defined(PNG_READ_sPLT_SUPPORTED)
  187625. PNG_CONST PNG_sPLT;
  187626. #endif
  187627. #if defined(PNG_READ_sRGB_SUPPORTED)
  187628. PNG_CONST PNG_sRGB;
  187629. #endif
  187630. #if defined(PNG_READ_tEXt_SUPPORTED)
  187631. PNG_CONST PNG_tEXt;
  187632. #endif
  187633. #if defined(PNG_READ_tIME_SUPPORTED)
  187634. PNG_CONST PNG_tIME;
  187635. #endif
  187636. #if defined(PNG_READ_tRNS_SUPPORTED)
  187637. PNG_CONST PNG_tRNS;
  187638. #endif
  187639. #if defined(PNG_READ_zTXt_SUPPORTED)
  187640. PNG_CONST PNG_zTXt;
  187641. #endif
  187642. #endif /* PNG_USE_LOCAL_ARRAYS */
  187643. png_read_data(png_ptr, chunk_length, 4);
  187644. length = png_get_uint_31(png_ptr,chunk_length);
  187645. png_reset_crc(png_ptr);
  187646. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187647. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  187648. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187649. png_handle_IHDR(png_ptr, info_ptr, length);
  187650. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187651. png_handle_IEND(png_ptr, info_ptr, length);
  187652. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187653. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187654. {
  187655. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187656. {
  187657. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187658. png_error(png_ptr, "Too many IDAT's found");
  187659. }
  187660. png_handle_unknown(png_ptr, info_ptr, length);
  187661. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187662. png_ptr->mode |= PNG_HAVE_PLTE;
  187663. }
  187664. #endif
  187665. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187666. {
  187667. /* Zero length IDATs are legal after the last IDAT has been
  187668. * read, but not after other chunks have been read.
  187669. */
  187670. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187671. png_error(png_ptr, "Too many IDAT's found");
  187672. png_crc_finish(png_ptr, length);
  187673. }
  187674. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187675. png_handle_PLTE(png_ptr, info_ptr, length);
  187676. #if defined(PNG_READ_bKGD_SUPPORTED)
  187677. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187678. png_handle_bKGD(png_ptr, info_ptr, length);
  187679. #endif
  187680. #if defined(PNG_READ_cHRM_SUPPORTED)
  187681. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187682. png_handle_cHRM(png_ptr, info_ptr, length);
  187683. #endif
  187684. #if defined(PNG_READ_gAMA_SUPPORTED)
  187685. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187686. png_handle_gAMA(png_ptr, info_ptr, length);
  187687. #endif
  187688. #if defined(PNG_READ_hIST_SUPPORTED)
  187689. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187690. png_handle_hIST(png_ptr, info_ptr, length);
  187691. #endif
  187692. #if defined(PNG_READ_oFFs_SUPPORTED)
  187693. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187694. png_handle_oFFs(png_ptr, info_ptr, length);
  187695. #endif
  187696. #if defined(PNG_READ_pCAL_SUPPORTED)
  187697. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187698. png_handle_pCAL(png_ptr, info_ptr, length);
  187699. #endif
  187700. #if defined(PNG_READ_sCAL_SUPPORTED)
  187701. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187702. png_handle_sCAL(png_ptr, info_ptr, length);
  187703. #endif
  187704. #if defined(PNG_READ_pHYs_SUPPORTED)
  187705. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187706. png_handle_pHYs(png_ptr, info_ptr, length);
  187707. #endif
  187708. #if defined(PNG_READ_sBIT_SUPPORTED)
  187709. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187710. png_handle_sBIT(png_ptr, info_ptr, length);
  187711. #endif
  187712. #if defined(PNG_READ_sRGB_SUPPORTED)
  187713. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187714. png_handle_sRGB(png_ptr, info_ptr, length);
  187715. #endif
  187716. #if defined(PNG_READ_iCCP_SUPPORTED)
  187717. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187718. png_handle_iCCP(png_ptr, info_ptr, length);
  187719. #endif
  187720. #if defined(PNG_READ_sPLT_SUPPORTED)
  187721. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187722. png_handle_sPLT(png_ptr, info_ptr, length);
  187723. #endif
  187724. #if defined(PNG_READ_tEXt_SUPPORTED)
  187725. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187726. png_handle_tEXt(png_ptr, info_ptr, length);
  187727. #endif
  187728. #if defined(PNG_READ_tIME_SUPPORTED)
  187729. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187730. png_handle_tIME(png_ptr, info_ptr, length);
  187731. #endif
  187732. #if defined(PNG_READ_tRNS_SUPPORTED)
  187733. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187734. png_handle_tRNS(png_ptr, info_ptr, length);
  187735. #endif
  187736. #if defined(PNG_READ_zTXt_SUPPORTED)
  187737. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187738. png_handle_zTXt(png_ptr, info_ptr, length);
  187739. #endif
  187740. #if defined(PNG_READ_iTXt_SUPPORTED)
  187741. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187742. png_handle_iTXt(png_ptr, info_ptr, length);
  187743. #endif
  187744. else
  187745. png_handle_unknown(png_ptr, info_ptr, length);
  187746. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  187747. }
  187748. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187749. /* free all memory used by the read */
  187750. void PNGAPI
  187751. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  187752. png_infopp end_info_ptr_ptr)
  187753. {
  187754. png_structp png_ptr = NULL;
  187755. png_infop info_ptr = NULL, end_info_ptr = NULL;
  187756. #ifdef PNG_USER_MEM_SUPPORTED
  187757. png_free_ptr free_fn;
  187758. png_voidp mem_ptr;
  187759. #endif
  187760. png_debug(1, "in png_destroy_read_struct\n");
  187761. if (png_ptr_ptr != NULL)
  187762. png_ptr = *png_ptr_ptr;
  187763. if (info_ptr_ptr != NULL)
  187764. info_ptr = *info_ptr_ptr;
  187765. if (end_info_ptr_ptr != NULL)
  187766. end_info_ptr = *end_info_ptr_ptr;
  187767. #ifdef PNG_USER_MEM_SUPPORTED
  187768. free_fn = png_ptr->free_fn;
  187769. mem_ptr = png_ptr->mem_ptr;
  187770. #endif
  187771. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  187772. if (info_ptr != NULL)
  187773. {
  187774. #if defined(PNG_TEXT_SUPPORTED)
  187775. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  187776. #endif
  187777. #ifdef PNG_USER_MEM_SUPPORTED
  187778. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  187779. (png_voidp)mem_ptr);
  187780. #else
  187781. png_destroy_struct((png_voidp)info_ptr);
  187782. #endif
  187783. *info_ptr_ptr = NULL;
  187784. }
  187785. if (end_info_ptr != NULL)
  187786. {
  187787. #if defined(PNG_READ_TEXT_SUPPORTED)
  187788. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  187789. #endif
  187790. #ifdef PNG_USER_MEM_SUPPORTED
  187791. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  187792. (png_voidp)mem_ptr);
  187793. #else
  187794. png_destroy_struct((png_voidp)end_info_ptr);
  187795. #endif
  187796. *end_info_ptr_ptr = NULL;
  187797. }
  187798. if (png_ptr != NULL)
  187799. {
  187800. #ifdef PNG_USER_MEM_SUPPORTED
  187801. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  187802. (png_voidp)mem_ptr);
  187803. #else
  187804. png_destroy_struct((png_voidp)png_ptr);
  187805. #endif
  187806. *png_ptr_ptr = NULL;
  187807. }
  187808. }
  187809. /* free all memory used by the read (old method) */
  187810. void /* PRIVATE */
  187811. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  187812. {
  187813. #ifdef PNG_SETJMP_SUPPORTED
  187814. jmp_buf tmp_jmp;
  187815. #endif
  187816. png_error_ptr error_fn;
  187817. png_error_ptr warning_fn;
  187818. png_voidp error_ptr;
  187819. #ifdef PNG_USER_MEM_SUPPORTED
  187820. png_free_ptr free_fn;
  187821. #endif
  187822. png_debug(1, "in png_read_destroy\n");
  187823. if (info_ptr != NULL)
  187824. png_info_destroy(png_ptr, info_ptr);
  187825. if (end_info_ptr != NULL)
  187826. png_info_destroy(png_ptr, end_info_ptr);
  187827. png_free(png_ptr, png_ptr->zbuf);
  187828. png_free(png_ptr, png_ptr->big_row_buf);
  187829. png_free(png_ptr, png_ptr->prev_row);
  187830. #if defined(PNG_READ_DITHER_SUPPORTED)
  187831. png_free(png_ptr, png_ptr->palette_lookup);
  187832. png_free(png_ptr, png_ptr->dither_index);
  187833. #endif
  187834. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187835. png_free(png_ptr, png_ptr->gamma_table);
  187836. #endif
  187837. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187838. png_free(png_ptr, png_ptr->gamma_from_1);
  187839. png_free(png_ptr, png_ptr->gamma_to_1);
  187840. #endif
  187841. #ifdef PNG_FREE_ME_SUPPORTED
  187842. if (png_ptr->free_me & PNG_FREE_PLTE)
  187843. png_zfree(png_ptr, png_ptr->palette);
  187844. png_ptr->free_me &= ~PNG_FREE_PLTE;
  187845. #else
  187846. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  187847. png_zfree(png_ptr, png_ptr->palette);
  187848. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  187849. #endif
  187850. #if defined(PNG_tRNS_SUPPORTED) || \
  187851. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187852. #ifdef PNG_FREE_ME_SUPPORTED
  187853. if (png_ptr->free_me & PNG_FREE_TRNS)
  187854. png_free(png_ptr, png_ptr->trans);
  187855. png_ptr->free_me &= ~PNG_FREE_TRNS;
  187856. #else
  187857. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  187858. png_free(png_ptr, png_ptr->trans);
  187859. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  187860. #endif
  187861. #endif
  187862. #if defined(PNG_READ_hIST_SUPPORTED)
  187863. #ifdef PNG_FREE_ME_SUPPORTED
  187864. if (png_ptr->free_me & PNG_FREE_HIST)
  187865. png_free(png_ptr, png_ptr->hist);
  187866. png_ptr->free_me &= ~PNG_FREE_HIST;
  187867. #else
  187868. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  187869. png_free(png_ptr, png_ptr->hist);
  187870. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  187871. #endif
  187872. #endif
  187873. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187874. if (png_ptr->gamma_16_table != NULL)
  187875. {
  187876. int i;
  187877. int istop = (1 << (8 - png_ptr->gamma_shift));
  187878. for (i = 0; i < istop; i++)
  187879. {
  187880. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  187881. }
  187882. png_free(png_ptr, png_ptr->gamma_16_table);
  187883. }
  187884. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187885. if (png_ptr->gamma_16_from_1 != NULL)
  187886. {
  187887. int i;
  187888. int istop = (1 << (8 - png_ptr->gamma_shift));
  187889. for (i = 0; i < istop; i++)
  187890. {
  187891. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  187892. }
  187893. png_free(png_ptr, png_ptr->gamma_16_from_1);
  187894. }
  187895. if (png_ptr->gamma_16_to_1 != NULL)
  187896. {
  187897. int i;
  187898. int istop = (1 << (8 - png_ptr->gamma_shift));
  187899. for (i = 0; i < istop; i++)
  187900. {
  187901. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  187902. }
  187903. png_free(png_ptr, png_ptr->gamma_16_to_1);
  187904. }
  187905. #endif
  187906. #endif
  187907. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  187908. png_free(png_ptr, png_ptr->time_buffer);
  187909. #endif
  187910. inflateEnd(&png_ptr->zstream);
  187911. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187912. png_free(png_ptr, png_ptr->save_buffer);
  187913. #endif
  187914. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187915. #ifdef PNG_TEXT_SUPPORTED
  187916. png_free(png_ptr, png_ptr->current_text);
  187917. #endif /* PNG_TEXT_SUPPORTED */
  187918. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  187919. /* Save the important info out of the png_struct, in case it is
  187920. * being used again.
  187921. */
  187922. #ifdef PNG_SETJMP_SUPPORTED
  187923. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187924. #endif
  187925. error_fn = png_ptr->error_fn;
  187926. warning_fn = png_ptr->warning_fn;
  187927. error_ptr = png_ptr->error_ptr;
  187928. #ifdef PNG_USER_MEM_SUPPORTED
  187929. free_fn = png_ptr->free_fn;
  187930. #endif
  187931. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187932. png_ptr->error_fn = error_fn;
  187933. png_ptr->warning_fn = warning_fn;
  187934. png_ptr->error_ptr = error_ptr;
  187935. #ifdef PNG_USER_MEM_SUPPORTED
  187936. png_ptr->free_fn = free_fn;
  187937. #endif
  187938. #ifdef PNG_SETJMP_SUPPORTED
  187939. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187940. #endif
  187941. }
  187942. void PNGAPI
  187943. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  187944. {
  187945. if(png_ptr == NULL) return;
  187946. png_ptr->read_row_fn = read_row_fn;
  187947. }
  187948. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187949. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  187950. void PNGAPI
  187951. png_read_png(png_structp png_ptr, png_infop info_ptr,
  187952. int transforms,
  187953. voidp params)
  187954. {
  187955. int row;
  187956. if(png_ptr == NULL) return;
  187957. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  187958. /* invert the alpha channel from opacity to transparency
  187959. */
  187960. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  187961. png_set_invert_alpha(png_ptr);
  187962. #endif
  187963. /* png_read_info() gives us all of the information from the
  187964. * PNG file before the first IDAT (image data chunk).
  187965. */
  187966. png_read_info(png_ptr, info_ptr);
  187967. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  187968. png_error(png_ptr,"Image is too high to process with png_read_png()");
  187969. /* -------------- image transformations start here ------------------- */
  187970. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187971. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  187972. */
  187973. if (transforms & PNG_TRANSFORM_STRIP_16)
  187974. png_set_strip_16(png_ptr);
  187975. #endif
  187976. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  187977. /* Strip alpha bytes from the input data without combining with
  187978. * the background (not recommended).
  187979. */
  187980. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  187981. png_set_strip_alpha(png_ptr);
  187982. #endif
  187983. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  187984. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  187985. * byte into separate bytes (useful for paletted and grayscale images).
  187986. */
  187987. if (transforms & PNG_TRANSFORM_PACKING)
  187988. png_set_packing(png_ptr);
  187989. #endif
  187990. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  187991. /* Change the order of packed pixels to least significant bit first
  187992. * (not useful if you are using png_set_packing).
  187993. */
  187994. if (transforms & PNG_TRANSFORM_PACKSWAP)
  187995. png_set_packswap(png_ptr);
  187996. #endif
  187997. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187998. /* Expand paletted colors into true RGB triplets
  187999. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  188000. * Expand paletted or RGB images with transparency to full alpha
  188001. * channels so the data will be available as RGBA quartets.
  188002. */
  188003. if (transforms & PNG_TRANSFORM_EXPAND)
  188004. if ((png_ptr->bit_depth < 8) ||
  188005. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  188006. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  188007. png_set_expand(png_ptr);
  188008. #endif
  188009. /* We don't handle background color or gamma transformation or dithering.
  188010. */
  188011. #if defined(PNG_READ_INVERT_SUPPORTED)
  188012. /* invert monochrome files to have 0 as white and 1 as black
  188013. */
  188014. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  188015. png_set_invert_mono(png_ptr);
  188016. #endif
  188017. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188018. /* If you want to shift the pixel values from the range [0,255] or
  188019. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188020. * colors were originally in:
  188021. */
  188022. if ((transforms & PNG_TRANSFORM_SHIFT)
  188023. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188024. {
  188025. png_color_8p sig_bit;
  188026. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188027. png_set_shift(png_ptr, sig_bit);
  188028. }
  188029. #endif
  188030. #if defined(PNG_READ_BGR_SUPPORTED)
  188031. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188032. */
  188033. if (transforms & PNG_TRANSFORM_BGR)
  188034. png_set_bgr(png_ptr);
  188035. #endif
  188036. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188037. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188038. */
  188039. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188040. png_set_swap_alpha(png_ptr);
  188041. #endif
  188042. #if defined(PNG_READ_SWAP_SUPPORTED)
  188043. /* swap bytes of 16 bit files to least significant byte first
  188044. */
  188045. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188046. png_set_swap(png_ptr);
  188047. #endif
  188048. /* We don't handle adding filler bytes */
  188049. /* Optional call to gamma correct and add the background to the palette
  188050. * and update info structure. REQUIRED if you are expecting libpng to
  188051. * update the palette for you (i.e., you selected such a transform above).
  188052. */
  188053. png_read_update_info(png_ptr, info_ptr);
  188054. /* -------------- image transformations end here ------------------- */
  188055. #ifdef PNG_FREE_ME_SUPPORTED
  188056. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188057. #endif
  188058. if(info_ptr->row_pointers == NULL)
  188059. {
  188060. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188061. info_ptr->height * png_sizeof(png_bytep));
  188062. #ifdef PNG_FREE_ME_SUPPORTED
  188063. info_ptr->free_me |= PNG_FREE_ROWS;
  188064. #endif
  188065. for (row = 0; row < (int)info_ptr->height; row++)
  188066. {
  188067. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188068. png_get_rowbytes(png_ptr, info_ptr));
  188069. }
  188070. }
  188071. png_read_image(png_ptr, info_ptr->row_pointers);
  188072. info_ptr->valid |= PNG_INFO_IDAT;
  188073. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188074. png_read_end(png_ptr, info_ptr);
  188075. transforms = transforms; /* quiet compiler warnings */
  188076. params = params;
  188077. }
  188078. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188079. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188080. #endif /* PNG_READ_SUPPORTED */
  188081. /*** End of inlined file: pngread.c ***/
  188082. /*** Start of inlined file: pngpread.c ***/
  188083. /* pngpread.c - read a png file in push mode
  188084. *
  188085. * Last changed in libpng 1.2.21 October 4, 2007
  188086. * For conditions of distribution and use, see copyright notice in png.h
  188087. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188088. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188089. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188090. */
  188091. #define PNG_INTERNAL
  188092. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188093. /* push model modes */
  188094. #define PNG_READ_SIG_MODE 0
  188095. #define PNG_READ_CHUNK_MODE 1
  188096. #define PNG_READ_IDAT_MODE 2
  188097. #define PNG_SKIP_MODE 3
  188098. #define PNG_READ_tEXt_MODE 4
  188099. #define PNG_READ_zTXt_MODE 5
  188100. #define PNG_READ_DONE_MODE 6
  188101. #define PNG_READ_iTXt_MODE 7
  188102. #define PNG_ERROR_MODE 8
  188103. void PNGAPI
  188104. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188105. png_bytep buffer, png_size_t buffer_size)
  188106. {
  188107. if(png_ptr == NULL) return;
  188108. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188109. while (png_ptr->buffer_size)
  188110. {
  188111. png_process_some_data(png_ptr, info_ptr);
  188112. }
  188113. }
  188114. /* What we do with the incoming data depends on what we were previously
  188115. * doing before we ran out of data...
  188116. */
  188117. void /* PRIVATE */
  188118. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188119. {
  188120. if(png_ptr == NULL) return;
  188121. switch (png_ptr->process_mode)
  188122. {
  188123. case PNG_READ_SIG_MODE:
  188124. {
  188125. png_push_read_sig(png_ptr, info_ptr);
  188126. break;
  188127. }
  188128. case PNG_READ_CHUNK_MODE:
  188129. {
  188130. png_push_read_chunk(png_ptr, info_ptr);
  188131. break;
  188132. }
  188133. case PNG_READ_IDAT_MODE:
  188134. {
  188135. png_push_read_IDAT(png_ptr);
  188136. break;
  188137. }
  188138. #if defined(PNG_READ_tEXt_SUPPORTED)
  188139. case PNG_READ_tEXt_MODE:
  188140. {
  188141. png_push_read_tEXt(png_ptr, info_ptr);
  188142. break;
  188143. }
  188144. #endif
  188145. #if defined(PNG_READ_zTXt_SUPPORTED)
  188146. case PNG_READ_zTXt_MODE:
  188147. {
  188148. png_push_read_zTXt(png_ptr, info_ptr);
  188149. break;
  188150. }
  188151. #endif
  188152. #if defined(PNG_READ_iTXt_SUPPORTED)
  188153. case PNG_READ_iTXt_MODE:
  188154. {
  188155. png_push_read_iTXt(png_ptr, info_ptr);
  188156. break;
  188157. }
  188158. #endif
  188159. case PNG_SKIP_MODE:
  188160. {
  188161. png_push_crc_finish(png_ptr);
  188162. break;
  188163. }
  188164. default:
  188165. {
  188166. png_ptr->buffer_size = 0;
  188167. break;
  188168. }
  188169. }
  188170. }
  188171. /* Read any remaining signature bytes from the stream and compare them with
  188172. * the correct PNG signature. It is possible that this routine is called
  188173. * with bytes already read from the signature, either because they have been
  188174. * checked by the calling application, or because of multiple calls to this
  188175. * routine.
  188176. */
  188177. void /* PRIVATE */
  188178. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188179. {
  188180. png_size_t num_checked = png_ptr->sig_bytes,
  188181. num_to_check = 8 - num_checked;
  188182. if (png_ptr->buffer_size < num_to_check)
  188183. {
  188184. num_to_check = png_ptr->buffer_size;
  188185. }
  188186. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188187. num_to_check);
  188188. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188189. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188190. {
  188191. if (num_checked < 4 &&
  188192. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188193. png_error(png_ptr, "Not a PNG file");
  188194. else
  188195. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188196. }
  188197. else
  188198. {
  188199. if (png_ptr->sig_bytes >= 8)
  188200. {
  188201. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188202. }
  188203. }
  188204. }
  188205. void /* PRIVATE */
  188206. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188207. {
  188208. #ifdef PNG_USE_LOCAL_ARRAYS
  188209. PNG_CONST PNG_IHDR;
  188210. PNG_CONST PNG_IDAT;
  188211. PNG_CONST PNG_IEND;
  188212. PNG_CONST PNG_PLTE;
  188213. #if defined(PNG_READ_bKGD_SUPPORTED)
  188214. PNG_CONST PNG_bKGD;
  188215. #endif
  188216. #if defined(PNG_READ_cHRM_SUPPORTED)
  188217. PNG_CONST PNG_cHRM;
  188218. #endif
  188219. #if defined(PNG_READ_gAMA_SUPPORTED)
  188220. PNG_CONST PNG_gAMA;
  188221. #endif
  188222. #if defined(PNG_READ_hIST_SUPPORTED)
  188223. PNG_CONST PNG_hIST;
  188224. #endif
  188225. #if defined(PNG_READ_iCCP_SUPPORTED)
  188226. PNG_CONST PNG_iCCP;
  188227. #endif
  188228. #if defined(PNG_READ_iTXt_SUPPORTED)
  188229. PNG_CONST PNG_iTXt;
  188230. #endif
  188231. #if defined(PNG_READ_oFFs_SUPPORTED)
  188232. PNG_CONST PNG_oFFs;
  188233. #endif
  188234. #if defined(PNG_READ_pCAL_SUPPORTED)
  188235. PNG_CONST PNG_pCAL;
  188236. #endif
  188237. #if defined(PNG_READ_pHYs_SUPPORTED)
  188238. PNG_CONST PNG_pHYs;
  188239. #endif
  188240. #if defined(PNG_READ_sBIT_SUPPORTED)
  188241. PNG_CONST PNG_sBIT;
  188242. #endif
  188243. #if defined(PNG_READ_sCAL_SUPPORTED)
  188244. PNG_CONST PNG_sCAL;
  188245. #endif
  188246. #if defined(PNG_READ_sRGB_SUPPORTED)
  188247. PNG_CONST PNG_sRGB;
  188248. #endif
  188249. #if defined(PNG_READ_sPLT_SUPPORTED)
  188250. PNG_CONST PNG_sPLT;
  188251. #endif
  188252. #if defined(PNG_READ_tEXt_SUPPORTED)
  188253. PNG_CONST PNG_tEXt;
  188254. #endif
  188255. #if defined(PNG_READ_tIME_SUPPORTED)
  188256. PNG_CONST PNG_tIME;
  188257. #endif
  188258. #if defined(PNG_READ_tRNS_SUPPORTED)
  188259. PNG_CONST PNG_tRNS;
  188260. #endif
  188261. #if defined(PNG_READ_zTXt_SUPPORTED)
  188262. PNG_CONST PNG_zTXt;
  188263. #endif
  188264. #endif /* PNG_USE_LOCAL_ARRAYS */
  188265. /* First we make sure we have enough data for the 4 byte chunk name
  188266. * and the 4 byte chunk length before proceeding with decoding the
  188267. * chunk data. To fully decode each of these chunks, we also make
  188268. * sure we have enough data in the buffer for the 4 byte CRC at the
  188269. * end of every chunk (except IDAT, which is handled separately).
  188270. */
  188271. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188272. {
  188273. png_byte chunk_length[4];
  188274. if (png_ptr->buffer_size < 8)
  188275. {
  188276. png_push_save_buffer(png_ptr);
  188277. return;
  188278. }
  188279. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188280. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188281. png_reset_crc(png_ptr);
  188282. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188283. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188284. }
  188285. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188286. if(png_ptr->mode & PNG_AFTER_IDAT)
  188287. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188288. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188289. {
  188290. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188291. {
  188292. png_push_save_buffer(png_ptr);
  188293. return;
  188294. }
  188295. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188296. }
  188297. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188298. {
  188299. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188300. {
  188301. png_push_save_buffer(png_ptr);
  188302. return;
  188303. }
  188304. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188305. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188306. png_push_have_end(png_ptr, info_ptr);
  188307. }
  188308. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188309. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188310. {
  188311. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188312. {
  188313. png_push_save_buffer(png_ptr);
  188314. return;
  188315. }
  188316. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188317. png_ptr->mode |= PNG_HAVE_IDAT;
  188318. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188319. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188320. png_ptr->mode |= PNG_HAVE_PLTE;
  188321. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188322. {
  188323. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188324. png_error(png_ptr, "Missing IHDR before IDAT");
  188325. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188326. !(png_ptr->mode & PNG_HAVE_PLTE))
  188327. png_error(png_ptr, "Missing PLTE before IDAT");
  188328. }
  188329. }
  188330. #endif
  188331. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188332. {
  188333. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188334. {
  188335. png_push_save_buffer(png_ptr);
  188336. return;
  188337. }
  188338. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188339. }
  188340. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188341. {
  188342. /* If we reach an IDAT chunk, this means we have read all of the
  188343. * header chunks, and we can start reading the image (or if this
  188344. * is called after the image has been read - we have an error).
  188345. */
  188346. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188347. png_error(png_ptr, "Missing IHDR before IDAT");
  188348. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188349. !(png_ptr->mode & PNG_HAVE_PLTE))
  188350. png_error(png_ptr, "Missing PLTE before IDAT");
  188351. if (png_ptr->mode & PNG_HAVE_IDAT)
  188352. {
  188353. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188354. if (png_ptr->push_length == 0)
  188355. return;
  188356. if (png_ptr->mode & PNG_AFTER_IDAT)
  188357. png_error(png_ptr, "Too many IDAT's found");
  188358. }
  188359. png_ptr->idat_size = png_ptr->push_length;
  188360. png_ptr->mode |= PNG_HAVE_IDAT;
  188361. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188362. png_push_have_info(png_ptr, info_ptr);
  188363. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188364. png_ptr->zstream.next_out = png_ptr->row_buf;
  188365. return;
  188366. }
  188367. #if defined(PNG_READ_gAMA_SUPPORTED)
  188368. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188369. {
  188370. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188371. {
  188372. png_push_save_buffer(png_ptr);
  188373. return;
  188374. }
  188375. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188376. }
  188377. #endif
  188378. #if defined(PNG_READ_sBIT_SUPPORTED)
  188379. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188380. {
  188381. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188382. {
  188383. png_push_save_buffer(png_ptr);
  188384. return;
  188385. }
  188386. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188387. }
  188388. #endif
  188389. #if defined(PNG_READ_cHRM_SUPPORTED)
  188390. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188391. {
  188392. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188393. {
  188394. png_push_save_buffer(png_ptr);
  188395. return;
  188396. }
  188397. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188398. }
  188399. #endif
  188400. #if defined(PNG_READ_sRGB_SUPPORTED)
  188401. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 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_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188409. }
  188410. #endif
  188411. #if defined(PNG_READ_iCCP_SUPPORTED)
  188412. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188413. {
  188414. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188415. {
  188416. png_push_save_buffer(png_ptr);
  188417. return;
  188418. }
  188419. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188420. }
  188421. #endif
  188422. #if defined(PNG_READ_sPLT_SUPPORTED)
  188423. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188424. {
  188425. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188426. {
  188427. png_push_save_buffer(png_ptr);
  188428. return;
  188429. }
  188430. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188431. }
  188432. #endif
  188433. #if defined(PNG_READ_tRNS_SUPPORTED)
  188434. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188435. {
  188436. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188437. {
  188438. png_push_save_buffer(png_ptr);
  188439. return;
  188440. }
  188441. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188442. }
  188443. #endif
  188444. #if defined(PNG_READ_bKGD_SUPPORTED)
  188445. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188446. {
  188447. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188448. {
  188449. png_push_save_buffer(png_ptr);
  188450. return;
  188451. }
  188452. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188453. }
  188454. #endif
  188455. #if defined(PNG_READ_hIST_SUPPORTED)
  188456. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188457. {
  188458. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188459. {
  188460. png_push_save_buffer(png_ptr);
  188461. return;
  188462. }
  188463. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188464. }
  188465. #endif
  188466. #if defined(PNG_READ_pHYs_SUPPORTED)
  188467. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188468. {
  188469. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188470. {
  188471. png_push_save_buffer(png_ptr);
  188472. return;
  188473. }
  188474. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188475. }
  188476. #endif
  188477. #if defined(PNG_READ_oFFs_SUPPORTED)
  188478. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188479. {
  188480. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188481. {
  188482. png_push_save_buffer(png_ptr);
  188483. return;
  188484. }
  188485. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188486. }
  188487. #endif
  188488. #if defined(PNG_READ_pCAL_SUPPORTED)
  188489. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188490. {
  188491. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188492. {
  188493. png_push_save_buffer(png_ptr);
  188494. return;
  188495. }
  188496. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  188497. }
  188498. #endif
  188499. #if defined(PNG_READ_sCAL_SUPPORTED)
  188500. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188501. {
  188502. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188503. {
  188504. png_push_save_buffer(png_ptr);
  188505. return;
  188506. }
  188507. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  188508. }
  188509. #endif
  188510. #if defined(PNG_READ_tIME_SUPPORTED)
  188511. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188512. {
  188513. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188514. {
  188515. png_push_save_buffer(png_ptr);
  188516. return;
  188517. }
  188518. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  188519. }
  188520. #endif
  188521. #if defined(PNG_READ_tEXt_SUPPORTED)
  188522. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188523. {
  188524. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188525. {
  188526. png_push_save_buffer(png_ptr);
  188527. return;
  188528. }
  188529. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  188530. }
  188531. #endif
  188532. #if defined(PNG_READ_zTXt_SUPPORTED)
  188533. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188534. {
  188535. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188536. {
  188537. png_push_save_buffer(png_ptr);
  188538. return;
  188539. }
  188540. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  188541. }
  188542. #endif
  188543. #if defined(PNG_READ_iTXt_SUPPORTED)
  188544. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188545. {
  188546. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188547. {
  188548. png_push_save_buffer(png_ptr);
  188549. return;
  188550. }
  188551. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  188552. }
  188553. #endif
  188554. else
  188555. {
  188556. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188557. {
  188558. png_push_save_buffer(png_ptr);
  188559. return;
  188560. }
  188561. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188562. }
  188563. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188564. }
  188565. void /* PRIVATE */
  188566. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  188567. {
  188568. png_ptr->process_mode = PNG_SKIP_MODE;
  188569. png_ptr->skip_length = skip;
  188570. }
  188571. void /* PRIVATE */
  188572. png_push_crc_finish(png_structp png_ptr)
  188573. {
  188574. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  188575. {
  188576. png_size_t save_size;
  188577. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  188578. save_size = (png_size_t)png_ptr->skip_length;
  188579. else
  188580. save_size = png_ptr->save_buffer_size;
  188581. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188582. png_ptr->skip_length -= save_size;
  188583. png_ptr->buffer_size -= save_size;
  188584. png_ptr->save_buffer_size -= save_size;
  188585. png_ptr->save_buffer_ptr += save_size;
  188586. }
  188587. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  188588. {
  188589. png_size_t save_size;
  188590. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  188591. save_size = (png_size_t)png_ptr->skip_length;
  188592. else
  188593. save_size = png_ptr->current_buffer_size;
  188594. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188595. png_ptr->skip_length -= save_size;
  188596. png_ptr->buffer_size -= save_size;
  188597. png_ptr->current_buffer_size -= save_size;
  188598. png_ptr->current_buffer_ptr += save_size;
  188599. }
  188600. if (!png_ptr->skip_length)
  188601. {
  188602. if (png_ptr->buffer_size < 4)
  188603. {
  188604. png_push_save_buffer(png_ptr);
  188605. return;
  188606. }
  188607. png_crc_finish(png_ptr, 0);
  188608. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188609. }
  188610. }
  188611. void PNGAPI
  188612. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  188613. {
  188614. png_bytep ptr;
  188615. if(png_ptr == NULL) return;
  188616. ptr = buffer;
  188617. if (png_ptr->save_buffer_size)
  188618. {
  188619. png_size_t save_size;
  188620. if (length < png_ptr->save_buffer_size)
  188621. save_size = length;
  188622. else
  188623. save_size = png_ptr->save_buffer_size;
  188624. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  188625. length -= save_size;
  188626. ptr += save_size;
  188627. png_ptr->buffer_size -= save_size;
  188628. png_ptr->save_buffer_size -= save_size;
  188629. png_ptr->save_buffer_ptr += save_size;
  188630. }
  188631. if (length && png_ptr->current_buffer_size)
  188632. {
  188633. png_size_t save_size;
  188634. if (length < png_ptr->current_buffer_size)
  188635. save_size = length;
  188636. else
  188637. save_size = png_ptr->current_buffer_size;
  188638. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  188639. png_ptr->buffer_size -= save_size;
  188640. png_ptr->current_buffer_size -= save_size;
  188641. png_ptr->current_buffer_ptr += save_size;
  188642. }
  188643. }
  188644. void /* PRIVATE */
  188645. png_push_save_buffer(png_structp png_ptr)
  188646. {
  188647. if (png_ptr->save_buffer_size)
  188648. {
  188649. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  188650. {
  188651. png_size_t i,istop;
  188652. png_bytep sp;
  188653. png_bytep dp;
  188654. istop = png_ptr->save_buffer_size;
  188655. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  188656. i < istop; i++, sp++, dp++)
  188657. {
  188658. *dp = *sp;
  188659. }
  188660. }
  188661. }
  188662. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  188663. png_ptr->save_buffer_max)
  188664. {
  188665. png_size_t new_max;
  188666. png_bytep old_buffer;
  188667. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  188668. (png_ptr->current_buffer_size + 256))
  188669. {
  188670. png_error(png_ptr, "Potential overflow of save_buffer");
  188671. }
  188672. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  188673. old_buffer = png_ptr->save_buffer;
  188674. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  188675. (png_uint_32)new_max);
  188676. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  188677. png_free(png_ptr, old_buffer);
  188678. png_ptr->save_buffer_max = new_max;
  188679. }
  188680. if (png_ptr->current_buffer_size)
  188681. {
  188682. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  188683. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  188684. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  188685. png_ptr->current_buffer_size = 0;
  188686. }
  188687. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  188688. png_ptr->buffer_size = 0;
  188689. }
  188690. void /* PRIVATE */
  188691. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  188692. png_size_t buffer_length)
  188693. {
  188694. png_ptr->current_buffer = buffer;
  188695. png_ptr->current_buffer_size = buffer_length;
  188696. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  188697. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  188698. }
  188699. void /* PRIVATE */
  188700. png_push_read_IDAT(png_structp png_ptr)
  188701. {
  188702. #ifdef PNG_USE_LOCAL_ARRAYS
  188703. PNG_CONST PNG_IDAT;
  188704. #endif
  188705. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188706. {
  188707. png_byte chunk_length[4];
  188708. if (png_ptr->buffer_size < 8)
  188709. {
  188710. png_push_save_buffer(png_ptr);
  188711. return;
  188712. }
  188713. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188714. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188715. png_reset_crc(png_ptr);
  188716. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188717. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188718. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188719. {
  188720. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188721. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188722. png_error(png_ptr, "Not enough compressed data");
  188723. return;
  188724. }
  188725. png_ptr->idat_size = png_ptr->push_length;
  188726. }
  188727. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  188728. {
  188729. png_size_t save_size;
  188730. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  188731. {
  188732. save_size = (png_size_t)png_ptr->idat_size;
  188733. /* check for overflow */
  188734. if((png_uint_32)save_size != png_ptr->idat_size)
  188735. png_error(png_ptr, "save_size overflowed in pngpread");
  188736. }
  188737. else
  188738. save_size = png_ptr->save_buffer_size;
  188739. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188740. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188741. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188742. png_ptr->idat_size -= save_size;
  188743. png_ptr->buffer_size -= save_size;
  188744. png_ptr->save_buffer_size -= save_size;
  188745. png_ptr->save_buffer_ptr += save_size;
  188746. }
  188747. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  188748. {
  188749. png_size_t save_size;
  188750. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  188751. {
  188752. save_size = (png_size_t)png_ptr->idat_size;
  188753. /* check for overflow */
  188754. if((png_uint_32)save_size != png_ptr->idat_size)
  188755. png_error(png_ptr, "save_size overflowed in pngpread");
  188756. }
  188757. else
  188758. save_size = png_ptr->current_buffer_size;
  188759. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188760. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188761. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188762. png_ptr->idat_size -= save_size;
  188763. png_ptr->buffer_size -= save_size;
  188764. png_ptr->current_buffer_size -= save_size;
  188765. png_ptr->current_buffer_ptr += save_size;
  188766. }
  188767. if (!png_ptr->idat_size)
  188768. {
  188769. if (png_ptr->buffer_size < 4)
  188770. {
  188771. png_push_save_buffer(png_ptr);
  188772. return;
  188773. }
  188774. png_crc_finish(png_ptr, 0);
  188775. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188776. png_ptr->mode |= PNG_AFTER_IDAT;
  188777. }
  188778. }
  188779. void /* PRIVATE */
  188780. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  188781. png_size_t buffer_length)
  188782. {
  188783. int ret;
  188784. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  188785. png_error(png_ptr, "Extra compression data");
  188786. png_ptr->zstream.next_in = buffer;
  188787. png_ptr->zstream.avail_in = (uInt)buffer_length;
  188788. for(;;)
  188789. {
  188790. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188791. if (ret != Z_OK)
  188792. {
  188793. if (ret == Z_STREAM_END)
  188794. {
  188795. if (png_ptr->zstream.avail_in)
  188796. png_error(png_ptr, "Extra compressed data");
  188797. if (!(png_ptr->zstream.avail_out))
  188798. {
  188799. png_push_process_row(png_ptr);
  188800. }
  188801. png_ptr->mode |= PNG_AFTER_IDAT;
  188802. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188803. break;
  188804. }
  188805. else if (ret == Z_BUF_ERROR)
  188806. break;
  188807. else
  188808. png_error(png_ptr, "Decompression Error");
  188809. }
  188810. if (!(png_ptr->zstream.avail_out))
  188811. {
  188812. if ((
  188813. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188814. png_ptr->interlaced && png_ptr->pass > 6) ||
  188815. (!png_ptr->interlaced &&
  188816. #endif
  188817. png_ptr->row_number == png_ptr->num_rows))
  188818. {
  188819. if (png_ptr->zstream.avail_in)
  188820. {
  188821. png_warning(png_ptr, "Too much data in IDAT chunks");
  188822. }
  188823. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188824. break;
  188825. }
  188826. png_push_process_row(png_ptr);
  188827. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188828. png_ptr->zstream.next_out = png_ptr->row_buf;
  188829. }
  188830. else
  188831. break;
  188832. }
  188833. }
  188834. void /* PRIVATE */
  188835. png_push_process_row(png_structp png_ptr)
  188836. {
  188837. png_ptr->row_info.color_type = png_ptr->color_type;
  188838. png_ptr->row_info.width = png_ptr->iwidth;
  188839. png_ptr->row_info.channels = png_ptr->channels;
  188840. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  188841. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  188842. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  188843. png_ptr->row_info.width);
  188844. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  188845. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  188846. (int)(png_ptr->row_buf[0]));
  188847. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  188848. png_ptr->rowbytes + 1);
  188849. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  188850. png_do_read_transformations(png_ptr);
  188851. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188852. /* blow up interlaced rows to full size */
  188853. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  188854. {
  188855. if (png_ptr->pass < 6)
  188856. /* old interface (pre-1.0.9):
  188857. png_do_read_interlace(&(png_ptr->row_info),
  188858. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  188859. */
  188860. png_do_read_interlace(png_ptr);
  188861. switch (png_ptr->pass)
  188862. {
  188863. case 0:
  188864. {
  188865. int i;
  188866. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  188867. {
  188868. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188869. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  188870. }
  188871. if (png_ptr->pass == 2) /* pass 1 might be empty */
  188872. {
  188873. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188874. {
  188875. png_push_have_row(png_ptr, png_bytep_NULL);
  188876. png_read_push_finish_row(png_ptr);
  188877. }
  188878. }
  188879. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  188880. {
  188881. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188882. {
  188883. png_push_have_row(png_ptr, png_bytep_NULL);
  188884. png_read_push_finish_row(png_ptr);
  188885. }
  188886. }
  188887. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  188888. {
  188889. png_push_have_row(png_ptr, png_bytep_NULL);
  188890. png_read_push_finish_row(png_ptr);
  188891. }
  188892. break;
  188893. }
  188894. case 1:
  188895. {
  188896. int i;
  188897. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  188898. {
  188899. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188900. png_read_push_finish_row(png_ptr);
  188901. }
  188902. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  188903. {
  188904. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188905. {
  188906. png_push_have_row(png_ptr, png_bytep_NULL);
  188907. png_read_push_finish_row(png_ptr);
  188908. }
  188909. }
  188910. break;
  188911. }
  188912. case 2:
  188913. {
  188914. int i;
  188915. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188916. {
  188917. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188918. png_read_push_finish_row(png_ptr);
  188919. }
  188920. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188921. {
  188922. png_push_have_row(png_ptr, png_bytep_NULL);
  188923. png_read_push_finish_row(png_ptr);
  188924. }
  188925. if (png_ptr->pass == 4) /* pass 3 might be empty */
  188926. {
  188927. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188928. {
  188929. png_push_have_row(png_ptr, png_bytep_NULL);
  188930. png_read_push_finish_row(png_ptr);
  188931. }
  188932. }
  188933. break;
  188934. }
  188935. case 3:
  188936. {
  188937. int i;
  188938. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  188939. {
  188940. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188941. png_read_push_finish_row(png_ptr);
  188942. }
  188943. if (png_ptr->pass == 4) /* skip top two generated rows */
  188944. {
  188945. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188946. {
  188947. png_push_have_row(png_ptr, png_bytep_NULL);
  188948. png_read_push_finish_row(png_ptr);
  188949. }
  188950. }
  188951. break;
  188952. }
  188953. case 4:
  188954. {
  188955. int i;
  188956. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188957. {
  188958. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188959. png_read_push_finish_row(png_ptr);
  188960. }
  188961. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188962. {
  188963. png_push_have_row(png_ptr, png_bytep_NULL);
  188964. png_read_push_finish_row(png_ptr);
  188965. }
  188966. if (png_ptr->pass == 6) /* pass 5 might be empty */
  188967. {
  188968. png_push_have_row(png_ptr, png_bytep_NULL);
  188969. png_read_push_finish_row(png_ptr);
  188970. }
  188971. break;
  188972. }
  188973. case 5:
  188974. {
  188975. int i;
  188976. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  188977. {
  188978. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188979. png_read_push_finish_row(png_ptr);
  188980. }
  188981. if (png_ptr->pass == 6) /* skip top generated row */
  188982. {
  188983. png_push_have_row(png_ptr, png_bytep_NULL);
  188984. png_read_push_finish_row(png_ptr);
  188985. }
  188986. break;
  188987. }
  188988. case 6:
  188989. {
  188990. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188991. png_read_push_finish_row(png_ptr);
  188992. if (png_ptr->pass != 6)
  188993. break;
  188994. png_push_have_row(png_ptr, png_bytep_NULL);
  188995. png_read_push_finish_row(png_ptr);
  188996. }
  188997. }
  188998. }
  188999. else
  189000. #endif
  189001. {
  189002. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189003. png_read_push_finish_row(png_ptr);
  189004. }
  189005. }
  189006. void /* PRIVATE */
  189007. png_read_push_finish_row(png_structp png_ptr)
  189008. {
  189009. #ifdef PNG_USE_LOCAL_ARRAYS
  189010. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189011. /* start of interlace block */
  189012. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  189013. /* offset to next interlace block */
  189014. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  189015. /* start of interlace block in the y direction */
  189016. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  189017. /* offset to next interlace block in the y direction */
  189018. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189019. /* Height of interlace block. This is not currently used - if you need
  189020. * it, uncomment it here and in png.h
  189021. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189022. */
  189023. #endif
  189024. png_ptr->row_number++;
  189025. if (png_ptr->row_number < png_ptr->num_rows)
  189026. return;
  189027. if (png_ptr->interlaced)
  189028. {
  189029. png_ptr->row_number = 0;
  189030. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189031. png_ptr->rowbytes + 1);
  189032. do
  189033. {
  189034. png_ptr->pass++;
  189035. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189036. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189037. (png_ptr->pass == 5 && png_ptr->width < 2))
  189038. png_ptr->pass++;
  189039. if (png_ptr->pass > 7)
  189040. png_ptr->pass--;
  189041. if (png_ptr->pass >= 7)
  189042. break;
  189043. png_ptr->iwidth = (png_ptr->width +
  189044. png_pass_inc[png_ptr->pass] - 1 -
  189045. png_pass_start[png_ptr->pass]) /
  189046. png_pass_inc[png_ptr->pass];
  189047. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189048. png_ptr->iwidth) + 1;
  189049. if (png_ptr->transformations & PNG_INTERLACE)
  189050. break;
  189051. png_ptr->num_rows = (png_ptr->height +
  189052. png_pass_yinc[png_ptr->pass] - 1 -
  189053. png_pass_ystart[png_ptr->pass]) /
  189054. png_pass_yinc[png_ptr->pass];
  189055. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189056. }
  189057. }
  189058. #if defined(PNG_READ_tEXt_SUPPORTED)
  189059. void /* PRIVATE */
  189060. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189061. length)
  189062. {
  189063. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189064. {
  189065. png_error(png_ptr, "Out of place tEXt");
  189066. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189067. }
  189068. #ifdef PNG_MAX_MALLOC_64K
  189069. png_ptr->skip_length = 0; /* This may not be necessary */
  189070. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189071. {
  189072. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189073. png_ptr->skip_length = length - (png_uint_32)65535L;
  189074. length = (png_uint_32)65535L;
  189075. }
  189076. #endif
  189077. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189078. (png_uint_32)(length+1));
  189079. png_ptr->current_text[length] = '\0';
  189080. png_ptr->current_text_ptr = png_ptr->current_text;
  189081. png_ptr->current_text_size = (png_size_t)length;
  189082. png_ptr->current_text_left = (png_size_t)length;
  189083. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189084. }
  189085. void /* PRIVATE */
  189086. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189087. {
  189088. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189089. {
  189090. png_size_t text_size;
  189091. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189092. text_size = png_ptr->buffer_size;
  189093. else
  189094. text_size = png_ptr->current_text_left;
  189095. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189096. png_ptr->current_text_left -= text_size;
  189097. png_ptr->current_text_ptr += text_size;
  189098. }
  189099. if (!(png_ptr->current_text_left))
  189100. {
  189101. png_textp text_ptr;
  189102. png_charp text;
  189103. png_charp key;
  189104. int ret;
  189105. if (png_ptr->buffer_size < 4)
  189106. {
  189107. png_push_save_buffer(png_ptr);
  189108. return;
  189109. }
  189110. png_push_crc_finish(png_ptr);
  189111. #if defined(PNG_MAX_MALLOC_64K)
  189112. if (png_ptr->skip_length)
  189113. return;
  189114. #endif
  189115. key = png_ptr->current_text;
  189116. for (text = key; *text; text++)
  189117. /* empty loop */ ;
  189118. if (text < key + png_ptr->current_text_size)
  189119. text++;
  189120. text_ptr = (png_textp)png_malloc(png_ptr,
  189121. (png_uint_32)png_sizeof(png_text));
  189122. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189123. text_ptr->key = key;
  189124. #ifdef PNG_iTXt_SUPPORTED
  189125. text_ptr->lang = NULL;
  189126. text_ptr->lang_key = NULL;
  189127. #endif
  189128. text_ptr->text = text;
  189129. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189130. png_free(png_ptr, key);
  189131. png_free(png_ptr, text_ptr);
  189132. png_ptr->current_text = NULL;
  189133. if (ret)
  189134. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189135. }
  189136. }
  189137. #endif
  189138. #if defined(PNG_READ_zTXt_SUPPORTED)
  189139. void /* PRIVATE */
  189140. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189141. length)
  189142. {
  189143. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189144. {
  189145. png_error(png_ptr, "Out of place zTXt");
  189146. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189147. }
  189148. #ifdef PNG_MAX_MALLOC_64K
  189149. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189150. * to be able to store the uncompressed data. Actually, the threshold
  189151. * is probably around 32K, but it isn't as definite as 64K is.
  189152. */
  189153. if (length > (png_uint_32)65535L)
  189154. {
  189155. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189156. png_push_crc_skip(png_ptr, length);
  189157. return;
  189158. }
  189159. #endif
  189160. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189161. (png_uint_32)(length+1));
  189162. png_ptr->current_text[length] = '\0';
  189163. png_ptr->current_text_ptr = png_ptr->current_text;
  189164. png_ptr->current_text_size = (png_size_t)length;
  189165. png_ptr->current_text_left = (png_size_t)length;
  189166. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189167. }
  189168. void /* PRIVATE */
  189169. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189170. {
  189171. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189172. {
  189173. png_size_t text_size;
  189174. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189175. text_size = png_ptr->buffer_size;
  189176. else
  189177. text_size = png_ptr->current_text_left;
  189178. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189179. png_ptr->current_text_left -= text_size;
  189180. png_ptr->current_text_ptr += text_size;
  189181. }
  189182. if (!(png_ptr->current_text_left))
  189183. {
  189184. png_textp text_ptr;
  189185. png_charp text;
  189186. png_charp key;
  189187. int ret;
  189188. png_size_t text_size, key_size;
  189189. if (png_ptr->buffer_size < 4)
  189190. {
  189191. png_push_save_buffer(png_ptr);
  189192. return;
  189193. }
  189194. png_push_crc_finish(png_ptr);
  189195. key = png_ptr->current_text;
  189196. for (text = key; *text; text++)
  189197. /* empty loop */ ;
  189198. /* zTXt can't have zero text */
  189199. if (text >= key + png_ptr->current_text_size)
  189200. {
  189201. png_ptr->current_text = NULL;
  189202. png_free(png_ptr, key);
  189203. return;
  189204. }
  189205. text++;
  189206. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189207. {
  189208. png_ptr->current_text = NULL;
  189209. png_free(png_ptr, key);
  189210. return;
  189211. }
  189212. text++;
  189213. png_ptr->zstream.next_in = (png_bytep )text;
  189214. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189215. (text - key));
  189216. png_ptr->zstream.next_out = png_ptr->zbuf;
  189217. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189218. key_size = text - key;
  189219. text_size = 0;
  189220. text = NULL;
  189221. ret = Z_STREAM_END;
  189222. while (png_ptr->zstream.avail_in)
  189223. {
  189224. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189225. if (ret != Z_OK && ret != Z_STREAM_END)
  189226. {
  189227. inflateReset(&png_ptr->zstream);
  189228. png_ptr->zstream.avail_in = 0;
  189229. png_ptr->current_text = NULL;
  189230. png_free(png_ptr, key);
  189231. png_free(png_ptr, text);
  189232. return;
  189233. }
  189234. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189235. {
  189236. if (text == NULL)
  189237. {
  189238. text = (png_charp)png_malloc(png_ptr,
  189239. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189240. + key_size + 1));
  189241. png_memcpy(text + key_size, png_ptr->zbuf,
  189242. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189243. png_memcpy(text, key, key_size);
  189244. text_size = key_size + png_ptr->zbuf_size -
  189245. png_ptr->zstream.avail_out;
  189246. *(text + text_size) = '\0';
  189247. }
  189248. else
  189249. {
  189250. png_charp tmp;
  189251. tmp = text;
  189252. text = (png_charp)png_malloc(png_ptr, text_size +
  189253. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189254. + 1));
  189255. png_memcpy(text, tmp, text_size);
  189256. png_free(png_ptr, tmp);
  189257. png_memcpy(text + text_size, png_ptr->zbuf,
  189258. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189259. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189260. *(text + text_size) = '\0';
  189261. }
  189262. if (ret != Z_STREAM_END)
  189263. {
  189264. png_ptr->zstream.next_out = png_ptr->zbuf;
  189265. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189266. }
  189267. }
  189268. else
  189269. {
  189270. break;
  189271. }
  189272. if (ret == Z_STREAM_END)
  189273. break;
  189274. }
  189275. inflateReset(&png_ptr->zstream);
  189276. png_ptr->zstream.avail_in = 0;
  189277. if (ret != Z_STREAM_END)
  189278. {
  189279. png_ptr->current_text = NULL;
  189280. png_free(png_ptr, key);
  189281. png_free(png_ptr, text);
  189282. return;
  189283. }
  189284. png_ptr->current_text = NULL;
  189285. png_free(png_ptr, key);
  189286. key = text;
  189287. text += key_size;
  189288. text_ptr = (png_textp)png_malloc(png_ptr,
  189289. (png_uint_32)png_sizeof(png_text));
  189290. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189291. text_ptr->key = key;
  189292. #ifdef PNG_iTXt_SUPPORTED
  189293. text_ptr->lang = NULL;
  189294. text_ptr->lang_key = NULL;
  189295. #endif
  189296. text_ptr->text = text;
  189297. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189298. png_free(png_ptr, key);
  189299. png_free(png_ptr, text_ptr);
  189300. if (ret)
  189301. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189302. }
  189303. }
  189304. #endif
  189305. #if defined(PNG_READ_iTXt_SUPPORTED)
  189306. void /* PRIVATE */
  189307. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189308. length)
  189309. {
  189310. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189311. {
  189312. png_error(png_ptr, "Out of place iTXt");
  189313. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189314. }
  189315. #ifdef PNG_MAX_MALLOC_64K
  189316. png_ptr->skip_length = 0; /* This may not be necessary */
  189317. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189318. {
  189319. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189320. png_ptr->skip_length = length - (png_uint_32)65535L;
  189321. length = (png_uint_32)65535L;
  189322. }
  189323. #endif
  189324. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189325. (png_uint_32)(length+1));
  189326. png_ptr->current_text[length] = '\0';
  189327. png_ptr->current_text_ptr = png_ptr->current_text;
  189328. png_ptr->current_text_size = (png_size_t)length;
  189329. png_ptr->current_text_left = (png_size_t)length;
  189330. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189331. }
  189332. void /* PRIVATE */
  189333. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189334. {
  189335. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189336. {
  189337. png_size_t text_size;
  189338. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189339. text_size = png_ptr->buffer_size;
  189340. else
  189341. text_size = png_ptr->current_text_left;
  189342. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189343. png_ptr->current_text_left -= text_size;
  189344. png_ptr->current_text_ptr += text_size;
  189345. }
  189346. if (!(png_ptr->current_text_left))
  189347. {
  189348. png_textp text_ptr;
  189349. png_charp key;
  189350. int comp_flag;
  189351. png_charp lang;
  189352. png_charp lang_key;
  189353. png_charp text;
  189354. int ret;
  189355. if (png_ptr->buffer_size < 4)
  189356. {
  189357. png_push_save_buffer(png_ptr);
  189358. return;
  189359. }
  189360. png_push_crc_finish(png_ptr);
  189361. #if defined(PNG_MAX_MALLOC_64K)
  189362. if (png_ptr->skip_length)
  189363. return;
  189364. #endif
  189365. key = png_ptr->current_text;
  189366. for (lang = key; *lang; lang++)
  189367. /* empty loop */ ;
  189368. if (lang < key + png_ptr->current_text_size - 3)
  189369. lang++;
  189370. comp_flag = *lang++;
  189371. lang++; /* skip comp_type, always zero */
  189372. for (lang_key = lang; *lang_key; lang_key++)
  189373. /* empty loop */ ;
  189374. lang_key++; /* skip NUL separator */
  189375. text=lang_key;
  189376. if (lang_key < key + png_ptr->current_text_size - 1)
  189377. {
  189378. for (; *text; text++)
  189379. /* empty loop */ ;
  189380. }
  189381. if (text < key + png_ptr->current_text_size)
  189382. text++;
  189383. text_ptr = (png_textp)png_malloc(png_ptr,
  189384. (png_uint_32)png_sizeof(png_text));
  189385. text_ptr->compression = comp_flag + 2;
  189386. text_ptr->key = key;
  189387. text_ptr->lang = lang;
  189388. text_ptr->lang_key = lang_key;
  189389. text_ptr->text = text;
  189390. text_ptr->text_length = 0;
  189391. text_ptr->itxt_length = png_strlen(text);
  189392. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189393. png_ptr->current_text = NULL;
  189394. png_free(png_ptr, text_ptr);
  189395. if (ret)
  189396. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189397. }
  189398. }
  189399. #endif
  189400. /* This function is called when we haven't found a handler for this
  189401. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189402. * name or a critical chunk), the chunk is (currently) silently ignored.
  189403. */
  189404. void /* PRIVATE */
  189405. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189406. length)
  189407. {
  189408. png_uint_32 skip=0;
  189409. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189410. if (!(png_ptr->chunk_name[0] & 0x20))
  189411. {
  189412. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189413. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189414. PNG_HANDLE_CHUNK_ALWAYS
  189415. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189416. && png_ptr->read_user_chunk_fn == NULL
  189417. #endif
  189418. )
  189419. #endif
  189420. png_chunk_error(png_ptr, "unknown critical chunk");
  189421. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189422. }
  189423. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189424. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189425. {
  189426. #ifdef PNG_MAX_MALLOC_64K
  189427. if (length > (png_uint_32)65535L)
  189428. {
  189429. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189430. skip = length - (png_uint_32)65535L;
  189431. length = (png_uint_32)65535L;
  189432. }
  189433. #endif
  189434. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189435. (png_charp)png_ptr->chunk_name, 5);
  189436. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189437. png_ptr->unknown_chunk.size = (png_size_t)length;
  189438. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189439. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189440. if(png_ptr->read_user_chunk_fn != NULL)
  189441. {
  189442. /* callback to user unknown chunk handler */
  189443. int ret;
  189444. ret = (*(png_ptr->read_user_chunk_fn))
  189445. (png_ptr, &png_ptr->unknown_chunk);
  189446. if (ret < 0)
  189447. png_chunk_error(png_ptr, "error in user chunk");
  189448. if (ret == 0)
  189449. {
  189450. if (!(png_ptr->chunk_name[0] & 0x20))
  189451. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189452. PNG_HANDLE_CHUNK_ALWAYS)
  189453. png_chunk_error(png_ptr, "unknown critical chunk");
  189454. png_set_unknown_chunks(png_ptr, info_ptr,
  189455. &png_ptr->unknown_chunk, 1);
  189456. }
  189457. }
  189458. #else
  189459. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189460. #endif
  189461. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189462. png_ptr->unknown_chunk.data = NULL;
  189463. }
  189464. else
  189465. #endif
  189466. skip=length;
  189467. png_push_crc_skip(png_ptr, skip);
  189468. }
  189469. void /* PRIVATE */
  189470. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189471. {
  189472. if (png_ptr->info_fn != NULL)
  189473. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189474. }
  189475. void /* PRIVATE */
  189476. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189477. {
  189478. if (png_ptr->end_fn != NULL)
  189479. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189480. }
  189481. void /* PRIVATE */
  189482. png_push_have_row(png_structp png_ptr, png_bytep row)
  189483. {
  189484. if (png_ptr->row_fn != NULL)
  189485. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189486. (int)png_ptr->pass);
  189487. }
  189488. void PNGAPI
  189489. png_progressive_combine_row (png_structp png_ptr,
  189490. png_bytep old_row, png_bytep new_row)
  189491. {
  189492. #ifdef PNG_USE_LOCAL_ARRAYS
  189493. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  189494. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  189495. #endif
  189496. if(png_ptr == NULL) return;
  189497. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  189498. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  189499. }
  189500. void PNGAPI
  189501. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  189502. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  189503. png_progressive_end_ptr end_fn)
  189504. {
  189505. if(png_ptr == NULL) return;
  189506. png_ptr->info_fn = info_fn;
  189507. png_ptr->row_fn = row_fn;
  189508. png_ptr->end_fn = end_fn;
  189509. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  189510. }
  189511. png_voidp PNGAPI
  189512. png_get_progressive_ptr(png_structp png_ptr)
  189513. {
  189514. if(png_ptr == NULL) return (NULL);
  189515. return png_ptr->io_ptr;
  189516. }
  189517. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  189518. /*** End of inlined file: pngpread.c ***/
  189519. /*** Start of inlined file: pngrio.c ***/
  189520. /* pngrio.c - functions for data input
  189521. *
  189522. * Last changed in libpng 1.2.13 November 13, 2006
  189523. * For conditions of distribution and use, see copyright notice in png.h
  189524. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  189525. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189526. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189527. *
  189528. * This file provides a location for all input. Users who need
  189529. * special handling are expected to write a function that has the same
  189530. * arguments as this and performs a similar function, but that possibly
  189531. * has a different input method. Note that you shouldn't change this
  189532. * function, but rather write a replacement function and then make
  189533. * libpng use it at run time with png_set_read_fn(...).
  189534. */
  189535. #define PNG_INTERNAL
  189536. #if defined(PNG_READ_SUPPORTED)
  189537. /* Read the data from whatever input you are using. The default routine
  189538. reads from a file pointer. Note that this routine sometimes gets called
  189539. with very small lengths, so you should implement some kind of simple
  189540. buffering if you are using unbuffered reads. This should never be asked
  189541. to read more then 64K on a 16 bit machine. */
  189542. void /* PRIVATE */
  189543. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189544. {
  189545. png_debug1(4,"reading %d bytes\n", (int)length);
  189546. if (png_ptr->read_data_fn != NULL)
  189547. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  189548. else
  189549. png_error(png_ptr, "Call to NULL read function");
  189550. }
  189551. #if !defined(PNG_NO_STDIO)
  189552. /* This is the function that does the actual reading of data. If you are
  189553. not reading from a standard C stream, you should create a replacement
  189554. read_data function and use it at run time with png_set_read_fn(), rather
  189555. than changing the library. */
  189556. #ifndef USE_FAR_KEYWORD
  189557. void PNGAPI
  189558. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189559. {
  189560. png_size_t check;
  189561. if(png_ptr == NULL) return;
  189562. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  189563. * instead of an int, which is what fread() actually returns.
  189564. */
  189565. #if defined(_WIN32_WCE)
  189566. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189567. check = 0;
  189568. #else
  189569. check = (png_size_t)fread(data, (png_size_t)1, length,
  189570. (png_FILE_p)png_ptr->io_ptr);
  189571. #endif
  189572. if (check != length)
  189573. png_error(png_ptr, "Read Error");
  189574. }
  189575. #else
  189576. /* this is the model-independent version. Since the standard I/O library
  189577. can't handle far buffers in the medium and small models, we have to copy
  189578. the data.
  189579. */
  189580. #define NEAR_BUF_SIZE 1024
  189581. #define MIN(a,b) (a <= b ? a : b)
  189582. static void PNGAPI
  189583. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189584. {
  189585. int check;
  189586. png_byte *n_data;
  189587. png_FILE_p io_ptr;
  189588. if(png_ptr == NULL) return;
  189589. /* Check if data really is near. If so, use usual code. */
  189590. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  189591. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  189592. if ((png_bytep)n_data == data)
  189593. {
  189594. #if defined(_WIN32_WCE)
  189595. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189596. check = 0;
  189597. #else
  189598. check = fread(n_data, 1, length, io_ptr);
  189599. #endif
  189600. }
  189601. else
  189602. {
  189603. png_byte buf[NEAR_BUF_SIZE];
  189604. png_size_t read, remaining, err;
  189605. check = 0;
  189606. remaining = length;
  189607. do
  189608. {
  189609. read = MIN(NEAR_BUF_SIZE, remaining);
  189610. #if defined(_WIN32_WCE)
  189611. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  189612. err = 0;
  189613. #else
  189614. err = fread(buf, (png_size_t)1, read, io_ptr);
  189615. #endif
  189616. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  189617. if(err != read)
  189618. break;
  189619. else
  189620. check += err;
  189621. data += read;
  189622. remaining -= read;
  189623. }
  189624. while (remaining != 0);
  189625. }
  189626. if ((png_uint_32)check != (png_uint_32)length)
  189627. png_error(png_ptr, "read Error");
  189628. }
  189629. #endif
  189630. #endif
  189631. /* This function allows the application to supply a new input function
  189632. for libpng if standard C streams aren't being used.
  189633. This function takes as its arguments:
  189634. png_ptr - pointer to a png input data structure
  189635. io_ptr - pointer to user supplied structure containing info about
  189636. the input functions. May be NULL.
  189637. read_data_fn - pointer to a new input function that takes as its
  189638. arguments a pointer to a png_struct, a pointer to
  189639. a location where input data can be stored, and a 32-bit
  189640. unsigned int that is the number of bytes to be read.
  189641. To exit and output any fatal error messages the new write
  189642. function should call png_error(png_ptr, "Error msg"). */
  189643. void PNGAPI
  189644. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  189645. png_rw_ptr read_data_fn)
  189646. {
  189647. if(png_ptr == NULL) return;
  189648. png_ptr->io_ptr = io_ptr;
  189649. #if !defined(PNG_NO_STDIO)
  189650. if (read_data_fn != NULL)
  189651. png_ptr->read_data_fn = read_data_fn;
  189652. else
  189653. png_ptr->read_data_fn = png_default_read_data;
  189654. #else
  189655. png_ptr->read_data_fn = read_data_fn;
  189656. #endif
  189657. /* It is an error to write to a read device */
  189658. if (png_ptr->write_data_fn != NULL)
  189659. {
  189660. png_ptr->write_data_fn = NULL;
  189661. png_warning(png_ptr,
  189662. "It's an error to set both read_data_fn and write_data_fn in the ");
  189663. png_warning(png_ptr,
  189664. "same structure. Resetting write_data_fn to NULL.");
  189665. }
  189666. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  189667. png_ptr->output_flush_fn = NULL;
  189668. #endif
  189669. }
  189670. #endif /* PNG_READ_SUPPORTED */
  189671. /*** End of inlined file: pngrio.c ***/
  189672. /*** Start of inlined file: pngrtran.c ***/
  189673. /* pngrtran.c - transforms the data in a row for PNG readers
  189674. *
  189675. * Last changed in libpng 1.2.21 [October 4, 2007]
  189676. * For conditions of distribution and use, see copyright notice in png.h
  189677. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189678. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189679. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189680. *
  189681. * This file contains functions optionally called by an application
  189682. * in order to tell libpng how to handle data when reading a PNG.
  189683. * Transformations that are used in both reading and writing are
  189684. * in pngtrans.c.
  189685. */
  189686. #define PNG_INTERNAL
  189687. #if defined(PNG_READ_SUPPORTED)
  189688. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  189689. void PNGAPI
  189690. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  189691. {
  189692. png_debug(1, "in png_set_crc_action\n");
  189693. /* Tell libpng how we react to CRC errors in critical chunks */
  189694. if(png_ptr == NULL) return;
  189695. switch (crit_action)
  189696. {
  189697. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189698. break;
  189699. case PNG_CRC_WARN_USE: /* warn/use data */
  189700. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189701. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  189702. break;
  189703. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189704. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189705. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  189706. PNG_FLAG_CRC_CRITICAL_IGNORE;
  189707. break;
  189708. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  189709. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  189710. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189711. case PNG_CRC_DEFAULT:
  189712. default:
  189713. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189714. break;
  189715. }
  189716. switch (ancil_action)
  189717. {
  189718. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189719. break;
  189720. case PNG_CRC_WARN_USE: /* warn/use data */
  189721. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189722. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  189723. break;
  189724. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189725. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189726. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  189727. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189728. break;
  189729. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189730. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189731. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189732. break;
  189733. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  189734. case PNG_CRC_DEFAULT:
  189735. default:
  189736. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189737. break;
  189738. }
  189739. }
  189740. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  189741. defined(PNG_FLOATING_POINT_SUPPORTED)
  189742. /* handle alpha and tRNS via a background color */
  189743. void PNGAPI
  189744. png_set_background(png_structp png_ptr,
  189745. png_color_16p background_color, int background_gamma_code,
  189746. int need_expand, double background_gamma)
  189747. {
  189748. png_debug(1, "in png_set_background\n");
  189749. if(png_ptr == NULL) return;
  189750. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  189751. {
  189752. png_warning(png_ptr, "Application must supply a known background gamma");
  189753. return;
  189754. }
  189755. png_ptr->transformations |= PNG_BACKGROUND;
  189756. png_memcpy(&(png_ptr->background), background_color,
  189757. png_sizeof(png_color_16));
  189758. png_ptr->background_gamma = (float)background_gamma;
  189759. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  189760. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  189761. }
  189762. #endif
  189763. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  189764. /* strip 16 bit depth files to 8 bit depth */
  189765. void PNGAPI
  189766. png_set_strip_16(png_structp png_ptr)
  189767. {
  189768. png_debug(1, "in png_set_strip_16\n");
  189769. if(png_ptr == NULL) return;
  189770. png_ptr->transformations |= PNG_16_TO_8;
  189771. }
  189772. #endif
  189773. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  189774. void PNGAPI
  189775. png_set_strip_alpha(png_structp png_ptr)
  189776. {
  189777. png_debug(1, "in png_set_strip_alpha\n");
  189778. if(png_ptr == NULL) return;
  189779. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  189780. }
  189781. #endif
  189782. #if defined(PNG_READ_DITHER_SUPPORTED)
  189783. /* Dither file to 8 bit. Supply a palette, the current number
  189784. * of elements in the palette, the maximum number of elements
  189785. * allowed, and a histogram if possible. If the current number
  189786. * of colors is greater then the maximum number, the palette will be
  189787. * modified to fit in the maximum number. "full_dither" indicates
  189788. * whether we need a dithering cube set up for RGB images, or if we
  189789. * simply are reducing the number of colors in a paletted image.
  189790. */
  189791. typedef struct png_dsort_struct
  189792. {
  189793. struct png_dsort_struct FAR * next;
  189794. png_byte left;
  189795. png_byte right;
  189796. } png_dsort;
  189797. typedef png_dsort FAR * png_dsortp;
  189798. typedef png_dsort FAR * FAR * png_dsortpp;
  189799. void PNGAPI
  189800. png_set_dither(png_structp png_ptr, png_colorp palette,
  189801. int num_palette, int maximum_colors, png_uint_16p histogram,
  189802. int full_dither)
  189803. {
  189804. png_debug(1, "in png_set_dither\n");
  189805. if(png_ptr == NULL) return;
  189806. png_ptr->transformations |= PNG_DITHER;
  189807. if (!full_dither)
  189808. {
  189809. int i;
  189810. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  189811. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189812. for (i = 0; i < num_palette; i++)
  189813. png_ptr->dither_index[i] = (png_byte)i;
  189814. }
  189815. if (num_palette > maximum_colors)
  189816. {
  189817. if (histogram != NULL)
  189818. {
  189819. /* This is easy enough, just throw out the least used colors.
  189820. Perhaps not the best solution, but good enough. */
  189821. int i;
  189822. /* initialize an array to sort colors */
  189823. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  189824. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189825. /* initialize the dither_sort array */
  189826. for (i = 0; i < num_palette; i++)
  189827. png_ptr->dither_sort[i] = (png_byte)i;
  189828. /* Find the least used palette entries by starting a
  189829. bubble sort, and running it until we have sorted
  189830. out enough colors. Note that we don't care about
  189831. sorting all the colors, just finding which are
  189832. least used. */
  189833. for (i = num_palette - 1; i >= maximum_colors; i--)
  189834. {
  189835. int done; /* to stop early if the list is pre-sorted */
  189836. int j;
  189837. done = 1;
  189838. for (j = 0; j < i; j++)
  189839. {
  189840. if (histogram[png_ptr->dither_sort[j]]
  189841. < histogram[png_ptr->dither_sort[j + 1]])
  189842. {
  189843. png_byte t;
  189844. t = png_ptr->dither_sort[j];
  189845. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  189846. png_ptr->dither_sort[j + 1] = t;
  189847. done = 0;
  189848. }
  189849. }
  189850. if (done)
  189851. break;
  189852. }
  189853. /* swap the palette around, and set up a table, if necessary */
  189854. if (full_dither)
  189855. {
  189856. int j = num_palette;
  189857. /* put all the useful colors within the max, but don't
  189858. move the others */
  189859. for (i = 0; i < maximum_colors; i++)
  189860. {
  189861. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189862. {
  189863. do
  189864. j--;
  189865. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189866. palette[i] = palette[j];
  189867. }
  189868. }
  189869. }
  189870. else
  189871. {
  189872. int j = num_palette;
  189873. /* move all the used colors inside the max limit, and
  189874. develop a translation table */
  189875. for (i = 0; i < maximum_colors; i++)
  189876. {
  189877. /* only move the colors we need to */
  189878. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189879. {
  189880. png_color tmp_color;
  189881. do
  189882. j--;
  189883. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189884. tmp_color = palette[j];
  189885. palette[j] = palette[i];
  189886. palette[i] = tmp_color;
  189887. /* indicate where the color went */
  189888. png_ptr->dither_index[j] = (png_byte)i;
  189889. png_ptr->dither_index[i] = (png_byte)j;
  189890. }
  189891. }
  189892. /* find closest color for those colors we are not using */
  189893. for (i = 0; i < num_palette; i++)
  189894. {
  189895. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  189896. {
  189897. int min_d, k, min_k, d_index;
  189898. /* find the closest color to one we threw out */
  189899. d_index = png_ptr->dither_index[i];
  189900. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  189901. for (k = 1, min_k = 0; k < maximum_colors; k++)
  189902. {
  189903. int d;
  189904. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  189905. if (d < min_d)
  189906. {
  189907. min_d = d;
  189908. min_k = k;
  189909. }
  189910. }
  189911. /* point to closest color */
  189912. png_ptr->dither_index[i] = (png_byte)min_k;
  189913. }
  189914. }
  189915. }
  189916. png_free(png_ptr, png_ptr->dither_sort);
  189917. png_ptr->dither_sort=NULL;
  189918. }
  189919. else
  189920. {
  189921. /* This is much harder to do simply (and quickly). Perhaps
  189922. we need to go through a median cut routine, but those
  189923. don't always behave themselves with only a few colors
  189924. as input. So we will just find the closest two colors,
  189925. and throw out one of them (chosen somewhat randomly).
  189926. [We don't understand this at all, so if someone wants to
  189927. work on improving it, be our guest - AED, GRP]
  189928. */
  189929. int i;
  189930. int max_d;
  189931. int num_new_palette;
  189932. png_dsortp t;
  189933. png_dsortpp hash;
  189934. t=NULL;
  189935. /* initialize palette index arrays */
  189936. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  189937. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189938. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  189939. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189940. /* initialize the sort array */
  189941. for (i = 0; i < num_palette; i++)
  189942. {
  189943. png_ptr->index_to_palette[i] = (png_byte)i;
  189944. png_ptr->palette_to_index[i] = (png_byte)i;
  189945. }
  189946. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  189947. png_sizeof (png_dsortp)));
  189948. for (i = 0; i < 769; i++)
  189949. hash[i] = NULL;
  189950. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  189951. num_new_palette = num_palette;
  189952. /* initial wild guess at how far apart the farthest pixel
  189953. pair we will be eliminating will be. Larger
  189954. numbers mean more areas will be allocated, Smaller
  189955. numbers run the risk of not saving enough data, and
  189956. having to do this all over again.
  189957. I have not done extensive checking on this number.
  189958. */
  189959. max_d = 96;
  189960. while (num_new_palette > maximum_colors)
  189961. {
  189962. for (i = 0; i < num_new_palette - 1; i++)
  189963. {
  189964. int j;
  189965. for (j = i + 1; j < num_new_palette; j++)
  189966. {
  189967. int d;
  189968. d = PNG_COLOR_DIST(palette[i], palette[j]);
  189969. if (d <= max_d)
  189970. {
  189971. t = (png_dsortp)png_malloc_warn(png_ptr,
  189972. (png_uint_32)(png_sizeof(png_dsort)));
  189973. if (t == NULL)
  189974. break;
  189975. t->next = hash[d];
  189976. t->left = (png_byte)i;
  189977. t->right = (png_byte)j;
  189978. hash[d] = t;
  189979. }
  189980. }
  189981. if (t == NULL)
  189982. break;
  189983. }
  189984. if (t != NULL)
  189985. for (i = 0; i <= max_d; i++)
  189986. {
  189987. if (hash[i] != NULL)
  189988. {
  189989. png_dsortp p;
  189990. for (p = hash[i]; p; p = p->next)
  189991. {
  189992. if ((int)png_ptr->index_to_palette[p->left]
  189993. < num_new_palette &&
  189994. (int)png_ptr->index_to_palette[p->right]
  189995. < num_new_palette)
  189996. {
  189997. int j, next_j;
  189998. if (num_new_palette & 0x01)
  189999. {
  190000. j = p->left;
  190001. next_j = p->right;
  190002. }
  190003. else
  190004. {
  190005. j = p->right;
  190006. next_j = p->left;
  190007. }
  190008. num_new_palette--;
  190009. palette[png_ptr->index_to_palette[j]]
  190010. = palette[num_new_palette];
  190011. if (!full_dither)
  190012. {
  190013. int k;
  190014. for (k = 0; k < num_palette; k++)
  190015. {
  190016. if (png_ptr->dither_index[k] ==
  190017. png_ptr->index_to_palette[j])
  190018. png_ptr->dither_index[k] =
  190019. png_ptr->index_to_palette[next_j];
  190020. if ((int)png_ptr->dither_index[k] ==
  190021. num_new_palette)
  190022. png_ptr->dither_index[k] =
  190023. png_ptr->index_to_palette[j];
  190024. }
  190025. }
  190026. png_ptr->index_to_palette[png_ptr->palette_to_index
  190027. [num_new_palette]] = png_ptr->index_to_palette[j];
  190028. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190029. = png_ptr->palette_to_index[num_new_palette];
  190030. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190031. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190032. }
  190033. if (num_new_palette <= maximum_colors)
  190034. break;
  190035. }
  190036. if (num_new_palette <= maximum_colors)
  190037. break;
  190038. }
  190039. }
  190040. for (i = 0; i < 769; i++)
  190041. {
  190042. if (hash[i] != NULL)
  190043. {
  190044. png_dsortp p = hash[i];
  190045. while (p)
  190046. {
  190047. t = p->next;
  190048. png_free(png_ptr, p);
  190049. p = t;
  190050. }
  190051. }
  190052. hash[i] = 0;
  190053. }
  190054. max_d += 96;
  190055. }
  190056. png_free(png_ptr, hash);
  190057. png_free(png_ptr, png_ptr->palette_to_index);
  190058. png_free(png_ptr, png_ptr->index_to_palette);
  190059. png_ptr->palette_to_index=NULL;
  190060. png_ptr->index_to_palette=NULL;
  190061. }
  190062. num_palette = maximum_colors;
  190063. }
  190064. if (png_ptr->palette == NULL)
  190065. {
  190066. png_ptr->palette = palette;
  190067. }
  190068. png_ptr->num_palette = (png_uint_16)num_palette;
  190069. if (full_dither)
  190070. {
  190071. int i;
  190072. png_bytep distance;
  190073. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190074. PNG_DITHER_BLUE_BITS;
  190075. int num_red = (1 << PNG_DITHER_RED_BITS);
  190076. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190077. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190078. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190079. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190080. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190081. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190082. png_sizeof (png_byte));
  190083. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190084. png_sizeof(png_byte)));
  190085. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190086. for (i = 0; i < num_palette; i++)
  190087. {
  190088. int ir, ig, ib;
  190089. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190090. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190091. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190092. for (ir = 0; ir < num_red; ir++)
  190093. {
  190094. /* int dr = abs(ir - r); */
  190095. int dr = ((ir > r) ? ir - r : r - ir);
  190096. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190097. for (ig = 0; ig < num_green; ig++)
  190098. {
  190099. /* int dg = abs(ig - g); */
  190100. int dg = ((ig > g) ? ig - g : g - ig);
  190101. int dt = dr + dg;
  190102. int dm = ((dr > dg) ? dr : dg);
  190103. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190104. for (ib = 0; ib < num_blue; ib++)
  190105. {
  190106. int d_index = index_g | ib;
  190107. /* int db = abs(ib - b); */
  190108. int db = ((ib > b) ? ib - b : b - ib);
  190109. int dmax = ((dm > db) ? dm : db);
  190110. int d = dmax + dt + db;
  190111. if (d < (int)distance[d_index])
  190112. {
  190113. distance[d_index] = (png_byte)d;
  190114. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190115. }
  190116. }
  190117. }
  190118. }
  190119. }
  190120. png_free(png_ptr, distance);
  190121. }
  190122. }
  190123. #endif
  190124. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190125. /* Transform the image from the file_gamma to the screen_gamma. We
  190126. * only do transformations on images where the file_gamma and screen_gamma
  190127. * are not close reciprocals, otherwise it slows things down slightly, and
  190128. * also needlessly introduces small errors.
  190129. *
  190130. * We will turn off gamma transformation later if no semitransparent entries
  190131. * are present in the tRNS array for palette images. We can't do it here
  190132. * because we don't necessarily have the tRNS chunk yet.
  190133. */
  190134. void PNGAPI
  190135. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190136. {
  190137. png_debug(1, "in png_set_gamma\n");
  190138. if(png_ptr == NULL) return;
  190139. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190140. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190141. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190142. png_ptr->transformations |= PNG_GAMMA;
  190143. png_ptr->gamma = (float)file_gamma;
  190144. png_ptr->screen_gamma = (float)scrn_gamma;
  190145. }
  190146. #endif
  190147. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190148. /* Expand paletted images to RGB, expand grayscale images of
  190149. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190150. * to alpha channels.
  190151. */
  190152. void PNGAPI
  190153. png_set_expand(png_structp png_ptr)
  190154. {
  190155. png_debug(1, "in png_set_expand\n");
  190156. if(png_ptr == NULL) return;
  190157. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190158. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190159. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190160. #endif
  190161. }
  190162. /* GRR 19990627: the following three functions currently are identical
  190163. * to png_set_expand(). However, it is entirely reasonable that someone
  190164. * might wish to expand an indexed image to RGB but *not* expand a single,
  190165. * fully transparent palette entry to a full alpha channel--perhaps instead
  190166. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190167. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190168. * IOW, a future version of the library may make the transformations flag
  190169. * a bit more fine-grained, with separate bits for each of these three
  190170. * functions.
  190171. *
  190172. * More to the point, these functions make it obvious what libpng will be
  190173. * doing, whereas "expand" can (and does) mean any number of things.
  190174. *
  190175. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190176. * to expand only the sample depth but not to expand the tRNS to alpha.
  190177. */
  190178. /* Expand paletted images to RGB. */
  190179. void PNGAPI
  190180. png_set_palette_to_rgb(png_structp png_ptr)
  190181. {
  190182. png_debug(1, "in png_set_palette_to_rgb\n");
  190183. if(png_ptr == NULL) return;
  190184. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190185. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190186. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190187. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190188. #endif
  190189. }
  190190. #if !defined(PNG_1_0_X)
  190191. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190192. void PNGAPI
  190193. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190194. {
  190195. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190196. if(png_ptr == NULL) return;
  190197. png_ptr->transformations |= PNG_EXPAND;
  190198. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190199. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190200. #endif
  190201. }
  190202. #endif
  190203. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190204. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190205. /* Deprecated as of libpng-1.2.9 */
  190206. void PNGAPI
  190207. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190208. {
  190209. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190210. if(png_ptr == NULL) return;
  190211. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190212. }
  190213. #endif
  190214. /* Expand tRNS chunks to alpha channels. */
  190215. void PNGAPI
  190216. png_set_tRNS_to_alpha(png_structp png_ptr)
  190217. {
  190218. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190219. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190220. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190221. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190222. #endif
  190223. }
  190224. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190225. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190226. void PNGAPI
  190227. png_set_gray_to_rgb(png_structp png_ptr)
  190228. {
  190229. png_debug(1, "in png_set_gray_to_rgb\n");
  190230. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190231. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190232. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190233. #endif
  190234. }
  190235. #endif
  190236. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190237. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190238. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190239. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190240. */
  190241. void PNGAPI
  190242. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190243. double green)
  190244. {
  190245. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190246. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190247. if(png_ptr == NULL) return;
  190248. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190249. }
  190250. #endif
  190251. void PNGAPI
  190252. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190253. png_fixed_point red, png_fixed_point green)
  190254. {
  190255. png_debug(1, "in png_set_rgb_to_gray\n");
  190256. if(png_ptr == NULL) return;
  190257. switch(error_action)
  190258. {
  190259. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190260. break;
  190261. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190262. break;
  190263. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190264. }
  190265. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190266. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190267. png_ptr->transformations |= PNG_EXPAND;
  190268. #else
  190269. {
  190270. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190271. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190272. }
  190273. #endif
  190274. {
  190275. png_uint_16 red_int, green_int;
  190276. if(red < 0 || green < 0)
  190277. {
  190278. red_int = 6968; /* .212671 * 32768 + .5 */
  190279. green_int = 23434; /* .715160 * 32768 + .5 */
  190280. }
  190281. else if(red + green < 100000L)
  190282. {
  190283. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190284. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190285. }
  190286. else
  190287. {
  190288. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190289. red_int = 6968;
  190290. green_int = 23434;
  190291. }
  190292. png_ptr->rgb_to_gray_red_coeff = red_int;
  190293. png_ptr->rgb_to_gray_green_coeff = green_int;
  190294. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190295. }
  190296. }
  190297. #endif
  190298. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190299. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190300. defined(PNG_LEGACY_SUPPORTED)
  190301. void PNGAPI
  190302. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190303. read_user_transform_fn)
  190304. {
  190305. png_debug(1, "in png_set_read_user_transform_fn\n");
  190306. if(png_ptr == NULL) return;
  190307. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190308. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190309. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190310. #endif
  190311. #ifdef PNG_LEGACY_SUPPORTED
  190312. if(read_user_transform_fn)
  190313. png_warning(png_ptr,
  190314. "This version of libpng does not support user transforms");
  190315. #endif
  190316. }
  190317. #endif
  190318. /* Initialize everything needed for the read. This includes modifying
  190319. * the palette.
  190320. */
  190321. void /* PRIVATE */
  190322. png_init_read_transformations(png_structp png_ptr)
  190323. {
  190324. png_debug(1, "in png_init_read_transformations\n");
  190325. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190326. if(png_ptr != NULL)
  190327. #endif
  190328. {
  190329. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190330. || defined(PNG_READ_GAMMA_SUPPORTED)
  190331. int color_type = png_ptr->color_type;
  190332. #endif
  190333. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190334. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190335. /* Detect gray background and attempt to enable optimization
  190336. * for gray --> RGB case */
  190337. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190338. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190339. * background color might actually be gray yet not be flagged as such.
  190340. * This is not a problem for the current code, which uses
  190341. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190342. * png_do_gray_to_rgb() transformation.
  190343. */
  190344. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190345. !(color_type & PNG_COLOR_MASK_COLOR))
  190346. {
  190347. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190348. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190349. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190350. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190351. png_ptr->background.red == png_ptr->background.green &&
  190352. png_ptr->background.red == png_ptr->background.blue)
  190353. {
  190354. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190355. png_ptr->background.gray = png_ptr->background.red;
  190356. }
  190357. #endif
  190358. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190359. (png_ptr->transformations & PNG_EXPAND))
  190360. {
  190361. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190362. {
  190363. /* expand background and tRNS chunks */
  190364. switch (png_ptr->bit_depth)
  190365. {
  190366. case 1:
  190367. png_ptr->background.gray *= (png_uint_16)0xff;
  190368. png_ptr->background.red = png_ptr->background.green
  190369. = png_ptr->background.blue = png_ptr->background.gray;
  190370. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190371. {
  190372. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190373. png_ptr->trans_values.red = png_ptr->trans_values.green
  190374. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190375. }
  190376. break;
  190377. case 2:
  190378. png_ptr->background.gray *= (png_uint_16)0x55;
  190379. png_ptr->background.red = png_ptr->background.green
  190380. = png_ptr->background.blue = png_ptr->background.gray;
  190381. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190382. {
  190383. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190384. png_ptr->trans_values.red = png_ptr->trans_values.green
  190385. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190386. }
  190387. break;
  190388. case 4:
  190389. png_ptr->background.gray *= (png_uint_16)0x11;
  190390. png_ptr->background.red = png_ptr->background.green
  190391. = png_ptr->background.blue = png_ptr->background.gray;
  190392. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190393. {
  190394. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190395. png_ptr->trans_values.red = png_ptr->trans_values.green
  190396. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190397. }
  190398. break;
  190399. case 8:
  190400. case 16:
  190401. png_ptr->background.red = png_ptr->background.green
  190402. = png_ptr->background.blue = png_ptr->background.gray;
  190403. break;
  190404. }
  190405. }
  190406. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190407. {
  190408. png_ptr->background.red =
  190409. png_ptr->palette[png_ptr->background.index].red;
  190410. png_ptr->background.green =
  190411. png_ptr->palette[png_ptr->background.index].green;
  190412. png_ptr->background.blue =
  190413. png_ptr->palette[png_ptr->background.index].blue;
  190414. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190415. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190416. {
  190417. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190418. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190419. #endif
  190420. {
  190421. /* invert the alpha channel (in tRNS) unless the pixels are
  190422. going to be expanded, in which case leave it for later */
  190423. int i,istop;
  190424. istop=(int)png_ptr->num_trans;
  190425. for (i=0; i<istop; i++)
  190426. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190427. }
  190428. }
  190429. #endif
  190430. }
  190431. }
  190432. #endif
  190433. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190434. png_ptr->background_1 = png_ptr->background;
  190435. #endif
  190436. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190437. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190438. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190439. < PNG_GAMMA_THRESHOLD))
  190440. {
  190441. int i,k;
  190442. k=0;
  190443. for (i=0; i<png_ptr->num_trans; i++)
  190444. {
  190445. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190446. k=1; /* partial transparency is present */
  190447. }
  190448. if (k == 0)
  190449. png_ptr->transformations &= (~PNG_GAMMA);
  190450. }
  190451. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190452. png_ptr->gamma != 0.0)
  190453. {
  190454. png_build_gamma_table(png_ptr);
  190455. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190456. if (png_ptr->transformations & PNG_BACKGROUND)
  190457. {
  190458. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190459. {
  190460. /* could skip if no transparency and
  190461. */
  190462. png_color back, back_1;
  190463. png_colorp palette = png_ptr->palette;
  190464. int num_palette = png_ptr->num_palette;
  190465. int i;
  190466. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190467. {
  190468. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190469. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190470. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190471. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190472. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190473. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190474. }
  190475. else
  190476. {
  190477. double g, gs;
  190478. switch (png_ptr->background_gamma_type)
  190479. {
  190480. case PNG_BACKGROUND_GAMMA_SCREEN:
  190481. g = (png_ptr->screen_gamma);
  190482. gs = 1.0;
  190483. break;
  190484. case PNG_BACKGROUND_GAMMA_FILE:
  190485. g = 1.0 / (png_ptr->gamma);
  190486. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190487. break;
  190488. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190489. g = 1.0 / (png_ptr->background_gamma);
  190490. gs = 1.0 / (png_ptr->background_gamma *
  190491. png_ptr->screen_gamma);
  190492. break;
  190493. default:
  190494. g = 1.0; /* back_1 */
  190495. gs = 1.0; /* back */
  190496. }
  190497. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  190498. {
  190499. back.red = (png_byte)png_ptr->background.red;
  190500. back.green = (png_byte)png_ptr->background.green;
  190501. back.blue = (png_byte)png_ptr->background.blue;
  190502. }
  190503. else
  190504. {
  190505. back.red = (png_byte)(pow(
  190506. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  190507. back.green = (png_byte)(pow(
  190508. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  190509. back.blue = (png_byte)(pow(
  190510. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  190511. }
  190512. back_1.red = (png_byte)(pow(
  190513. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  190514. back_1.green = (png_byte)(pow(
  190515. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  190516. back_1.blue = (png_byte)(pow(
  190517. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  190518. }
  190519. for (i = 0; i < num_palette; i++)
  190520. {
  190521. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  190522. {
  190523. if (png_ptr->trans[i] == 0)
  190524. {
  190525. palette[i] = back;
  190526. }
  190527. else /* if (png_ptr->trans[i] != 0xff) */
  190528. {
  190529. png_byte v, w;
  190530. v = png_ptr->gamma_to_1[palette[i].red];
  190531. png_composite(w, v, png_ptr->trans[i], back_1.red);
  190532. palette[i].red = png_ptr->gamma_from_1[w];
  190533. v = png_ptr->gamma_to_1[palette[i].green];
  190534. png_composite(w, v, png_ptr->trans[i], back_1.green);
  190535. palette[i].green = png_ptr->gamma_from_1[w];
  190536. v = png_ptr->gamma_to_1[palette[i].blue];
  190537. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  190538. palette[i].blue = png_ptr->gamma_from_1[w];
  190539. }
  190540. }
  190541. else
  190542. {
  190543. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190544. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190545. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190546. }
  190547. }
  190548. }
  190549. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  190550. else
  190551. /* color_type != PNG_COLOR_TYPE_PALETTE */
  190552. {
  190553. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  190554. double g = 1.0;
  190555. double gs = 1.0;
  190556. switch (png_ptr->background_gamma_type)
  190557. {
  190558. case PNG_BACKGROUND_GAMMA_SCREEN:
  190559. g = (png_ptr->screen_gamma);
  190560. gs = 1.0;
  190561. break;
  190562. case PNG_BACKGROUND_GAMMA_FILE:
  190563. g = 1.0 / (png_ptr->gamma);
  190564. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190565. break;
  190566. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190567. g = 1.0 / (png_ptr->background_gamma);
  190568. gs = 1.0 / (png_ptr->background_gamma *
  190569. png_ptr->screen_gamma);
  190570. break;
  190571. }
  190572. png_ptr->background_1.gray = (png_uint_16)(pow(
  190573. (double)png_ptr->background.gray / m, g) * m + .5);
  190574. png_ptr->background.gray = (png_uint_16)(pow(
  190575. (double)png_ptr->background.gray / m, gs) * m + .5);
  190576. if ((png_ptr->background.red != png_ptr->background.green) ||
  190577. (png_ptr->background.red != png_ptr->background.blue) ||
  190578. (png_ptr->background.red != png_ptr->background.gray))
  190579. {
  190580. /* RGB or RGBA with color background */
  190581. png_ptr->background_1.red = (png_uint_16)(pow(
  190582. (double)png_ptr->background.red / m, g) * m + .5);
  190583. png_ptr->background_1.green = (png_uint_16)(pow(
  190584. (double)png_ptr->background.green / m, g) * m + .5);
  190585. png_ptr->background_1.blue = (png_uint_16)(pow(
  190586. (double)png_ptr->background.blue / m, g) * m + .5);
  190587. png_ptr->background.red = (png_uint_16)(pow(
  190588. (double)png_ptr->background.red / m, gs) * m + .5);
  190589. png_ptr->background.green = (png_uint_16)(pow(
  190590. (double)png_ptr->background.green / m, gs) * m + .5);
  190591. png_ptr->background.blue = (png_uint_16)(pow(
  190592. (double)png_ptr->background.blue / m, gs) * m + .5);
  190593. }
  190594. else
  190595. {
  190596. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  190597. png_ptr->background_1.red = png_ptr->background_1.green
  190598. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  190599. png_ptr->background.red = png_ptr->background.green
  190600. = png_ptr->background.blue = png_ptr->background.gray;
  190601. }
  190602. }
  190603. }
  190604. else
  190605. /* transformation does not include PNG_BACKGROUND */
  190606. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190607. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190608. {
  190609. png_colorp palette = png_ptr->palette;
  190610. int num_palette = png_ptr->num_palette;
  190611. int i;
  190612. for (i = 0; i < num_palette; i++)
  190613. {
  190614. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190615. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190616. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190617. }
  190618. }
  190619. }
  190620. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190621. else
  190622. #endif
  190623. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  190624. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190625. /* No GAMMA transformation */
  190626. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190627. (color_type == PNG_COLOR_TYPE_PALETTE))
  190628. {
  190629. int i;
  190630. int istop = (int)png_ptr->num_trans;
  190631. png_color back;
  190632. png_colorp palette = png_ptr->palette;
  190633. back.red = (png_byte)png_ptr->background.red;
  190634. back.green = (png_byte)png_ptr->background.green;
  190635. back.blue = (png_byte)png_ptr->background.blue;
  190636. for (i = 0; i < istop; i++)
  190637. {
  190638. if (png_ptr->trans[i] == 0)
  190639. {
  190640. palette[i] = back;
  190641. }
  190642. else if (png_ptr->trans[i] != 0xff)
  190643. {
  190644. /* The png_composite() macro is defined in png.h */
  190645. png_composite(palette[i].red, palette[i].red,
  190646. png_ptr->trans[i], back.red);
  190647. png_composite(palette[i].green, palette[i].green,
  190648. png_ptr->trans[i], back.green);
  190649. png_composite(palette[i].blue, palette[i].blue,
  190650. png_ptr->trans[i], back.blue);
  190651. }
  190652. }
  190653. }
  190654. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190655. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190656. if ((png_ptr->transformations & PNG_SHIFT) &&
  190657. (color_type == PNG_COLOR_TYPE_PALETTE))
  190658. {
  190659. png_uint_16 i;
  190660. png_uint_16 istop = png_ptr->num_palette;
  190661. int sr = 8 - png_ptr->sig_bit.red;
  190662. int sg = 8 - png_ptr->sig_bit.green;
  190663. int sb = 8 - png_ptr->sig_bit.blue;
  190664. if (sr < 0 || sr > 8)
  190665. sr = 0;
  190666. if (sg < 0 || sg > 8)
  190667. sg = 0;
  190668. if (sb < 0 || sb > 8)
  190669. sb = 0;
  190670. for (i = 0; i < istop; i++)
  190671. {
  190672. png_ptr->palette[i].red >>= sr;
  190673. png_ptr->palette[i].green >>= sg;
  190674. png_ptr->palette[i].blue >>= sb;
  190675. }
  190676. }
  190677. #endif /* PNG_READ_SHIFT_SUPPORTED */
  190678. }
  190679. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  190680. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  190681. if(png_ptr)
  190682. return;
  190683. #endif
  190684. }
  190685. /* Modify the info structure to reflect the transformations. The
  190686. * info should be updated so a PNG file could be written with it,
  190687. * assuming the transformations result in valid PNG data.
  190688. */
  190689. void /* PRIVATE */
  190690. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  190691. {
  190692. png_debug(1, "in png_read_transform_info\n");
  190693. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190694. if (png_ptr->transformations & PNG_EXPAND)
  190695. {
  190696. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190697. {
  190698. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  190699. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  190700. else
  190701. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  190702. info_ptr->bit_depth = 8;
  190703. info_ptr->num_trans = 0;
  190704. }
  190705. else
  190706. {
  190707. if (png_ptr->num_trans)
  190708. {
  190709. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  190710. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190711. else
  190712. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190713. }
  190714. if (info_ptr->bit_depth < 8)
  190715. info_ptr->bit_depth = 8;
  190716. info_ptr->num_trans = 0;
  190717. }
  190718. }
  190719. #endif
  190720. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190721. if (png_ptr->transformations & PNG_BACKGROUND)
  190722. {
  190723. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190724. info_ptr->num_trans = 0;
  190725. info_ptr->background = png_ptr->background;
  190726. }
  190727. #endif
  190728. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190729. if (png_ptr->transformations & PNG_GAMMA)
  190730. {
  190731. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190732. info_ptr->gamma = png_ptr->gamma;
  190733. #endif
  190734. #ifdef PNG_FIXED_POINT_SUPPORTED
  190735. info_ptr->int_gamma = png_ptr->int_gamma;
  190736. #endif
  190737. }
  190738. #endif
  190739. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190740. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  190741. info_ptr->bit_depth = 8;
  190742. #endif
  190743. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190744. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  190745. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190746. #endif
  190747. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190748. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190749. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  190750. #endif
  190751. #if defined(PNG_READ_DITHER_SUPPORTED)
  190752. if (png_ptr->transformations & PNG_DITHER)
  190753. {
  190754. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190755. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  190756. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  190757. {
  190758. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  190759. }
  190760. }
  190761. #endif
  190762. #if defined(PNG_READ_PACK_SUPPORTED)
  190763. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  190764. info_ptr->bit_depth = 8;
  190765. #endif
  190766. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190767. info_ptr->channels = 1;
  190768. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190769. info_ptr->channels = 3;
  190770. else
  190771. info_ptr->channels = 1;
  190772. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190773. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190774. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190775. #endif
  190776. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  190777. info_ptr->channels++;
  190778. #if defined(PNG_READ_FILLER_SUPPORTED)
  190779. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  190780. if ((png_ptr->transformations & PNG_FILLER) &&
  190781. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190782. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  190783. {
  190784. info_ptr->channels++;
  190785. /* if adding a true alpha channel not just filler */
  190786. #if !defined(PNG_1_0_X)
  190787. if (png_ptr->transformations & PNG_ADD_ALPHA)
  190788. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190789. #endif
  190790. }
  190791. #endif
  190792. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  190793. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190794. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  190795. {
  190796. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  190797. info_ptr->bit_depth = png_ptr->user_transform_depth;
  190798. if(info_ptr->channels < png_ptr->user_transform_channels)
  190799. info_ptr->channels = png_ptr->user_transform_channels;
  190800. }
  190801. #endif
  190802. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  190803. info_ptr->bit_depth);
  190804. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  190805. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  190806. if(png_ptr)
  190807. return;
  190808. #endif
  190809. }
  190810. /* Transform the row. The order of transformations is significant,
  190811. * and is very touchy. If you add a transformation, take care to
  190812. * decide how it fits in with the other transformations here.
  190813. */
  190814. void /* PRIVATE */
  190815. png_do_read_transformations(png_structp png_ptr)
  190816. {
  190817. png_debug(1, "in png_do_read_transformations\n");
  190818. if (png_ptr->row_buf == NULL)
  190819. {
  190820. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  190821. char msg[50];
  190822. png_snprintf2(msg, 50,
  190823. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  190824. png_ptr->pass);
  190825. png_error(png_ptr, msg);
  190826. #else
  190827. png_error(png_ptr, "NULL row buffer");
  190828. #endif
  190829. }
  190830. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190831. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  190832. /* Application has failed to call either png_read_start_image()
  190833. * or png_read_update_info() after setting transforms that expand
  190834. * pixels. This check added to libpng-1.2.19 */
  190835. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  190836. png_error(png_ptr, "Uninitialized row");
  190837. #else
  190838. png_warning(png_ptr, "Uninitialized row");
  190839. #endif
  190840. #endif
  190841. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190842. if (png_ptr->transformations & PNG_EXPAND)
  190843. {
  190844. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  190845. {
  190846. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190847. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  190848. }
  190849. else
  190850. {
  190851. if (png_ptr->num_trans &&
  190852. (png_ptr->transformations & PNG_EXPAND_tRNS))
  190853. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190854. &(png_ptr->trans_values));
  190855. else
  190856. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190857. NULL);
  190858. }
  190859. }
  190860. #endif
  190861. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190862. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190863. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190864. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  190865. #endif
  190866. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190867. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190868. {
  190869. int rgb_error =
  190870. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  190871. if(rgb_error)
  190872. {
  190873. png_ptr->rgb_to_gray_status=1;
  190874. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190875. PNG_RGB_TO_GRAY_WARN)
  190876. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190877. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190878. PNG_RGB_TO_GRAY_ERR)
  190879. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190880. }
  190881. }
  190882. #endif
  190883. /*
  190884. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  190885. In most cases, the "simple transparency" should be done prior to doing
  190886. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  190887. pixel is transparent. You would also need to make sure that the
  190888. transparency information is upgraded to RGB.
  190889. To summarize, the current flow is:
  190890. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  190891. with background "in place" if transparent,
  190892. convert to RGB if necessary
  190893. - Gray + alpha -> composite with gray background and remove alpha bytes,
  190894. convert to RGB if necessary
  190895. To support RGB backgrounds for gray images we need:
  190896. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  190897. 3 or 6 bytes and composite with background
  190898. "in place" if transparent (3x compare/pixel
  190899. compared to doing composite with gray bkgrnd)
  190900. - Gray + alpha -> convert to RGB + alpha, composite with background and
  190901. remove alpha bytes (3x float operations/pixel
  190902. compared with composite on gray background)
  190903. Greg's change will do this. The reason it wasn't done before is for
  190904. performance, as this increases the per-pixel operations. If we would check
  190905. in advance if the background was gray or RGB, and position the gray-to-RGB
  190906. transform appropriately, then it would save a lot of work/time.
  190907. */
  190908. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190909. /* if gray -> RGB, do so now only if background is non-gray; else do later
  190910. * for performance reasons */
  190911. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190912. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190913. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190914. #endif
  190915. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190916. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190917. ((png_ptr->num_trans != 0 ) ||
  190918. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  190919. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190920. &(png_ptr->trans_values), &(png_ptr->background)
  190921. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190922. , &(png_ptr->background_1),
  190923. png_ptr->gamma_table, png_ptr->gamma_from_1,
  190924. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  190925. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  190926. png_ptr->gamma_shift
  190927. #endif
  190928. );
  190929. #endif
  190930. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190931. if ((png_ptr->transformations & PNG_GAMMA) &&
  190932. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190933. !((png_ptr->transformations & PNG_BACKGROUND) &&
  190934. ((png_ptr->num_trans != 0) ||
  190935. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  190936. #endif
  190937. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  190938. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190939. png_ptr->gamma_table, png_ptr->gamma_16_table,
  190940. png_ptr->gamma_shift);
  190941. #endif
  190942. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190943. if (png_ptr->transformations & PNG_16_TO_8)
  190944. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190945. #endif
  190946. #if defined(PNG_READ_DITHER_SUPPORTED)
  190947. if (png_ptr->transformations & PNG_DITHER)
  190948. {
  190949. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  190950. png_ptr->palette_lookup, png_ptr->dither_index);
  190951. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  190952. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  190953. }
  190954. #endif
  190955. #if defined(PNG_READ_INVERT_SUPPORTED)
  190956. if (png_ptr->transformations & PNG_INVERT_MONO)
  190957. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190958. #endif
  190959. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190960. if (png_ptr->transformations & PNG_SHIFT)
  190961. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190962. &(png_ptr->shift));
  190963. #endif
  190964. #if defined(PNG_READ_PACK_SUPPORTED)
  190965. if (png_ptr->transformations & PNG_PACK)
  190966. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190967. #endif
  190968. #if defined(PNG_READ_BGR_SUPPORTED)
  190969. if (png_ptr->transformations & PNG_BGR)
  190970. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190971. #endif
  190972. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190973. if (png_ptr->transformations & PNG_PACKSWAP)
  190974. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190975. #endif
  190976. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190977. /* if gray -> RGB, do so now only if we did not do so above */
  190978. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190979. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190980. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190981. #endif
  190982. #if defined(PNG_READ_FILLER_SUPPORTED)
  190983. if (png_ptr->transformations & PNG_FILLER)
  190984. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190985. (png_uint_32)png_ptr->filler, png_ptr->flags);
  190986. #endif
  190987. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190988. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190989. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190990. #endif
  190991. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  190992. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  190993. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190994. #endif
  190995. #if defined(PNG_READ_SWAP_SUPPORTED)
  190996. if (png_ptr->transformations & PNG_SWAP_BYTES)
  190997. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190998. #endif
  190999. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191000. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  191001. {
  191002. if(png_ptr->read_user_transform_fn != NULL)
  191003. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  191004. (png_ptr, /* png_ptr */
  191005. &(png_ptr->row_info), /* row_info: */
  191006. /* png_uint_32 width; width of row */
  191007. /* png_uint_32 rowbytes; number of bytes in row */
  191008. /* png_byte color_type; color type of pixels */
  191009. /* png_byte bit_depth; bit depth of samples */
  191010. /* png_byte channels; number of channels (1-4) */
  191011. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  191012. png_ptr->row_buf + 1); /* start of pixel data for row */
  191013. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191014. if(png_ptr->user_transform_depth)
  191015. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  191016. if(png_ptr->user_transform_channels)
  191017. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  191018. #endif
  191019. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191020. png_ptr->row_info.channels);
  191021. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191022. png_ptr->row_info.width);
  191023. }
  191024. #endif
  191025. }
  191026. #if defined(PNG_READ_PACK_SUPPORTED)
  191027. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191028. * without changing the actual values. Thus, if you had a row with
  191029. * a bit depth of 1, you would end up with bytes that only contained
  191030. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191031. * png_do_shift() after this.
  191032. */
  191033. void /* PRIVATE */
  191034. png_do_unpack(png_row_infop row_info, png_bytep row)
  191035. {
  191036. png_debug(1, "in png_do_unpack\n");
  191037. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191038. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191039. #else
  191040. if (row_info->bit_depth < 8)
  191041. #endif
  191042. {
  191043. png_uint_32 i;
  191044. png_uint_32 row_width=row_info->width;
  191045. switch (row_info->bit_depth)
  191046. {
  191047. case 1:
  191048. {
  191049. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191050. png_bytep dp = row + (png_size_t)row_width - 1;
  191051. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191052. for (i = 0; i < row_width; i++)
  191053. {
  191054. *dp = (png_byte)((*sp >> shift) & 0x01);
  191055. if (shift == 7)
  191056. {
  191057. shift = 0;
  191058. sp--;
  191059. }
  191060. else
  191061. shift++;
  191062. dp--;
  191063. }
  191064. break;
  191065. }
  191066. case 2:
  191067. {
  191068. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191069. png_bytep dp = row + (png_size_t)row_width - 1;
  191070. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191071. for (i = 0; i < row_width; i++)
  191072. {
  191073. *dp = (png_byte)((*sp >> shift) & 0x03);
  191074. if (shift == 6)
  191075. {
  191076. shift = 0;
  191077. sp--;
  191078. }
  191079. else
  191080. shift += 2;
  191081. dp--;
  191082. }
  191083. break;
  191084. }
  191085. case 4:
  191086. {
  191087. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191088. png_bytep dp = row + (png_size_t)row_width - 1;
  191089. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191090. for (i = 0; i < row_width; i++)
  191091. {
  191092. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191093. if (shift == 4)
  191094. {
  191095. shift = 0;
  191096. sp--;
  191097. }
  191098. else
  191099. shift = 4;
  191100. dp--;
  191101. }
  191102. break;
  191103. }
  191104. }
  191105. row_info->bit_depth = 8;
  191106. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191107. row_info->rowbytes = row_width * row_info->channels;
  191108. }
  191109. }
  191110. #endif
  191111. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191112. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191113. * pixels back to their significant bits values. Thus, if you have
  191114. * a row of bit depth 8, but only 5 are significant, this will shift
  191115. * the values back to 0 through 31.
  191116. */
  191117. void /* PRIVATE */
  191118. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191119. {
  191120. png_debug(1, "in png_do_unshift\n");
  191121. if (
  191122. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191123. row != NULL && row_info != NULL && sig_bits != NULL &&
  191124. #endif
  191125. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191126. {
  191127. int shift[4];
  191128. int channels = 0;
  191129. int c;
  191130. png_uint_16 value = 0;
  191131. png_uint_32 row_width = row_info->width;
  191132. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191133. {
  191134. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191135. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191136. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191137. }
  191138. else
  191139. {
  191140. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191141. }
  191142. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191143. {
  191144. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191145. }
  191146. for (c = 0; c < channels; c++)
  191147. {
  191148. if (shift[c] <= 0)
  191149. shift[c] = 0;
  191150. else
  191151. value = 1;
  191152. }
  191153. if (!value)
  191154. return;
  191155. switch (row_info->bit_depth)
  191156. {
  191157. case 2:
  191158. {
  191159. png_bytep bp;
  191160. png_uint_32 i;
  191161. png_uint_32 istop = row_info->rowbytes;
  191162. for (bp = row, i = 0; i < istop; i++)
  191163. {
  191164. *bp >>= 1;
  191165. *bp++ &= 0x55;
  191166. }
  191167. break;
  191168. }
  191169. case 4:
  191170. {
  191171. png_bytep bp = row;
  191172. png_uint_32 i;
  191173. png_uint_32 istop = row_info->rowbytes;
  191174. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191175. (png_byte)((int)0xf >> shift[0]));
  191176. for (i = 0; i < istop; i++)
  191177. {
  191178. *bp >>= shift[0];
  191179. *bp++ &= mask;
  191180. }
  191181. break;
  191182. }
  191183. case 8:
  191184. {
  191185. png_bytep bp = row;
  191186. png_uint_32 i;
  191187. png_uint_32 istop = row_width * channels;
  191188. for (i = 0; i < istop; i++)
  191189. {
  191190. *bp++ >>= shift[i%channels];
  191191. }
  191192. break;
  191193. }
  191194. case 16:
  191195. {
  191196. png_bytep bp = row;
  191197. png_uint_32 i;
  191198. png_uint_32 istop = channels * row_width;
  191199. for (i = 0; i < istop; i++)
  191200. {
  191201. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191202. value >>= shift[i%channels];
  191203. *bp++ = (png_byte)(value >> 8);
  191204. *bp++ = (png_byte)(value & 0xff);
  191205. }
  191206. break;
  191207. }
  191208. }
  191209. }
  191210. }
  191211. #endif
  191212. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191213. /* chop rows of bit depth 16 down to 8 */
  191214. void /* PRIVATE */
  191215. png_do_chop(png_row_infop row_info, png_bytep row)
  191216. {
  191217. png_debug(1, "in png_do_chop\n");
  191218. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191219. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191220. #else
  191221. if (row_info->bit_depth == 16)
  191222. #endif
  191223. {
  191224. png_bytep sp = row;
  191225. png_bytep dp = row;
  191226. png_uint_32 i;
  191227. png_uint_32 istop = row_info->width * row_info->channels;
  191228. for (i = 0; i<istop; i++, sp += 2, dp++)
  191229. {
  191230. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191231. /* This does a more accurate scaling of the 16-bit color
  191232. * value, rather than a simple low-byte truncation.
  191233. *
  191234. * What the ideal calculation should be:
  191235. * *dp = (((((png_uint_32)(*sp) << 8) |
  191236. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191237. *
  191238. * GRR: no, I think this is what it really should be:
  191239. * *dp = (((((png_uint_32)(*sp) << 8) |
  191240. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191241. *
  191242. * GRR: here's the exact calculation with shifts:
  191243. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191244. * *dp = (temp - (temp >> 8)) >> 8;
  191245. *
  191246. * Approximate calculation with shift/add instead of multiply/divide:
  191247. * *dp = ((((png_uint_32)(*sp) << 8) |
  191248. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191249. *
  191250. * What we actually do to avoid extra shifting and conversion:
  191251. */
  191252. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191253. #else
  191254. /* Simply discard the low order byte */
  191255. *dp = *sp;
  191256. #endif
  191257. }
  191258. row_info->bit_depth = 8;
  191259. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191260. row_info->rowbytes = row_info->width * row_info->channels;
  191261. }
  191262. }
  191263. #endif
  191264. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191265. void /* PRIVATE */
  191266. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191267. {
  191268. png_debug(1, "in png_do_read_swap_alpha\n");
  191269. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191270. if (row != NULL && row_info != NULL)
  191271. #endif
  191272. {
  191273. png_uint_32 row_width = row_info->width;
  191274. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191275. {
  191276. /* This converts from RGBA to ARGB */
  191277. if (row_info->bit_depth == 8)
  191278. {
  191279. png_bytep sp = row + row_info->rowbytes;
  191280. png_bytep dp = sp;
  191281. png_byte save;
  191282. png_uint_32 i;
  191283. for (i = 0; i < row_width; i++)
  191284. {
  191285. save = *(--sp);
  191286. *(--dp) = *(--sp);
  191287. *(--dp) = *(--sp);
  191288. *(--dp) = *(--sp);
  191289. *(--dp) = save;
  191290. }
  191291. }
  191292. /* This converts from RRGGBBAA to AARRGGBB */
  191293. else
  191294. {
  191295. png_bytep sp = row + row_info->rowbytes;
  191296. png_bytep dp = sp;
  191297. png_byte save[2];
  191298. png_uint_32 i;
  191299. for (i = 0; i < row_width; i++)
  191300. {
  191301. save[0] = *(--sp);
  191302. save[1] = *(--sp);
  191303. *(--dp) = *(--sp);
  191304. *(--dp) = *(--sp);
  191305. *(--dp) = *(--sp);
  191306. *(--dp) = *(--sp);
  191307. *(--dp) = *(--sp);
  191308. *(--dp) = *(--sp);
  191309. *(--dp) = save[0];
  191310. *(--dp) = save[1];
  191311. }
  191312. }
  191313. }
  191314. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191315. {
  191316. /* This converts from GA to AG */
  191317. if (row_info->bit_depth == 8)
  191318. {
  191319. png_bytep sp = row + row_info->rowbytes;
  191320. png_bytep dp = sp;
  191321. png_byte save;
  191322. png_uint_32 i;
  191323. for (i = 0; i < row_width; i++)
  191324. {
  191325. save = *(--sp);
  191326. *(--dp) = *(--sp);
  191327. *(--dp) = save;
  191328. }
  191329. }
  191330. /* This converts from GGAA to AAGG */
  191331. else
  191332. {
  191333. png_bytep sp = row + row_info->rowbytes;
  191334. png_bytep dp = sp;
  191335. png_byte save[2];
  191336. png_uint_32 i;
  191337. for (i = 0; i < row_width; i++)
  191338. {
  191339. save[0] = *(--sp);
  191340. save[1] = *(--sp);
  191341. *(--dp) = *(--sp);
  191342. *(--dp) = *(--sp);
  191343. *(--dp) = save[0];
  191344. *(--dp) = save[1];
  191345. }
  191346. }
  191347. }
  191348. }
  191349. }
  191350. #endif
  191351. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191352. void /* PRIVATE */
  191353. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191354. {
  191355. png_debug(1, "in png_do_read_invert_alpha\n");
  191356. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191357. if (row != NULL && row_info != NULL)
  191358. #endif
  191359. {
  191360. png_uint_32 row_width = row_info->width;
  191361. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191362. {
  191363. /* This inverts the alpha channel in RGBA */
  191364. if (row_info->bit_depth == 8)
  191365. {
  191366. png_bytep sp = row + row_info->rowbytes;
  191367. png_bytep dp = sp;
  191368. png_uint_32 i;
  191369. for (i = 0; i < row_width; i++)
  191370. {
  191371. *(--dp) = (png_byte)(255 - *(--sp));
  191372. /* This does nothing:
  191373. *(--dp) = *(--sp);
  191374. *(--dp) = *(--sp);
  191375. *(--dp) = *(--sp);
  191376. We can replace it with:
  191377. */
  191378. sp-=3;
  191379. dp=sp;
  191380. }
  191381. }
  191382. /* This inverts the alpha channel in RRGGBBAA */
  191383. else
  191384. {
  191385. png_bytep sp = row + row_info->rowbytes;
  191386. png_bytep dp = sp;
  191387. png_uint_32 i;
  191388. for (i = 0; i < row_width; i++)
  191389. {
  191390. *(--dp) = (png_byte)(255 - *(--sp));
  191391. *(--dp) = (png_byte)(255 - *(--sp));
  191392. /* This does nothing:
  191393. *(--dp) = *(--sp);
  191394. *(--dp) = *(--sp);
  191395. *(--dp) = *(--sp);
  191396. *(--dp) = *(--sp);
  191397. *(--dp) = *(--sp);
  191398. *(--dp) = *(--sp);
  191399. We can replace it with:
  191400. */
  191401. sp-=6;
  191402. dp=sp;
  191403. }
  191404. }
  191405. }
  191406. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191407. {
  191408. /* This inverts the alpha channel in GA */
  191409. if (row_info->bit_depth == 8)
  191410. {
  191411. png_bytep sp = row + row_info->rowbytes;
  191412. png_bytep dp = sp;
  191413. png_uint_32 i;
  191414. for (i = 0; i < row_width; i++)
  191415. {
  191416. *(--dp) = (png_byte)(255 - *(--sp));
  191417. *(--dp) = *(--sp);
  191418. }
  191419. }
  191420. /* This inverts the alpha channel in GGAA */
  191421. else
  191422. {
  191423. png_bytep sp = row + row_info->rowbytes;
  191424. png_bytep dp = sp;
  191425. png_uint_32 i;
  191426. for (i = 0; i < row_width; i++)
  191427. {
  191428. *(--dp) = (png_byte)(255 - *(--sp));
  191429. *(--dp) = (png_byte)(255 - *(--sp));
  191430. /*
  191431. *(--dp) = *(--sp);
  191432. *(--dp) = *(--sp);
  191433. */
  191434. sp-=2;
  191435. dp=sp;
  191436. }
  191437. }
  191438. }
  191439. }
  191440. }
  191441. #endif
  191442. #if defined(PNG_READ_FILLER_SUPPORTED)
  191443. /* Add filler channel if we have RGB color */
  191444. void /* PRIVATE */
  191445. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191446. png_uint_32 filler, png_uint_32 flags)
  191447. {
  191448. png_uint_32 i;
  191449. png_uint_32 row_width = row_info->width;
  191450. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191451. png_byte lo_filler = (png_byte)(filler & 0xff);
  191452. png_debug(1, "in png_do_read_filler\n");
  191453. if (
  191454. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191455. row != NULL && row_info != NULL &&
  191456. #endif
  191457. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191458. {
  191459. if(row_info->bit_depth == 8)
  191460. {
  191461. /* This changes the data from G to GX */
  191462. if (flags & PNG_FLAG_FILLER_AFTER)
  191463. {
  191464. png_bytep sp = row + (png_size_t)row_width;
  191465. png_bytep dp = sp + (png_size_t)row_width;
  191466. for (i = 1; i < row_width; i++)
  191467. {
  191468. *(--dp) = lo_filler;
  191469. *(--dp) = *(--sp);
  191470. }
  191471. *(--dp) = lo_filler;
  191472. row_info->channels = 2;
  191473. row_info->pixel_depth = 16;
  191474. row_info->rowbytes = row_width * 2;
  191475. }
  191476. /* This changes the data from G to XG */
  191477. else
  191478. {
  191479. png_bytep sp = row + (png_size_t)row_width;
  191480. png_bytep dp = sp + (png_size_t)row_width;
  191481. for (i = 0; i < row_width; i++)
  191482. {
  191483. *(--dp) = *(--sp);
  191484. *(--dp) = lo_filler;
  191485. }
  191486. row_info->channels = 2;
  191487. row_info->pixel_depth = 16;
  191488. row_info->rowbytes = row_width * 2;
  191489. }
  191490. }
  191491. else if(row_info->bit_depth == 16)
  191492. {
  191493. /* This changes the data from GG to GGXX */
  191494. if (flags & PNG_FLAG_FILLER_AFTER)
  191495. {
  191496. png_bytep sp = row + (png_size_t)row_width * 2;
  191497. png_bytep dp = sp + (png_size_t)row_width * 2;
  191498. for (i = 1; i < row_width; i++)
  191499. {
  191500. *(--dp) = hi_filler;
  191501. *(--dp) = lo_filler;
  191502. *(--dp) = *(--sp);
  191503. *(--dp) = *(--sp);
  191504. }
  191505. *(--dp) = hi_filler;
  191506. *(--dp) = lo_filler;
  191507. row_info->channels = 2;
  191508. row_info->pixel_depth = 32;
  191509. row_info->rowbytes = row_width * 4;
  191510. }
  191511. /* This changes the data from GG to XXGG */
  191512. else
  191513. {
  191514. png_bytep sp = row + (png_size_t)row_width * 2;
  191515. png_bytep dp = sp + (png_size_t)row_width * 2;
  191516. for (i = 0; i < row_width; i++)
  191517. {
  191518. *(--dp) = *(--sp);
  191519. *(--dp) = *(--sp);
  191520. *(--dp) = hi_filler;
  191521. *(--dp) = lo_filler;
  191522. }
  191523. row_info->channels = 2;
  191524. row_info->pixel_depth = 32;
  191525. row_info->rowbytes = row_width * 4;
  191526. }
  191527. }
  191528. } /* COLOR_TYPE == GRAY */
  191529. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191530. {
  191531. if(row_info->bit_depth == 8)
  191532. {
  191533. /* This changes the data from RGB to RGBX */
  191534. if (flags & PNG_FLAG_FILLER_AFTER)
  191535. {
  191536. png_bytep sp = row + (png_size_t)row_width * 3;
  191537. png_bytep dp = sp + (png_size_t)row_width;
  191538. for (i = 1; i < row_width; i++)
  191539. {
  191540. *(--dp) = lo_filler;
  191541. *(--dp) = *(--sp);
  191542. *(--dp) = *(--sp);
  191543. *(--dp) = *(--sp);
  191544. }
  191545. *(--dp) = lo_filler;
  191546. row_info->channels = 4;
  191547. row_info->pixel_depth = 32;
  191548. row_info->rowbytes = row_width * 4;
  191549. }
  191550. /* This changes the data from RGB to XRGB */
  191551. else
  191552. {
  191553. png_bytep sp = row + (png_size_t)row_width * 3;
  191554. png_bytep dp = sp + (png_size_t)row_width;
  191555. for (i = 0; i < row_width; i++)
  191556. {
  191557. *(--dp) = *(--sp);
  191558. *(--dp) = *(--sp);
  191559. *(--dp) = *(--sp);
  191560. *(--dp) = lo_filler;
  191561. }
  191562. row_info->channels = 4;
  191563. row_info->pixel_depth = 32;
  191564. row_info->rowbytes = row_width * 4;
  191565. }
  191566. }
  191567. else if(row_info->bit_depth == 16)
  191568. {
  191569. /* This changes the data from RRGGBB to RRGGBBXX */
  191570. if (flags & PNG_FLAG_FILLER_AFTER)
  191571. {
  191572. png_bytep sp = row + (png_size_t)row_width * 6;
  191573. png_bytep dp = sp + (png_size_t)row_width * 2;
  191574. for (i = 1; i < row_width; i++)
  191575. {
  191576. *(--dp) = hi_filler;
  191577. *(--dp) = lo_filler;
  191578. *(--dp) = *(--sp);
  191579. *(--dp) = *(--sp);
  191580. *(--dp) = *(--sp);
  191581. *(--dp) = *(--sp);
  191582. *(--dp) = *(--sp);
  191583. *(--dp) = *(--sp);
  191584. }
  191585. *(--dp) = hi_filler;
  191586. *(--dp) = lo_filler;
  191587. row_info->channels = 4;
  191588. row_info->pixel_depth = 64;
  191589. row_info->rowbytes = row_width * 8;
  191590. }
  191591. /* This changes the data from RRGGBB to XXRRGGBB */
  191592. else
  191593. {
  191594. png_bytep sp = row + (png_size_t)row_width * 6;
  191595. png_bytep dp = sp + (png_size_t)row_width * 2;
  191596. for (i = 0; i < row_width; i++)
  191597. {
  191598. *(--dp) = *(--sp);
  191599. *(--dp) = *(--sp);
  191600. *(--dp) = *(--sp);
  191601. *(--dp) = *(--sp);
  191602. *(--dp) = *(--sp);
  191603. *(--dp) = *(--sp);
  191604. *(--dp) = hi_filler;
  191605. *(--dp) = lo_filler;
  191606. }
  191607. row_info->channels = 4;
  191608. row_info->pixel_depth = 64;
  191609. row_info->rowbytes = row_width * 8;
  191610. }
  191611. }
  191612. } /* COLOR_TYPE == RGB */
  191613. }
  191614. #endif
  191615. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191616. /* expand grayscale files to RGB, with or without alpha */
  191617. void /* PRIVATE */
  191618. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  191619. {
  191620. png_uint_32 i;
  191621. png_uint_32 row_width = row_info->width;
  191622. png_debug(1, "in png_do_gray_to_rgb\n");
  191623. if (row_info->bit_depth >= 8 &&
  191624. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191625. row != NULL && row_info != NULL &&
  191626. #endif
  191627. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  191628. {
  191629. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191630. {
  191631. if (row_info->bit_depth == 8)
  191632. {
  191633. png_bytep sp = row + (png_size_t)row_width - 1;
  191634. png_bytep dp = sp + (png_size_t)row_width * 2;
  191635. for (i = 0; i < row_width; i++)
  191636. {
  191637. *(dp--) = *sp;
  191638. *(dp--) = *sp;
  191639. *(dp--) = *(sp--);
  191640. }
  191641. }
  191642. else
  191643. {
  191644. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191645. png_bytep dp = sp + (png_size_t)row_width * 4;
  191646. for (i = 0; i < row_width; i++)
  191647. {
  191648. *(dp--) = *sp;
  191649. *(dp--) = *(sp - 1);
  191650. *(dp--) = *sp;
  191651. *(dp--) = *(sp - 1);
  191652. *(dp--) = *(sp--);
  191653. *(dp--) = *(sp--);
  191654. }
  191655. }
  191656. }
  191657. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191658. {
  191659. if (row_info->bit_depth == 8)
  191660. {
  191661. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191662. png_bytep dp = sp + (png_size_t)row_width * 2;
  191663. for (i = 0; i < row_width; i++)
  191664. {
  191665. *(dp--) = *(sp--);
  191666. *(dp--) = *sp;
  191667. *(dp--) = *sp;
  191668. *(dp--) = *(sp--);
  191669. }
  191670. }
  191671. else
  191672. {
  191673. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  191674. png_bytep dp = sp + (png_size_t)row_width * 4;
  191675. for (i = 0; i < row_width; i++)
  191676. {
  191677. *(dp--) = *(sp--);
  191678. *(dp--) = *(sp--);
  191679. *(dp--) = *sp;
  191680. *(dp--) = *(sp - 1);
  191681. *(dp--) = *sp;
  191682. *(dp--) = *(sp - 1);
  191683. *(dp--) = *(sp--);
  191684. *(dp--) = *(sp--);
  191685. }
  191686. }
  191687. }
  191688. row_info->channels += (png_byte)2;
  191689. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  191690. row_info->pixel_depth = (png_byte)(row_info->channels *
  191691. row_info->bit_depth);
  191692. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191693. }
  191694. }
  191695. #endif
  191696. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191697. /* reduce RGB files to grayscale, with or without alpha
  191698. * using the equation given in Poynton's ColorFAQ at
  191699. * <http://www.inforamp.net/~poynton/>
  191700. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  191701. *
  191702. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  191703. *
  191704. * We approximate this with
  191705. *
  191706. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  191707. *
  191708. * which can be expressed with integers as
  191709. *
  191710. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  191711. *
  191712. * The calculation is to be done in a linear colorspace.
  191713. *
  191714. * Other integer coefficents can be used via png_set_rgb_to_gray().
  191715. */
  191716. int /* PRIVATE */
  191717. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  191718. {
  191719. png_uint_32 i;
  191720. png_uint_32 row_width = row_info->width;
  191721. int rgb_error = 0;
  191722. png_debug(1, "in png_do_rgb_to_gray\n");
  191723. if (
  191724. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191725. row != NULL && row_info != NULL &&
  191726. #endif
  191727. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  191728. {
  191729. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  191730. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  191731. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  191732. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191733. {
  191734. if (row_info->bit_depth == 8)
  191735. {
  191736. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191737. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191738. {
  191739. png_bytep sp = row;
  191740. png_bytep dp = row;
  191741. for (i = 0; i < row_width; i++)
  191742. {
  191743. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191744. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191745. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191746. if(red != green || red != blue)
  191747. {
  191748. rgb_error |= 1;
  191749. *(dp++) = png_ptr->gamma_from_1[
  191750. (rc*red+gc*green+bc*blue)>>15];
  191751. }
  191752. else
  191753. *(dp++) = *(sp-1);
  191754. }
  191755. }
  191756. else
  191757. #endif
  191758. {
  191759. png_bytep sp = row;
  191760. png_bytep dp = row;
  191761. for (i = 0; i < row_width; i++)
  191762. {
  191763. png_byte red = *(sp++);
  191764. png_byte green = *(sp++);
  191765. png_byte blue = *(sp++);
  191766. if(red != green || red != blue)
  191767. {
  191768. rgb_error |= 1;
  191769. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  191770. }
  191771. else
  191772. *(dp++) = *(sp-1);
  191773. }
  191774. }
  191775. }
  191776. else /* RGB bit_depth == 16 */
  191777. {
  191778. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191779. if (png_ptr->gamma_16_to_1 != NULL &&
  191780. png_ptr->gamma_16_from_1 != NULL)
  191781. {
  191782. png_bytep sp = row;
  191783. png_bytep dp = row;
  191784. for (i = 0; i < row_width; i++)
  191785. {
  191786. png_uint_16 red, green, blue, w;
  191787. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191788. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191789. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191790. if(red == green && red == blue)
  191791. w = red;
  191792. else
  191793. {
  191794. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191795. png_ptr->gamma_shift][red>>8];
  191796. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191797. png_ptr->gamma_shift][green>>8];
  191798. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191799. png_ptr->gamma_shift][blue>>8];
  191800. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  191801. + bc*blue_1)>>15);
  191802. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191803. png_ptr->gamma_shift][gray16 >> 8];
  191804. rgb_error |= 1;
  191805. }
  191806. *(dp++) = (png_byte)((w>>8) & 0xff);
  191807. *(dp++) = (png_byte)(w & 0xff);
  191808. }
  191809. }
  191810. else
  191811. #endif
  191812. {
  191813. png_bytep sp = row;
  191814. png_bytep dp = row;
  191815. for (i = 0; i < row_width; i++)
  191816. {
  191817. png_uint_16 red, green, blue, gray16;
  191818. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191819. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191820. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191821. if(red != green || red != blue)
  191822. rgb_error |= 1;
  191823. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191824. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191825. *(dp++) = (png_byte)(gray16 & 0xff);
  191826. }
  191827. }
  191828. }
  191829. }
  191830. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191831. {
  191832. if (row_info->bit_depth == 8)
  191833. {
  191834. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191835. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191836. {
  191837. png_bytep sp = row;
  191838. png_bytep dp = row;
  191839. for (i = 0; i < row_width; i++)
  191840. {
  191841. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191842. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191843. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191844. if(red != green || red != blue)
  191845. rgb_error |= 1;
  191846. *(dp++) = png_ptr->gamma_from_1
  191847. [(rc*red + gc*green + bc*blue)>>15];
  191848. *(dp++) = *(sp++); /* alpha */
  191849. }
  191850. }
  191851. else
  191852. #endif
  191853. {
  191854. png_bytep sp = row;
  191855. png_bytep dp = row;
  191856. for (i = 0; i < row_width; i++)
  191857. {
  191858. png_byte red = *(sp++);
  191859. png_byte green = *(sp++);
  191860. png_byte blue = *(sp++);
  191861. if(red != green || red != blue)
  191862. rgb_error |= 1;
  191863. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  191864. *(dp++) = *(sp++); /* alpha */
  191865. }
  191866. }
  191867. }
  191868. else /* RGBA bit_depth == 16 */
  191869. {
  191870. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191871. if (png_ptr->gamma_16_to_1 != NULL &&
  191872. png_ptr->gamma_16_from_1 != NULL)
  191873. {
  191874. png_bytep sp = row;
  191875. png_bytep dp = row;
  191876. for (i = 0; i < row_width; i++)
  191877. {
  191878. png_uint_16 red, green, blue, w;
  191879. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191880. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191881. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191882. if(red == green && red == blue)
  191883. w = red;
  191884. else
  191885. {
  191886. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191887. png_ptr->gamma_shift][red>>8];
  191888. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191889. png_ptr->gamma_shift][green>>8];
  191890. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191891. png_ptr->gamma_shift][blue>>8];
  191892. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  191893. + gc * green_1 + bc * blue_1)>>15);
  191894. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191895. png_ptr->gamma_shift][gray16 >> 8];
  191896. rgb_error |= 1;
  191897. }
  191898. *(dp++) = (png_byte)((w>>8) & 0xff);
  191899. *(dp++) = (png_byte)(w & 0xff);
  191900. *(dp++) = *(sp++); /* alpha */
  191901. *(dp++) = *(sp++);
  191902. }
  191903. }
  191904. else
  191905. #endif
  191906. {
  191907. png_bytep sp = row;
  191908. png_bytep dp = row;
  191909. for (i = 0; i < row_width; i++)
  191910. {
  191911. png_uint_16 red, green, blue, gray16;
  191912. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191913. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191914. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191915. if(red != green || red != blue)
  191916. rgb_error |= 1;
  191917. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191918. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191919. *(dp++) = (png_byte)(gray16 & 0xff);
  191920. *(dp++) = *(sp++); /* alpha */
  191921. *(dp++) = *(sp++);
  191922. }
  191923. }
  191924. }
  191925. }
  191926. row_info->channels -= (png_byte)2;
  191927. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  191928. row_info->pixel_depth = (png_byte)(row_info->channels *
  191929. row_info->bit_depth);
  191930. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191931. }
  191932. return rgb_error;
  191933. }
  191934. #endif
  191935. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  191936. * large of png_color. This lets grayscale images be treated as
  191937. * paletted. Most useful for gamma correction and simplification
  191938. * of code.
  191939. */
  191940. void PNGAPI
  191941. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  191942. {
  191943. int num_palette;
  191944. int color_inc;
  191945. int i;
  191946. int v;
  191947. png_debug(1, "in png_do_build_grayscale_palette\n");
  191948. if (palette == NULL)
  191949. return;
  191950. switch (bit_depth)
  191951. {
  191952. case 1:
  191953. num_palette = 2;
  191954. color_inc = 0xff;
  191955. break;
  191956. case 2:
  191957. num_palette = 4;
  191958. color_inc = 0x55;
  191959. break;
  191960. case 4:
  191961. num_palette = 16;
  191962. color_inc = 0x11;
  191963. break;
  191964. case 8:
  191965. num_palette = 256;
  191966. color_inc = 1;
  191967. break;
  191968. default:
  191969. num_palette = 0;
  191970. color_inc = 0;
  191971. break;
  191972. }
  191973. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  191974. {
  191975. palette[i].red = (png_byte)v;
  191976. palette[i].green = (png_byte)v;
  191977. palette[i].blue = (png_byte)v;
  191978. }
  191979. }
  191980. /* This function is currently unused. Do we really need it? */
  191981. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  191982. void /* PRIVATE */
  191983. png_correct_palette(png_structp png_ptr, png_colorp palette,
  191984. int num_palette)
  191985. {
  191986. png_debug(1, "in png_correct_palette\n");
  191987. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  191988. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  191989. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  191990. {
  191991. png_color back, back_1;
  191992. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  191993. {
  191994. back.red = png_ptr->gamma_table[png_ptr->background.red];
  191995. back.green = png_ptr->gamma_table[png_ptr->background.green];
  191996. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  191997. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  191998. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  191999. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  192000. }
  192001. else
  192002. {
  192003. double g;
  192004. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  192005. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  192006. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  192007. {
  192008. back.red = png_ptr->background.red;
  192009. back.green = png_ptr->background.green;
  192010. back.blue = png_ptr->background.blue;
  192011. }
  192012. else
  192013. {
  192014. back.red =
  192015. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192016. 255.0 + 0.5);
  192017. back.green =
  192018. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192019. 255.0 + 0.5);
  192020. back.blue =
  192021. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192022. 255.0 + 0.5);
  192023. }
  192024. g = 1.0 / png_ptr->background_gamma;
  192025. back_1.red =
  192026. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192027. 255.0 + 0.5);
  192028. back_1.green =
  192029. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192030. 255.0 + 0.5);
  192031. back_1.blue =
  192032. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192033. 255.0 + 0.5);
  192034. }
  192035. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192036. {
  192037. png_uint_32 i;
  192038. for (i = 0; i < (png_uint_32)num_palette; i++)
  192039. {
  192040. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192041. {
  192042. palette[i] = back;
  192043. }
  192044. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192045. {
  192046. png_byte v, w;
  192047. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192048. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192049. palette[i].red = png_ptr->gamma_from_1[w];
  192050. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192051. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192052. palette[i].green = png_ptr->gamma_from_1[w];
  192053. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192054. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192055. palette[i].blue = png_ptr->gamma_from_1[w];
  192056. }
  192057. else
  192058. {
  192059. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192060. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192061. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192062. }
  192063. }
  192064. }
  192065. else
  192066. {
  192067. int i;
  192068. for (i = 0; i < num_palette; i++)
  192069. {
  192070. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192071. {
  192072. palette[i] = back;
  192073. }
  192074. else
  192075. {
  192076. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192077. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192078. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192079. }
  192080. }
  192081. }
  192082. }
  192083. else
  192084. #endif
  192085. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192086. if (png_ptr->transformations & PNG_GAMMA)
  192087. {
  192088. int i;
  192089. for (i = 0; i < num_palette; i++)
  192090. {
  192091. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192092. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192093. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192094. }
  192095. }
  192096. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192097. else
  192098. #endif
  192099. #endif
  192100. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192101. if (png_ptr->transformations & PNG_BACKGROUND)
  192102. {
  192103. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192104. {
  192105. png_color back;
  192106. back.red = (png_byte)png_ptr->background.red;
  192107. back.green = (png_byte)png_ptr->background.green;
  192108. back.blue = (png_byte)png_ptr->background.blue;
  192109. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192110. {
  192111. if (png_ptr->trans[i] == 0)
  192112. {
  192113. palette[i].red = back.red;
  192114. palette[i].green = back.green;
  192115. palette[i].blue = back.blue;
  192116. }
  192117. else if (png_ptr->trans[i] != 0xff)
  192118. {
  192119. png_composite(palette[i].red, png_ptr->palette[i].red,
  192120. png_ptr->trans[i], back.red);
  192121. png_composite(palette[i].green, png_ptr->palette[i].green,
  192122. png_ptr->trans[i], back.green);
  192123. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192124. png_ptr->trans[i], back.blue);
  192125. }
  192126. }
  192127. }
  192128. else /* assume grayscale palette (what else could it be?) */
  192129. {
  192130. int i;
  192131. for (i = 0; i < num_palette; i++)
  192132. {
  192133. if (i == (png_byte)png_ptr->trans_values.gray)
  192134. {
  192135. palette[i].red = (png_byte)png_ptr->background.red;
  192136. palette[i].green = (png_byte)png_ptr->background.green;
  192137. palette[i].blue = (png_byte)png_ptr->background.blue;
  192138. }
  192139. }
  192140. }
  192141. }
  192142. #endif
  192143. }
  192144. #endif
  192145. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192146. /* Replace any alpha or transparency with the supplied background color.
  192147. * "background" is already in the screen gamma, while "background_1" is
  192148. * at a gamma of 1.0. Paletted files have already been taken care of.
  192149. */
  192150. void /* PRIVATE */
  192151. png_do_background(png_row_infop row_info, png_bytep row,
  192152. png_color_16p trans_values, png_color_16p background
  192153. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192154. , png_color_16p background_1,
  192155. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192156. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192157. png_uint_16pp gamma_16_to_1, int gamma_shift
  192158. #endif
  192159. )
  192160. {
  192161. png_bytep sp, dp;
  192162. png_uint_32 i;
  192163. png_uint_32 row_width=row_info->width;
  192164. int shift;
  192165. png_debug(1, "in png_do_background\n");
  192166. if (background != NULL &&
  192167. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192168. row != NULL && row_info != NULL &&
  192169. #endif
  192170. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192171. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192172. {
  192173. switch (row_info->color_type)
  192174. {
  192175. case PNG_COLOR_TYPE_GRAY:
  192176. {
  192177. switch (row_info->bit_depth)
  192178. {
  192179. case 1:
  192180. {
  192181. sp = row;
  192182. shift = 7;
  192183. for (i = 0; i < row_width; i++)
  192184. {
  192185. if ((png_uint_16)((*sp >> shift) & 0x01)
  192186. == trans_values->gray)
  192187. {
  192188. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192189. *sp |= (png_byte)(background->gray << shift);
  192190. }
  192191. if (!shift)
  192192. {
  192193. shift = 7;
  192194. sp++;
  192195. }
  192196. else
  192197. shift--;
  192198. }
  192199. break;
  192200. }
  192201. case 2:
  192202. {
  192203. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192204. if (gamma_table != NULL)
  192205. {
  192206. sp = row;
  192207. shift = 6;
  192208. for (i = 0; i < row_width; i++)
  192209. {
  192210. if ((png_uint_16)((*sp >> shift) & 0x03)
  192211. == trans_values->gray)
  192212. {
  192213. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192214. *sp |= (png_byte)(background->gray << shift);
  192215. }
  192216. else
  192217. {
  192218. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192219. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192220. (p << 4) | (p << 6)] >> 6) & 0x03);
  192221. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192222. *sp |= (png_byte)(g << shift);
  192223. }
  192224. if (!shift)
  192225. {
  192226. shift = 6;
  192227. sp++;
  192228. }
  192229. else
  192230. shift -= 2;
  192231. }
  192232. }
  192233. else
  192234. #endif
  192235. {
  192236. sp = row;
  192237. shift = 6;
  192238. for (i = 0; i < row_width; i++)
  192239. {
  192240. if ((png_uint_16)((*sp >> shift) & 0x03)
  192241. == trans_values->gray)
  192242. {
  192243. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192244. *sp |= (png_byte)(background->gray << shift);
  192245. }
  192246. if (!shift)
  192247. {
  192248. shift = 6;
  192249. sp++;
  192250. }
  192251. else
  192252. shift -= 2;
  192253. }
  192254. }
  192255. break;
  192256. }
  192257. case 4:
  192258. {
  192259. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192260. if (gamma_table != NULL)
  192261. {
  192262. sp = row;
  192263. shift = 4;
  192264. for (i = 0; i < row_width; i++)
  192265. {
  192266. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192267. == trans_values->gray)
  192268. {
  192269. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192270. *sp |= (png_byte)(background->gray << shift);
  192271. }
  192272. else
  192273. {
  192274. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192275. png_byte g = (png_byte)((gamma_table[p |
  192276. (p << 4)] >> 4) & 0x0f);
  192277. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192278. *sp |= (png_byte)(g << shift);
  192279. }
  192280. if (!shift)
  192281. {
  192282. shift = 4;
  192283. sp++;
  192284. }
  192285. else
  192286. shift -= 4;
  192287. }
  192288. }
  192289. else
  192290. #endif
  192291. {
  192292. sp = row;
  192293. shift = 4;
  192294. for (i = 0; i < row_width; i++)
  192295. {
  192296. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192297. == trans_values->gray)
  192298. {
  192299. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192300. *sp |= (png_byte)(background->gray << shift);
  192301. }
  192302. if (!shift)
  192303. {
  192304. shift = 4;
  192305. sp++;
  192306. }
  192307. else
  192308. shift -= 4;
  192309. }
  192310. }
  192311. break;
  192312. }
  192313. case 8:
  192314. {
  192315. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192316. if (gamma_table != NULL)
  192317. {
  192318. sp = row;
  192319. for (i = 0; i < row_width; i++, sp++)
  192320. {
  192321. if (*sp == trans_values->gray)
  192322. {
  192323. *sp = (png_byte)background->gray;
  192324. }
  192325. else
  192326. {
  192327. *sp = gamma_table[*sp];
  192328. }
  192329. }
  192330. }
  192331. else
  192332. #endif
  192333. {
  192334. sp = row;
  192335. for (i = 0; i < row_width; i++, sp++)
  192336. {
  192337. if (*sp == trans_values->gray)
  192338. {
  192339. *sp = (png_byte)background->gray;
  192340. }
  192341. }
  192342. }
  192343. break;
  192344. }
  192345. case 16:
  192346. {
  192347. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192348. if (gamma_16 != NULL)
  192349. {
  192350. sp = row;
  192351. for (i = 0; i < row_width; i++, sp += 2)
  192352. {
  192353. png_uint_16 v;
  192354. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192355. if (v == trans_values->gray)
  192356. {
  192357. /* background is already in screen gamma */
  192358. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192359. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192360. }
  192361. else
  192362. {
  192363. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192364. *sp = (png_byte)((v >> 8) & 0xff);
  192365. *(sp + 1) = (png_byte)(v & 0xff);
  192366. }
  192367. }
  192368. }
  192369. else
  192370. #endif
  192371. {
  192372. sp = row;
  192373. for (i = 0; i < row_width; i++, sp += 2)
  192374. {
  192375. png_uint_16 v;
  192376. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192377. if (v == trans_values->gray)
  192378. {
  192379. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192380. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192381. }
  192382. }
  192383. }
  192384. break;
  192385. }
  192386. }
  192387. break;
  192388. }
  192389. case PNG_COLOR_TYPE_RGB:
  192390. {
  192391. if (row_info->bit_depth == 8)
  192392. {
  192393. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192394. if (gamma_table != NULL)
  192395. {
  192396. sp = row;
  192397. for (i = 0; i < row_width; i++, sp += 3)
  192398. {
  192399. if (*sp == trans_values->red &&
  192400. *(sp + 1) == trans_values->green &&
  192401. *(sp + 2) == trans_values->blue)
  192402. {
  192403. *sp = (png_byte)background->red;
  192404. *(sp + 1) = (png_byte)background->green;
  192405. *(sp + 2) = (png_byte)background->blue;
  192406. }
  192407. else
  192408. {
  192409. *sp = gamma_table[*sp];
  192410. *(sp + 1) = gamma_table[*(sp + 1)];
  192411. *(sp + 2) = gamma_table[*(sp + 2)];
  192412. }
  192413. }
  192414. }
  192415. else
  192416. #endif
  192417. {
  192418. sp = row;
  192419. for (i = 0; i < row_width; i++, sp += 3)
  192420. {
  192421. if (*sp == trans_values->red &&
  192422. *(sp + 1) == trans_values->green &&
  192423. *(sp + 2) == trans_values->blue)
  192424. {
  192425. *sp = (png_byte)background->red;
  192426. *(sp + 1) = (png_byte)background->green;
  192427. *(sp + 2) = (png_byte)background->blue;
  192428. }
  192429. }
  192430. }
  192431. }
  192432. else /* if (row_info->bit_depth == 16) */
  192433. {
  192434. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192435. if (gamma_16 != NULL)
  192436. {
  192437. sp = row;
  192438. for (i = 0; i < row_width; i++, sp += 6)
  192439. {
  192440. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192441. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192442. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192443. if (r == trans_values->red && g == trans_values->green &&
  192444. b == trans_values->blue)
  192445. {
  192446. /* background is already in screen gamma */
  192447. *sp = (png_byte)((background->red >> 8) & 0xff);
  192448. *(sp + 1) = (png_byte)(background->red & 0xff);
  192449. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192450. *(sp + 3) = (png_byte)(background->green & 0xff);
  192451. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192452. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192453. }
  192454. else
  192455. {
  192456. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192457. *sp = (png_byte)((v >> 8) & 0xff);
  192458. *(sp + 1) = (png_byte)(v & 0xff);
  192459. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192460. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192461. *(sp + 3) = (png_byte)(v & 0xff);
  192462. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192463. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192464. *(sp + 5) = (png_byte)(v & 0xff);
  192465. }
  192466. }
  192467. }
  192468. else
  192469. #endif
  192470. {
  192471. sp = row;
  192472. for (i = 0; i < row_width; i++, sp += 6)
  192473. {
  192474. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192475. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192476. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192477. if (r == trans_values->red && g == trans_values->green &&
  192478. b == trans_values->blue)
  192479. {
  192480. *sp = (png_byte)((background->red >> 8) & 0xff);
  192481. *(sp + 1) = (png_byte)(background->red & 0xff);
  192482. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192483. *(sp + 3) = (png_byte)(background->green & 0xff);
  192484. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192485. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192486. }
  192487. }
  192488. }
  192489. }
  192490. break;
  192491. }
  192492. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192493. {
  192494. if (row_info->bit_depth == 8)
  192495. {
  192496. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192497. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192498. gamma_table != NULL)
  192499. {
  192500. sp = row;
  192501. dp = row;
  192502. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192503. {
  192504. png_uint_16 a = *(sp + 1);
  192505. if (a == 0xff)
  192506. {
  192507. *dp = gamma_table[*sp];
  192508. }
  192509. else if (a == 0)
  192510. {
  192511. /* background is already in screen gamma */
  192512. *dp = (png_byte)background->gray;
  192513. }
  192514. else
  192515. {
  192516. png_byte v, w;
  192517. v = gamma_to_1[*sp];
  192518. png_composite(w, v, a, background_1->gray);
  192519. *dp = gamma_from_1[w];
  192520. }
  192521. }
  192522. }
  192523. else
  192524. #endif
  192525. {
  192526. sp = row;
  192527. dp = row;
  192528. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192529. {
  192530. png_byte a = *(sp + 1);
  192531. if (a == 0xff)
  192532. {
  192533. *dp = *sp;
  192534. }
  192535. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192536. else if (a == 0)
  192537. {
  192538. *dp = (png_byte)background->gray;
  192539. }
  192540. else
  192541. {
  192542. png_composite(*dp, *sp, a, background_1->gray);
  192543. }
  192544. #else
  192545. *dp = (png_byte)background->gray;
  192546. #endif
  192547. }
  192548. }
  192549. }
  192550. else /* if (png_ptr->bit_depth == 16) */
  192551. {
  192552. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192553. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192554. gamma_16_to_1 != NULL)
  192555. {
  192556. sp = row;
  192557. dp = row;
  192558. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192559. {
  192560. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192561. if (a == (png_uint_16)0xffff)
  192562. {
  192563. png_uint_16 v;
  192564. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192565. *dp = (png_byte)((v >> 8) & 0xff);
  192566. *(dp + 1) = (png_byte)(v & 0xff);
  192567. }
  192568. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192569. else if (a == 0)
  192570. #else
  192571. else
  192572. #endif
  192573. {
  192574. /* background is already in screen gamma */
  192575. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192576. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192577. }
  192578. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192579. else
  192580. {
  192581. png_uint_16 g, v, w;
  192582. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192583. png_composite_16(v, g, a, background_1->gray);
  192584. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  192585. *dp = (png_byte)((w >> 8) & 0xff);
  192586. *(dp + 1) = (png_byte)(w & 0xff);
  192587. }
  192588. #endif
  192589. }
  192590. }
  192591. else
  192592. #endif
  192593. {
  192594. sp = row;
  192595. dp = row;
  192596. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192597. {
  192598. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192599. if (a == (png_uint_16)0xffff)
  192600. {
  192601. png_memcpy(dp, sp, 2);
  192602. }
  192603. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192604. else if (a == 0)
  192605. #else
  192606. else
  192607. #endif
  192608. {
  192609. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192610. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192611. }
  192612. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192613. else
  192614. {
  192615. png_uint_16 g, v;
  192616. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192617. png_composite_16(v, g, a, background_1->gray);
  192618. *dp = (png_byte)((v >> 8) & 0xff);
  192619. *(dp + 1) = (png_byte)(v & 0xff);
  192620. }
  192621. #endif
  192622. }
  192623. }
  192624. }
  192625. break;
  192626. }
  192627. case PNG_COLOR_TYPE_RGB_ALPHA:
  192628. {
  192629. if (row_info->bit_depth == 8)
  192630. {
  192631. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192632. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192633. gamma_table != NULL)
  192634. {
  192635. sp = row;
  192636. dp = row;
  192637. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192638. {
  192639. png_byte a = *(sp + 3);
  192640. if (a == 0xff)
  192641. {
  192642. *dp = gamma_table[*sp];
  192643. *(dp + 1) = gamma_table[*(sp + 1)];
  192644. *(dp + 2) = gamma_table[*(sp + 2)];
  192645. }
  192646. else if (a == 0)
  192647. {
  192648. /* background is already in screen gamma */
  192649. *dp = (png_byte)background->red;
  192650. *(dp + 1) = (png_byte)background->green;
  192651. *(dp + 2) = (png_byte)background->blue;
  192652. }
  192653. else
  192654. {
  192655. png_byte v, w;
  192656. v = gamma_to_1[*sp];
  192657. png_composite(w, v, a, background_1->red);
  192658. *dp = gamma_from_1[w];
  192659. v = gamma_to_1[*(sp + 1)];
  192660. png_composite(w, v, a, background_1->green);
  192661. *(dp + 1) = gamma_from_1[w];
  192662. v = gamma_to_1[*(sp + 2)];
  192663. png_composite(w, v, a, background_1->blue);
  192664. *(dp + 2) = gamma_from_1[w];
  192665. }
  192666. }
  192667. }
  192668. else
  192669. #endif
  192670. {
  192671. sp = row;
  192672. dp = row;
  192673. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192674. {
  192675. png_byte a = *(sp + 3);
  192676. if (a == 0xff)
  192677. {
  192678. *dp = *sp;
  192679. *(dp + 1) = *(sp + 1);
  192680. *(dp + 2) = *(sp + 2);
  192681. }
  192682. else if (a == 0)
  192683. {
  192684. *dp = (png_byte)background->red;
  192685. *(dp + 1) = (png_byte)background->green;
  192686. *(dp + 2) = (png_byte)background->blue;
  192687. }
  192688. else
  192689. {
  192690. png_composite(*dp, *sp, a, background->red);
  192691. png_composite(*(dp + 1), *(sp + 1), a,
  192692. background->green);
  192693. png_composite(*(dp + 2), *(sp + 2), a,
  192694. background->blue);
  192695. }
  192696. }
  192697. }
  192698. }
  192699. else /* if (row_info->bit_depth == 16) */
  192700. {
  192701. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192702. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192703. gamma_16_to_1 != NULL)
  192704. {
  192705. sp = row;
  192706. dp = row;
  192707. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192708. {
  192709. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192710. << 8) + (png_uint_16)(*(sp + 7)));
  192711. if (a == (png_uint_16)0xffff)
  192712. {
  192713. png_uint_16 v;
  192714. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192715. *dp = (png_byte)((v >> 8) & 0xff);
  192716. *(dp + 1) = (png_byte)(v & 0xff);
  192717. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192718. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192719. *(dp + 3) = (png_byte)(v & 0xff);
  192720. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192721. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192722. *(dp + 5) = (png_byte)(v & 0xff);
  192723. }
  192724. else if (a == 0)
  192725. {
  192726. /* background is already in screen gamma */
  192727. *dp = (png_byte)((background->red >> 8) & 0xff);
  192728. *(dp + 1) = (png_byte)(background->red & 0xff);
  192729. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192730. *(dp + 3) = (png_byte)(background->green & 0xff);
  192731. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192732. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192733. }
  192734. else
  192735. {
  192736. png_uint_16 v, w, x;
  192737. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192738. png_composite_16(w, v, a, background_1->red);
  192739. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192740. *dp = (png_byte)((x >> 8) & 0xff);
  192741. *(dp + 1) = (png_byte)(x & 0xff);
  192742. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192743. png_composite_16(w, v, a, background_1->green);
  192744. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192745. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  192746. *(dp + 3) = (png_byte)(x & 0xff);
  192747. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192748. png_composite_16(w, v, a, background_1->blue);
  192749. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  192750. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  192751. *(dp + 5) = (png_byte)(x & 0xff);
  192752. }
  192753. }
  192754. }
  192755. else
  192756. #endif
  192757. {
  192758. sp = row;
  192759. dp = row;
  192760. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192761. {
  192762. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192763. << 8) + (png_uint_16)(*(sp + 7)));
  192764. if (a == (png_uint_16)0xffff)
  192765. {
  192766. png_memcpy(dp, sp, 6);
  192767. }
  192768. else if (a == 0)
  192769. {
  192770. *dp = (png_byte)((background->red >> 8) & 0xff);
  192771. *(dp + 1) = (png_byte)(background->red & 0xff);
  192772. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192773. *(dp + 3) = (png_byte)(background->green & 0xff);
  192774. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192775. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192776. }
  192777. else
  192778. {
  192779. png_uint_16 v;
  192780. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192781. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  192782. + *(sp + 3));
  192783. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  192784. + *(sp + 5));
  192785. png_composite_16(v, r, a, background->red);
  192786. *dp = (png_byte)((v >> 8) & 0xff);
  192787. *(dp + 1) = (png_byte)(v & 0xff);
  192788. png_composite_16(v, g, a, background->green);
  192789. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192790. *(dp + 3) = (png_byte)(v & 0xff);
  192791. png_composite_16(v, b, a, background->blue);
  192792. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192793. *(dp + 5) = (png_byte)(v & 0xff);
  192794. }
  192795. }
  192796. }
  192797. }
  192798. break;
  192799. }
  192800. }
  192801. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  192802. {
  192803. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  192804. row_info->channels--;
  192805. row_info->pixel_depth = (png_byte)(row_info->channels *
  192806. row_info->bit_depth);
  192807. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192808. }
  192809. }
  192810. }
  192811. #endif
  192812. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192813. /* Gamma correct the image, avoiding the alpha channel. Make sure
  192814. * you do this after you deal with the transparency issue on grayscale
  192815. * or RGB images. If your bit depth is 8, use gamma_table, if it
  192816. * is 16, use gamma_16_table and gamma_shift. Build these with
  192817. * build_gamma_table().
  192818. */
  192819. void /* PRIVATE */
  192820. png_do_gamma(png_row_infop row_info, png_bytep row,
  192821. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  192822. int gamma_shift)
  192823. {
  192824. png_bytep sp;
  192825. png_uint_32 i;
  192826. png_uint_32 row_width=row_info->width;
  192827. png_debug(1, "in png_do_gamma\n");
  192828. if (
  192829. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192830. row != NULL && row_info != NULL &&
  192831. #endif
  192832. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  192833. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  192834. {
  192835. switch (row_info->color_type)
  192836. {
  192837. case PNG_COLOR_TYPE_RGB:
  192838. {
  192839. if (row_info->bit_depth == 8)
  192840. {
  192841. sp = row;
  192842. for (i = 0; i < row_width; i++)
  192843. {
  192844. *sp = gamma_table[*sp];
  192845. sp++;
  192846. *sp = gamma_table[*sp];
  192847. sp++;
  192848. *sp = gamma_table[*sp];
  192849. sp++;
  192850. }
  192851. }
  192852. else /* if (row_info->bit_depth == 16) */
  192853. {
  192854. sp = row;
  192855. for (i = 0; i < row_width; i++)
  192856. {
  192857. png_uint_16 v;
  192858. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192859. *sp = (png_byte)((v >> 8) & 0xff);
  192860. *(sp + 1) = (png_byte)(v & 0xff);
  192861. sp += 2;
  192862. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192863. *sp = (png_byte)((v >> 8) & 0xff);
  192864. *(sp + 1) = (png_byte)(v & 0xff);
  192865. sp += 2;
  192866. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192867. *sp = (png_byte)((v >> 8) & 0xff);
  192868. *(sp + 1) = (png_byte)(v & 0xff);
  192869. sp += 2;
  192870. }
  192871. }
  192872. break;
  192873. }
  192874. case PNG_COLOR_TYPE_RGB_ALPHA:
  192875. {
  192876. if (row_info->bit_depth == 8)
  192877. {
  192878. sp = row;
  192879. for (i = 0; i < row_width; i++)
  192880. {
  192881. *sp = gamma_table[*sp];
  192882. sp++;
  192883. *sp = gamma_table[*sp];
  192884. sp++;
  192885. *sp = gamma_table[*sp];
  192886. sp++;
  192887. sp++;
  192888. }
  192889. }
  192890. else /* if (row_info->bit_depth == 16) */
  192891. {
  192892. sp = row;
  192893. for (i = 0; i < row_width; i++)
  192894. {
  192895. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192896. *sp = (png_byte)((v >> 8) & 0xff);
  192897. *(sp + 1) = (png_byte)(v & 0xff);
  192898. sp += 2;
  192899. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192900. *sp = (png_byte)((v >> 8) & 0xff);
  192901. *(sp + 1) = (png_byte)(v & 0xff);
  192902. sp += 2;
  192903. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192904. *sp = (png_byte)((v >> 8) & 0xff);
  192905. *(sp + 1) = (png_byte)(v & 0xff);
  192906. sp += 4;
  192907. }
  192908. }
  192909. break;
  192910. }
  192911. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192912. {
  192913. if (row_info->bit_depth == 8)
  192914. {
  192915. sp = row;
  192916. for (i = 0; i < row_width; i++)
  192917. {
  192918. *sp = gamma_table[*sp];
  192919. sp += 2;
  192920. }
  192921. }
  192922. else /* if (row_info->bit_depth == 16) */
  192923. {
  192924. sp = row;
  192925. for (i = 0; i < row_width; i++)
  192926. {
  192927. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192928. *sp = (png_byte)((v >> 8) & 0xff);
  192929. *(sp + 1) = (png_byte)(v & 0xff);
  192930. sp += 4;
  192931. }
  192932. }
  192933. break;
  192934. }
  192935. case PNG_COLOR_TYPE_GRAY:
  192936. {
  192937. if (row_info->bit_depth == 2)
  192938. {
  192939. sp = row;
  192940. for (i = 0; i < row_width; i += 4)
  192941. {
  192942. int a = *sp & 0xc0;
  192943. int b = *sp & 0x30;
  192944. int c = *sp & 0x0c;
  192945. int d = *sp & 0x03;
  192946. *sp = (png_byte)(
  192947. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  192948. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  192949. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  192950. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  192951. sp++;
  192952. }
  192953. }
  192954. if (row_info->bit_depth == 4)
  192955. {
  192956. sp = row;
  192957. for (i = 0; i < row_width; i += 2)
  192958. {
  192959. int msb = *sp & 0xf0;
  192960. int lsb = *sp & 0x0f;
  192961. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  192962. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  192963. sp++;
  192964. }
  192965. }
  192966. else if (row_info->bit_depth == 8)
  192967. {
  192968. sp = row;
  192969. for (i = 0; i < row_width; i++)
  192970. {
  192971. *sp = gamma_table[*sp];
  192972. sp++;
  192973. }
  192974. }
  192975. else if (row_info->bit_depth == 16)
  192976. {
  192977. sp = row;
  192978. for (i = 0; i < row_width; i++)
  192979. {
  192980. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192981. *sp = (png_byte)((v >> 8) & 0xff);
  192982. *(sp + 1) = (png_byte)(v & 0xff);
  192983. sp += 2;
  192984. }
  192985. }
  192986. break;
  192987. }
  192988. }
  192989. }
  192990. }
  192991. #endif
  192992. #if defined(PNG_READ_EXPAND_SUPPORTED)
  192993. /* Expands a palette row to an RGB or RGBA row depending
  192994. * upon whether you supply trans and num_trans.
  192995. */
  192996. void /* PRIVATE */
  192997. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  192998. png_colorp palette, png_bytep trans, int num_trans)
  192999. {
  193000. int shift, value;
  193001. png_bytep sp, dp;
  193002. png_uint_32 i;
  193003. png_uint_32 row_width=row_info->width;
  193004. png_debug(1, "in png_do_expand_palette\n");
  193005. if (
  193006. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193007. row != NULL && row_info != NULL &&
  193008. #endif
  193009. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  193010. {
  193011. if (row_info->bit_depth < 8)
  193012. {
  193013. switch (row_info->bit_depth)
  193014. {
  193015. case 1:
  193016. {
  193017. sp = row + (png_size_t)((row_width - 1) >> 3);
  193018. dp = row + (png_size_t)row_width - 1;
  193019. shift = 7 - (int)((row_width + 7) & 0x07);
  193020. for (i = 0; i < row_width; i++)
  193021. {
  193022. if ((*sp >> shift) & 0x01)
  193023. *dp = 1;
  193024. else
  193025. *dp = 0;
  193026. if (shift == 7)
  193027. {
  193028. shift = 0;
  193029. sp--;
  193030. }
  193031. else
  193032. shift++;
  193033. dp--;
  193034. }
  193035. break;
  193036. }
  193037. case 2:
  193038. {
  193039. sp = row + (png_size_t)((row_width - 1) >> 2);
  193040. dp = row + (png_size_t)row_width - 1;
  193041. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193042. for (i = 0; i < row_width; i++)
  193043. {
  193044. value = (*sp >> shift) & 0x03;
  193045. *dp = (png_byte)value;
  193046. if (shift == 6)
  193047. {
  193048. shift = 0;
  193049. sp--;
  193050. }
  193051. else
  193052. shift += 2;
  193053. dp--;
  193054. }
  193055. break;
  193056. }
  193057. case 4:
  193058. {
  193059. sp = row + (png_size_t)((row_width - 1) >> 1);
  193060. dp = row + (png_size_t)row_width - 1;
  193061. shift = (int)((row_width & 0x01) << 2);
  193062. for (i = 0; i < row_width; i++)
  193063. {
  193064. value = (*sp >> shift) & 0x0f;
  193065. *dp = (png_byte)value;
  193066. if (shift == 4)
  193067. {
  193068. shift = 0;
  193069. sp--;
  193070. }
  193071. else
  193072. shift += 4;
  193073. dp--;
  193074. }
  193075. break;
  193076. }
  193077. }
  193078. row_info->bit_depth = 8;
  193079. row_info->pixel_depth = 8;
  193080. row_info->rowbytes = row_width;
  193081. }
  193082. switch (row_info->bit_depth)
  193083. {
  193084. case 8:
  193085. {
  193086. if (trans != NULL)
  193087. {
  193088. sp = row + (png_size_t)row_width - 1;
  193089. dp = row + (png_size_t)(row_width << 2) - 1;
  193090. for (i = 0; i < row_width; i++)
  193091. {
  193092. if ((int)(*sp) >= num_trans)
  193093. *dp-- = 0xff;
  193094. else
  193095. *dp-- = trans[*sp];
  193096. *dp-- = palette[*sp].blue;
  193097. *dp-- = palette[*sp].green;
  193098. *dp-- = palette[*sp].red;
  193099. sp--;
  193100. }
  193101. row_info->bit_depth = 8;
  193102. row_info->pixel_depth = 32;
  193103. row_info->rowbytes = row_width * 4;
  193104. row_info->color_type = 6;
  193105. row_info->channels = 4;
  193106. }
  193107. else
  193108. {
  193109. sp = row + (png_size_t)row_width - 1;
  193110. dp = row + (png_size_t)(row_width * 3) - 1;
  193111. for (i = 0; i < row_width; i++)
  193112. {
  193113. *dp-- = palette[*sp].blue;
  193114. *dp-- = palette[*sp].green;
  193115. *dp-- = palette[*sp].red;
  193116. sp--;
  193117. }
  193118. row_info->bit_depth = 8;
  193119. row_info->pixel_depth = 24;
  193120. row_info->rowbytes = row_width * 3;
  193121. row_info->color_type = 2;
  193122. row_info->channels = 3;
  193123. }
  193124. break;
  193125. }
  193126. }
  193127. }
  193128. }
  193129. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193130. * expanded transparency value is supplied, an alpha channel is built.
  193131. */
  193132. void /* PRIVATE */
  193133. png_do_expand(png_row_infop row_info, png_bytep row,
  193134. png_color_16p trans_value)
  193135. {
  193136. int shift, value;
  193137. png_bytep sp, dp;
  193138. png_uint_32 i;
  193139. png_uint_32 row_width=row_info->width;
  193140. png_debug(1, "in png_do_expand\n");
  193141. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193142. if (row != NULL && row_info != NULL)
  193143. #endif
  193144. {
  193145. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193146. {
  193147. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193148. if (row_info->bit_depth < 8)
  193149. {
  193150. switch (row_info->bit_depth)
  193151. {
  193152. case 1:
  193153. {
  193154. gray = (png_uint_16)((gray&0x01)*0xff);
  193155. sp = row + (png_size_t)((row_width - 1) >> 3);
  193156. dp = row + (png_size_t)row_width - 1;
  193157. shift = 7 - (int)((row_width + 7) & 0x07);
  193158. for (i = 0; i < row_width; i++)
  193159. {
  193160. if ((*sp >> shift) & 0x01)
  193161. *dp = 0xff;
  193162. else
  193163. *dp = 0;
  193164. if (shift == 7)
  193165. {
  193166. shift = 0;
  193167. sp--;
  193168. }
  193169. else
  193170. shift++;
  193171. dp--;
  193172. }
  193173. break;
  193174. }
  193175. case 2:
  193176. {
  193177. gray = (png_uint_16)((gray&0x03)*0x55);
  193178. sp = row + (png_size_t)((row_width - 1) >> 2);
  193179. dp = row + (png_size_t)row_width - 1;
  193180. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193181. for (i = 0; i < row_width; i++)
  193182. {
  193183. value = (*sp >> shift) & 0x03;
  193184. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193185. (value << 6));
  193186. if (shift == 6)
  193187. {
  193188. shift = 0;
  193189. sp--;
  193190. }
  193191. else
  193192. shift += 2;
  193193. dp--;
  193194. }
  193195. break;
  193196. }
  193197. case 4:
  193198. {
  193199. gray = (png_uint_16)((gray&0x0f)*0x11);
  193200. sp = row + (png_size_t)((row_width - 1) >> 1);
  193201. dp = row + (png_size_t)row_width - 1;
  193202. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193203. for (i = 0; i < row_width; i++)
  193204. {
  193205. value = (*sp >> shift) & 0x0f;
  193206. *dp = (png_byte)(value | (value << 4));
  193207. if (shift == 4)
  193208. {
  193209. shift = 0;
  193210. sp--;
  193211. }
  193212. else
  193213. shift = 4;
  193214. dp--;
  193215. }
  193216. break;
  193217. }
  193218. }
  193219. row_info->bit_depth = 8;
  193220. row_info->pixel_depth = 8;
  193221. row_info->rowbytes = row_width;
  193222. }
  193223. if (trans_value != NULL)
  193224. {
  193225. if (row_info->bit_depth == 8)
  193226. {
  193227. gray = gray & 0xff;
  193228. sp = row + (png_size_t)row_width - 1;
  193229. dp = row + (png_size_t)(row_width << 1) - 1;
  193230. for (i = 0; i < row_width; i++)
  193231. {
  193232. if (*sp == gray)
  193233. *dp-- = 0;
  193234. else
  193235. *dp-- = 0xff;
  193236. *dp-- = *sp--;
  193237. }
  193238. }
  193239. else if (row_info->bit_depth == 16)
  193240. {
  193241. png_byte gray_high = (gray >> 8) & 0xff;
  193242. png_byte gray_low = gray & 0xff;
  193243. sp = row + row_info->rowbytes - 1;
  193244. dp = row + (row_info->rowbytes << 1) - 1;
  193245. for (i = 0; i < row_width; i++)
  193246. {
  193247. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193248. {
  193249. *dp-- = 0;
  193250. *dp-- = 0;
  193251. }
  193252. else
  193253. {
  193254. *dp-- = 0xff;
  193255. *dp-- = 0xff;
  193256. }
  193257. *dp-- = *sp--;
  193258. *dp-- = *sp--;
  193259. }
  193260. }
  193261. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193262. row_info->channels = 2;
  193263. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193264. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193265. row_width);
  193266. }
  193267. }
  193268. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193269. {
  193270. if (row_info->bit_depth == 8)
  193271. {
  193272. png_byte red = trans_value->red & 0xff;
  193273. png_byte green = trans_value->green & 0xff;
  193274. png_byte blue = trans_value->blue & 0xff;
  193275. sp = row + (png_size_t)row_info->rowbytes - 1;
  193276. dp = row + (png_size_t)(row_width << 2) - 1;
  193277. for (i = 0; i < row_width; i++)
  193278. {
  193279. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193280. *dp-- = 0;
  193281. else
  193282. *dp-- = 0xff;
  193283. *dp-- = *sp--;
  193284. *dp-- = *sp--;
  193285. *dp-- = *sp--;
  193286. }
  193287. }
  193288. else if (row_info->bit_depth == 16)
  193289. {
  193290. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193291. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193292. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193293. png_byte red_low = trans_value->red & 0xff;
  193294. png_byte green_low = trans_value->green & 0xff;
  193295. png_byte blue_low = trans_value->blue & 0xff;
  193296. sp = row + row_info->rowbytes - 1;
  193297. dp = row + (png_size_t)(row_width << 3) - 1;
  193298. for (i = 0; i < row_width; i++)
  193299. {
  193300. if (*(sp - 5) == red_high &&
  193301. *(sp - 4) == red_low &&
  193302. *(sp - 3) == green_high &&
  193303. *(sp - 2) == green_low &&
  193304. *(sp - 1) == blue_high &&
  193305. *(sp ) == blue_low)
  193306. {
  193307. *dp-- = 0;
  193308. *dp-- = 0;
  193309. }
  193310. else
  193311. {
  193312. *dp-- = 0xff;
  193313. *dp-- = 0xff;
  193314. }
  193315. *dp-- = *sp--;
  193316. *dp-- = *sp--;
  193317. *dp-- = *sp--;
  193318. *dp-- = *sp--;
  193319. *dp-- = *sp--;
  193320. *dp-- = *sp--;
  193321. }
  193322. }
  193323. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193324. row_info->channels = 4;
  193325. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193326. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193327. }
  193328. }
  193329. }
  193330. #endif
  193331. #if defined(PNG_READ_DITHER_SUPPORTED)
  193332. void /* PRIVATE */
  193333. png_do_dither(png_row_infop row_info, png_bytep row,
  193334. png_bytep palette_lookup, png_bytep dither_lookup)
  193335. {
  193336. png_bytep sp, dp;
  193337. png_uint_32 i;
  193338. png_uint_32 row_width=row_info->width;
  193339. png_debug(1, "in png_do_dither\n");
  193340. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193341. if (row != NULL && row_info != NULL)
  193342. #endif
  193343. {
  193344. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193345. palette_lookup && row_info->bit_depth == 8)
  193346. {
  193347. int r, g, b, p;
  193348. sp = row;
  193349. dp = row;
  193350. for (i = 0; i < row_width; i++)
  193351. {
  193352. r = *sp++;
  193353. g = *sp++;
  193354. b = *sp++;
  193355. /* this looks real messy, but the compiler will reduce
  193356. it down to a reasonable formula. For example, with
  193357. 5 bits per color, we get:
  193358. p = (((r >> 3) & 0x1f) << 10) |
  193359. (((g >> 3) & 0x1f) << 5) |
  193360. ((b >> 3) & 0x1f);
  193361. */
  193362. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193363. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193364. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193365. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193366. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193367. (PNG_DITHER_BLUE_BITS)) |
  193368. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193369. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193370. *dp++ = palette_lookup[p];
  193371. }
  193372. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193373. row_info->channels = 1;
  193374. row_info->pixel_depth = row_info->bit_depth;
  193375. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193376. }
  193377. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193378. palette_lookup != NULL && row_info->bit_depth == 8)
  193379. {
  193380. int r, g, b, p;
  193381. sp = row;
  193382. dp = row;
  193383. for (i = 0; i < row_width; i++)
  193384. {
  193385. r = *sp++;
  193386. g = *sp++;
  193387. b = *sp++;
  193388. sp++;
  193389. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193390. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193391. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193392. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193393. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193394. (PNG_DITHER_BLUE_BITS)) |
  193395. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193396. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193397. *dp++ = palette_lookup[p];
  193398. }
  193399. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193400. row_info->channels = 1;
  193401. row_info->pixel_depth = row_info->bit_depth;
  193402. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193403. }
  193404. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193405. dither_lookup && row_info->bit_depth == 8)
  193406. {
  193407. sp = row;
  193408. for (i = 0; i < row_width; i++, sp++)
  193409. {
  193410. *sp = dither_lookup[*sp];
  193411. }
  193412. }
  193413. }
  193414. }
  193415. #endif
  193416. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193417. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193418. static PNG_CONST int png_gamma_shift[] =
  193419. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193420. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193421. * tables, we don't make a full table if we are reducing to 8-bit in
  193422. * the future. Note also how the gamma_16 tables are segmented so that
  193423. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193424. */
  193425. void /* PRIVATE */
  193426. png_build_gamma_table(png_structp png_ptr)
  193427. {
  193428. png_debug(1, "in png_build_gamma_table\n");
  193429. if (png_ptr->bit_depth <= 8)
  193430. {
  193431. int i;
  193432. double g;
  193433. if (png_ptr->screen_gamma > .000001)
  193434. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193435. else
  193436. g = 1.0;
  193437. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193438. (png_uint_32)256);
  193439. for (i = 0; i < 256; i++)
  193440. {
  193441. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193442. g) * 255.0 + .5);
  193443. }
  193444. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193445. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193446. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193447. {
  193448. g = 1.0 / (png_ptr->gamma);
  193449. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193450. (png_uint_32)256);
  193451. for (i = 0; i < 256; i++)
  193452. {
  193453. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193454. g) * 255.0 + .5);
  193455. }
  193456. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193457. (png_uint_32)256);
  193458. if(png_ptr->screen_gamma > 0.000001)
  193459. g = 1.0 / png_ptr->screen_gamma;
  193460. else
  193461. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193462. for (i = 0; i < 256; i++)
  193463. {
  193464. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193465. g) * 255.0 + .5);
  193466. }
  193467. }
  193468. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193469. }
  193470. else
  193471. {
  193472. double g;
  193473. int i, j, shift, num;
  193474. int sig_bit;
  193475. png_uint_32 ig;
  193476. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193477. {
  193478. sig_bit = (int)png_ptr->sig_bit.red;
  193479. if ((int)png_ptr->sig_bit.green > sig_bit)
  193480. sig_bit = png_ptr->sig_bit.green;
  193481. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193482. sig_bit = png_ptr->sig_bit.blue;
  193483. }
  193484. else
  193485. {
  193486. sig_bit = (int)png_ptr->sig_bit.gray;
  193487. }
  193488. if (sig_bit > 0)
  193489. shift = 16 - sig_bit;
  193490. else
  193491. shift = 0;
  193492. if (png_ptr->transformations & PNG_16_TO_8)
  193493. {
  193494. if (shift < (16 - PNG_MAX_GAMMA_8))
  193495. shift = (16 - PNG_MAX_GAMMA_8);
  193496. }
  193497. if (shift > 8)
  193498. shift = 8;
  193499. if (shift < 0)
  193500. shift = 0;
  193501. png_ptr->gamma_shift = (png_byte)shift;
  193502. num = (1 << (8 - shift));
  193503. if (png_ptr->screen_gamma > .000001)
  193504. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193505. else
  193506. g = 1.0;
  193507. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  193508. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193509. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  193510. {
  193511. double fin, fout;
  193512. png_uint_32 last, max;
  193513. for (i = 0; i < num; i++)
  193514. {
  193515. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193516. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193517. }
  193518. g = 1.0 / g;
  193519. last = 0;
  193520. for (i = 0; i < 256; i++)
  193521. {
  193522. fout = ((double)i + 0.5) / 256.0;
  193523. fin = pow(fout, g);
  193524. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  193525. while (last <= max)
  193526. {
  193527. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193528. [(int)(last >> (8 - shift))] = (png_uint_16)(
  193529. (png_uint_16)i | ((png_uint_16)i << 8));
  193530. last++;
  193531. }
  193532. }
  193533. while (last < ((png_uint_32)num << 8))
  193534. {
  193535. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193536. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  193537. last++;
  193538. }
  193539. }
  193540. else
  193541. {
  193542. for (i = 0; i < num; i++)
  193543. {
  193544. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193545. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193546. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  193547. for (j = 0; j < 256; j++)
  193548. {
  193549. png_ptr->gamma_16_table[i][j] =
  193550. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193551. 65535.0, g) * 65535.0 + .5);
  193552. }
  193553. }
  193554. }
  193555. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193556. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193557. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  193558. {
  193559. g = 1.0 / (png_ptr->gamma);
  193560. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  193561. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  193562. for (i = 0; i < num; i++)
  193563. {
  193564. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193565. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193566. ig = (((png_uint_32)i *
  193567. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193568. for (j = 0; j < 256; j++)
  193569. {
  193570. png_ptr->gamma_16_to_1[i][j] =
  193571. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193572. 65535.0, g) * 65535.0 + .5);
  193573. }
  193574. }
  193575. if(png_ptr->screen_gamma > 0.000001)
  193576. g = 1.0 / png_ptr->screen_gamma;
  193577. else
  193578. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193579. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  193580. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193581. for (i = 0; i < num; i++)
  193582. {
  193583. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193584. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193585. ig = (((png_uint_32)i *
  193586. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193587. for (j = 0; j < 256; j++)
  193588. {
  193589. png_ptr->gamma_16_from_1[i][j] =
  193590. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193591. 65535.0, g) * 65535.0 + .5);
  193592. }
  193593. }
  193594. }
  193595. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193596. }
  193597. }
  193598. #endif
  193599. /* To do: install integer version of png_build_gamma_table here */
  193600. #endif
  193601. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193602. /* undoes intrapixel differencing */
  193603. void /* PRIVATE */
  193604. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  193605. {
  193606. png_debug(1, "in png_do_read_intrapixel\n");
  193607. if (
  193608. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193609. row != NULL && row_info != NULL &&
  193610. #endif
  193611. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193612. {
  193613. int bytes_per_pixel;
  193614. png_uint_32 row_width = row_info->width;
  193615. if (row_info->bit_depth == 8)
  193616. {
  193617. png_bytep rp;
  193618. png_uint_32 i;
  193619. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193620. bytes_per_pixel = 3;
  193621. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193622. bytes_per_pixel = 4;
  193623. else
  193624. return;
  193625. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193626. {
  193627. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  193628. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  193629. }
  193630. }
  193631. else if (row_info->bit_depth == 16)
  193632. {
  193633. png_bytep rp;
  193634. png_uint_32 i;
  193635. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193636. bytes_per_pixel = 6;
  193637. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193638. bytes_per_pixel = 8;
  193639. else
  193640. return;
  193641. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193642. {
  193643. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  193644. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  193645. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  193646. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  193647. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  193648. *(rp ) = (png_byte)((red >> 8) & 0xff);
  193649. *(rp+1) = (png_byte)(red & 0xff);
  193650. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  193651. *(rp+5) = (png_byte)(blue & 0xff);
  193652. }
  193653. }
  193654. }
  193655. }
  193656. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  193657. #endif /* PNG_READ_SUPPORTED */
  193658. /*** End of inlined file: pngrtran.c ***/
  193659. /*** Start of inlined file: pngrutil.c ***/
  193660. /* pngrutil.c - utilities to read a PNG file
  193661. *
  193662. * Last changed in libpng 1.2.21 [October 4, 2007]
  193663. * For conditions of distribution and use, see copyright notice in png.h
  193664. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193665. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193666. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193667. *
  193668. * This file contains routines that are only called from within
  193669. * libpng itself during the course of reading an image.
  193670. */
  193671. #define PNG_INTERNAL
  193672. #if defined(PNG_READ_SUPPORTED)
  193673. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  193674. # define WIN32_WCE_OLD
  193675. #endif
  193676. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193677. # if defined(WIN32_WCE_OLD)
  193678. /* strtod() function is not supported on WindowsCE */
  193679. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  193680. {
  193681. double result = 0;
  193682. int len;
  193683. wchar_t *str, *end;
  193684. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  193685. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  193686. if ( NULL != str )
  193687. {
  193688. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  193689. result = wcstod(str, &end);
  193690. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  193691. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  193692. png_free(png_ptr, str);
  193693. }
  193694. return result;
  193695. }
  193696. # else
  193697. # define png_strtod(p,a,b) strtod(a,b)
  193698. # endif
  193699. #endif
  193700. png_uint_32 PNGAPI
  193701. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  193702. {
  193703. png_uint_32 i = png_get_uint_32(buf);
  193704. if (i > PNG_UINT_31_MAX)
  193705. png_error(png_ptr, "PNG unsigned integer out of range.");
  193706. return (i);
  193707. }
  193708. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  193709. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  193710. png_uint_32 PNGAPI
  193711. png_get_uint_32(png_bytep buf)
  193712. {
  193713. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  193714. ((png_uint_32)(*(buf + 1)) << 16) +
  193715. ((png_uint_32)(*(buf + 2)) << 8) +
  193716. (png_uint_32)(*(buf + 3));
  193717. return (i);
  193718. }
  193719. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  193720. * data is stored in the PNG file in two's complement format, and it is
  193721. * assumed that the machine format for signed integers is the same. */
  193722. png_int_32 PNGAPI
  193723. png_get_int_32(png_bytep buf)
  193724. {
  193725. png_int_32 i = ((png_int_32)(*buf) << 24) +
  193726. ((png_int_32)(*(buf + 1)) << 16) +
  193727. ((png_int_32)(*(buf + 2)) << 8) +
  193728. (png_int_32)(*(buf + 3));
  193729. return (i);
  193730. }
  193731. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  193732. png_uint_16 PNGAPI
  193733. png_get_uint_16(png_bytep buf)
  193734. {
  193735. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  193736. (png_uint_16)(*(buf + 1)));
  193737. return (i);
  193738. }
  193739. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  193740. /* Read data, and (optionally) run it through the CRC. */
  193741. void /* PRIVATE */
  193742. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  193743. {
  193744. if(png_ptr == NULL) return;
  193745. png_read_data(png_ptr, buf, length);
  193746. png_calculate_crc(png_ptr, buf, length);
  193747. }
  193748. /* Optionally skip data and then check the CRC. Depending on whether we
  193749. are reading a ancillary or critical chunk, and how the program has set
  193750. things up, we may calculate the CRC on the data and print a message.
  193751. Returns '1' if there was a CRC error, '0' otherwise. */
  193752. int /* PRIVATE */
  193753. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  193754. {
  193755. png_size_t i;
  193756. png_size_t istop = png_ptr->zbuf_size;
  193757. for (i = (png_size_t)skip; i > istop; i -= istop)
  193758. {
  193759. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  193760. }
  193761. if (i)
  193762. {
  193763. png_crc_read(png_ptr, png_ptr->zbuf, i);
  193764. }
  193765. if (png_crc_error(png_ptr))
  193766. {
  193767. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  193768. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  193769. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  193770. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  193771. {
  193772. png_chunk_warning(png_ptr, "CRC error");
  193773. }
  193774. else
  193775. {
  193776. png_chunk_error(png_ptr, "CRC error");
  193777. }
  193778. return (1);
  193779. }
  193780. return (0);
  193781. }
  193782. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  193783. the data it has read thus far. */
  193784. int /* PRIVATE */
  193785. png_crc_error(png_structp png_ptr)
  193786. {
  193787. png_byte crc_bytes[4];
  193788. png_uint_32 crc;
  193789. int need_crc = 1;
  193790. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  193791. {
  193792. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  193793. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  193794. need_crc = 0;
  193795. }
  193796. else /* critical */
  193797. {
  193798. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  193799. need_crc = 0;
  193800. }
  193801. png_read_data(png_ptr, crc_bytes, 4);
  193802. if (need_crc)
  193803. {
  193804. crc = png_get_uint_32(crc_bytes);
  193805. return ((int)(crc != png_ptr->crc));
  193806. }
  193807. else
  193808. return (0);
  193809. }
  193810. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  193811. defined(PNG_READ_iCCP_SUPPORTED)
  193812. /*
  193813. * Decompress trailing data in a chunk. The assumption is that chunkdata
  193814. * points at an allocated area holding the contents of a chunk with a
  193815. * trailing compressed part. What we get back is an allocated area
  193816. * holding the original prefix part and an uncompressed version of the
  193817. * trailing part (the malloc area passed in is freed).
  193818. */
  193819. png_charp /* PRIVATE */
  193820. png_decompress_chunk(png_structp png_ptr, int comp_type,
  193821. png_charp chunkdata, png_size_t chunklength,
  193822. png_size_t prefix_size, png_size_t *newlength)
  193823. {
  193824. static PNG_CONST char msg[] = "Error decoding compressed text";
  193825. png_charp text;
  193826. png_size_t text_size;
  193827. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  193828. {
  193829. int ret = Z_OK;
  193830. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  193831. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  193832. png_ptr->zstream.next_out = png_ptr->zbuf;
  193833. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193834. text_size = 0;
  193835. text = NULL;
  193836. while (png_ptr->zstream.avail_in)
  193837. {
  193838. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  193839. if (ret != Z_OK && ret != Z_STREAM_END)
  193840. {
  193841. if (png_ptr->zstream.msg != NULL)
  193842. png_warning(png_ptr, png_ptr->zstream.msg);
  193843. else
  193844. png_warning(png_ptr, msg);
  193845. inflateReset(&png_ptr->zstream);
  193846. png_ptr->zstream.avail_in = 0;
  193847. if (text == NULL)
  193848. {
  193849. text_size = prefix_size + png_sizeof(msg) + 1;
  193850. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  193851. if (text == NULL)
  193852. {
  193853. png_free(png_ptr,chunkdata);
  193854. png_error(png_ptr,"Not enough memory to decompress chunk");
  193855. }
  193856. png_memcpy(text, chunkdata, prefix_size);
  193857. }
  193858. text[text_size - 1] = 0x00;
  193859. /* Copy what we can of the error message into the text chunk */
  193860. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  193861. text_size = png_sizeof(msg) > text_size ? text_size :
  193862. png_sizeof(msg);
  193863. png_memcpy(text + prefix_size, msg, text_size + 1);
  193864. break;
  193865. }
  193866. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  193867. {
  193868. if (text == NULL)
  193869. {
  193870. text_size = prefix_size +
  193871. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193872. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  193873. if (text == NULL)
  193874. {
  193875. png_free(png_ptr,chunkdata);
  193876. png_error(png_ptr,"Not enough memory to decompress chunk.");
  193877. }
  193878. png_memcpy(text + prefix_size, png_ptr->zbuf,
  193879. text_size - prefix_size);
  193880. png_memcpy(text, chunkdata, prefix_size);
  193881. *(text + text_size) = 0x00;
  193882. }
  193883. else
  193884. {
  193885. png_charp tmp;
  193886. tmp = text;
  193887. text = (png_charp)png_malloc_warn(png_ptr,
  193888. (png_uint_32)(text_size +
  193889. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  193890. if (text == NULL)
  193891. {
  193892. png_free(png_ptr, tmp);
  193893. png_free(png_ptr, chunkdata);
  193894. png_error(png_ptr,"Not enough memory to decompress chunk..");
  193895. }
  193896. png_memcpy(text, tmp, text_size);
  193897. png_free(png_ptr, tmp);
  193898. png_memcpy(text + text_size, png_ptr->zbuf,
  193899. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  193900. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193901. *(text + text_size) = 0x00;
  193902. }
  193903. if (ret == Z_STREAM_END)
  193904. break;
  193905. else
  193906. {
  193907. png_ptr->zstream.next_out = png_ptr->zbuf;
  193908. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193909. }
  193910. }
  193911. }
  193912. if (ret != Z_STREAM_END)
  193913. {
  193914. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193915. char umsg[52];
  193916. if (ret == Z_BUF_ERROR)
  193917. png_snprintf(umsg, 52,
  193918. "Buffer error in compressed datastream in %s chunk",
  193919. png_ptr->chunk_name);
  193920. else if (ret == Z_DATA_ERROR)
  193921. png_snprintf(umsg, 52,
  193922. "Data error in compressed datastream in %s chunk",
  193923. png_ptr->chunk_name);
  193924. else
  193925. png_snprintf(umsg, 52,
  193926. "Incomplete compressed datastream in %s chunk",
  193927. png_ptr->chunk_name);
  193928. png_warning(png_ptr, umsg);
  193929. #else
  193930. png_warning(png_ptr,
  193931. "Incomplete compressed datastream in chunk other than IDAT");
  193932. #endif
  193933. text_size=prefix_size;
  193934. if (text == NULL)
  193935. {
  193936. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  193937. if (text == NULL)
  193938. {
  193939. png_free(png_ptr, chunkdata);
  193940. png_error(png_ptr,"Not enough memory for text.");
  193941. }
  193942. png_memcpy(text, chunkdata, prefix_size);
  193943. }
  193944. *(text + text_size) = 0x00;
  193945. }
  193946. inflateReset(&png_ptr->zstream);
  193947. png_ptr->zstream.avail_in = 0;
  193948. png_free(png_ptr, chunkdata);
  193949. chunkdata = text;
  193950. *newlength=text_size;
  193951. }
  193952. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  193953. {
  193954. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193955. char umsg[50];
  193956. png_snprintf(umsg, 50,
  193957. "Unknown zTXt compression type %d", comp_type);
  193958. png_warning(png_ptr, umsg);
  193959. #else
  193960. png_warning(png_ptr, "Unknown zTXt compression type");
  193961. #endif
  193962. *(chunkdata + prefix_size) = 0x00;
  193963. *newlength=prefix_size;
  193964. }
  193965. return chunkdata;
  193966. }
  193967. #endif
  193968. /* read and check the IDHR chunk */
  193969. void /* PRIVATE */
  193970. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193971. {
  193972. png_byte buf[13];
  193973. png_uint_32 width, height;
  193974. int bit_depth, color_type, compression_type, filter_type;
  193975. int interlace_type;
  193976. png_debug(1, "in png_handle_IHDR\n");
  193977. if (png_ptr->mode & PNG_HAVE_IHDR)
  193978. png_error(png_ptr, "Out of place IHDR");
  193979. /* check the length */
  193980. if (length != 13)
  193981. png_error(png_ptr, "Invalid IHDR chunk");
  193982. png_ptr->mode |= PNG_HAVE_IHDR;
  193983. png_crc_read(png_ptr, buf, 13);
  193984. png_crc_finish(png_ptr, 0);
  193985. width = png_get_uint_31(png_ptr, buf);
  193986. height = png_get_uint_31(png_ptr, buf + 4);
  193987. bit_depth = buf[8];
  193988. color_type = buf[9];
  193989. compression_type = buf[10];
  193990. filter_type = buf[11];
  193991. interlace_type = buf[12];
  193992. /* set internal variables */
  193993. png_ptr->width = width;
  193994. png_ptr->height = height;
  193995. png_ptr->bit_depth = (png_byte)bit_depth;
  193996. png_ptr->interlaced = (png_byte)interlace_type;
  193997. png_ptr->color_type = (png_byte)color_type;
  193998. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193999. png_ptr->filter_type = (png_byte)filter_type;
  194000. #endif
  194001. png_ptr->compression_type = (png_byte)compression_type;
  194002. /* find number of channels */
  194003. switch (png_ptr->color_type)
  194004. {
  194005. case PNG_COLOR_TYPE_GRAY:
  194006. case PNG_COLOR_TYPE_PALETTE:
  194007. png_ptr->channels = 1;
  194008. break;
  194009. case PNG_COLOR_TYPE_RGB:
  194010. png_ptr->channels = 3;
  194011. break;
  194012. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194013. png_ptr->channels = 2;
  194014. break;
  194015. case PNG_COLOR_TYPE_RGB_ALPHA:
  194016. png_ptr->channels = 4;
  194017. break;
  194018. }
  194019. /* set up other useful info */
  194020. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194021. png_ptr->channels);
  194022. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194023. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194024. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194025. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194026. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194027. color_type, interlace_type, compression_type, filter_type);
  194028. }
  194029. /* read and check the palette */
  194030. void /* PRIVATE */
  194031. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194032. {
  194033. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194034. int num, i;
  194035. #ifndef PNG_NO_POINTER_INDEXING
  194036. png_colorp pal_ptr;
  194037. #endif
  194038. png_debug(1, "in png_handle_PLTE\n");
  194039. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194040. png_error(png_ptr, "Missing IHDR before PLTE");
  194041. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194042. {
  194043. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194044. png_crc_finish(png_ptr, length);
  194045. return;
  194046. }
  194047. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194048. png_error(png_ptr, "Duplicate PLTE chunk");
  194049. png_ptr->mode |= PNG_HAVE_PLTE;
  194050. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194051. {
  194052. png_warning(png_ptr,
  194053. "Ignoring PLTE chunk in grayscale PNG");
  194054. png_crc_finish(png_ptr, length);
  194055. return;
  194056. }
  194057. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194058. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194059. {
  194060. png_crc_finish(png_ptr, length);
  194061. return;
  194062. }
  194063. #endif
  194064. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194065. {
  194066. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194067. {
  194068. png_warning(png_ptr, "Invalid palette chunk");
  194069. png_crc_finish(png_ptr, length);
  194070. return;
  194071. }
  194072. else
  194073. {
  194074. png_error(png_ptr, "Invalid palette chunk");
  194075. }
  194076. }
  194077. num = (int)length / 3;
  194078. #ifndef PNG_NO_POINTER_INDEXING
  194079. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194080. {
  194081. png_byte buf[3];
  194082. png_crc_read(png_ptr, buf, 3);
  194083. pal_ptr->red = buf[0];
  194084. pal_ptr->green = buf[1];
  194085. pal_ptr->blue = buf[2];
  194086. }
  194087. #else
  194088. for (i = 0; i < num; i++)
  194089. {
  194090. png_byte buf[3];
  194091. png_crc_read(png_ptr, buf, 3);
  194092. /* don't depend upon png_color being any order */
  194093. palette[i].red = buf[0];
  194094. palette[i].green = buf[1];
  194095. palette[i].blue = buf[2];
  194096. }
  194097. #endif
  194098. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194099. whatever the normal CRC configuration tells us. However, if we
  194100. have an RGB image, the PLTE can be considered ancillary, so
  194101. we will act as though it is. */
  194102. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194103. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194104. #endif
  194105. {
  194106. png_crc_finish(png_ptr, 0);
  194107. }
  194108. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194109. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194110. {
  194111. /* If we don't want to use the data from an ancillary chunk,
  194112. we have two options: an error abort, or a warning and we
  194113. ignore the data in this chunk (which should be OK, since
  194114. it's considered ancillary for a RGB or RGBA image). */
  194115. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194116. {
  194117. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194118. {
  194119. png_chunk_error(png_ptr, "CRC error");
  194120. }
  194121. else
  194122. {
  194123. png_chunk_warning(png_ptr, "CRC error");
  194124. return;
  194125. }
  194126. }
  194127. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194128. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194129. {
  194130. png_chunk_warning(png_ptr, "CRC error");
  194131. }
  194132. }
  194133. #endif
  194134. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194135. #if defined(PNG_READ_tRNS_SUPPORTED)
  194136. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194137. {
  194138. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194139. {
  194140. if (png_ptr->num_trans > (png_uint_16)num)
  194141. {
  194142. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194143. png_ptr->num_trans = (png_uint_16)num;
  194144. }
  194145. if (info_ptr->num_trans > (png_uint_16)num)
  194146. {
  194147. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194148. info_ptr->num_trans = (png_uint_16)num;
  194149. }
  194150. }
  194151. }
  194152. #endif
  194153. }
  194154. void /* PRIVATE */
  194155. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194156. {
  194157. png_debug(1, "in png_handle_IEND\n");
  194158. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194159. {
  194160. png_error(png_ptr, "No image in file");
  194161. }
  194162. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194163. if (length != 0)
  194164. {
  194165. png_warning(png_ptr, "Incorrect IEND chunk length");
  194166. }
  194167. png_crc_finish(png_ptr, length);
  194168. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194169. }
  194170. #if defined(PNG_READ_gAMA_SUPPORTED)
  194171. void /* PRIVATE */
  194172. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194173. {
  194174. png_fixed_point igamma;
  194175. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194176. float file_gamma;
  194177. #endif
  194178. png_byte buf[4];
  194179. png_debug(1, "in png_handle_gAMA\n");
  194180. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194181. png_error(png_ptr, "Missing IHDR before gAMA");
  194182. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194183. {
  194184. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194185. png_crc_finish(png_ptr, length);
  194186. return;
  194187. }
  194188. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194189. /* Should be an error, but we can cope with it */
  194190. png_warning(png_ptr, "Out of place gAMA chunk");
  194191. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194192. #if defined(PNG_READ_sRGB_SUPPORTED)
  194193. && !(info_ptr->valid & PNG_INFO_sRGB)
  194194. #endif
  194195. )
  194196. {
  194197. png_warning(png_ptr, "Duplicate gAMA chunk");
  194198. png_crc_finish(png_ptr, length);
  194199. return;
  194200. }
  194201. if (length != 4)
  194202. {
  194203. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194204. png_crc_finish(png_ptr, length);
  194205. return;
  194206. }
  194207. png_crc_read(png_ptr, buf, 4);
  194208. if (png_crc_finish(png_ptr, 0))
  194209. return;
  194210. igamma = (png_fixed_point)png_get_uint_32(buf);
  194211. /* check for zero gamma */
  194212. if (igamma == 0)
  194213. {
  194214. png_warning(png_ptr,
  194215. "Ignoring gAMA chunk with gamma=0");
  194216. return;
  194217. }
  194218. #if defined(PNG_READ_sRGB_SUPPORTED)
  194219. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194220. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194221. {
  194222. png_warning(png_ptr,
  194223. "Ignoring incorrect gAMA value when sRGB is also present");
  194224. #ifndef PNG_NO_CONSOLE_IO
  194225. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194226. #endif
  194227. return;
  194228. }
  194229. #endif /* PNG_READ_sRGB_SUPPORTED */
  194230. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194231. file_gamma = (float)igamma / (float)100000.0;
  194232. # ifdef PNG_READ_GAMMA_SUPPORTED
  194233. png_ptr->gamma = file_gamma;
  194234. # endif
  194235. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194236. #endif
  194237. #ifdef PNG_FIXED_POINT_SUPPORTED
  194238. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194239. #endif
  194240. }
  194241. #endif
  194242. #if defined(PNG_READ_sBIT_SUPPORTED)
  194243. void /* PRIVATE */
  194244. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194245. {
  194246. png_size_t truelen;
  194247. png_byte buf[4];
  194248. png_debug(1, "in png_handle_sBIT\n");
  194249. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194250. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194251. png_error(png_ptr, "Missing IHDR before sBIT");
  194252. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194253. {
  194254. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194255. png_crc_finish(png_ptr, length);
  194256. return;
  194257. }
  194258. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194259. {
  194260. /* Should be an error, but we can cope with it */
  194261. png_warning(png_ptr, "Out of place sBIT chunk");
  194262. }
  194263. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194264. {
  194265. png_warning(png_ptr, "Duplicate sBIT chunk");
  194266. png_crc_finish(png_ptr, length);
  194267. return;
  194268. }
  194269. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194270. truelen = 3;
  194271. else
  194272. truelen = (png_size_t)png_ptr->channels;
  194273. if (length != truelen || length > 4)
  194274. {
  194275. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194276. png_crc_finish(png_ptr, length);
  194277. return;
  194278. }
  194279. png_crc_read(png_ptr, buf, truelen);
  194280. if (png_crc_finish(png_ptr, 0))
  194281. return;
  194282. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194283. {
  194284. png_ptr->sig_bit.red = buf[0];
  194285. png_ptr->sig_bit.green = buf[1];
  194286. png_ptr->sig_bit.blue = buf[2];
  194287. png_ptr->sig_bit.alpha = buf[3];
  194288. }
  194289. else
  194290. {
  194291. png_ptr->sig_bit.gray = buf[0];
  194292. png_ptr->sig_bit.red = buf[0];
  194293. png_ptr->sig_bit.green = buf[0];
  194294. png_ptr->sig_bit.blue = buf[0];
  194295. png_ptr->sig_bit.alpha = buf[1];
  194296. }
  194297. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194298. }
  194299. #endif
  194300. #if defined(PNG_READ_cHRM_SUPPORTED)
  194301. void /* PRIVATE */
  194302. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194303. {
  194304. png_byte buf[4];
  194305. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194306. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194307. #endif
  194308. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194309. int_y_green, int_x_blue, int_y_blue;
  194310. png_uint_32 uint_x, uint_y;
  194311. png_debug(1, "in png_handle_cHRM\n");
  194312. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194313. png_error(png_ptr, "Missing IHDR before cHRM");
  194314. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194315. {
  194316. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194317. png_crc_finish(png_ptr, length);
  194318. return;
  194319. }
  194320. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194321. /* Should be an error, but we can cope with it */
  194322. png_warning(png_ptr, "Missing PLTE before cHRM");
  194323. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194324. #if defined(PNG_READ_sRGB_SUPPORTED)
  194325. && !(info_ptr->valid & PNG_INFO_sRGB)
  194326. #endif
  194327. )
  194328. {
  194329. png_warning(png_ptr, "Duplicate cHRM chunk");
  194330. png_crc_finish(png_ptr, length);
  194331. return;
  194332. }
  194333. if (length != 32)
  194334. {
  194335. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194336. png_crc_finish(png_ptr, length);
  194337. return;
  194338. }
  194339. png_crc_read(png_ptr, buf, 4);
  194340. uint_x = png_get_uint_32(buf);
  194341. png_crc_read(png_ptr, buf, 4);
  194342. uint_y = png_get_uint_32(buf);
  194343. if (uint_x > 80000L || uint_y > 80000L ||
  194344. uint_x + uint_y > 100000L)
  194345. {
  194346. png_warning(png_ptr, "Invalid cHRM white point");
  194347. png_crc_finish(png_ptr, 24);
  194348. return;
  194349. }
  194350. int_x_white = (png_fixed_point)uint_x;
  194351. int_y_white = (png_fixed_point)uint_y;
  194352. png_crc_read(png_ptr, buf, 4);
  194353. uint_x = png_get_uint_32(buf);
  194354. png_crc_read(png_ptr, buf, 4);
  194355. uint_y = png_get_uint_32(buf);
  194356. if (uint_x + uint_y > 100000L)
  194357. {
  194358. png_warning(png_ptr, "Invalid cHRM red point");
  194359. png_crc_finish(png_ptr, 16);
  194360. return;
  194361. }
  194362. int_x_red = (png_fixed_point)uint_x;
  194363. int_y_red = (png_fixed_point)uint_y;
  194364. png_crc_read(png_ptr, buf, 4);
  194365. uint_x = png_get_uint_32(buf);
  194366. png_crc_read(png_ptr, buf, 4);
  194367. uint_y = png_get_uint_32(buf);
  194368. if (uint_x + uint_y > 100000L)
  194369. {
  194370. png_warning(png_ptr, "Invalid cHRM green point");
  194371. png_crc_finish(png_ptr, 8);
  194372. return;
  194373. }
  194374. int_x_green = (png_fixed_point)uint_x;
  194375. int_y_green = (png_fixed_point)uint_y;
  194376. png_crc_read(png_ptr, buf, 4);
  194377. uint_x = png_get_uint_32(buf);
  194378. png_crc_read(png_ptr, buf, 4);
  194379. uint_y = png_get_uint_32(buf);
  194380. if (uint_x + uint_y > 100000L)
  194381. {
  194382. png_warning(png_ptr, "Invalid cHRM blue point");
  194383. png_crc_finish(png_ptr, 0);
  194384. return;
  194385. }
  194386. int_x_blue = (png_fixed_point)uint_x;
  194387. int_y_blue = (png_fixed_point)uint_y;
  194388. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194389. white_x = (float)int_x_white / (float)100000.0;
  194390. white_y = (float)int_y_white / (float)100000.0;
  194391. red_x = (float)int_x_red / (float)100000.0;
  194392. red_y = (float)int_y_red / (float)100000.0;
  194393. green_x = (float)int_x_green / (float)100000.0;
  194394. green_y = (float)int_y_green / (float)100000.0;
  194395. blue_x = (float)int_x_blue / (float)100000.0;
  194396. blue_y = (float)int_y_blue / (float)100000.0;
  194397. #endif
  194398. #if defined(PNG_READ_sRGB_SUPPORTED)
  194399. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194400. {
  194401. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194402. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194403. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194404. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194405. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194406. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194407. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194408. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194409. {
  194410. png_warning(png_ptr,
  194411. "Ignoring incorrect cHRM value when sRGB is also present");
  194412. #ifndef PNG_NO_CONSOLE_IO
  194413. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194414. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194415. white_x, white_y, red_x, red_y);
  194416. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194417. green_x, green_y, blue_x, blue_y);
  194418. #else
  194419. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194420. int_x_white, int_y_white, int_x_red, int_y_red);
  194421. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194422. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194423. #endif
  194424. #endif /* PNG_NO_CONSOLE_IO */
  194425. }
  194426. png_crc_finish(png_ptr, 0);
  194427. return;
  194428. }
  194429. #endif /* PNG_READ_sRGB_SUPPORTED */
  194430. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194431. png_set_cHRM(png_ptr, info_ptr,
  194432. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194433. #endif
  194434. #ifdef PNG_FIXED_POINT_SUPPORTED
  194435. png_set_cHRM_fixed(png_ptr, info_ptr,
  194436. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194437. int_y_green, int_x_blue, int_y_blue);
  194438. #endif
  194439. if (png_crc_finish(png_ptr, 0))
  194440. return;
  194441. }
  194442. #endif
  194443. #if defined(PNG_READ_sRGB_SUPPORTED)
  194444. void /* PRIVATE */
  194445. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194446. {
  194447. int intent;
  194448. png_byte buf[1];
  194449. png_debug(1, "in png_handle_sRGB\n");
  194450. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194451. png_error(png_ptr, "Missing IHDR before sRGB");
  194452. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194453. {
  194454. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194455. png_crc_finish(png_ptr, length);
  194456. return;
  194457. }
  194458. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194459. /* Should be an error, but we can cope with it */
  194460. png_warning(png_ptr, "Out of place sRGB chunk");
  194461. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194462. {
  194463. png_warning(png_ptr, "Duplicate sRGB chunk");
  194464. png_crc_finish(png_ptr, length);
  194465. return;
  194466. }
  194467. if (length != 1)
  194468. {
  194469. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194470. png_crc_finish(png_ptr, length);
  194471. return;
  194472. }
  194473. png_crc_read(png_ptr, buf, 1);
  194474. if (png_crc_finish(png_ptr, 0))
  194475. return;
  194476. intent = buf[0];
  194477. /* check for bad intent */
  194478. if (intent >= PNG_sRGB_INTENT_LAST)
  194479. {
  194480. png_warning(png_ptr, "Unknown sRGB intent");
  194481. return;
  194482. }
  194483. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194484. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194485. {
  194486. png_fixed_point igamma;
  194487. #ifdef PNG_FIXED_POINT_SUPPORTED
  194488. igamma=info_ptr->int_gamma;
  194489. #else
  194490. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194491. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  194492. # endif
  194493. #endif
  194494. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194495. {
  194496. png_warning(png_ptr,
  194497. "Ignoring incorrect gAMA value when sRGB is also present");
  194498. #ifndef PNG_NO_CONSOLE_IO
  194499. # ifdef PNG_FIXED_POINT_SUPPORTED
  194500. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  194501. # else
  194502. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194503. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  194504. # endif
  194505. # endif
  194506. #endif
  194507. }
  194508. }
  194509. #endif /* PNG_READ_gAMA_SUPPORTED */
  194510. #ifdef PNG_READ_cHRM_SUPPORTED
  194511. #ifdef PNG_FIXED_POINT_SUPPORTED
  194512. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  194513. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  194514. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  194515. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  194516. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  194517. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  194518. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  194519. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  194520. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  194521. {
  194522. png_warning(png_ptr,
  194523. "Ignoring incorrect cHRM value when sRGB is also present");
  194524. }
  194525. #endif /* PNG_FIXED_POINT_SUPPORTED */
  194526. #endif /* PNG_READ_cHRM_SUPPORTED */
  194527. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  194528. }
  194529. #endif /* PNG_READ_sRGB_SUPPORTED */
  194530. #if defined(PNG_READ_iCCP_SUPPORTED)
  194531. void /* PRIVATE */
  194532. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194533. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194534. {
  194535. png_charp chunkdata;
  194536. png_byte compression_type;
  194537. png_bytep pC;
  194538. png_charp profile;
  194539. png_uint_32 skip = 0;
  194540. png_uint_32 profile_size, profile_length;
  194541. png_size_t slength, prefix_length, data_length;
  194542. png_debug(1, "in png_handle_iCCP\n");
  194543. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194544. png_error(png_ptr, "Missing IHDR before iCCP");
  194545. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194546. {
  194547. png_warning(png_ptr, "Invalid iCCP after IDAT");
  194548. png_crc_finish(png_ptr, length);
  194549. return;
  194550. }
  194551. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194552. /* Should be an error, but we can cope with it */
  194553. png_warning(png_ptr, "Out of place iCCP chunk");
  194554. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  194555. {
  194556. png_warning(png_ptr, "Duplicate iCCP chunk");
  194557. png_crc_finish(png_ptr, length);
  194558. return;
  194559. }
  194560. #ifdef PNG_MAX_MALLOC_64K
  194561. if (length > (png_uint_32)65535L)
  194562. {
  194563. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  194564. skip = length - (png_uint_32)65535L;
  194565. length = (png_uint_32)65535L;
  194566. }
  194567. #endif
  194568. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  194569. slength = (png_size_t)length;
  194570. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194571. if (png_crc_finish(png_ptr, skip))
  194572. {
  194573. png_free(png_ptr, chunkdata);
  194574. return;
  194575. }
  194576. chunkdata[slength] = 0x00;
  194577. for (profile = chunkdata; *profile; profile++)
  194578. /* empty loop to find end of name */ ;
  194579. ++profile;
  194580. /* there should be at least one zero (the compression type byte)
  194581. following the separator, and we should be on it */
  194582. if ( profile >= chunkdata + slength - 1)
  194583. {
  194584. png_free(png_ptr, chunkdata);
  194585. png_warning(png_ptr, "Malformed iCCP chunk");
  194586. return;
  194587. }
  194588. /* compression_type should always be zero */
  194589. compression_type = *profile++;
  194590. if (compression_type)
  194591. {
  194592. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  194593. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  194594. wrote nonzero) */
  194595. }
  194596. prefix_length = profile - chunkdata;
  194597. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  194598. slength, prefix_length, &data_length);
  194599. profile_length = data_length - prefix_length;
  194600. if ( prefix_length > data_length || profile_length < 4)
  194601. {
  194602. png_free(png_ptr, chunkdata);
  194603. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  194604. return;
  194605. }
  194606. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  194607. pC = (png_bytep)(chunkdata+prefix_length);
  194608. profile_size = ((*(pC ))<<24) |
  194609. ((*(pC+1))<<16) |
  194610. ((*(pC+2))<< 8) |
  194611. ((*(pC+3)) );
  194612. if(profile_size < profile_length)
  194613. profile_length = profile_size;
  194614. if(profile_size > profile_length)
  194615. {
  194616. png_free(png_ptr, chunkdata);
  194617. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  194618. return;
  194619. }
  194620. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  194621. chunkdata + prefix_length, profile_length);
  194622. png_free(png_ptr, chunkdata);
  194623. }
  194624. #endif /* PNG_READ_iCCP_SUPPORTED */
  194625. #if defined(PNG_READ_sPLT_SUPPORTED)
  194626. void /* PRIVATE */
  194627. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194628. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194629. {
  194630. png_bytep chunkdata;
  194631. png_bytep entry_start;
  194632. png_sPLT_t new_palette;
  194633. #ifdef PNG_NO_POINTER_INDEXING
  194634. png_sPLT_entryp pp;
  194635. #endif
  194636. int data_length, entry_size, i;
  194637. png_uint_32 skip = 0;
  194638. png_size_t slength;
  194639. png_debug(1, "in png_handle_sPLT\n");
  194640. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194641. png_error(png_ptr, "Missing IHDR before sPLT");
  194642. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194643. {
  194644. png_warning(png_ptr, "Invalid sPLT after IDAT");
  194645. png_crc_finish(png_ptr, length);
  194646. return;
  194647. }
  194648. #ifdef PNG_MAX_MALLOC_64K
  194649. if (length > (png_uint_32)65535L)
  194650. {
  194651. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  194652. skip = length - (png_uint_32)65535L;
  194653. length = (png_uint_32)65535L;
  194654. }
  194655. #endif
  194656. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  194657. slength = (png_size_t)length;
  194658. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194659. if (png_crc_finish(png_ptr, skip))
  194660. {
  194661. png_free(png_ptr, chunkdata);
  194662. return;
  194663. }
  194664. chunkdata[slength] = 0x00;
  194665. for (entry_start = chunkdata; *entry_start; entry_start++)
  194666. /* empty loop to find end of name */ ;
  194667. ++entry_start;
  194668. /* a sample depth should follow the separator, and we should be on it */
  194669. if (entry_start > chunkdata + slength - 2)
  194670. {
  194671. png_free(png_ptr, chunkdata);
  194672. png_warning(png_ptr, "malformed sPLT chunk");
  194673. return;
  194674. }
  194675. new_palette.depth = *entry_start++;
  194676. entry_size = (new_palette.depth == 8 ? 6 : 10);
  194677. data_length = (slength - (entry_start - chunkdata));
  194678. /* integrity-check the data length */
  194679. if (data_length % entry_size)
  194680. {
  194681. png_free(png_ptr, chunkdata);
  194682. png_warning(png_ptr, "sPLT chunk has bad length");
  194683. return;
  194684. }
  194685. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  194686. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  194687. png_sizeof(png_sPLT_entry)))
  194688. {
  194689. png_warning(png_ptr, "sPLT chunk too long");
  194690. return;
  194691. }
  194692. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  194693. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  194694. if (new_palette.entries == NULL)
  194695. {
  194696. png_warning(png_ptr, "sPLT chunk requires too much memory");
  194697. return;
  194698. }
  194699. #ifndef PNG_NO_POINTER_INDEXING
  194700. for (i = 0; i < new_palette.nentries; i++)
  194701. {
  194702. png_sPLT_entryp pp = new_palette.entries + i;
  194703. if (new_palette.depth == 8)
  194704. {
  194705. pp->red = *entry_start++;
  194706. pp->green = *entry_start++;
  194707. pp->blue = *entry_start++;
  194708. pp->alpha = *entry_start++;
  194709. }
  194710. else
  194711. {
  194712. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  194713. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  194714. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  194715. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  194716. }
  194717. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194718. }
  194719. #else
  194720. pp = new_palette.entries;
  194721. for (i = 0; i < new_palette.nentries; i++)
  194722. {
  194723. if (new_palette.depth == 8)
  194724. {
  194725. pp[i].red = *entry_start++;
  194726. pp[i].green = *entry_start++;
  194727. pp[i].blue = *entry_start++;
  194728. pp[i].alpha = *entry_start++;
  194729. }
  194730. else
  194731. {
  194732. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  194733. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  194734. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  194735. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  194736. }
  194737. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194738. }
  194739. #endif
  194740. /* discard all chunk data except the name and stash that */
  194741. new_palette.name = (png_charp)chunkdata;
  194742. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  194743. png_free(png_ptr, chunkdata);
  194744. png_free(png_ptr, new_palette.entries);
  194745. }
  194746. #endif /* PNG_READ_sPLT_SUPPORTED */
  194747. #if defined(PNG_READ_tRNS_SUPPORTED)
  194748. void /* PRIVATE */
  194749. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194750. {
  194751. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  194752. int bit_mask;
  194753. png_debug(1, "in png_handle_tRNS\n");
  194754. /* For non-indexed color, mask off any bits in the tRNS value that
  194755. * exceed the bit depth. Some creators were writing extra bits there.
  194756. * This is not needed for indexed color. */
  194757. bit_mask = (1 << png_ptr->bit_depth) - 1;
  194758. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194759. png_error(png_ptr, "Missing IHDR before tRNS");
  194760. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194761. {
  194762. png_warning(png_ptr, "Invalid tRNS after IDAT");
  194763. png_crc_finish(png_ptr, length);
  194764. return;
  194765. }
  194766. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194767. {
  194768. png_warning(png_ptr, "Duplicate tRNS chunk");
  194769. png_crc_finish(png_ptr, length);
  194770. return;
  194771. }
  194772. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  194773. {
  194774. png_byte buf[2];
  194775. if (length != 2)
  194776. {
  194777. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194778. png_crc_finish(png_ptr, length);
  194779. return;
  194780. }
  194781. png_crc_read(png_ptr, buf, 2);
  194782. png_ptr->num_trans = 1;
  194783. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  194784. }
  194785. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  194786. {
  194787. png_byte buf[6];
  194788. if (length != 6)
  194789. {
  194790. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194791. png_crc_finish(png_ptr, length);
  194792. return;
  194793. }
  194794. png_crc_read(png_ptr, buf, (png_size_t)length);
  194795. png_ptr->num_trans = 1;
  194796. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  194797. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  194798. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  194799. }
  194800. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194801. {
  194802. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194803. {
  194804. /* Should be an error, but we can cope with it. */
  194805. png_warning(png_ptr, "Missing PLTE before tRNS");
  194806. }
  194807. if (length > (png_uint_32)png_ptr->num_palette ||
  194808. length > PNG_MAX_PALETTE_LENGTH)
  194809. {
  194810. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194811. png_crc_finish(png_ptr, length);
  194812. return;
  194813. }
  194814. if (length == 0)
  194815. {
  194816. png_warning(png_ptr, "Zero length tRNS chunk");
  194817. png_crc_finish(png_ptr, length);
  194818. return;
  194819. }
  194820. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  194821. png_ptr->num_trans = (png_uint_16)length;
  194822. }
  194823. else
  194824. {
  194825. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  194826. png_crc_finish(png_ptr, length);
  194827. return;
  194828. }
  194829. if (png_crc_finish(png_ptr, 0))
  194830. {
  194831. png_ptr->num_trans = 0;
  194832. return;
  194833. }
  194834. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  194835. &(png_ptr->trans_values));
  194836. }
  194837. #endif
  194838. #if defined(PNG_READ_bKGD_SUPPORTED)
  194839. void /* PRIVATE */
  194840. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194841. {
  194842. png_size_t truelen;
  194843. png_byte buf[6];
  194844. png_debug(1, "in png_handle_bKGD\n");
  194845. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194846. png_error(png_ptr, "Missing IHDR before bKGD");
  194847. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194848. {
  194849. png_warning(png_ptr, "Invalid bKGD after IDAT");
  194850. png_crc_finish(png_ptr, length);
  194851. return;
  194852. }
  194853. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  194854. !(png_ptr->mode & PNG_HAVE_PLTE))
  194855. {
  194856. png_warning(png_ptr, "Missing PLTE before bKGD");
  194857. png_crc_finish(png_ptr, length);
  194858. return;
  194859. }
  194860. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  194861. {
  194862. png_warning(png_ptr, "Duplicate bKGD chunk");
  194863. png_crc_finish(png_ptr, length);
  194864. return;
  194865. }
  194866. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194867. truelen = 1;
  194868. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194869. truelen = 6;
  194870. else
  194871. truelen = 2;
  194872. if (length != truelen)
  194873. {
  194874. png_warning(png_ptr, "Incorrect bKGD chunk length");
  194875. png_crc_finish(png_ptr, length);
  194876. return;
  194877. }
  194878. png_crc_read(png_ptr, buf, truelen);
  194879. if (png_crc_finish(png_ptr, 0))
  194880. return;
  194881. /* We convert the index value into RGB components so that we can allow
  194882. * arbitrary RGB values for background when we have transparency, and
  194883. * so it is easy to determine the RGB values of the background color
  194884. * from the info_ptr struct. */
  194885. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194886. {
  194887. png_ptr->background.index = buf[0];
  194888. if(info_ptr->num_palette)
  194889. {
  194890. if(buf[0] > info_ptr->num_palette)
  194891. {
  194892. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  194893. return;
  194894. }
  194895. png_ptr->background.red =
  194896. (png_uint_16)png_ptr->palette[buf[0]].red;
  194897. png_ptr->background.green =
  194898. (png_uint_16)png_ptr->palette[buf[0]].green;
  194899. png_ptr->background.blue =
  194900. (png_uint_16)png_ptr->palette[buf[0]].blue;
  194901. }
  194902. }
  194903. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  194904. {
  194905. png_ptr->background.red =
  194906. png_ptr->background.green =
  194907. png_ptr->background.blue =
  194908. png_ptr->background.gray = png_get_uint_16(buf);
  194909. }
  194910. else
  194911. {
  194912. png_ptr->background.red = png_get_uint_16(buf);
  194913. png_ptr->background.green = png_get_uint_16(buf + 2);
  194914. png_ptr->background.blue = png_get_uint_16(buf + 4);
  194915. }
  194916. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  194917. }
  194918. #endif
  194919. #if defined(PNG_READ_hIST_SUPPORTED)
  194920. void /* PRIVATE */
  194921. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194922. {
  194923. unsigned int num, i;
  194924. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  194925. png_debug(1, "in png_handle_hIST\n");
  194926. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194927. png_error(png_ptr, "Missing IHDR before hIST");
  194928. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194929. {
  194930. png_warning(png_ptr, "Invalid hIST after IDAT");
  194931. png_crc_finish(png_ptr, length);
  194932. return;
  194933. }
  194934. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194935. {
  194936. png_warning(png_ptr, "Missing PLTE before hIST");
  194937. png_crc_finish(png_ptr, length);
  194938. return;
  194939. }
  194940. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  194941. {
  194942. png_warning(png_ptr, "Duplicate hIST chunk");
  194943. png_crc_finish(png_ptr, length);
  194944. return;
  194945. }
  194946. num = length / 2 ;
  194947. if (num != (unsigned int) png_ptr->num_palette || num >
  194948. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  194949. {
  194950. png_warning(png_ptr, "Incorrect hIST chunk length");
  194951. png_crc_finish(png_ptr, length);
  194952. return;
  194953. }
  194954. for (i = 0; i < num; i++)
  194955. {
  194956. png_byte buf[2];
  194957. png_crc_read(png_ptr, buf, 2);
  194958. readbuf[i] = png_get_uint_16(buf);
  194959. }
  194960. if (png_crc_finish(png_ptr, 0))
  194961. return;
  194962. png_set_hIST(png_ptr, info_ptr, readbuf);
  194963. }
  194964. #endif
  194965. #if defined(PNG_READ_pHYs_SUPPORTED)
  194966. void /* PRIVATE */
  194967. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194968. {
  194969. png_byte buf[9];
  194970. png_uint_32 res_x, res_y;
  194971. int unit_type;
  194972. png_debug(1, "in png_handle_pHYs\n");
  194973. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194974. png_error(png_ptr, "Missing IHDR before pHYs");
  194975. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194976. {
  194977. png_warning(png_ptr, "Invalid pHYs after IDAT");
  194978. png_crc_finish(png_ptr, length);
  194979. return;
  194980. }
  194981. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  194982. {
  194983. png_warning(png_ptr, "Duplicate pHYs chunk");
  194984. png_crc_finish(png_ptr, length);
  194985. return;
  194986. }
  194987. if (length != 9)
  194988. {
  194989. png_warning(png_ptr, "Incorrect pHYs chunk length");
  194990. png_crc_finish(png_ptr, length);
  194991. return;
  194992. }
  194993. png_crc_read(png_ptr, buf, 9);
  194994. if (png_crc_finish(png_ptr, 0))
  194995. return;
  194996. res_x = png_get_uint_32(buf);
  194997. res_y = png_get_uint_32(buf + 4);
  194998. unit_type = buf[8];
  194999. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  195000. }
  195001. #endif
  195002. #if defined(PNG_READ_oFFs_SUPPORTED)
  195003. void /* PRIVATE */
  195004. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195005. {
  195006. png_byte buf[9];
  195007. png_int_32 offset_x, offset_y;
  195008. int unit_type;
  195009. png_debug(1, "in png_handle_oFFs\n");
  195010. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195011. png_error(png_ptr, "Missing IHDR before oFFs");
  195012. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195013. {
  195014. png_warning(png_ptr, "Invalid oFFs after IDAT");
  195015. png_crc_finish(png_ptr, length);
  195016. return;
  195017. }
  195018. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195019. {
  195020. png_warning(png_ptr, "Duplicate oFFs chunk");
  195021. png_crc_finish(png_ptr, length);
  195022. return;
  195023. }
  195024. if (length != 9)
  195025. {
  195026. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195027. png_crc_finish(png_ptr, length);
  195028. return;
  195029. }
  195030. png_crc_read(png_ptr, buf, 9);
  195031. if (png_crc_finish(png_ptr, 0))
  195032. return;
  195033. offset_x = png_get_int_32(buf);
  195034. offset_y = png_get_int_32(buf + 4);
  195035. unit_type = buf[8];
  195036. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195037. }
  195038. #endif
  195039. #if defined(PNG_READ_pCAL_SUPPORTED)
  195040. /* read the pCAL chunk (described in the PNG Extensions document) */
  195041. void /* PRIVATE */
  195042. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195043. {
  195044. png_charp purpose;
  195045. png_int_32 X0, X1;
  195046. png_byte type, nparams;
  195047. png_charp buf, units, endptr;
  195048. png_charpp params;
  195049. png_size_t slength;
  195050. int i;
  195051. png_debug(1, "in png_handle_pCAL\n");
  195052. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195053. png_error(png_ptr, "Missing IHDR before pCAL");
  195054. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195055. {
  195056. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195057. png_crc_finish(png_ptr, length);
  195058. return;
  195059. }
  195060. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195061. {
  195062. png_warning(png_ptr, "Duplicate pCAL chunk");
  195063. png_crc_finish(png_ptr, length);
  195064. return;
  195065. }
  195066. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195067. length + 1);
  195068. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195069. if (purpose == NULL)
  195070. {
  195071. png_warning(png_ptr, "No memory for pCAL purpose.");
  195072. return;
  195073. }
  195074. slength = (png_size_t)length;
  195075. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195076. if (png_crc_finish(png_ptr, 0))
  195077. {
  195078. png_free(png_ptr, purpose);
  195079. return;
  195080. }
  195081. purpose[slength] = 0x00; /* null terminate the last string */
  195082. png_debug(3, "Finding end of pCAL purpose string\n");
  195083. for (buf = purpose; *buf; buf++)
  195084. /* empty loop */ ;
  195085. endptr = purpose + slength;
  195086. /* We need to have at least 12 bytes after the purpose string
  195087. in order to get the parameter information. */
  195088. if (endptr <= buf + 12)
  195089. {
  195090. png_warning(png_ptr, "Invalid pCAL data");
  195091. png_free(png_ptr, purpose);
  195092. return;
  195093. }
  195094. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195095. X0 = png_get_int_32((png_bytep)buf+1);
  195096. X1 = png_get_int_32((png_bytep)buf+5);
  195097. type = buf[9];
  195098. nparams = buf[10];
  195099. units = buf + 11;
  195100. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195101. /* Check that we have the right number of parameters for known
  195102. equation types. */
  195103. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195104. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195105. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195106. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195107. {
  195108. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195109. png_free(png_ptr, purpose);
  195110. return;
  195111. }
  195112. else if (type >= PNG_EQUATION_LAST)
  195113. {
  195114. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195115. }
  195116. for (buf = units; *buf; buf++)
  195117. /* Empty loop to move past the units string. */ ;
  195118. png_debug(3, "Allocating pCAL parameters array\n");
  195119. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195120. *png_sizeof(png_charp))) ;
  195121. if (params == NULL)
  195122. {
  195123. png_free(png_ptr, purpose);
  195124. png_warning(png_ptr, "No memory for pCAL params.");
  195125. return;
  195126. }
  195127. /* Get pointers to the start of each parameter string. */
  195128. for (i = 0; i < (int)nparams; i++)
  195129. {
  195130. buf++; /* Skip the null string terminator from previous parameter. */
  195131. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195132. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195133. /* Empty loop to move past each parameter string */ ;
  195134. /* Make sure we haven't run out of data yet */
  195135. if (buf > endptr)
  195136. {
  195137. png_warning(png_ptr, "Invalid pCAL data");
  195138. png_free(png_ptr, purpose);
  195139. png_free(png_ptr, params);
  195140. return;
  195141. }
  195142. }
  195143. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195144. units, params);
  195145. png_free(png_ptr, purpose);
  195146. png_free(png_ptr, params);
  195147. }
  195148. #endif
  195149. #if defined(PNG_READ_sCAL_SUPPORTED)
  195150. /* read the sCAL chunk */
  195151. void /* PRIVATE */
  195152. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195153. {
  195154. png_charp buffer, ep;
  195155. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195156. double width, height;
  195157. png_charp vp;
  195158. #else
  195159. #ifdef PNG_FIXED_POINT_SUPPORTED
  195160. png_charp swidth, sheight;
  195161. #endif
  195162. #endif
  195163. png_size_t slength;
  195164. png_debug(1, "in png_handle_sCAL\n");
  195165. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195166. png_error(png_ptr, "Missing IHDR before sCAL");
  195167. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195168. {
  195169. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195170. png_crc_finish(png_ptr, length);
  195171. return;
  195172. }
  195173. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195174. {
  195175. png_warning(png_ptr, "Duplicate sCAL chunk");
  195176. png_crc_finish(png_ptr, length);
  195177. return;
  195178. }
  195179. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195180. length + 1);
  195181. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195182. if (buffer == NULL)
  195183. {
  195184. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195185. return;
  195186. }
  195187. slength = (png_size_t)length;
  195188. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195189. if (png_crc_finish(png_ptr, 0))
  195190. {
  195191. png_free(png_ptr, buffer);
  195192. return;
  195193. }
  195194. buffer[slength] = 0x00; /* null terminate the last string */
  195195. ep = buffer + 1; /* skip unit byte */
  195196. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195197. width = png_strtod(png_ptr, ep, &vp);
  195198. if (*vp)
  195199. {
  195200. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195201. return;
  195202. }
  195203. #else
  195204. #ifdef PNG_FIXED_POINT_SUPPORTED
  195205. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195206. if (swidth == NULL)
  195207. {
  195208. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195209. return;
  195210. }
  195211. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195212. #endif
  195213. #endif
  195214. for (ep = buffer; *ep; ep++)
  195215. /* empty loop */ ;
  195216. ep++;
  195217. if (buffer + slength < ep)
  195218. {
  195219. png_warning(png_ptr, "Truncated sCAL chunk");
  195220. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195221. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195222. png_free(png_ptr, swidth);
  195223. #endif
  195224. png_free(png_ptr, buffer);
  195225. return;
  195226. }
  195227. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195228. height = png_strtod(png_ptr, ep, &vp);
  195229. if (*vp)
  195230. {
  195231. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195232. return;
  195233. }
  195234. #else
  195235. #ifdef PNG_FIXED_POINT_SUPPORTED
  195236. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195237. if (swidth == NULL)
  195238. {
  195239. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195240. return;
  195241. }
  195242. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195243. #endif
  195244. #endif
  195245. if (buffer + slength < ep
  195246. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195247. || width <= 0. || height <= 0.
  195248. #endif
  195249. )
  195250. {
  195251. png_warning(png_ptr, "Invalid sCAL data");
  195252. png_free(png_ptr, buffer);
  195253. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195254. png_free(png_ptr, swidth);
  195255. png_free(png_ptr, sheight);
  195256. #endif
  195257. return;
  195258. }
  195259. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195260. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195261. #else
  195262. #ifdef PNG_FIXED_POINT_SUPPORTED
  195263. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195264. #endif
  195265. #endif
  195266. png_free(png_ptr, buffer);
  195267. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195268. png_free(png_ptr, swidth);
  195269. png_free(png_ptr, sheight);
  195270. #endif
  195271. }
  195272. #endif
  195273. #if defined(PNG_READ_tIME_SUPPORTED)
  195274. void /* PRIVATE */
  195275. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195276. {
  195277. png_byte buf[7];
  195278. png_time mod_time;
  195279. png_debug(1, "in png_handle_tIME\n");
  195280. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195281. png_error(png_ptr, "Out of place tIME chunk");
  195282. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195283. {
  195284. png_warning(png_ptr, "Duplicate tIME chunk");
  195285. png_crc_finish(png_ptr, length);
  195286. return;
  195287. }
  195288. if (png_ptr->mode & PNG_HAVE_IDAT)
  195289. png_ptr->mode |= PNG_AFTER_IDAT;
  195290. if (length != 7)
  195291. {
  195292. png_warning(png_ptr, "Incorrect tIME chunk length");
  195293. png_crc_finish(png_ptr, length);
  195294. return;
  195295. }
  195296. png_crc_read(png_ptr, buf, 7);
  195297. if (png_crc_finish(png_ptr, 0))
  195298. return;
  195299. mod_time.second = buf[6];
  195300. mod_time.minute = buf[5];
  195301. mod_time.hour = buf[4];
  195302. mod_time.day = buf[3];
  195303. mod_time.month = buf[2];
  195304. mod_time.year = png_get_uint_16(buf);
  195305. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195306. }
  195307. #endif
  195308. #if defined(PNG_READ_tEXt_SUPPORTED)
  195309. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195310. void /* PRIVATE */
  195311. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195312. {
  195313. png_textp text_ptr;
  195314. png_charp key;
  195315. png_charp text;
  195316. png_uint_32 skip = 0;
  195317. png_size_t slength;
  195318. int ret;
  195319. png_debug(1, "in png_handle_tEXt\n");
  195320. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195321. png_error(png_ptr, "Missing IHDR before tEXt");
  195322. if (png_ptr->mode & PNG_HAVE_IDAT)
  195323. png_ptr->mode |= PNG_AFTER_IDAT;
  195324. #ifdef PNG_MAX_MALLOC_64K
  195325. if (length > (png_uint_32)65535L)
  195326. {
  195327. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195328. skip = length - (png_uint_32)65535L;
  195329. length = (png_uint_32)65535L;
  195330. }
  195331. #endif
  195332. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195333. if (key == NULL)
  195334. {
  195335. png_warning(png_ptr, "No memory to process text chunk.");
  195336. return;
  195337. }
  195338. slength = (png_size_t)length;
  195339. png_crc_read(png_ptr, (png_bytep)key, slength);
  195340. if (png_crc_finish(png_ptr, skip))
  195341. {
  195342. png_free(png_ptr, key);
  195343. return;
  195344. }
  195345. key[slength] = 0x00;
  195346. for (text = key; *text; text++)
  195347. /* empty loop to find end of key */ ;
  195348. if (text != key + slength)
  195349. text++;
  195350. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195351. (png_uint_32)png_sizeof(png_text));
  195352. if (text_ptr == NULL)
  195353. {
  195354. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195355. png_free(png_ptr, key);
  195356. return;
  195357. }
  195358. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195359. text_ptr->key = key;
  195360. #ifdef PNG_iTXt_SUPPORTED
  195361. text_ptr->lang = NULL;
  195362. text_ptr->lang_key = NULL;
  195363. text_ptr->itxt_length = 0;
  195364. #endif
  195365. text_ptr->text = text;
  195366. text_ptr->text_length = png_strlen(text);
  195367. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195368. png_free(png_ptr, key);
  195369. png_free(png_ptr, text_ptr);
  195370. if (ret)
  195371. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195372. }
  195373. #endif
  195374. #if defined(PNG_READ_zTXt_SUPPORTED)
  195375. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195376. void /* PRIVATE */
  195377. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195378. {
  195379. png_textp text_ptr;
  195380. png_charp chunkdata;
  195381. png_charp text;
  195382. int comp_type;
  195383. int ret;
  195384. png_size_t slength, prefix_len, data_len;
  195385. png_debug(1, "in png_handle_zTXt\n");
  195386. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195387. png_error(png_ptr, "Missing IHDR before zTXt");
  195388. if (png_ptr->mode & PNG_HAVE_IDAT)
  195389. png_ptr->mode |= PNG_AFTER_IDAT;
  195390. #ifdef PNG_MAX_MALLOC_64K
  195391. /* We will no doubt have problems with chunks even half this size, but
  195392. there is no hard and fast rule to tell us where to stop. */
  195393. if (length > (png_uint_32)65535L)
  195394. {
  195395. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195396. png_crc_finish(png_ptr, length);
  195397. return;
  195398. }
  195399. #endif
  195400. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195401. if (chunkdata == NULL)
  195402. {
  195403. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195404. return;
  195405. }
  195406. slength = (png_size_t)length;
  195407. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195408. if (png_crc_finish(png_ptr, 0))
  195409. {
  195410. png_free(png_ptr, chunkdata);
  195411. return;
  195412. }
  195413. chunkdata[slength] = 0x00;
  195414. for (text = chunkdata; *text; text++)
  195415. /* empty loop */ ;
  195416. /* zTXt must have some text after the chunkdataword */
  195417. if (text >= chunkdata + slength - 2)
  195418. {
  195419. png_warning(png_ptr, "Truncated zTXt chunk");
  195420. png_free(png_ptr, chunkdata);
  195421. return;
  195422. }
  195423. else
  195424. {
  195425. comp_type = *(++text);
  195426. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195427. {
  195428. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195429. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195430. }
  195431. text++; /* skip the compression_method byte */
  195432. }
  195433. prefix_len = text - chunkdata;
  195434. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195435. (png_size_t)length, prefix_len, &data_len);
  195436. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195437. (png_uint_32)png_sizeof(png_text));
  195438. if (text_ptr == NULL)
  195439. {
  195440. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195441. png_free(png_ptr, chunkdata);
  195442. return;
  195443. }
  195444. text_ptr->compression = comp_type;
  195445. text_ptr->key = chunkdata;
  195446. #ifdef PNG_iTXt_SUPPORTED
  195447. text_ptr->lang = NULL;
  195448. text_ptr->lang_key = NULL;
  195449. text_ptr->itxt_length = 0;
  195450. #endif
  195451. text_ptr->text = chunkdata + prefix_len;
  195452. text_ptr->text_length = data_len;
  195453. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195454. png_free(png_ptr, text_ptr);
  195455. png_free(png_ptr, chunkdata);
  195456. if (ret)
  195457. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195458. }
  195459. #endif
  195460. #if defined(PNG_READ_iTXt_SUPPORTED)
  195461. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195462. void /* PRIVATE */
  195463. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195464. {
  195465. png_textp text_ptr;
  195466. png_charp chunkdata;
  195467. png_charp key, lang, text, lang_key;
  195468. int comp_flag;
  195469. int comp_type = 0;
  195470. int ret;
  195471. png_size_t slength, prefix_len, data_len;
  195472. png_debug(1, "in png_handle_iTXt\n");
  195473. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195474. png_error(png_ptr, "Missing IHDR before iTXt");
  195475. if (png_ptr->mode & PNG_HAVE_IDAT)
  195476. png_ptr->mode |= PNG_AFTER_IDAT;
  195477. #ifdef PNG_MAX_MALLOC_64K
  195478. /* We will no doubt have problems with chunks even half this size, but
  195479. there is no hard and fast rule to tell us where to stop. */
  195480. if (length > (png_uint_32)65535L)
  195481. {
  195482. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195483. png_crc_finish(png_ptr, length);
  195484. return;
  195485. }
  195486. #endif
  195487. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195488. if (chunkdata == NULL)
  195489. {
  195490. png_warning(png_ptr, "No memory to process iTXt chunk.");
  195491. return;
  195492. }
  195493. slength = (png_size_t)length;
  195494. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195495. if (png_crc_finish(png_ptr, 0))
  195496. {
  195497. png_free(png_ptr, chunkdata);
  195498. return;
  195499. }
  195500. chunkdata[slength] = 0x00;
  195501. for (lang = chunkdata; *lang; lang++)
  195502. /* empty loop */ ;
  195503. lang++; /* skip NUL separator */
  195504. /* iTXt must have a language tag (possibly empty), two compression bytes,
  195505. translated keyword (possibly empty), and possibly some text after the
  195506. keyword */
  195507. if (lang >= chunkdata + slength - 3)
  195508. {
  195509. png_warning(png_ptr, "Truncated iTXt chunk");
  195510. png_free(png_ptr, chunkdata);
  195511. return;
  195512. }
  195513. else
  195514. {
  195515. comp_flag = *lang++;
  195516. comp_type = *lang++;
  195517. }
  195518. for (lang_key = lang; *lang_key; lang_key++)
  195519. /* empty loop */ ;
  195520. lang_key++; /* skip NUL separator */
  195521. if (lang_key >= chunkdata + slength)
  195522. {
  195523. png_warning(png_ptr, "Truncated iTXt chunk");
  195524. png_free(png_ptr, chunkdata);
  195525. return;
  195526. }
  195527. for (text = lang_key; *text; text++)
  195528. /* empty loop */ ;
  195529. text++; /* skip NUL separator */
  195530. if (text >= chunkdata + slength)
  195531. {
  195532. png_warning(png_ptr, "Malformed iTXt chunk");
  195533. png_free(png_ptr, chunkdata);
  195534. return;
  195535. }
  195536. prefix_len = text - chunkdata;
  195537. key=chunkdata;
  195538. if (comp_flag)
  195539. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195540. (size_t)length, prefix_len, &data_len);
  195541. else
  195542. data_len=png_strlen(chunkdata + prefix_len);
  195543. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195544. (png_uint_32)png_sizeof(png_text));
  195545. if (text_ptr == NULL)
  195546. {
  195547. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  195548. png_free(png_ptr, chunkdata);
  195549. return;
  195550. }
  195551. text_ptr->compression = (int)comp_flag + 1;
  195552. text_ptr->lang_key = chunkdata+(lang_key-key);
  195553. text_ptr->lang = chunkdata+(lang-key);
  195554. text_ptr->itxt_length = data_len;
  195555. text_ptr->text_length = 0;
  195556. text_ptr->key = chunkdata;
  195557. text_ptr->text = chunkdata + prefix_len;
  195558. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195559. png_free(png_ptr, text_ptr);
  195560. png_free(png_ptr, chunkdata);
  195561. if (ret)
  195562. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  195563. }
  195564. #endif
  195565. /* This function is called when we haven't found a handler for a
  195566. chunk. If there isn't a problem with the chunk itself (ie bad
  195567. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  195568. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  195569. case it will be saved away to be written out later. */
  195570. void /* PRIVATE */
  195571. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195572. {
  195573. png_uint_32 skip = 0;
  195574. png_debug(1, "in png_handle_unknown\n");
  195575. if (png_ptr->mode & PNG_HAVE_IDAT)
  195576. {
  195577. #ifdef PNG_USE_LOCAL_ARRAYS
  195578. PNG_CONST PNG_IDAT;
  195579. #endif
  195580. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  195581. png_ptr->mode |= PNG_AFTER_IDAT;
  195582. }
  195583. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  195584. if (!(png_ptr->chunk_name[0] & 0x20))
  195585. {
  195586. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195587. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195588. PNG_HANDLE_CHUNK_ALWAYS
  195589. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195590. && png_ptr->read_user_chunk_fn == NULL
  195591. #endif
  195592. )
  195593. #endif
  195594. png_chunk_error(png_ptr, "unknown critical chunk");
  195595. }
  195596. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195597. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  195598. (png_ptr->read_user_chunk_fn != NULL))
  195599. {
  195600. #ifdef PNG_MAX_MALLOC_64K
  195601. if (length > (png_uint_32)65535L)
  195602. {
  195603. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  195604. skip = length - (png_uint_32)65535L;
  195605. length = (png_uint_32)65535L;
  195606. }
  195607. #endif
  195608. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  195609. (png_charp)png_ptr->chunk_name, 5);
  195610. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  195611. png_ptr->unknown_chunk.size = (png_size_t)length;
  195612. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  195613. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195614. if(png_ptr->read_user_chunk_fn != NULL)
  195615. {
  195616. /* callback to user unknown chunk handler */
  195617. int ret;
  195618. ret = (*(png_ptr->read_user_chunk_fn))
  195619. (png_ptr, &png_ptr->unknown_chunk);
  195620. if (ret < 0)
  195621. png_chunk_error(png_ptr, "error in user chunk");
  195622. if (ret == 0)
  195623. {
  195624. if (!(png_ptr->chunk_name[0] & 0x20))
  195625. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195626. PNG_HANDLE_CHUNK_ALWAYS)
  195627. png_chunk_error(png_ptr, "unknown critical chunk");
  195628. png_set_unknown_chunks(png_ptr, info_ptr,
  195629. &png_ptr->unknown_chunk, 1);
  195630. }
  195631. }
  195632. #else
  195633. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  195634. #endif
  195635. png_free(png_ptr, png_ptr->unknown_chunk.data);
  195636. png_ptr->unknown_chunk.data = NULL;
  195637. }
  195638. else
  195639. #endif
  195640. skip = length;
  195641. png_crc_finish(png_ptr, skip);
  195642. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195643. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  195644. #endif
  195645. }
  195646. /* This function is called to verify that a chunk name is valid.
  195647. This function can't have the "critical chunk check" incorporated
  195648. into it, since in the future we will need to be able to call user
  195649. functions to handle unknown critical chunks after we check that
  195650. the chunk name itself is valid. */
  195651. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  195652. void /* PRIVATE */
  195653. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  195654. {
  195655. png_debug(1, "in png_check_chunk_name\n");
  195656. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  195657. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  195658. {
  195659. png_chunk_error(png_ptr, "invalid chunk type");
  195660. }
  195661. }
  195662. /* Combines the row recently read in with the existing pixels in the
  195663. row. This routine takes care of alpha and transparency if requested.
  195664. This routine also handles the two methods of progressive display
  195665. of interlaced images, depending on the mask value.
  195666. The mask value describes which pixels are to be combined with
  195667. the row. The pattern always repeats every 8 pixels, so just 8
  195668. bits are needed. A one indicates the pixel is to be combined,
  195669. a zero indicates the pixel is to be skipped. This is in addition
  195670. to any alpha or transparency value associated with the pixel. If
  195671. you want all pixels to be combined, pass 0xff (255) in mask. */
  195672. void /* PRIVATE */
  195673. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  195674. {
  195675. png_debug(1,"in png_combine_row\n");
  195676. if (mask == 0xff)
  195677. {
  195678. png_memcpy(row, png_ptr->row_buf + 1,
  195679. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  195680. }
  195681. else
  195682. {
  195683. switch (png_ptr->row_info.pixel_depth)
  195684. {
  195685. case 1:
  195686. {
  195687. png_bytep sp = png_ptr->row_buf + 1;
  195688. png_bytep dp = row;
  195689. int s_inc, s_start, s_end;
  195690. int m = 0x80;
  195691. int shift;
  195692. png_uint_32 i;
  195693. png_uint_32 row_width = png_ptr->width;
  195694. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195695. if (png_ptr->transformations & PNG_PACKSWAP)
  195696. {
  195697. s_start = 0;
  195698. s_end = 7;
  195699. s_inc = 1;
  195700. }
  195701. else
  195702. #endif
  195703. {
  195704. s_start = 7;
  195705. s_end = 0;
  195706. s_inc = -1;
  195707. }
  195708. shift = s_start;
  195709. for (i = 0; i < row_width; i++)
  195710. {
  195711. if (m & mask)
  195712. {
  195713. int value;
  195714. value = (*sp >> shift) & 0x01;
  195715. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  195716. *dp |= (png_byte)(value << shift);
  195717. }
  195718. if (shift == s_end)
  195719. {
  195720. shift = s_start;
  195721. sp++;
  195722. dp++;
  195723. }
  195724. else
  195725. shift += s_inc;
  195726. if (m == 1)
  195727. m = 0x80;
  195728. else
  195729. m >>= 1;
  195730. }
  195731. break;
  195732. }
  195733. case 2:
  195734. {
  195735. png_bytep sp = png_ptr->row_buf + 1;
  195736. png_bytep dp = row;
  195737. int s_start, s_end, s_inc;
  195738. int m = 0x80;
  195739. int shift;
  195740. png_uint_32 i;
  195741. png_uint_32 row_width = png_ptr->width;
  195742. int value;
  195743. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195744. if (png_ptr->transformations & PNG_PACKSWAP)
  195745. {
  195746. s_start = 0;
  195747. s_end = 6;
  195748. s_inc = 2;
  195749. }
  195750. else
  195751. #endif
  195752. {
  195753. s_start = 6;
  195754. s_end = 0;
  195755. s_inc = -2;
  195756. }
  195757. shift = s_start;
  195758. for (i = 0; i < row_width; i++)
  195759. {
  195760. if (m & mask)
  195761. {
  195762. value = (*sp >> shift) & 0x03;
  195763. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  195764. *dp |= (png_byte)(value << shift);
  195765. }
  195766. if (shift == s_end)
  195767. {
  195768. shift = s_start;
  195769. sp++;
  195770. dp++;
  195771. }
  195772. else
  195773. shift += s_inc;
  195774. if (m == 1)
  195775. m = 0x80;
  195776. else
  195777. m >>= 1;
  195778. }
  195779. break;
  195780. }
  195781. case 4:
  195782. {
  195783. png_bytep sp = png_ptr->row_buf + 1;
  195784. png_bytep dp = row;
  195785. int s_start, s_end, s_inc;
  195786. int m = 0x80;
  195787. int shift;
  195788. png_uint_32 i;
  195789. png_uint_32 row_width = png_ptr->width;
  195790. int value;
  195791. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195792. if (png_ptr->transformations & PNG_PACKSWAP)
  195793. {
  195794. s_start = 0;
  195795. s_end = 4;
  195796. s_inc = 4;
  195797. }
  195798. else
  195799. #endif
  195800. {
  195801. s_start = 4;
  195802. s_end = 0;
  195803. s_inc = -4;
  195804. }
  195805. shift = s_start;
  195806. for (i = 0; i < row_width; i++)
  195807. {
  195808. if (m & mask)
  195809. {
  195810. value = (*sp >> shift) & 0xf;
  195811. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  195812. *dp |= (png_byte)(value << shift);
  195813. }
  195814. if (shift == s_end)
  195815. {
  195816. shift = s_start;
  195817. sp++;
  195818. dp++;
  195819. }
  195820. else
  195821. shift += s_inc;
  195822. if (m == 1)
  195823. m = 0x80;
  195824. else
  195825. m >>= 1;
  195826. }
  195827. break;
  195828. }
  195829. default:
  195830. {
  195831. png_bytep sp = png_ptr->row_buf + 1;
  195832. png_bytep dp = row;
  195833. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  195834. png_uint_32 i;
  195835. png_uint_32 row_width = png_ptr->width;
  195836. png_byte m = 0x80;
  195837. for (i = 0; i < row_width; i++)
  195838. {
  195839. if (m & mask)
  195840. {
  195841. png_memcpy(dp, sp, pixel_bytes);
  195842. }
  195843. sp += pixel_bytes;
  195844. dp += pixel_bytes;
  195845. if (m == 1)
  195846. m = 0x80;
  195847. else
  195848. m >>= 1;
  195849. }
  195850. break;
  195851. }
  195852. }
  195853. }
  195854. }
  195855. #ifdef PNG_READ_INTERLACING_SUPPORTED
  195856. /* OLD pre-1.0.9 interface:
  195857. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  195858. png_uint_32 transformations)
  195859. */
  195860. void /* PRIVATE */
  195861. png_do_read_interlace(png_structp png_ptr)
  195862. {
  195863. png_row_infop row_info = &(png_ptr->row_info);
  195864. png_bytep row = png_ptr->row_buf + 1;
  195865. int pass = png_ptr->pass;
  195866. png_uint_32 transformations = png_ptr->transformations;
  195867. #ifdef PNG_USE_LOCAL_ARRAYS
  195868. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195869. /* offset to next interlace block */
  195870. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195871. #endif
  195872. png_debug(1,"in png_do_read_interlace\n");
  195873. if (row != NULL && row_info != NULL)
  195874. {
  195875. png_uint_32 final_width;
  195876. final_width = row_info->width * png_pass_inc[pass];
  195877. switch (row_info->pixel_depth)
  195878. {
  195879. case 1:
  195880. {
  195881. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  195882. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  195883. int sshift, dshift;
  195884. int s_start, s_end, s_inc;
  195885. int jstop = png_pass_inc[pass];
  195886. png_byte v;
  195887. png_uint_32 i;
  195888. int j;
  195889. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195890. if (transformations & PNG_PACKSWAP)
  195891. {
  195892. sshift = (int)((row_info->width + 7) & 0x07);
  195893. dshift = (int)((final_width + 7) & 0x07);
  195894. s_start = 7;
  195895. s_end = 0;
  195896. s_inc = -1;
  195897. }
  195898. else
  195899. #endif
  195900. {
  195901. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  195902. dshift = 7 - (int)((final_width + 7) & 0x07);
  195903. s_start = 0;
  195904. s_end = 7;
  195905. s_inc = 1;
  195906. }
  195907. for (i = 0; i < row_info->width; i++)
  195908. {
  195909. v = (png_byte)((*sp >> sshift) & 0x01);
  195910. for (j = 0; j < jstop; j++)
  195911. {
  195912. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  195913. *dp |= (png_byte)(v << dshift);
  195914. if (dshift == s_end)
  195915. {
  195916. dshift = s_start;
  195917. dp--;
  195918. }
  195919. else
  195920. dshift += s_inc;
  195921. }
  195922. if (sshift == s_end)
  195923. {
  195924. sshift = s_start;
  195925. sp--;
  195926. }
  195927. else
  195928. sshift += s_inc;
  195929. }
  195930. break;
  195931. }
  195932. case 2:
  195933. {
  195934. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  195935. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  195936. int sshift, dshift;
  195937. int s_start, s_end, s_inc;
  195938. int jstop = png_pass_inc[pass];
  195939. png_uint_32 i;
  195940. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195941. if (transformations & PNG_PACKSWAP)
  195942. {
  195943. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  195944. dshift = (int)(((final_width + 3) & 0x03) << 1);
  195945. s_start = 6;
  195946. s_end = 0;
  195947. s_inc = -2;
  195948. }
  195949. else
  195950. #endif
  195951. {
  195952. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  195953. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  195954. s_start = 0;
  195955. s_end = 6;
  195956. s_inc = 2;
  195957. }
  195958. for (i = 0; i < row_info->width; i++)
  195959. {
  195960. png_byte v;
  195961. int j;
  195962. v = (png_byte)((*sp >> sshift) & 0x03);
  195963. for (j = 0; j < jstop; j++)
  195964. {
  195965. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  195966. *dp |= (png_byte)(v << dshift);
  195967. if (dshift == s_end)
  195968. {
  195969. dshift = s_start;
  195970. dp--;
  195971. }
  195972. else
  195973. dshift += s_inc;
  195974. }
  195975. if (sshift == s_end)
  195976. {
  195977. sshift = s_start;
  195978. sp--;
  195979. }
  195980. else
  195981. sshift += s_inc;
  195982. }
  195983. break;
  195984. }
  195985. case 4:
  195986. {
  195987. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  195988. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  195989. int sshift, dshift;
  195990. int s_start, s_end, s_inc;
  195991. png_uint_32 i;
  195992. int jstop = png_pass_inc[pass];
  195993. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195994. if (transformations & PNG_PACKSWAP)
  195995. {
  195996. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  195997. dshift = (int)(((final_width + 1) & 0x01) << 2);
  195998. s_start = 4;
  195999. s_end = 0;
  196000. s_inc = -4;
  196001. }
  196002. else
  196003. #endif
  196004. {
  196005. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  196006. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  196007. s_start = 0;
  196008. s_end = 4;
  196009. s_inc = 4;
  196010. }
  196011. for (i = 0; i < row_info->width; i++)
  196012. {
  196013. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  196014. int j;
  196015. for (j = 0; j < jstop; j++)
  196016. {
  196017. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  196018. *dp |= (png_byte)(v << dshift);
  196019. if (dshift == s_end)
  196020. {
  196021. dshift = s_start;
  196022. dp--;
  196023. }
  196024. else
  196025. dshift += s_inc;
  196026. }
  196027. if (sshift == s_end)
  196028. {
  196029. sshift = s_start;
  196030. sp--;
  196031. }
  196032. else
  196033. sshift += s_inc;
  196034. }
  196035. break;
  196036. }
  196037. default:
  196038. {
  196039. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196040. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196041. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196042. int jstop = png_pass_inc[pass];
  196043. png_uint_32 i;
  196044. for (i = 0; i < row_info->width; i++)
  196045. {
  196046. png_byte v[8];
  196047. int j;
  196048. png_memcpy(v, sp, pixel_bytes);
  196049. for (j = 0; j < jstop; j++)
  196050. {
  196051. png_memcpy(dp, v, pixel_bytes);
  196052. dp -= pixel_bytes;
  196053. }
  196054. sp -= pixel_bytes;
  196055. }
  196056. break;
  196057. }
  196058. }
  196059. row_info->width = final_width;
  196060. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196061. }
  196062. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196063. transformations = transformations; /* silence compiler warning */
  196064. #endif
  196065. }
  196066. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196067. void /* PRIVATE */
  196068. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196069. png_bytep prev_row, int filter)
  196070. {
  196071. png_debug(1, "in png_read_filter_row\n");
  196072. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196073. switch (filter)
  196074. {
  196075. case PNG_FILTER_VALUE_NONE:
  196076. break;
  196077. case PNG_FILTER_VALUE_SUB:
  196078. {
  196079. png_uint_32 i;
  196080. png_uint_32 istop = row_info->rowbytes;
  196081. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196082. png_bytep rp = row + bpp;
  196083. png_bytep lp = row;
  196084. for (i = bpp; i < istop; i++)
  196085. {
  196086. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196087. rp++;
  196088. }
  196089. break;
  196090. }
  196091. case PNG_FILTER_VALUE_UP:
  196092. {
  196093. png_uint_32 i;
  196094. png_uint_32 istop = row_info->rowbytes;
  196095. png_bytep rp = row;
  196096. png_bytep pp = prev_row;
  196097. for (i = 0; i < istop; i++)
  196098. {
  196099. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196100. rp++;
  196101. }
  196102. break;
  196103. }
  196104. case PNG_FILTER_VALUE_AVG:
  196105. {
  196106. png_uint_32 i;
  196107. png_bytep rp = row;
  196108. png_bytep pp = prev_row;
  196109. png_bytep lp = row;
  196110. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196111. png_uint_32 istop = row_info->rowbytes - bpp;
  196112. for (i = 0; i < bpp; i++)
  196113. {
  196114. *rp = (png_byte)(((int)(*rp) +
  196115. ((int)(*pp++) / 2 )) & 0xff);
  196116. rp++;
  196117. }
  196118. for (i = 0; i < istop; i++)
  196119. {
  196120. *rp = (png_byte)(((int)(*rp) +
  196121. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196122. rp++;
  196123. }
  196124. break;
  196125. }
  196126. case PNG_FILTER_VALUE_PAETH:
  196127. {
  196128. png_uint_32 i;
  196129. png_bytep rp = row;
  196130. png_bytep pp = prev_row;
  196131. png_bytep lp = row;
  196132. png_bytep cp = prev_row;
  196133. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196134. png_uint_32 istop=row_info->rowbytes - bpp;
  196135. for (i = 0; i < bpp; i++)
  196136. {
  196137. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196138. rp++;
  196139. }
  196140. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196141. {
  196142. int a, b, c, pa, pb, pc, p;
  196143. a = *lp++;
  196144. b = *pp++;
  196145. c = *cp++;
  196146. p = b - c;
  196147. pc = a - c;
  196148. #ifdef PNG_USE_ABS
  196149. pa = abs(p);
  196150. pb = abs(pc);
  196151. pc = abs(p + pc);
  196152. #else
  196153. pa = p < 0 ? -p : p;
  196154. pb = pc < 0 ? -pc : pc;
  196155. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196156. #endif
  196157. /*
  196158. if (pa <= pb && pa <= pc)
  196159. p = a;
  196160. else if (pb <= pc)
  196161. p = b;
  196162. else
  196163. p = c;
  196164. */
  196165. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196166. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196167. rp++;
  196168. }
  196169. break;
  196170. }
  196171. default:
  196172. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196173. *row=0;
  196174. break;
  196175. }
  196176. }
  196177. void /* PRIVATE */
  196178. png_read_finish_row(png_structp png_ptr)
  196179. {
  196180. #ifdef PNG_USE_LOCAL_ARRAYS
  196181. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196182. /* start of interlace block */
  196183. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196184. /* offset to next interlace block */
  196185. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196186. /* start of interlace block in the y direction */
  196187. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196188. /* offset to next interlace block in the y direction */
  196189. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196190. #endif
  196191. png_debug(1, "in png_read_finish_row\n");
  196192. png_ptr->row_number++;
  196193. if (png_ptr->row_number < png_ptr->num_rows)
  196194. return;
  196195. if (png_ptr->interlaced)
  196196. {
  196197. png_ptr->row_number = 0;
  196198. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196199. png_ptr->rowbytes + 1);
  196200. do
  196201. {
  196202. png_ptr->pass++;
  196203. if (png_ptr->pass >= 7)
  196204. break;
  196205. png_ptr->iwidth = (png_ptr->width +
  196206. png_pass_inc[png_ptr->pass] - 1 -
  196207. png_pass_start[png_ptr->pass]) /
  196208. png_pass_inc[png_ptr->pass];
  196209. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196210. png_ptr->iwidth) + 1;
  196211. if (!(png_ptr->transformations & PNG_INTERLACE))
  196212. {
  196213. png_ptr->num_rows = (png_ptr->height +
  196214. png_pass_yinc[png_ptr->pass] - 1 -
  196215. png_pass_ystart[png_ptr->pass]) /
  196216. png_pass_yinc[png_ptr->pass];
  196217. if (!(png_ptr->num_rows))
  196218. continue;
  196219. }
  196220. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196221. break;
  196222. } while (png_ptr->iwidth == 0);
  196223. if (png_ptr->pass < 7)
  196224. return;
  196225. }
  196226. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196227. {
  196228. #ifdef PNG_USE_LOCAL_ARRAYS
  196229. PNG_CONST PNG_IDAT;
  196230. #endif
  196231. char extra;
  196232. int ret;
  196233. png_ptr->zstream.next_out = (Bytef *)&extra;
  196234. png_ptr->zstream.avail_out = (uInt)1;
  196235. for(;;)
  196236. {
  196237. if (!(png_ptr->zstream.avail_in))
  196238. {
  196239. while (!png_ptr->idat_size)
  196240. {
  196241. png_byte chunk_length[4];
  196242. png_crc_finish(png_ptr, 0);
  196243. png_read_data(png_ptr, chunk_length, 4);
  196244. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196245. png_reset_crc(png_ptr);
  196246. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196247. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196248. png_error(png_ptr, "Not enough image data");
  196249. }
  196250. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196251. png_ptr->zstream.next_in = png_ptr->zbuf;
  196252. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196253. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196254. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196255. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196256. }
  196257. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196258. if (ret == Z_STREAM_END)
  196259. {
  196260. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196261. png_ptr->idat_size)
  196262. png_warning(png_ptr, "Extra compressed data");
  196263. png_ptr->mode |= PNG_AFTER_IDAT;
  196264. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196265. break;
  196266. }
  196267. if (ret != Z_OK)
  196268. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196269. "Decompression Error");
  196270. if (!(png_ptr->zstream.avail_out))
  196271. {
  196272. png_warning(png_ptr, "Extra compressed data.");
  196273. png_ptr->mode |= PNG_AFTER_IDAT;
  196274. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196275. break;
  196276. }
  196277. }
  196278. png_ptr->zstream.avail_out = 0;
  196279. }
  196280. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196281. png_warning(png_ptr, "Extra compression data");
  196282. inflateReset(&png_ptr->zstream);
  196283. png_ptr->mode |= PNG_AFTER_IDAT;
  196284. }
  196285. void /* PRIVATE */
  196286. png_read_start_row(png_structp png_ptr)
  196287. {
  196288. #ifdef PNG_USE_LOCAL_ARRAYS
  196289. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196290. /* start of interlace block */
  196291. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196292. /* offset to next interlace block */
  196293. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196294. /* start of interlace block in the y direction */
  196295. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196296. /* offset to next interlace block in the y direction */
  196297. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196298. #endif
  196299. int max_pixel_depth;
  196300. png_uint_32 row_bytes;
  196301. png_debug(1, "in png_read_start_row\n");
  196302. png_ptr->zstream.avail_in = 0;
  196303. png_init_read_transformations(png_ptr);
  196304. if (png_ptr->interlaced)
  196305. {
  196306. if (!(png_ptr->transformations & PNG_INTERLACE))
  196307. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196308. png_pass_ystart[0]) / png_pass_yinc[0];
  196309. else
  196310. png_ptr->num_rows = png_ptr->height;
  196311. png_ptr->iwidth = (png_ptr->width +
  196312. png_pass_inc[png_ptr->pass] - 1 -
  196313. png_pass_start[png_ptr->pass]) /
  196314. png_pass_inc[png_ptr->pass];
  196315. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196316. png_ptr->irowbytes = (png_size_t)row_bytes;
  196317. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196318. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196319. }
  196320. else
  196321. {
  196322. png_ptr->num_rows = png_ptr->height;
  196323. png_ptr->iwidth = png_ptr->width;
  196324. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196325. }
  196326. max_pixel_depth = png_ptr->pixel_depth;
  196327. #if defined(PNG_READ_PACK_SUPPORTED)
  196328. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196329. max_pixel_depth = 8;
  196330. #endif
  196331. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196332. if (png_ptr->transformations & PNG_EXPAND)
  196333. {
  196334. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196335. {
  196336. if (png_ptr->num_trans)
  196337. max_pixel_depth = 32;
  196338. else
  196339. max_pixel_depth = 24;
  196340. }
  196341. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196342. {
  196343. if (max_pixel_depth < 8)
  196344. max_pixel_depth = 8;
  196345. if (png_ptr->num_trans)
  196346. max_pixel_depth *= 2;
  196347. }
  196348. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196349. {
  196350. if (png_ptr->num_trans)
  196351. {
  196352. max_pixel_depth *= 4;
  196353. max_pixel_depth /= 3;
  196354. }
  196355. }
  196356. }
  196357. #endif
  196358. #if defined(PNG_READ_FILLER_SUPPORTED)
  196359. if (png_ptr->transformations & (PNG_FILLER))
  196360. {
  196361. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196362. max_pixel_depth = 32;
  196363. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196364. {
  196365. if (max_pixel_depth <= 8)
  196366. max_pixel_depth = 16;
  196367. else
  196368. max_pixel_depth = 32;
  196369. }
  196370. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196371. {
  196372. if (max_pixel_depth <= 32)
  196373. max_pixel_depth = 32;
  196374. else
  196375. max_pixel_depth = 64;
  196376. }
  196377. }
  196378. #endif
  196379. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196380. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196381. {
  196382. if (
  196383. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196384. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196385. #endif
  196386. #if defined(PNG_READ_FILLER_SUPPORTED)
  196387. (png_ptr->transformations & (PNG_FILLER)) ||
  196388. #endif
  196389. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196390. {
  196391. if (max_pixel_depth <= 16)
  196392. max_pixel_depth = 32;
  196393. else
  196394. max_pixel_depth = 64;
  196395. }
  196396. else
  196397. {
  196398. if (max_pixel_depth <= 8)
  196399. {
  196400. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196401. max_pixel_depth = 32;
  196402. else
  196403. max_pixel_depth = 24;
  196404. }
  196405. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196406. max_pixel_depth = 64;
  196407. else
  196408. max_pixel_depth = 48;
  196409. }
  196410. }
  196411. #endif
  196412. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196413. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196414. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196415. {
  196416. int user_pixel_depth=png_ptr->user_transform_depth*
  196417. png_ptr->user_transform_channels;
  196418. if(user_pixel_depth > max_pixel_depth)
  196419. max_pixel_depth=user_pixel_depth;
  196420. }
  196421. #endif
  196422. /* align the width on the next larger 8 pixels. Mainly used
  196423. for interlacing */
  196424. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196425. /* calculate the maximum bytes needed, adding a byte and a pixel
  196426. for safety's sake */
  196427. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196428. 1 + ((max_pixel_depth + 7) >> 3);
  196429. #ifdef PNG_MAX_MALLOC_64K
  196430. if (row_bytes > (png_uint_32)65536L)
  196431. png_error(png_ptr, "This image requires a row greater than 64KB");
  196432. #endif
  196433. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196434. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196435. #ifdef PNG_MAX_MALLOC_64K
  196436. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196437. png_error(png_ptr, "This image requires a row greater than 64KB");
  196438. #endif
  196439. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196440. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196441. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196442. png_ptr->rowbytes + 1));
  196443. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196444. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196445. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196446. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196447. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196448. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196449. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196450. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196451. }
  196452. #endif /* PNG_READ_SUPPORTED */
  196453. /*** End of inlined file: pngrutil.c ***/
  196454. /*** Start of inlined file: pngset.c ***/
  196455. /* pngset.c - storage of image information into info struct
  196456. *
  196457. * Last changed in libpng 1.2.21 [October 4, 2007]
  196458. * For conditions of distribution and use, see copyright notice in png.h
  196459. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196460. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196461. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196462. *
  196463. * The functions here are used during reads to store data from the file
  196464. * into the info struct, and during writes to store application data
  196465. * into the info struct for writing into the file. This abstracts the
  196466. * info struct and allows us to change the structure in the future.
  196467. */
  196468. #define PNG_INTERNAL
  196469. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196470. #if defined(PNG_bKGD_SUPPORTED)
  196471. void PNGAPI
  196472. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196473. {
  196474. png_debug1(1, "in %s storage function\n", "bKGD");
  196475. if (png_ptr == NULL || info_ptr == NULL)
  196476. return;
  196477. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196478. info_ptr->valid |= PNG_INFO_bKGD;
  196479. }
  196480. #endif
  196481. #if defined(PNG_cHRM_SUPPORTED)
  196482. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196483. void PNGAPI
  196484. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196485. double white_x, double white_y, double red_x, double red_y,
  196486. double green_x, double green_y, double blue_x, double blue_y)
  196487. {
  196488. png_debug1(1, "in %s storage function\n", "cHRM");
  196489. if (png_ptr == NULL || info_ptr == NULL)
  196490. return;
  196491. if (white_x < 0.0 || white_y < 0.0 ||
  196492. red_x < 0.0 || red_y < 0.0 ||
  196493. green_x < 0.0 || green_y < 0.0 ||
  196494. blue_x < 0.0 || blue_y < 0.0)
  196495. {
  196496. png_warning(png_ptr,
  196497. "Ignoring attempt to set negative chromaticity value");
  196498. return;
  196499. }
  196500. if (white_x > 21474.83 || white_y > 21474.83 ||
  196501. red_x > 21474.83 || red_y > 21474.83 ||
  196502. green_x > 21474.83 || green_y > 21474.83 ||
  196503. blue_x > 21474.83 || blue_y > 21474.83)
  196504. {
  196505. png_warning(png_ptr,
  196506. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196507. return;
  196508. }
  196509. info_ptr->x_white = (float)white_x;
  196510. info_ptr->y_white = (float)white_y;
  196511. info_ptr->x_red = (float)red_x;
  196512. info_ptr->y_red = (float)red_y;
  196513. info_ptr->x_green = (float)green_x;
  196514. info_ptr->y_green = (float)green_y;
  196515. info_ptr->x_blue = (float)blue_x;
  196516. info_ptr->y_blue = (float)blue_y;
  196517. #ifdef PNG_FIXED_POINT_SUPPORTED
  196518. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  196519. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  196520. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  196521. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  196522. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  196523. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  196524. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  196525. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  196526. #endif
  196527. info_ptr->valid |= PNG_INFO_cHRM;
  196528. }
  196529. #endif
  196530. #ifdef PNG_FIXED_POINT_SUPPORTED
  196531. void PNGAPI
  196532. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  196533. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  196534. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  196535. png_fixed_point blue_x, png_fixed_point blue_y)
  196536. {
  196537. png_debug1(1, "in %s storage function\n", "cHRM");
  196538. if (png_ptr == NULL || info_ptr == NULL)
  196539. return;
  196540. if (white_x < 0 || white_y < 0 ||
  196541. red_x < 0 || red_y < 0 ||
  196542. green_x < 0 || green_y < 0 ||
  196543. blue_x < 0 || blue_y < 0)
  196544. {
  196545. png_warning(png_ptr,
  196546. "Ignoring attempt to set negative chromaticity value");
  196547. return;
  196548. }
  196549. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196550. if (white_x > (double) PNG_UINT_31_MAX ||
  196551. white_y > (double) PNG_UINT_31_MAX ||
  196552. red_x > (double) PNG_UINT_31_MAX ||
  196553. red_y > (double) PNG_UINT_31_MAX ||
  196554. green_x > (double) PNG_UINT_31_MAX ||
  196555. green_y > (double) PNG_UINT_31_MAX ||
  196556. blue_x > (double) PNG_UINT_31_MAX ||
  196557. blue_y > (double) PNG_UINT_31_MAX)
  196558. #else
  196559. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196560. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196561. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196562. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196563. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196564. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196565. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196566. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  196567. #endif
  196568. {
  196569. png_warning(png_ptr,
  196570. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196571. return;
  196572. }
  196573. info_ptr->int_x_white = white_x;
  196574. info_ptr->int_y_white = white_y;
  196575. info_ptr->int_x_red = red_x;
  196576. info_ptr->int_y_red = red_y;
  196577. info_ptr->int_x_green = green_x;
  196578. info_ptr->int_y_green = green_y;
  196579. info_ptr->int_x_blue = blue_x;
  196580. info_ptr->int_y_blue = blue_y;
  196581. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196582. info_ptr->x_white = (float)(white_x/100000.);
  196583. info_ptr->y_white = (float)(white_y/100000.);
  196584. info_ptr->x_red = (float)( red_x/100000.);
  196585. info_ptr->y_red = (float)( red_y/100000.);
  196586. info_ptr->x_green = (float)(green_x/100000.);
  196587. info_ptr->y_green = (float)(green_y/100000.);
  196588. info_ptr->x_blue = (float)( blue_x/100000.);
  196589. info_ptr->y_blue = (float)( blue_y/100000.);
  196590. #endif
  196591. info_ptr->valid |= PNG_INFO_cHRM;
  196592. }
  196593. #endif
  196594. #endif
  196595. #if defined(PNG_gAMA_SUPPORTED)
  196596. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196597. void PNGAPI
  196598. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  196599. {
  196600. double gamma;
  196601. png_debug1(1, "in %s storage function\n", "gAMA");
  196602. if (png_ptr == NULL || info_ptr == NULL)
  196603. return;
  196604. /* Check for overflow */
  196605. if (file_gamma > 21474.83)
  196606. {
  196607. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196608. gamma=21474.83;
  196609. }
  196610. else
  196611. gamma=file_gamma;
  196612. info_ptr->gamma = (float)gamma;
  196613. #ifdef PNG_FIXED_POINT_SUPPORTED
  196614. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  196615. #endif
  196616. info_ptr->valid |= PNG_INFO_gAMA;
  196617. if(gamma == 0.0)
  196618. png_warning(png_ptr, "Setting gamma=0");
  196619. }
  196620. #endif
  196621. void PNGAPI
  196622. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  196623. int_gamma)
  196624. {
  196625. png_fixed_point gamma;
  196626. png_debug1(1, "in %s storage function\n", "gAMA");
  196627. if (png_ptr == NULL || info_ptr == NULL)
  196628. return;
  196629. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  196630. {
  196631. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196632. gamma=PNG_UINT_31_MAX;
  196633. }
  196634. else
  196635. {
  196636. if (int_gamma < 0)
  196637. {
  196638. png_warning(png_ptr, "Setting negative gamma to zero");
  196639. gamma=0;
  196640. }
  196641. else
  196642. gamma=int_gamma;
  196643. }
  196644. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196645. info_ptr->gamma = (float)(gamma/100000.);
  196646. #endif
  196647. #ifdef PNG_FIXED_POINT_SUPPORTED
  196648. info_ptr->int_gamma = gamma;
  196649. #endif
  196650. info_ptr->valid |= PNG_INFO_gAMA;
  196651. if(gamma == 0)
  196652. png_warning(png_ptr, "Setting gamma=0");
  196653. }
  196654. #endif
  196655. #if defined(PNG_hIST_SUPPORTED)
  196656. void PNGAPI
  196657. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  196658. {
  196659. int i;
  196660. png_debug1(1, "in %s storage function\n", "hIST");
  196661. if (png_ptr == NULL || info_ptr == NULL)
  196662. return;
  196663. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  196664. > PNG_MAX_PALETTE_LENGTH)
  196665. {
  196666. png_warning(png_ptr,
  196667. "Invalid palette size, hIST allocation skipped.");
  196668. return;
  196669. }
  196670. #ifdef PNG_FREE_ME_SUPPORTED
  196671. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  196672. #endif
  196673. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  196674. 1.2.1 */
  196675. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  196676. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  196677. if (png_ptr->hist == NULL)
  196678. {
  196679. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  196680. return;
  196681. }
  196682. for (i = 0; i < info_ptr->num_palette; i++)
  196683. png_ptr->hist[i] = hist[i];
  196684. info_ptr->hist = png_ptr->hist;
  196685. info_ptr->valid |= PNG_INFO_hIST;
  196686. #ifdef PNG_FREE_ME_SUPPORTED
  196687. info_ptr->free_me |= PNG_FREE_HIST;
  196688. #else
  196689. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  196690. #endif
  196691. }
  196692. #endif
  196693. void PNGAPI
  196694. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  196695. png_uint_32 width, png_uint_32 height, int bit_depth,
  196696. int color_type, int interlace_type, int compression_type,
  196697. int filter_type)
  196698. {
  196699. png_debug1(1, "in %s storage function\n", "IHDR");
  196700. if (png_ptr == NULL || info_ptr == NULL)
  196701. return;
  196702. /* check for width and height valid values */
  196703. if (width == 0 || height == 0)
  196704. png_error(png_ptr, "Image width or height is zero in IHDR");
  196705. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196706. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  196707. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196708. #else
  196709. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  196710. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196711. #endif
  196712. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  196713. png_error(png_ptr, "Invalid image size in IHDR");
  196714. if ( width > (PNG_UINT_32_MAX
  196715. >> 3) /* 8-byte RGBA pixels */
  196716. - 64 /* bigrowbuf hack */
  196717. - 1 /* filter byte */
  196718. - 7*8 /* rounding of width to multiple of 8 pixels */
  196719. - 8) /* extra max_pixel_depth pad */
  196720. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  196721. /* check other values */
  196722. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  196723. bit_depth != 8 && bit_depth != 16)
  196724. png_error(png_ptr, "Invalid bit depth in IHDR");
  196725. if (color_type < 0 || color_type == 1 ||
  196726. color_type == 5 || color_type > 6)
  196727. png_error(png_ptr, "Invalid color type in IHDR");
  196728. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  196729. ((color_type == PNG_COLOR_TYPE_RGB ||
  196730. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  196731. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  196732. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  196733. if (interlace_type >= PNG_INTERLACE_LAST)
  196734. png_error(png_ptr, "Unknown interlace method in IHDR");
  196735. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196736. png_error(png_ptr, "Unknown compression method in IHDR");
  196737. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196738. /* Accept filter_method 64 (intrapixel differencing) only if
  196739. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196740. * 2. Libpng did not read a PNG signature (this filter_method is only
  196741. * used in PNG datastreams that are embedded in MNG datastreams) and
  196742. * 3. The application called png_permit_mng_features with a mask that
  196743. * included PNG_FLAG_MNG_FILTER_64 and
  196744. * 4. The filter_method is 64 and
  196745. * 5. The color_type is RGB or RGBA
  196746. */
  196747. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  196748. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  196749. if(filter_type != PNG_FILTER_TYPE_BASE)
  196750. {
  196751. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196752. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  196753. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  196754. (color_type == PNG_COLOR_TYPE_RGB ||
  196755. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  196756. png_error(png_ptr, "Unknown filter method in IHDR");
  196757. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  196758. png_warning(png_ptr, "Invalid filter method in IHDR");
  196759. }
  196760. #else
  196761. if(filter_type != PNG_FILTER_TYPE_BASE)
  196762. png_error(png_ptr, "Unknown filter method in IHDR");
  196763. #endif
  196764. info_ptr->width = width;
  196765. info_ptr->height = height;
  196766. info_ptr->bit_depth = (png_byte)bit_depth;
  196767. info_ptr->color_type =(png_byte) color_type;
  196768. info_ptr->compression_type = (png_byte)compression_type;
  196769. info_ptr->filter_type = (png_byte)filter_type;
  196770. info_ptr->interlace_type = (png_byte)interlace_type;
  196771. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196772. info_ptr->channels = 1;
  196773. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  196774. info_ptr->channels = 3;
  196775. else
  196776. info_ptr->channels = 1;
  196777. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  196778. info_ptr->channels++;
  196779. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  196780. /* check for potential overflow */
  196781. if (width > (PNG_UINT_32_MAX
  196782. >> 3) /* 8-byte RGBA pixels */
  196783. - 64 /* bigrowbuf hack */
  196784. - 1 /* filter byte */
  196785. - 7*8 /* rounding of width to multiple of 8 pixels */
  196786. - 8) /* extra max_pixel_depth pad */
  196787. info_ptr->rowbytes = (png_size_t)0;
  196788. else
  196789. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  196790. }
  196791. #if defined(PNG_oFFs_SUPPORTED)
  196792. void PNGAPI
  196793. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  196794. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  196795. {
  196796. png_debug1(1, "in %s storage function\n", "oFFs");
  196797. if (png_ptr == NULL || info_ptr == NULL)
  196798. return;
  196799. info_ptr->x_offset = offset_x;
  196800. info_ptr->y_offset = offset_y;
  196801. info_ptr->offset_unit_type = (png_byte)unit_type;
  196802. info_ptr->valid |= PNG_INFO_oFFs;
  196803. }
  196804. #endif
  196805. #if defined(PNG_pCAL_SUPPORTED)
  196806. void PNGAPI
  196807. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  196808. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  196809. png_charp units, png_charpp params)
  196810. {
  196811. png_uint_32 length;
  196812. int i;
  196813. png_debug1(1, "in %s storage function\n", "pCAL");
  196814. if (png_ptr == NULL || info_ptr == NULL)
  196815. return;
  196816. length = png_strlen(purpose) + 1;
  196817. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  196818. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  196819. if (info_ptr->pcal_purpose == NULL)
  196820. {
  196821. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  196822. return;
  196823. }
  196824. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  196825. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  196826. info_ptr->pcal_X0 = X0;
  196827. info_ptr->pcal_X1 = X1;
  196828. info_ptr->pcal_type = (png_byte)type;
  196829. info_ptr->pcal_nparams = (png_byte)nparams;
  196830. length = png_strlen(units) + 1;
  196831. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  196832. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  196833. if (info_ptr->pcal_units == NULL)
  196834. {
  196835. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  196836. return;
  196837. }
  196838. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  196839. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  196840. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  196841. if (info_ptr->pcal_params == NULL)
  196842. {
  196843. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  196844. return;
  196845. }
  196846. info_ptr->pcal_params[nparams] = NULL;
  196847. for (i = 0; i < nparams; i++)
  196848. {
  196849. length = png_strlen(params[i]) + 1;
  196850. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  196851. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  196852. if (info_ptr->pcal_params[i] == NULL)
  196853. {
  196854. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  196855. return;
  196856. }
  196857. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  196858. }
  196859. info_ptr->valid |= PNG_INFO_pCAL;
  196860. #ifdef PNG_FREE_ME_SUPPORTED
  196861. info_ptr->free_me |= PNG_FREE_PCAL;
  196862. #endif
  196863. }
  196864. #endif
  196865. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  196866. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196867. void PNGAPI
  196868. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  196869. int unit, double width, double height)
  196870. {
  196871. png_debug1(1, "in %s storage function\n", "sCAL");
  196872. if (png_ptr == NULL || info_ptr == NULL)
  196873. return;
  196874. info_ptr->scal_unit = (png_byte)unit;
  196875. info_ptr->scal_pixel_width = width;
  196876. info_ptr->scal_pixel_height = height;
  196877. info_ptr->valid |= PNG_INFO_sCAL;
  196878. }
  196879. #else
  196880. #ifdef PNG_FIXED_POINT_SUPPORTED
  196881. void PNGAPI
  196882. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  196883. int unit, png_charp swidth, png_charp sheight)
  196884. {
  196885. png_uint_32 length;
  196886. png_debug1(1, "in %s storage function\n", "sCAL");
  196887. if (png_ptr == NULL || info_ptr == NULL)
  196888. return;
  196889. info_ptr->scal_unit = (png_byte)unit;
  196890. length = png_strlen(swidth) + 1;
  196891. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196892. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  196893. if (info_ptr->scal_s_width == NULL)
  196894. {
  196895. png_warning(png_ptr,
  196896. "Memory allocation failed while processing sCAL.");
  196897. }
  196898. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  196899. length = png_strlen(sheight) + 1;
  196900. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196901. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  196902. if (info_ptr->scal_s_height == NULL)
  196903. {
  196904. png_free (png_ptr, info_ptr->scal_s_width);
  196905. png_warning(png_ptr,
  196906. "Memory allocation failed while processing sCAL.");
  196907. }
  196908. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  196909. info_ptr->valid |= PNG_INFO_sCAL;
  196910. #ifdef PNG_FREE_ME_SUPPORTED
  196911. info_ptr->free_me |= PNG_FREE_SCAL;
  196912. #endif
  196913. }
  196914. #endif
  196915. #endif
  196916. #endif
  196917. #if defined(PNG_pHYs_SUPPORTED)
  196918. void PNGAPI
  196919. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  196920. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  196921. {
  196922. png_debug1(1, "in %s storage function\n", "pHYs");
  196923. if (png_ptr == NULL || info_ptr == NULL)
  196924. return;
  196925. info_ptr->x_pixels_per_unit = res_x;
  196926. info_ptr->y_pixels_per_unit = res_y;
  196927. info_ptr->phys_unit_type = (png_byte)unit_type;
  196928. info_ptr->valid |= PNG_INFO_pHYs;
  196929. }
  196930. #endif
  196931. void PNGAPI
  196932. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  196933. png_colorp palette, int num_palette)
  196934. {
  196935. png_debug1(1, "in %s storage function\n", "PLTE");
  196936. if (png_ptr == NULL || info_ptr == NULL)
  196937. return;
  196938. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  196939. {
  196940. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196941. png_error(png_ptr, "Invalid palette length");
  196942. else
  196943. {
  196944. png_warning(png_ptr, "Invalid palette length");
  196945. return;
  196946. }
  196947. }
  196948. /*
  196949. * It may not actually be necessary to set png_ptr->palette here;
  196950. * we do it for backward compatibility with the way the png_handle_tRNS
  196951. * function used to do the allocation.
  196952. */
  196953. #ifdef PNG_FREE_ME_SUPPORTED
  196954. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  196955. #endif
  196956. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  196957. of num_palette entries,
  196958. in case of an invalid PNG file that has too-large sample values. */
  196959. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  196960. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  196961. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  196962. png_sizeof(png_color));
  196963. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  196964. info_ptr->palette = png_ptr->palette;
  196965. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  196966. #ifdef PNG_FREE_ME_SUPPORTED
  196967. info_ptr->free_me |= PNG_FREE_PLTE;
  196968. #else
  196969. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  196970. #endif
  196971. info_ptr->valid |= PNG_INFO_PLTE;
  196972. }
  196973. #if defined(PNG_sBIT_SUPPORTED)
  196974. void PNGAPI
  196975. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  196976. png_color_8p sig_bit)
  196977. {
  196978. png_debug1(1, "in %s storage function\n", "sBIT");
  196979. if (png_ptr == NULL || info_ptr == NULL)
  196980. return;
  196981. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  196982. info_ptr->valid |= PNG_INFO_sBIT;
  196983. }
  196984. #endif
  196985. #if defined(PNG_sRGB_SUPPORTED)
  196986. void PNGAPI
  196987. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  196988. {
  196989. png_debug1(1, "in %s storage function\n", "sRGB");
  196990. if (png_ptr == NULL || info_ptr == NULL)
  196991. return;
  196992. info_ptr->srgb_intent = (png_byte)intent;
  196993. info_ptr->valid |= PNG_INFO_sRGB;
  196994. }
  196995. void PNGAPI
  196996. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  196997. int intent)
  196998. {
  196999. #if defined(PNG_gAMA_SUPPORTED)
  197000. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197001. float file_gamma;
  197002. #endif
  197003. #ifdef PNG_FIXED_POINT_SUPPORTED
  197004. png_fixed_point int_file_gamma;
  197005. #endif
  197006. #endif
  197007. #if defined(PNG_cHRM_SUPPORTED)
  197008. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197009. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  197010. #endif
  197011. #ifdef PNG_FIXED_POINT_SUPPORTED
  197012. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  197013. int_green_y, int_blue_x, int_blue_y;
  197014. #endif
  197015. #endif
  197016. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  197017. if (png_ptr == NULL || info_ptr == NULL)
  197018. return;
  197019. png_set_sRGB(png_ptr, info_ptr, intent);
  197020. #if defined(PNG_gAMA_SUPPORTED)
  197021. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197022. file_gamma = (float).45455;
  197023. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197024. #endif
  197025. #ifdef PNG_FIXED_POINT_SUPPORTED
  197026. int_file_gamma = 45455L;
  197027. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197028. #endif
  197029. #endif
  197030. #if defined(PNG_cHRM_SUPPORTED)
  197031. #ifdef PNG_FIXED_POINT_SUPPORTED
  197032. int_white_x = 31270L;
  197033. int_white_y = 32900L;
  197034. int_red_x = 64000L;
  197035. int_red_y = 33000L;
  197036. int_green_x = 30000L;
  197037. int_green_y = 60000L;
  197038. int_blue_x = 15000L;
  197039. int_blue_y = 6000L;
  197040. png_set_cHRM_fixed(png_ptr, info_ptr,
  197041. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197042. int_blue_x, int_blue_y);
  197043. #endif
  197044. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197045. white_x = (float).3127;
  197046. white_y = (float).3290;
  197047. red_x = (float).64;
  197048. red_y = (float).33;
  197049. green_x = (float).30;
  197050. green_y = (float).60;
  197051. blue_x = (float).15;
  197052. blue_y = (float).06;
  197053. png_set_cHRM(png_ptr, info_ptr,
  197054. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197055. #endif
  197056. #endif
  197057. }
  197058. #endif
  197059. #if defined(PNG_iCCP_SUPPORTED)
  197060. void PNGAPI
  197061. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197062. png_charp name, int compression_type,
  197063. png_charp profile, png_uint_32 proflen)
  197064. {
  197065. png_charp new_iccp_name;
  197066. png_charp new_iccp_profile;
  197067. png_debug1(1, "in %s storage function\n", "iCCP");
  197068. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197069. return;
  197070. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197071. if (new_iccp_name == NULL)
  197072. {
  197073. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197074. return;
  197075. }
  197076. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197077. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197078. if (new_iccp_profile == NULL)
  197079. {
  197080. png_free (png_ptr, new_iccp_name);
  197081. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197082. return;
  197083. }
  197084. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197085. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197086. info_ptr->iccp_proflen = proflen;
  197087. info_ptr->iccp_name = new_iccp_name;
  197088. info_ptr->iccp_profile = new_iccp_profile;
  197089. /* Compression is always zero but is here so the API and info structure
  197090. * does not have to change if we introduce multiple compression types */
  197091. info_ptr->iccp_compression = (png_byte)compression_type;
  197092. #ifdef PNG_FREE_ME_SUPPORTED
  197093. info_ptr->free_me |= PNG_FREE_ICCP;
  197094. #endif
  197095. info_ptr->valid |= PNG_INFO_iCCP;
  197096. }
  197097. #endif
  197098. #if defined(PNG_TEXT_SUPPORTED)
  197099. void PNGAPI
  197100. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197101. int num_text)
  197102. {
  197103. int ret;
  197104. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197105. if (ret)
  197106. png_error(png_ptr, "Insufficient memory to store text");
  197107. }
  197108. int /* PRIVATE */
  197109. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197110. int num_text)
  197111. {
  197112. int i;
  197113. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197114. "text" : (png_const_charp)png_ptr->chunk_name));
  197115. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197116. return(0);
  197117. /* Make sure we have enough space in the "text" array in info_struct
  197118. * to hold all of the incoming text_ptr objects.
  197119. */
  197120. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197121. {
  197122. if (info_ptr->text != NULL)
  197123. {
  197124. png_textp old_text;
  197125. int old_max;
  197126. old_max = info_ptr->max_text;
  197127. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197128. old_text = info_ptr->text;
  197129. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197130. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197131. if (info_ptr->text == NULL)
  197132. {
  197133. png_free(png_ptr, old_text);
  197134. return(1);
  197135. }
  197136. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197137. png_sizeof(png_text)));
  197138. png_free(png_ptr, old_text);
  197139. }
  197140. else
  197141. {
  197142. info_ptr->max_text = num_text + 8;
  197143. info_ptr->num_text = 0;
  197144. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197145. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197146. if (info_ptr->text == NULL)
  197147. return(1);
  197148. #ifdef PNG_FREE_ME_SUPPORTED
  197149. info_ptr->free_me |= PNG_FREE_TEXT;
  197150. #endif
  197151. }
  197152. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197153. info_ptr->max_text);
  197154. }
  197155. for (i = 0; i < num_text; i++)
  197156. {
  197157. png_size_t text_length,key_len;
  197158. png_size_t lang_len,lang_key_len;
  197159. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197160. if (text_ptr[i].key == NULL)
  197161. continue;
  197162. key_len = png_strlen(text_ptr[i].key);
  197163. if(text_ptr[i].compression <= 0)
  197164. {
  197165. lang_len = 0;
  197166. lang_key_len = 0;
  197167. }
  197168. else
  197169. #ifdef PNG_iTXt_SUPPORTED
  197170. {
  197171. /* set iTXt data */
  197172. if (text_ptr[i].lang != NULL)
  197173. lang_len = png_strlen(text_ptr[i].lang);
  197174. else
  197175. lang_len = 0;
  197176. if (text_ptr[i].lang_key != NULL)
  197177. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197178. else
  197179. lang_key_len = 0;
  197180. }
  197181. #else
  197182. {
  197183. png_warning(png_ptr, "iTXt chunk not supported.");
  197184. continue;
  197185. }
  197186. #endif
  197187. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197188. {
  197189. text_length = 0;
  197190. #ifdef PNG_iTXt_SUPPORTED
  197191. if(text_ptr[i].compression > 0)
  197192. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197193. else
  197194. #endif
  197195. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197196. }
  197197. else
  197198. {
  197199. text_length = png_strlen(text_ptr[i].text);
  197200. textp->compression = text_ptr[i].compression;
  197201. }
  197202. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197203. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197204. if (textp->key == NULL)
  197205. return(1);
  197206. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197207. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197208. (int)textp->key);
  197209. png_memcpy(textp->key, text_ptr[i].key,
  197210. (png_size_t)(key_len));
  197211. *(textp->key+key_len) = '\0';
  197212. #ifdef PNG_iTXt_SUPPORTED
  197213. if (text_ptr[i].compression > 0)
  197214. {
  197215. textp->lang=textp->key + key_len + 1;
  197216. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197217. *(textp->lang+lang_len) = '\0';
  197218. textp->lang_key=textp->lang + lang_len + 1;
  197219. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197220. *(textp->lang_key+lang_key_len) = '\0';
  197221. textp->text=textp->lang_key + lang_key_len + 1;
  197222. }
  197223. else
  197224. #endif
  197225. {
  197226. #ifdef PNG_iTXt_SUPPORTED
  197227. textp->lang=NULL;
  197228. textp->lang_key=NULL;
  197229. #endif
  197230. textp->text=textp->key + key_len + 1;
  197231. }
  197232. if(text_length)
  197233. png_memcpy(textp->text, text_ptr[i].text,
  197234. (png_size_t)(text_length));
  197235. *(textp->text+text_length) = '\0';
  197236. #ifdef PNG_iTXt_SUPPORTED
  197237. if(textp->compression > 0)
  197238. {
  197239. textp->text_length = 0;
  197240. textp->itxt_length = text_length;
  197241. }
  197242. else
  197243. #endif
  197244. {
  197245. textp->text_length = text_length;
  197246. #ifdef PNG_iTXt_SUPPORTED
  197247. textp->itxt_length = 0;
  197248. #endif
  197249. }
  197250. info_ptr->num_text++;
  197251. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197252. }
  197253. return(0);
  197254. }
  197255. #endif
  197256. #if defined(PNG_tIME_SUPPORTED)
  197257. void PNGAPI
  197258. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197259. {
  197260. png_debug1(1, "in %s storage function\n", "tIME");
  197261. if (png_ptr == NULL || info_ptr == NULL ||
  197262. (png_ptr->mode & PNG_WROTE_tIME))
  197263. return;
  197264. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197265. info_ptr->valid |= PNG_INFO_tIME;
  197266. }
  197267. #endif
  197268. #if defined(PNG_tRNS_SUPPORTED)
  197269. void PNGAPI
  197270. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197271. png_bytep trans, int num_trans, png_color_16p trans_values)
  197272. {
  197273. png_debug1(1, "in %s storage function\n", "tRNS");
  197274. if (png_ptr == NULL || info_ptr == NULL)
  197275. return;
  197276. if (trans != NULL)
  197277. {
  197278. /*
  197279. * It may not actually be necessary to set png_ptr->trans here;
  197280. * we do it for backward compatibility with the way the png_handle_tRNS
  197281. * function used to do the allocation.
  197282. */
  197283. #ifdef PNG_FREE_ME_SUPPORTED
  197284. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197285. #endif
  197286. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197287. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197288. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197289. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197290. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197291. #ifdef PNG_FREE_ME_SUPPORTED
  197292. info_ptr->free_me |= PNG_FREE_TRNS;
  197293. #else
  197294. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197295. #endif
  197296. }
  197297. if (trans_values != NULL)
  197298. {
  197299. png_memcpy(&(info_ptr->trans_values), trans_values,
  197300. png_sizeof(png_color_16));
  197301. if (num_trans == 0)
  197302. num_trans = 1;
  197303. }
  197304. info_ptr->num_trans = (png_uint_16)num_trans;
  197305. info_ptr->valid |= PNG_INFO_tRNS;
  197306. }
  197307. #endif
  197308. #if defined(PNG_sPLT_SUPPORTED)
  197309. void PNGAPI
  197310. png_set_sPLT(png_structp png_ptr,
  197311. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197312. {
  197313. png_sPLT_tp np;
  197314. int i;
  197315. if (png_ptr == NULL || info_ptr == NULL)
  197316. return;
  197317. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197318. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197319. if (np == NULL)
  197320. {
  197321. png_warning(png_ptr, "No memory for sPLT palettes.");
  197322. return;
  197323. }
  197324. png_memcpy(np, info_ptr->splt_palettes,
  197325. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197326. png_free(png_ptr, info_ptr->splt_palettes);
  197327. info_ptr->splt_palettes=NULL;
  197328. for (i = 0; i < nentries; i++)
  197329. {
  197330. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197331. png_sPLT_tp from = entries + i;
  197332. to->name = (png_charp)png_malloc_warn(png_ptr,
  197333. png_strlen(from->name) + 1);
  197334. if (to->name == NULL)
  197335. {
  197336. png_warning(png_ptr,
  197337. "Out of memory while processing sPLT chunk");
  197338. }
  197339. /* TODO: use png_malloc_warn */
  197340. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197341. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197342. from->nentries * png_sizeof(png_sPLT_entry));
  197343. /* TODO: use png_malloc_warn */
  197344. png_memcpy(to->entries, from->entries,
  197345. from->nentries * png_sizeof(png_sPLT_entry));
  197346. if (to->entries == NULL)
  197347. {
  197348. png_warning(png_ptr,
  197349. "Out of memory while processing sPLT chunk");
  197350. png_free(png_ptr,to->name);
  197351. to->name = NULL;
  197352. }
  197353. to->nentries = from->nentries;
  197354. to->depth = from->depth;
  197355. }
  197356. info_ptr->splt_palettes = np;
  197357. info_ptr->splt_palettes_num += nentries;
  197358. info_ptr->valid |= PNG_INFO_sPLT;
  197359. #ifdef PNG_FREE_ME_SUPPORTED
  197360. info_ptr->free_me |= PNG_FREE_SPLT;
  197361. #endif
  197362. }
  197363. #endif /* PNG_sPLT_SUPPORTED */
  197364. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197365. void PNGAPI
  197366. png_set_unknown_chunks(png_structp png_ptr,
  197367. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197368. {
  197369. png_unknown_chunkp np;
  197370. int i;
  197371. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197372. return;
  197373. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197374. (info_ptr->unknown_chunks_num + num_unknowns) *
  197375. png_sizeof(png_unknown_chunk));
  197376. if (np == NULL)
  197377. {
  197378. png_warning(png_ptr,
  197379. "Out of memory while processing unknown chunk.");
  197380. return;
  197381. }
  197382. png_memcpy(np, info_ptr->unknown_chunks,
  197383. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197384. png_free(png_ptr, info_ptr->unknown_chunks);
  197385. info_ptr->unknown_chunks=NULL;
  197386. for (i = 0; i < num_unknowns; i++)
  197387. {
  197388. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197389. png_unknown_chunkp from = unknowns + i;
  197390. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197391. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197392. if (to->data == NULL)
  197393. {
  197394. png_warning(png_ptr,
  197395. "Out of memory while processing unknown chunk.");
  197396. }
  197397. else
  197398. {
  197399. png_memcpy(to->data, from->data, from->size);
  197400. to->size = from->size;
  197401. /* note our location in the read or write sequence */
  197402. to->location = (png_byte)(png_ptr->mode & 0xff);
  197403. }
  197404. }
  197405. info_ptr->unknown_chunks = np;
  197406. info_ptr->unknown_chunks_num += num_unknowns;
  197407. #ifdef PNG_FREE_ME_SUPPORTED
  197408. info_ptr->free_me |= PNG_FREE_UNKN;
  197409. #endif
  197410. }
  197411. void PNGAPI
  197412. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197413. int chunk, int location)
  197414. {
  197415. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197416. (int)info_ptr->unknown_chunks_num)
  197417. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197418. }
  197419. #endif
  197420. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197421. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197422. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197423. void PNGAPI
  197424. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197425. {
  197426. /* This function is deprecated in favor of png_permit_mng_features()
  197427. and will be removed from libpng-1.3.0 */
  197428. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197429. if (png_ptr == NULL)
  197430. return;
  197431. png_ptr->mng_features_permitted = (png_byte)
  197432. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197433. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197434. }
  197435. #endif
  197436. #endif
  197437. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197438. png_uint_32 PNGAPI
  197439. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197440. {
  197441. png_debug(1, "in png_permit_mng_features\n");
  197442. if (png_ptr == NULL)
  197443. return (png_uint_32)0;
  197444. png_ptr->mng_features_permitted =
  197445. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197446. return (png_uint_32)png_ptr->mng_features_permitted;
  197447. }
  197448. #endif
  197449. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197450. void PNGAPI
  197451. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197452. chunk_list, int num_chunks)
  197453. {
  197454. png_bytep new_list, p;
  197455. int i, old_num_chunks;
  197456. if (png_ptr == NULL)
  197457. return;
  197458. if (num_chunks == 0)
  197459. {
  197460. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197461. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197462. else
  197463. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197464. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197465. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197466. else
  197467. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197468. return;
  197469. }
  197470. if (chunk_list == NULL)
  197471. return;
  197472. old_num_chunks=png_ptr->num_chunk_list;
  197473. new_list=(png_bytep)png_malloc(png_ptr,
  197474. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197475. if(png_ptr->chunk_list != NULL)
  197476. {
  197477. png_memcpy(new_list, png_ptr->chunk_list,
  197478. (png_size_t)(5*old_num_chunks));
  197479. png_free(png_ptr, png_ptr->chunk_list);
  197480. png_ptr->chunk_list=NULL;
  197481. }
  197482. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197483. (png_size_t)(5*num_chunks));
  197484. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197485. *p=(png_byte)keep;
  197486. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197487. png_ptr->chunk_list=new_list;
  197488. #ifdef PNG_FREE_ME_SUPPORTED
  197489. png_ptr->free_me |= PNG_FREE_LIST;
  197490. #endif
  197491. }
  197492. #endif
  197493. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  197494. void PNGAPI
  197495. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  197496. png_user_chunk_ptr read_user_chunk_fn)
  197497. {
  197498. png_debug(1, "in png_set_read_user_chunk_fn\n");
  197499. if (png_ptr == NULL)
  197500. return;
  197501. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  197502. png_ptr->user_chunk_ptr = user_chunk_ptr;
  197503. }
  197504. #endif
  197505. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197506. void PNGAPI
  197507. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  197508. {
  197509. png_debug1(1, "in %s storage function\n", "rows");
  197510. if (png_ptr == NULL || info_ptr == NULL)
  197511. return;
  197512. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  197513. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  197514. info_ptr->row_pointers = row_pointers;
  197515. if(row_pointers)
  197516. info_ptr->valid |= PNG_INFO_IDAT;
  197517. }
  197518. #endif
  197519. #ifdef PNG_WRITE_SUPPORTED
  197520. void PNGAPI
  197521. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  197522. {
  197523. if (png_ptr == NULL)
  197524. return;
  197525. if(png_ptr->zbuf)
  197526. png_free(png_ptr, png_ptr->zbuf);
  197527. png_ptr->zbuf_size = (png_size_t)size;
  197528. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  197529. png_ptr->zstream.next_out = png_ptr->zbuf;
  197530. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197531. }
  197532. #endif
  197533. void PNGAPI
  197534. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  197535. {
  197536. if (png_ptr && info_ptr)
  197537. info_ptr->valid &= ~(mask);
  197538. }
  197539. #ifndef PNG_1_0_X
  197540. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  197541. /* function was added to libpng 1.2.0 and should always exist by default */
  197542. void PNGAPI
  197543. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  197544. {
  197545. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197546. if (png_ptr != NULL)
  197547. png_ptr->asm_flags = 0;
  197548. }
  197549. /* this function was added to libpng 1.2.0 */
  197550. void PNGAPI
  197551. png_set_mmx_thresholds (png_structp png_ptr,
  197552. png_byte,
  197553. png_uint_32)
  197554. {
  197555. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197556. if (png_ptr == NULL)
  197557. return;
  197558. }
  197559. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  197560. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197561. /* this function was added to libpng 1.2.6 */
  197562. void PNGAPI
  197563. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  197564. png_uint_32 user_height_max)
  197565. {
  197566. /* Images with dimensions larger than these limits will be
  197567. * rejected by png_set_IHDR(). To accept any PNG datastream
  197568. * regardless of dimensions, set both limits to 0x7ffffffL.
  197569. */
  197570. if(png_ptr == NULL) return;
  197571. png_ptr->user_width_max = user_width_max;
  197572. png_ptr->user_height_max = user_height_max;
  197573. }
  197574. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  197575. #endif /* ?PNG_1_0_X */
  197576. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197577. /*** End of inlined file: pngset.c ***/
  197578. /*** Start of inlined file: pngtrans.c ***/
  197579. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  197580. *
  197581. * Last changed in libpng 1.2.17 May 15, 2007
  197582. * For conditions of distribution and use, see copyright notice in png.h
  197583. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197584. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197585. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197586. */
  197587. #define PNG_INTERNAL
  197588. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197589. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197590. /* turn on BGR-to-RGB mapping */
  197591. void PNGAPI
  197592. png_set_bgr(png_structp png_ptr)
  197593. {
  197594. png_debug(1, "in png_set_bgr\n");
  197595. if(png_ptr == NULL) return;
  197596. png_ptr->transformations |= PNG_BGR;
  197597. }
  197598. #endif
  197599. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197600. /* turn on 16 bit byte swapping */
  197601. void PNGAPI
  197602. png_set_swap(png_structp png_ptr)
  197603. {
  197604. png_debug(1, "in png_set_swap\n");
  197605. if(png_ptr == NULL) return;
  197606. if (png_ptr->bit_depth == 16)
  197607. png_ptr->transformations |= PNG_SWAP_BYTES;
  197608. }
  197609. #endif
  197610. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  197611. /* turn on pixel packing */
  197612. void PNGAPI
  197613. png_set_packing(png_structp png_ptr)
  197614. {
  197615. png_debug(1, "in png_set_packing\n");
  197616. if(png_ptr == NULL) return;
  197617. if (png_ptr->bit_depth < 8)
  197618. {
  197619. png_ptr->transformations |= PNG_PACK;
  197620. png_ptr->usr_bit_depth = 8;
  197621. }
  197622. }
  197623. #endif
  197624. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197625. /* turn on packed pixel swapping */
  197626. void PNGAPI
  197627. png_set_packswap(png_structp png_ptr)
  197628. {
  197629. png_debug(1, "in png_set_packswap\n");
  197630. if(png_ptr == NULL) return;
  197631. if (png_ptr->bit_depth < 8)
  197632. png_ptr->transformations |= PNG_PACKSWAP;
  197633. }
  197634. #endif
  197635. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  197636. void PNGAPI
  197637. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  197638. {
  197639. png_debug(1, "in png_set_shift\n");
  197640. if(png_ptr == NULL) return;
  197641. png_ptr->transformations |= PNG_SHIFT;
  197642. png_ptr->shift = *true_bits;
  197643. }
  197644. #endif
  197645. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  197646. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197647. int PNGAPI
  197648. png_set_interlace_handling(png_structp png_ptr)
  197649. {
  197650. png_debug(1, "in png_set_interlace handling\n");
  197651. if (png_ptr && png_ptr->interlaced)
  197652. {
  197653. png_ptr->transformations |= PNG_INTERLACE;
  197654. return (7);
  197655. }
  197656. return (1);
  197657. }
  197658. #endif
  197659. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  197660. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  197661. * The filler type has changed in v0.95 to allow future 2-byte fillers
  197662. * for 48-bit input data, as well as to avoid problems with some compilers
  197663. * that don't like bytes as parameters.
  197664. */
  197665. void PNGAPI
  197666. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197667. {
  197668. png_debug(1, "in png_set_filler\n");
  197669. if(png_ptr == NULL) return;
  197670. png_ptr->transformations |= PNG_FILLER;
  197671. png_ptr->filler = (png_byte)filler;
  197672. if (filler_loc == PNG_FILLER_AFTER)
  197673. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  197674. else
  197675. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  197676. /* This should probably go in the "do_read_filler" routine.
  197677. * I attempted to do that in libpng-1.0.1a but that caused problems
  197678. * so I restored it in libpng-1.0.2a
  197679. */
  197680. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  197681. {
  197682. png_ptr->usr_channels = 4;
  197683. }
  197684. /* Also I added this in libpng-1.0.2a (what happens when we expand
  197685. * a less-than-8-bit grayscale to GA? */
  197686. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  197687. {
  197688. png_ptr->usr_channels = 2;
  197689. }
  197690. }
  197691. #if !defined(PNG_1_0_X)
  197692. /* Added to libpng-1.2.7 */
  197693. void PNGAPI
  197694. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197695. {
  197696. png_debug(1, "in png_set_add_alpha\n");
  197697. if(png_ptr == NULL) return;
  197698. png_set_filler(png_ptr, filler, filler_loc);
  197699. png_ptr->transformations |= PNG_ADD_ALPHA;
  197700. }
  197701. #endif
  197702. #endif
  197703. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  197704. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197705. void PNGAPI
  197706. png_set_swap_alpha(png_structp png_ptr)
  197707. {
  197708. png_debug(1, "in png_set_swap_alpha\n");
  197709. if(png_ptr == NULL) return;
  197710. png_ptr->transformations |= PNG_SWAP_ALPHA;
  197711. }
  197712. #endif
  197713. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  197714. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197715. void PNGAPI
  197716. png_set_invert_alpha(png_structp png_ptr)
  197717. {
  197718. png_debug(1, "in png_set_invert_alpha\n");
  197719. if(png_ptr == NULL) return;
  197720. png_ptr->transformations |= PNG_INVERT_ALPHA;
  197721. }
  197722. #endif
  197723. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  197724. void PNGAPI
  197725. png_set_invert_mono(png_structp png_ptr)
  197726. {
  197727. png_debug(1, "in png_set_invert_mono\n");
  197728. if(png_ptr == NULL) return;
  197729. png_ptr->transformations |= PNG_INVERT_MONO;
  197730. }
  197731. /* invert monochrome grayscale data */
  197732. void /* PRIVATE */
  197733. png_do_invert(png_row_infop row_info, png_bytep row)
  197734. {
  197735. png_debug(1, "in png_do_invert\n");
  197736. /* This test removed from libpng version 1.0.13 and 1.2.0:
  197737. * if (row_info->bit_depth == 1 &&
  197738. */
  197739. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197740. if (row == NULL || row_info == NULL)
  197741. return;
  197742. #endif
  197743. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  197744. {
  197745. png_bytep rp = row;
  197746. png_uint_32 i;
  197747. png_uint_32 istop = row_info->rowbytes;
  197748. for (i = 0; i < istop; i++)
  197749. {
  197750. *rp = (png_byte)(~(*rp));
  197751. rp++;
  197752. }
  197753. }
  197754. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197755. row_info->bit_depth == 8)
  197756. {
  197757. png_bytep rp = row;
  197758. png_uint_32 i;
  197759. png_uint_32 istop = row_info->rowbytes;
  197760. for (i = 0; i < istop; i+=2)
  197761. {
  197762. *rp = (png_byte)(~(*rp));
  197763. rp+=2;
  197764. }
  197765. }
  197766. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197767. row_info->bit_depth == 16)
  197768. {
  197769. png_bytep rp = row;
  197770. png_uint_32 i;
  197771. png_uint_32 istop = row_info->rowbytes;
  197772. for (i = 0; i < istop; i+=4)
  197773. {
  197774. *rp = (png_byte)(~(*rp));
  197775. *(rp+1) = (png_byte)(~(*(rp+1)));
  197776. rp+=4;
  197777. }
  197778. }
  197779. }
  197780. #endif
  197781. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197782. /* swaps byte order on 16 bit depth images */
  197783. void /* PRIVATE */
  197784. png_do_swap(png_row_infop row_info, png_bytep row)
  197785. {
  197786. png_debug(1, "in png_do_swap\n");
  197787. if (
  197788. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197789. row != NULL && row_info != NULL &&
  197790. #endif
  197791. row_info->bit_depth == 16)
  197792. {
  197793. png_bytep rp = row;
  197794. png_uint_32 i;
  197795. png_uint_32 istop= row_info->width * row_info->channels;
  197796. for (i = 0; i < istop; i++, rp += 2)
  197797. {
  197798. png_byte t = *rp;
  197799. *rp = *(rp + 1);
  197800. *(rp + 1) = t;
  197801. }
  197802. }
  197803. }
  197804. #endif
  197805. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197806. static PNG_CONST png_byte onebppswaptable[256] = {
  197807. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  197808. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  197809. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  197810. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  197811. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  197812. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  197813. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  197814. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  197815. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  197816. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  197817. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  197818. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  197819. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  197820. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  197821. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  197822. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  197823. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  197824. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  197825. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  197826. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  197827. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  197828. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  197829. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  197830. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  197831. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  197832. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  197833. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  197834. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  197835. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  197836. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  197837. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  197838. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  197839. };
  197840. static PNG_CONST png_byte twobppswaptable[256] = {
  197841. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  197842. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  197843. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  197844. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  197845. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  197846. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  197847. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  197848. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  197849. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  197850. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  197851. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  197852. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  197853. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  197854. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  197855. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  197856. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  197857. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  197858. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  197859. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  197860. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  197861. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  197862. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  197863. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  197864. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  197865. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  197866. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  197867. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  197868. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  197869. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  197870. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  197871. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  197872. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  197873. };
  197874. static PNG_CONST png_byte fourbppswaptable[256] = {
  197875. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  197876. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  197877. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  197878. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  197879. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  197880. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  197881. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  197882. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  197883. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  197884. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  197885. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  197886. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  197887. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  197888. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  197889. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  197890. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  197891. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  197892. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  197893. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  197894. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  197895. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  197896. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  197897. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  197898. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  197899. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  197900. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  197901. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  197902. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  197903. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  197904. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  197905. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  197906. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  197907. };
  197908. /* swaps pixel packing order within bytes */
  197909. void /* PRIVATE */
  197910. png_do_packswap(png_row_infop row_info, png_bytep row)
  197911. {
  197912. png_debug(1, "in png_do_packswap\n");
  197913. if (
  197914. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197915. row != NULL && row_info != NULL &&
  197916. #endif
  197917. row_info->bit_depth < 8)
  197918. {
  197919. png_bytep rp, end, table;
  197920. end = row + row_info->rowbytes;
  197921. if (row_info->bit_depth == 1)
  197922. table = (png_bytep)onebppswaptable;
  197923. else if (row_info->bit_depth == 2)
  197924. table = (png_bytep)twobppswaptable;
  197925. else if (row_info->bit_depth == 4)
  197926. table = (png_bytep)fourbppswaptable;
  197927. else
  197928. return;
  197929. for (rp = row; rp < end; rp++)
  197930. *rp = table[*rp];
  197931. }
  197932. }
  197933. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  197934. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  197935. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  197936. /* remove filler or alpha byte(s) */
  197937. void /* PRIVATE */
  197938. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  197939. {
  197940. png_debug(1, "in png_do_strip_filler\n");
  197941. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197942. if (row != NULL && row_info != NULL)
  197943. #endif
  197944. {
  197945. png_bytep sp=row;
  197946. png_bytep dp=row;
  197947. png_uint_32 row_width=row_info->width;
  197948. png_uint_32 i;
  197949. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  197950. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  197951. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  197952. row_info->channels == 4)
  197953. {
  197954. if (row_info->bit_depth == 8)
  197955. {
  197956. /* This converts from RGBX or RGBA to RGB */
  197957. if (flags & PNG_FLAG_FILLER_AFTER)
  197958. {
  197959. dp+=3; sp+=4;
  197960. for (i = 1; i < row_width; i++)
  197961. {
  197962. *dp++ = *sp++;
  197963. *dp++ = *sp++;
  197964. *dp++ = *sp++;
  197965. sp++;
  197966. }
  197967. }
  197968. /* This converts from XRGB or ARGB to RGB */
  197969. else
  197970. {
  197971. for (i = 0; i < row_width; i++)
  197972. {
  197973. sp++;
  197974. *dp++ = *sp++;
  197975. *dp++ = *sp++;
  197976. *dp++ = *sp++;
  197977. }
  197978. }
  197979. row_info->pixel_depth = 24;
  197980. row_info->rowbytes = row_width * 3;
  197981. }
  197982. else /* if (row_info->bit_depth == 16) */
  197983. {
  197984. if (flags & PNG_FLAG_FILLER_AFTER)
  197985. {
  197986. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  197987. sp += 8; dp += 6;
  197988. for (i = 1; i < row_width; i++)
  197989. {
  197990. /* This could be (although png_memcpy is probably slower):
  197991. png_memcpy(dp, sp, 6);
  197992. sp += 8;
  197993. dp += 6;
  197994. */
  197995. *dp++ = *sp++;
  197996. *dp++ = *sp++;
  197997. *dp++ = *sp++;
  197998. *dp++ = *sp++;
  197999. *dp++ = *sp++;
  198000. *dp++ = *sp++;
  198001. sp += 2;
  198002. }
  198003. }
  198004. else
  198005. {
  198006. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  198007. for (i = 0; i < row_width; i++)
  198008. {
  198009. /* This could be (although png_memcpy is probably slower):
  198010. png_memcpy(dp, sp, 6);
  198011. sp += 8;
  198012. dp += 6;
  198013. */
  198014. sp+=2;
  198015. *dp++ = *sp++;
  198016. *dp++ = *sp++;
  198017. *dp++ = *sp++;
  198018. *dp++ = *sp++;
  198019. *dp++ = *sp++;
  198020. *dp++ = *sp++;
  198021. }
  198022. }
  198023. row_info->pixel_depth = 48;
  198024. row_info->rowbytes = row_width * 6;
  198025. }
  198026. row_info->channels = 3;
  198027. }
  198028. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198029. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198030. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198031. row_info->channels == 2)
  198032. {
  198033. if (row_info->bit_depth == 8)
  198034. {
  198035. /* This converts from GX or GA to G */
  198036. if (flags & PNG_FLAG_FILLER_AFTER)
  198037. {
  198038. for (i = 0; i < row_width; i++)
  198039. {
  198040. *dp++ = *sp++;
  198041. sp++;
  198042. }
  198043. }
  198044. /* This converts from XG or AG to G */
  198045. else
  198046. {
  198047. for (i = 0; i < row_width; i++)
  198048. {
  198049. sp++;
  198050. *dp++ = *sp++;
  198051. }
  198052. }
  198053. row_info->pixel_depth = 8;
  198054. row_info->rowbytes = row_width;
  198055. }
  198056. else /* if (row_info->bit_depth == 16) */
  198057. {
  198058. if (flags & PNG_FLAG_FILLER_AFTER)
  198059. {
  198060. /* This converts from GGXX or GGAA to GG */
  198061. sp += 4; dp += 2;
  198062. for (i = 1; i < row_width; i++)
  198063. {
  198064. *dp++ = *sp++;
  198065. *dp++ = *sp++;
  198066. sp += 2;
  198067. }
  198068. }
  198069. else
  198070. {
  198071. /* This converts from XXGG or AAGG to GG */
  198072. for (i = 0; i < row_width; i++)
  198073. {
  198074. sp += 2;
  198075. *dp++ = *sp++;
  198076. *dp++ = *sp++;
  198077. }
  198078. }
  198079. row_info->pixel_depth = 16;
  198080. row_info->rowbytes = row_width * 2;
  198081. }
  198082. row_info->channels = 1;
  198083. }
  198084. if (flags & PNG_FLAG_STRIP_ALPHA)
  198085. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198086. }
  198087. }
  198088. #endif
  198089. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198090. /* swaps red and blue bytes within a pixel */
  198091. void /* PRIVATE */
  198092. png_do_bgr(png_row_infop row_info, png_bytep row)
  198093. {
  198094. png_debug(1, "in png_do_bgr\n");
  198095. if (
  198096. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198097. row != NULL && row_info != NULL &&
  198098. #endif
  198099. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198100. {
  198101. png_uint_32 row_width = row_info->width;
  198102. if (row_info->bit_depth == 8)
  198103. {
  198104. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198105. {
  198106. png_bytep rp;
  198107. png_uint_32 i;
  198108. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198109. {
  198110. png_byte save = *rp;
  198111. *rp = *(rp + 2);
  198112. *(rp + 2) = save;
  198113. }
  198114. }
  198115. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198116. {
  198117. png_bytep rp;
  198118. png_uint_32 i;
  198119. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198120. {
  198121. png_byte save = *rp;
  198122. *rp = *(rp + 2);
  198123. *(rp + 2) = save;
  198124. }
  198125. }
  198126. }
  198127. else if (row_info->bit_depth == 16)
  198128. {
  198129. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198130. {
  198131. png_bytep rp;
  198132. png_uint_32 i;
  198133. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198134. {
  198135. png_byte save = *rp;
  198136. *rp = *(rp + 4);
  198137. *(rp + 4) = save;
  198138. save = *(rp + 1);
  198139. *(rp + 1) = *(rp + 5);
  198140. *(rp + 5) = save;
  198141. }
  198142. }
  198143. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198144. {
  198145. png_bytep rp;
  198146. png_uint_32 i;
  198147. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198148. {
  198149. png_byte save = *rp;
  198150. *rp = *(rp + 4);
  198151. *(rp + 4) = save;
  198152. save = *(rp + 1);
  198153. *(rp + 1) = *(rp + 5);
  198154. *(rp + 5) = save;
  198155. }
  198156. }
  198157. }
  198158. }
  198159. }
  198160. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198161. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198162. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198163. defined(PNG_LEGACY_SUPPORTED)
  198164. void PNGAPI
  198165. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198166. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198167. {
  198168. png_debug(1, "in png_set_user_transform_info\n");
  198169. if(png_ptr == NULL) return;
  198170. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198171. png_ptr->user_transform_ptr = user_transform_ptr;
  198172. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198173. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198174. #else
  198175. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198176. png_warning(png_ptr,
  198177. "This version of libpng does not support user transform info");
  198178. #endif
  198179. }
  198180. #endif
  198181. /* This function returns a pointer to the user_transform_ptr associated with
  198182. * the user transform functions. The application should free any memory
  198183. * associated with this pointer before png_write_destroy and png_read_destroy
  198184. * are called.
  198185. */
  198186. png_voidp PNGAPI
  198187. png_get_user_transform_ptr(png_structp png_ptr)
  198188. {
  198189. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198190. if (png_ptr == NULL) return (NULL);
  198191. return ((png_voidp)png_ptr->user_transform_ptr);
  198192. #else
  198193. return (NULL);
  198194. #endif
  198195. }
  198196. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198197. /*** End of inlined file: pngtrans.c ***/
  198198. /*** Start of inlined file: pngwio.c ***/
  198199. /* pngwio.c - functions for data output
  198200. *
  198201. * Last changed in libpng 1.2.13 November 13, 2006
  198202. * For conditions of distribution and use, see copyright notice in png.h
  198203. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198204. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198205. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198206. *
  198207. * This file provides a location for all output. Users who need
  198208. * special handling are expected to write functions that have the same
  198209. * arguments as these and perform similar functions, but that possibly
  198210. * use different output methods. Note that you shouldn't change these
  198211. * functions, but rather write replacement functions and then change
  198212. * them at run time with png_set_write_fn(...).
  198213. */
  198214. #define PNG_INTERNAL
  198215. #ifdef PNG_WRITE_SUPPORTED
  198216. /* Write the data to whatever output you are using. The default routine
  198217. writes to a file pointer. Note that this routine sometimes gets called
  198218. with very small lengths, so you should implement some kind of simple
  198219. buffering if you are using unbuffered writes. This should never be asked
  198220. to write more than 64K on a 16 bit machine. */
  198221. void /* PRIVATE */
  198222. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198223. {
  198224. if (png_ptr->write_data_fn != NULL )
  198225. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198226. else
  198227. png_error(png_ptr, "Call to NULL write function");
  198228. }
  198229. #if !defined(PNG_NO_STDIO)
  198230. /* This is the function that does the actual writing of data. If you are
  198231. not writing to a standard C stream, you should create a replacement
  198232. write_data function and use it at run time with png_set_write_fn(), rather
  198233. than changing the library. */
  198234. #ifndef USE_FAR_KEYWORD
  198235. void PNGAPI
  198236. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198237. {
  198238. png_uint_32 check;
  198239. if(png_ptr == NULL) return;
  198240. #if defined(_WIN32_WCE)
  198241. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198242. check = 0;
  198243. #else
  198244. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198245. #endif
  198246. if (check != length)
  198247. png_error(png_ptr, "Write Error");
  198248. }
  198249. #else
  198250. /* this is the model-independent version. Since the standard I/O library
  198251. can't handle far buffers in the medium and small models, we have to copy
  198252. the data.
  198253. */
  198254. #define NEAR_BUF_SIZE 1024
  198255. #define MIN(a,b) (a <= b ? a : b)
  198256. void PNGAPI
  198257. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198258. {
  198259. png_uint_32 check;
  198260. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198261. png_FILE_p io_ptr;
  198262. if(png_ptr == NULL) return;
  198263. /* Check if data really is near. If so, use usual code. */
  198264. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198265. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198266. if ((png_bytep)near_data == data)
  198267. {
  198268. #if defined(_WIN32_WCE)
  198269. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198270. check = 0;
  198271. #else
  198272. check = fwrite(near_data, 1, length, io_ptr);
  198273. #endif
  198274. }
  198275. else
  198276. {
  198277. png_byte buf[NEAR_BUF_SIZE];
  198278. png_size_t written, remaining, err;
  198279. check = 0;
  198280. remaining = length;
  198281. do
  198282. {
  198283. written = MIN(NEAR_BUF_SIZE, remaining);
  198284. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198285. #if defined(_WIN32_WCE)
  198286. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198287. err = 0;
  198288. #else
  198289. err = fwrite(buf, 1, written, io_ptr);
  198290. #endif
  198291. if (err != written)
  198292. break;
  198293. else
  198294. check += err;
  198295. data += written;
  198296. remaining -= written;
  198297. }
  198298. while (remaining != 0);
  198299. }
  198300. if (check != length)
  198301. png_error(png_ptr, "Write Error");
  198302. }
  198303. #endif
  198304. #endif
  198305. /* This function is called to output any data pending writing (normally
  198306. to disk). After png_flush is called, there should be no data pending
  198307. writing in any buffers. */
  198308. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198309. void /* PRIVATE */
  198310. png_flush(png_structp png_ptr)
  198311. {
  198312. if (png_ptr->output_flush_fn != NULL)
  198313. (*(png_ptr->output_flush_fn))(png_ptr);
  198314. }
  198315. #if !defined(PNG_NO_STDIO)
  198316. void PNGAPI
  198317. png_default_flush(png_structp png_ptr)
  198318. {
  198319. #if !defined(_WIN32_WCE)
  198320. png_FILE_p io_ptr;
  198321. #endif
  198322. if(png_ptr == NULL) return;
  198323. #if !defined(_WIN32_WCE)
  198324. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198325. if (io_ptr != NULL)
  198326. fflush(io_ptr);
  198327. #endif
  198328. }
  198329. #endif
  198330. #endif
  198331. /* This function allows the application to supply new output functions for
  198332. libpng if standard C streams aren't being used.
  198333. This function takes as its arguments:
  198334. png_ptr - pointer to a png output data structure
  198335. io_ptr - pointer to user supplied structure containing info about
  198336. the output functions. May be NULL.
  198337. write_data_fn - pointer to a new output function that takes as its
  198338. arguments a pointer to a png_struct, a pointer to
  198339. data to be written, and a 32-bit unsigned int that is
  198340. the number of bytes to be written. The new write
  198341. function should call png_error(png_ptr, "Error msg")
  198342. to exit and output any fatal error messages.
  198343. flush_data_fn - pointer to a new flush function that takes as its
  198344. arguments a pointer to a png_struct. After a call to
  198345. the flush function, there should be no data in any buffers
  198346. or pending transmission. If the output method doesn't do
  198347. any buffering of ouput, a function prototype must still be
  198348. supplied although it doesn't have to do anything. If
  198349. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198350. time, output_flush_fn will be ignored, although it must be
  198351. supplied for compatibility. */
  198352. void PNGAPI
  198353. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198354. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198355. {
  198356. if(png_ptr == NULL) return;
  198357. png_ptr->io_ptr = io_ptr;
  198358. #if !defined(PNG_NO_STDIO)
  198359. if (write_data_fn != NULL)
  198360. png_ptr->write_data_fn = write_data_fn;
  198361. else
  198362. png_ptr->write_data_fn = png_default_write_data;
  198363. #else
  198364. png_ptr->write_data_fn = write_data_fn;
  198365. #endif
  198366. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198367. #if !defined(PNG_NO_STDIO)
  198368. if (output_flush_fn != NULL)
  198369. png_ptr->output_flush_fn = output_flush_fn;
  198370. else
  198371. png_ptr->output_flush_fn = png_default_flush;
  198372. #else
  198373. png_ptr->output_flush_fn = output_flush_fn;
  198374. #endif
  198375. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198376. /* It is an error to read while writing a png file */
  198377. if (png_ptr->read_data_fn != NULL)
  198378. {
  198379. png_ptr->read_data_fn = NULL;
  198380. png_warning(png_ptr,
  198381. "Attempted to set both read_data_fn and write_data_fn in");
  198382. png_warning(png_ptr,
  198383. "the same structure. Resetting read_data_fn to NULL.");
  198384. }
  198385. }
  198386. #if defined(USE_FAR_KEYWORD)
  198387. #if defined(_MSC_VER)
  198388. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198389. {
  198390. void *near_ptr;
  198391. void FAR *far_ptr;
  198392. FP_OFF(near_ptr) = FP_OFF(ptr);
  198393. far_ptr = (void FAR *)near_ptr;
  198394. if(check != 0)
  198395. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198396. png_error(png_ptr,"segment lost in conversion");
  198397. return(near_ptr);
  198398. }
  198399. # else
  198400. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198401. {
  198402. void *near_ptr;
  198403. void FAR *far_ptr;
  198404. near_ptr = (void FAR *)ptr;
  198405. far_ptr = (void FAR *)near_ptr;
  198406. if(check != 0)
  198407. if(far_ptr != ptr)
  198408. png_error(png_ptr,"segment lost in conversion");
  198409. return(near_ptr);
  198410. }
  198411. # endif
  198412. # endif
  198413. #endif /* PNG_WRITE_SUPPORTED */
  198414. /*** End of inlined file: pngwio.c ***/
  198415. /*** Start of inlined file: pngwrite.c ***/
  198416. /* pngwrite.c - general routines to write a PNG file
  198417. *
  198418. * Last changed in libpng 1.2.15 January 5, 2007
  198419. * For conditions of distribution and use, see copyright notice in png.h
  198420. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198421. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198422. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198423. */
  198424. /* get internal access to png.h */
  198425. #define PNG_INTERNAL
  198426. #ifdef PNG_WRITE_SUPPORTED
  198427. /* Writes all the PNG information. This is the suggested way to use the
  198428. * library. If you have a new chunk to add, make a function to write it,
  198429. * and put it in the correct location here. If you want the chunk written
  198430. * after the image data, put it in png_write_end(). I strongly encourage
  198431. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198432. * the chunk, as that will keep the code from breaking if you want to just
  198433. * write a plain PNG file. If you have long comments, I suggest writing
  198434. * them in png_write_end(), and compressing them.
  198435. */
  198436. void PNGAPI
  198437. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198438. {
  198439. png_debug(1, "in png_write_info_before_PLTE\n");
  198440. if (png_ptr == NULL || info_ptr == NULL)
  198441. return;
  198442. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198443. {
  198444. png_write_sig(png_ptr); /* write PNG signature */
  198445. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198446. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198447. {
  198448. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198449. png_ptr->mng_features_permitted=0;
  198450. }
  198451. #endif
  198452. /* write IHDR information. */
  198453. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198454. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198455. info_ptr->filter_type,
  198456. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198457. info_ptr->interlace_type);
  198458. #else
  198459. 0);
  198460. #endif
  198461. /* the rest of these check to see if the valid field has the appropriate
  198462. flag set, and if it does, writes the chunk. */
  198463. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198464. if (info_ptr->valid & PNG_INFO_gAMA)
  198465. {
  198466. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198467. png_write_gAMA(png_ptr, info_ptr->gamma);
  198468. #else
  198469. #ifdef PNG_FIXED_POINT_SUPPORTED
  198470. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198471. # endif
  198472. #endif
  198473. }
  198474. #endif
  198475. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198476. if (info_ptr->valid & PNG_INFO_sRGB)
  198477. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198478. #endif
  198479. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198480. if (info_ptr->valid & PNG_INFO_iCCP)
  198481. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198482. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198483. #endif
  198484. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198485. if (info_ptr->valid & PNG_INFO_sBIT)
  198486. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198487. #endif
  198488. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198489. if (info_ptr->valid & PNG_INFO_cHRM)
  198490. {
  198491. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198492. png_write_cHRM(png_ptr,
  198493. info_ptr->x_white, info_ptr->y_white,
  198494. info_ptr->x_red, info_ptr->y_red,
  198495. info_ptr->x_green, info_ptr->y_green,
  198496. info_ptr->x_blue, info_ptr->y_blue);
  198497. #else
  198498. # ifdef PNG_FIXED_POINT_SUPPORTED
  198499. png_write_cHRM_fixed(png_ptr,
  198500. info_ptr->int_x_white, info_ptr->int_y_white,
  198501. info_ptr->int_x_red, info_ptr->int_y_red,
  198502. info_ptr->int_x_green, info_ptr->int_y_green,
  198503. info_ptr->int_x_blue, info_ptr->int_y_blue);
  198504. # endif
  198505. #endif
  198506. }
  198507. #endif
  198508. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198509. if (info_ptr->unknown_chunks_num)
  198510. {
  198511. png_unknown_chunk *up;
  198512. png_debug(5, "writing extra chunks\n");
  198513. for (up = info_ptr->unknown_chunks;
  198514. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198515. up++)
  198516. {
  198517. int keep=png_handle_as_unknown(png_ptr, up->name);
  198518. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198519. up->location && !(up->location & PNG_HAVE_PLTE) &&
  198520. !(up->location & PNG_HAVE_IDAT) &&
  198521. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198522. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198523. {
  198524. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198525. }
  198526. }
  198527. }
  198528. #endif
  198529. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  198530. }
  198531. }
  198532. void PNGAPI
  198533. png_write_info(png_structp png_ptr, png_infop info_ptr)
  198534. {
  198535. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198536. int i;
  198537. #endif
  198538. png_debug(1, "in png_write_info\n");
  198539. if (png_ptr == NULL || info_ptr == NULL)
  198540. return;
  198541. png_write_info_before_PLTE(png_ptr, info_ptr);
  198542. if (info_ptr->valid & PNG_INFO_PLTE)
  198543. png_write_PLTE(png_ptr, info_ptr->palette,
  198544. (png_uint_32)info_ptr->num_palette);
  198545. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198546. png_error(png_ptr, "Valid palette required for paletted images");
  198547. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198548. if (info_ptr->valid & PNG_INFO_tRNS)
  198549. {
  198550. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198551. /* invert the alpha channel (in tRNS) */
  198552. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  198553. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198554. {
  198555. int j;
  198556. for (j=0; j<(int)info_ptr->num_trans; j++)
  198557. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  198558. }
  198559. #endif
  198560. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  198561. info_ptr->num_trans, info_ptr->color_type);
  198562. }
  198563. #endif
  198564. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198565. if (info_ptr->valid & PNG_INFO_bKGD)
  198566. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  198567. #endif
  198568. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198569. if (info_ptr->valid & PNG_INFO_hIST)
  198570. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  198571. #endif
  198572. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198573. if (info_ptr->valid & PNG_INFO_oFFs)
  198574. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  198575. info_ptr->offset_unit_type);
  198576. #endif
  198577. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198578. if (info_ptr->valid & PNG_INFO_pCAL)
  198579. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  198580. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  198581. info_ptr->pcal_units, info_ptr->pcal_params);
  198582. #endif
  198583. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198584. if (info_ptr->valid & PNG_INFO_sCAL)
  198585. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198586. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  198587. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  198588. #else
  198589. #ifdef PNG_FIXED_POINT_SUPPORTED
  198590. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  198591. info_ptr->scal_s_width, info_ptr->scal_s_height);
  198592. #else
  198593. png_warning(png_ptr,
  198594. "png_write_sCAL not supported; sCAL chunk not written.");
  198595. #endif
  198596. #endif
  198597. #endif
  198598. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198599. if (info_ptr->valid & PNG_INFO_pHYs)
  198600. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  198601. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  198602. #endif
  198603. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198604. if (info_ptr->valid & PNG_INFO_tIME)
  198605. {
  198606. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198607. png_ptr->mode |= PNG_WROTE_tIME;
  198608. }
  198609. #endif
  198610. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198611. if (info_ptr->valid & PNG_INFO_sPLT)
  198612. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  198613. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  198614. #endif
  198615. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198616. /* Check to see if we need to write text chunks */
  198617. for (i = 0; i < info_ptr->num_text; i++)
  198618. {
  198619. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  198620. info_ptr->text[i].compression);
  198621. /* an internationalized chunk? */
  198622. if (info_ptr->text[i].compression > 0)
  198623. {
  198624. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198625. /* write international chunk */
  198626. png_write_iTXt(png_ptr,
  198627. info_ptr->text[i].compression,
  198628. info_ptr->text[i].key,
  198629. info_ptr->text[i].lang,
  198630. info_ptr->text[i].lang_key,
  198631. info_ptr->text[i].text);
  198632. #else
  198633. png_warning(png_ptr, "Unable to write international text");
  198634. #endif
  198635. /* Mark this chunk as written */
  198636. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198637. }
  198638. /* If we want a compressed text chunk */
  198639. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  198640. {
  198641. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198642. /* write compressed chunk */
  198643. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198644. info_ptr->text[i].text, 0,
  198645. info_ptr->text[i].compression);
  198646. #else
  198647. png_warning(png_ptr, "Unable to write compressed text");
  198648. #endif
  198649. /* Mark this chunk as written */
  198650. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198651. }
  198652. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198653. {
  198654. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198655. /* write uncompressed chunk */
  198656. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198657. info_ptr->text[i].text,
  198658. 0);
  198659. #else
  198660. png_warning(png_ptr, "Unable to write uncompressed text");
  198661. #endif
  198662. /* Mark this chunk as written */
  198663. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198664. }
  198665. }
  198666. #endif
  198667. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198668. if (info_ptr->unknown_chunks_num)
  198669. {
  198670. png_unknown_chunk *up;
  198671. png_debug(5, "writing extra chunks\n");
  198672. for (up = info_ptr->unknown_chunks;
  198673. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198674. up++)
  198675. {
  198676. int keep=png_handle_as_unknown(png_ptr, up->name);
  198677. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198678. up->location && (up->location & PNG_HAVE_PLTE) &&
  198679. !(up->location & PNG_HAVE_IDAT) &&
  198680. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198681. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198682. {
  198683. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198684. }
  198685. }
  198686. }
  198687. #endif
  198688. }
  198689. /* Writes the end of the PNG file. If you don't want to write comments or
  198690. * time information, you can pass NULL for info. If you already wrote these
  198691. * in png_write_info(), do not write them again here. If you have long
  198692. * comments, I suggest writing them here, and compressing them.
  198693. */
  198694. void PNGAPI
  198695. png_write_end(png_structp png_ptr, png_infop info_ptr)
  198696. {
  198697. png_debug(1, "in png_write_end\n");
  198698. if (png_ptr == NULL)
  198699. return;
  198700. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  198701. png_error(png_ptr, "No IDATs written into file");
  198702. /* see if user wants us to write information chunks */
  198703. if (info_ptr != NULL)
  198704. {
  198705. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198706. int i; /* local index variable */
  198707. #endif
  198708. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198709. /* check to see if user has supplied a time chunk */
  198710. if ((info_ptr->valid & PNG_INFO_tIME) &&
  198711. !(png_ptr->mode & PNG_WROTE_tIME))
  198712. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198713. #endif
  198714. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198715. /* loop through comment chunks */
  198716. for (i = 0; i < info_ptr->num_text; i++)
  198717. {
  198718. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  198719. info_ptr->text[i].compression);
  198720. /* an internationalized chunk? */
  198721. if (info_ptr->text[i].compression > 0)
  198722. {
  198723. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198724. /* write international chunk */
  198725. png_write_iTXt(png_ptr,
  198726. info_ptr->text[i].compression,
  198727. info_ptr->text[i].key,
  198728. info_ptr->text[i].lang,
  198729. info_ptr->text[i].lang_key,
  198730. info_ptr->text[i].text);
  198731. #else
  198732. png_warning(png_ptr, "Unable to write international text");
  198733. #endif
  198734. /* Mark this chunk as written */
  198735. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198736. }
  198737. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  198738. {
  198739. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198740. /* write compressed chunk */
  198741. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198742. info_ptr->text[i].text, 0,
  198743. info_ptr->text[i].compression);
  198744. #else
  198745. png_warning(png_ptr, "Unable to write compressed text");
  198746. #endif
  198747. /* Mark this chunk as written */
  198748. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198749. }
  198750. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198751. {
  198752. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198753. /* write uncompressed chunk */
  198754. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198755. info_ptr->text[i].text, 0);
  198756. #else
  198757. png_warning(png_ptr, "Unable to write uncompressed text");
  198758. #endif
  198759. /* Mark this chunk as written */
  198760. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198761. }
  198762. }
  198763. #endif
  198764. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198765. if (info_ptr->unknown_chunks_num)
  198766. {
  198767. png_unknown_chunk *up;
  198768. png_debug(5, "writing extra chunks\n");
  198769. for (up = info_ptr->unknown_chunks;
  198770. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198771. up++)
  198772. {
  198773. int keep=png_handle_as_unknown(png_ptr, up->name);
  198774. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198775. up->location && (up->location & PNG_AFTER_IDAT) &&
  198776. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198777. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198778. {
  198779. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198780. }
  198781. }
  198782. }
  198783. #endif
  198784. }
  198785. png_ptr->mode |= PNG_AFTER_IDAT;
  198786. /* write end of PNG file */
  198787. png_write_IEND(png_ptr);
  198788. }
  198789. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198790. #if !defined(_WIN32_WCE)
  198791. /* "time.h" functions are not supported on WindowsCE */
  198792. void PNGAPI
  198793. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  198794. {
  198795. png_debug(1, "in png_convert_from_struct_tm\n");
  198796. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  198797. ptime->month = (png_byte)(ttime->tm_mon + 1);
  198798. ptime->day = (png_byte)ttime->tm_mday;
  198799. ptime->hour = (png_byte)ttime->tm_hour;
  198800. ptime->minute = (png_byte)ttime->tm_min;
  198801. ptime->second = (png_byte)ttime->tm_sec;
  198802. }
  198803. void PNGAPI
  198804. png_convert_from_time_t(png_timep ptime, time_t ttime)
  198805. {
  198806. struct tm *tbuf;
  198807. png_debug(1, "in png_convert_from_time_t\n");
  198808. tbuf = gmtime(&ttime);
  198809. png_convert_from_struct_tm(ptime, tbuf);
  198810. }
  198811. #endif
  198812. #endif
  198813. /* Initialize png_ptr structure, and allocate any memory needed */
  198814. png_structp PNGAPI
  198815. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  198816. png_error_ptr error_fn, png_error_ptr warn_fn)
  198817. {
  198818. #ifdef PNG_USER_MEM_SUPPORTED
  198819. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  198820. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  198821. }
  198822. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  198823. png_structp PNGAPI
  198824. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  198825. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  198826. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  198827. {
  198828. #endif /* PNG_USER_MEM_SUPPORTED */
  198829. png_structp png_ptr;
  198830. #ifdef PNG_SETJMP_SUPPORTED
  198831. #ifdef USE_FAR_KEYWORD
  198832. jmp_buf jmpbuf;
  198833. #endif
  198834. #endif
  198835. int i;
  198836. png_debug(1, "in png_create_write_struct\n");
  198837. #ifdef PNG_USER_MEM_SUPPORTED
  198838. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  198839. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  198840. #else
  198841. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  198842. #endif /* PNG_USER_MEM_SUPPORTED */
  198843. if (png_ptr == NULL)
  198844. return (NULL);
  198845. /* added at libpng-1.2.6 */
  198846. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198847. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  198848. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  198849. #endif
  198850. #ifdef PNG_SETJMP_SUPPORTED
  198851. #ifdef USE_FAR_KEYWORD
  198852. if (setjmp(jmpbuf))
  198853. #else
  198854. if (setjmp(png_ptr->jmpbuf))
  198855. #endif
  198856. {
  198857. png_free(png_ptr, png_ptr->zbuf);
  198858. png_ptr->zbuf=NULL;
  198859. png_destroy_struct(png_ptr);
  198860. return (NULL);
  198861. }
  198862. #ifdef USE_FAR_KEYWORD
  198863. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198864. #endif
  198865. #endif
  198866. #ifdef PNG_USER_MEM_SUPPORTED
  198867. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  198868. #endif /* PNG_USER_MEM_SUPPORTED */
  198869. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  198870. i=0;
  198871. do
  198872. {
  198873. if(user_png_ver[i] != png_libpng_ver[i])
  198874. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198875. } while (png_libpng_ver[i++]);
  198876. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  198877. {
  198878. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  198879. * we must recompile any applications that use any older library version.
  198880. * For versions after libpng 1.0, we will be compatible, so we need
  198881. * only check the first digit.
  198882. */
  198883. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  198884. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  198885. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  198886. {
  198887. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198888. char msg[80];
  198889. if (user_png_ver)
  198890. {
  198891. png_snprintf(msg, 80,
  198892. "Application was compiled with png.h from libpng-%.20s",
  198893. user_png_ver);
  198894. png_warning(png_ptr, msg);
  198895. }
  198896. png_snprintf(msg, 80,
  198897. "Application is running with png.c from libpng-%.20s",
  198898. png_libpng_ver);
  198899. png_warning(png_ptr, msg);
  198900. #endif
  198901. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198902. png_ptr->flags=0;
  198903. #endif
  198904. png_error(png_ptr,
  198905. "Incompatible libpng version in application and library");
  198906. }
  198907. }
  198908. /* initialize zbuf - compression buffer */
  198909. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  198910. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  198911. (png_uint_32)png_ptr->zbuf_size);
  198912. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  198913. png_flush_ptr_NULL);
  198914. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198915. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  198916. 1, png_doublep_NULL, png_doublep_NULL);
  198917. #endif
  198918. #ifdef PNG_SETJMP_SUPPORTED
  198919. /* Applications that neglect to set up their own setjmp() and then encounter
  198920. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  198921. abort instead of returning. */
  198922. #ifdef USE_FAR_KEYWORD
  198923. if (setjmp(jmpbuf))
  198924. PNG_ABORT();
  198925. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198926. #else
  198927. if (setjmp(png_ptr->jmpbuf))
  198928. PNG_ABORT();
  198929. #endif
  198930. #endif
  198931. return (png_ptr);
  198932. }
  198933. /* Initialize png_ptr structure, and allocate any memory needed */
  198934. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  198935. /* Deprecated. */
  198936. #undef png_write_init
  198937. void PNGAPI
  198938. png_write_init(png_structp png_ptr)
  198939. {
  198940. /* We only come here via pre-1.0.7-compiled applications */
  198941. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  198942. }
  198943. void PNGAPI
  198944. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  198945. png_size_t png_struct_size, png_size_t png_info_size)
  198946. {
  198947. /* We only come here via pre-1.0.12-compiled applications */
  198948. if(png_ptr == NULL) return;
  198949. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198950. if(png_sizeof(png_struct) > png_struct_size ||
  198951. png_sizeof(png_info) > png_info_size)
  198952. {
  198953. char msg[80];
  198954. png_ptr->warning_fn=NULL;
  198955. if (user_png_ver)
  198956. {
  198957. png_snprintf(msg, 80,
  198958. "Application was compiled with png.h from libpng-%.20s",
  198959. user_png_ver);
  198960. png_warning(png_ptr, msg);
  198961. }
  198962. png_snprintf(msg, 80,
  198963. "Application is running with png.c from libpng-%.20s",
  198964. png_libpng_ver);
  198965. png_warning(png_ptr, msg);
  198966. }
  198967. #endif
  198968. if(png_sizeof(png_struct) > png_struct_size)
  198969. {
  198970. png_ptr->error_fn=NULL;
  198971. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198972. png_ptr->flags=0;
  198973. #endif
  198974. png_error(png_ptr,
  198975. "The png struct allocated by the application for writing is too small.");
  198976. }
  198977. if(png_sizeof(png_info) > png_info_size)
  198978. {
  198979. png_ptr->error_fn=NULL;
  198980. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198981. png_ptr->flags=0;
  198982. #endif
  198983. png_error(png_ptr,
  198984. "The info struct allocated by the application for writing is too small.");
  198985. }
  198986. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  198987. }
  198988. #endif /* PNG_1_0_X || PNG_1_2_X */
  198989. void PNGAPI
  198990. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  198991. png_size_t png_struct_size)
  198992. {
  198993. png_structp png_ptr=*ptr_ptr;
  198994. #ifdef PNG_SETJMP_SUPPORTED
  198995. jmp_buf tmp_jmp; /* to save current jump buffer */
  198996. #endif
  198997. int i = 0;
  198998. if (png_ptr == NULL)
  198999. return;
  199000. do
  199001. {
  199002. if (user_png_ver[i] != png_libpng_ver[i])
  199003. {
  199004. #ifdef PNG_LEGACY_SUPPORTED
  199005. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199006. #else
  199007. png_ptr->warning_fn=NULL;
  199008. png_warning(png_ptr,
  199009. "Application uses deprecated png_write_init() and should be recompiled.");
  199010. break;
  199011. #endif
  199012. }
  199013. } while (png_libpng_ver[i++]);
  199014. png_debug(1, "in png_write_init_3\n");
  199015. #ifdef PNG_SETJMP_SUPPORTED
  199016. /* save jump buffer and error functions */
  199017. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199018. #endif
  199019. if (png_sizeof(png_struct) > png_struct_size)
  199020. {
  199021. png_destroy_struct(png_ptr);
  199022. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199023. *ptr_ptr = png_ptr;
  199024. }
  199025. /* reset all variables to 0 */
  199026. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199027. /* added at libpng-1.2.6 */
  199028. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199029. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199030. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199031. #endif
  199032. #ifdef PNG_SETJMP_SUPPORTED
  199033. /* restore jump buffer */
  199034. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199035. #endif
  199036. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199037. png_flush_ptr_NULL);
  199038. /* initialize zbuf - compression buffer */
  199039. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199040. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199041. (png_uint_32)png_ptr->zbuf_size);
  199042. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199043. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199044. 1, png_doublep_NULL, png_doublep_NULL);
  199045. #endif
  199046. }
  199047. /* Write a few rows of image data. If the image is interlaced,
  199048. * either you will have to write the 7 sub images, or, if you
  199049. * have called png_set_interlace_handling(), you will have to
  199050. * "write" the image seven times.
  199051. */
  199052. void PNGAPI
  199053. png_write_rows(png_structp png_ptr, png_bytepp row,
  199054. png_uint_32 num_rows)
  199055. {
  199056. png_uint_32 i; /* row counter */
  199057. png_bytepp rp; /* row pointer */
  199058. png_debug(1, "in png_write_rows\n");
  199059. if (png_ptr == NULL)
  199060. return;
  199061. /* loop through the rows */
  199062. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199063. {
  199064. png_write_row(png_ptr, *rp);
  199065. }
  199066. }
  199067. /* Write the image. You only need to call this function once, even
  199068. * if you are writing an interlaced image.
  199069. */
  199070. void PNGAPI
  199071. png_write_image(png_structp png_ptr, png_bytepp image)
  199072. {
  199073. png_uint_32 i; /* row index */
  199074. int pass, num_pass; /* pass variables */
  199075. png_bytepp rp; /* points to current row */
  199076. if (png_ptr == NULL)
  199077. return;
  199078. png_debug(1, "in png_write_image\n");
  199079. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199080. /* intialize interlace handling. If image is not interlaced,
  199081. this will set pass to 1 */
  199082. num_pass = png_set_interlace_handling(png_ptr);
  199083. #else
  199084. num_pass = 1;
  199085. #endif
  199086. /* loop through passes */
  199087. for (pass = 0; pass < num_pass; pass++)
  199088. {
  199089. /* loop through image */
  199090. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199091. {
  199092. png_write_row(png_ptr, *rp);
  199093. }
  199094. }
  199095. }
  199096. /* called by user to write a row of image data */
  199097. void PNGAPI
  199098. png_write_row(png_structp png_ptr, png_bytep row)
  199099. {
  199100. if (png_ptr == NULL)
  199101. return;
  199102. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199103. png_ptr->row_number, png_ptr->pass);
  199104. /* initialize transformations and other stuff if first time */
  199105. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199106. {
  199107. /* make sure we wrote the header info */
  199108. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199109. png_error(png_ptr,
  199110. "png_write_info was never called before png_write_row.");
  199111. /* check for transforms that have been set but were defined out */
  199112. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199113. if (png_ptr->transformations & PNG_INVERT_MONO)
  199114. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199115. #endif
  199116. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199117. if (png_ptr->transformations & PNG_FILLER)
  199118. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199119. #endif
  199120. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199121. if (png_ptr->transformations & PNG_PACKSWAP)
  199122. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199123. #endif
  199124. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199125. if (png_ptr->transformations & PNG_PACK)
  199126. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199127. #endif
  199128. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199129. if (png_ptr->transformations & PNG_SHIFT)
  199130. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199131. #endif
  199132. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199133. if (png_ptr->transformations & PNG_BGR)
  199134. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199135. #endif
  199136. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199137. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199138. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199139. #endif
  199140. png_write_start_row(png_ptr);
  199141. }
  199142. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199143. /* if interlaced and not interested in row, return */
  199144. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199145. {
  199146. switch (png_ptr->pass)
  199147. {
  199148. case 0:
  199149. if (png_ptr->row_number & 0x07)
  199150. {
  199151. png_write_finish_row(png_ptr);
  199152. return;
  199153. }
  199154. break;
  199155. case 1:
  199156. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199157. {
  199158. png_write_finish_row(png_ptr);
  199159. return;
  199160. }
  199161. break;
  199162. case 2:
  199163. if ((png_ptr->row_number & 0x07) != 4)
  199164. {
  199165. png_write_finish_row(png_ptr);
  199166. return;
  199167. }
  199168. break;
  199169. case 3:
  199170. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199171. {
  199172. png_write_finish_row(png_ptr);
  199173. return;
  199174. }
  199175. break;
  199176. case 4:
  199177. if ((png_ptr->row_number & 0x03) != 2)
  199178. {
  199179. png_write_finish_row(png_ptr);
  199180. return;
  199181. }
  199182. break;
  199183. case 5:
  199184. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199185. {
  199186. png_write_finish_row(png_ptr);
  199187. return;
  199188. }
  199189. break;
  199190. case 6:
  199191. if (!(png_ptr->row_number & 0x01))
  199192. {
  199193. png_write_finish_row(png_ptr);
  199194. return;
  199195. }
  199196. break;
  199197. }
  199198. }
  199199. #endif
  199200. /* set up row info for transformations */
  199201. png_ptr->row_info.color_type = png_ptr->color_type;
  199202. png_ptr->row_info.width = png_ptr->usr_width;
  199203. png_ptr->row_info.channels = png_ptr->usr_channels;
  199204. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199205. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199206. png_ptr->row_info.channels);
  199207. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199208. png_ptr->row_info.width);
  199209. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199210. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199211. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199212. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199213. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199214. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199215. /* Copy user's row into buffer, leaving room for filter byte. */
  199216. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199217. png_ptr->row_info.rowbytes);
  199218. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199219. /* handle interlacing */
  199220. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199221. (png_ptr->transformations & PNG_INTERLACE))
  199222. {
  199223. png_do_write_interlace(&(png_ptr->row_info),
  199224. png_ptr->row_buf + 1, png_ptr->pass);
  199225. /* this should always get caught above, but still ... */
  199226. if (!(png_ptr->row_info.width))
  199227. {
  199228. png_write_finish_row(png_ptr);
  199229. return;
  199230. }
  199231. }
  199232. #endif
  199233. /* handle other transformations */
  199234. if (png_ptr->transformations)
  199235. png_do_write_transformations(png_ptr);
  199236. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199237. /* Write filter_method 64 (intrapixel differencing) only if
  199238. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199239. * 2. Libpng did not write a PNG signature (this filter_method is only
  199240. * used in PNG datastreams that are embedded in MNG datastreams) and
  199241. * 3. The application called png_permit_mng_features with a mask that
  199242. * included PNG_FLAG_MNG_FILTER_64 and
  199243. * 4. The filter_method is 64 and
  199244. * 5. The color_type is RGB or RGBA
  199245. */
  199246. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199247. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199248. {
  199249. /* Intrapixel differencing */
  199250. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199251. }
  199252. #endif
  199253. /* Find a filter if necessary, filter the row and write it out. */
  199254. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199255. if (png_ptr->write_row_fn != NULL)
  199256. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199257. }
  199258. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199259. /* Set the automatic flush interval or 0 to turn flushing off */
  199260. void PNGAPI
  199261. png_set_flush(png_structp png_ptr, int nrows)
  199262. {
  199263. png_debug(1, "in png_set_flush\n");
  199264. if (png_ptr == NULL)
  199265. return;
  199266. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199267. }
  199268. /* flush the current output buffers now */
  199269. void PNGAPI
  199270. png_write_flush(png_structp png_ptr)
  199271. {
  199272. int wrote_IDAT;
  199273. png_debug(1, "in png_write_flush\n");
  199274. if (png_ptr == NULL)
  199275. return;
  199276. /* We have already written out all of the data */
  199277. if (png_ptr->row_number >= png_ptr->num_rows)
  199278. return;
  199279. do
  199280. {
  199281. int ret;
  199282. /* compress the data */
  199283. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199284. wrote_IDAT = 0;
  199285. /* check for compression errors */
  199286. if (ret != Z_OK)
  199287. {
  199288. if (png_ptr->zstream.msg != NULL)
  199289. png_error(png_ptr, png_ptr->zstream.msg);
  199290. else
  199291. png_error(png_ptr, "zlib error");
  199292. }
  199293. if (!(png_ptr->zstream.avail_out))
  199294. {
  199295. /* write the IDAT and reset the zlib output buffer */
  199296. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199297. png_ptr->zbuf_size);
  199298. png_ptr->zstream.next_out = png_ptr->zbuf;
  199299. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199300. wrote_IDAT = 1;
  199301. }
  199302. } while(wrote_IDAT == 1);
  199303. /* If there is any data left to be output, write it into a new IDAT */
  199304. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199305. {
  199306. /* write the IDAT and reset the zlib output buffer */
  199307. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199308. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199309. png_ptr->zstream.next_out = png_ptr->zbuf;
  199310. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199311. }
  199312. png_ptr->flush_rows = 0;
  199313. png_flush(png_ptr);
  199314. }
  199315. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199316. /* free all memory used by the write */
  199317. void PNGAPI
  199318. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199319. {
  199320. png_structp png_ptr = NULL;
  199321. png_infop info_ptr = NULL;
  199322. #ifdef PNG_USER_MEM_SUPPORTED
  199323. png_free_ptr free_fn = NULL;
  199324. png_voidp mem_ptr = NULL;
  199325. #endif
  199326. png_debug(1, "in png_destroy_write_struct\n");
  199327. if (png_ptr_ptr != NULL)
  199328. {
  199329. png_ptr = *png_ptr_ptr;
  199330. #ifdef PNG_USER_MEM_SUPPORTED
  199331. free_fn = png_ptr->free_fn;
  199332. mem_ptr = png_ptr->mem_ptr;
  199333. #endif
  199334. }
  199335. if (info_ptr_ptr != NULL)
  199336. info_ptr = *info_ptr_ptr;
  199337. if (info_ptr != NULL)
  199338. {
  199339. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199340. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199341. if (png_ptr->num_chunk_list)
  199342. {
  199343. png_free(png_ptr, png_ptr->chunk_list);
  199344. png_ptr->chunk_list=NULL;
  199345. png_ptr->num_chunk_list=0;
  199346. }
  199347. #endif
  199348. #ifdef PNG_USER_MEM_SUPPORTED
  199349. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199350. (png_voidp)mem_ptr);
  199351. #else
  199352. png_destroy_struct((png_voidp)info_ptr);
  199353. #endif
  199354. *info_ptr_ptr = NULL;
  199355. }
  199356. if (png_ptr != NULL)
  199357. {
  199358. png_write_destroy(png_ptr);
  199359. #ifdef PNG_USER_MEM_SUPPORTED
  199360. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199361. (png_voidp)mem_ptr);
  199362. #else
  199363. png_destroy_struct((png_voidp)png_ptr);
  199364. #endif
  199365. *png_ptr_ptr = NULL;
  199366. }
  199367. }
  199368. /* Free any memory used in png_ptr struct (old method) */
  199369. void /* PRIVATE */
  199370. png_write_destroy(png_structp png_ptr)
  199371. {
  199372. #ifdef PNG_SETJMP_SUPPORTED
  199373. jmp_buf tmp_jmp; /* save jump buffer */
  199374. #endif
  199375. png_error_ptr error_fn;
  199376. png_error_ptr warning_fn;
  199377. png_voidp error_ptr;
  199378. #ifdef PNG_USER_MEM_SUPPORTED
  199379. png_free_ptr free_fn;
  199380. #endif
  199381. png_debug(1, "in png_write_destroy\n");
  199382. /* free any memory zlib uses */
  199383. deflateEnd(&png_ptr->zstream);
  199384. /* free our memory. png_free checks NULL for us. */
  199385. png_free(png_ptr, png_ptr->zbuf);
  199386. png_free(png_ptr, png_ptr->row_buf);
  199387. png_free(png_ptr, png_ptr->prev_row);
  199388. png_free(png_ptr, png_ptr->sub_row);
  199389. png_free(png_ptr, png_ptr->up_row);
  199390. png_free(png_ptr, png_ptr->avg_row);
  199391. png_free(png_ptr, png_ptr->paeth_row);
  199392. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199393. png_free(png_ptr, png_ptr->time_buffer);
  199394. #endif
  199395. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199396. png_free(png_ptr, png_ptr->prev_filters);
  199397. png_free(png_ptr, png_ptr->filter_weights);
  199398. png_free(png_ptr, png_ptr->inv_filter_weights);
  199399. png_free(png_ptr, png_ptr->filter_costs);
  199400. png_free(png_ptr, png_ptr->inv_filter_costs);
  199401. #endif
  199402. #ifdef PNG_SETJMP_SUPPORTED
  199403. /* reset structure */
  199404. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199405. #endif
  199406. error_fn = png_ptr->error_fn;
  199407. warning_fn = png_ptr->warning_fn;
  199408. error_ptr = png_ptr->error_ptr;
  199409. #ifdef PNG_USER_MEM_SUPPORTED
  199410. free_fn = png_ptr->free_fn;
  199411. #endif
  199412. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199413. png_ptr->error_fn = error_fn;
  199414. png_ptr->warning_fn = warning_fn;
  199415. png_ptr->error_ptr = error_ptr;
  199416. #ifdef PNG_USER_MEM_SUPPORTED
  199417. png_ptr->free_fn = free_fn;
  199418. #endif
  199419. #ifdef PNG_SETJMP_SUPPORTED
  199420. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199421. #endif
  199422. }
  199423. /* Allow the application to select one or more row filters to use. */
  199424. void PNGAPI
  199425. png_set_filter(png_structp png_ptr, int method, int filters)
  199426. {
  199427. png_debug(1, "in png_set_filter\n");
  199428. if (png_ptr == NULL)
  199429. return;
  199430. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199431. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199432. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199433. method = PNG_FILTER_TYPE_BASE;
  199434. #endif
  199435. if (method == PNG_FILTER_TYPE_BASE)
  199436. {
  199437. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199438. {
  199439. #ifndef PNG_NO_WRITE_FILTER
  199440. case 5:
  199441. case 6:
  199442. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199443. #endif /* PNG_NO_WRITE_FILTER */
  199444. case PNG_FILTER_VALUE_NONE:
  199445. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199446. #ifndef PNG_NO_WRITE_FILTER
  199447. case PNG_FILTER_VALUE_SUB:
  199448. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199449. case PNG_FILTER_VALUE_UP:
  199450. png_ptr->do_filter=PNG_FILTER_UP; break;
  199451. case PNG_FILTER_VALUE_AVG:
  199452. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199453. case PNG_FILTER_VALUE_PAETH:
  199454. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199455. default: png_ptr->do_filter = (png_byte)filters; break;
  199456. #else
  199457. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199458. #endif /* PNG_NO_WRITE_FILTER */
  199459. }
  199460. /* If we have allocated the row_buf, this means we have already started
  199461. * with the image and we should have allocated all of the filter buffers
  199462. * that have been selected. If prev_row isn't already allocated, then
  199463. * it is too late to start using the filters that need it, since we
  199464. * will be missing the data in the previous row. If an application
  199465. * wants to start and stop using particular filters during compression,
  199466. * it should start out with all of the filters, and then add and
  199467. * remove them after the start of compression.
  199468. */
  199469. if (png_ptr->row_buf != NULL)
  199470. {
  199471. #ifndef PNG_NO_WRITE_FILTER
  199472. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199473. {
  199474. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199475. (png_ptr->rowbytes + 1));
  199476. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199477. }
  199478. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199479. {
  199480. if (png_ptr->prev_row == NULL)
  199481. {
  199482. png_warning(png_ptr, "Can't add Up filter after starting");
  199483. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199484. }
  199485. else
  199486. {
  199487. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199488. (png_ptr->rowbytes + 1));
  199489. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199490. }
  199491. }
  199492. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  199493. {
  199494. if (png_ptr->prev_row == NULL)
  199495. {
  199496. png_warning(png_ptr, "Can't add Average filter after starting");
  199497. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  199498. }
  199499. else
  199500. {
  199501. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199502. (png_ptr->rowbytes + 1));
  199503. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199504. }
  199505. }
  199506. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  199507. png_ptr->paeth_row == NULL)
  199508. {
  199509. if (png_ptr->prev_row == NULL)
  199510. {
  199511. png_warning(png_ptr, "Can't add Paeth filter after starting");
  199512. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  199513. }
  199514. else
  199515. {
  199516. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199517. (png_ptr->rowbytes + 1));
  199518. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199519. }
  199520. }
  199521. if (png_ptr->do_filter == PNG_NO_FILTERS)
  199522. #endif /* PNG_NO_WRITE_FILTER */
  199523. png_ptr->do_filter = PNG_FILTER_NONE;
  199524. }
  199525. }
  199526. else
  199527. png_error(png_ptr, "Unknown custom filter method");
  199528. }
  199529. /* This allows us to influence the way in which libpng chooses the "best"
  199530. * filter for the current scanline. While the "minimum-sum-of-absolute-
  199531. * differences metric is relatively fast and effective, there is some
  199532. * question as to whether it can be improved upon by trying to keep the
  199533. * filtered data going to zlib more consistent, hopefully resulting in
  199534. * better compression.
  199535. */
  199536. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  199537. void PNGAPI
  199538. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  199539. int num_weights, png_doublep filter_weights,
  199540. png_doublep filter_costs)
  199541. {
  199542. int i;
  199543. png_debug(1, "in png_set_filter_heuristics\n");
  199544. if (png_ptr == NULL)
  199545. return;
  199546. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  199547. {
  199548. png_warning(png_ptr, "Unknown filter heuristic method");
  199549. return;
  199550. }
  199551. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  199552. {
  199553. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  199554. }
  199555. if (num_weights < 0 || filter_weights == NULL ||
  199556. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  199557. {
  199558. num_weights = 0;
  199559. }
  199560. png_ptr->num_prev_filters = (png_byte)num_weights;
  199561. png_ptr->heuristic_method = (png_byte)heuristic_method;
  199562. if (num_weights > 0)
  199563. {
  199564. if (png_ptr->prev_filters == NULL)
  199565. {
  199566. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  199567. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  199568. /* To make sure that the weighting starts out fairly */
  199569. for (i = 0; i < num_weights; i++)
  199570. {
  199571. png_ptr->prev_filters[i] = 255;
  199572. }
  199573. }
  199574. if (png_ptr->filter_weights == NULL)
  199575. {
  199576. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199577. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199578. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199579. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199580. for (i = 0; i < num_weights; i++)
  199581. {
  199582. png_ptr->inv_filter_weights[i] =
  199583. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199584. }
  199585. }
  199586. for (i = 0; i < num_weights; i++)
  199587. {
  199588. if (filter_weights[i] < 0.0)
  199589. {
  199590. png_ptr->inv_filter_weights[i] =
  199591. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199592. }
  199593. else
  199594. {
  199595. png_ptr->inv_filter_weights[i] =
  199596. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  199597. png_ptr->filter_weights[i] =
  199598. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  199599. }
  199600. }
  199601. }
  199602. /* If, in the future, there are other filter methods, this would
  199603. * need to be based on png_ptr->filter.
  199604. */
  199605. if (png_ptr->filter_costs == NULL)
  199606. {
  199607. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199608. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199609. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199610. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199611. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199612. {
  199613. png_ptr->inv_filter_costs[i] =
  199614. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199615. }
  199616. }
  199617. /* Here is where we set the relative costs of the different filters. We
  199618. * should take the desired compression level into account when setting
  199619. * the costs, so that Paeth, for instance, has a high relative cost at low
  199620. * compression levels, while it has a lower relative cost at higher
  199621. * compression settings. The filter types are in order of increasing
  199622. * relative cost, so it would be possible to do this with an algorithm.
  199623. */
  199624. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199625. {
  199626. if (filter_costs == NULL || filter_costs[i] < 0.0)
  199627. {
  199628. png_ptr->inv_filter_costs[i] =
  199629. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199630. }
  199631. else if (filter_costs[i] >= 1.0)
  199632. {
  199633. png_ptr->inv_filter_costs[i] =
  199634. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  199635. png_ptr->filter_costs[i] =
  199636. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  199637. }
  199638. }
  199639. }
  199640. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  199641. void PNGAPI
  199642. png_set_compression_level(png_structp png_ptr, int level)
  199643. {
  199644. png_debug(1, "in png_set_compression_level\n");
  199645. if (png_ptr == NULL)
  199646. return;
  199647. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  199648. png_ptr->zlib_level = level;
  199649. }
  199650. void PNGAPI
  199651. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  199652. {
  199653. png_debug(1, "in png_set_compression_mem_level\n");
  199654. if (png_ptr == NULL)
  199655. return;
  199656. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  199657. png_ptr->zlib_mem_level = mem_level;
  199658. }
  199659. void PNGAPI
  199660. png_set_compression_strategy(png_structp png_ptr, int strategy)
  199661. {
  199662. png_debug(1, "in png_set_compression_strategy\n");
  199663. if (png_ptr == NULL)
  199664. return;
  199665. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  199666. png_ptr->zlib_strategy = strategy;
  199667. }
  199668. void PNGAPI
  199669. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  199670. {
  199671. if (png_ptr == NULL)
  199672. return;
  199673. if (window_bits > 15)
  199674. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  199675. else if (window_bits < 8)
  199676. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  199677. #ifndef WBITS_8_OK
  199678. /* avoid libpng bug with 256-byte windows */
  199679. if (window_bits == 8)
  199680. {
  199681. png_warning(png_ptr, "Compression window is being reset to 512");
  199682. window_bits=9;
  199683. }
  199684. #endif
  199685. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  199686. png_ptr->zlib_window_bits = window_bits;
  199687. }
  199688. void PNGAPI
  199689. png_set_compression_method(png_structp png_ptr, int method)
  199690. {
  199691. png_debug(1, "in png_set_compression_method\n");
  199692. if (png_ptr == NULL)
  199693. return;
  199694. if (method != 8)
  199695. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  199696. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  199697. png_ptr->zlib_method = method;
  199698. }
  199699. void PNGAPI
  199700. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  199701. {
  199702. if (png_ptr == NULL)
  199703. return;
  199704. png_ptr->write_row_fn = write_row_fn;
  199705. }
  199706. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199707. void PNGAPI
  199708. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  199709. write_user_transform_fn)
  199710. {
  199711. png_debug(1, "in png_set_write_user_transform_fn\n");
  199712. if (png_ptr == NULL)
  199713. return;
  199714. png_ptr->transformations |= PNG_USER_TRANSFORM;
  199715. png_ptr->write_user_transform_fn = write_user_transform_fn;
  199716. }
  199717. #endif
  199718. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  199719. void PNGAPI
  199720. png_write_png(png_structp png_ptr, png_infop info_ptr,
  199721. int transforms, voidp params)
  199722. {
  199723. if (png_ptr == NULL || info_ptr == NULL)
  199724. return;
  199725. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199726. /* invert the alpha channel from opacity to transparency */
  199727. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  199728. png_set_invert_alpha(png_ptr);
  199729. #endif
  199730. /* Write the file header information. */
  199731. png_write_info(png_ptr, info_ptr);
  199732. /* ------ these transformations don't touch the info structure ------- */
  199733. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199734. /* invert monochrome pixels */
  199735. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  199736. png_set_invert_mono(png_ptr);
  199737. #endif
  199738. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199739. /* Shift the pixels up to a legal bit depth and fill in
  199740. * as appropriate to correctly scale the image.
  199741. */
  199742. if ((transforms & PNG_TRANSFORM_SHIFT)
  199743. && (info_ptr->valid & PNG_INFO_sBIT))
  199744. png_set_shift(png_ptr, &info_ptr->sig_bit);
  199745. #endif
  199746. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199747. /* pack pixels into bytes */
  199748. if (transforms & PNG_TRANSFORM_PACKING)
  199749. png_set_packing(png_ptr);
  199750. #endif
  199751. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199752. /* swap location of alpha bytes from ARGB to RGBA */
  199753. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  199754. png_set_swap_alpha(png_ptr);
  199755. #endif
  199756. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199757. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  199758. * RGB (4 channels -> 3 channels). The second parameter is not used.
  199759. */
  199760. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  199761. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  199762. #endif
  199763. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199764. /* flip BGR pixels to RGB */
  199765. if (transforms & PNG_TRANSFORM_BGR)
  199766. png_set_bgr(png_ptr);
  199767. #endif
  199768. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199769. /* swap bytes of 16-bit files to most significant byte first */
  199770. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  199771. png_set_swap(png_ptr);
  199772. #endif
  199773. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199774. /* swap bits of 1, 2, 4 bit packed pixel formats */
  199775. if (transforms & PNG_TRANSFORM_PACKSWAP)
  199776. png_set_packswap(png_ptr);
  199777. #endif
  199778. /* ----------------------- end of transformations ------------------- */
  199779. /* write the bits */
  199780. if (info_ptr->valid & PNG_INFO_IDAT)
  199781. png_write_image(png_ptr, info_ptr->row_pointers);
  199782. /* It is REQUIRED to call this to finish writing the rest of the file */
  199783. png_write_end(png_ptr, info_ptr);
  199784. transforms = transforms; /* quiet compiler warnings */
  199785. params = params;
  199786. }
  199787. #endif
  199788. #endif /* PNG_WRITE_SUPPORTED */
  199789. /*** End of inlined file: pngwrite.c ***/
  199790. /*** Start of inlined file: pngwtran.c ***/
  199791. /* pngwtran.c - transforms the data in a row for PNG writers
  199792. *
  199793. * Last changed in libpng 1.2.9 April 14, 2006
  199794. * For conditions of distribution and use, see copyright notice in png.h
  199795. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  199796. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  199797. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  199798. */
  199799. #define PNG_INTERNAL
  199800. #ifdef PNG_WRITE_SUPPORTED
  199801. /* Transform the data according to the user's wishes. The order of
  199802. * transformations is significant.
  199803. */
  199804. void /* PRIVATE */
  199805. png_do_write_transformations(png_structp png_ptr)
  199806. {
  199807. png_debug(1, "in png_do_write_transformations\n");
  199808. if (png_ptr == NULL)
  199809. return;
  199810. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199811. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  199812. if(png_ptr->write_user_transform_fn != NULL)
  199813. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  199814. (png_ptr, /* png_ptr */
  199815. &(png_ptr->row_info), /* row_info: */
  199816. /* png_uint_32 width; width of row */
  199817. /* png_uint_32 rowbytes; number of bytes in row */
  199818. /* png_byte color_type; color type of pixels */
  199819. /* png_byte bit_depth; bit depth of samples */
  199820. /* png_byte channels; number of channels (1-4) */
  199821. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  199822. png_ptr->row_buf + 1); /* start of pixel data for row */
  199823. #endif
  199824. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199825. if (png_ptr->transformations & PNG_FILLER)
  199826. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199827. png_ptr->flags);
  199828. #endif
  199829. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199830. if (png_ptr->transformations & PNG_PACKSWAP)
  199831. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199832. #endif
  199833. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199834. if (png_ptr->transformations & PNG_PACK)
  199835. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199836. (png_uint_32)png_ptr->bit_depth);
  199837. #endif
  199838. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199839. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199840. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199841. #endif
  199842. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199843. if (png_ptr->transformations & PNG_SHIFT)
  199844. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199845. &(png_ptr->shift));
  199846. #endif
  199847. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199848. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  199849. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199850. #endif
  199851. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199852. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  199853. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199854. #endif
  199855. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199856. if (png_ptr->transformations & PNG_BGR)
  199857. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199858. #endif
  199859. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199860. if (png_ptr->transformations & PNG_INVERT_MONO)
  199861. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199862. #endif
  199863. }
  199864. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199865. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  199866. * row_info bit depth should be 8 (one pixel per byte). The channels
  199867. * should be 1 (this only happens on grayscale and paletted images).
  199868. */
  199869. void /* PRIVATE */
  199870. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  199871. {
  199872. png_debug(1, "in png_do_pack\n");
  199873. if (row_info->bit_depth == 8 &&
  199874. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199875. row != NULL && row_info != NULL &&
  199876. #endif
  199877. row_info->channels == 1)
  199878. {
  199879. switch ((int)bit_depth)
  199880. {
  199881. case 1:
  199882. {
  199883. png_bytep sp, dp;
  199884. int mask, v;
  199885. png_uint_32 i;
  199886. png_uint_32 row_width = row_info->width;
  199887. sp = row;
  199888. dp = row;
  199889. mask = 0x80;
  199890. v = 0;
  199891. for (i = 0; i < row_width; i++)
  199892. {
  199893. if (*sp != 0)
  199894. v |= mask;
  199895. sp++;
  199896. if (mask > 1)
  199897. mask >>= 1;
  199898. else
  199899. {
  199900. mask = 0x80;
  199901. *dp = (png_byte)v;
  199902. dp++;
  199903. v = 0;
  199904. }
  199905. }
  199906. if (mask != 0x80)
  199907. *dp = (png_byte)v;
  199908. break;
  199909. }
  199910. case 2:
  199911. {
  199912. png_bytep sp, dp;
  199913. int shift, v;
  199914. png_uint_32 i;
  199915. png_uint_32 row_width = row_info->width;
  199916. sp = row;
  199917. dp = row;
  199918. shift = 6;
  199919. v = 0;
  199920. for (i = 0; i < row_width; i++)
  199921. {
  199922. png_byte value;
  199923. value = (png_byte)(*sp & 0x03);
  199924. v |= (value << shift);
  199925. if (shift == 0)
  199926. {
  199927. shift = 6;
  199928. *dp = (png_byte)v;
  199929. dp++;
  199930. v = 0;
  199931. }
  199932. else
  199933. shift -= 2;
  199934. sp++;
  199935. }
  199936. if (shift != 6)
  199937. *dp = (png_byte)v;
  199938. break;
  199939. }
  199940. case 4:
  199941. {
  199942. png_bytep sp, dp;
  199943. int shift, v;
  199944. png_uint_32 i;
  199945. png_uint_32 row_width = row_info->width;
  199946. sp = row;
  199947. dp = row;
  199948. shift = 4;
  199949. v = 0;
  199950. for (i = 0; i < row_width; i++)
  199951. {
  199952. png_byte value;
  199953. value = (png_byte)(*sp & 0x0f);
  199954. v |= (value << shift);
  199955. if (shift == 0)
  199956. {
  199957. shift = 4;
  199958. *dp = (png_byte)v;
  199959. dp++;
  199960. v = 0;
  199961. }
  199962. else
  199963. shift -= 4;
  199964. sp++;
  199965. }
  199966. if (shift != 4)
  199967. *dp = (png_byte)v;
  199968. break;
  199969. }
  199970. }
  199971. row_info->bit_depth = (png_byte)bit_depth;
  199972. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  199973. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  199974. row_info->width);
  199975. }
  199976. }
  199977. #endif
  199978. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199979. /* Shift pixel values to take advantage of whole range. Pass the
  199980. * true number of bits in bit_depth. The row should be packed
  199981. * according to row_info->bit_depth. Thus, if you had a row of
  199982. * bit depth 4, but the pixels only had values from 0 to 7, you
  199983. * would pass 3 as bit_depth, and this routine would translate the
  199984. * data to 0 to 15.
  199985. */
  199986. void /* PRIVATE */
  199987. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  199988. {
  199989. png_debug(1, "in png_do_shift\n");
  199990. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199991. if (row != NULL && row_info != NULL &&
  199992. #else
  199993. if (
  199994. #endif
  199995. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  199996. {
  199997. int shift_start[4], shift_dec[4];
  199998. int channels = 0;
  199999. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  200000. {
  200001. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  200002. shift_dec[channels] = bit_depth->red;
  200003. channels++;
  200004. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  200005. shift_dec[channels] = bit_depth->green;
  200006. channels++;
  200007. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  200008. shift_dec[channels] = bit_depth->blue;
  200009. channels++;
  200010. }
  200011. else
  200012. {
  200013. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  200014. shift_dec[channels] = bit_depth->gray;
  200015. channels++;
  200016. }
  200017. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  200018. {
  200019. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200020. shift_dec[channels] = bit_depth->alpha;
  200021. channels++;
  200022. }
  200023. /* with low row depths, could only be grayscale, so one channel */
  200024. if (row_info->bit_depth < 8)
  200025. {
  200026. png_bytep bp = row;
  200027. png_uint_32 i;
  200028. png_byte mask;
  200029. png_uint_32 row_bytes = row_info->rowbytes;
  200030. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200031. mask = 0x55;
  200032. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200033. mask = 0x11;
  200034. else
  200035. mask = 0xff;
  200036. for (i = 0; i < row_bytes; i++, bp++)
  200037. {
  200038. png_uint_16 v;
  200039. int j;
  200040. v = *bp;
  200041. *bp = 0;
  200042. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200043. {
  200044. if (j > 0)
  200045. *bp |= (png_byte)((v << j) & 0xff);
  200046. else
  200047. *bp |= (png_byte)((v >> (-j)) & mask);
  200048. }
  200049. }
  200050. }
  200051. else if (row_info->bit_depth == 8)
  200052. {
  200053. png_bytep bp = row;
  200054. png_uint_32 i;
  200055. png_uint_32 istop = channels * row_info->width;
  200056. for (i = 0; i < istop; i++, bp++)
  200057. {
  200058. png_uint_16 v;
  200059. int j;
  200060. int c = (int)(i%channels);
  200061. v = *bp;
  200062. *bp = 0;
  200063. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200064. {
  200065. if (j > 0)
  200066. *bp |= (png_byte)((v << j) & 0xff);
  200067. else
  200068. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200069. }
  200070. }
  200071. }
  200072. else
  200073. {
  200074. png_bytep bp;
  200075. png_uint_32 i;
  200076. png_uint_32 istop = channels * row_info->width;
  200077. for (bp = row, i = 0; i < istop; i++)
  200078. {
  200079. int c = (int)(i%channels);
  200080. png_uint_16 value, v;
  200081. int j;
  200082. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200083. value = 0;
  200084. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200085. {
  200086. if (j > 0)
  200087. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200088. else
  200089. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200090. }
  200091. *bp++ = (png_byte)(value >> 8);
  200092. *bp++ = (png_byte)(value & 0xff);
  200093. }
  200094. }
  200095. }
  200096. }
  200097. #endif
  200098. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200099. void /* PRIVATE */
  200100. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200101. {
  200102. png_debug(1, "in png_do_write_swap_alpha\n");
  200103. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200104. if (row != NULL && row_info != NULL)
  200105. #endif
  200106. {
  200107. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200108. {
  200109. /* This converts from ARGB to RGBA */
  200110. if (row_info->bit_depth == 8)
  200111. {
  200112. png_bytep sp, dp;
  200113. png_uint_32 i;
  200114. png_uint_32 row_width = row_info->width;
  200115. for (i = 0, sp = dp = row; i < row_width; i++)
  200116. {
  200117. png_byte save = *(sp++);
  200118. *(dp++) = *(sp++);
  200119. *(dp++) = *(sp++);
  200120. *(dp++) = *(sp++);
  200121. *(dp++) = save;
  200122. }
  200123. }
  200124. /* This converts from AARRGGBB to RRGGBBAA */
  200125. else
  200126. {
  200127. png_bytep sp, dp;
  200128. png_uint_32 i;
  200129. png_uint_32 row_width = row_info->width;
  200130. for (i = 0, sp = dp = row; i < row_width; i++)
  200131. {
  200132. png_byte save[2];
  200133. save[0] = *(sp++);
  200134. save[1] = *(sp++);
  200135. *(dp++) = *(sp++);
  200136. *(dp++) = *(sp++);
  200137. *(dp++) = *(sp++);
  200138. *(dp++) = *(sp++);
  200139. *(dp++) = *(sp++);
  200140. *(dp++) = *(sp++);
  200141. *(dp++) = save[0];
  200142. *(dp++) = save[1];
  200143. }
  200144. }
  200145. }
  200146. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200147. {
  200148. /* This converts from AG to GA */
  200149. if (row_info->bit_depth == 8)
  200150. {
  200151. png_bytep sp, dp;
  200152. png_uint_32 i;
  200153. png_uint_32 row_width = row_info->width;
  200154. for (i = 0, sp = dp = row; i < row_width; i++)
  200155. {
  200156. png_byte save = *(sp++);
  200157. *(dp++) = *(sp++);
  200158. *(dp++) = save;
  200159. }
  200160. }
  200161. /* This converts from AAGG to GGAA */
  200162. else
  200163. {
  200164. png_bytep sp, dp;
  200165. png_uint_32 i;
  200166. png_uint_32 row_width = row_info->width;
  200167. for (i = 0, sp = dp = row; i < row_width; i++)
  200168. {
  200169. png_byte save[2];
  200170. save[0] = *(sp++);
  200171. save[1] = *(sp++);
  200172. *(dp++) = *(sp++);
  200173. *(dp++) = *(sp++);
  200174. *(dp++) = save[0];
  200175. *(dp++) = save[1];
  200176. }
  200177. }
  200178. }
  200179. }
  200180. }
  200181. #endif
  200182. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200183. void /* PRIVATE */
  200184. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200185. {
  200186. png_debug(1, "in png_do_write_invert_alpha\n");
  200187. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200188. if (row != NULL && row_info != NULL)
  200189. #endif
  200190. {
  200191. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200192. {
  200193. /* This inverts the alpha channel in RGBA */
  200194. if (row_info->bit_depth == 8)
  200195. {
  200196. png_bytep sp, dp;
  200197. png_uint_32 i;
  200198. png_uint_32 row_width = row_info->width;
  200199. for (i = 0, sp = dp = row; i < row_width; i++)
  200200. {
  200201. /* does nothing
  200202. *(dp++) = *(sp++);
  200203. *(dp++) = *(sp++);
  200204. *(dp++) = *(sp++);
  200205. */
  200206. sp+=3; dp = sp;
  200207. *(dp++) = (png_byte)(255 - *(sp++));
  200208. }
  200209. }
  200210. /* This inverts the alpha channel in RRGGBBAA */
  200211. else
  200212. {
  200213. png_bytep sp, dp;
  200214. png_uint_32 i;
  200215. png_uint_32 row_width = row_info->width;
  200216. for (i = 0, sp = dp = row; i < row_width; i++)
  200217. {
  200218. /* does nothing
  200219. *(dp++) = *(sp++);
  200220. *(dp++) = *(sp++);
  200221. *(dp++) = *(sp++);
  200222. *(dp++) = *(sp++);
  200223. *(dp++) = *(sp++);
  200224. *(dp++) = *(sp++);
  200225. */
  200226. sp+=6; dp = sp;
  200227. *(dp++) = (png_byte)(255 - *(sp++));
  200228. *(dp++) = (png_byte)(255 - *(sp++));
  200229. }
  200230. }
  200231. }
  200232. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200233. {
  200234. /* This inverts the alpha channel in GA */
  200235. if (row_info->bit_depth == 8)
  200236. {
  200237. png_bytep sp, dp;
  200238. png_uint_32 i;
  200239. png_uint_32 row_width = row_info->width;
  200240. for (i = 0, sp = dp = row; i < row_width; i++)
  200241. {
  200242. *(dp++) = *(sp++);
  200243. *(dp++) = (png_byte)(255 - *(sp++));
  200244. }
  200245. }
  200246. /* This inverts the alpha channel in GGAA */
  200247. else
  200248. {
  200249. png_bytep sp, dp;
  200250. png_uint_32 i;
  200251. png_uint_32 row_width = row_info->width;
  200252. for (i = 0, sp = dp = row; i < row_width; i++)
  200253. {
  200254. /* does nothing
  200255. *(dp++) = *(sp++);
  200256. *(dp++) = *(sp++);
  200257. */
  200258. sp+=2; dp = sp;
  200259. *(dp++) = (png_byte)(255 - *(sp++));
  200260. *(dp++) = (png_byte)(255 - *(sp++));
  200261. }
  200262. }
  200263. }
  200264. }
  200265. }
  200266. #endif
  200267. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200268. /* undoes intrapixel differencing */
  200269. void /* PRIVATE */
  200270. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200271. {
  200272. png_debug(1, "in png_do_write_intrapixel\n");
  200273. if (
  200274. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200275. row != NULL && row_info != NULL &&
  200276. #endif
  200277. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200278. {
  200279. int bytes_per_pixel;
  200280. png_uint_32 row_width = row_info->width;
  200281. if (row_info->bit_depth == 8)
  200282. {
  200283. png_bytep rp;
  200284. png_uint_32 i;
  200285. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200286. bytes_per_pixel = 3;
  200287. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200288. bytes_per_pixel = 4;
  200289. else
  200290. return;
  200291. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200292. {
  200293. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200294. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200295. }
  200296. }
  200297. else if (row_info->bit_depth == 16)
  200298. {
  200299. png_bytep rp;
  200300. png_uint_32 i;
  200301. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200302. bytes_per_pixel = 6;
  200303. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200304. bytes_per_pixel = 8;
  200305. else
  200306. return;
  200307. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200308. {
  200309. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200310. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200311. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200312. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200313. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200314. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200315. *(rp+1) = (png_byte)(red & 0xff);
  200316. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200317. *(rp+5) = (png_byte)(blue & 0xff);
  200318. }
  200319. }
  200320. }
  200321. }
  200322. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200323. #endif /* PNG_WRITE_SUPPORTED */
  200324. /*** End of inlined file: pngwtran.c ***/
  200325. /*** Start of inlined file: pngwutil.c ***/
  200326. /* pngwutil.c - utilities to write a PNG file
  200327. *
  200328. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200329. * For conditions of distribution and use, see copyright notice in png.h
  200330. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200331. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200332. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200333. */
  200334. #define PNG_INTERNAL
  200335. #ifdef PNG_WRITE_SUPPORTED
  200336. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200337. * with unsigned numbers for convenience, although one supported
  200338. * ancillary chunk uses signed (two's complement) numbers.
  200339. */
  200340. void PNGAPI
  200341. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200342. {
  200343. buf[0] = (png_byte)((i >> 24) & 0xff);
  200344. buf[1] = (png_byte)((i >> 16) & 0xff);
  200345. buf[2] = (png_byte)((i >> 8) & 0xff);
  200346. buf[3] = (png_byte)(i & 0xff);
  200347. }
  200348. /* The png_save_int_32 function assumes integers are stored in two's
  200349. * complement format. If this isn't the case, then this routine needs to
  200350. * be modified to write data in two's complement format.
  200351. */
  200352. void PNGAPI
  200353. png_save_int_32(png_bytep buf, png_int_32 i)
  200354. {
  200355. buf[0] = (png_byte)((i >> 24) & 0xff);
  200356. buf[1] = (png_byte)((i >> 16) & 0xff);
  200357. buf[2] = (png_byte)((i >> 8) & 0xff);
  200358. buf[3] = (png_byte)(i & 0xff);
  200359. }
  200360. /* Place a 16-bit number into a buffer in PNG byte order.
  200361. * The parameter is declared unsigned int, not png_uint_16,
  200362. * just to avoid potential problems on pre-ANSI C compilers.
  200363. */
  200364. void PNGAPI
  200365. png_save_uint_16(png_bytep buf, unsigned int i)
  200366. {
  200367. buf[0] = (png_byte)((i >> 8) & 0xff);
  200368. buf[1] = (png_byte)(i & 0xff);
  200369. }
  200370. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200371. * representing the chunk name. The array must be at least 4 bytes in
  200372. * length, and does not need to be null terminated. To be safe, pass the
  200373. * pre-defined chunk names here, and if you need a new one, define it
  200374. * where the others are defined. The length is the length of the data.
  200375. * All the data must be present. If that is not possible, use the
  200376. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200377. * functions instead.
  200378. */
  200379. void PNGAPI
  200380. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200381. png_bytep data, png_size_t length)
  200382. {
  200383. if(png_ptr == NULL) return;
  200384. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200385. png_write_chunk_data(png_ptr, data, length);
  200386. png_write_chunk_end(png_ptr);
  200387. }
  200388. /* Write the start of a PNG chunk. The type is the chunk type.
  200389. * The total_length is the sum of the lengths of all the data you will be
  200390. * passing in png_write_chunk_data().
  200391. */
  200392. void PNGAPI
  200393. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200394. png_uint_32 length)
  200395. {
  200396. png_byte buf[4];
  200397. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200398. if(png_ptr == NULL) return;
  200399. /* write the length */
  200400. png_save_uint_32(buf, length);
  200401. png_write_data(png_ptr, buf, (png_size_t)4);
  200402. /* write the chunk name */
  200403. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200404. /* reset the crc and run it over the chunk name */
  200405. png_reset_crc(png_ptr);
  200406. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200407. }
  200408. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200409. * Note that multiple calls to this function are allowed, and that the
  200410. * sum of the lengths from these calls *must* add up to the total_length
  200411. * given to png_write_chunk_start().
  200412. */
  200413. void PNGAPI
  200414. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200415. {
  200416. /* write the data, and run the CRC over it */
  200417. if(png_ptr == NULL) return;
  200418. if (data != NULL && length > 0)
  200419. {
  200420. png_calculate_crc(png_ptr, data, length);
  200421. png_write_data(png_ptr, data, length);
  200422. }
  200423. }
  200424. /* Finish a chunk started with png_write_chunk_start(). */
  200425. void PNGAPI
  200426. png_write_chunk_end(png_structp png_ptr)
  200427. {
  200428. png_byte buf[4];
  200429. if(png_ptr == NULL) return;
  200430. /* write the crc */
  200431. png_save_uint_32(buf, png_ptr->crc);
  200432. png_write_data(png_ptr, buf, (png_size_t)4);
  200433. }
  200434. /* Simple function to write the signature. If we have already written
  200435. * the magic bytes of the signature, or more likely, the PNG stream is
  200436. * being embedded into another stream and doesn't need its own signature,
  200437. * we should call png_set_sig_bytes() to tell libpng how many of the
  200438. * bytes have already been written.
  200439. */
  200440. void /* PRIVATE */
  200441. png_write_sig(png_structp png_ptr)
  200442. {
  200443. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200444. /* write the rest of the 8 byte signature */
  200445. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200446. (png_size_t)8 - png_ptr->sig_bytes);
  200447. if(png_ptr->sig_bytes < 3)
  200448. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200449. }
  200450. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200451. /*
  200452. * This pair of functions encapsulates the operation of (a) compressing a
  200453. * text string, and (b) issuing it later as a series of chunk data writes.
  200454. * The compression_state structure is shared context for these functions
  200455. * set up by the caller in order to make the whole mess thread-safe.
  200456. */
  200457. typedef struct
  200458. {
  200459. char *input; /* the uncompressed input data */
  200460. int input_len; /* its length */
  200461. int num_output_ptr; /* number of output pointers used */
  200462. int max_output_ptr; /* size of output_ptr */
  200463. png_charpp output_ptr; /* array of pointers to output */
  200464. } compression_state;
  200465. /* compress given text into storage in the png_ptr structure */
  200466. static int /* PRIVATE */
  200467. png_text_compress(png_structp png_ptr,
  200468. png_charp text, png_size_t text_len, int compression,
  200469. compression_state *comp)
  200470. {
  200471. int ret;
  200472. comp->num_output_ptr = 0;
  200473. comp->max_output_ptr = 0;
  200474. comp->output_ptr = NULL;
  200475. comp->input = NULL;
  200476. comp->input_len = 0;
  200477. /* we may just want to pass the text right through */
  200478. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200479. {
  200480. comp->input = text;
  200481. comp->input_len = text_len;
  200482. return((int)text_len);
  200483. }
  200484. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200485. {
  200486. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200487. char msg[50];
  200488. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200489. png_warning(png_ptr, msg);
  200490. #else
  200491. png_warning(png_ptr, "Unknown compression type");
  200492. #endif
  200493. }
  200494. /* We can't write the chunk until we find out how much data we have,
  200495. * which means we need to run the compressor first and save the
  200496. * output. This shouldn't be a problem, as the vast majority of
  200497. * comments should be reasonable, but we will set up an array of
  200498. * malloc'd pointers to be sure.
  200499. *
  200500. * If we knew the application was well behaved, we could simplify this
  200501. * greatly by assuming we can always malloc an output buffer large
  200502. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  200503. * and malloc this directly. The only time this would be a bad idea is
  200504. * if we can't malloc more than 64K and we have 64K of random input
  200505. * data, or if the input string is incredibly large (although this
  200506. * wouldn't cause a failure, just a slowdown due to swapping).
  200507. */
  200508. /* set up the compression buffers */
  200509. png_ptr->zstream.avail_in = (uInt)text_len;
  200510. png_ptr->zstream.next_in = (Bytef *)text;
  200511. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200512. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  200513. /* this is the same compression loop as in png_write_row() */
  200514. do
  200515. {
  200516. /* compress the data */
  200517. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200518. if (ret != Z_OK)
  200519. {
  200520. /* error */
  200521. if (png_ptr->zstream.msg != NULL)
  200522. png_error(png_ptr, png_ptr->zstream.msg);
  200523. else
  200524. png_error(png_ptr, "zlib error");
  200525. }
  200526. /* check to see if we need more room */
  200527. if (!(png_ptr->zstream.avail_out))
  200528. {
  200529. /* make sure the output array has room */
  200530. if (comp->num_output_ptr >= comp->max_output_ptr)
  200531. {
  200532. int old_max;
  200533. old_max = comp->max_output_ptr;
  200534. comp->max_output_ptr = comp->num_output_ptr + 4;
  200535. if (comp->output_ptr != NULL)
  200536. {
  200537. png_charpp old_ptr;
  200538. old_ptr = comp->output_ptr;
  200539. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200540. (png_uint_32)(comp->max_output_ptr *
  200541. png_sizeof (png_charpp)));
  200542. png_memcpy(comp->output_ptr, old_ptr, old_max
  200543. * png_sizeof (png_charp));
  200544. png_free(png_ptr, old_ptr);
  200545. }
  200546. else
  200547. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200548. (png_uint_32)(comp->max_output_ptr *
  200549. png_sizeof (png_charp)));
  200550. }
  200551. /* save the data */
  200552. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  200553. (png_uint_32)png_ptr->zbuf_size);
  200554. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200555. png_ptr->zbuf_size);
  200556. comp->num_output_ptr++;
  200557. /* and reset the buffer */
  200558. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200559. png_ptr->zstream.next_out = png_ptr->zbuf;
  200560. }
  200561. /* continue until we don't have any more to compress */
  200562. } while (png_ptr->zstream.avail_in);
  200563. /* finish the compression */
  200564. do
  200565. {
  200566. /* tell zlib we are finished */
  200567. ret = deflate(&png_ptr->zstream, Z_FINISH);
  200568. if (ret == Z_OK)
  200569. {
  200570. /* check to see if we need more room */
  200571. if (!(png_ptr->zstream.avail_out))
  200572. {
  200573. /* check to make sure our output array has room */
  200574. if (comp->num_output_ptr >= comp->max_output_ptr)
  200575. {
  200576. int old_max;
  200577. old_max = comp->max_output_ptr;
  200578. comp->max_output_ptr = comp->num_output_ptr + 4;
  200579. if (comp->output_ptr != NULL)
  200580. {
  200581. png_charpp old_ptr;
  200582. old_ptr = comp->output_ptr;
  200583. /* This could be optimized to realloc() */
  200584. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200585. (png_uint_32)(comp->max_output_ptr *
  200586. png_sizeof (png_charpp)));
  200587. png_memcpy(comp->output_ptr, old_ptr,
  200588. old_max * png_sizeof (png_charp));
  200589. png_free(png_ptr, old_ptr);
  200590. }
  200591. else
  200592. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200593. (png_uint_32)(comp->max_output_ptr *
  200594. png_sizeof (png_charp)));
  200595. }
  200596. /* save off the data */
  200597. comp->output_ptr[comp->num_output_ptr] =
  200598. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  200599. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200600. png_ptr->zbuf_size);
  200601. comp->num_output_ptr++;
  200602. /* and reset the buffer pointers */
  200603. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200604. png_ptr->zstream.next_out = png_ptr->zbuf;
  200605. }
  200606. }
  200607. else if (ret != Z_STREAM_END)
  200608. {
  200609. /* we got an error */
  200610. if (png_ptr->zstream.msg != NULL)
  200611. png_error(png_ptr, png_ptr->zstream.msg);
  200612. else
  200613. png_error(png_ptr, "zlib error");
  200614. }
  200615. } while (ret != Z_STREAM_END);
  200616. /* text length is number of buffers plus last buffer */
  200617. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  200618. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  200619. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  200620. return((int)text_len);
  200621. }
  200622. /* ship the compressed text out via chunk writes */
  200623. static void /* PRIVATE */
  200624. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  200625. {
  200626. int i;
  200627. /* handle the no-compression case */
  200628. if (comp->input)
  200629. {
  200630. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  200631. (png_size_t)comp->input_len);
  200632. return;
  200633. }
  200634. /* write saved output buffers, if any */
  200635. for (i = 0; i < comp->num_output_ptr; i++)
  200636. {
  200637. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  200638. png_ptr->zbuf_size);
  200639. png_free(png_ptr, comp->output_ptr[i]);
  200640. comp->output_ptr[i]=NULL;
  200641. }
  200642. if (comp->max_output_ptr != 0)
  200643. png_free(png_ptr, comp->output_ptr);
  200644. comp->output_ptr=NULL;
  200645. /* write anything left in zbuf */
  200646. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  200647. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  200648. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  200649. /* reset zlib for another zTXt/iTXt or image data */
  200650. deflateReset(&png_ptr->zstream);
  200651. png_ptr->zstream.data_type = Z_BINARY;
  200652. }
  200653. #endif
  200654. /* Write the IHDR chunk, and update the png_struct with the necessary
  200655. * information. Note that the rest of this code depends upon this
  200656. * information being correct.
  200657. */
  200658. void /* PRIVATE */
  200659. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  200660. int bit_depth, int color_type, int compression_type, int filter_type,
  200661. int interlace_type)
  200662. {
  200663. #ifdef PNG_USE_LOCAL_ARRAYS
  200664. PNG_IHDR;
  200665. #endif
  200666. png_byte buf[13]; /* buffer to store the IHDR info */
  200667. png_debug(1, "in png_write_IHDR\n");
  200668. /* Check that we have valid input data from the application info */
  200669. switch (color_type)
  200670. {
  200671. case PNG_COLOR_TYPE_GRAY:
  200672. switch (bit_depth)
  200673. {
  200674. case 1:
  200675. case 2:
  200676. case 4:
  200677. case 8:
  200678. case 16: png_ptr->channels = 1; break;
  200679. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  200680. }
  200681. break;
  200682. case PNG_COLOR_TYPE_RGB:
  200683. if (bit_depth != 8 && bit_depth != 16)
  200684. png_error(png_ptr, "Invalid bit depth for RGB image");
  200685. png_ptr->channels = 3;
  200686. break;
  200687. case PNG_COLOR_TYPE_PALETTE:
  200688. switch (bit_depth)
  200689. {
  200690. case 1:
  200691. case 2:
  200692. case 4:
  200693. case 8: png_ptr->channels = 1; break;
  200694. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  200695. }
  200696. break;
  200697. case PNG_COLOR_TYPE_GRAY_ALPHA:
  200698. if (bit_depth != 8 && bit_depth != 16)
  200699. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  200700. png_ptr->channels = 2;
  200701. break;
  200702. case PNG_COLOR_TYPE_RGB_ALPHA:
  200703. if (bit_depth != 8 && bit_depth != 16)
  200704. png_error(png_ptr, "Invalid bit depth for RGBA image");
  200705. png_ptr->channels = 4;
  200706. break;
  200707. default:
  200708. png_error(png_ptr, "Invalid image color type specified");
  200709. }
  200710. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200711. {
  200712. png_warning(png_ptr, "Invalid compression type specified");
  200713. compression_type = PNG_COMPRESSION_TYPE_BASE;
  200714. }
  200715. /* Write filter_method 64 (intrapixel differencing) only if
  200716. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  200717. * 2. Libpng did not write a PNG signature (this filter_method is only
  200718. * used in PNG datastreams that are embedded in MNG datastreams) and
  200719. * 3. The application called png_permit_mng_features with a mask that
  200720. * included PNG_FLAG_MNG_FILTER_64 and
  200721. * 4. The filter_method is 64 and
  200722. * 5. The color_type is RGB or RGBA
  200723. */
  200724. if (
  200725. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200726. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  200727. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  200728. (color_type == PNG_COLOR_TYPE_RGB ||
  200729. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  200730. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  200731. #endif
  200732. filter_type != PNG_FILTER_TYPE_BASE)
  200733. {
  200734. png_warning(png_ptr, "Invalid filter type specified");
  200735. filter_type = PNG_FILTER_TYPE_BASE;
  200736. }
  200737. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  200738. if (interlace_type != PNG_INTERLACE_NONE &&
  200739. interlace_type != PNG_INTERLACE_ADAM7)
  200740. {
  200741. png_warning(png_ptr, "Invalid interlace type specified");
  200742. interlace_type = PNG_INTERLACE_ADAM7;
  200743. }
  200744. #else
  200745. interlace_type=PNG_INTERLACE_NONE;
  200746. #endif
  200747. /* save off the relevent information */
  200748. png_ptr->bit_depth = (png_byte)bit_depth;
  200749. png_ptr->color_type = (png_byte)color_type;
  200750. png_ptr->interlaced = (png_byte)interlace_type;
  200751. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200752. png_ptr->filter_type = (png_byte)filter_type;
  200753. #endif
  200754. png_ptr->compression_type = (png_byte)compression_type;
  200755. png_ptr->width = width;
  200756. png_ptr->height = height;
  200757. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  200758. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  200759. /* set the usr info, so any transformations can modify it */
  200760. png_ptr->usr_width = png_ptr->width;
  200761. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  200762. png_ptr->usr_channels = png_ptr->channels;
  200763. /* pack the header information into the buffer */
  200764. png_save_uint_32(buf, width);
  200765. png_save_uint_32(buf + 4, height);
  200766. buf[8] = (png_byte)bit_depth;
  200767. buf[9] = (png_byte)color_type;
  200768. buf[10] = (png_byte)compression_type;
  200769. buf[11] = (png_byte)filter_type;
  200770. buf[12] = (png_byte)interlace_type;
  200771. /* write the chunk */
  200772. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  200773. /* initialize zlib with PNG info */
  200774. png_ptr->zstream.zalloc = png_zalloc;
  200775. png_ptr->zstream.zfree = png_zfree;
  200776. png_ptr->zstream.opaque = (voidpf)png_ptr;
  200777. if (!(png_ptr->do_filter))
  200778. {
  200779. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  200780. png_ptr->bit_depth < 8)
  200781. png_ptr->do_filter = PNG_FILTER_NONE;
  200782. else
  200783. png_ptr->do_filter = PNG_ALL_FILTERS;
  200784. }
  200785. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  200786. {
  200787. if (png_ptr->do_filter != PNG_FILTER_NONE)
  200788. png_ptr->zlib_strategy = Z_FILTERED;
  200789. else
  200790. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  200791. }
  200792. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  200793. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  200794. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  200795. png_ptr->zlib_mem_level = 8;
  200796. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  200797. png_ptr->zlib_window_bits = 15;
  200798. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  200799. png_ptr->zlib_method = 8;
  200800. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  200801. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  200802. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  200803. png_error(png_ptr, "zlib failed to initialize compressor");
  200804. png_ptr->zstream.next_out = png_ptr->zbuf;
  200805. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200806. /* libpng is not interested in zstream.data_type */
  200807. /* set it to a predefined value, to avoid its evaluation inside zlib */
  200808. png_ptr->zstream.data_type = Z_BINARY;
  200809. png_ptr->mode = PNG_HAVE_IHDR;
  200810. }
  200811. /* write the palette. We are careful not to trust png_color to be in the
  200812. * correct order for PNG, so people can redefine it to any convenient
  200813. * structure.
  200814. */
  200815. void /* PRIVATE */
  200816. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  200817. {
  200818. #ifdef PNG_USE_LOCAL_ARRAYS
  200819. PNG_PLTE;
  200820. #endif
  200821. png_uint_32 i;
  200822. png_colorp pal_ptr;
  200823. png_byte buf[3];
  200824. png_debug(1, "in png_write_PLTE\n");
  200825. if ((
  200826. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200827. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  200828. #endif
  200829. num_pal == 0) || num_pal > 256)
  200830. {
  200831. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  200832. {
  200833. png_error(png_ptr, "Invalid number of colors in palette");
  200834. }
  200835. else
  200836. {
  200837. png_warning(png_ptr, "Invalid number of colors in palette");
  200838. return;
  200839. }
  200840. }
  200841. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  200842. {
  200843. png_warning(png_ptr,
  200844. "Ignoring request to write a PLTE chunk in grayscale PNG");
  200845. return;
  200846. }
  200847. png_ptr->num_palette = (png_uint_16)num_pal;
  200848. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  200849. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  200850. #ifndef PNG_NO_POINTER_INDEXING
  200851. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  200852. {
  200853. buf[0] = pal_ptr->red;
  200854. buf[1] = pal_ptr->green;
  200855. buf[2] = pal_ptr->blue;
  200856. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200857. }
  200858. #else
  200859. /* This is a little slower but some buggy compilers need to do this instead */
  200860. pal_ptr=palette;
  200861. for (i = 0; i < num_pal; i++)
  200862. {
  200863. buf[0] = pal_ptr[i].red;
  200864. buf[1] = pal_ptr[i].green;
  200865. buf[2] = pal_ptr[i].blue;
  200866. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200867. }
  200868. #endif
  200869. png_write_chunk_end(png_ptr);
  200870. png_ptr->mode |= PNG_HAVE_PLTE;
  200871. }
  200872. /* write an IDAT chunk */
  200873. void /* PRIVATE */
  200874. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  200875. {
  200876. #ifdef PNG_USE_LOCAL_ARRAYS
  200877. PNG_IDAT;
  200878. #endif
  200879. png_debug(1, "in png_write_IDAT\n");
  200880. /* Optimize the CMF field in the zlib stream. */
  200881. /* This hack of the zlib stream is compliant to the stream specification. */
  200882. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  200883. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  200884. {
  200885. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  200886. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  200887. {
  200888. /* Avoid memory underflows and multiplication overflows. */
  200889. /* The conditions below are practically always satisfied;
  200890. however, they still must be checked. */
  200891. if (length >= 2 &&
  200892. png_ptr->height < 16384 && png_ptr->width < 16384)
  200893. {
  200894. png_uint_32 uncompressed_idat_size = png_ptr->height *
  200895. ((png_ptr->width *
  200896. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  200897. unsigned int z_cinfo = z_cmf >> 4;
  200898. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  200899. while (uncompressed_idat_size <= half_z_window_size &&
  200900. half_z_window_size >= 256)
  200901. {
  200902. z_cinfo--;
  200903. half_z_window_size >>= 1;
  200904. }
  200905. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  200906. if (data[0] != (png_byte)z_cmf)
  200907. {
  200908. data[0] = (png_byte)z_cmf;
  200909. data[1] &= 0xe0;
  200910. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  200911. }
  200912. }
  200913. }
  200914. else
  200915. png_error(png_ptr,
  200916. "Invalid zlib compression method or flags in IDAT");
  200917. }
  200918. png_write_chunk(png_ptr, png_IDAT, data, length);
  200919. png_ptr->mode |= PNG_HAVE_IDAT;
  200920. }
  200921. /* write an IEND chunk */
  200922. void /* PRIVATE */
  200923. png_write_IEND(png_structp png_ptr)
  200924. {
  200925. #ifdef PNG_USE_LOCAL_ARRAYS
  200926. PNG_IEND;
  200927. #endif
  200928. png_debug(1, "in png_write_IEND\n");
  200929. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  200930. (png_size_t)0);
  200931. png_ptr->mode |= PNG_HAVE_IEND;
  200932. }
  200933. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  200934. /* write a gAMA chunk */
  200935. #ifdef PNG_FLOATING_POINT_SUPPORTED
  200936. void /* PRIVATE */
  200937. png_write_gAMA(png_structp png_ptr, double file_gamma)
  200938. {
  200939. #ifdef PNG_USE_LOCAL_ARRAYS
  200940. PNG_gAMA;
  200941. #endif
  200942. png_uint_32 igamma;
  200943. png_byte buf[4];
  200944. png_debug(1, "in png_write_gAMA\n");
  200945. /* file_gamma is saved in 1/100,000ths */
  200946. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  200947. png_save_uint_32(buf, igamma);
  200948. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200949. }
  200950. #endif
  200951. #ifdef PNG_FIXED_POINT_SUPPORTED
  200952. void /* PRIVATE */
  200953. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  200954. {
  200955. #ifdef PNG_USE_LOCAL_ARRAYS
  200956. PNG_gAMA;
  200957. #endif
  200958. png_byte buf[4];
  200959. png_debug(1, "in png_write_gAMA\n");
  200960. /* file_gamma is saved in 1/100,000ths */
  200961. png_save_uint_32(buf, (png_uint_32)file_gamma);
  200962. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200963. }
  200964. #endif
  200965. #endif
  200966. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  200967. /* write a sRGB chunk */
  200968. void /* PRIVATE */
  200969. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  200970. {
  200971. #ifdef PNG_USE_LOCAL_ARRAYS
  200972. PNG_sRGB;
  200973. #endif
  200974. png_byte buf[1];
  200975. png_debug(1, "in png_write_sRGB\n");
  200976. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  200977. png_warning(png_ptr,
  200978. "Invalid sRGB rendering intent specified");
  200979. buf[0]=(png_byte)srgb_intent;
  200980. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  200981. }
  200982. #endif
  200983. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  200984. /* write an iCCP chunk */
  200985. void /* PRIVATE */
  200986. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  200987. png_charp profile, int profile_len)
  200988. {
  200989. #ifdef PNG_USE_LOCAL_ARRAYS
  200990. PNG_iCCP;
  200991. #endif
  200992. png_size_t name_len;
  200993. png_charp new_name;
  200994. compression_state comp;
  200995. int embedded_profile_len = 0;
  200996. png_debug(1, "in png_write_iCCP\n");
  200997. comp.num_output_ptr = 0;
  200998. comp.max_output_ptr = 0;
  200999. comp.output_ptr = NULL;
  201000. comp.input = NULL;
  201001. comp.input_len = 0;
  201002. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  201003. &new_name)) == 0)
  201004. {
  201005. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  201006. return;
  201007. }
  201008. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201009. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  201010. if (profile == NULL)
  201011. profile_len = 0;
  201012. if (profile_len > 3)
  201013. embedded_profile_len =
  201014. ((*( (png_bytep)profile ))<<24) |
  201015. ((*( (png_bytep)profile+1))<<16) |
  201016. ((*( (png_bytep)profile+2))<< 8) |
  201017. ((*( (png_bytep)profile+3)) );
  201018. if (profile_len < embedded_profile_len)
  201019. {
  201020. png_warning(png_ptr,
  201021. "Embedded profile length too large in iCCP chunk");
  201022. return;
  201023. }
  201024. if (profile_len > embedded_profile_len)
  201025. {
  201026. png_warning(png_ptr,
  201027. "Truncating profile to actual length in iCCP chunk");
  201028. profile_len = embedded_profile_len;
  201029. }
  201030. if (profile_len)
  201031. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201032. PNG_COMPRESSION_TYPE_BASE, &comp);
  201033. /* make sure we include the NULL after the name and the compression type */
  201034. png_write_chunk_start(png_ptr, png_iCCP,
  201035. (png_uint_32)name_len+profile_len+2);
  201036. new_name[name_len+1]=0x00;
  201037. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201038. if (profile_len)
  201039. png_write_compressed_data_out(png_ptr, &comp);
  201040. png_write_chunk_end(png_ptr);
  201041. png_free(png_ptr, new_name);
  201042. }
  201043. #endif
  201044. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201045. /* write a sPLT chunk */
  201046. void /* PRIVATE */
  201047. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201048. {
  201049. #ifdef PNG_USE_LOCAL_ARRAYS
  201050. PNG_sPLT;
  201051. #endif
  201052. png_size_t name_len;
  201053. png_charp new_name;
  201054. png_byte entrybuf[10];
  201055. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201056. int palette_size = entry_size * spalette->nentries;
  201057. png_sPLT_entryp ep;
  201058. #ifdef PNG_NO_POINTER_INDEXING
  201059. int i;
  201060. #endif
  201061. png_debug(1, "in png_write_sPLT\n");
  201062. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201063. spalette->name, &new_name))==0)
  201064. {
  201065. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201066. return;
  201067. }
  201068. /* make sure we include the NULL after the name */
  201069. png_write_chunk_start(png_ptr, png_sPLT,
  201070. (png_uint_32)(name_len + 2 + palette_size));
  201071. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201072. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201073. /* loop through each palette entry, writing appropriately */
  201074. #ifndef PNG_NO_POINTER_INDEXING
  201075. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201076. {
  201077. if (spalette->depth == 8)
  201078. {
  201079. entrybuf[0] = (png_byte)ep->red;
  201080. entrybuf[1] = (png_byte)ep->green;
  201081. entrybuf[2] = (png_byte)ep->blue;
  201082. entrybuf[3] = (png_byte)ep->alpha;
  201083. png_save_uint_16(entrybuf + 4, ep->frequency);
  201084. }
  201085. else
  201086. {
  201087. png_save_uint_16(entrybuf + 0, ep->red);
  201088. png_save_uint_16(entrybuf + 2, ep->green);
  201089. png_save_uint_16(entrybuf + 4, ep->blue);
  201090. png_save_uint_16(entrybuf + 6, ep->alpha);
  201091. png_save_uint_16(entrybuf + 8, ep->frequency);
  201092. }
  201093. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201094. }
  201095. #else
  201096. ep=spalette->entries;
  201097. for (i=0; i>spalette->nentries; i++)
  201098. {
  201099. if (spalette->depth == 8)
  201100. {
  201101. entrybuf[0] = (png_byte)ep[i].red;
  201102. entrybuf[1] = (png_byte)ep[i].green;
  201103. entrybuf[2] = (png_byte)ep[i].blue;
  201104. entrybuf[3] = (png_byte)ep[i].alpha;
  201105. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201106. }
  201107. else
  201108. {
  201109. png_save_uint_16(entrybuf + 0, ep[i].red);
  201110. png_save_uint_16(entrybuf + 2, ep[i].green);
  201111. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201112. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201113. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201114. }
  201115. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201116. }
  201117. #endif
  201118. png_write_chunk_end(png_ptr);
  201119. png_free(png_ptr, new_name);
  201120. }
  201121. #endif
  201122. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201123. /* write the sBIT chunk */
  201124. void /* PRIVATE */
  201125. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201126. {
  201127. #ifdef PNG_USE_LOCAL_ARRAYS
  201128. PNG_sBIT;
  201129. #endif
  201130. png_byte buf[4];
  201131. png_size_t size;
  201132. png_debug(1, "in png_write_sBIT\n");
  201133. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201134. if (color_type & PNG_COLOR_MASK_COLOR)
  201135. {
  201136. png_byte maxbits;
  201137. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201138. png_ptr->usr_bit_depth);
  201139. if (sbit->red == 0 || sbit->red > maxbits ||
  201140. sbit->green == 0 || sbit->green > maxbits ||
  201141. sbit->blue == 0 || sbit->blue > maxbits)
  201142. {
  201143. png_warning(png_ptr, "Invalid sBIT depth specified");
  201144. return;
  201145. }
  201146. buf[0] = sbit->red;
  201147. buf[1] = sbit->green;
  201148. buf[2] = sbit->blue;
  201149. size = 3;
  201150. }
  201151. else
  201152. {
  201153. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201154. {
  201155. png_warning(png_ptr, "Invalid sBIT depth specified");
  201156. return;
  201157. }
  201158. buf[0] = sbit->gray;
  201159. size = 1;
  201160. }
  201161. if (color_type & PNG_COLOR_MASK_ALPHA)
  201162. {
  201163. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201164. {
  201165. png_warning(png_ptr, "Invalid sBIT depth specified");
  201166. return;
  201167. }
  201168. buf[size++] = sbit->alpha;
  201169. }
  201170. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201171. }
  201172. #endif
  201173. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201174. /* write the cHRM chunk */
  201175. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201176. void /* PRIVATE */
  201177. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201178. double red_x, double red_y, double green_x, double green_y,
  201179. double blue_x, double blue_y)
  201180. {
  201181. #ifdef PNG_USE_LOCAL_ARRAYS
  201182. PNG_cHRM;
  201183. #endif
  201184. png_byte buf[32];
  201185. png_uint_32 itemp;
  201186. png_debug(1, "in png_write_cHRM\n");
  201187. /* each value is saved in 1/100,000ths */
  201188. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201189. white_x + white_y > 1.0)
  201190. {
  201191. png_warning(png_ptr, "Invalid cHRM white point specified");
  201192. #if !defined(PNG_NO_CONSOLE_IO)
  201193. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201194. #endif
  201195. return;
  201196. }
  201197. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201198. png_save_uint_32(buf, itemp);
  201199. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201200. png_save_uint_32(buf + 4, itemp);
  201201. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201202. {
  201203. png_warning(png_ptr, "Invalid cHRM red point specified");
  201204. return;
  201205. }
  201206. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201207. png_save_uint_32(buf + 8, itemp);
  201208. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201209. png_save_uint_32(buf + 12, itemp);
  201210. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201211. {
  201212. png_warning(png_ptr, "Invalid cHRM green point specified");
  201213. return;
  201214. }
  201215. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201216. png_save_uint_32(buf + 16, itemp);
  201217. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201218. png_save_uint_32(buf + 20, itemp);
  201219. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201220. {
  201221. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201222. return;
  201223. }
  201224. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201225. png_save_uint_32(buf + 24, itemp);
  201226. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201227. png_save_uint_32(buf + 28, itemp);
  201228. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201229. }
  201230. #endif
  201231. #ifdef PNG_FIXED_POINT_SUPPORTED
  201232. void /* PRIVATE */
  201233. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201234. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201235. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201236. png_fixed_point blue_y)
  201237. {
  201238. #ifdef PNG_USE_LOCAL_ARRAYS
  201239. PNG_cHRM;
  201240. #endif
  201241. png_byte buf[32];
  201242. png_debug(1, "in png_write_cHRM\n");
  201243. /* each value is saved in 1/100,000ths */
  201244. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201245. {
  201246. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201247. #if !defined(PNG_NO_CONSOLE_IO)
  201248. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201249. #endif
  201250. return;
  201251. }
  201252. png_save_uint_32(buf, (png_uint_32)white_x);
  201253. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201254. if (red_x + red_y > 100000L)
  201255. {
  201256. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201257. return;
  201258. }
  201259. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201260. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201261. if (green_x + green_y > 100000L)
  201262. {
  201263. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201264. return;
  201265. }
  201266. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201267. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201268. if (blue_x + blue_y > 100000L)
  201269. {
  201270. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201271. return;
  201272. }
  201273. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201274. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201275. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201276. }
  201277. #endif
  201278. #endif
  201279. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201280. /* write the tRNS chunk */
  201281. void /* PRIVATE */
  201282. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201283. int num_trans, int color_type)
  201284. {
  201285. #ifdef PNG_USE_LOCAL_ARRAYS
  201286. PNG_tRNS;
  201287. #endif
  201288. png_byte buf[6];
  201289. png_debug(1, "in png_write_tRNS\n");
  201290. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201291. {
  201292. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201293. {
  201294. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201295. return;
  201296. }
  201297. /* write the chunk out as it is */
  201298. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201299. }
  201300. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201301. {
  201302. /* one 16 bit value */
  201303. if(tran->gray >= (1 << png_ptr->bit_depth))
  201304. {
  201305. png_warning(png_ptr,
  201306. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201307. return;
  201308. }
  201309. png_save_uint_16(buf, tran->gray);
  201310. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201311. }
  201312. else if (color_type == PNG_COLOR_TYPE_RGB)
  201313. {
  201314. /* three 16 bit values */
  201315. png_save_uint_16(buf, tran->red);
  201316. png_save_uint_16(buf + 2, tran->green);
  201317. png_save_uint_16(buf + 4, tran->blue);
  201318. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201319. {
  201320. png_warning(png_ptr,
  201321. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201322. return;
  201323. }
  201324. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201325. }
  201326. else
  201327. {
  201328. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201329. }
  201330. }
  201331. #endif
  201332. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201333. /* write the background chunk */
  201334. void /* PRIVATE */
  201335. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201336. {
  201337. #ifdef PNG_USE_LOCAL_ARRAYS
  201338. PNG_bKGD;
  201339. #endif
  201340. png_byte buf[6];
  201341. png_debug(1, "in png_write_bKGD\n");
  201342. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201343. {
  201344. if (
  201345. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201346. (png_ptr->num_palette ||
  201347. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201348. #endif
  201349. back->index > png_ptr->num_palette)
  201350. {
  201351. png_warning(png_ptr, "Invalid background palette index");
  201352. return;
  201353. }
  201354. buf[0] = back->index;
  201355. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201356. }
  201357. else if (color_type & PNG_COLOR_MASK_COLOR)
  201358. {
  201359. png_save_uint_16(buf, back->red);
  201360. png_save_uint_16(buf + 2, back->green);
  201361. png_save_uint_16(buf + 4, back->blue);
  201362. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201363. {
  201364. png_warning(png_ptr,
  201365. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201366. return;
  201367. }
  201368. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201369. }
  201370. else
  201371. {
  201372. if(back->gray >= (1 << png_ptr->bit_depth))
  201373. {
  201374. png_warning(png_ptr,
  201375. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201376. return;
  201377. }
  201378. png_save_uint_16(buf, back->gray);
  201379. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201380. }
  201381. }
  201382. #endif
  201383. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201384. /* write the histogram */
  201385. void /* PRIVATE */
  201386. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201387. {
  201388. #ifdef PNG_USE_LOCAL_ARRAYS
  201389. PNG_hIST;
  201390. #endif
  201391. int i;
  201392. png_byte buf[3];
  201393. png_debug(1, "in png_write_hIST\n");
  201394. if (num_hist > (int)png_ptr->num_palette)
  201395. {
  201396. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201397. png_ptr->num_palette);
  201398. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201399. return;
  201400. }
  201401. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201402. for (i = 0; i < num_hist; i++)
  201403. {
  201404. png_save_uint_16(buf, hist[i]);
  201405. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201406. }
  201407. png_write_chunk_end(png_ptr);
  201408. }
  201409. #endif
  201410. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201411. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201412. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201413. * and if invalid, correct the keyword rather than discarding the entire
  201414. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201415. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201416. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201417. *
  201418. * The new_key is allocated to hold the corrected keyword and must be freed
  201419. * by the calling routine. This avoids problems with trying to write to
  201420. * static keywords without having to have duplicate copies of the strings.
  201421. */
  201422. png_size_t /* PRIVATE */
  201423. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201424. {
  201425. png_size_t key_len;
  201426. png_charp kp, dp;
  201427. int kflag;
  201428. int kwarn=0;
  201429. png_debug(1, "in png_check_keyword\n");
  201430. *new_key = NULL;
  201431. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201432. {
  201433. png_warning(png_ptr, "zero length keyword");
  201434. return ((png_size_t)0);
  201435. }
  201436. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201437. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201438. if (*new_key == NULL)
  201439. {
  201440. png_warning(png_ptr, "Out of memory while procesing keyword");
  201441. return ((png_size_t)0);
  201442. }
  201443. /* Replace non-printing characters with a blank and print a warning */
  201444. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201445. {
  201446. if ((png_byte)*kp < 0x20 ||
  201447. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201448. {
  201449. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201450. char msg[40];
  201451. png_snprintf(msg, 40,
  201452. "invalid keyword character 0x%02X", (png_byte)*kp);
  201453. png_warning(png_ptr, msg);
  201454. #else
  201455. png_warning(png_ptr, "invalid character in keyword");
  201456. #endif
  201457. *dp = ' ';
  201458. }
  201459. else
  201460. {
  201461. *dp = *kp;
  201462. }
  201463. }
  201464. *dp = '\0';
  201465. /* Remove any trailing white space. */
  201466. kp = *new_key + key_len - 1;
  201467. if (*kp == ' ')
  201468. {
  201469. png_warning(png_ptr, "trailing spaces removed from keyword");
  201470. while (*kp == ' ')
  201471. {
  201472. *(kp--) = '\0';
  201473. key_len--;
  201474. }
  201475. }
  201476. /* Remove any leading white space. */
  201477. kp = *new_key;
  201478. if (*kp == ' ')
  201479. {
  201480. png_warning(png_ptr, "leading spaces removed from keyword");
  201481. while (*kp == ' ')
  201482. {
  201483. kp++;
  201484. key_len--;
  201485. }
  201486. }
  201487. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201488. /* Remove multiple internal spaces. */
  201489. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201490. {
  201491. if (*kp == ' ' && kflag == 0)
  201492. {
  201493. *(dp++) = *kp;
  201494. kflag = 1;
  201495. }
  201496. else if (*kp == ' ')
  201497. {
  201498. key_len--;
  201499. kwarn=1;
  201500. }
  201501. else
  201502. {
  201503. *(dp++) = *kp;
  201504. kflag = 0;
  201505. }
  201506. }
  201507. *dp = '\0';
  201508. if(kwarn)
  201509. png_warning(png_ptr, "extra interior spaces removed from keyword");
  201510. if (key_len == 0)
  201511. {
  201512. png_free(png_ptr, *new_key);
  201513. *new_key=NULL;
  201514. png_warning(png_ptr, "Zero length keyword");
  201515. }
  201516. if (key_len > 79)
  201517. {
  201518. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  201519. new_key[79] = '\0';
  201520. key_len = 79;
  201521. }
  201522. return (key_len);
  201523. }
  201524. #endif
  201525. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  201526. /* write a tEXt chunk */
  201527. void /* PRIVATE */
  201528. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  201529. png_size_t text_len)
  201530. {
  201531. #ifdef PNG_USE_LOCAL_ARRAYS
  201532. PNG_tEXt;
  201533. #endif
  201534. png_size_t key_len;
  201535. png_charp new_key;
  201536. png_debug(1, "in png_write_tEXt\n");
  201537. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201538. {
  201539. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  201540. return;
  201541. }
  201542. if (text == NULL || *text == '\0')
  201543. text_len = 0;
  201544. else
  201545. text_len = png_strlen(text);
  201546. /* make sure we include the 0 after the key */
  201547. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  201548. /*
  201549. * We leave it to the application to meet PNG-1.0 requirements on the
  201550. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201551. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201552. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201553. */
  201554. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201555. if (text_len)
  201556. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  201557. png_write_chunk_end(png_ptr);
  201558. png_free(png_ptr, new_key);
  201559. }
  201560. #endif
  201561. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  201562. /* write a compressed text chunk */
  201563. void /* PRIVATE */
  201564. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  201565. png_size_t text_len, int compression)
  201566. {
  201567. #ifdef PNG_USE_LOCAL_ARRAYS
  201568. PNG_zTXt;
  201569. #endif
  201570. png_size_t key_len;
  201571. char buf[1];
  201572. png_charp new_key;
  201573. compression_state comp;
  201574. png_debug(1, "in png_write_zTXt\n");
  201575. comp.num_output_ptr = 0;
  201576. comp.max_output_ptr = 0;
  201577. comp.output_ptr = NULL;
  201578. comp.input = NULL;
  201579. comp.input_len = 0;
  201580. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201581. {
  201582. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  201583. return;
  201584. }
  201585. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  201586. {
  201587. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  201588. png_free(png_ptr, new_key);
  201589. return;
  201590. }
  201591. text_len = png_strlen(text);
  201592. /* compute the compressed data; do it now for the length */
  201593. text_len = png_text_compress(png_ptr, text, text_len, compression,
  201594. &comp);
  201595. /* write start of chunk */
  201596. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  201597. (key_len+text_len+2));
  201598. /* write key */
  201599. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201600. png_free(png_ptr, new_key);
  201601. buf[0] = (png_byte)compression;
  201602. /* write compression */
  201603. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  201604. /* write the compressed data */
  201605. png_write_compressed_data_out(png_ptr, &comp);
  201606. /* close the chunk */
  201607. png_write_chunk_end(png_ptr);
  201608. }
  201609. #endif
  201610. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  201611. /* write an iTXt chunk */
  201612. void /* PRIVATE */
  201613. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  201614. png_charp lang, png_charp lang_key, png_charp text)
  201615. {
  201616. #ifdef PNG_USE_LOCAL_ARRAYS
  201617. PNG_iTXt;
  201618. #endif
  201619. png_size_t lang_len, key_len, lang_key_len, text_len;
  201620. png_charp new_lang, new_key;
  201621. png_byte cbuf[2];
  201622. compression_state comp;
  201623. png_debug(1, "in png_write_iTXt\n");
  201624. comp.num_output_ptr = 0;
  201625. comp.max_output_ptr = 0;
  201626. comp.output_ptr = NULL;
  201627. comp.input = NULL;
  201628. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201629. {
  201630. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  201631. return;
  201632. }
  201633. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  201634. {
  201635. png_warning(png_ptr, "Empty language field in iTXt chunk");
  201636. new_lang = NULL;
  201637. lang_len = 0;
  201638. }
  201639. if (lang_key == NULL)
  201640. lang_key_len = 0;
  201641. else
  201642. lang_key_len = png_strlen(lang_key);
  201643. if (text == NULL)
  201644. text_len = 0;
  201645. else
  201646. text_len = png_strlen(text);
  201647. /* compute the compressed data; do it now for the length */
  201648. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  201649. &comp);
  201650. /* make sure we include the compression flag, the compression byte,
  201651. * and the NULs after the key, lang, and lang_key parts */
  201652. png_write_chunk_start(png_ptr, png_iTXt,
  201653. (png_uint_32)(
  201654. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  201655. + key_len
  201656. + lang_len
  201657. + lang_key_len
  201658. + text_len));
  201659. /*
  201660. * We leave it to the application to meet PNG-1.0 requirements on the
  201661. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201662. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201663. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201664. */
  201665. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201666. /* set the compression flag */
  201667. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  201668. compression == PNG_TEXT_COMPRESSION_NONE)
  201669. cbuf[0] = 0;
  201670. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  201671. cbuf[0] = 1;
  201672. /* set the compression method */
  201673. cbuf[1] = 0;
  201674. png_write_chunk_data(png_ptr, cbuf, 2);
  201675. cbuf[0] = 0;
  201676. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  201677. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  201678. png_write_compressed_data_out(png_ptr, &comp);
  201679. png_write_chunk_end(png_ptr);
  201680. png_free(png_ptr, new_key);
  201681. if (new_lang)
  201682. png_free(png_ptr, new_lang);
  201683. }
  201684. #endif
  201685. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  201686. /* write the oFFs chunk */
  201687. void /* PRIVATE */
  201688. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  201689. int unit_type)
  201690. {
  201691. #ifdef PNG_USE_LOCAL_ARRAYS
  201692. PNG_oFFs;
  201693. #endif
  201694. png_byte buf[9];
  201695. png_debug(1, "in png_write_oFFs\n");
  201696. if (unit_type >= PNG_OFFSET_LAST)
  201697. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  201698. png_save_int_32(buf, x_offset);
  201699. png_save_int_32(buf + 4, y_offset);
  201700. buf[8] = (png_byte)unit_type;
  201701. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  201702. }
  201703. #endif
  201704. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  201705. /* write the pCAL chunk (described in the PNG extensions document) */
  201706. void /* PRIVATE */
  201707. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  201708. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  201709. {
  201710. #ifdef PNG_USE_LOCAL_ARRAYS
  201711. PNG_pCAL;
  201712. #endif
  201713. png_size_t purpose_len, units_len, total_len;
  201714. png_uint_32p params_len;
  201715. png_byte buf[10];
  201716. png_charp new_purpose;
  201717. int i;
  201718. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  201719. if (type >= PNG_EQUATION_LAST)
  201720. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  201721. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  201722. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  201723. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  201724. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  201725. total_len = purpose_len + units_len + 10;
  201726. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  201727. *png_sizeof(png_uint_32)));
  201728. /* Find the length of each parameter, making sure we don't count the
  201729. null terminator for the last parameter. */
  201730. for (i = 0; i < nparams; i++)
  201731. {
  201732. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  201733. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  201734. total_len += (png_size_t)params_len[i];
  201735. }
  201736. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  201737. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  201738. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  201739. png_save_int_32(buf, X0);
  201740. png_save_int_32(buf + 4, X1);
  201741. buf[8] = (png_byte)type;
  201742. buf[9] = (png_byte)nparams;
  201743. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  201744. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  201745. png_free(png_ptr, new_purpose);
  201746. for (i = 0; i < nparams; i++)
  201747. {
  201748. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  201749. (png_size_t)params_len[i]);
  201750. }
  201751. png_free(png_ptr, params_len);
  201752. png_write_chunk_end(png_ptr);
  201753. }
  201754. #endif
  201755. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  201756. /* write the sCAL chunk */
  201757. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  201758. void /* PRIVATE */
  201759. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  201760. {
  201761. #ifdef PNG_USE_LOCAL_ARRAYS
  201762. PNG_sCAL;
  201763. #endif
  201764. char buf[64];
  201765. png_size_t total_len;
  201766. png_debug(1, "in png_write_sCAL\n");
  201767. buf[0] = (char)unit;
  201768. #if defined(_WIN32_WCE)
  201769. /* sprintf() function is not supported on WindowsCE */
  201770. {
  201771. wchar_t wc_buf[32];
  201772. size_t wc_len;
  201773. swprintf(wc_buf, TEXT("%12.12e"), width);
  201774. wc_len = wcslen(wc_buf);
  201775. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  201776. total_len = wc_len + 2;
  201777. swprintf(wc_buf, TEXT("%12.12e"), height);
  201778. wc_len = wcslen(wc_buf);
  201779. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  201780. NULL, NULL);
  201781. total_len += wc_len;
  201782. }
  201783. #else
  201784. png_snprintf(buf + 1, 63, "%12.12e", width);
  201785. total_len = 1 + png_strlen(buf + 1) + 1;
  201786. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  201787. total_len += png_strlen(buf + total_len);
  201788. #endif
  201789. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201790. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  201791. }
  201792. #else
  201793. #ifdef PNG_FIXED_POINT_SUPPORTED
  201794. void /* PRIVATE */
  201795. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  201796. png_charp height)
  201797. {
  201798. #ifdef PNG_USE_LOCAL_ARRAYS
  201799. PNG_sCAL;
  201800. #endif
  201801. png_byte buf[64];
  201802. png_size_t wlen, hlen, total_len;
  201803. png_debug(1, "in png_write_sCAL_s\n");
  201804. wlen = png_strlen(width);
  201805. hlen = png_strlen(height);
  201806. total_len = wlen + hlen + 2;
  201807. if (total_len > 64)
  201808. {
  201809. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  201810. return;
  201811. }
  201812. buf[0] = (png_byte)unit;
  201813. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  201814. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  201815. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201816. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  201817. }
  201818. #endif
  201819. #endif
  201820. #endif
  201821. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  201822. /* write the pHYs chunk */
  201823. void /* PRIVATE */
  201824. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  201825. png_uint_32 y_pixels_per_unit,
  201826. int unit_type)
  201827. {
  201828. #ifdef PNG_USE_LOCAL_ARRAYS
  201829. PNG_pHYs;
  201830. #endif
  201831. png_byte buf[9];
  201832. png_debug(1, "in png_write_pHYs\n");
  201833. if (unit_type >= PNG_RESOLUTION_LAST)
  201834. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  201835. png_save_uint_32(buf, x_pixels_per_unit);
  201836. png_save_uint_32(buf + 4, y_pixels_per_unit);
  201837. buf[8] = (png_byte)unit_type;
  201838. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  201839. }
  201840. #endif
  201841. #if defined(PNG_WRITE_tIME_SUPPORTED)
  201842. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  201843. * or png_convert_from_time_t(), or fill in the structure yourself.
  201844. */
  201845. void /* PRIVATE */
  201846. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  201847. {
  201848. #ifdef PNG_USE_LOCAL_ARRAYS
  201849. PNG_tIME;
  201850. #endif
  201851. png_byte buf[7];
  201852. png_debug(1, "in png_write_tIME\n");
  201853. if (mod_time->month > 12 || mod_time->month < 1 ||
  201854. mod_time->day > 31 || mod_time->day < 1 ||
  201855. mod_time->hour > 23 || mod_time->second > 60)
  201856. {
  201857. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  201858. return;
  201859. }
  201860. png_save_uint_16(buf, mod_time->year);
  201861. buf[2] = mod_time->month;
  201862. buf[3] = mod_time->day;
  201863. buf[4] = mod_time->hour;
  201864. buf[5] = mod_time->minute;
  201865. buf[6] = mod_time->second;
  201866. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  201867. }
  201868. #endif
  201869. /* initializes the row writing capability of libpng */
  201870. void /* PRIVATE */
  201871. png_write_start_row(png_structp png_ptr)
  201872. {
  201873. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201874. #ifdef PNG_USE_LOCAL_ARRAYS
  201875. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201876. /* start of interlace block */
  201877. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201878. /* offset to next interlace block */
  201879. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201880. /* start of interlace block in the y direction */
  201881. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201882. /* offset to next interlace block in the y direction */
  201883. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201884. #endif
  201885. #endif
  201886. png_size_t buf_size;
  201887. png_debug(1, "in png_write_start_row\n");
  201888. buf_size = (png_size_t)(PNG_ROWBYTES(
  201889. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  201890. /* set up row buffer */
  201891. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201892. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  201893. #ifndef PNG_NO_WRITE_FILTERING
  201894. /* set up filtering buffer, if using this filter */
  201895. if (png_ptr->do_filter & PNG_FILTER_SUB)
  201896. {
  201897. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  201898. (png_ptr->rowbytes + 1));
  201899. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  201900. }
  201901. /* We only need to keep the previous row if we are using one of these. */
  201902. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  201903. {
  201904. /* set up previous row buffer */
  201905. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201906. png_memset(png_ptr->prev_row, 0, buf_size);
  201907. if (png_ptr->do_filter & PNG_FILTER_UP)
  201908. {
  201909. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  201910. (png_ptr->rowbytes + 1));
  201911. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  201912. }
  201913. if (png_ptr->do_filter & PNG_FILTER_AVG)
  201914. {
  201915. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  201916. (png_ptr->rowbytes + 1));
  201917. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  201918. }
  201919. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  201920. {
  201921. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  201922. (png_ptr->rowbytes + 1));
  201923. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  201924. }
  201925. #endif /* PNG_NO_WRITE_FILTERING */
  201926. }
  201927. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201928. /* if interlaced, we need to set up width and height of pass */
  201929. if (png_ptr->interlaced)
  201930. {
  201931. if (!(png_ptr->transformations & PNG_INTERLACE))
  201932. {
  201933. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  201934. png_pass_ystart[0]) / png_pass_yinc[0];
  201935. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  201936. png_pass_start[0]) / png_pass_inc[0];
  201937. }
  201938. else
  201939. {
  201940. png_ptr->num_rows = png_ptr->height;
  201941. png_ptr->usr_width = png_ptr->width;
  201942. }
  201943. }
  201944. else
  201945. #endif
  201946. {
  201947. png_ptr->num_rows = png_ptr->height;
  201948. png_ptr->usr_width = png_ptr->width;
  201949. }
  201950. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201951. png_ptr->zstream.next_out = png_ptr->zbuf;
  201952. }
  201953. /* Internal use only. Called when finished processing a row of data. */
  201954. void /* PRIVATE */
  201955. png_write_finish_row(png_structp png_ptr)
  201956. {
  201957. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201958. #ifdef PNG_USE_LOCAL_ARRAYS
  201959. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201960. /* start of interlace block */
  201961. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201962. /* offset to next interlace block */
  201963. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201964. /* start of interlace block in the y direction */
  201965. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201966. /* offset to next interlace block in the y direction */
  201967. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201968. #endif
  201969. #endif
  201970. int ret;
  201971. png_debug(1, "in png_write_finish_row\n");
  201972. /* next row */
  201973. png_ptr->row_number++;
  201974. /* see if we are done */
  201975. if (png_ptr->row_number < png_ptr->num_rows)
  201976. return;
  201977. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201978. /* if interlaced, go to next pass */
  201979. if (png_ptr->interlaced)
  201980. {
  201981. png_ptr->row_number = 0;
  201982. if (png_ptr->transformations & PNG_INTERLACE)
  201983. {
  201984. png_ptr->pass++;
  201985. }
  201986. else
  201987. {
  201988. /* loop until we find a non-zero width or height pass */
  201989. do
  201990. {
  201991. png_ptr->pass++;
  201992. if (png_ptr->pass >= 7)
  201993. break;
  201994. png_ptr->usr_width = (png_ptr->width +
  201995. png_pass_inc[png_ptr->pass] - 1 -
  201996. png_pass_start[png_ptr->pass]) /
  201997. png_pass_inc[png_ptr->pass];
  201998. png_ptr->num_rows = (png_ptr->height +
  201999. png_pass_yinc[png_ptr->pass] - 1 -
  202000. png_pass_ystart[png_ptr->pass]) /
  202001. png_pass_yinc[png_ptr->pass];
  202002. if (png_ptr->transformations & PNG_INTERLACE)
  202003. break;
  202004. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  202005. }
  202006. /* reset the row above the image for the next pass */
  202007. if (png_ptr->pass < 7)
  202008. {
  202009. if (png_ptr->prev_row != NULL)
  202010. png_memset(png_ptr->prev_row, 0,
  202011. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  202012. png_ptr->usr_bit_depth,png_ptr->width))+1);
  202013. return;
  202014. }
  202015. }
  202016. #endif
  202017. /* if we get here, we've just written the last row, so we need
  202018. to flush the compressor */
  202019. do
  202020. {
  202021. /* tell the compressor we are done */
  202022. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202023. /* check for an error */
  202024. if (ret == Z_OK)
  202025. {
  202026. /* check to see if we need more room */
  202027. if (!(png_ptr->zstream.avail_out))
  202028. {
  202029. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202030. png_ptr->zstream.next_out = png_ptr->zbuf;
  202031. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202032. }
  202033. }
  202034. else if (ret != Z_STREAM_END)
  202035. {
  202036. if (png_ptr->zstream.msg != NULL)
  202037. png_error(png_ptr, png_ptr->zstream.msg);
  202038. else
  202039. png_error(png_ptr, "zlib error");
  202040. }
  202041. } while (ret != Z_STREAM_END);
  202042. /* write any extra space */
  202043. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202044. {
  202045. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202046. png_ptr->zstream.avail_out);
  202047. }
  202048. deflateReset(&png_ptr->zstream);
  202049. png_ptr->zstream.data_type = Z_BINARY;
  202050. }
  202051. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202052. /* Pick out the correct pixels for the interlace pass.
  202053. * The basic idea here is to go through the row with a source
  202054. * pointer and a destination pointer (sp and dp), and copy the
  202055. * correct pixels for the pass. As the row gets compacted,
  202056. * sp will always be >= dp, so we should never overwrite anything.
  202057. * See the default: case for the easiest code to understand.
  202058. */
  202059. void /* PRIVATE */
  202060. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202061. {
  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. #endif
  202069. png_debug(1, "in png_do_write_interlace\n");
  202070. /* we don't have to do anything on the last pass (6) */
  202071. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202072. if (row != NULL && row_info != NULL && pass < 6)
  202073. #else
  202074. if (pass < 6)
  202075. #endif
  202076. {
  202077. /* each pixel depth is handled separately */
  202078. switch (row_info->pixel_depth)
  202079. {
  202080. case 1:
  202081. {
  202082. png_bytep sp;
  202083. png_bytep dp;
  202084. int shift;
  202085. int d;
  202086. int value;
  202087. png_uint_32 i;
  202088. png_uint_32 row_width = row_info->width;
  202089. dp = row;
  202090. d = 0;
  202091. shift = 7;
  202092. for (i = png_pass_start[pass]; i < row_width;
  202093. i += png_pass_inc[pass])
  202094. {
  202095. sp = row + (png_size_t)(i >> 3);
  202096. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202097. d |= (value << shift);
  202098. if (shift == 0)
  202099. {
  202100. shift = 7;
  202101. *dp++ = (png_byte)d;
  202102. d = 0;
  202103. }
  202104. else
  202105. shift--;
  202106. }
  202107. if (shift != 7)
  202108. *dp = (png_byte)d;
  202109. break;
  202110. }
  202111. case 2:
  202112. {
  202113. png_bytep sp;
  202114. png_bytep dp;
  202115. int shift;
  202116. int d;
  202117. int value;
  202118. png_uint_32 i;
  202119. png_uint_32 row_width = row_info->width;
  202120. dp = row;
  202121. shift = 6;
  202122. d = 0;
  202123. for (i = png_pass_start[pass]; i < row_width;
  202124. i += png_pass_inc[pass])
  202125. {
  202126. sp = row + (png_size_t)(i >> 2);
  202127. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202128. d |= (value << shift);
  202129. if (shift == 0)
  202130. {
  202131. shift = 6;
  202132. *dp++ = (png_byte)d;
  202133. d = 0;
  202134. }
  202135. else
  202136. shift -= 2;
  202137. }
  202138. if (shift != 6)
  202139. *dp = (png_byte)d;
  202140. break;
  202141. }
  202142. case 4:
  202143. {
  202144. png_bytep sp;
  202145. png_bytep dp;
  202146. int shift;
  202147. int d;
  202148. int value;
  202149. png_uint_32 i;
  202150. png_uint_32 row_width = row_info->width;
  202151. dp = row;
  202152. shift = 4;
  202153. d = 0;
  202154. for (i = png_pass_start[pass]; i < row_width;
  202155. i += png_pass_inc[pass])
  202156. {
  202157. sp = row + (png_size_t)(i >> 1);
  202158. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202159. d |= (value << shift);
  202160. if (shift == 0)
  202161. {
  202162. shift = 4;
  202163. *dp++ = (png_byte)d;
  202164. d = 0;
  202165. }
  202166. else
  202167. shift -= 4;
  202168. }
  202169. if (shift != 4)
  202170. *dp = (png_byte)d;
  202171. break;
  202172. }
  202173. default:
  202174. {
  202175. png_bytep sp;
  202176. png_bytep dp;
  202177. png_uint_32 i;
  202178. png_uint_32 row_width = row_info->width;
  202179. png_size_t pixel_bytes;
  202180. /* start at the beginning */
  202181. dp = row;
  202182. /* find out how many bytes each pixel takes up */
  202183. pixel_bytes = (row_info->pixel_depth >> 3);
  202184. /* loop through the row, only looking at the pixels that
  202185. matter */
  202186. for (i = png_pass_start[pass]; i < row_width;
  202187. i += png_pass_inc[pass])
  202188. {
  202189. /* find out where the original pixel is */
  202190. sp = row + (png_size_t)i * pixel_bytes;
  202191. /* move the pixel */
  202192. if (dp != sp)
  202193. png_memcpy(dp, sp, pixel_bytes);
  202194. /* next pixel */
  202195. dp += pixel_bytes;
  202196. }
  202197. break;
  202198. }
  202199. }
  202200. /* set new row width */
  202201. row_info->width = (row_info->width +
  202202. png_pass_inc[pass] - 1 -
  202203. png_pass_start[pass]) /
  202204. png_pass_inc[pass];
  202205. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202206. row_info->width);
  202207. }
  202208. }
  202209. #endif
  202210. /* This filters the row, chooses which filter to use, if it has not already
  202211. * been specified by the application, and then writes the row out with the
  202212. * chosen filter.
  202213. */
  202214. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202215. #define PNG_HISHIFT 10
  202216. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202217. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202218. void /* PRIVATE */
  202219. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202220. {
  202221. png_bytep best_row;
  202222. #ifndef PNG_NO_WRITE_FILTER
  202223. png_bytep prev_row, row_buf;
  202224. png_uint_32 mins, bpp;
  202225. png_byte filter_to_do = png_ptr->do_filter;
  202226. png_uint_32 row_bytes = row_info->rowbytes;
  202227. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202228. int num_p_filters = (int)png_ptr->num_prev_filters;
  202229. #endif
  202230. png_debug(1, "in png_write_find_filter\n");
  202231. /* find out how many bytes offset each pixel is */
  202232. bpp = (row_info->pixel_depth + 7) >> 3;
  202233. prev_row = png_ptr->prev_row;
  202234. #endif
  202235. best_row = png_ptr->row_buf;
  202236. #ifndef PNG_NO_WRITE_FILTER
  202237. row_buf = best_row;
  202238. mins = PNG_MAXSUM;
  202239. /* The prediction method we use is to find which method provides the
  202240. * smallest value when summing the absolute values of the distances
  202241. * from zero, using anything >= 128 as negative numbers. This is known
  202242. * as the "minimum sum of absolute differences" heuristic. Other
  202243. * heuristics are the "weighted minimum sum of absolute differences"
  202244. * (experimental and can in theory improve compression), and the "zlib
  202245. * predictive" method (not implemented yet), which does test compressions
  202246. * of lines using different filter methods, and then chooses the
  202247. * (series of) filter(s) that give minimum compressed data size (VERY
  202248. * computationally expensive).
  202249. *
  202250. * GRR 980525: consider also
  202251. * (1) minimum sum of absolute differences from running average (i.e.,
  202252. * keep running sum of non-absolute differences & count of bytes)
  202253. * [track dispersion, too? restart average if dispersion too large?]
  202254. * (1b) minimum sum of absolute differences from sliding average, probably
  202255. * with window size <= deflate window (usually 32K)
  202256. * (2) minimum sum of squared differences from zero or running average
  202257. * (i.e., ~ root-mean-square approach)
  202258. */
  202259. /* We don't need to test the 'no filter' case if this is the only filter
  202260. * that has been chosen, as it doesn't actually do anything to the data.
  202261. */
  202262. if ((filter_to_do & PNG_FILTER_NONE) &&
  202263. filter_to_do != PNG_FILTER_NONE)
  202264. {
  202265. png_bytep rp;
  202266. png_uint_32 sum = 0;
  202267. png_uint_32 i;
  202268. int v;
  202269. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202270. {
  202271. v = *rp;
  202272. sum += (v < 128) ? v : 256 - v;
  202273. }
  202274. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202275. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202276. {
  202277. png_uint_32 sumhi, sumlo;
  202278. int j;
  202279. sumlo = sum & PNG_LOMASK;
  202280. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202281. /* Reduce the sum if we match any of the previous rows */
  202282. for (j = 0; j < num_p_filters; j++)
  202283. {
  202284. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202285. {
  202286. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202287. PNG_WEIGHT_SHIFT;
  202288. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202289. PNG_WEIGHT_SHIFT;
  202290. }
  202291. }
  202292. /* Factor in the cost of this filter (this is here for completeness,
  202293. * but it makes no sense to have a "cost" for the NONE filter, as
  202294. * it has the minimum possible computational cost - none).
  202295. */
  202296. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202297. PNG_COST_SHIFT;
  202298. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202299. PNG_COST_SHIFT;
  202300. if (sumhi > PNG_HIMASK)
  202301. sum = PNG_MAXSUM;
  202302. else
  202303. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202304. }
  202305. #endif
  202306. mins = sum;
  202307. }
  202308. /* sub filter */
  202309. if (filter_to_do == PNG_FILTER_SUB)
  202310. /* it's the only filter so no testing is needed */
  202311. {
  202312. png_bytep rp, lp, dp;
  202313. png_uint_32 i;
  202314. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202315. i++, rp++, dp++)
  202316. {
  202317. *dp = *rp;
  202318. }
  202319. for (lp = row_buf + 1; i < row_bytes;
  202320. i++, rp++, lp++, dp++)
  202321. {
  202322. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202323. }
  202324. best_row = png_ptr->sub_row;
  202325. }
  202326. else if (filter_to_do & PNG_FILTER_SUB)
  202327. {
  202328. png_bytep rp, dp, lp;
  202329. png_uint_32 sum = 0, lmins = mins;
  202330. png_uint_32 i;
  202331. int v;
  202332. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202333. /* We temporarily increase the "minimum sum" by the factor we
  202334. * would reduce the sum of this filter, so that we can do the
  202335. * early exit comparison without scaling the sum each time.
  202336. */
  202337. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202338. {
  202339. int j;
  202340. png_uint_32 lmhi, lmlo;
  202341. lmlo = lmins & PNG_LOMASK;
  202342. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202343. for (j = 0; j < num_p_filters; j++)
  202344. {
  202345. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202346. {
  202347. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202348. PNG_WEIGHT_SHIFT;
  202349. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202350. PNG_WEIGHT_SHIFT;
  202351. }
  202352. }
  202353. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202354. PNG_COST_SHIFT;
  202355. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202356. PNG_COST_SHIFT;
  202357. if (lmhi > PNG_HIMASK)
  202358. lmins = PNG_MAXSUM;
  202359. else
  202360. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202361. }
  202362. #endif
  202363. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202364. i++, rp++, dp++)
  202365. {
  202366. v = *dp = *rp;
  202367. sum += (v < 128) ? v : 256 - v;
  202368. }
  202369. for (lp = row_buf + 1; i < row_bytes;
  202370. i++, rp++, lp++, dp++)
  202371. {
  202372. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202373. sum += (v < 128) ? v : 256 - v;
  202374. if (sum > lmins) /* We are already worse, don't continue. */
  202375. break;
  202376. }
  202377. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202378. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202379. {
  202380. int j;
  202381. png_uint_32 sumhi, sumlo;
  202382. sumlo = sum & PNG_LOMASK;
  202383. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202384. for (j = 0; j < num_p_filters; j++)
  202385. {
  202386. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202387. {
  202388. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202389. PNG_WEIGHT_SHIFT;
  202390. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202391. PNG_WEIGHT_SHIFT;
  202392. }
  202393. }
  202394. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202395. PNG_COST_SHIFT;
  202396. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202397. PNG_COST_SHIFT;
  202398. if (sumhi > PNG_HIMASK)
  202399. sum = PNG_MAXSUM;
  202400. else
  202401. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202402. }
  202403. #endif
  202404. if (sum < mins)
  202405. {
  202406. mins = sum;
  202407. best_row = png_ptr->sub_row;
  202408. }
  202409. }
  202410. /* up filter */
  202411. if (filter_to_do == PNG_FILTER_UP)
  202412. {
  202413. png_bytep rp, dp, pp;
  202414. png_uint_32 i;
  202415. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202416. pp = prev_row + 1; i < row_bytes;
  202417. i++, rp++, pp++, dp++)
  202418. {
  202419. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202420. }
  202421. best_row = png_ptr->up_row;
  202422. }
  202423. else if (filter_to_do & PNG_FILTER_UP)
  202424. {
  202425. png_bytep rp, dp, pp;
  202426. png_uint_32 sum = 0, lmins = mins;
  202427. png_uint_32 i;
  202428. int v;
  202429. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202430. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202431. {
  202432. int j;
  202433. png_uint_32 lmhi, lmlo;
  202434. lmlo = lmins & PNG_LOMASK;
  202435. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202436. for (j = 0; j < num_p_filters; j++)
  202437. {
  202438. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202439. {
  202440. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202441. PNG_WEIGHT_SHIFT;
  202442. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202443. PNG_WEIGHT_SHIFT;
  202444. }
  202445. }
  202446. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202447. PNG_COST_SHIFT;
  202448. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202449. PNG_COST_SHIFT;
  202450. if (lmhi > PNG_HIMASK)
  202451. lmins = PNG_MAXSUM;
  202452. else
  202453. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202454. }
  202455. #endif
  202456. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202457. pp = prev_row + 1; i < row_bytes; i++)
  202458. {
  202459. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202460. sum += (v < 128) ? v : 256 - v;
  202461. if (sum > lmins) /* We are already worse, don't continue. */
  202462. break;
  202463. }
  202464. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202465. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202466. {
  202467. int j;
  202468. png_uint_32 sumhi, sumlo;
  202469. sumlo = sum & PNG_LOMASK;
  202470. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202471. for (j = 0; j < num_p_filters; j++)
  202472. {
  202473. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202474. {
  202475. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202476. PNG_WEIGHT_SHIFT;
  202477. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202478. PNG_WEIGHT_SHIFT;
  202479. }
  202480. }
  202481. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202482. PNG_COST_SHIFT;
  202483. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202484. PNG_COST_SHIFT;
  202485. if (sumhi > PNG_HIMASK)
  202486. sum = PNG_MAXSUM;
  202487. else
  202488. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202489. }
  202490. #endif
  202491. if (sum < mins)
  202492. {
  202493. mins = sum;
  202494. best_row = png_ptr->up_row;
  202495. }
  202496. }
  202497. /* avg filter */
  202498. if (filter_to_do == PNG_FILTER_AVG)
  202499. {
  202500. png_bytep rp, dp, pp, lp;
  202501. png_uint_32 i;
  202502. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202503. pp = prev_row + 1; i < bpp; i++)
  202504. {
  202505. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202506. }
  202507. for (lp = row_buf + 1; i < row_bytes; i++)
  202508. {
  202509. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  202510. & 0xff);
  202511. }
  202512. best_row = png_ptr->avg_row;
  202513. }
  202514. else if (filter_to_do & PNG_FILTER_AVG)
  202515. {
  202516. png_bytep rp, dp, pp, lp;
  202517. png_uint_32 sum = 0, lmins = mins;
  202518. png_uint_32 i;
  202519. int v;
  202520. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202521. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202522. {
  202523. int j;
  202524. png_uint_32 lmhi, lmlo;
  202525. lmlo = lmins & PNG_LOMASK;
  202526. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202527. for (j = 0; j < num_p_filters; j++)
  202528. {
  202529. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  202530. {
  202531. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202532. PNG_WEIGHT_SHIFT;
  202533. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202534. PNG_WEIGHT_SHIFT;
  202535. }
  202536. }
  202537. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202538. PNG_COST_SHIFT;
  202539. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202540. PNG_COST_SHIFT;
  202541. if (lmhi > PNG_HIMASK)
  202542. lmins = PNG_MAXSUM;
  202543. else
  202544. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202545. }
  202546. #endif
  202547. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202548. pp = prev_row + 1; i < bpp; i++)
  202549. {
  202550. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202551. sum += (v < 128) ? v : 256 - v;
  202552. }
  202553. for (lp = row_buf + 1; i < row_bytes; i++)
  202554. {
  202555. v = *dp++ =
  202556. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  202557. sum += (v < 128) ? v : 256 - v;
  202558. if (sum > lmins) /* We are already worse, don't continue. */
  202559. break;
  202560. }
  202561. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202562. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202563. {
  202564. int j;
  202565. png_uint_32 sumhi, sumlo;
  202566. sumlo = sum & PNG_LOMASK;
  202567. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202568. for (j = 0; j < num_p_filters; j++)
  202569. {
  202570. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202571. {
  202572. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202573. PNG_WEIGHT_SHIFT;
  202574. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202575. PNG_WEIGHT_SHIFT;
  202576. }
  202577. }
  202578. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202579. PNG_COST_SHIFT;
  202580. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202581. PNG_COST_SHIFT;
  202582. if (sumhi > PNG_HIMASK)
  202583. sum = PNG_MAXSUM;
  202584. else
  202585. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202586. }
  202587. #endif
  202588. if (sum < mins)
  202589. {
  202590. mins = sum;
  202591. best_row = png_ptr->avg_row;
  202592. }
  202593. }
  202594. /* Paeth filter */
  202595. if (filter_to_do == PNG_FILTER_PAETH)
  202596. {
  202597. png_bytep rp, dp, pp, cp, lp;
  202598. png_uint_32 i;
  202599. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202600. pp = prev_row + 1; i < bpp; i++)
  202601. {
  202602. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202603. }
  202604. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202605. {
  202606. int a, b, c, pa, pb, pc, p;
  202607. b = *pp++;
  202608. c = *cp++;
  202609. a = *lp++;
  202610. p = b - c;
  202611. pc = a - c;
  202612. #ifdef PNG_USE_ABS
  202613. pa = abs(p);
  202614. pb = abs(pc);
  202615. pc = abs(p + pc);
  202616. #else
  202617. pa = p < 0 ? -p : p;
  202618. pb = pc < 0 ? -pc : pc;
  202619. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202620. #endif
  202621. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202622. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202623. }
  202624. best_row = png_ptr->paeth_row;
  202625. }
  202626. else if (filter_to_do & PNG_FILTER_PAETH)
  202627. {
  202628. png_bytep rp, dp, pp, cp, lp;
  202629. png_uint_32 sum = 0, lmins = mins;
  202630. png_uint_32 i;
  202631. int v;
  202632. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202633. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202634. {
  202635. int j;
  202636. png_uint_32 lmhi, lmlo;
  202637. lmlo = lmins & PNG_LOMASK;
  202638. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202639. for (j = 0; j < num_p_filters; j++)
  202640. {
  202641. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202642. {
  202643. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202644. PNG_WEIGHT_SHIFT;
  202645. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202646. PNG_WEIGHT_SHIFT;
  202647. }
  202648. }
  202649. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202650. PNG_COST_SHIFT;
  202651. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202652. PNG_COST_SHIFT;
  202653. if (lmhi > PNG_HIMASK)
  202654. lmins = PNG_MAXSUM;
  202655. else
  202656. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202657. }
  202658. #endif
  202659. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202660. pp = prev_row + 1; i < bpp; i++)
  202661. {
  202662. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202663. sum += (v < 128) ? v : 256 - v;
  202664. }
  202665. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202666. {
  202667. int a, b, c, pa, pb, pc, p;
  202668. b = *pp++;
  202669. c = *cp++;
  202670. a = *lp++;
  202671. #ifndef PNG_SLOW_PAETH
  202672. p = b - c;
  202673. pc = a - c;
  202674. #ifdef PNG_USE_ABS
  202675. pa = abs(p);
  202676. pb = abs(pc);
  202677. pc = abs(p + pc);
  202678. #else
  202679. pa = p < 0 ? -p : p;
  202680. pb = pc < 0 ? -pc : pc;
  202681. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202682. #endif
  202683. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202684. #else /* PNG_SLOW_PAETH */
  202685. p = a + b - c;
  202686. pa = abs(p - a);
  202687. pb = abs(p - b);
  202688. pc = abs(p - c);
  202689. if (pa <= pb && pa <= pc)
  202690. p = a;
  202691. else if (pb <= pc)
  202692. p = b;
  202693. else
  202694. p = c;
  202695. #endif /* PNG_SLOW_PAETH */
  202696. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202697. sum += (v < 128) ? v : 256 - v;
  202698. if (sum > lmins) /* We are already worse, don't continue. */
  202699. break;
  202700. }
  202701. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202702. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202703. {
  202704. int j;
  202705. png_uint_32 sumhi, sumlo;
  202706. sumlo = sum & PNG_LOMASK;
  202707. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202708. for (j = 0; j < num_p_filters; j++)
  202709. {
  202710. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202711. {
  202712. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202713. PNG_WEIGHT_SHIFT;
  202714. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202715. PNG_WEIGHT_SHIFT;
  202716. }
  202717. }
  202718. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202719. PNG_COST_SHIFT;
  202720. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202721. PNG_COST_SHIFT;
  202722. if (sumhi > PNG_HIMASK)
  202723. sum = PNG_MAXSUM;
  202724. else
  202725. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202726. }
  202727. #endif
  202728. if (sum < mins)
  202729. {
  202730. best_row = png_ptr->paeth_row;
  202731. }
  202732. }
  202733. #endif /* PNG_NO_WRITE_FILTER */
  202734. /* Do the actual writing of the filtered row data from the chosen filter. */
  202735. png_write_filtered_row(png_ptr, best_row);
  202736. #ifndef PNG_NO_WRITE_FILTER
  202737. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202738. /* Save the type of filter we picked this time for future calculations */
  202739. if (png_ptr->num_prev_filters > 0)
  202740. {
  202741. int j;
  202742. for (j = 1; j < num_p_filters; j++)
  202743. {
  202744. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  202745. }
  202746. png_ptr->prev_filters[j] = best_row[0];
  202747. }
  202748. #endif
  202749. #endif /* PNG_NO_WRITE_FILTER */
  202750. }
  202751. /* Do the actual writing of a previously filtered row. */
  202752. void /* PRIVATE */
  202753. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  202754. {
  202755. png_debug(1, "in png_write_filtered_row\n");
  202756. png_debug1(2, "filter = %d\n", filtered_row[0]);
  202757. /* set up the zlib input buffer */
  202758. png_ptr->zstream.next_in = filtered_row;
  202759. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  202760. /* repeat until we have compressed all the data */
  202761. do
  202762. {
  202763. int ret; /* return of zlib */
  202764. /* compress the data */
  202765. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  202766. /* check for compression errors */
  202767. if (ret != Z_OK)
  202768. {
  202769. if (png_ptr->zstream.msg != NULL)
  202770. png_error(png_ptr, png_ptr->zstream.msg);
  202771. else
  202772. png_error(png_ptr, "zlib error");
  202773. }
  202774. /* see if it is time to write another IDAT */
  202775. if (!(png_ptr->zstream.avail_out))
  202776. {
  202777. /* write the IDAT and reset the zlib output buffer */
  202778. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202779. png_ptr->zstream.next_out = png_ptr->zbuf;
  202780. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202781. }
  202782. /* repeat until all data has been compressed */
  202783. } while (png_ptr->zstream.avail_in);
  202784. /* swap the current and previous rows */
  202785. if (png_ptr->prev_row != NULL)
  202786. {
  202787. png_bytep tptr;
  202788. tptr = png_ptr->prev_row;
  202789. png_ptr->prev_row = png_ptr->row_buf;
  202790. png_ptr->row_buf = tptr;
  202791. }
  202792. /* finish row - updates counters and flushes zlib if last row */
  202793. png_write_finish_row(png_ptr);
  202794. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  202795. png_ptr->flush_rows++;
  202796. if (png_ptr->flush_dist > 0 &&
  202797. png_ptr->flush_rows >= png_ptr->flush_dist)
  202798. {
  202799. png_write_flush(png_ptr);
  202800. }
  202801. #endif
  202802. }
  202803. #endif /* PNG_WRITE_SUPPORTED */
  202804. /*** End of inlined file: pngwutil.c ***/
  202805. #else
  202806. extern "C"
  202807. {
  202808. #include <png.h>
  202809. #include <pngconf.h>
  202810. }
  202811. #endif
  202812. }
  202813. #undef max
  202814. #undef min
  202815. #if JUCE_MSVC
  202816. #pragma warning (pop)
  202817. #endif
  202818. BEGIN_JUCE_NAMESPACE
  202819. using ::calloc;
  202820. using ::malloc;
  202821. using ::free;
  202822. namespace PNGHelpers
  202823. {
  202824. using namespace pnglibNamespace;
  202825. void JUCE_CDECL readCallback (png_structp png, png_bytep data, png_size_t length)
  202826. {
  202827. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  202828. }
  202829. void JUCE_CDECL writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  202830. {
  202831. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  202832. }
  202833. struct PNGErrorStruct {};
  202834. void JUCE_CDECL errorCallback (png_structp, png_const_charp)
  202835. {
  202836. throw PNGErrorStruct();
  202837. }
  202838. }
  202839. PNGImageFormat::PNGImageFormat() {}
  202840. PNGImageFormat::~PNGImageFormat() {}
  202841. const String PNGImageFormat::getFormatName()
  202842. {
  202843. return "PNG";
  202844. }
  202845. bool PNGImageFormat::canUnderstand (InputStream& in)
  202846. {
  202847. const int bytesNeeded = 4;
  202848. char header [bytesNeeded];
  202849. return in.read (header, bytesNeeded) == bytesNeeded
  202850. && header[1] == 'P'
  202851. && header[2] == 'N'
  202852. && header[3] == 'G';
  202853. }
  202854. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  202855. const Image juce_loadWithCoreImage (InputStream& input);
  202856. #endif
  202857. const Image PNGImageFormat::decodeImage (InputStream& in)
  202858. {
  202859. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  202860. return juce_loadWithCoreImage (in);
  202861. #else
  202862. using namespace pnglibNamespace;
  202863. Image image;
  202864. png_structp pngReadStruct;
  202865. png_infop pngInfoStruct;
  202866. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202867. if (pngReadStruct != 0)
  202868. {
  202869. pngInfoStruct = png_create_info_struct (pngReadStruct);
  202870. if (pngInfoStruct == 0)
  202871. {
  202872. png_destroy_read_struct (&pngReadStruct, 0, 0);
  202873. return Image::null;
  202874. }
  202875. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  202876. // read the header..
  202877. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  202878. png_uint_32 width, height;
  202879. int bitDepth, colorType, interlaceType;
  202880. png_read_info (pngReadStruct, pngInfoStruct);
  202881. png_get_IHDR (pngReadStruct, pngInfoStruct,
  202882. &width, &height,
  202883. &bitDepth, &colorType,
  202884. &interlaceType, 0, 0);
  202885. if (bitDepth == 16)
  202886. png_set_strip_16 (pngReadStruct);
  202887. if (colorType == PNG_COLOR_TYPE_PALETTE)
  202888. png_set_expand (pngReadStruct);
  202889. if (bitDepth < 8)
  202890. png_set_expand (pngReadStruct);
  202891. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  202892. png_set_expand (pngReadStruct);
  202893. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  202894. png_set_gray_to_rgb (pngReadStruct);
  202895. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  202896. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  202897. || pngInfoStruct->num_trans > 0;
  202898. // Load the image into a temp buffer in the pnglib format..
  202899. HeapBlock <uint8> tempBuffer (height * (width << 2));
  202900. {
  202901. HeapBlock <png_bytep> rows (height);
  202902. for (int y = (int) height; --y >= 0;)
  202903. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  202904. png_read_image (pngReadStruct, rows);
  202905. png_read_end (pngReadStruct, pngInfoStruct);
  202906. }
  202907. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  202908. // now convert the data to a juce image format..
  202909. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  202910. (int) width, (int) height, hasAlphaChan);
  202911. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  202912. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  202913. const Image::BitmapData destData (image, true);
  202914. uint8* srcRow = tempBuffer;
  202915. uint8* destRow = destData.data;
  202916. for (int y = 0; y < (int) height; ++y)
  202917. {
  202918. const uint8* src = srcRow;
  202919. srcRow += (width << 2);
  202920. uint8* dest = destRow;
  202921. destRow += destData.lineStride;
  202922. if (hasAlphaChan)
  202923. {
  202924. for (int i = (int) width; --i >= 0;)
  202925. {
  202926. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  202927. ((PixelARGB*) dest)->premultiply();
  202928. dest += destData.pixelStride;
  202929. src += 4;
  202930. }
  202931. }
  202932. else
  202933. {
  202934. for (int i = (int) width; --i >= 0;)
  202935. {
  202936. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  202937. dest += destData.pixelStride;
  202938. src += 4;
  202939. }
  202940. }
  202941. }
  202942. }
  202943. return image;
  202944. #endif
  202945. }
  202946. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  202947. {
  202948. using namespace pnglibNamespace;
  202949. const int width = image.getWidth();
  202950. const int height = image.getHeight();
  202951. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202952. if (pngWriteStruct == 0)
  202953. return false;
  202954. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  202955. if (pngInfoStruct == 0)
  202956. {
  202957. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  202958. return false;
  202959. }
  202960. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  202961. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  202962. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  202963. : PNG_COLOR_TYPE_RGB,
  202964. PNG_INTERLACE_NONE,
  202965. PNG_COMPRESSION_TYPE_BASE,
  202966. PNG_FILTER_TYPE_BASE);
  202967. HeapBlock <uint8> rowData (width * 4);
  202968. png_color_8 sig_bit;
  202969. sig_bit.red = 8;
  202970. sig_bit.green = 8;
  202971. sig_bit.blue = 8;
  202972. sig_bit.alpha = 8;
  202973. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  202974. png_write_info (pngWriteStruct, pngInfoStruct);
  202975. png_set_shift (pngWriteStruct, &sig_bit);
  202976. png_set_packing (pngWriteStruct);
  202977. const Image::BitmapData srcData (image, false);
  202978. for (int y = 0; y < height; ++y)
  202979. {
  202980. uint8* dst = rowData;
  202981. const uint8* src = srcData.getLinePointer (y);
  202982. if (image.hasAlphaChannel())
  202983. {
  202984. for (int i = width; --i >= 0;)
  202985. {
  202986. PixelARGB p (*(const PixelARGB*) src);
  202987. p.unpremultiply();
  202988. *dst++ = p.getRed();
  202989. *dst++ = p.getGreen();
  202990. *dst++ = p.getBlue();
  202991. *dst++ = p.getAlpha();
  202992. src += srcData.pixelStride;
  202993. }
  202994. }
  202995. else
  202996. {
  202997. for (int i = width; --i >= 0;)
  202998. {
  202999. *dst++ = ((const PixelRGB*) src)->getRed();
  203000. *dst++ = ((const PixelRGB*) src)->getGreen();
  203001. *dst++ = ((const PixelRGB*) src)->getBlue();
  203002. src += srcData.pixelStride;
  203003. }
  203004. }
  203005. png_bytep rowPtr = rowData;
  203006. png_write_rows (pngWriteStruct, &rowPtr, 1);
  203007. }
  203008. png_write_end (pngWriteStruct, pngInfoStruct);
  203009. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  203010. out.flush();
  203011. return true;
  203012. }
  203013. END_JUCE_NAMESPACE
  203014. /*** End of inlined file: juce_PNGLoader.cpp ***/
  203015. #endif
  203016. //==============================================================================
  203017. #if JUCE_BUILD_NATIVE
  203018. // Non-public headers that are needed by more than one platform must be included
  203019. // before the platform-specific sections..
  203020. BEGIN_JUCE_NAMESPACE
  203021. /*** Start of inlined file: juce_MidiDataConcatenator.h ***/
  203022. #ifndef __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203023. #define __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203024. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203025. /**
  203026. Helper class that takes chunks of incoming midi bytes, packages them into
  203027. messages, and dispatches them to a midi callback.
  203028. */
  203029. class MidiDataConcatenator
  203030. {
  203031. public:
  203032. MidiDataConcatenator (const int initialBufferSize)
  203033. : pendingData (initialBufferSize),
  203034. pendingBytes (0), pendingDataTime (0)
  203035. {
  203036. }
  203037. void reset()
  203038. {
  203039. pendingBytes = 0;
  203040. pendingDataTime = 0;
  203041. }
  203042. void pushMidiData (const void* data, int numBytes, double time,
  203043. MidiInput* input, MidiInputCallback& callback)
  203044. {
  203045. const uint8* d = static_cast <const uint8*> (data);
  203046. while (numBytes > 0)
  203047. {
  203048. if (pendingBytes > 0 || d[0] == 0xf0)
  203049. {
  203050. processSysex (d, numBytes, time, input, callback);
  203051. }
  203052. else
  203053. {
  203054. int used = 0;
  203055. const MidiMessage m (d, numBytes, used, 0, time);
  203056. if (used <= 0)
  203057. break; // malformed message..
  203058. callback.handleIncomingMidiMessage (input, m);
  203059. numBytes -= used;
  203060. d += used;
  203061. }
  203062. }
  203063. }
  203064. private:
  203065. void processSysex (const uint8*& d, int& numBytes, double time,
  203066. MidiInput* input, MidiInputCallback& callback)
  203067. {
  203068. if (*d == 0xf0)
  203069. {
  203070. pendingBytes = 0;
  203071. pendingDataTime = time;
  203072. }
  203073. pendingData.ensureSize (pendingBytes + numBytes, false);
  203074. uint8* totalMessage = static_cast<uint8*> (pendingData.getData());
  203075. uint8* dest = totalMessage + pendingBytes;
  203076. do
  203077. {
  203078. if (pendingBytes > 0 && *d >= 0x80)
  203079. {
  203080. if (*d >= 0xfa || *d == 0xf8)
  203081. {
  203082. callback.handleIncomingMidiMessage (input, MidiMessage (*d, time));
  203083. ++d;
  203084. --numBytes;
  203085. }
  203086. else
  203087. {
  203088. if (*d == 0xf7)
  203089. {
  203090. *dest++ = *d++;
  203091. pendingBytes++;
  203092. --numBytes;
  203093. }
  203094. break;
  203095. }
  203096. }
  203097. else
  203098. {
  203099. *dest++ = *d++;
  203100. pendingBytes++;
  203101. --numBytes;
  203102. }
  203103. }
  203104. while (numBytes > 0);
  203105. if (pendingBytes > 0)
  203106. {
  203107. if (totalMessage [pendingBytes - 1] == 0xf7)
  203108. {
  203109. callback.handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  203110. pendingBytes = 0;
  203111. }
  203112. else
  203113. {
  203114. callback.handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  203115. }
  203116. }
  203117. }
  203118. MemoryBlock pendingData;
  203119. int pendingBytes;
  203120. double pendingDataTime;
  203121. JUCE_DECLARE_NON_COPYABLE (MidiDataConcatenator);
  203122. };
  203123. #endif
  203124. #endif // __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203125. /*** End of inlined file: juce_MidiDataConcatenator.h ***/
  203126. END_JUCE_NAMESPACE
  203127. #if JUCE_WINDOWS
  203128. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203129. /*
  203130. This file wraps together all the win32-specific code, so that
  203131. we can include all the native headers just once, and compile all our
  203132. platform-specific stuff in one big lump, keeping it out of the way of
  203133. the rest of the codebase.
  203134. */
  203135. #if JUCE_WINDOWS
  203136. #undef JUCE_BUILD_NATIVE
  203137. #define JUCE_BUILD_NATIVE 1
  203138. BEGIN_JUCE_NAMESPACE
  203139. #define JUCE_INCLUDED_FILE 1
  203140. // Now include the actual code files..
  203141. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203142. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203143. // compiled on its own).
  203144. #if JUCE_INCLUDED_FILE
  203145. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203146. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203147. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203148. #ifndef DOXYGEN
  203149. // use with DynamicLibraryLoader to simplify importing functions
  203150. //
  203151. // functionName: function to import
  203152. // localFunctionName: name you want to use to actually call it (must be different)
  203153. // returnType: the return type
  203154. // object: the DynamicLibraryLoader to use
  203155. // params: list of params (bracketed)
  203156. //
  203157. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203158. typedef returnType (WINAPI *type##localFunctionName) params; \
  203159. type##localFunctionName localFunctionName \
  203160. = (type##localFunctionName)object.findProcAddress (#functionName);
  203161. // loads and unloads a DLL automatically
  203162. class JUCE_API DynamicLibraryLoader
  203163. {
  203164. public:
  203165. DynamicLibraryLoader (const String& name = String::empty);
  203166. ~DynamicLibraryLoader();
  203167. bool load (const String& libraryName);
  203168. void* findProcAddress (const String& functionName);
  203169. private:
  203170. void* libHandle;
  203171. };
  203172. #endif
  203173. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203174. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203175. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203176. : libHandle (0)
  203177. {
  203178. load (name);
  203179. }
  203180. DynamicLibraryLoader::~DynamicLibraryLoader()
  203181. {
  203182. load (String::empty);
  203183. }
  203184. bool DynamicLibraryLoader::load (const String& name)
  203185. {
  203186. FreeLibrary ((HMODULE) libHandle);
  203187. libHandle = name.isNotEmpty() ? LoadLibrary (name.toUTF16()) : 0;
  203188. return libHandle != 0;
  203189. }
  203190. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203191. {
  203192. return (void*) GetProcAddress ((HMODULE) libHandle, functionName.toUTF8()); // (void* cast is required for mingw)
  203193. }
  203194. #endif
  203195. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203196. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203197. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203198. // compiled on its own).
  203199. #if JUCE_INCLUDED_FILE
  203200. void Logger::outputDebugString (const String& text)
  203201. {
  203202. OutputDebugString ((text + "\n").toUTF16());
  203203. }
  203204. static int64 hiResTicksPerSecond;
  203205. static double hiResTicksScaleFactor;
  203206. #if JUCE_USE_INTRINSICS
  203207. // CPU info functions using intrinsics...
  203208. #pragma intrinsic (__cpuid)
  203209. #pragma intrinsic (__rdtsc)
  203210. const String SystemStats::getCpuVendor()
  203211. {
  203212. int info [4];
  203213. __cpuid (info, 0);
  203214. char v [12];
  203215. memcpy (v, info + 1, 4);
  203216. memcpy (v + 4, info + 3, 4);
  203217. memcpy (v + 8, info + 2, 4);
  203218. return String (v, 12);
  203219. }
  203220. #else
  203221. // CPU info functions using old fashioned inline asm...
  203222. static void juce_getCpuVendor (char* const v)
  203223. {
  203224. int vendor[4];
  203225. zeromem (vendor, 16);
  203226. #ifdef JUCE_64BIT
  203227. #else
  203228. #ifndef __MINGW32__
  203229. __try
  203230. #endif
  203231. {
  203232. #if JUCE_GCC
  203233. unsigned int dummy = 0;
  203234. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203235. #else
  203236. __asm
  203237. {
  203238. mov eax, 0
  203239. cpuid
  203240. mov [vendor], ebx
  203241. mov [vendor + 4], edx
  203242. mov [vendor + 8], ecx
  203243. }
  203244. #endif
  203245. }
  203246. #ifndef __MINGW32__
  203247. __except (EXCEPTION_EXECUTE_HANDLER)
  203248. {
  203249. *v = 0;
  203250. }
  203251. #endif
  203252. #endif
  203253. memcpy (v, vendor, 16);
  203254. }
  203255. const String SystemStats::getCpuVendor()
  203256. {
  203257. char v [16];
  203258. juce_getCpuVendor (v);
  203259. return String (v, 16);
  203260. }
  203261. #endif
  203262. void SystemStats::initialiseStats()
  203263. {
  203264. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203265. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203266. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203267. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203268. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203269. #else
  203270. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203271. #endif
  203272. {
  203273. SYSTEM_INFO systemInfo;
  203274. GetSystemInfo (&systemInfo);
  203275. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203276. }
  203277. LARGE_INTEGER f;
  203278. QueryPerformanceFrequency (&f);
  203279. hiResTicksPerSecond = f.QuadPart;
  203280. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203281. String s (SystemStats::getJUCEVersion());
  203282. const MMRESULT res = timeBeginPeriod (1);
  203283. (void) res;
  203284. jassert (res == TIMERR_NOERROR);
  203285. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203286. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203287. #endif
  203288. }
  203289. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203290. {
  203291. OSVERSIONINFO info;
  203292. info.dwOSVersionInfoSize = sizeof (info);
  203293. GetVersionEx (&info);
  203294. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203295. {
  203296. switch (info.dwMajorVersion)
  203297. {
  203298. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203299. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203300. default: jassertfalse; break; // !! not a supported OS!
  203301. }
  203302. }
  203303. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203304. {
  203305. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203306. return Win98;
  203307. }
  203308. return UnknownOS;
  203309. }
  203310. const String SystemStats::getOperatingSystemName()
  203311. {
  203312. const char* name = "Unknown OS";
  203313. switch (getOperatingSystemType())
  203314. {
  203315. case Windows7: name = "Windows 7"; break;
  203316. case WinVista: name = "Windows Vista"; break;
  203317. case WinXP: name = "Windows XP"; break;
  203318. case Win2000: name = "Windows 2000"; break;
  203319. case Win98: name = "Windows 98"; break;
  203320. default: jassertfalse; break; // !! new type of OS?
  203321. }
  203322. return name;
  203323. }
  203324. bool SystemStats::isOperatingSystem64Bit()
  203325. {
  203326. #ifdef _WIN64
  203327. return true;
  203328. #else
  203329. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203330. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203331. BOOL isWow64 = FALSE;
  203332. return (fnIsWow64Process != 0)
  203333. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203334. && (isWow64 != FALSE);
  203335. #endif
  203336. }
  203337. int SystemStats::getMemorySizeInMegabytes()
  203338. {
  203339. MEMORYSTATUSEX mem;
  203340. mem.dwLength = sizeof (mem);
  203341. GlobalMemoryStatusEx (&mem);
  203342. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203343. }
  203344. uint32 juce_millisecondsSinceStartup() throw()
  203345. {
  203346. return (uint32) timeGetTime();
  203347. }
  203348. int64 Time::getHighResolutionTicks() throw()
  203349. {
  203350. LARGE_INTEGER ticks;
  203351. QueryPerformanceCounter (&ticks);
  203352. const int64 mainCounterAsHiResTicks = (juce_millisecondsSinceStartup() * hiResTicksPerSecond) / 1000;
  203353. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203354. // fix for a very obscure PCI hardware bug that can make the counter
  203355. // sometimes jump forwards by a few seconds..
  203356. static int64 hiResTicksOffset = 0;
  203357. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203358. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203359. hiResTicksOffset = newOffset;
  203360. return ticks.QuadPart + hiResTicksOffset;
  203361. }
  203362. double Time::getMillisecondCounterHiRes() throw()
  203363. {
  203364. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203365. }
  203366. int64 Time::getHighResolutionTicksPerSecond() throw()
  203367. {
  203368. return hiResTicksPerSecond;
  203369. }
  203370. static int64 juce_getClockCycleCounter() throw()
  203371. {
  203372. #if JUCE_USE_INTRINSICS
  203373. // MS intrinsics version...
  203374. return __rdtsc();
  203375. #elif JUCE_GCC
  203376. // GNU inline asm version...
  203377. unsigned int hi = 0, lo = 0;
  203378. __asm__ __volatile__ (
  203379. "xor %%eax, %%eax \n\
  203380. xor %%edx, %%edx \n\
  203381. rdtsc \n\
  203382. movl %%eax, %[lo] \n\
  203383. movl %%edx, %[hi]"
  203384. :
  203385. : [hi] "m" (hi),
  203386. [lo] "m" (lo)
  203387. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203388. return (int64) ((((uint64) hi) << 32) | lo);
  203389. #else
  203390. // MSVC inline asm version...
  203391. unsigned int hi = 0, lo = 0;
  203392. __asm
  203393. {
  203394. xor eax, eax
  203395. xor edx, edx
  203396. rdtsc
  203397. mov lo, eax
  203398. mov hi, edx
  203399. }
  203400. return (int64) ((((uint64) hi) << 32) | lo);
  203401. #endif
  203402. }
  203403. int SystemStats::getCpuSpeedInMegaherz()
  203404. {
  203405. const int64 cycles = juce_getClockCycleCounter();
  203406. const uint32 millis = Time::getMillisecondCounter();
  203407. int lastResult = 0;
  203408. for (;;)
  203409. {
  203410. int n = 1000000;
  203411. while (--n > 0) {}
  203412. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203413. const int64 cyclesNow = juce_getClockCycleCounter();
  203414. if (millisElapsed > 80)
  203415. {
  203416. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203417. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203418. return newResult;
  203419. lastResult = newResult;
  203420. }
  203421. }
  203422. }
  203423. bool Time::setSystemTimeToThisTime() const
  203424. {
  203425. SYSTEMTIME st;
  203426. st.wDayOfWeek = 0;
  203427. st.wYear = (WORD) getYear();
  203428. st.wMonth = (WORD) (getMonth() + 1);
  203429. st.wDay = (WORD) getDayOfMonth();
  203430. st.wHour = (WORD) getHours();
  203431. st.wMinute = (WORD) getMinutes();
  203432. st.wSecond = (WORD) getSeconds();
  203433. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203434. // do this twice because of daylight saving conversion problems - the
  203435. // first one sets it up, the second one kicks it in.
  203436. return SetLocalTime (&st) != 0
  203437. && SetLocalTime (&st) != 0;
  203438. }
  203439. int SystemStats::getPageSize()
  203440. {
  203441. SYSTEM_INFO systemInfo;
  203442. GetSystemInfo (&systemInfo);
  203443. return systemInfo.dwPageSize;
  203444. }
  203445. const String SystemStats::getLogonName()
  203446. {
  203447. TCHAR text [256];
  203448. DWORD len = numElementsInArray (text) - 2;
  203449. zerostruct (text);
  203450. GetUserName (text, &len);
  203451. return String (text, len);
  203452. }
  203453. const String SystemStats::getFullUserName()
  203454. {
  203455. return getLogonName();
  203456. }
  203457. #endif
  203458. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203459. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203460. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203461. // compiled on its own).
  203462. #if JUCE_INCLUDED_FILE
  203463. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203464. extern HWND juce_messageWindowHandle;
  203465. #endif
  203466. #if ! JUCE_USE_INTRINSICS
  203467. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203468. // older ones we have to actually call the ops as win32 functions..
  203469. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203470. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203471. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203472. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203473. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203474. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203475. {
  203476. jassertfalse; // This operation isn't available in old MS compiler versions!
  203477. __int64 oldValue = *value;
  203478. if (oldValue == valueToCompare)
  203479. *value = newValue;
  203480. return oldValue;
  203481. }
  203482. #endif
  203483. CriticalSection::CriticalSection() throw()
  203484. {
  203485. // (just to check the MS haven't changed this structure and broken things...)
  203486. #if JUCE_VC7_OR_EARLIER
  203487. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203488. #else
  203489. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203490. #endif
  203491. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  203492. }
  203493. CriticalSection::~CriticalSection() throw()
  203494. {
  203495. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  203496. }
  203497. void CriticalSection::enter() const throw()
  203498. {
  203499. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  203500. }
  203501. bool CriticalSection::tryEnter() const throw()
  203502. {
  203503. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  203504. }
  203505. void CriticalSection::exit() const throw()
  203506. {
  203507. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  203508. }
  203509. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  203510. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  203511. {
  203512. }
  203513. WaitableEvent::~WaitableEvent() throw()
  203514. {
  203515. CloseHandle (internal);
  203516. }
  203517. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  203518. {
  203519. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  203520. }
  203521. void WaitableEvent::signal() const throw()
  203522. {
  203523. SetEvent (internal);
  203524. }
  203525. void WaitableEvent::reset() const throw()
  203526. {
  203527. ResetEvent (internal);
  203528. }
  203529. void JUCE_API juce_threadEntryPoint (void*);
  203530. static unsigned int __stdcall threadEntryProc (void* userData)
  203531. {
  203532. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203533. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  203534. GetCurrentThreadId(), TRUE);
  203535. #endif
  203536. juce_threadEntryPoint (userData);
  203537. _endthreadex (0);
  203538. return 0;
  203539. }
  203540. void Thread::launchThread()
  203541. {
  203542. unsigned int newThreadId;
  203543. threadHandle_ = (void*) _beginthreadex (0, 0, &threadEntryProc, this, 0, &newThreadId);
  203544. threadId_ = (ThreadID) newThreadId;
  203545. }
  203546. void Thread::closeThreadHandle()
  203547. {
  203548. CloseHandle ((HANDLE) threadHandle_);
  203549. threadId_ = 0;
  203550. threadHandle_ = 0;
  203551. }
  203552. void Thread::killThread()
  203553. {
  203554. if (threadHandle_ != 0)
  203555. {
  203556. #if JUCE_DEBUG
  203557. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  203558. #endif
  203559. TerminateThread (threadHandle_, 0);
  203560. }
  203561. }
  203562. void Thread::setCurrentThreadName (const String& name)
  203563. {
  203564. #if JUCE_DEBUG && JUCE_MSVC
  203565. struct
  203566. {
  203567. DWORD dwType;
  203568. LPCSTR szName;
  203569. DWORD dwThreadID;
  203570. DWORD dwFlags;
  203571. } info;
  203572. info.dwType = 0x1000;
  203573. info.szName = name.toCString();
  203574. info.dwThreadID = GetCurrentThreadId();
  203575. info.dwFlags = 0;
  203576. __try
  203577. {
  203578. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  203579. }
  203580. __except (EXCEPTION_CONTINUE_EXECUTION)
  203581. {}
  203582. #else
  203583. (void) name;
  203584. #endif
  203585. }
  203586. Thread::ThreadID Thread::getCurrentThreadId()
  203587. {
  203588. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  203589. }
  203590. bool Thread::setThreadPriority (void* handle, int priority)
  203591. {
  203592. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  203593. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  203594. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  203595. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  203596. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  203597. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  203598. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  203599. if (handle == 0)
  203600. handle = GetCurrentThread();
  203601. return SetThreadPriority (handle, pri) != FALSE;
  203602. }
  203603. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  203604. {
  203605. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  203606. }
  203607. struct SleepEvent
  203608. {
  203609. SleepEvent()
  203610. : handle (CreateEvent (0, 0, 0,
  203611. #if JUCE_DEBUG
  203612. _T("Juce Sleep Event")))
  203613. #else
  203614. 0))
  203615. #endif
  203616. {
  203617. }
  203618. HANDLE handle;
  203619. };
  203620. static SleepEvent sleepEvent;
  203621. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  203622. {
  203623. if (millisecs >= 10)
  203624. {
  203625. Sleep (millisecs);
  203626. }
  203627. else
  203628. {
  203629. // unlike Sleep() this is guaranteed to return to the current thread after
  203630. // the time expires, so we'll use this for short waits, which are more likely
  203631. // to need to be accurate
  203632. WaitForSingleObject (sleepEvent.handle, millisecs);
  203633. }
  203634. }
  203635. void Thread::yield()
  203636. {
  203637. Sleep (0);
  203638. }
  203639. static int lastProcessPriority = -1;
  203640. // called by WindowDriver because Windows does wierd things to process priority
  203641. // when you swap apps, and this forces an update when the app is brought to the front.
  203642. void juce_repeatLastProcessPriority()
  203643. {
  203644. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  203645. {
  203646. DWORD p;
  203647. switch (lastProcessPriority)
  203648. {
  203649. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  203650. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  203651. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  203652. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  203653. default: jassertfalse; return; // bad priority value
  203654. }
  203655. SetPriorityClass (GetCurrentProcess(), p);
  203656. }
  203657. }
  203658. void Process::setPriority (ProcessPriority prior)
  203659. {
  203660. if (lastProcessPriority != (int) prior)
  203661. {
  203662. lastProcessPriority = (int) prior;
  203663. juce_repeatLastProcessPriority();
  203664. }
  203665. }
  203666. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  203667. {
  203668. return IsDebuggerPresent() != FALSE;
  203669. }
  203670. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  203671. {
  203672. return juce_isRunningUnderDebugger();
  203673. }
  203674. void Process::raisePrivilege()
  203675. {
  203676. jassertfalse; // xxx not implemented
  203677. }
  203678. void Process::lowerPrivilege()
  203679. {
  203680. jassertfalse; // xxx not implemented
  203681. }
  203682. void Process::terminate()
  203683. {
  203684. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203685. _CrtDumpMemoryLeaks();
  203686. #endif
  203687. // bullet in the head in case there's a problem shutting down..
  203688. ExitProcess (0);
  203689. }
  203690. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  203691. {
  203692. void* result = 0;
  203693. JUCE_TRY
  203694. {
  203695. result = LoadLibrary (name.toUTF16());
  203696. }
  203697. JUCE_CATCH_ALL
  203698. return result;
  203699. }
  203700. void PlatformUtilities::freeDynamicLibrary (void* h)
  203701. {
  203702. JUCE_TRY
  203703. {
  203704. if (h != 0)
  203705. FreeLibrary ((HMODULE) h);
  203706. }
  203707. JUCE_CATCH_ALL
  203708. }
  203709. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  203710. {
  203711. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name.toCString()) : 0; // (void* cast is required for mingw)
  203712. }
  203713. class InterProcessLock::Pimpl
  203714. {
  203715. public:
  203716. Pimpl (const String& name, const int timeOutMillisecs)
  203717. : handle (0), refCount (1)
  203718. {
  203719. handle = CreateMutex (0, TRUE, ("Global\\" + name.replaceCharacter ('\\','/')).toUTF16());
  203720. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  203721. {
  203722. if (timeOutMillisecs == 0)
  203723. {
  203724. close();
  203725. return;
  203726. }
  203727. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  203728. {
  203729. case WAIT_OBJECT_0:
  203730. case WAIT_ABANDONED:
  203731. break;
  203732. case WAIT_TIMEOUT:
  203733. default:
  203734. close();
  203735. break;
  203736. }
  203737. }
  203738. }
  203739. ~Pimpl()
  203740. {
  203741. close();
  203742. }
  203743. void close()
  203744. {
  203745. if (handle != 0)
  203746. {
  203747. ReleaseMutex (handle);
  203748. CloseHandle (handle);
  203749. handle = 0;
  203750. }
  203751. }
  203752. HANDLE handle;
  203753. int refCount;
  203754. };
  203755. InterProcessLock::InterProcessLock (const String& name_)
  203756. : name (name_)
  203757. {
  203758. }
  203759. InterProcessLock::~InterProcessLock()
  203760. {
  203761. }
  203762. bool InterProcessLock::enter (const int timeOutMillisecs)
  203763. {
  203764. const ScopedLock sl (lock);
  203765. if (pimpl == 0)
  203766. {
  203767. pimpl = new Pimpl (name, timeOutMillisecs);
  203768. if (pimpl->handle == 0)
  203769. pimpl = 0;
  203770. }
  203771. else
  203772. {
  203773. pimpl->refCount++;
  203774. }
  203775. return pimpl != 0;
  203776. }
  203777. void InterProcessLock::exit()
  203778. {
  203779. const ScopedLock sl (lock);
  203780. // Trying to release the lock too many times!
  203781. jassert (pimpl != 0);
  203782. if (pimpl != 0 && --(pimpl->refCount) == 0)
  203783. pimpl = 0;
  203784. }
  203785. #endif
  203786. /*** End of inlined file: juce_win32_Threads.cpp ***/
  203787. /*** Start of inlined file: juce_win32_Files.cpp ***/
  203788. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203789. // compiled on its own).
  203790. #if JUCE_INCLUDED_FILE
  203791. #ifndef CSIDL_MYMUSIC
  203792. #define CSIDL_MYMUSIC 0x000d
  203793. #endif
  203794. #ifndef CSIDL_MYVIDEO
  203795. #define CSIDL_MYVIDEO 0x000e
  203796. #endif
  203797. #ifndef INVALID_FILE_ATTRIBUTES
  203798. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  203799. #endif
  203800. namespace WindowsFileHelpers
  203801. {
  203802. int64 fileTimeToTime (const FILETIME* const ft)
  203803. {
  203804. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  203805. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  203806. }
  203807. void timeToFileTime (const int64 time, FILETIME* const ft)
  203808. {
  203809. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  203810. }
  203811. const String getDriveFromPath (String path)
  203812. {
  203813. WCHAR* p = const_cast <WCHAR*> (path.toUTF16().getAddress());
  203814. if (PathStripToRoot (p))
  203815. return String ((const WCHAR*) p);
  203816. return path;
  203817. }
  203818. int64 getDiskSpaceInfo (const String& path, const bool total)
  203819. {
  203820. ULARGE_INTEGER spc, tot, totFree;
  203821. if (GetDiskFreeSpaceEx (getDriveFromPath (path).toUTF16(), &spc, &tot, &totFree))
  203822. return total ? (int64) tot.QuadPart
  203823. : (int64) spc.QuadPart;
  203824. return 0;
  203825. }
  203826. unsigned int getWindowsDriveType (const String& path)
  203827. {
  203828. return GetDriveType (getDriveFromPath (path).toUTF16());
  203829. }
  203830. const File getSpecialFolderPath (int type)
  203831. {
  203832. WCHAR path [MAX_PATH + 256];
  203833. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  203834. return File (String (path));
  203835. return File::nonexistent;
  203836. }
  203837. }
  203838. const juce_wchar File::separator = '\\';
  203839. const String File::separatorString ("\\");
  203840. bool File::exists() const
  203841. {
  203842. return fullPath.isNotEmpty()
  203843. && GetFileAttributes (fullPath.toUTF16()) != INVALID_FILE_ATTRIBUTES;
  203844. }
  203845. bool File::existsAsFile() const
  203846. {
  203847. return fullPath.isNotEmpty()
  203848. && (GetFileAttributes (fullPath.toUTF16()) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  203849. }
  203850. bool File::isDirectory() const
  203851. {
  203852. const DWORD attr = GetFileAttributes (fullPath.toUTF16());
  203853. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  203854. }
  203855. bool File::hasWriteAccess() const
  203856. {
  203857. if (exists())
  203858. return (GetFileAttributes (fullPath.toUTF16()) & FILE_ATTRIBUTE_READONLY) == 0;
  203859. // on windows, it seems that even read-only directories can still be written into,
  203860. // so checking the parent directory's permissions would return the wrong result..
  203861. return true;
  203862. }
  203863. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  203864. {
  203865. DWORD attr = GetFileAttributes (fullPath.toUTF16());
  203866. if (attr == INVALID_FILE_ATTRIBUTES)
  203867. return false;
  203868. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  203869. return true;
  203870. if (shouldBeReadOnly)
  203871. attr |= FILE_ATTRIBUTE_READONLY;
  203872. else
  203873. attr &= ~FILE_ATTRIBUTE_READONLY;
  203874. return SetFileAttributes (fullPath.toUTF16(), attr) != FALSE;
  203875. }
  203876. bool File::isHidden() const
  203877. {
  203878. return (GetFileAttributes (getFullPathName().toUTF16()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  203879. }
  203880. bool File::deleteFile() const
  203881. {
  203882. if (! exists())
  203883. return true;
  203884. else if (isDirectory())
  203885. return RemoveDirectory (fullPath.toUTF16()) != 0;
  203886. else
  203887. return DeleteFile (fullPath.toUTF16()) != 0;
  203888. }
  203889. bool File::moveToTrash() const
  203890. {
  203891. if (! exists())
  203892. return true;
  203893. SHFILEOPSTRUCT fos;
  203894. zerostruct (fos);
  203895. // The string we pass in must be double null terminated..
  203896. String doubleNullTermPath (getFullPathName() + " ");
  203897. WCHAR* const p = const_cast <WCHAR*> (doubleNullTermPath.toUTF16().getAddress());
  203898. p [getFullPathName().length()] = 0;
  203899. fos.wFunc = FO_DELETE;
  203900. fos.pFrom = p;
  203901. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  203902. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  203903. return SHFileOperation (&fos) == 0;
  203904. }
  203905. bool File::copyInternal (const File& dest) const
  203906. {
  203907. return CopyFile (fullPath.toUTF16(), dest.getFullPathName().toUTF16(), false) != 0;
  203908. }
  203909. bool File::moveInternal (const File& dest) const
  203910. {
  203911. return MoveFile (fullPath.toUTF16(), dest.getFullPathName().toUTF16()) != 0;
  203912. }
  203913. void File::createDirectoryInternal (const String& fileName) const
  203914. {
  203915. CreateDirectory (fileName.toUTF16(), 0);
  203916. }
  203917. int64 juce_fileSetPosition (void* handle, int64 pos)
  203918. {
  203919. LARGE_INTEGER li;
  203920. li.QuadPart = pos;
  203921. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  203922. return li.QuadPart;
  203923. }
  203924. void FileInputStream::openHandle()
  203925. {
  203926. totalSize = file.getSize();
  203927. HANDLE h = CreateFile (file.getFullPathName().toUTF16(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  203928. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  203929. if (h != INVALID_HANDLE_VALUE)
  203930. fileHandle = (void*) h;
  203931. }
  203932. void FileInputStream::closeHandle()
  203933. {
  203934. CloseHandle ((HANDLE) fileHandle);
  203935. }
  203936. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  203937. {
  203938. if (fileHandle != 0)
  203939. {
  203940. DWORD actualNum = 0;
  203941. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  203942. return (size_t) actualNum;
  203943. }
  203944. return 0;
  203945. }
  203946. void FileOutputStream::openHandle()
  203947. {
  203948. HANDLE h = CreateFile (file.getFullPathName().toUTF16(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  203949. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  203950. if (h != INVALID_HANDLE_VALUE)
  203951. {
  203952. LARGE_INTEGER li;
  203953. li.QuadPart = 0;
  203954. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  203955. if (li.LowPart != INVALID_SET_FILE_POINTER)
  203956. {
  203957. fileHandle = (void*) h;
  203958. currentPosition = li.QuadPart;
  203959. }
  203960. }
  203961. }
  203962. void FileOutputStream::closeHandle()
  203963. {
  203964. CloseHandle ((HANDLE) fileHandle);
  203965. }
  203966. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  203967. {
  203968. if (fileHandle != 0)
  203969. {
  203970. DWORD actualNum = 0;
  203971. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  203972. return (int) actualNum;
  203973. }
  203974. return 0;
  203975. }
  203976. void FileOutputStream::flushInternal()
  203977. {
  203978. if (fileHandle != 0)
  203979. FlushFileBuffers ((HANDLE) fileHandle);
  203980. }
  203981. int64 File::getSize() const
  203982. {
  203983. WIN32_FILE_ATTRIBUTE_DATA attributes;
  203984. if (GetFileAttributesEx (fullPath.toUTF16(), GetFileExInfoStandard, &attributes))
  203985. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  203986. return 0;
  203987. }
  203988. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  203989. {
  203990. using namespace WindowsFileHelpers;
  203991. WIN32_FILE_ATTRIBUTE_DATA attributes;
  203992. if (GetFileAttributesEx (fullPath.toUTF16(), GetFileExInfoStandard, &attributes))
  203993. {
  203994. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  203995. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  203996. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  203997. }
  203998. else
  203999. {
  204000. creationTime = accessTime = modificationTime = 0;
  204001. }
  204002. }
  204003. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  204004. {
  204005. using namespace WindowsFileHelpers;
  204006. bool ok = false;
  204007. HANDLE h = CreateFile (fullPath.toUTF16(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204008. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204009. if (h != INVALID_HANDLE_VALUE)
  204010. {
  204011. FILETIME m, a, c;
  204012. timeToFileTime (modificationTime, &m);
  204013. timeToFileTime (accessTime, &a);
  204014. timeToFileTime (creationTime, &c);
  204015. ok = SetFileTime (h,
  204016. creationTime > 0 ? &c : 0,
  204017. accessTime > 0 ? &a : 0,
  204018. modificationTime > 0 ? &m : 0) != 0;
  204019. CloseHandle (h);
  204020. }
  204021. return ok;
  204022. }
  204023. void File::findFileSystemRoots (Array<File>& destArray)
  204024. {
  204025. TCHAR buffer [2048];
  204026. buffer[0] = 0;
  204027. buffer[1] = 0;
  204028. GetLogicalDriveStrings (2048, buffer);
  204029. const TCHAR* n = buffer;
  204030. StringArray roots;
  204031. while (*n != 0)
  204032. {
  204033. roots.add (String (n));
  204034. while (*n++ != 0)
  204035. {}
  204036. }
  204037. roots.sort (true);
  204038. for (int i = 0; i < roots.size(); ++i)
  204039. destArray.add (roots [i]);
  204040. }
  204041. const String File::getVolumeLabel() const
  204042. {
  204043. TCHAR dest[64];
  204044. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()).toUTF16(), dest,
  204045. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204046. dest[0] = 0;
  204047. return dest;
  204048. }
  204049. int File::getVolumeSerialNumber() const
  204050. {
  204051. TCHAR dest[64];
  204052. DWORD serialNum;
  204053. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()).toUTF16(), dest,
  204054. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204055. return 0;
  204056. return (int) serialNum;
  204057. }
  204058. int64 File::getBytesFreeOnVolume() const
  204059. {
  204060. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), false);
  204061. }
  204062. int64 File::getVolumeTotalSize() const
  204063. {
  204064. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), true);
  204065. }
  204066. bool File::isOnCDRomDrive() const
  204067. {
  204068. return WindowsFileHelpers::getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204069. }
  204070. bool File::isOnHardDisk() const
  204071. {
  204072. if (fullPath.isEmpty())
  204073. return false;
  204074. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204075. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204076. return n != DRIVE_REMOVABLE;
  204077. else
  204078. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204079. }
  204080. bool File::isOnRemovableDrive() const
  204081. {
  204082. if (fullPath.isEmpty())
  204083. return false;
  204084. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204085. return n == DRIVE_CDROM
  204086. || n == DRIVE_REMOTE
  204087. || n == DRIVE_REMOVABLE
  204088. || n == DRIVE_RAMDISK;
  204089. }
  204090. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204091. {
  204092. int csidlType = 0;
  204093. switch (type)
  204094. {
  204095. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204096. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204097. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204098. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204099. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204100. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204101. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204102. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204103. case tempDirectory:
  204104. {
  204105. WCHAR dest [2048];
  204106. dest[0] = 0;
  204107. GetTempPath (numElementsInArray (dest), dest);
  204108. return File (String (dest));
  204109. }
  204110. case invokedExecutableFile:
  204111. case currentExecutableFile:
  204112. case currentApplicationFile:
  204113. {
  204114. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204115. WCHAR dest [MAX_PATH + 256];
  204116. dest[0] = 0;
  204117. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204118. return File (String (dest));
  204119. }
  204120. case hostApplicationPath:
  204121. {
  204122. WCHAR dest [MAX_PATH + 256];
  204123. dest[0] = 0;
  204124. GetModuleFileName (0, dest, numElementsInArray (dest));
  204125. return File (String (dest));
  204126. }
  204127. default:
  204128. jassertfalse; // unknown type?
  204129. return File::nonexistent;
  204130. }
  204131. return WindowsFileHelpers::getSpecialFolderPath (csidlType);
  204132. }
  204133. const File File::getCurrentWorkingDirectory()
  204134. {
  204135. WCHAR dest [MAX_PATH + 256];
  204136. dest[0] = 0;
  204137. GetCurrentDirectory (numElementsInArray (dest), dest);
  204138. return File (String (dest));
  204139. }
  204140. bool File::setAsCurrentWorkingDirectory() const
  204141. {
  204142. return SetCurrentDirectory (getFullPathName().toUTF16()) != FALSE;
  204143. }
  204144. const String File::getVersion() const
  204145. {
  204146. String result;
  204147. DWORD handle = 0;
  204148. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName().toUTF16(), &handle);
  204149. HeapBlock<char> buffer;
  204150. buffer.calloc (bufferSize);
  204151. if (GetFileVersionInfo (getFullPathName().toUTF16(), 0, bufferSize, buffer))
  204152. {
  204153. VS_FIXEDFILEINFO* vffi;
  204154. UINT len = 0;
  204155. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204156. {
  204157. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204158. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204159. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204160. << (int) LOWORD (vffi->dwFileVersionLS);
  204161. }
  204162. }
  204163. return result;
  204164. }
  204165. const File File::getLinkedTarget() const
  204166. {
  204167. File result (*this);
  204168. String p (getFullPathName());
  204169. if (! exists())
  204170. p += ".lnk";
  204171. else if (getFileExtension() != ".lnk")
  204172. return result;
  204173. ComSmartPtr <IShellLink> shellLink;
  204174. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204175. {
  204176. ComSmartPtr <IPersistFile> persistFile;
  204177. if (SUCCEEDED (shellLink.QueryInterface (IID_IPersistFile, persistFile)))
  204178. {
  204179. if (SUCCEEDED (persistFile->Load (p.toUTF16(), STGM_READ))
  204180. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204181. {
  204182. WIN32_FIND_DATA winFindData;
  204183. WCHAR resolvedPath [MAX_PATH];
  204184. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204185. result = File (resolvedPath);
  204186. }
  204187. }
  204188. }
  204189. return result;
  204190. }
  204191. class DirectoryIterator::NativeIterator::Pimpl
  204192. {
  204193. public:
  204194. Pimpl (const File& directory, const String& wildCard)
  204195. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204196. handle (INVALID_HANDLE_VALUE)
  204197. {
  204198. }
  204199. ~Pimpl()
  204200. {
  204201. if (handle != INVALID_HANDLE_VALUE)
  204202. FindClose (handle);
  204203. }
  204204. bool next (String& filenameFound,
  204205. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204206. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204207. {
  204208. using namespace WindowsFileHelpers;
  204209. WIN32_FIND_DATA findData;
  204210. if (handle == INVALID_HANDLE_VALUE)
  204211. {
  204212. handle = FindFirstFile (directoryWithWildCard.toUTF16(), &findData);
  204213. if (handle == INVALID_HANDLE_VALUE)
  204214. return false;
  204215. }
  204216. else
  204217. {
  204218. if (FindNextFile (handle, &findData) == 0)
  204219. return false;
  204220. }
  204221. filenameFound = findData.cFileName;
  204222. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204223. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204224. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204225. if (modTime != 0) *modTime = Time (fileTimeToTime (&findData.ftLastWriteTime));
  204226. if (creationTime != 0) *creationTime = Time (fileTimeToTime (&findData.ftCreationTime));
  204227. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204228. return true;
  204229. }
  204230. private:
  204231. const String directoryWithWildCard;
  204232. HANDLE handle;
  204233. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl);
  204234. };
  204235. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204236. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204237. {
  204238. }
  204239. DirectoryIterator::NativeIterator::~NativeIterator()
  204240. {
  204241. }
  204242. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204243. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204244. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204245. {
  204246. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204247. }
  204248. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204249. {
  204250. HINSTANCE hInstance = 0;
  204251. JUCE_TRY
  204252. {
  204253. hInstance = ShellExecute (0, 0, fileName.toUTF16(), parameters.toUTF16(), 0, SW_SHOWDEFAULT);
  204254. }
  204255. JUCE_CATCH_ALL
  204256. return hInstance > (HINSTANCE) 32;
  204257. }
  204258. void File::revealToUser() const
  204259. {
  204260. if (isDirectory())
  204261. startAsProcess();
  204262. else if (getParentDirectory().exists())
  204263. getParentDirectory().startAsProcess();
  204264. }
  204265. class NamedPipeInternal
  204266. {
  204267. public:
  204268. NamedPipeInternal (const String& file, const bool isPipe_)
  204269. : pipeH (0),
  204270. cancelEvent (0),
  204271. connected (false),
  204272. isPipe (isPipe_)
  204273. {
  204274. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204275. pipeH = isPipe ? CreateNamedPipe (file.toUTF16(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204276. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204277. : CreateFile (file.toUTF16(), GENERIC_READ | GENERIC_WRITE, 0, 0,
  204278. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204279. }
  204280. ~NamedPipeInternal()
  204281. {
  204282. disconnectPipe();
  204283. if (pipeH != 0)
  204284. CloseHandle (pipeH);
  204285. CloseHandle (cancelEvent);
  204286. }
  204287. bool connect (const int timeOutMs)
  204288. {
  204289. if (! isPipe)
  204290. return true;
  204291. if (! connected)
  204292. {
  204293. OVERLAPPED over;
  204294. zerostruct (over);
  204295. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204296. if (ConnectNamedPipe (pipeH, &over))
  204297. {
  204298. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204299. }
  204300. else
  204301. {
  204302. const int err = GetLastError();
  204303. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204304. {
  204305. HANDLE handles[] = { over.hEvent, cancelEvent };
  204306. if (WaitForMultipleObjects (2, handles, FALSE,
  204307. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204308. connected = true;
  204309. }
  204310. else if (err == ERROR_PIPE_CONNECTED)
  204311. {
  204312. connected = true;
  204313. }
  204314. }
  204315. CloseHandle (over.hEvent);
  204316. }
  204317. return connected;
  204318. }
  204319. void disconnectPipe()
  204320. {
  204321. if (connected)
  204322. {
  204323. DisconnectNamedPipe (pipeH);
  204324. connected = false;
  204325. }
  204326. }
  204327. HANDLE pipeH;
  204328. HANDLE cancelEvent;
  204329. bool connected, isPipe;
  204330. };
  204331. void NamedPipe::close()
  204332. {
  204333. cancelPendingReads();
  204334. const ScopedLock sl (lock);
  204335. delete static_cast<NamedPipeInternal*> (internal);
  204336. internal = 0;
  204337. }
  204338. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204339. {
  204340. close();
  204341. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204342. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204343. {
  204344. internal = intern.release();
  204345. return true;
  204346. }
  204347. return false;
  204348. }
  204349. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204350. {
  204351. const ScopedLock sl (lock);
  204352. int bytesRead = -1;
  204353. bool waitAgain = true;
  204354. while (waitAgain && internal != 0)
  204355. {
  204356. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204357. waitAgain = false;
  204358. if (! intern->connect (timeOutMilliseconds))
  204359. break;
  204360. if (maxBytesToRead <= 0)
  204361. return 0;
  204362. OVERLAPPED over;
  204363. zerostruct (over);
  204364. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204365. unsigned long numRead;
  204366. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204367. {
  204368. bytesRead = (int) numRead;
  204369. }
  204370. else if (GetLastError() == ERROR_IO_PENDING)
  204371. {
  204372. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204373. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204374. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204375. : INFINITE);
  204376. if (waitResult != WAIT_OBJECT_0)
  204377. {
  204378. // if the operation timed out, let's cancel it...
  204379. CancelIo (intern->pipeH);
  204380. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204381. }
  204382. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204383. {
  204384. bytesRead = (int) numRead;
  204385. }
  204386. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204387. {
  204388. intern->disconnectPipe();
  204389. waitAgain = true;
  204390. }
  204391. }
  204392. else
  204393. {
  204394. waitAgain = internal != 0;
  204395. Sleep (5);
  204396. }
  204397. CloseHandle (over.hEvent);
  204398. }
  204399. return bytesRead;
  204400. }
  204401. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204402. {
  204403. int bytesWritten = -1;
  204404. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204405. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204406. {
  204407. if (numBytesToWrite <= 0)
  204408. return 0;
  204409. OVERLAPPED over;
  204410. zerostruct (over);
  204411. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204412. unsigned long numWritten;
  204413. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204414. {
  204415. bytesWritten = (int) numWritten;
  204416. }
  204417. else if (GetLastError() == ERROR_IO_PENDING)
  204418. {
  204419. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204420. DWORD waitResult;
  204421. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204422. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204423. : INFINITE);
  204424. if (waitResult != WAIT_OBJECT_0)
  204425. {
  204426. CancelIo (intern->pipeH);
  204427. WaitForSingleObject (over.hEvent, INFINITE);
  204428. }
  204429. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204430. {
  204431. bytesWritten = (int) numWritten;
  204432. }
  204433. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204434. {
  204435. intern->disconnectPipe();
  204436. }
  204437. }
  204438. CloseHandle (over.hEvent);
  204439. }
  204440. return bytesWritten;
  204441. }
  204442. void NamedPipe::cancelPendingReads()
  204443. {
  204444. if (internal != 0)
  204445. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204446. }
  204447. #endif
  204448. /*** End of inlined file: juce_win32_Files.cpp ***/
  204449. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204450. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204451. // compiled on its own).
  204452. #if JUCE_INCLUDED_FILE
  204453. #ifndef INTERNET_FLAG_NEED_FILE
  204454. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204455. #endif
  204456. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204457. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204458. #endif
  204459. #ifndef WORKAROUND_TIMEOUT_BUG
  204460. //#define WORKAROUND_TIMEOUT_BUG 1
  204461. #endif
  204462. #if WORKAROUND_TIMEOUT_BUG
  204463. // Required because of a Microsoft bug in setting a timeout
  204464. class InternetConnectThread : public Thread
  204465. {
  204466. public:
  204467. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET sessionHandle_, HINTERNET& connection_, const bool isFtp_)
  204468. : Thread ("Internet"), uc (uc_), sessionHandle (sessionHandle_), connection (connection_), isFtp (isFtp_)
  204469. {
  204470. startThread();
  204471. }
  204472. ~InternetConnectThread()
  204473. {
  204474. stopThread (60000);
  204475. }
  204476. void run()
  204477. {
  204478. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204479. uc.nPort, _T(""), _T(""),
  204480. isFtp ? INTERNET_SERVICE_FTP
  204481. : INTERNET_SERVICE_HTTP,
  204482. 0, 0);
  204483. notify();
  204484. }
  204485. private:
  204486. URL_COMPONENTS& uc;
  204487. HINTERNET sessionHandle;
  204488. HINTERNET& connection;
  204489. const bool isFtp;
  204490. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternetConnectThread);
  204491. };
  204492. #endif
  204493. class WebInputStream : public InputStream
  204494. {
  204495. public:
  204496. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  204497. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  204498. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  204499. : connection (0), request (0),
  204500. address (address_), headers (headers_), postData (postData_), position (0),
  204501. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  204502. {
  204503. createConnection (progressCallback, progressCallbackContext);
  204504. if (responseHeaders != 0 && ! isError())
  204505. {
  204506. DWORD bufferSizeBytes = 4096;
  204507. for (;;)
  204508. {
  204509. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  204510. if (HttpQueryInfo (request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  204511. {
  204512. StringArray headersArray;
  204513. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  204514. for (int i = 0; i < headersArray.size(); ++i)
  204515. {
  204516. const String& header = headersArray[i];
  204517. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  204518. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  204519. const String previousValue ((*responseHeaders) [key]);
  204520. responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  204521. }
  204522. break;
  204523. }
  204524. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  204525. break;
  204526. }
  204527. }
  204528. }
  204529. ~WebInputStream()
  204530. {
  204531. close();
  204532. }
  204533. bool isError() const { return request == 0; }
  204534. bool isExhausted() { return finished; }
  204535. int64 getPosition() { return position; }
  204536. int64 getTotalLength()
  204537. {
  204538. if (! isError())
  204539. {
  204540. DWORD index = 0, result = 0, size = sizeof (result);
  204541. if (HttpQueryInfo (request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  204542. return (int64) result;
  204543. }
  204544. return -1;
  204545. }
  204546. int read (void* buffer, int bytesToRead)
  204547. {
  204548. DWORD bytesRead = 0;
  204549. if (! (finished || isError()))
  204550. {
  204551. InternetReadFile (request, buffer, bytesToRead, &bytesRead);
  204552. position += bytesRead;
  204553. if (bytesRead == 0)
  204554. finished = true;
  204555. }
  204556. return (int) bytesRead;
  204557. }
  204558. bool setPosition (int64 wantedPos)
  204559. {
  204560. if (isError())
  204561. return false;
  204562. if (wantedPos != position)
  204563. {
  204564. finished = false;
  204565. position = (int64) InternetSetFilePointer (request, (LONG) wantedPos, 0, FILE_BEGIN, 0);
  204566. if (position == wantedPos)
  204567. return true;
  204568. if (wantedPos < position)
  204569. {
  204570. close();
  204571. position = 0;
  204572. createConnection (0, 0);
  204573. }
  204574. skipNextBytes (wantedPos - position);
  204575. }
  204576. return true;
  204577. }
  204578. private:
  204579. HINTERNET connection, request;
  204580. String address, headers;
  204581. MemoryBlock postData;
  204582. int64 position;
  204583. bool finished;
  204584. const bool isPost;
  204585. int timeOutMs;
  204586. void close()
  204587. {
  204588. if (request != 0)
  204589. {
  204590. InternetCloseHandle (request);
  204591. request = 0;
  204592. }
  204593. if (connection != 0)
  204594. {
  204595. InternetCloseHandle (connection);
  204596. connection = 0;
  204597. }
  204598. }
  204599. void createConnection (URL::OpenStreamProgressCallback* progressCallback,
  204600. void* progressCallbackContext)
  204601. {
  204602. static HINTERNET sessionHandle = InternetOpen (_T("juce"), INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0);
  204603. close();
  204604. if (sessionHandle != 0)
  204605. {
  204606. // break up the url..
  204607. TCHAR file[1024], server[1024];
  204608. URL_COMPONENTS uc;
  204609. zerostruct (uc);
  204610. uc.dwStructSize = sizeof (uc);
  204611. uc.dwUrlPathLength = sizeof (file);
  204612. uc.dwHostNameLength = sizeof (server);
  204613. uc.lpszUrlPath = file;
  204614. uc.lpszHostName = server;
  204615. if (InternetCrackUrl (address.toUTF16(), 0, 0, &uc))
  204616. {
  204617. int disable = 1;
  204618. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  204619. if (timeOutMs == 0)
  204620. timeOutMs = 30000;
  204621. else if (timeOutMs < 0)
  204622. timeOutMs = -1;
  204623. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  204624. const bool isFtp = address.startsWithIgnoreCase ("ftp:");
  204625. #if WORKAROUND_TIMEOUT_BUG
  204626. connection = 0;
  204627. {
  204628. InternetConnectThread connectThread (uc, sessionHandle, connection, isFtp);
  204629. connectThread.wait (timeOutMs);
  204630. if (connection == 0)
  204631. {
  204632. InternetCloseHandle (sessionHandle);
  204633. sessionHandle = 0;
  204634. }
  204635. }
  204636. #else
  204637. connection = InternetConnect (sessionHandle, uc.lpszHostName, uc.nPort,
  204638. _T(""), _T(""),
  204639. isFtp ? INTERNET_SERVICE_FTP
  204640. : INTERNET_SERVICE_HTTP,
  204641. 0, 0);
  204642. #endif
  204643. if (connection != 0)
  204644. {
  204645. if (isFtp)
  204646. {
  204647. request = FtpOpenFile (connection, uc.lpszUrlPath, GENERIC_READ,
  204648. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE, 0);
  204649. }
  204650. else
  204651. {
  204652. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  204653. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  204654. if (address.startsWithIgnoreCase ("https:"))
  204655. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  204656. // IE7 seems to automatically work out when it's https)
  204657. request = HttpOpenRequest (connection, isPost ? _T("POST") : _T("GET"),
  204658. uc.lpszUrlPath, 0, 0, mimeTypes, flags, 0);
  204659. if (request != 0)
  204660. {
  204661. INTERNET_BUFFERS buffers;
  204662. zerostruct (buffers);
  204663. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  204664. buffers.lpcszHeader = headers.toUTF16();
  204665. buffers.dwHeadersLength = headers.length();
  204666. buffers.dwBufferTotal = (DWORD) postData.getSize();
  204667. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  204668. {
  204669. int bytesSent = 0;
  204670. for (;;)
  204671. {
  204672. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  204673. DWORD bytesDone = 0;
  204674. if (bytesToDo > 0
  204675. && ! InternetWriteFile (request,
  204676. static_cast <const char*> (postData.getData()) + bytesSent,
  204677. bytesToDo, &bytesDone))
  204678. {
  204679. break;
  204680. }
  204681. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  204682. {
  204683. if (HttpEndRequest (request, 0, 0, 0))
  204684. return;
  204685. break;
  204686. }
  204687. bytesSent += bytesDone;
  204688. if (progressCallback != 0 && ! progressCallback (progressCallbackContext, bytesSent, postData.getSize()))
  204689. break;
  204690. }
  204691. }
  204692. }
  204693. close();
  204694. }
  204695. }
  204696. }
  204697. }
  204698. }
  204699. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  204700. };
  204701. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  204702. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  204703. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  204704. {
  204705. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  204706. progressCallback, progressCallbackContext,
  204707. headers, timeOutMs, responseHeaders));
  204708. return wi->isError() ? 0 : wi.release();
  204709. }
  204710. namespace MACAddressHelpers
  204711. {
  204712. void getViaGetAdaptersInfo (Array<MACAddress>& result)
  204713. {
  204714. DynamicLibraryLoader dll ("iphlpapi.dll");
  204715. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  204716. if (getAdaptersInfo != 0)
  204717. {
  204718. ULONG len = sizeof (IP_ADAPTER_INFO);
  204719. MemoryBlock mb;
  204720. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204721. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  204722. {
  204723. mb.setSize (len);
  204724. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204725. }
  204726. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  204727. {
  204728. for (PIP_ADAPTER_INFO adapter = adapterInfo; adapter != 0; adapter = adapter->Next)
  204729. {
  204730. if (adapter->AddressLength >= 6)
  204731. result.addIfNotAlreadyThere (MACAddress (adapter->Address));
  204732. }
  204733. }
  204734. }
  204735. }
  204736. void getViaNetBios (Array<MACAddress>& result)
  204737. {
  204738. DynamicLibraryLoader dll ("netapi32.dll");
  204739. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  204740. if (NetbiosCall != 0)
  204741. {
  204742. NCB ncb;
  204743. zerostruct (ncb);
  204744. struct ASTAT
  204745. {
  204746. ADAPTER_STATUS adapt;
  204747. NAME_BUFFER NameBuff [30];
  204748. };
  204749. ASTAT astat;
  204750. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  204751. LANA_ENUM enums;
  204752. zerostruct (enums);
  204753. ncb.ncb_command = NCBENUM;
  204754. ncb.ncb_buffer = (unsigned char*) &enums;
  204755. ncb.ncb_length = sizeof (LANA_ENUM);
  204756. NetbiosCall (&ncb);
  204757. for (int i = 0; i < enums.length; ++i)
  204758. {
  204759. zerostruct (ncb);
  204760. ncb.ncb_command = NCBRESET;
  204761. ncb.ncb_lana_num = enums.lana[i];
  204762. if (NetbiosCall (&ncb) == 0)
  204763. {
  204764. zerostruct (ncb);
  204765. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  204766. ncb.ncb_command = NCBASTAT;
  204767. ncb.ncb_lana_num = enums.lana[i];
  204768. ncb.ncb_buffer = (unsigned char*) &astat;
  204769. ncb.ncb_length = sizeof (ASTAT);
  204770. if (NetbiosCall (&ncb) == 0 && astat.adapt.adapter_type == 0xfe)
  204771. result.addIfNotAlreadyThere (MACAddress (astat.adapt.adapter_address));
  204772. }
  204773. }
  204774. }
  204775. }
  204776. }
  204777. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  204778. {
  204779. MACAddressHelpers::getViaGetAdaptersInfo (result);
  204780. MACAddressHelpers::getViaNetBios (result);
  204781. }
  204782. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  204783. const String& emailSubject,
  204784. const String& bodyText,
  204785. const StringArray& filesToAttach)
  204786. {
  204787. HMODULE h = LoadLibraryA ("MAPI32.dll");
  204788. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  204789. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  204790. bool ok = false;
  204791. if (mapiSendMail != 0)
  204792. {
  204793. MapiMessage message;
  204794. zerostruct (message);
  204795. message.lpszSubject = (LPSTR) emailSubject.toCString();
  204796. message.lpszNoteText = (LPSTR) bodyText.toCString();
  204797. MapiRecipDesc recip;
  204798. zerostruct (recip);
  204799. recip.ulRecipClass = MAPI_TO;
  204800. String targetEmailAddress_ (targetEmailAddress);
  204801. if (targetEmailAddress_.isEmpty())
  204802. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  204803. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  204804. message.nRecipCount = 1;
  204805. message.lpRecips = &recip;
  204806. HeapBlock <MapiFileDesc> files;
  204807. files.calloc (filesToAttach.size());
  204808. message.nFileCount = filesToAttach.size();
  204809. message.lpFiles = files;
  204810. for (int i = 0; i < filesToAttach.size(); ++i)
  204811. {
  204812. files[i].nPosition = (ULONG) -1;
  204813. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  204814. }
  204815. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  204816. }
  204817. FreeLibrary (h);
  204818. return ok;
  204819. }
  204820. #endif
  204821. /*** End of inlined file: juce_win32_Network.cpp ***/
  204822. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  204823. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204824. // compiled on its own).
  204825. #if JUCE_INCLUDED_FILE
  204826. namespace
  204827. {
  204828. HKEY findKeyForPath (String name, const bool createForWriting, String& valueName)
  204829. {
  204830. HKEY rootKey = 0;
  204831. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  204832. rootKey = HKEY_CURRENT_USER;
  204833. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  204834. rootKey = HKEY_LOCAL_MACHINE;
  204835. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  204836. rootKey = HKEY_CLASSES_ROOT;
  204837. if (rootKey != 0)
  204838. {
  204839. name = name.substring (name.indexOfChar ('\\') + 1);
  204840. const int lastSlash = name.lastIndexOfChar ('\\');
  204841. valueName = name.substring (lastSlash + 1);
  204842. name = name.substring (0, lastSlash);
  204843. HKEY key;
  204844. DWORD result;
  204845. if (createForWriting)
  204846. {
  204847. if (RegCreateKeyEx (rootKey, name.toUTF16(), 0, 0, REG_OPTION_NON_VOLATILE,
  204848. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  204849. return key;
  204850. }
  204851. else
  204852. {
  204853. if (RegOpenKeyEx (rootKey, name.toUTF16(), 0, KEY_READ, &key) == ERROR_SUCCESS)
  204854. return key;
  204855. }
  204856. }
  204857. return 0;
  204858. }
  204859. }
  204860. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  204861. const String& defaultValue)
  204862. {
  204863. String valueName, result (defaultValue);
  204864. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204865. if (k != 0)
  204866. {
  204867. WCHAR buffer [2048];
  204868. unsigned long bufferSize = sizeof (buffer);
  204869. DWORD type = REG_SZ;
  204870. if (RegQueryValueEx (k, valueName.toUTF16(), 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  204871. {
  204872. if (type == REG_SZ)
  204873. result = buffer;
  204874. else if (type == REG_DWORD)
  204875. result = String ((int) *(DWORD*) buffer);
  204876. }
  204877. RegCloseKey (k);
  204878. }
  204879. return result;
  204880. }
  204881. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  204882. const String& value)
  204883. {
  204884. String valueName;
  204885. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204886. if (k != 0)
  204887. {
  204888. RegSetValueEx (k, valueName.toUTF16(), 0, REG_SZ,
  204889. (const BYTE*) value.toUTF16().getAddress(),
  204890. CharPointer_UTF16::getBytesRequiredFor (value.getCharPointer()));
  204891. RegCloseKey (k);
  204892. }
  204893. }
  204894. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  204895. {
  204896. bool exists = false;
  204897. String valueName;
  204898. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204899. if (k != 0)
  204900. {
  204901. unsigned char buffer [2048];
  204902. unsigned long bufferSize = sizeof (buffer);
  204903. DWORD type = 0;
  204904. if (RegQueryValueEx (k, valueName.toUTF16(), 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  204905. exists = true;
  204906. RegCloseKey (k);
  204907. }
  204908. return exists;
  204909. }
  204910. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  204911. {
  204912. String valueName;
  204913. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204914. if (k != 0)
  204915. {
  204916. RegDeleteValue (k, valueName.toUTF16());
  204917. RegCloseKey (k);
  204918. }
  204919. }
  204920. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  204921. {
  204922. String valueName;
  204923. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  204924. if (k != 0)
  204925. {
  204926. RegDeleteKey (k, valueName.toUTF16());
  204927. RegCloseKey (k);
  204928. }
  204929. }
  204930. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  204931. const String& symbolicDescription,
  204932. const String& fullDescription,
  204933. const File& targetExecutable,
  204934. int iconResourceNumber)
  204935. {
  204936. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  204937. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  204938. if (iconResourceNumber != 0)
  204939. setRegistryValue (key + "\\DefaultIcon\\",
  204940. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  204941. setRegistryValue (key + "\\", fullDescription);
  204942. setRegistryValue (key + "\\shell\\open\\command\\",
  204943. targetExecutable.getFullPathName() + " %1");
  204944. }
  204945. bool juce_IsRunningInWine()
  204946. {
  204947. HKEY key;
  204948. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  204949. {
  204950. RegCloseKey (key);
  204951. return true;
  204952. }
  204953. return false;
  204954. }
  204955. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  204956. {
  204957. String s (::GetCommandLineW());
  204958. StringArray tokens;
  204959. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  204960. return tokens.joinIntoString (" ", 1);
  204961. }
  204962. static void* currentModuleHandle = 0;
  204963. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  204964. {
  204965. if (currentModuleHandle == 0)
  204966. currentModuleHandle = GetModuleHandle (0);
  204967. return currentModuleHandle;
  204968. }
  204969. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  204970. {
  204971. currentModuleHandle = newHandle;
  204972. }
  204973. void PlatformUtilities::fpuReset()
  204974. {
  204975. #if JUCE_MSVC
  204976. _clearfp();
  204977. #endif
  204978. }
  204979. void PlatformUtilities::beep()
  204980. {
  204981. MessageBeep (MB_OK);
  204982. }
  204983. #endif
  204984. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  204985. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  204986. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  204987. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204988. // compiled on its own).
  204989. #if JUCE_INCLUDED_FILE
  204990. static const unsigned int specialId = WM_APP + 0x4400;
  204991. static const unsigned int broadcastId = WM_APP + 0x4403;
  204992. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  204993. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  204994. HWND juce_messageWindowHandle = 0;
  204995. extern long improbableWindowNumber; // defined in windowing.cpp
  204996. #ifndef WM_APPCOMMAND
  204997. #define WM_APPCOMMAND 0x0319
  204998. #endif
  204999. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  205000. const UINT message,
  205001. const WPARAM wParam,
  205002. const LPARAM lParam) throw()
  205003. {
  205004. JUCE_TRY
  205005. {
  205006. if (h == juce_messageWindowHandle)
  205007. {
  205008. if (message == specialCallbackId)
  205009. {
  205010. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  205011. return (LRESULT) (*func) ((void*) lParam);
  205012. }
  205013. else if (message == specialId)
  205014. {
  205015. // these are trapped early in the dispatch call, but must also be checked
  205016. // here in case there are windows modal dialog boxes doing their own
  205017. // dispatch loop and not calling our version
  205018. Message* const message = reinterpret_cast <Message*> (lParam);
  205019. MessageManager::getInstance()->deliverMessage (message);
  205020. message->decReferenceCount();
  205021. return 0;
  205022. }
  205023. else if (message == broadcastId)
  205024. {
  205025. const ScopedPointer <String> messageString ((String*) lParam);
  205026. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205027. return 0;
  205028. }
  205029. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205030. {
  205031. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205032. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205033. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205034. return 0;
  205035. }
  205036. }
  205037. }
  205038. JUCE_CATCH_EXCEPTION
  205039. return DefWindowProc (h, message, wParam, lParam);
  205040. }
  205041. static bool isEventBlockedByModalComps (MSG& m)
  205042. {
  205043. if (Component::getNumCurrentlyModalComponents() == 0
  205044. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205045. return false;
  205046. switch (m.message)
  205047. {
  205048. case WM_MOUSEMOVE:
  205049. case WM_NCMOUSEMOVE:
  205050. case 0x020A: /* WM_MOUSEWHEEL */
  205051. case 0x020E: /* WM_MOUSEHWHEEL */
  205052. case WM_KEYUP:
  205053. case WM_SYSKEYUP:
  205054. case WM_CHAR:
  205055. case WM_APPCOMMAND:
  205056. case WM_LBUTTONUP:
  205057. case WM_MBUTTONUP:
  205058. case WM_RBUTTONUP:
  205059. case WM_MOUSEACTIVATE:
  205060. case WM_NCMOUSEHOVER:
  205061. case WM_MOUSEHOVER:
  205062. return true;
  205063. case WM_NCLBUTTONDOWN:
  205064. case WM_NCLBUTTONDBLCLK:
  205065. case WM_NCRBUTTONDOWN:
  205066. case WM_NCRBUTTONDBLCLK:
  205067. case WM_NCMBUTTONDOWN:
  205068. case WM_NCMBUTTONDBLCLK:
  205069. case WM_LBUTTONDOWN:
  205070. case WM_LBUTTONDBLCLK:
  205071. case WM_MBUTTONDOWN:
  205072. case WM_MBUTTONDBLCLK:
  205073. case WM_RBUTTONDOWN:
  205074. case WM_RBUTTONDBLCLK:
  205075. case WM_KEYDOWN:
  205076. case WM_SYSKEYDOWN:
  205077. {
  205078. Component* const modal = Component::getCurrentlyModalComponent (0);
  205079. if (modal != 0)
  205080. modal->inputAttemptWhenModal();
  205081. return true;
  205082. }
  205083. default:
  205084. break;
  205085. }
  205086. return false;
  205087. }
  205088. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205089. {
  205090. MSG m;
  205091. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205092. return false;
  205093. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205094. {
  205095. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205096. {
  205097. Message* const message = reinterpret_cast <Message*> (m.lParam);
  205098. MessageManager::getInstance()->deliverMessage (message);
  205099. message->decReferenceCount();
  205100. }
  205101. else if (m.message == WM_QUIT)
  205102. {
  205103. if (JUCEApplication::getInstance() != 0)
  205104. JUCEApplication::getInstance()->systemRequestedQuit();
  205105. }
  205106. else if (! isEventBlockedByModalComps (m))
  205107. {
  205108. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205109. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205110. {
  205111. // if it's someone else's window being clicked on, and the focus is
  205112. // currently on a juce window, pass the kb focus over..
  205113. HWND currentFocus = GetFocus();
  205114. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205115. SetFocus (m.hwnd);
  205116. }
  205117. TranslateMessage (&m);
  205118. DispatchMessage (&m);
  205119. }
  205120. }
  205121. return true;
  205122. }
  205123. bool juce_postMessageToSystemQueue (Message* message)
  205124. {
  205125. message->incReferenceCount();
  205126. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205127. }
  205128. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205129. void* userData)
  205130. {
  205131. if (MessageManager::getInstance()->isThisTheMessageThread())
  205132. {
  205133. return (*callback) (userData);
  205134. }
  205135. else
  205136. {
  205137. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205138. // deadlock because the message manager is blocked from running, and can't
  205139. // call your function..
  205140. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205141. return (void*) SendMessage (juce_messageWindowHandle,
  205142. specialCallbackId,
  205143. (WPARAM) callback,
  205144. (LPARAM) userData);
  205145. }
  205146. }
  205147. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205148. {
  205149. if (hwnd != juce_messageWindowHandle)
  205150. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205151. return TRUE;
  205152. }
  205153. void MessageManager::broadcastMessage (const String& value)
  205154. {
  205155. Array<void*> windows;
  205156. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205157. const String localCopy (value);
  205158. COPYDATASTRUCT data;
  205159. data.dwData = broadcastId;
  205160. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205161. data.lpData = (void*) localCopy.toUTF16().getAddress();
  205162. for (int i = windows.size(); --i >= 0;)
  205163. {
  205164. HWND hwnd = (HWND) windows.getUnchecked(i);
  205165. TCHAR windowName [64]; // no need to read longer strings than this
  205166. GetWindowText (hwnd, windowName, 64);
  205167. windowName [63] = 0;
  205168. if (String (windowName) == messageWindowName)
  205169. {
  205170. DWORD_PTR result;
  205171. SendMessageTimeout (hwnd, WM_COPYDATA,
  205172. (WPARAM) juce_messageWindowHandle,
  205173. (LPARAM) &data,
  205174. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205175. 8000,
  205176. &result);
  205177. }
  205178. }
  205179. }
  205180. static const String getMessageWindowClassName()
  205181. {
  205182. // this name has to be different for each app/dll instance because otherwise
  205183. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205184. // window class).
  205185. static int number = 0;
  205186. if (number == 0)
  205187. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205188. return "JUCEcs_" + String (number);
  205189. }
  205190. void MessageManager::doPlatformSpecificInitialisation()
  205191. {
  205192. OleInitialize (0);
  205193. const String className (getMessageWindowClassName());
  205194. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205195. WNDCLASSEX wc;
  205196. zerostruct (wc);
  205197. wc.cbSize = sizeof (wc);
  205198. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205199. wc.cbWndExtra = 4;
  205200. wc.hInstance = hmod;
  205201. wc.lpszClassName = className.toUTF16();
  205202. RegisterClassEx (&wc);
  205203. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205204. messageWindowName,
  205205. 0, 0, 0, 0, 0, 0, 0,
  205206. hmod, 0);
  205207. }
  205208. void MessageManager::doPlatformSpecificShutdown()
  205209. {
  205210. DestroyWindow (juce_messageWindowHandle);
  205211. UnregisterClass (getMessageWindowClassName().toUTF16(), 0);
  205212. OleUninitialize();
  205213. }
  205214. #endif
  205215. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205216. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205217. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205218. // compiled on its own).
  205219. #if JUCE_INCLUDED_FILE
  205220. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205221. NEWTEXTMETRICEXW*,
  205222. int type,
  205223. LPARAM lParam)
  205224. {
  205225. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205226. {
  205227. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205228. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205229. }
  205230. return 1;
  205231. }
  205232. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205233. NEWTEXTMETRICEXW*,
  205234. int type,
  205235. LPARAM lParam)
  205236. {
  205237. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205238. {
  205239. LOGFONTW lf;
  205240. zerostruct (lf);
  205241. lf.lfWeight = FW_DONTCARE;
  205242. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205243. lf.lfQuality = DEFAULT_QUALITY;
  205244. lf.lfCharSet = DEFAULT_CHARSET;
  205245. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205246. lf.lfPitchAndFamily = FF_DONTCARE;
  205247. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205248. fontName.copyToUTF16 (lf.lfFaceName, LF_FACESIZE - 1);
  205249. HDC dc = CreateCompatibleDC (0);
  205250. EnumFontFamiliesEx (dc, &lf,
  205251. (FONTENUMPROCW) &wfontEnum2,
  205252. lParam, 0);
  205253. DeleteDC (dc);
  205254. }
  205255. return 1;
  205256. }
  205257. const StringArray Font::findAllTypefaceNames()
  205258. {
  205259. StringArray results;
  205260. HDC dc = CreateCompatibleDC (0);
  205261. {
  205262. LOGFONTW lf;
  205263. zerostruct (lf);
  205264. lf.lfWeight = FW_DONTCARE;
  205265. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205266. lf.lfQuality = DEFAULT_QUALITY;
  205267. lf.lfCharSet = DEFAULT_CHARSET;
  205268. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205269. lf.lfPitchAndFamily = FF_DONTCARE;
  205270. lf.lfFaceName[0] = 0;
  205271. EnumFontFamiliesEx (dc, &lf,
  205272. (FONTENUMPROCW) &wfontEnum1,
  205273. (LPARAM) &results, 0);
  205274. }
  205275. DeleteDC (dc);
  205276. results.sort (true);
  205277. return results;
  205278. }
  205279. extern bool juce_IsRunningInWine();
  205280. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  205281. {
  205282. if (juce_IsRunningInWine())
  205283. {
  205284. // If we're running in Wine, then use fonts that might be available on Linux..
  205285. defaultSans = "Bitstream Vera Sans";
  205286. defaultSerif = "Bitstream Vera Serif";
  205287. defaultFixed = "Bitstream Vera Sans Mono";
  205288. }
  205289. else
  205290. {
  205291. defaultSans = "Verdana";
  205292. defaultSerif = "Times";
  205293. defaultFixed = "Lucida Console";
  205294. defaultFallback = "Tahoma"; // (contains plenty of unicode characters)
  205295. }
  205296. }
  205297. class FontDCHolder : private DeletedAtShutdown
  205298. {
  205299. public:
  205300. FontDCHolder()
  205301. : fontH (0), previousFontH (0), dc (0), numKPs (0), size (0),
  205302. bold (false), italic (false)
  205303. {
  205304. }
  205305. ~FontDCHolder()
  205306. {
  205307. deleteDCAndFont();
  205308. clearSingletonInstance();
  205309. }
  205310. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205311. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205312. {
  205313. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205314. {
  205315. fontName = fontName_;
  205316. bold = bold_;
  205317. italic = italic_;
  205318. size = size_;
  205319. deleteDCAndFont();
  205320. dc = CreateCompatibleDC (0);
  205321. SetMapperFlags (dc, 0);
  205322. SetMapMode (dc, MM_TEXT);
  205323. LOGFONTW lfw;
  205324. zerostruct (lfw);
  205325. lfw.lfCharSet = DEFAULT_CHARSET;
  205326. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205327. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205328. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205329. lfw.lfQuality = PROOF_QUALITY;
  205330. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205331. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205332. fontName.copyToUTF16 (lfw.lfFaceName, LF_FACESIZE - 1);
  205333. lfw.lfHeight = size > 0 ? size : -256;
  205334. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205335. if (standardSizedFont != 0)
  205336. {
  205337. if ((previousFontH = SelectObject (dc, standardSizedFont)) != 0)
  205338. {
  205339. fontH = standardSizedFont;
  205340. if (size == 0)
  205341. {
  205342. OUTLINETEXTMETRIC otm;
  205343. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205344. {
  205345. lfw.lfHeight = -(int) otm.otmEMSquare;
  205346. fontH = CreateFontIndirect (&lfw);
  205347. SelectObject (dc, fontH);
  205348. DeleteObject (standardSizedFont);
  205349. }
  205350. }
  205351. }
  205352. }
  205353. }
  205354. return dc;
  205355. }
  205356. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205357. {
  205358. if (kps == 0)
  205359. {
  205360. numKPs = GetKerningPairs (dc, 0, 0);
  205361. kps.calloc (numKPs);
  205362. GetKerningPairs (dc, numKPs, kps);
  205363. }
  205364. numKPs_ = numKPs;
  205365. return kps;
  205366. }
  205367. private:
  205368. HFONT fontH;
  205369. HGDIOBJ previousFontH;
  205370. HDC dc;
  205371. String fontName;
  205372. HeapBlock <KERNINGPAIR> kps;
  205373. int numKPs, size;
  205374. bool bold, italic;
  205375. void deleteDCAndFont()
  205376. {
  205377. if (dc != 0)
  205378. {
  205379. SelectObject (dc, previousFontH); // Replacing the previous font before deleting the DC avoids a warning in BoundsChecker
  205380. DeleteDC (dc);
  205381. dc = 0;
  205382. }
  205383. if (fontH != 0)
  205384. {
  205385. DeleteObject (fontH);
  205386. fontH = 0;
  205387. }
  205388. kps.free();
  205389. }
  205390. JUCE_DECLARE_NON_COPYABLE (FontDCHolder);
  205391. };
  205392. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205393. class WindowsTypeface : public CustomTypeface
  205394. {
  205395. public:
  205396. WindowsTypeface (const Font& font)
  205397. {
  205398. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205399. font.isBold(), font.isItalic(), 0);
  205400. TEXTMETRIC tm;
  205401. tm.tmAscent = tm.tmHeight = 1;
  205402. tm.tmDefaultChar = 0;
  205403. GetTextMetrics (dc, &tm);
  205404. setCharacteristics (font.getTypefaceName(),
  205405. tm.tmAscent / (float) tm.tmHeight,
  205406. font.isBold(), font.isItalic(),
  205407. tm.tmDefaultChar);
  205408. }
  205409. bool loadGlyphIfPossible (juce_wchar character)
  205410. {
  205411. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205412. GLYPHMETRICS gm;
  205413. // if this is the fallback font, skip checking for the glyph's existence. This is because
  205414. // with fonts like Tahoma, GetGlyphIndices can say that a glyph doesn't exist, but it still
  205415. // gets correctly created later on.
  205416. if (! isFallbackFont)
  205417. {
  205418. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205419. WORD index = 0;
  205420. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205421. && index == 0xffff)
  205422. {
  205423. return false;
  205424. }
  205425. }
  205426. Path glyphPath;
  205427. TEXTMETRIC tm;
  205428. if (! GetTextMetrics (dc, &tm))
  205429. {
  205430. addGlyph (character, glyphPath, 0);
  205431. return true;
  205432. }
  205433. const float height = (float) tm.tmHeight;
  205434. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205435. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205436. &gm, 0, 0, &identityMatrix);
  205437. if (bufSize > 0)
  205438. {
  205439. HeapBlock<char> data (bufSize);
  205440. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205441. bufSize, data, &identityMatrix);
  205442. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205443. const float scaleX = 1.0f / height;
  205444. const float scaleY = -1.0f / height;
  205445. while ((char*) pheader < data + bufSize)
  205446. {
  205447. float x = scaleX * pheader->pfxStart.x.value;
  205448. float y = scaleY * pheader->pfxStart.y.value;
  205449. glyphPath.startNewSubPath (x, y);
  205450. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205451. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205452. while ((const char*) curve < curveEnd)
  205453. {
  205454. if (curve->wType == TT_PRIM_LINE)
  205455. {
  205456. for (int i = 0; i < curve->cpfx; ++i)
  205457. {
  205458. x = scaleX * curve->apfx[i].x.value;
  205459. y = scaleY * curve->apfx[i].y.value;
  205460. glyphPath.lineTo (x, y);
  205461. }
  205462. }
  205463. else if (curve->wType == TT_PRIM_QSPLINE)
  205464. {
  205465. for (int i = 0; i < curve->cpfx - 1; ++i)
  205466. {
  205467. const float x2 = scaleX * curve->apfx[i].x.value;
  205468. const float y2 = scaleY * curve->apfx[i].y.value;
  205469. float x3, y3;
  205470. if (i < curve->cpfx - 2)
  205471. {
  205472. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205473. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205474. }
  205475. else
  205476. {
  205477. x3 = scaleX * curve->apfx[i + 1].x.value;
  205478. y3 = scaleY * curve->apfx[i + 1].y.value;
  205479. }
  205480. glyphPath.quadraticTo (x2, y2, x3, y3);
  205481. x = x3;
  205482. y = y3;
  205483. }
  205484. }
  205485. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205486. }
  205487. pheader = (const TTPOLYGONHEADER*) curve;
  205488. glyphPath.closeSubPath();
  205489. }
  205490. }
  205491. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  205492. int numKPs;
  205493. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  205494. for (int i = 0; i < numKPs; ++i)
  205495. {
  205496. if (kps[i].wFirst == character)
  205497. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  205498. kps[i].iKernAmount / height);
  205499. }
  205500. return true;
  205501. }
  205502. private:
  205503. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsTypeface);
  205504. };
  205505. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  205506. {
  205507. return new WindowsTypeface (font);
  205508. }
  205509. #endif
  205510. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  205511. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  205512. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205513. // compiled on its own).
  205514. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  205515. class SharedD2DFactory : public DeletedAtShutdown
  205516. {
  205517. public:
  205518. SharedD2DFactory()
  205519. {
  205520. jassertfalse; //xxx Direct2D support isn't ready for use yet!
  205521. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, d2dFactory.resetAndGetPointerAddress());
  205522. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) directWriteFactory.resetAndGetPointerAddress());
  205523. if (directWriteFactory != 0)
  205524. directWriteFactory->GetSystemFontCollection (systemFonts.resetAndGetPointerAddress());
  205525. }
  205526. ~SharedD2DFactory()
  205527. {
  205528. clearSingletonInstance();
  205529. }
  205530. juce_DeclareSingleton (SharedD2DFactory, false);
  205531. ComSmartPtr <ID2D1Factory> d2dFactory;
  205532. ComSmartPtr <IDWriteFactory> directWriteFactory;
  205533. ComSmartPtr <IDWriteFontCollection> systemFonts;
  205534. };
  205535. juce_ImplementSingleton (SharedD2DFactory)
  205536. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  205537. {
  205538. public:
  205539. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  205540. : hwnd (hwnd_),
  205541. currentState (0)
  205542. {
  205543. RECT windowRect;
  205544. GetClientRect (hwnd, &windowRect);
  205545. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205546. bounds.setSize (size.width, size.height);
  205547. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  205548. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  205549. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, renderingTarget.resetAndGetPointerAddress());
  205550. // xxx check for error
  205551. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), colourBrush.resetAndGetPointerAddress());
  205552. }
  205553. ~Direct2DLowLevelGraphicsContext()
  205554. {
  205555. states.clear();
  205556. }
  205557. void resized()
  205558. {
  205559. RECT windowRect;
  205560. GetClientRect (hwnd, &windowRect);
  205561. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205562. renderingTarget->Resize (size);
  205563. bounds.setSize (size.width, size.height);
  205564. }
  205565. void clear()
  205566. {
  205567. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  205568. }
  205569. void start()
  205570. {
  205571. renderingTarget->BeginDraw();
  205572. saveState();
  205573. }
  205574. void end()
  205575. {
  205576. states.clear();
  205577. currentState = 0;
  205578. renderingTarget->EndDraw();
  205579. renderingTarget->CheckWindowState();
  205580. }
  205581. bool isVectorDevice() const { return false; }
  205582. void setOrigin (int x, int y)
  205583. {
  205584. currentState->origin.addXY (x, y);
  205585. }
  205586. void addTransform (const AffineTransform& transform)
  205587. {
  205588. //xxx todo
  205589. jassertfalse;
  205590. }
  205591. float getScaleFactor()
  205592. {
  205593. jassertfalse; //xxx
  205594. return 1.0f;
  205595. }
  205596. bool clipToRectangle (const Rectangle<int>& r)
  205597. {
  205598. currentState->clipToRectangle (r);
  205599. return ! isClipEmpty();
  205600. }
  205601. bool clipToRectangleList (const RectangleList& clipRegion)
  205602. {
  205603. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  205604. return ! isClipEmpty();
  205605. }
  205606. void excludeClipRectangle (const Rectangle<int>&)
  205607. {
  205608. //xxx
  205609. }
  205610. void clipToPath (const Path& path, const AffineTransform& transform)
  205611. {
  205612. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  205613. }
  205614. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  205615. {
  205616. currentState->clipToImage (sourceImage,transform);
  205617. }
  205618. bool clipRegionIntersects (const Rectangle<int>& r)
  205619. {
  205620. const Rectangle<int> r2 (r + currentState->origin);
  205621. return currentState->clipRect.intersects (r2);
  205622. }
  205623. const Rectangle<int> getClipBounds() const
  205624. {
  205625. // xxx could this take into account complex clip regions?
  205626. return currentState->clipRect - currentState->origin;
  205627. }
  205628. bool isClipEmpty() const
  205629. {
  205630. return currentState->clipRect.isEmpty();
  205631. }
  205632. void saveState()
  205633. {
  205634. states.add (new SavedState (*this));
  205635. currentState = states.getLast();
  205636. }
  205637. void restoreState()
  205638. {
  205639. jassert (states.size() > 1) //you should never pop the last state!
  205640. states.removeLast (1);
  205641. currentState = states.getLast();
  205642. }
  205643. void beginTransparencyLayer (float opacity)
  205644. {
  205645. jassertfalse; //xxx todo
  205646. }
  205647. void endTransparencyLayer()
  205648. {
  205649. jassertfalse; //xxx todo
  205650. }
  205651. void setFill (const FillType& fillType)
  205652. {
  205653. currentState->setFill (fillType);
  205654. }
  205655. void setOpacity (float newOpacity)
  205656. {
  205657. currentState->setOpacity (newOpacity);
  205658. }
  205659. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  205660. {
  205661. }
  205662. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  205663. {
  205664. currentState->createBrush();
  205665. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  205666. }
  205667. void fillPath (const Path& p, const AffineTransform& transform)
  205668. {
  205669. currentState->createBrush();
  205670. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  205671. if (renderingTarget != 0)
  205672. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  205673. }
  205674. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  205675. {
  205676. const int x = currentState->origin.getX();
  205677. const int y = currentState->origin.getY();
  205678. renderingTarget->SetTransform (transformToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205679. D2D1_SIZE_U size;
  205680. size.width = image.getWidth();
  205681. size.height = image.getHeight();
  205682. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205683. Image img (image.convertedToFormat (Image::ARGB));
  205684. Image::BitmapData bd (img, false);
  205685. bp.pixelFormat = renderingTarget->GetPixelFormat();
  205686. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205687. {
  205688. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  205689. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, tempBitmap.resetAndGetPointerAddress());
  205690. if (tempBitmap != 0)
  205691. renderingTarget->DrawBitmap (tempBitmap);
  205692. }
  205693. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205694. }
  205695. void drawLine (const Line <float>& line)
  205696. {
  205697. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205698. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  205699. line.getEnd() + currentState->origin.toFloat());
  205700. currentState->createBrush();
  205701. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  205702. D2D1::Point2F (l.getEndX(), l.getEndY()),
  205703. currentState->currentBrush);
  205704. }
  205705. void drawVerticalLine (int x, float top, float bottom)
  205706. {
  205707. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205708. currentState->createBrush();
  205709. x += currentState->origin.getX();
  205710. const int y = currentState->origin.getY();
  205711. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  205712. D2D1::Point2F (x, y + bottom),
  205713. currentState->currentBrush);
  205714. }
  205715. void drawHorizontalLine (int y, float left, float right)
  205716. {
  205717. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205718. currentState->createBrush();
  205719. y += currentState->origin.getY();
  205720. const int x = currentState->origin.getX();
  205721. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  205722. D2D1::Point2F (x + right, y),
  205723. currentState->currentBrush);
  205724. }
  205725. void setFont (const Font& newFont)
  205726. {
  205727. currentState->setFont (newFont);
  205728. }
  205729. const Font getFont()
  205730. {
  205731. return currentState->font;
  205732. }
  205733. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  205734. {
  205735. const float x = currentState->origin.getX();
  205736. const float y = currentState->origin.getY();
  205737. currentState->createBrush();
  205738. currentState->createFont();
  205739. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  205740. float hScale = currentState->font.getHorizontalScale();
  205741. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transformToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205742. float dpiX = 0, dpiY = 0;
  205743. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  205744. UINT32 glyphNum = glyphNumber;
  205745. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  205746. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  205747. DWRITE_GLYPH_OFFSET offset;
  205748. offset.advanceOffset = 0;
  205749. offset.ascenderOffset = 0;
  205750. float glyphAdvances = 0;
  205751. DWRITE_GLYPH_RUN glyph;
  205752. glyph.fontFace = currentState->currentFontFace;
  205753. glyph.glyphCount = 1;
  205754. glyph.glyphIndices = &glyphNum1;
  205755. glyph.isSideways = FALSE;
  205756. glyph.glyphAdvances = &glyphAdvances;
  205757. glyph.glyphOffsets = &offset;
  205758. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  205759. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  205760. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205761. }
  205762. class SavedState
  205763. {
  205764. public:
  205765. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  205766. : owner (owner_), currentBrush (0),
  205767. fontScaling (1.0f), currentFontFace (0),
  205768. clipsRect (false), shouldClipRect (false),
  205769. clipsRectList (false), shouldClipRectList (false),
  205770. clipsComplex (false), shouldClipComplex (false),
  205771. clipsBitmap (false), shouldClipBitmap (false)
  205772. {
  205773. if (owner.currentState != 0)
  205774. {
  205775. // xxx seems like a very slow way to create one of these, and this is a performance
  205776. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  205777. setFill (owner.currentState->fillType);
  205778. currentBrush = owner.currentState->currentBrush;
  205779. origin = owner.currentState->origin;
  205780. clipRect = owner.currentState->clipRect;
  205781. font = owner.currentState->font;
  205782. currentFontFace = owner.currentState->currentFontFace;
  205783. }
  205784. else
  205785. {
  205786. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  205787. clipRect.setSize (size.width, size.height);
  205788. setFill (FillType (Colours::black));
  205789. }
  205790. }
  205791. ~SavedState()
  205792. {
  205793. clearClip();
  205794. clearFont();
  205795. clearFill();
  205796. clearPathClip();
  205797. clearImageClip();
  205798. complexClipLayer = 0;
  205799. bitmapMaskLayer = 0;
  205800. }
  205801. void clearClip()
  205802. {
  205803. popClips();
  205804. shouldClipRect = false;
  205805. }
  205806. void clipToRectangle (const Rectangle<int>& r)
  205807. {
  205808. clearClip();
  205809. clipRect = r + origin;
  205810. shouldClipRect = true;
  205811. pushClips();
  205812. }
  205813. void clearPathClip()
  205814. {
  205815. popClips();
  205816. if (shouldClipComplex)
  205817. {
  205818. complexClipGeometry = 0;
  205819. shouldClipComplex = false;
  205820. }
  205821. }
  205822. void clipToPath (ID2D1Geometry* geometry)
  205823. {
  205824. clearPathClip();
  205825. if (complexClipLayer == 0)
  205826. owner.renderingTarget->CreateLayer (complexClipLayer.resetAndGetPointerAddress());
  205827. complexClipGeometry = geometry;
  205828. shouldClipComplex = true;
  205829. pushClips();
  205830. }
  205831. void clearRectListClip()
  205832. {
  205833. popClips();
  205834. if (shouldClipRectList)
  205835. {
  205836. rectListGeometry = 0;
  205837. shouldClipRectList = false;
  205838. }
  205839. }
  205840. void clipToRectList (ID2D1Geometry* geometry)
  205841. {
  205842. clearRectListClip();
  205843. if (rectListLayer == 0)
  205844. owner.renderingTarget->CreateLayer (rectListLayer.resetAndGetPointerAddress());
  205845. rectListGeometry = geometry;
  205846. shouldClipRectList = true;
  205847. pushClips();
  205848. }
  205849. void clearImageClip()
  205850. {
  205851. popClips();
  205852. if (shouldClipBitmap)
  205853. {
  205854. maskBitmap = 0;
  205855. bitmapMaskBrush = 0;
  205856. shouldClipBitmap = false;
  205857. }
  205858. }
  205859. void clipToImage (const Image& image, const AffineTransform& transform)
  205860. {
  205861. clearImageClip();
  205862. if (bitmapMaskLayer == 0)
  205863. owner.renderingTarget->CreateLayer (bitmapMaskLayer.resetAndGetPointerAddress());
  205864. D2D1_BRUSH_PROPERTIES brushProps;
  205865. brushProps.opacity = 1;
  205866. brushProps.transform = transformToMatrix (transform);
  205867. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  205868. D2D1_SIZE_U size;
  205869. size.width = image.getWidth();
  205870. size.height = image.getHeight();
  205871. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205872. maskImage = image.convertedToFormat (Image::ARGB);
  205873. Image::BitmapData bd (this->image, false); // xxx should be maskImage?
  205874. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  205875. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205876. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, maskBitmap.resetAndGetPointerAddress());
  205877. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, bitmapMaskBrush.resetAndGetPointerAddress());
  205878. imageMaskLayerParams = D2D1::LayerParameters();
  205879. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  205880. shouldClipBitmap = true;
  205881. pushClips();
  205882. }
  205883. void popClips()
  205884. {
  205885. if (clipsBitmap)
  205886. {
  205887. owner.renderingTarget->PopLayer();
  205888. clipsBitmap = false;
  205889. }
  205890. if (clipsComplex)
  205891. {
  205892. owner.renderingTarget->PopLayer();
  205893. clipsComplex = false;
  205894. }
  205895. if (clipsRectList)
  205896. {
  205897. owner.renderingTarget->PopLayer();
  205898. clipsRectList = false;
  205899. }
  205900. if (clipsRect)
  205901. {
  205902. owner.renderingTarget->PopAxisAlignedClip();
  205903. clipsRect = false;
  205904. }
  205905. }
  205906. void pushClips()
  205907. {
  205908. if (shouldClipRect && ! clipsRect)
  205909. {
  205910. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  205911. clipsRect = true;
  205912. }
  205913. if (shouldClipRectList && ! clipsRectList)
  205914. {
  205915. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  205916. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  205917. layerParams.geometricMask = rectListGeometry;
  205918. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  205919. clipsRectList = true;
  205920. }
  205921. if (shouldClipComplex && ! clipsComplex)
  205922. {
  205923. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  205924. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  205925. layerParams.geometricMask = complexClipGeometry;
  205926. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  205927. clipsComplex = true;
  205928. }
  205929. if (shouldClipBitmap && ! clipsBitmap)
  205930. {
  205931. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  205932. clipsBitmap = true;
  205933. }
  205934. }
  205935. void setFill (const FillType& newFillType)
  205936. {
  205937. if (fillType != newFillType)
  205938. {
  205939. fillType = newFillType;
  205940. clearFill();
  205941. }
  205942. }
  205943. void clearFont()
  205944. {
  205945. currentFontFace = localFontFace = 0;
  205946. }
  205947. void setFont (const Font& newFont)
  205948. {
  205949. if (font != newFont)
  205950. {
  205951. font = newFont;
  205952. clearFont();
  205953. }
  205954. }
  205955. void createFont()
  205956. {
  205957. // xxx The font shouldn't be managed by the graphics context.
  205958. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  205959. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  205960. // WindowsTypeface class.
  205961. if (currentFontFace == 0)
  205962. {
  205963. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  205964. fontScaling = systemType->getAscent();
  205965. BOOL fontFound;
  205966. uint32 fontIndex;
  205967. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  205968. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  205969. if (! fontFound)
  205970. fontIndex = 0;
  205971. ComSmartPtr <IDWriteFontFamily> fontFam;
  205972. fonts->GetFontFamily (fontIndex, fontFam.resetAndGetPointerAddress());
  205973. ComSmartPtr <IDWriteFont> font;
  205974. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  205975. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  205976. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, font.resetAndGetPointerAddress());
  205977. font->CreateFontFace (localFontFace.resetAndGetPointerAddress());
  205978. currentFontFace = localFontFace;
  205979. }
  205980. }
  205981. void setOpacity (float newOpacity)
  205982. {
  205983. fillType.setOpacity (newOpacity);
  205984. if (currentBrush != 0)
  205985. currentBrush->SetOpacity (newOpacity);
  205986. }
  205987. void clearFill()
  205988. {
  205989. gradientStops = 0;
  205990. linearGradient = 0;
  205991. radialGradient = 0;
  205992. bitmap = 0;
  205993. bitmapBrush = 0;
  205994. currentBrush = 0;
  205995. }
  205996. void createBrush()
  205997. {
  205998. if (currentBrush == 0)
  205999. {
  206000. const int x = origin.getX();
  206001. const int y = origin.getY();
  206002. if (fillType.isColour())
  206003. {
  206004. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  206005. owner.colourBrush->SetColor (colour);
  206006. currentBrush = owner.colourBrush;
  206007. }
  206008. else if (fillType.isTiledImage())
  206009. {
  206010. D2D1_BRUSH_PROPERTIES brushProps;
  206011. brushProps.opacity = fillType.getOpacity();
  206012. brushProps.transform = transformToMatrix (fillType.transform);
  206013. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  206014. image = fillType.image;
  206015. D2D1_SIZE_U size;
  206016. size.width = image.getWidth();
  206017. size.height = image.getHeight();
  206018. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206019. this->image = image.convertedToFormat (Image::ARGB);
  206020. Image::BitmapData bd (this->image, false);
  206021. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206022. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206023. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, bitmap.resetAndGetPointerAddress());
  206024. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, bitmapBrush.resetAndGetPointerAddress());
  206025. currentBrush = bitmapBrush;
  206026. }
  206027. else if (fillType.isGradient())
  206028. {
  206029. gradientStops = 0;
  206030. D2D1_BRUSH_PROPERTIES brushProps;
  206031. brushProps.opacity = fillType.getOpacity();
  206032. brushProps.transform = transformToMatrix (fillType.transform);
  206033. const int numColors = fillType.gradient->getNumColours();
  206034. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206035. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206036. {
  206037. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206038. stops[i].position = fillType.gradient->getColourPosition(i);
  206039. }
  206040. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, gradientStops.resetAndGetPointerAddress());
  206041. if (fillType.gradient->isRadial)
  206042. {
  206043. radialGradient = 0;
  206044. const Point<float>& p1 = fillType.gradient->point1;
  206045. const Point<float>& p2 = fillType.gradient->point2;
  206046. float r = p1.getDistanceFrom (p2);
  206047. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206048. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206049. D2D1::Point2F (0, 0),
  206050. r, r);
  206051. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, radialGradient.resetAndGetPointerAddress());
  206052. currentBrush = radialGradient;
  206053. }
  206054. else
  206055. {
  206056. linearGradient = 0;
  206057. const Point<float>& p1 = fillType.gradient->point1;
  206058. const Point<float>& p2 = fillType.gradient->point2;
  206059. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206060. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206061. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206062. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, linearGradient.resetAndGetPointerAddress());
  206063. currentBrush = linearGradient;
  206064. }
  206065. }
  206066. }
  206067. }
  206068. //xxx most of these members should probably be private...
  206069. Direct2DLowLevelGraphicsContext& owner;
  206070. Point<int> origin;
  206071. Font font;
  206072. float fontScaling;
  206073. IDWriteFontFace* currentFontFace;
  206074. ComSmartPtr <IDWriteFontFace> localFontFace;
  206075. FillType fillType;
  206076. Image image;
  206077. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206078. Rectangle<int> clipRect;
  206079. bool clipsRect, shouldClipRect;
  206080. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206081. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206082. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206083. bool clipsComplex, shouldClipComplex;
  206084. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206085. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206086. ComSmartPtr <ID2D1Layer> rectListLayer;
  206087. bool clipsRectList, shouldClipRectList;
  206088. Image maskImage;
  206089. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206090. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206091. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206092. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206093. bool clipsBitmap, shouldClipBitmap;
  206094. ID2D1Brush* currentBrush;
  206095. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206096. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206097. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206098. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206099. private:
  206100. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SavedState);
  206101. };
  206102. private:
  206103. HWND hwnd;
  206104. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206105. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206106. Rectangle<int> bounds;
  206107. SavedState* currentState;
  206108. OwnedArray<SavedState> states;
  206109. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206110. {
  206111. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206112. }
  206113. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206114. {
  206115. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206116. }
  206117. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206118. {
  206119. transform.transformPoint (x, y);
  206120. return D2D1::Point2F (x, y);
  206121. }
  206122. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206123. {
  206124. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206125. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206126. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206127. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206128. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206129. }
  206130. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206131. {
  206132. ID2D1PathGeometry* p = 0;
  206133. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206134. ComSmartPtr <ID2D1GeometrySink> sink;
  206135. HRESULT hr = p->Open (sink.resetAndGetPointerAddress()); // xxx handle error
  206136. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206137. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206138. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206139. hr = sink->Close();
  206140. return p;
  206141. }
  206142. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206143. {
  206144. Path::Iterator it (path);
  206145. while (it.next())
  206146. {
  206147. switch (it.elementType)
  206148. {
  206149. case Path::Iterator::cubicTo:
  206150. {
  206151. D2D1_BEZIER_SEGMENT seg;
  206152. transform.transformPoint (it.x1, it.y1);
  206153. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206154. transform.transformPoint (it.x2, it.y2);
  206155. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206156. transform.transformPoint(it.x3, it.y3);
  206157. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206158. sink->AddBezier (seg);
  206159. break;
  206160. }
  206161. case Path::Iterator::lineTo:
  206162. {
  206163. transform.transformPoint (it.x1, it.y1);
  206164. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206165. break;
  206166. }
  206167. case Path::Iterator::quadraticTo:
  206168. {
  206169. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206170. transform.transformPoint (it.x1, it.y1);
  206171. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206172. transform.transformPoint (it.x2, it.y2);
  206173. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206174. sink->AddQuadraticBezier (seg);
  206175. break;
  206176. }
  206177. case Path::Iterator::closePath:
  206178. {
  206179. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206180. break;
  206181. }
  206182. case Path::Iterator::startNewSubPath:
  206183. {
  206184. transform.transformPoint (it.x1, it.y1);
  206185. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206186. break;
  206187. }
  206188. }
  206189. }
  206190. }
  206191. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206192. {
  206193. ID2D1PathGeometry* p = 0;
  206194. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206195. ComSmartPtr <ID2D1GeometrySink> sink;
  206196. HRESULT hr = p->Open (sink.resetAndGetPointerAddress());
  206197. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206198. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206199. hr = sink->Close();
  206200. return p;
  206201. }
  206202. static const D2D1::Matrix3x2F transformToMatrix (const AffineTransform& transform)
  206203. {
  206204. D2D1::Matrix3x2F matrix;
  206205. matrix._11 = transform.mat00;
  206206. matrix._12 = transform.mat10;
  206207. matrix._21 = transform.mat01;
  206208. matrix._22 = transform.mat11;
  206209. matrix._31 = transform.mat02;
  206210. matrix._32 = transform.mat12;
  206211. return matrix;
  206212. }
  206213. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Direct2DLowLevelGraphicsContext);
  206214. };
  206215. #endif
  206216. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206217. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206218. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206219. // compiled on its own).
  206220. #if JUCE_INCLUDED_FILE
  206221. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206222. // these are in the windows SDK, but need to be repeated here for GCC..
  206223. #ifndef GET_APPCOMMAND_LPARAM
  206224. #define FAPPCOMMAND_MASK 0xF000
  206225. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206226. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206227. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206228. #define APPCOMMAND_MEDIA_STOP 13
  206229. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206230. #define WM_APPCOMMAND 0x0319
  206231. #endif
  206232. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206233. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206234. extern bool juce_IsRunningInWine();
  206235. #ifndef ULW_ALPHA
  206236. #define ULW_ALPHA 0x00000002
  206237. #endif
  206238. #ifndef AC_SRC_ALPHA
  206239. #define AC_SRC_ALPHA 0x01
  206240. #endif
  206241. static bool shouldDeactivateTitleBar = true;
  206242. #define WM_TRAYNOTIFY WM_USER + 100
  206243. using ::abs;
  206244. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206245. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206246. bool Desktop::canUseSemiTransparentWindows() throw()
  206247. {
  206248. if (updateLayeredWindow == 0)
  206249. {
  206250. if (! juce_IsRunningInWine())
  206251. {
  206252. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206253. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206254. }
  206255. }
  206256. return updateLayeredWindow != 0;
  206257. }
  206258. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  206259. {
  206260. return upright;
  206261. }
  206262. const int extendedKeyModifier = 0x10000;
  206263. const int KeyPress::spaceKey = VK_SPACE;
  206264. const int KeyPress::returnKey = VK_RETURN;
  206265. const int KeyPress::escapeKey = VK_ESCAPE;
  206266. const int KeyPress::backspaceKey = VK_BACK;
  206267. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206268. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206269. const int KeyPress::tabKey = VK_TAB;
  206270. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206271. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206272. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206273. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206274. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206275. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206276. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206277. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206278. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206279. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206280. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206281. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206282. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206283. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206284. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206285. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206286. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206287. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206288. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206289. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206290. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206291. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206292. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206293. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206294. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206295. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206296. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206297. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206298. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206299. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206300. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206301. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206302. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206303. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206304. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206305. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206306. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206307. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206308. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206309. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206310. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206311. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206312. const int KeyPress::playKey = 0x30000;
  206313. const int KeyPress::stopKey = 0x30001;
  206314. const int KeyPress::fastForwardKey = 0x30002;
  206315. const int KeyPress::rewindKey = 0x30003;
  206316. class WindowsBitmapImage : public Image::SharedImage
  206317. {
  206318. public:
  206319. HBITMAP hBitmap;
  206320. HGDIOBJ previousBitmap;
  206321. BITMAPV4HEADER bitmapInfo;
  206322. HDC hdc;
  206323. unsigned char* bitmapData;
  206324. WindowsBitmapImage (const Image::PixelFormat format_,
  206325. const int w, const int h, const bool clearImage)
  206326. : Image::SharedImage (format_, w, h)
  206327. {
  206328. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206329. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206330. zerostruct (bitmapInfo);
  206331. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206332. bitmapInfo.bV4Width = w;
  206333. bitmapInfo.bV4Height = h;
  206334. bitmapInfo.bV4Planes = 1;
  206335. bitmapInfo.bV4CSType = 1;
  206336. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206337. if (format_ == Image::ARGB)
  206338. {
  206339. bitmapInfo.bV4AlphaMask = 0xff000000;
  206340. bitmapInfo.bV4RedMask = 0xff0000;
  206341. bitmapInfo.bV4GreenMask = 0xff00;
  206342. bitmapInfo.bV4BlueMask = 0xff;
  206343. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206344. }
  206345. else
  206346. {
  206347. bitmapInfo.bV4V4Compression = BI_RGB;
  206348. }
  206349. lineStride = -((w * pixelStride + 3) & ~3);
  206350. HDC dc = GetDC (0);
  206351. hdc = CreateCompatibleDC (dc);
  206352. ReleaseDC (0, dc);
  206353. SetMapMode (hdc, MM_TEXT);
  206354. hBitmap = CreateDIBSection (hdc,
  206355. (BITMAPINFO*) &(bitmapInfo),
  206356. DIB_RGB_COLORS,
  206357. (void**) &bitmapData,
  206358. 0, 0);
  206359. previousBitmap = SelectObject (hdc, hBitmap);
  206360. if (format_ == Image::ARGB && clearImage)
  206361. zeromem (bitmapData, abs (h * lineStride));
  206362. imageData = bitmapData - (lineStride * (h - 1));
  206363. }
  206364. ~WindowsBitmapImage()
  206365. {
  206366. SelectObject (hdc, previousBitmap); // Selecting the previous bitmap before deleting the DC avoids a warning in BoundsChecker
  206367. DeleteDC (hdc);
  206368. DeleteObject (hBitmap);
  206369. }
  206370. Image::ImageType getType() const { return Image::NativeImage; }
  206371. LowLevelGraphicsContext* createLowLevelContext()
  206372. {
  206373. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206374. }
  206375. Image::SharedImage* clone()
  206376. {
  206377. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206378. for (int i = 0; i < height; ++i)
  206379. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206380. return im;
  206381. }
  206382. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206383. const int x, const int y,
  206384. const RectangleList& maskedRegion,
  206385. const uint8 updateLayeredWindowAlpha) throw()
  206386. {
  206387. static HDRAWDIB hdd = 0;
  206388. static bool needToCreateDrawDib = true;
  206389. if (needToCreateDrawDib)
  206390. {
  206391. needToCreateDrawDib = false;
  206392. HDC dc = GetDC (0);
  206393. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206394. ReleaseDC (0, dc);
  206395. // only open if we're not palettised
  206396. if (n > 8)
  206397. hdd = DrawDibOpen();
  206398. }
  206399. SetMapMode (dc, MM_TEXT);
  206400. if (transparent)
  206401. {
  206402. POINT p, pos;
  206403. SIZE size;
  206404. RECT windowBounds;
  206405. GetWindowRect (hwnd, &windowBounds);
  206406. p.x = -x;
  206407. p.y = -y;
  206408. pos.x = windowBounds.left;
  206409. pos.y = windowBounds.top;
  206410. size.cx = windowBounds.right - windowBounds.left;
  206411. size.cy = windowBounds.bottom - windowBounds.top;
  206412. BLENDFUNCTION bf;
  206413. bf.AlphaFormat = AC_SRC_ALPHA;
  206414. bf.BlendFlags = 0;
  206415. bf.BlendOp = AC_SRC_OVER;
  206416. bf.SourceConstantAlpha = updateLayeredWindowAlpha;
  206417. if (! maskedRegion.isEmpty())
  206418. {
  206419. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206420. {
  206421. const Rectangle<int>& r = *i.getRectangle();
  206422. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206423. }
  206424. }
  206425. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206426. }
  206427. else
  206428. {
  206429. int savedDC = 0;
  206430. if (! maskedRegion.isEmpty())
  206431. {
  206432. savedDC = SaveDC (dc);
  206433. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206434. {
  206435. const Rectangle<int>& r = *i.getRectangle();
  206436. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206437. }
  206438. }
  206439. if (hdd == 0)
  206440. {
  206441. StretchDIBits (dc,
  206442. x, y, width, height,
  206443. 0, 0, width, height,
  206444. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206445. DIB_RGB_COLORS, SRCCOPY);
  206446. }
  206447. else
  206448. {
  206449. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206450. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206451. 0, 0, width, height, 0);
  206452. }
  206453. if (! maskedRegion.isEmpty())
  206454. RestoreDC (dc, savedDC);
  206455. }
  206456. }
  206457. private:
  206458. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsBitmapImage);
  206459. };
  206460. namespace IconConverters
  206461. {
  206462. const Image createImageFromHBITMAP (HBITMAP bitmap)
  206463. {
  206464. Image im;
  206465. if (bitmap != 0)
  206466. {
  206467. BITMAP bm;
  206468. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206469. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206470. {
  206471. HDC tempDC = GetDC (0);
  206472. HDC dc = CreateCompatibleDC (tempDC);
  206473. ReleaseDC (0, tempDC);
  206474. SelectObject (dc, bitmap);
  206475. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206476. Image::BitmapData imageData (im, true);
  206477. for (int y = bm.bmHeight; --y >= 0;)
  206478. {
  206479. for (int x = bm.bmWidth; --x >= 0;)
  206480. {
  206481. COLORREF col = GetPixel (dc, x, y);
  206482. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  206483. (uint8) GetGValue (col),
  206484. (uint8) GetBValue (col)));
  206485. }
  206486. }
  206487. DeleteDC (dc);
  206488. }
  206489. }
  206490. return im;
  206491. }
  206492. const Image createImageFromHICON (HICON icon)
  206493. {
  206494. ICONINFO info;
  206495. if (GetIconInfo (icon, &info))
  206496. {
  206497. Image mask (createImageFromHBITMAP (info.hbmMask));
  206498. Image image (createImageFromHBITMAP (info.hbmColor));
  206499. if (mask.isValid() && image.isValid())
  206500. {
  206501. for (int y = image.getHeight(); --y >= 0;)
  206502. {
  206503. for (int x = image.getWidth(); --x >= 0;)
  206504. {
  206505. const float brightness = mask.getPixelAt (x, y).getBrightness();
  206506. if (brightness > 0.0f)
  206507. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  206508. }
  206509. }
  206510. return image;
  206511. }
  206512. }
  206513. return Image::null;
  206514. }
  206515. HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  206516. {
  206517. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  206518. Image bitmap (nativeBitmap);
  206519. {
  206520. Graphics g (bitmap);
  206521. g.drawImageAt (image, 0, 0);
  206522. }
  206523. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  206524. ICONINFO info;
  206525. info.fIcon = isIcon;
  206526. info.xHotspot = hotspotX;
  206527. info.yHotspot = hotspotY;
  206528. info.hbmMask = mask;
  206529. info.hbmColor = nativeBitmap->hBitmap;
  206530. HICON hi = CreateIconIndirect (&info);
  206531. DeleteObject (mask);
  206532. return hi;
  206533. }
  206534. }
  206535. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  206536. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  206537. {
  206538. SHORT k = (SHORT) keyCode;
  206539. if ((keyCode & extendedKeyModifier) == 0
  206540. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  206541. k += (SHORT) 'A' - (SHORT) 'a';
  206542. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  206543. (SHORT) '+', VK_OEM_PLUS,
  206544. (SHORT) '-', VK_OEM_MINUS,
  206545. (SHORT) '.', VK_OEM_PERIOD,
  206546. (SHORT) ';', VK_OEM_1,
  206547. (SHORT) ':', VK_OEM_1,
  206548. (SHORT) '/', VK_OEM_2,
  206549. (SHORT) '?', VK_OEM_2,
  206550. (SHORT) '[', VK_OEM_4,
  206551. (SHORT) ']', VK_OEM_6 };
  206552. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  206553. if (k == translatedValues [i])
  206554. k = translatedValues [i + 1];
  206555. return (GetKeyState (k) & 0x8000) != 0;
  206556. }
  206557. class Win32ComponentPeer : public ComponentPeer
  206558. {
  206559. public:
  206560. enum RenderingEngineType
  206561. {
  206562. softwareRenderingEngine = 0,
  206563. direct2DRenderingEngine
  206564. };
  206565. Win32ComponentPeer (Component* const component,
  206566. const int windowStyleFlags,
  206567. HWND parentToAddTo_)
  206568. : ComponentPeer (component, windowStyleFlags),
  206569. dontRepaint (false),
  206570. #if JUCE_DIRECT2D
  206571. currentRenderingEngine (direct2DRenderingEngine),
  206572. #else
  206573. currentRenderingEngine (softwareRenderingEngine),
  206574. #endif
  206575. fullScreen (false),
  206576. isDragging (false),
  206577. isMouseOver (false),
  206578. hasCreatedCaret (false),
  206579. constrainerIsResizing (false),
  206580. currentWindowIcon (0),
  206581. dropTarget (0),
  206582. parentToAddTo (parentToAddTo_),
  206583. updateLayeredWindowAlpha (255)
  206584. {
  206585. callFunctionIfNotLocked (&createWindowCallback, this);
  206586. setTitle (component->getName());
  206587. if ((windowStyleFlags & windowHasDropShadow) != 0
  206588. && Desktop::canUseSemiTransparentWindows())
  206589. {
  206590. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  206591. if (shadower != 0)
  206592. shadower->setOwner (component);
  206593. }
  206594. }
  206595. ~Win32ComponentPeer()
  206596. {
  206597. setTaskBarIcon (Image());
  206598. shadower = 0;
  206599. // do this before the next bit to avoid messages arriving for this window
  206600. // before it's destroyed
  206601. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  206602. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  206603. if (currentWindowIcon != 0)
  206604. DestroyIcon (currentWindowIcon);
  206605. if (dropTarget != 0)
  206606. {
  206607. dropTarget->Release();
  206608. dropTarget = 0;
  206609. }
  206610. #if JUCE_DIRECT2D
  206611. direct2DContext = 0;
  206612. #endif
  206613. }
  206614. void* getNativeHandle() const
  206615. {
  206616. return hwnd;
  206617. }
  206618. void setVisible (bool shouldBeVisible)
  206619. {
  206620. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  206621. if (shouldBeVisible)
  206622. InvalidateRect (hwnd, 0, 0);
  206623. else
  206624. lastPaintTime = 0;
  206625. }
  206626. void setTitle (const String& title)
  206627. {
  206628. SetWindowText (hwnd, title.toUTF16());
  206629. }
  206630. void setPosition (int x, int y)
  206631. {
  206632. offsetWithinParent (x, y);
  206633. SetWindowPos (hwnd, 0,
  206634. x - windowBorder.getLeft(),
  206635. y - windowBorder.getTop(),
  206636. 0, 0,
  206637. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206638. }
  206639. void repaintNowIfTransparent()
  206640. {
  206641. if (isUsingUpdateLayeredWindow() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  206642. handlePaintMessage();
  206643. }
  206644. void updateBorderSize()
  206645. {
  206646. WINDOWINFO info;
  206647. info.cbSize = sizeof (info);
  206648. if (GetWindowInfo (hwnd, &info))
  206649. {
  206650. windowBorder = BorderSize<int> (info.rcClient.top - info.rcWindow.top,
  206651. info.rcClient.left - info.rcWindow.left,
  206652. info.rcWindow.bottom - info.rcClient.bottom,
  206653. info.rcWindow.right - info.rcClient.right);
  206654. }
  206655. #if JUCE_DIRECT2D
  206656. if (direct2DContext != 0)
  206657. direct2DContext->resized();
  206658. #endif
  206659. }
  206660. void setSize (int w, int h)
  206661. {
  206662. SetWindowPos (hwnd, 0, 0, 0,
  206663. w + windowBorder.getLeftAndRight(),
  206664. h + windowBorder.getTopAndBottom(),
  206665. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206666. updateBorderSize();
  206667. repaintNowIfTransparent();
  206668. }
  206669. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  206670. {
  206671. fullScreen = isNowFullScreen;
  206672. offsetWithinParent (x, y);
  206673. SetWindowPos (hwnd, 0,
  206674. x - windowBorder.getLeft(),
  206675. y - windowBorder.getTop(),
  206676. w + windowBorder.getLeftAndRight(),
  206677. h + windowBorder.getTopAndBottom(),
  206678. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206679. updateBorderSize();
  206680. repaintNowIfTransparent();
  206681. }
  206682. const Rectangle<int> getBounds() const
  206683. {
  206684. RECT r;
  206685. GetWindowRect (hwnd, &r);
  206686. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  206687. HWND parentH = GetParent (hwnd);
  206688. if (parentH != 0)
  206689. {
  206690. GetWindowRect (parentH, &r);
  206691. bounds.translate (-r.left, -r.top);
  206692. }
  206693. return windowBorder.subtractedFrom (bounds);
  206694. }
  206695. const Point<int> getScreenPosition() const
  206696. {
  206697. RECT r;
  206698. GetWindowRect (hwnd, &r);
  206699. return Point<int> (r.left + windowBorder.getLeft(),
  206700. r.top + windowBorder.getTop());
  206701. }
  206702. const Point<int> localToGlobal (const Point<int>& relativePosition)
  206703. {
  206704. return relativePosition + getScreenPosition();
  206705. }
  206706. const Point<int> globalToLocal (const Point<int>& screenPosition)
  206707. {
  206708. return screenPosition - getScreenPosition();
  206709. }
  206710. void setAlpha (float newAlpha)
  206711. {
  206712. const uint8 intAlpha = (uint8) jlimit (0, 255, (int) (newAlpha * 255.0f));
  206713. if (component->isOpaque())
  206714. {
  206715. if (newAlpha < 1.0f)
  206716. {
  206717. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  206718. SetLayeredWindowAttributes (hwnd, RGB (0, 0, 0), intAlpha, LWA_ALPHA);
  206719. }
  206720. else
  206721. {
  206722. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  206723. RedrawWindow (hwnd, 0, 0, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
  206724. }
  206725. }
  206726. else
  206727. {
  206728. updateLayeredWindowAlpha = intAlpha;
  206729. component->repaint();
  206730. }
  206731. }
  206732. void setMinimised (bool shouldBeMinimised)
  206733. {
  206734. if (shouldBeMinimised != isMinimised())
  206735. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  206736. }
  206737. bool isMinimised() const
  206738. {
  206739. WINDOWPLACEMENT wp;
  206740. wp.length = sizeof (WINDOWPLACEMENT);
  206741. GetWindowPlacement (hwnd, &wp);
  206742. return wp.showCmd == SW_SHOWMINIMIZED;
  206743. }
  206744. void setFullScreen (bool shouldBeFullScreen)
  206745. {
  206746. setMinimised (false);
  206747. if (fullScreen != shouldBeFullScreen)
  206748. {
  206749. fullScreen = shouldBeFullScreen;
  206750. const WeakReference<Component> deletionChecker (component);
  206751. if (! fullScreen)
  206752. {
  206753. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  206754. if (hasTitleBar())
  206755. ShowWindow (hwnd, SW_SHOWNORMAL);
  206756. if (! boundsCopy.isEmpty())
  206757. {
  206758. setBounds (boundsCopy.getX(),
  206759. boundsCopy.getY(),
  206760. boundsCopy.getWidth(),
  206761. boundsCopy.getHeight(),
  206762. false);
  206763. }
  206764. }
  206765. else
  206766. {
  206767. if (hasTitleBar())
  206768. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  206769. else
  206770. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  206771. }
  206772. if (deletionChecker != 0)
  206773. handleMovedOrResized();
  206774. }
  206775. }
  206776. bool isFullScreen() const
  206777. {
  206778. if (! hasTitleBar())
  206779. return fullScreen;
  206780. WINDOWPLACEMENT wp;
  206781. wp.length = sizeof (wp);
  206782. GetWindowPlacement (hwnd, &wp);
  206783. return wp.showCmd == SW_SHOWMAXIMIZED;
  206784. }
  206785. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  206786. {
  206787. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  206788. && isPositiveAndBelow (position.getY(), component->getHeight())))
  206789. return false;
  206790. RECT r;
  206791. GetWindowRect (hwnd, &r);
  206792. POINT p;
  206793. p.x = position.getX() + r.left + windowBorder.getLeft();
  206794. p.y = position.getY() + r.top + windowBorder.getTop();
  206795. HWND w = WindowFromPoint (p);
  206796. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  206797. }
  206798. const BorderSize<int> getFrameSize() const
  206799. {
  206800. return windowBorder;
  206801. }
  206802. bool setAlwaysOnTop (bool alwaysOnTop)
  206803. {
  206804. const bool oldDeactivate = shouldDeactivateTitleBar;
  206805. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206806. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  206807. 0, 0, 0, 0,
  206808. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206809. shouldDeactivateTitleBar = oldDeactivate;
  206810. if (shadower != 0)
  206811. shadower->componentBroughtToFront (*component);
  206812. return true;
  206813. }
  206814. void toFront (bool makeActive)
  206815. {
  206816. setMinimised (false);
  206817. const bool oldDeactivate = shouldDeactivateTitleBar;
  206818. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206819. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  206820. shouldDeactivateTitleBar = oldDeactivate;
  206821. if (! makeActive)
  206822. {
  206823. // in this case a broughttofront call won't have occured, so do it now..
  206824. handleBroughtToFront();
  206825. }
  206826. }
  206827. void toBehind (ComponentPeer* other)
  206828. {
  206829. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  206830. jassert (otherPeer != 0); // wrong type of window?
  206831. if (otherPeer != 0)
  206832. {
  206833. setMinimised (false);
  206834. // must be careful not to try to put a topmost window behind a normal one, or win32
  206835. // promotes the normal one to be topmost!
  206836. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  206837. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  206838. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206839. else if (otherPeer->getComponent()->isAlwaysOnTop())
  206840. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  206841. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206842. }
  206843. }
  206844. bool isFocused() const
  206845. {
  206846. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  206847. }
  206848. void grabFocus()
  206849. {
  206850. const bool oldDeactivate = shouldDeactivateTitleBar;
  206851. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206852. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  206853. shouldDeactivateTitleBar = oldDeactivate;
  206854. }
  206855. void textInputRequired (const Point<int>&)
  206856. {
  206857. if (! hasCreatedCaret)
  206858. {
  206859. hasCreatedCaret = true;
  206860. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  206861. }
  206862. ShowCaret (hwnd);
  206863. SetCaretPos (0, 0);
  206864. }
  206865. void repaint (const Rectangle<int>& area)
  206866. {
  206867. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  206868. InvalidateRect (hwnd, &r, FALSE);
  206869. }
  206870. void performAnyPendingRepaintsNow()
  206871. {
  206872. MSG m;
  206873. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  206874. DispatchMessage (&m);
  206875. }
  206876. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  206877. {
  206878. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  206879. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  206880. return 0;
  206881. }
  206882. void setTaskBarIcon (const Image& image)
  206883. {
  206884. if (image.isValid())
  206885. {
  206886. HICON hicon = IconConverters::createHICONFromImage (image, TRUE, 0, 0);
  206887. if (taskBarIcon == 0)
  206888. {
  206889. taskBarIcon = new NOTIFYICONDATA();
  206890. zeromem (taskBarIcon, sizeof (NOTIFYICONDATA));
  206891. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  206892. taskBarIcon->hWnd = (HWND) hwnd;
  206893. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  206894. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  206895. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  206896. taskBarIcon->hIcon = hicon;
  206897. taskBarIcon->szTip[0] = 0;
  206898. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  206899. }
  206900. else
  206901. {
  206902. HICON oldIcon = taskBarIcon->hIcon;
  206903. taskBarIcon->hIcon = hicon;
  206904. taskBarIcon->uFlags = NIF_ICON;
  206905. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  206906. DestroyIcon (oldIcon);
  206907. }
  206908. }
  206909. else if (taskBarIcon != 0)
  206910. {
  206911. taskBarIcon->uFlags = 0;
  206912. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  206913. DestroyIcon (taskBarIcon->hIcon);
  206914. taskBarIcon = 0;
  206915. }
  206916. }
  206917. void setTaskBarIconToolTip (const String& toolTip) const
  206918. {
  206919. if (taskBarIcon != 0)
  206920. {
  206921. taskBarIcon->uFlags = NIF_TIP;
  206922. toolTip.copyToUTF16 (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  206923. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  206924. }
  206925. }
  206926. void handleTaskBarEvent (const LPARAM lParam)
  206927. {
  206928. if (component->isCurrentlyBlockedByAnotherModalComponent())
  206929. {
  206930. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  206931. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  206932. {
  206933. Component* const current = Component::getCurrentlyModalComponent();
  206934. if (current != 0)
  206935. current->inputAttemptWhenModal();
  206936. }
  206937. }
  206938. else
  206939. {
  206940. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  206941. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  206942. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  206943. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  206944. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  206945. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  206946. eventMods = eventMods.withoutMouseButtons();
  206947. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  206948. Point<int>(), eventMods, component, component, Time (getMouseEventTime()),
  206949. Point<int>(), Time (getMouseEventTime()), 1, false);
  206950. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  206951. {
  206952. SetFocus (hwnd);
  206953. SetForegroundWindow (hwnd);
  206954. component->mouseDown (e);
  206955. }
  206956. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  206957. {
  206958. component->mouseUp (e);
  206959. }
  206960. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  206961. {
  206962. component->mouseDoubleClick (e);
  206963. }
  206964. else if (lParam == WM_MOUSEMOVE)
  206965. {
  206966. component->mouseMove (e);
  206967. }
  206968. }
  206969. }
  206970. bool isInside (HWND h) const
  206971. {
  206972. return GetAncestor (hwnd, GA_ROOT) == h;
  206973. }
  206974. static void updateKeyModifiers() throw()
  206975. {
  206976. int keyMods = 0;
  206977. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  206978. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  206979. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  206980. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  206981. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  206982. }
  206983. static void updateModifiersFromWParam (const WPARAM wParam)
  206984. {
  206985. int mouseMods = 0;
  206986. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  206987. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  206988. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  206989. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  206990. updateKeyModifiers();
  206991. }
  206992. static int64 getMouseEventTime()
  206993. {
  206994. static int64 eventTimeOffset = 0;
  206995. static DWORD lastMessageTime = 0;
  206996. const DWORD thisMessageTime = GetMessageTime();
  206997. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  206998. {
  206999. lastMessageTime = thisMessageTime;
  207000. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  207001. }
  207002. return eventTimeOffset + thisMessageTime;
  207003. }
  207004. bool dontRepaint;
  207005. static ModifierKeys currentModifiers;
  207006. static ModifierKeys modifiersAtLastCallback;
  207007. private:
  207008. HWND hwnd, parentToAddTo;
  207009. ScopedPointer<DropShadower> shadower;
  207010. RenderingEngineType currentRenderingEngine;
  207011. #if JUCE_DIRECT2D
  207012. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  207013. #endif
  207014. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret, constrainerIsResizing;
  207015. BorderSize<int> windowBorder;
  207016. HICON currentWindowIcon;
  207017. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  207018. IDropTarget* dropTarget;
  207019. uint8 updateLayeredWindowAlpha;
  207020. class TemporaryImage : public Timer
  207021. {
  207022. public:
  207023. TemporaryImage() {}
  207024. ~TemporaryImage() {}
  207025. const Image& getImage (const bool transparent, const int w, const int h)
  207026. {
  207027. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  207028. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  207029. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  207030. startTimer (3000);
  207031. return image;
  207032. }
  207033. void timerCallback()
  207034. {
  207035. stopTimer();
  207036. image = Image::null;
  207037. }
  207038. private:
  207039. Image image;
  207040. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryImage);
  207041. };
  207042. TemporaryImage offscreenImageGenerator;
  207043. class WindowClassHolder : public DeletedAtShutdown
  207044. {
  207045. public:
  207046. WindowClassHolder()
  207047. : windowClassName ("JUCE_")
  207048. {
  207049. // this name has to be different for each app/dll instance because otherwise
  207050. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207051. // window class).
  207052. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207053. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207054. TCHAR moduleFile [1024];
  207055. moduleFile[0] = 0;
  207056. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207057. WORD iconNum = 0;
  207058. WNDCLASSEX wcex;
  207059. wcex.cbSize = sizeof (wcex);
  207060. wcex.style = CS_OWNDC;
  207061. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207062. wcex.lpszClassName = windowClassName.toUTF16();
  207063. wcex.cbClsExtra = 0;
  207064. wcex.cbWndExtra = 32;
  207065. wcex.hInstance = moduleHandle;
  207066. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207067. iconNum = 1;
  207068. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207069. wcex.hCursor = 0;
  207070. wcex.hbrBackground = 0;
  207071. wcex.lpszMenuName = 0;
  207072. RegisterClassEx (&wcex);
  207073. }
  207074. ~WindowClassHolder()
  207075. {
  207076. if (ComponentPeer::getNumPeers() == 0)
  207077. UnregisterClass (windowClassName.toUTF16(), (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207078. clearSingletonInstance();
  207079. }
  207080. String windowClassName;
  207081. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207082. };
  207083. static void* createWindowCallback (void* userData)
  207084. {
  207085. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207086. return 0;
  207087. }
  207088. void createWindow()
  207089. {
  207090. DWORD exstyle = WS_EX_ACCEPTFILES;
  207091. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207092. if (hasTitleBar())
  207093. {
  207094. type |= WS_OVERLAPPED;
  207095. if ((styleFlags & windowHasCloseButton) != 0)
  207096. {
  207097. type |= WS_SYSMENU;
  207098. }
  207099. else
  207100. {
  207101. // annoyingly, windows won't let you have a min/max button without a close button
  207102. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207103. }
  207104. if ((styleFlags & windowIsResizable) != 0)
  207105. type |= WS_THICKFRAME;
  207106. }
  207107. else if (parentToAddTo != 0)
  207108. {
  207109. type |= WS_CHILD;
  207110. }
  207111. else
  207112. {
  207113. type |= WS_POPUP | WS_SYSMENU;
  207114. }
  207115. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207116. exstyle |= WS_EX_TOOLWINDOW;
  207117. else
  207118. exstyle |= WS_EX_APPWINDOW;
  207119. if ((styleFlags & windowHasMinimiseButton) != 0)
  207120. type |= WS_MINIMIZEBOX;
  207121. if ((styleFlags & windowHasMaximiseButton) != 0)
  207122. type |= WS_MAXIMIZEBOX;
  207123. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207124. exstyle |= WS_EX_TRANSPARENT;
  207125. if ((styleFlags & windowIsSemiTransparent) != 0
  207126. && Desktop::canUseSemiTransparentWindows())
  207127. exstyle |= WS_EX_LAYERED;
  207128. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName.toUTF16(), L"", type, 0, 0, 0, 0,
  207129. parentToAddTo, 0, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(), 0);
  207130. #if JUCE_DIRECT2D
  207131. updateDirect2DContext();
  207132. #endif
  207133. if (hwnd != 0)
  207134. {
  207135. SetWindowLongPtr (hwnd, 0, 0);
  207136. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207137. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207138. if (dropTarget == 0)
  207139. dropTarget = new JuceDropTarget (this);
  207140. RegisterDragDrop (hwnd, dropTarget);
  207141. updateBorderSize();
  207142. // Calling this function here is (for some reason) necessary to make Windows
  207143. // correctly enable the menu items that we specify in the wm_initmenu message.
  207144. GetSystemMenu (hwnd, false);
  207145. const float alpha = component->getAlpha();
  207146. if (alpha < 1.0f)
  207147. setAlpha (alpha);
  207148. }
  207149. else
  207150. {
  207151. jassertfalse;
  207152. }
  207153. }
  207154. static void* destroyWindowCallback (void* handle)
  207155. {
  207156. RevokeDragDrop ((HWND) handle);
  207157. DestroyWindow ((HWND) handle);
  207158. return 0;
  207159. }
  207160. static void* toFrontCallback1 (void* h)
  207161. {
  207162. SetForegroundWindow ((HWND) h);
  207163. return 0;
  207164. }
  207165. static void* toFrontCallback2 (void* h)
  207166. {
  207167. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207168. return 0;
  207169. }
  207170. static void* setFocusCallback (void* h)
  207171. {
  207172. SetFocus ((HWND) h);
  207173. return 0;
  207174. }
  207175. static void* getFocusCallback (void*)
  207176. {
  207177. return GetFocus();
  207178. }
  207179. void offsetWithinParent (int& x, int& y) const
  207180. {
  207181. if (isUsingUpdateLayeredWindow())
  207182. {
  207183. HWND parentHwnd = GetParent (hwnd);
  207184. if (parentHwnd != 0)
  207185. {
  207186. RECT parentRect;
  207187. GetWindowRect (parentHwnd, &parentRect);
  207188. x += parentRect.left;
  207189. y += parentRect.top;
  207190. }
  207191. }
  207192. }
  207193. bool isUsingUpdateLayeredWindow() const
  207194. {
  207195. return ! component->isOpaque();
  207196. }
  207197. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207198. void setIcon (const Image& newIcon)
  207199. {
  207200. HICON hicon = IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0);
  207201. if (hicon != 0)
  207202. {
  207203. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207204. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207205. if (currentWindowIcon != 0)
  207206. DestroyIcon (currentWindowIcon);
  207207. currentWindowIcon = hicon;
  207208. }
  207209. }
  207210. void handlePaintMessage()
  207211. {
  207212. #if JUCE_DIRECT2D
  207213. if (direct2DContext != 0)
  207214. {
  207215. RECT r;
  207216. if (GetUpdateRect (hwnd, &r, false))
  207217. {
  207218. direct2DContext->start();
  207219. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207220. handlePaint (*direct2DContext);
  207221. direct2DContext->end();
  207222. }
  207223. }
  207224. else
  207225. #endif
  207226. {
  207227. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207228. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207229. PAINTSTRUCT paintStruct;
  207230. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207231. // message and become re-entrant, but that's OK
  207232. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207233. // corrupt the image it's using to paint into, so do a check here.
  207234. static bool reentrant = false;
  207235. if (reentrant)
  207236. {
  207237. DeleteObject (rgn);
  207238. EndPaint (hwnd, &paintStruct);
  207239. return;
  207240. }
  207241. const ScopedValueSetter<bool> setter (reentrant, true, false);
  207242. // this is the rectangle to update..
  207243. int x = paintStruct.rcPaint.left;
  207244. int y = paintStruct.rcPaint.top;
  207245. int w = paintStruct.rcPaint.right - x;
  207246. int h = paintStruct.rcPaint.bottom - y;
  207247. const bool transparent = isUsingUpdateLayeredWindow();
  207248. if (transparent)
  207249. {
  207250. // it's not possible to have a transparent window with a title bar at the moment!
  207251. jassert (! hasTitleBar());
  207252. RECT r;
  207253. GetWindowRect (hwnd, &r);
  207254. x = y = 0;
  207255. w = r.right - r.left;
  207256. h = r.bottom - r.top;
  207257. }
  207258. if (w > 0 && h > 0)
  207259. {
  207260. clearMaskedRegion();
  207261. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207262. RectangleList contextClip;
  207263. const Rectangle<int> clipBounds (0, 0, w, h);
  207264. bool needToPaintAll = true;
  207265. if (regionType == COMPLEXREGION && ! transparent)
  207266. {
  207267. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207268. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207269. DeleteObject (clipRgn);
  207270. char rgnData [8192];
  207271. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207272. if (res > 0 && res <= sizeof (rgnData))
  207273. {
  207274. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207275. if (hdr->iType == RDH_RECTANGLES
  207276. && hdr->rcBound.right - hdr->rcBound.left >= w
  207277. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207278. {
  207279. needToPaintAll = false;
  207280. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207281. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207282. while (--num >= 0)
  207283. {
  207284. if (rects->right <= x + w && rects->bottom <= y + h)
  207285. {
  207286. const int cx = jmax (x, (int) rects->left);
  207287. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207288. .getIntersection (clipBounds));
  207289. }
  207290. else
  207291. {
  207292. needToPaintAll = true;
  207293. break;
  207294. }
  207295. ++rects;
  207296. }
  207297. }
  207298. }
  207299. }
  207300. if (needToPaintAll)
  207301. {
  207302. contextClip.clear();
  207303. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207304. }
  207305. if (transparent)
  207306. {
  207307. RectangleList::Iterator i (contextClip);
  207308. while (i.next())
  207309. offscreenImage.clear (*i.getRectangle());
  207310. }
  207311. // if the component's not opaque, this won't draw properly unless the platform can support this
  207312. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207313. updateCurrentModifiers();
  207314. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207315. handlePaint (context);
  207316. if (! dontRepaint)
  207317. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207318. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion, updateLayeredWindowAlpha);
  207319. }
  207320. DeleteObject (rgn);
  207321. EndPaint (hwnd, &paintStruct);
  207322. }
  207323. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207324. _fpreset(); // because some graphics cards can unmask FP exceptions
  207325. #endif
  207326. lastPaintTime = Time::getMillisecondCounter();
  207327. }
  207328. void doMouseEvent (const Point<int>& position)
  207329. {
  207330. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207331. }
  207332. const StringArray getAvailableRenderingEngines()
  207333. {
  207334. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207335. #if JUCE_DIRECT2D
  207336. // xxx is this correct? Seems to enable it on Vista too??
  207337. OSVERSIONINFO info;
  207338. zerostruct (info);
  207339. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207340. GetVersionEx (&info);
  207341. if (info.dwMajorVersion >= 6)
  207342. s.add ("Direct2D");
  207343. #endif
  207344. return s;
  207345. }
  207346. int getCurrentRenderingEngine() throw()
  207347. {
  207348. return currentRenderingEngine;
  207349. }
  207350. #if JUCE_DIRECT2D
  207351. void updateDirect2DContext()
  207352. {
  207353. if (currentRenderingEngine != direct2DRenderingEngine)
  207354. direct2DContext = 0;
  207355. else if (direct2DContext == 0)
  207356. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207357. }
  207358. #endif
  207359. void setCurrentRenderingEngine (int index)
  207360. {
  207361. (void) index;
  207362. #if JUCE_DIRECT2D
  207363. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207364. updateDirect2DContext();
  207365. repaint (component->getLocalBounds());
  207366. #endif
  207367. }
  207368. void doMouseMove (const Point<int>& position)
  207369. {
  207370. if (! isMouseOver)
  207371. {
  207372. isMouseOver = true;
  207373. updateKeyModifiers();
  207374. TRACKMOUSEEVENT tme;
  207375. tme.cbSize = sizeof (tme);
  207376. tme.dwFlags = TME_LEAVE;
  207377. tme.hwndTrack = hwnd;
  207378. tme.dwHoverTime = 0;
  207379. if (! TrackMouseEvent (&tme))
  207380. jassertfalse;
  207381. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207382. }
  207383. else if (! isDragging)
  207384. {
  207385. if (! contains (position, false))
  207386. return;
  207387. }
  207388. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207389. static uint32 lastMouseTime = 0;
  207390. const uint32 now = Time::getMillisecondCounter();
  207391. const int maxMouseMovesPerSecond = 60;
  207392. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207393. {
  207394. lastMouseTime = now;
  207395. doMouseEvent (position);
  207396. }
  207397. }
  207398. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207399. {
  207400. if (GetCapture() != hwnd)
  207401. SetCapture (hwnd);
  207402. doMouseMove (position);
  207403. updateModifiersFromWParam (wParam);
  207404. isDragging = true;
  207405. doMouseEvent (position);
  207406. }
  207407. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207408. {
  207409. updateModifiersFromWParam (wParam);
  207410. isDragging = false;
  207411. // release the mouse capture if the user has released all buttons
  207412. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207413. ReleaseCapture();
  207414. doMouseEvent (position);
  207415. }
  207416. void doCaptureChanged()
  207417. {
  207418. if (constrainerIsResizing)
  207419. {
  207420. if (constrainer != 0)
  207421. constrainer->resizeEnd();
  207422. constrainerIsResizing = false;
  207423. }
  207424. if (isDragging)
  207425. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207426. }
  207427. void doMouseExit()
  207428. {
  207429. isMouseOver = false;
  207430. doMouseEvent (getCurrentMousePos());
  207431. }
  207432. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207433. {
  207434. updateKeyModifiers();
  207435. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207436. handleMouseWheel (0, position, getMouseEventTime(),
  207437. isVertical ? 0.0f : amount,
  207438. isVertical ? amount : 0.0f);
  207439. }
  207440. void sendModifierKeyChangeIfNeeded()
  207441. {
  207442. if (modifiersAtLastCallback != currentModifiers)
  207443. {
  207444. modifiersAtLastCallback = currentModifiers;
  207445. handleModifierKeysChange();
  207446. }
  207447. }
  207448. bool doKeyUp (const WPARAM key)
  207449. {
  207450. updateKeyModifiers();
  207451. switch (key)
  207452. {
  207453. case VK_SHIFT:
  207454. case VK_CONTROL:
  207455. case VK_MENU:
  207456. case VK_CAPITAL:
  207457. case VK_LWIN:
  207458. case VK_RWIN:
  207459. case VK_APPS:
  207460. case VK_NUMLOCK:
  207461. case VK_SCROLL:
  207462. case VK_LSHIFT:
  207463. case VK_RSHIFT:
  207464. case VK_LCONTROL:
  207465. case VK_LMENU:
  207466. case VK_RCONTROL:
  207467. case VK_RMENU:
  207468. sendModifierKeyChangeIfNeeded();
  207469. }
  207470. return handleKeyUpOrDown (false)
  207471. || Component::getCurrentlyModalComponent() != 0;
  207472. }
  207473. bool doKeyDown (const WPARAM key)
  207474. {
  207475. updateKeyModifiers();
  207476. bool used = false;
  207477. switch (key)
  207478. {
  207479. case VK_SHIFT:
  207480. case VK_LSHIFT:
  207481. case VK_RSHIFT:
  207482. case VK_CONTROL:
  207483. case VK_LCONTROL:
  207484. case VK_RCONTROL:
  207485. case VK_MENU:
  207486. case VK_LMENU:
  207487. case VK_RMENU:
  207488. case VK_LWIN:
  207489. case VK_RWIN:
  207490. case VK_CAPITAL:
  207491. case VK_NUMLOCK:
  207492. case VK_SCROLL:
  207493. case VK_APPS:
  207494. sendModifierKeyChangeIfNeeded();
  207495. break;
  207496. case VK_LEFT:
  207497. case VK_RIGHT:
  207498. case VK_UP:
  207499. case VK_DOWN:
  207500. case VK_PRIOR:
  207501. case VK_NEXT:
  207502. case VK_HOME:
  207503. case VK_END:
  207504. case VK_DELETE:
  207505. case VK_INSERT:
  207506. case VK_F1:
  207507. case VK_F2:
  207508. case VK_F3:
  207509. case VK_F4:
  207510. case VK_F5:
  207511. case VK_F6:
  207512. case VK_F7:
  207513. case VK_F8:
  207514. case VK_F9:
  207515. case VK_F10:
  207516. case VK_F11:
  207517. case VK_F12:
  207518. case VK_F13:
  207519. case VK_F14:
  207520. case VK_F15:
  207521. case VK_F16:
  207522. used = handleKeyUpOrDown (true);
  207523. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  207524. break;
  207525. case VK_ADD:
  207526. case VK_SUBTRACT:
  207527. case VK_MULTIPLY:
  207528. case VK_DIVIDE:
  207529. case VK_SEPARATOR:
  207530. case VK_DECIMAL:
  207531. used = handleKeyUpOrDown (true);
  207532. break;
  207533. default:
  207534. used = handleKeyUpOrDown (true);
  207535. {
  207536. MSG msg;
  207537. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  207538. {
  207539. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  207540. // manually generate the key-press event that matches this key-down.
  207541. const UINT keyChar = MapVirtualKey (key, 2);
  207542. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  207543. }
  207544. }
  207545. break;
  207546. }
  207547. if (Component::getCurrentlyModalComponent() != 0)
  207548. used = true;
  207549. return used;
  207550. }
  207551. bool doKeyChar (int key, const LPARAM flags)
  207552. {
  207553. updateKeyModifiers();
  207554. juce_wchar textChar = (juce_wchar) key;
  207555. const int virtualScanCode = (flags >> 16) & 0xff;
  207556. if (key >= '0' && key <= '9')
  207557. {
  207558. switch (virtualScanCode) // check for a numeric keypad scan-code
  207559. {
  207560. case 0x52:
  207561. case 0x4f:
  207562. case 0x50:
  207563. case 0x51:
  207564. case 0x4b:
  207565. case 0x4c:
  207566. case 0x4d:
  207567. case 0x47:
  207568. case 0x48:
  207569. case 0x49:
  207570. key = (key - '0') + KeyPress::numberPad0;
  207571. break;
  207572. default:
  207573. break;
  207574. }
  207575. }
  207576. else
  207577. {
  207578. // convert the scan code to an unmodified character code..
  207579. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  207580. UINT keyChar = MapVirtualKey (virtualKey, 2);
  207581. keyChar = LOWORD (keyChar);
  207582. if (keyChar != 0)
  207583. key = (int) keyChar;
  207584. // avoid sending junk text characters for some control-key combinations
  207585. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  207586. textChar = 0;
  207587. }
  207588. return handleKeyPress (key, textChar);
  207589. }
  207590. bool doAppCommand (const LPARAM lParam)
  207591. {
  207592. int key = 0;
  207593. switch (GET_APPCOMMAND_LPARAM (lParam))
  207594. {
  207595. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  207596. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  207597. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  207598. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  207599. default: break;
  207600. }
  207601. if (key != 0)
  207602. {
  207603. updateKeyModifiers();
  207604. if (hwnd == GetActiveWindow())
  207605. {
  207606. handleKeyPress (key, 0);
  207607. return true;
  207608. }
  207609. }
  207610. return false;
  207611. }
  207612. bool isConstrainedNativeWindow() const
  207613. {
  207614. return constrainer != 0
  207615. && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable);
  207616. }
  207617. LRESULT handleSizeConstraining (RECT* const r, const WPARAM wParam)
  207618. {
  207619. if (isConstrainedNativeWindow())
  207620. {
  207621. Rectangle<int> pos (r->left, r->top, r->right - r->left, r->bottom - r->top);
  207622. constrainer->checkBounds (pos, windowBorder.addedTo (component->getBounds()),
  207623. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207624. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  207625. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  207626. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  207627. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  207628. r->left = pos.getX();
  207629. r->top = pos.getY();
  207630. r->right = pos.getRight();
  207631. r->bottom = pos.getBottom();
  207632. }
  207633. return TRUE;
  207634. }
  207635. LRESULT handlePositionChanging (WINDOWPOS* const wp)
  207636. {
  207637. if (isConstrainedNativeWindow())
  207638. {
  207639. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  207640. && ! Component::isMouseButtonDownAnywhere())
  207641. {
  207642. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  207643. const Rectangle<int> current (windowBorder.addedTo (component->getBounds()));
  207644. constrainer->checkBounds (pos, current,
  207645. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207646. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  207647. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  207648. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  207649. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  207650. wp->x = pos.getX();
  207651. wp->y = pos.getY();
  207652. wp->cx = pos.getWidth();
  207653. wp->cy = pos.getHeight();
  207654. }
  207655. }
  207656. return 0;
  207657. }
  207658. void handleAppActivation (const WPARAM wParam)
  207659. {
  207660. modifiersAtLastCallback = -1;
  207661. updateKeyModifiers();
  207662. if (isMinimised())
  207663. {
  207664. component->repaint();
  207665. handleMovedOrResized();
  207666. if (! ComponentPeer::isValidPeer (this))
  207667. return;
  207668. }
  207669. if (LOWORD (wParam) == WA_CLICKACTIVE && component->isCurrentlyBlockedByAnotherModalComponent())
  207670. {
  207671. Component* const underMouse = component->getComponentAt (component->getMouseXYRelative());
  207672. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  207673. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  207674. }
  207675. else
  207676. {
  207677. handleBroughtToFront();
  207678. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207679. Component::getCurrentlyModalComponent()->toFront (true);
  207680. }
  207681. }
  207682. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  207683. {
  207684. public:
  207685. JuceDropTarget (Win32ComponentPeer* const owner_)
  207686. : owner (owner_)
  207687. {
  207688. }
  207689. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207690. {
  207691. updateFileList (pDataObject);
  207692. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207693. *pdwEffect = DROPEFFECT_COPY;
  207694. return S_OK;
  207695. }
  207696. HRESULT __stdcall DragLeave()
  207697. {
  207698. owner->handleFileDragExit (files);
  207699. return S_OK;
  207700. }
  207701. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207702. {
  207703. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207704. *pdwEffect = DROPEFFECT_COPY;
  207705. return S_OK;
  207706. }
  207707. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207708. {
  207709. updateFileList (pDataObject);
  207710. owner->handleFileDragDrop (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207711. *pdwEffect = DROPEFFECT_COPY;
  207712. return S_OK;
  207713. }
  207714. private:
  207715. Win32ComponentPeer* const owner;
  207716. StringArray files;
  207717. void updateFileList (IDataObject* const pDataObject)
  207718. {
  207719. files.clear();
  207720. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207721. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207722. if (pDataObject->GetData (&format, &medium) == S_OK)
  207723. {
  207724. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  207725. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  207726. unsigned int i = 0;
  207727. if (pDropFiles->fWide)
  207728. {
  207729. const WCHAR* const fname = (WCHAR*) addBytesToPointer (pDropFiles, sizeof (DROPFILES));
  207730. for (;;)
  207731. {
  207732. unsigned int len = 0;
  207733. while (i + len < totalLen && fname [i + len] != 0)
  207734. ++len;
  207735. if (len == 0)
  207736. break;
  207737. files.add (String (fname + i, len));
  207738. i += len + 1;
  207739. }
  207740. }
  207741. else
  207742. {
  207743. const char* const fname = (const char*) addBytesToPointer (pDropFiles, sizeof (DROPFILES));
  207744. for (;;)
  207745. {
  207746. unsigned int len = 0;
  207747. while (i + len < totalLen && fname [i + len] != 0)
  207748. ++len;
  207749. if (len == 0)
  207750. break;
  207751. files.add (String (fname + i, len));
  207752. i += len + 1;
  207753. }
  207754. }
  207755. GlobalUnlock (medium.hGlobal);
  207756. }
  207757. }
  207758. JUCE_DECLARE_NON_COPYABLE (JuceDropTarget);
  207759. };
  207760. void doSettingChange()
  207761. {
  207762. Desktop::getInstance().refreshMonitorSizes();
  207763. if (fullScreen && ! isMinimised())
  207764. {
  207765. const Rectangle<int> r (component->getParentMonitorArea());
  207766. SetWindowPos (hwnd, 0, r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  207767. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  207768. }
  207769. }
  207770. public:
  207771. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207772. {
  207773. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  207774. if (peer != 0)
  207775. {
  207776. jassert (isValidPeer (peer));
  207777. return peer->peerWindowProc (h, message, wParam, lParam);
  207778. }
  207779. return DefWindowProcW (h, message, wParam, lParam);
  207780. }
  207781. private:
  207782. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  207783. {
  207784. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  207785. return callback (userData);
  207786. else
  207787. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  207788. }
  207789. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  207790. {
  207791. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  207792. }
  207793. const Point<int> getCurrentMousePos() throw()
  207794. {
  207795. RECT wr;
  207796. GetWindowRect (hwnd, &wr);
  207797. const DWORD mp = GetMessagePos();
  207798. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  207799. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  207800. }
  207801. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207802. {
  207803. switch (message)
  207804. {
  207805. case WM_NCHITTEST:
  207806. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207807. return HTTRANSPARENT;
  207808. else if (! hasTitleBar())
  207809. return HTCLIENT;
  207810. break;
  207811. case WM_PAINT:
  207812. handlePaintMessage();
  207813. return 0;
  207814. case WM_NCPAINT:
  207815. if (hasTitleBar())
  207816. break;
  207817. else if (wParam != 1)
  207818. handlePaintMessage();
  207819. return 0;
  207820. case WM_ERASEBKGND:
  207821. case WM_NCCALCSIZE:
  207822. if (hasTitleBar())
  207823. break;
  207824. return 1;
  207825. case WM_MOUSEMOVE:
  207826. doMouseMove (getPointFromLParam (lParam));
  207827. return 0;
  207828. case WM_MOUSELEAVE:
  207829. doMouseExit();
  207830. return 0;
  207831. case WM_LBUTTONDOWN:
  207832. case WM_MBUTTONDOWN:
  207833. case WM_RBUTTONDOWN:
  207834. doMouseDown (getPointFromLParam (lParam), wParam);
  207835. return 0;
  207836. case WM_LBUTTONUP:
  207837. case WM_MBUTTONUP:
  207838. case WM_RBUTTONUP:
  207839. doMouseUp (getPointFromLParam (lParam), wParam);
  207840. return 0;
  207841. case WM_CAPTURECHANGED:
  207842. doCaptureChanged();
  207843. return 0;
  207844. case WM_NCMOUSEMOVE:
  207845. if (hasTitleBar())
  207846. break;
  207847. return 0;
  207848. case 0x020A: /* WM_MOUSEWHEEL */
  207849. case 0x020E: /* WM_MOUSEHWHEEL */
  207850. doMouseWheel (getCurrentMousePos(), wParam, message == 0x020A);
  207851. return 0;
  207852. case WM_SIZING:
  207853. return handleSizeConstraining ((RECT*) lParam, wParam);
  207854. case WM_WINDOWPOSCHANGING:
  207855. return handlePositionChanging ((WINDOWPOS*) lParam);
  207856. case WM_WINDOWPOSCHANGED:
  207857. {
  207858. const Point<int> pos (getCurrentMousePos());
  207859. if (contains (pos, false))
  207860. doMouseEvent (pos);
  207861. }
  207862. handleMovedOrResized();
  207863. if (dontRepaint)
  207864. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  207865. return 0;
  207866. case WM_KEYDOWN:
  207867. case WM_SYSKEYDOWN:
  207868. if (doKeyDown (wParam))
  207869. return 0;
  207870. break;
  207871. case WM_KEYUP:
  207872. case WM_SYSKEYUP:
  207873. if (doKeyUp (wParam))
  207874. return 0;
  207875. break;
  207876. case WM_CHAR:
  207877. if (doKeyChar ((int) wParam, lParam))
  207878. return 0;
  207879. break;
  207880. case WM_APPCOMMAND:
  207881. if (doAppCommand (lParam))
  207882. return TRUE;
  207883. break;
  207884. case WM_SETFOCUS:
  207885. updateKeyModifiers();
  207886. handleFocusGain();
  207887. break;
  207888. case WM_KILLFOCUS:
  207889. if (hasCreatedCaret)
  207890. {
  207891. hasCreatedCaret = false;
  207892. DestroyCaret();
  207893. }
  207894. handleFocusLoss();
  207895. break;
  207896. case WM_ACTIVATEAPP:
  207897. // Windows does weird things to process priority when you swap apps,
  207898. // so this forces an update when the app is brought to the front
  207899. if (wParam != FALSE)
  207900. juce_repeatLastProcessPriority();
  207901. else
  207902. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  207903. juce_CheckCurrentlyFocusedTopLevelWindow();
  207904. modifiersAtLastCallback = -1;
  207905. return 0;
  207906. case WM_ACTIVATE:
  207907. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  207908. {
  207909. handleAppActivation (wParam);
  207910. return 0;
  207911. }
  207912. break;
  207913. case WM_NCACTIVATE:
  207914. // while a temporary window is being shown, prevent Windows from deactivating the
  207915. // title bars of our main windows.
  207916. if (wParam == 0 && ! shouldDeactivateTitleBar)
  207917. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  207918. break;
  207919. case WM_MOUSEACTIVATE:
  207920. if (! component->getMouseClickGrabsKeyboardFocus())
  207921. return MA_NOACTIVATE;
  207922. break;
  207923. case WM_SHOWWINDOW:
  207924. if (wParam != 0)
  207925. handleBroughtToFront();
  207926. break;
  207927. case WM_CLOSE:
  207928. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  207929. handleUserClosingWindow();
  207930. return 0;
  207931. case WM_QUERYENDSESSION:
  207932. if (JUCEApplication::getInstance() != 0)
  207933. {
  207934. JUCEApplication::getInstance()->systemRequestedQuit();
  207935. return MessageManager::getInstance()->hasStopMessageBeenSent();
  207936. }
  207937. return TRUE;
  207938. case WM_TRAYNOTIFY:
  207939. handleTaskBarEvent (lParam);
  207940. break;
  207941. case WM_SYNCPAINT:
  207942. return 0;
  207943. case WM_DISPLAYCHANGE:
  207944. InvalidateRect (h, 0, 0);
  207945. // intentional fall-through...
  207946. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  207947. doSettingChange();
  207948. break;
  207949. case WM_INITMENU:
  207950. if (! hasTitleBar())
  207951. {
  207952. if (isFullScreen())
  207953. {
  207954. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  207955. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  207956. }
  207957. else if (! isMinimised())
  207958. {
  207959. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  207960. }
  207961. }
  207962. break;
  207963. case WM_SYSCOMMAND:
  207964. switch (wParam & 0xfff0)
  207965. {
  207966. case SC_CLOSE:
  207967. if (sendInputAttemptWhenModalMessage())
  207968. return 0;
  207969. if (hasTitleBar())
  207970. {
  207971. PostMessage (h, WM_CLOSE, 0, 0);
  207972. return 0;
  207973. }
  207974. break;
  207975. case SC_KEYMENU:
  207976. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  207977. // situations that can arise if a modal loop is started from an alt-key keypress).
  207978. if (hasTitleBar() && h == GetCapture())
  207979. ReleaseCapture();
  207980. break;
  207981. case SC_MAXIMIZE:
  207982. if (! sendInputAttemptWhenModalMessage())
  207983. setFullScreen (true);
  207984. return 0;
  207985. case SC_MINIMIZE:
  207986. if (sendInputAttemptWhenModalMessage())
  207987. return 0;
  207988. if (! hasTitleBar())
  207989. {
  207990. setMinimised (true);
  207991. return 0;
  207992. }
  207993. break;
  207994. case SC_RESTORE:
  207995. if (sendInputAttemptWhenModalMessage())
  207996. return 0;
  207997. if (hasTitleBar())
  207998. {
  207999. if (isFullScreen())
  208000. {
  208001. setFullScreen (false);
  208002. return 0;
  208003. }
  208004. }
  208005. else
  208006. {
  208007. if (isMinimised())
  208008. setMinimised (false);
  208009. else if (isFullScreen())
  208010. setFullScreen (false);
  208011. return 0;
  208012. }
  208013. break;
  208014. }
  208015. break;
  208016. case WM_NCLBUTTONDOWN:
  208017. if (! sendInputAttemptWhenModalMessage())
  208018. {
  208019. switch (wParam)
  208020. {
  208021. case HTBOTTOM:
  208022. case HTBOTTOMLEFT:
  208023. case HTBOTTOMRIGHT:
  208024. case HTGROWBOX:
  208025. case HTLEFT:
  208026. case HTRIGHT:
  208027. case HTTOP:
  208028. case HTTOPLEFT:
  208029. case HTTOPRIGHT:
  208030. if (isConstrainedNativeWindow())
  208031. {
  208032. constrainerIsResizing = true;
  208033. constrainer->resizeStart();
  208034. }
  208035. break;
  208036. default:
  208037. break;
  208038. };
  208039. }
  208040. break;
  208041. case WM_NCRBUTTONDOWN:
  208042. case WM_NCMBUTTONDOWN:
  208043. sendInputAttemptWhenModalMessage();
  208044. break;
  208045. //case WM_IME_STARTCOMPOSITION;
  208046. // return 0;
  208047. case WM_GETDLGCODE:
  208048. return DLGC_WANTALLKEYS;
  208049. default:
  208050. if (taskBarIcon != 0)
  208051. {
  208052. static const DWORD taskbarCreatedMessage = RegisterWindowMessage (TEXT("TaskbarCreated"));
  208053. if (message == taskbarCreatedMessage)
  208054. {
  208055. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  208056. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  208057. }
  208058. }
  208059. break;
  208060. }
  208061. return DefWindowProcW (h, message, wParam, lParam);
  208062. }
  208063. bool sendInputAttemptWhenModalMessage()
  208064. {
  208065. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208066. {
  208067. Component* const current = Component::getCurrentlyModalComponent();
  208068. if (current != 0)
  208069. current->inputAttemptWhenModal();
  208070. return true;
  208071. }
  208072. return false;
  208073. }
  208074. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Win32ComponentPeer);
  208075. };
  208076. ModifierKeys Win32ComponentPeer::currentModifiers;
  208077. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208078. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  208079. {
  208080. return new Win32ComponentPeer (this, styleFlags, (HWND) nativeWindowToAttachTo);
  208081. }
  208082. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208083. void ModifierKeys::updateCurrentModifiers() throw()
  208084. {
  208085. currentModifiers = Win32ComponentPeer::currentModifiers;
  208086. }
  208087. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208088. {
  208089. Win32ComponentPeer::updateKeyModifiers();
  208090. int mouseMods = 0;
  208091. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  208092. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  208093. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  208094. Win32ComponentPeer::currentModifiers
  208095. = Win32ComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  208096. return Win32ComponentPeer::currentModifiers;
  208097. }
  208098. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208099. {
  208100. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208101. if (wp != 0)
  208102. wp->setTaskBarIcon (newImage);
  208103. }
  208104. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208105. {
  208106. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208107. if (wp != 0)
  208108. wp->setTaskBarIconToolTip (tooltip);
  208109. }
  208110. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208111. {
  208112. DWORD val = GetWindowLong (h, styleType);
  208113. if (bitIsSet)
  208114. val |= feature;
  208115. else
  208116. val &= ~feature;
  208117. SetWindowLongPtr (h, styleType, val);
  208118. SetWindowPos (h, 0, 0, 0, 0, 0,
  208119. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208120. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208121. }
  208122. bool Process::isForegroundProcess()
  208123. {
  208124. HWND fg = GetForegroundWindow();
  208125. if (fg == 0)
  208126. return true;
  208127. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208128. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208129. // have to see if any of our windows are children of the foreground window
  208130. fg = GetAncestor (fg, GA_ROOT);
  208131. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208132. {
  208133. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208134. if (wp != 0 && wp->isInside (fg))
  208135. return true;
  208136. }
  208137. return false;
  208138. }
  208139. bool AlertWindow::showNativeDialogBox (const String& title,
  208140. const String& bodyText,
  208141. bool isOkCancel)
  208142. {
  208143. return MessageBox (0, bodyText.toUTF16(), title.toUTF16(),
  208144. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208145. : MB_OK)) == IDOK;
  208146. }
  208147. void Desktop::createMouseInputSources()
  208148. {
  208149. mouseSources.add (new MouseInputSource (0, true));
  208150. }
  208151. const Point<int> MouseInputSource::getCurrentMousePosition()
  208152. {
  208153. POINT mousePos;
  208154. GetCursorPos (&mousePos);
  208155. return Point<int> (mousePos.x, mousePos.y);
  208156. }
  208157. void Desktop::setMousePosition (const Point<int>& newPosition)
  208158. {
  208159. SetCursorPos (newPosition.getX(), newPosition.getY());
  208160. }
  208161. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208162. {
  208163. return createSoftwareImage (format, width, height, clearImage);
  208164. }
  208165. class ScreenSaverDefeater : public Timer,
  208166. public DeletedAtShutdown
  208167. {
  208168. public:
  208169. ScreenSaverDefeater()
  208170. {
  208171. startTimer (10000);
  208172. timerCallback();
  208173. }
  208174. ~ScreenSaverDefeater() {}
  208175. void timerCallback()
  208176. {
  208177. if (Process::isForegroundProcess())
  208178. {
  208179. // simulate a shift key getting pressed..
  208180. INPUT input[2];
  208181. input[0].type = INPUT_KEYBOARD;
  208182. input[0].ki.wVk = VK_SHIFT;
  208183. input[0].ki.dwFlags = 0;
  208184. input[0].ki.dwExtraInfo = 0;
  208185. input[1].type = INPUT_KEYBOARD;
  208186. input[1].ki.wVk = VK_SHIFT;
  208187. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208188. input[1].ki.dwExtraInfo = 0;
  208189. SendInput (2, input, sizeof (INPUT));
  208190. }
  208191. }
  208192. };
  208193. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208194. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208195. {
  208196. if (isEnabled)
  208197. deleteAndZero (screenSaverDefeater);
  208198. else if (screenSaverDefeater == 0)
  208199. screenSaverDefeater = new ScreenSaverDefeater();
  208200. }
  208201. bool Desktop::isScreenSaverEnabled()
  208202. {
  208203. return screenSaverDefeater == 0;
  208204. }
  208205. /* (The code below is the "correct" way to disable the screen saver, but it
  208206. completely fails on winXP when the saver is password-protected...)
  208207. static bool juce_screenSaverEnabled = true;
  208208. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208209. {
  208210. juce_screenSaverEnabled = isEnabled;
  208211. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208212. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208213. }
  208214. bool Desktop::isScreenSaverEnabled() throw()
  208215. {
  208216. return juce_screenSaverEnabled;
  208217. }
  208218. */
  208219. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208220. {
  208221. if (enableOrDisable)
  208222. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208223. }
  208224. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208225. {
  208226. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208227. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208228. return TRUE;
  208229. }
  208230. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208231. {
  208232. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208233. // make sure the first in the list is the main monitor
  208234. for (int i = 1; i < monitorCoords.size(); ++i)
  208235. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208236. monitorCoords.swap (i, 0);
  208237. if (monitorCoords.size() == 0)
  208238. {
  208239. RECT r;
  208240. GetWindowRect (GetDesktopWindow(), &r);
  208241. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208242. }
  208243. if (clipToWorkArea)
  208244. {
  208245. // clip the main monitor to the active non-taskbar area
  208246. RECT r;
  208247. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208248. Rectangle<int>& screen = monitorCoords.getReference (0);
  208249. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208250. jmax (screen.getY(), (int) r.top));
  208251. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208252. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208253. }
  208254. }
  208255. const Image juce_createIconForFile (const File& file)
  208256. {
  208257. Image image;
  208258. WORD iconNum = 0;
  208259. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208260. const_cast <WCHAR*> (file.getFullPathName().toUTF16().getAddress()), &iconNum);
  208261. if (icon != 0)
  208262. {
  208263. image = IconConverters::createImageFromHICON (icon);
  208264. DestroyIcon (icon);
  208265. }
  208266. return image;
  208267. }
  208268. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208269. {
  208270. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208271. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208272. Image im (image);
  208273. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208274. {
  208275. im = im.rescaled (maxW, maxH);
  208276. hotspotX = (hotspotX * maxW) / image.getWidth();
  208277. hotspotY = (hotspotY * maxH) / image.getHeight();
  208278. }
  208279. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208280. }
  208281. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208282. {
  208283. if (cursorHandle != 0 && ! isStandard)
  208284. DestroyCursor ((HCURSOR) cursorHandle);
  208285. }
  208286. enum
  208287. {
  208288. hiddenMouseCursorHandle = 32500 // (arbitrary non-zero value to mark this type of cursor)
  208289. };
  208290. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208291. {
  208292. LPCTSTR cursorName = IDC_ARROW;
  208293. switch (type)
  208294. {
  208295. case NormalCursor: break;
  208296. case NoCursor: return (void*) hiddenMouseCursorHandle;
  208297. case WaitCursor: cursorName = IDC_WAIT; break;
  208298. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208299. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208300. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208301. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208302. case LeftRightResizeCursor:
  208303. case LeftEdgeResizeCursor:
  208304. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208305. case UpDownResizeCursor:
  208306. case TopEdgeResizeCursor:
  208307. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208308. case TopLeftCornerResizeCursor:
  208309. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208310. case TopRightCornerResizeCursor:
  208311. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208312. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208313. case DraggingHandCursor:
  208314. {
  208315. static void* dragHandCursor = 0;
  208316. if (dragHandCursor == 0)
  208317. {
  208318. static const unsigned char dragHandData[] =
  208319. { 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,
  208320. 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,
  208321. 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 };
  208322. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208323. }
  208324. return dragHandCursor;
  208325. }
  208326. default:
  208327. jassertfalse; break;
  208328. }
  208329. HCURSOR cursorH = LoadCursor (0, cursorName);
  208330. if (cursorH == 0)
  208331. cursorH = LoadCursor (0, IDC_ARROW);
  208332. return cursorH;
  208333. }
  208334. void MouseCursor::showInWindow (ComponentPeer*) const
  208335. {
  208336. HCURSOR c = (HCURSOR) getHandle();
  208337. if (c == 0)
  208338. c = LoadCursor (0, IDC_ARROW);
  208339. else if (c == (HCURSOR) hiddenMouseCursorHandle)
  208340. c = 0;
  208341. SetCursor (c);
  208342. }
  208343. void MouseCursor::showInAllWindows() const
  208344. {
  208345. showInWindow (0);
  208346. }
  208347. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208348. {
  208349. public:
  208350. JuceDropSource() {}
  208351. ~JuceDropSource() {}
  208352. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208353. {
  208354. if (escapePressed)
  208355. return DRAGDROP_S_CANCEL;
  208356. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208357. return DRAGDROP_S_DROP;
  208358. return S_OK;
  208359. }
  208360. HRESULT __stdcall GiveFeedback (DWORD)
  208361. {
  208362. return DRAGDROP_S_USEDEFAULTCURSORS;
  208363. }
  208364. };
  208365. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208366. {
  208367. public:
  208368. JuceEnumFormatEtc (const FORMATETC* const format_)
  208369. : format (format_),
  208370. index (0)
  208371. {
  208372. }
  208373. ~JuceEnumFormatEtc() {}
  208374. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208375. {
  208376. if (result == 0)
  208377. return E_POINTER;
  208378. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208379. newOne->index = index;
  208380. *result = newOne;
  208381. return S_OK;
  208382. }
  208383. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208384. {
  208385. if (pceltFetched != 0)
  208386. *pceltFetched = 0;
  208387. else if (celt != 1)
  208388. return S_FALSE;
  208389. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208390. {
  208391. copyFormatEtc (lpFormatEtc [0], *format);
  208392. ++index;
  208393. if (pceltFetched != 0)
  208394. *pceltFetched = 1;
  208395. return S_OK;
  208396. }
  208397. return S_FALSE;
  208398. }
  208399. HRESULT __stdcall Skip (ULONG celt)
  208400. {
  208401. if (index + (int) celt >= 1)
  208402. return S_FALSE;
  208403. index += celt;
  208404. return S_OK;
  208405. }
  208406. HRESULT __stdcall Reset()
  208407. {
  208408. index = 0;
  208409. return S_OK;
  208410. }
  208411. private:
  208412. const FORMATETC* const format;
  208413. int index;
  208414. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208415. {
  208416. dest = source;
  208417. if (source.ptd != 0)
  208418. {
  208419. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208420. *(dest.ptd) = *(source.ptd);
  208421. }
  208422. }
  208423. JUCE_DECLARE_NON_COPYABLE (JuceEnumFormatEtc);
  208424. };
  208425. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208426. {
  208427. public:
  208428. JuceDataObject (JuceDropSource* const dropSource_,
  208429. const FORMATETC* const format_,
  208430. const STGMEDIUM* const medium_)
  208431. : dropSource (dropSource_),
  208432. format (format_),
  208433. medium (medium_)
  208434. {
  208435. }
  208436. ~JuceDataObject()
  208437. {
  208438. jassert (refCount == 0);
  208439. }
  208440. HRESULT __stdcall GetData (FORMATETC* pFormatEtc, STGMEDIUM* pMedium)
  208441. {
  208442. if ((pFormatEtc->tymed & format->tymed) != 0
  208443. && pFormatEtc->cfFormat == format->cfFormat
  208444. && pFormatEtc->dwAspect == format->dwAspect)
  208445. {
  208446. pMedium->tymed = format->tymed;
  208447. pMedium->pUnkForRelease = 0;
  208448. if (format->tymed == TYMED_HGLOBAL)
  208449. {
  208450. const SIZE_T len = GlobalSize (medium->hGlobal);
  208451. void* const src = GlobalLock (medium->hGlobal);
  208452. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208453. memcpy (dst, src, len);
  208454. GlobalUnlock (medium->hGlobal);
  208455. pMedium->hGlobal = dst;
  208456. return S_OK;
  208457. }
  208458. }
  208459. return DV_E_FORMATETC;
  208460. }
  208461. HRESULT __stdcall QueryGetData (FORMATETC* f)
  208462. {
  208463. if (f == 0)
  208464. return E_INVALIDARG;
  208465. if (f->tymed == format->tymed
  208466. && f->cfFormat == format->cfFormat
  208467. && f->dwAspect == format->dwAspect)
  208468. return S_OK;
  208469. return DV_E_FORMATETC;
  208470. }
  208471. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC*, FORMATETC* pFormatEtcOut)
  208472. {
  208473. pFormatEtcOut->ptd = 0;
  208474. return E_NOTIMPL;
  208475. }
  208476. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC** result)
  208477. {
  208478. if (result == 0)
  208479. return E_POINTER;
  208480. if (direction == DATADIR_GET)
  208481. {
  208482. *result = new JuceEnumFormatEtc (format);
  208483. return S_OK;
  208484. }
  208485. *result = 0;
  208486. return E_NOTIMPL;
  208487. }
  208488. HRESULT __stdcall GetDataHere (FORMATETC*, STGMEDIUM*) { return DATA_E_FORMATETC; }
  208489. HRESULT __stdcall SetData (FORMATETC*, STGMEDIUM*, BOOL) { return E_NOTIMPL; }
  208490. HRESULT __stdcall DAdvise (FORMATETC*, DWORD, IAdviseSink*, DWORD*) { return OLE_E_ADVISENOTSUPPORTED; }
  208491. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  208492. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA**) { return OLE_E_ADVISENOTSUPPORTED; }
  208493. private:
  208494. JuceDropSource* const dropSource;
  208495. const FORMATETC* const format;
  208496. const STGMEDIUM* const medium;
  208497. JUCE_DECLARE_NON_COPYABLE (JuceDataObject);
  208498. };
  208499. static HDROP createHDrop (const StringArray& fileNames)
  208500. {
  208501. int totalBytes = 0;
  208502. for (int i = fileNames.size(); --i >= 0;)
  208503. totalBytes += CharPointer_UTF16::getBytesRequiredFor (fileNames[i].getCharPointer()) + sizeof (WCHAR);
  208504. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, sizeof (DROPFILES) + totalBytes + 4);
  208505. if (hDrop != 0)
  208506. {
  208507. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  208508. pDropFiles->pFiles = sizeof (DROPFILES);
  208509. pDropFiles->fWide = true;
  208510. WCHAR* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
  208511. for (int i = 0; i < fileNames.size(); ++i)
  208512. {
  208513. const int bytesWritten = fileNames[i].copyToUTF16 (fname, 2048);
  208514. fname = reinterpret_cast<WCHAR*> (addBytesToPointer (fname, bytesWritten));
  208515. }
  208516. *fname = 0;
  208517. GlobalUnlock (hDrop);
  208518. }
  208519. return hDrop;
  208520. }
  208521. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  208522. {
  208523. JuceDropSource* const source = new JuceDropSource();
  208524. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  208525. DWORD effect;
  208526. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  208527. data->Release();
  208528. source->Release();
  208529. return res == DRAGDROP_S_DROP;
  208530. }
  208531. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  208532. {
  208533. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208534. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208535. medium.hGlobal = createHDrop (files);
  208536. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  208537. : DROPEFFECT_COPY);
  208538. }
  208539. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  208540. {
  208541. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208542. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208543. const int numBytes = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer());
  208544. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, numBytes + 2);
  208545. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  208546. text.copyToUTF16 (data, numBytes);
  208547. format.cfFormat = CF_UNICODETEXT;
  208548. GlobalUnlock (medium.hGlobal);
  208549. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  208550. }
  208551. #endif
  208552. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  208553. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  208554. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208555. // compiled on its own).
  208556. #if JUCE_INCLUDED_FILE
  208557. namespace FileChooserHelpers
  208558. {
  208559. static bool areThereAnyAlwaysOnTopWindows()
  208560. {
  208561. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  208562. {
  208563. Component* c = Desktop::getInstance().getComponent (i);
  208564. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  208565. return true;
  208566. }
  208567. return false;
  208568. }
  208569. struct FileChooserCallbackInfo
  208570. {
  208571. String initialPath;
  208572. String returnedString; // need this to get non-existent pathnames from the directory chooser
  208573. ScopedPointer<Component> customComponent;
  208574. };
  208575. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  208576. {
  208577. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) lpData;
  208578. if (msg == BFFM_INITIALIZED)
  208579. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) info->initialPath.toUTF16().getAddress());
  208580. else if (msg == BFFM_VALIDATEFAILEDW)
  208581. info->returnedString = (LPCWSTR) lParam;
  208582. else if (msg == BFFM_VALIDATEFAILEDA)
  208583. info->returnedString = (const char*) lParam;
  208584. return 0;
  208585. }
  208586. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  208587. {
  208588. if (uiMsg == WM_INITDIALOG)
  208589. {
  208590. Component* customComp = ((FileChooserCallbackInfo*) (((OPENFILENAMEW*) lParam)->lCustData))->customComponent;
  208591. HWND dialogH = GetParent (hdlg);
  208592. jassert (dialogH != 0);
  208593. if (dialogH == 0)
  208594. dialogH = hdlg;
  208595. RECT r, cr;
  208596. GetWindowRect (dialogH, &r);
  208597. GetClientRect (dialogH, &cr);
  208598. SetWindowPos (dialogH, 0,
  208599. r.left, r.top,
  208600. customComp->getWidth() + jmax (150, (int) (r.right - r.left)),
  208601. jmax (150, (int) (r.bottom - r.top)),
  208602. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  208603. customComp->setBounds (cr.right, cr.top, customComp->getWidth(), cr.bottom - cr.top);
  208604. customComp->addToDesktop (0, dialogH);
  208605. }
  208606. else if (uiMsg == WM_NOTIFY)
  208607. {
  208608. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  208609. if (ofn->hdr.code == CDN_SELCHANGE)
  208610. {
  208611. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) ofn->lpOFN->lCustData;
  208612. FilePreviewComponent* comp = static_cast<FilePreviewComponent*> (info->customComponent->getChildComponent(0));
  208613. if (comp != 0)
  208614. {
  208615. WCHAR path [MAX_PATH * 2];
  208616. zerostruct (path);
  208617. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  208618. comp->selectedFileChanged (File (path));
  208619. }
  208620. }
  208621. }
  208622. return 0;
  208623. }
  208624. class CustomComponentHolder : public Component
  208625. {
  208626. public:
  208627. CustomComponentHolder (Component* customComp)
  208628. {
  208629. setVisible (true);
  208630. setOpaque (true);
  208631. addAndMakeVisible (customComp);
  208632. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  208633. }
  208634. void paint (Graphics& g)
  208635. {
  208636. g.fillAll (Colours::lightgrey);
  208637. }
  208638. void resized()
  208639. {
  208640. if (getNumChildComponents() > 0)
  208641. getChildComponent(0)->setBounds (getLocalBounds());
  208642. }
  208643. private:
  208644. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponentHolder);
  208645. };
  208646. }
  208647. void FileChooser::showPlatformDialog (Array<File>& results, const String& title, const File& currentFileOrDirectory,
  208648. const String& filter, bool selectsDirectory, bool /*selectsFiles*/,
  208649. bool isSaveDialogue, bool warnAboutOverwritingExistingFiles,
  208650. bool selectMultipleFiles, FilePreviewComponent* extraInfoComponent)
  208651. {
  208652. using namespace FileChooserHelpers;
  208653. HeapBlock<WCHAR> files;
  208654. const int charsAvailableForResult = 32768;
  208655. files.calloc (charsAvailableForResult + 1);
  208656. int filenameOffset = 0;
  208657. FileChooserCallbackInfo info;
  208658. // use a modal window as the parent for this dialog box
  208659. // to block input from other app windows
  208660. Component parentWindow (String::empty);
  208661. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  208662. parentWindow.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  208663. mainMon.getY() + mainMon.getHeight() / 4,
  208664. 0, 0);
  208665. parentWindow.setOpaque (true);
  208666. parentWindow.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  208667. parentWindow.addToDesktop (0);
  208668. if (extraInfoComponent == 0)
  208669. parentWindow.enterModalState();
  208670. if (currentFileOrDirectory.isDirectory())
  208671. {
  208672. info.initialPath = currentFileOrDirectory.getFullPathName();
  208673. }
  208674. else
  208675. {
  208676. currentFileOrDirectory.getFileName().copyToUTF16 (files, charsAvailableForResult * sizeof (WCHAR));
  208677. info.initialPath = currentFileOrDirectory.getParentDirectory().getFullPathName();
  208678. }
  208679. if (selectsDirectory)
  208680. {
  208681. BROWSEINFO bi;
  208682. zerostruct (bi);
  208683. bi.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208684. bi.pszDisplayName = files;
  208685. bi.lpszTitle = title.toUTF16();
  208686. bi.lParam = (LPARAM) &info;
  208687. bi.lpfn = browseCallbackProc;
  208688. #ifdef BIF_USENEWUI
  208689. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  208690. #else
  208691. bi.ulFlags = 0x50;
  208692. #endif
  208693. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  208694. if (! SHGetPathFromIDListW (list, files))
  208695. {
  208696. files[0] = 0;
  208697. info.returnedString = String::empty;
  208698. }
  208699. LPMALLOC al;
  208700. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  208701. al->Free (list);
  208702. if (info.returnedString.isNotEmpty())
  208703. {
  208704. results.add (File (String (files)).getSiblingFile (info.returnedString));
  208705. return;
  208706. }
  208707. }
  208708. else
  208709. {
  208710. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  208711. if (warnAboutOverwritingExistingFiles)
  208712. flags |= OFN_OVERWRITEPROMPT;
  208713. if (selectMultipleFiles)
  208714. flags |= OFN_ALLOWMULTISELECT;
  208715. if (extraInfoComponent != 0)
  208716. {
  208717. flags |= OFN_ENABLEHOOK;
  208718. info.customComponent = new CustomComponentHolder (extraInfoComponent);
  208719. info.customComponent->enterModalState();
  208720. }
  208721. const int filterSpace = 2048;
  208722. HeapBlock<char> filters;
  208723. filters.calloc (filterSpace * 2);
  208724. const int bytesWritten = filter.copyToUTF16 (reinterpret_cast <WCHAR*> (filters.getData()), filterSpace);
  208725. filter.copyToUTF16 (reinterpret_cast <WCHAR*> (filters + bytesWritten), filterSpace);
  208726. OPENFILENAMEW of;
  208727. zerostruct (of);
  208728. #ifdef OPENFILENAME_SIZE_VERSION_400W
  208729. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  208730. #else
  208731. of.lStructSize = sizeof (of);
  208732. #endif
  208733. of.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208734. of.lpstrFilter = reinterpret_cast <WCHAR*> (filters.getData());
  208735. of.nFilterIndex = 1;
  208736. of.lpstrFile = files;
  208737. of.nMaxFile = charsAvailableForResult;
  208738. of.lpstrInitialDir = info.initialPath.toUTF16();
  208739. of.lpstrTitle = title.toUTF16();
  208740. of.Flags = flags;
  208741. of.lCustData = (LPARAM) &info;
  208742. if (extraInfoComponent != 0)
  208743. of.lpfnHook = &openCallback;
  208744. if (! (isSaveDialogue ? GetSaveFileName (&of)
  208745. : GetOpenFileName (&of)))
  208746. return;
  208747. filenameOffset = of.nFileOffset;
  208748. }
  208749. if (selectMultipleFiles && filenameOffset > 0 && files [filenameOffset - 1] == 0)
  208750. {
  208751. const WCHAR* filename = files + filenameOffset;
  208752. while (*filename != 0)
  208753. {
  208754. results.add (File (String (files) + "\\" + String (filename)));
  208755. filename += wcslen (filename) + 1;
  208756. }
  208757. }
  208758. else if (files[0] != 0)
  208759. {
  208760. results.add (File (String (files)));
  208761. }
  208762. }
  208763. #endif
  208764. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  208765. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  208766. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208767. // compiled on its own).
  208768. #if JUCE_INCLUDED_FILE
  208769. void SystemClipboard::copyTextToClipboard (const String& text)
  208770. {
  208771. if (OpenClipboard (0) != 0)
  208772. {
  208773. if (EmptyClipboard() != 0)
  208774. {
  208775. const int bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer()) + 4;
  208776. if (bytesNeeded > 0)
  208777. {
  208778. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE | GMEM_ZEROINIT, bytesNeeded + sizeof (WCHAR));
  208779. if (bufH != 0)
  208780. {
  208781. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  208782. text.copyToUTF16 (data, bytesNeeded);
  208783. GlobalUnlock (bufH);
  208784. SetClipboardData (CF_UNICODETEXT, bufH);
  208785. }
  208786. }
  208787. }
  208788. CloseClipboard();
  208789. }
  208790. }
  208791. const String SystemClipboard::getTextFromClipboard()
  208792. {
  208793. String result;
  208794. if (OpenClipboard (0) != 0)
  208795. {
  208796. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  208797. if (bufH != 0)
  208798. {
  208799. const WCHAR* const data = (const WCHAR*) GlobalLock (bufH);
  208800. if (data != 0)
  208801. {
  208802. result = String (data, (int) (GlobalSize (bufH) / sizeof (WCHAR)));
  208803. GlobalUnlock (bufH);
  208804. }
  208805. }
  208806. CloseClipboard();
  208807. }
  208808. return result;
  208809. }
  208810. #endif
  208811. /*** End of inlined file: juce_win32_Misc.cpp ***/
  208812. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  208813. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208814. // compiled on its own).
  208815. #if JUCE_INCLUDED_FILE
  208816. namespace ActiveXHelpers
  208817. {
  208818. class JuceIStorage : public ComBaseClassHelper <IStorage>
  208819. {
  208820. public:
  208821. JuceIStorage() {}
  208822. ~JuceIStorage() {}
  208823. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208824. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208825. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  208826. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  208827. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  208828. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  208829. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  208830. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  208831. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  208832. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  208833. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  208834. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  208835. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  208836. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  208837. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  208838. };
  208839. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  208840. {
  208841. HWND window;
  208842. public:
  208843. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  208844. ~JuceOleInPlaceFrame() {}
  208845. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  208846. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  208847. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  208848. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  208849. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  208850. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  208851. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  208852. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  208853. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  208854. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  208855. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  208856. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  208857. };
  208858. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  208859. {
  208860. HWND window;
  208861. JuceOleInPlaceFrame* frame;
  208862. public:
  208863. JuceIOleInPlaceSite (HWND window_)
  208864. : window (window_),
  208865. frame (new JuceOleInPlaceFrame (window))
  208866. {}
  208867. ~JuceIOleInPlaceSite()
  208868. {
  208869. frame->Release();
  208870. }
  208871. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  208872. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  208873. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  208874. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  208875. HRESULT __stdcall OnUIActivate() { return S_OK; }
  208876. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  208877. {
  208878. /* Note: if you call AddRef on the frame here, then some types of object (e.g. web browser control) cause leaks..
  208879. If you don't call AddRef then others crash (e.g. QuickTime).. Bit of a catch-22, so letting it leak is probably preferable.
  208880. */
  208881. if (lplpFrame != 0) { frame->AddRef(); *lplpFrame = frame; }
  208882. if (lplpDoc != 0) *lplpDoc = 0;
  208883. lpFrameInfo->fMDIApp = FALSE;
  208884. lpFrameInfo->hwndFrame = window;
  208885. lpFrameInfo->haccel = 0;
  208886. lpFrameInfo->cAccelEntries = 0;
  208887. return S_OK;
  208888. }
  208889. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  208890. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  208891. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  208892. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  208893. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  208894. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  208895. };
  208896. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  208897. {
  208898. JuceIOleInPlaceSite* inplaceSite;
  208899. public:
  208900. JuceIOleClientSite (HWND window)
  208901. : inplaceSite (new JuceIOleInPlaceSite (window))
  208902. {}
  208903. ~JuceIOleClientSite()
  208904. {
  208905. inplaceSite->Release();
  208906. }
  208907. HRESULT __stdcall QueryInterface (REFIID type, void** result)
  208908. {
  208909. if (type == IID_IOleInPlaceSite)
  208910. {
  208911. inplaceSite->AddRef();
  208912. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  208913. return S_OK;
  208914. }
  208915. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  208916. }
  208917. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  208918. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  208919. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  208920. HRESULT __stdcall ShowObject() { return S_OK; }
  208921. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  208922. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  208923. };
  208924. static Array<ActiveXControlComponent*> activeXComps;
  208925. static HWND getHWND (const ActiveXControlComponent* const component)
  208926. {
  208927. HWND hwnd = 0;
  208928. const IID iid = IID_IOleWindow;
  208929. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  208930. if (window != 0)
  208931. {
  208932. window->GetWindow (&hwnd);
  208933. window->Release();
  208934. }
  208935. return hwnd;
  208936. }
  208937. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  208938. {
  208939. RECT activeXRect, peerRect;
  208940. GetWindowRect (hwnd, &activeXRect);
  208941. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  208942. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  208943. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  208944. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  208945. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  208946. switch (message)
  208947. {
  208948. case WM_MOUSEMOVE:
  208949. case WM_LBUTTONDOWN:
  208950. case WM_MBUTTONDOWN:
  208951. case WM_RBUTTONDOWN:
  208952. case WM_LBUTTONUP:
  208953. case WM_MBUTTONUP:
  208954. case WM_RBUTTONUP:
  208955. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  208956. break;
  208957. default:
  208958. break;
  208959. }
  208960. }
  208961. }
  208962. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  208963. {
  208964. public:
  208965. Pimpl (HWND hwnd, ActiveXControlComponent& owner_)
  208966. : ComponentMovementWatcher (&owner_),
  208967. owner (owner_),
  208968. controlHWND (0),
  208969. storage (new ActiveXHelpers::JuceIStorage()),
  208970. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  208971. control (0)
  208972. {
  208973. }
  208974. ~Pimpl()
  208975. {
  208976. if (control != 0)
  208977. {
  208978. control->Close (OLECLOSE_NOSAVE);
  208979. control->Release();
  208980. }
  208981. clientSite->Release();
  208982. storage->Release();
  208983. }
  208984. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  208985. {
  208986. Component* const topComp = owner.getTopLevelComponent();
  208987. if (topComp->getPeer() != 0)
  208988. {
  208989. const Point<int> pos (topComp->getLocalPoint (&owner, Point<int>()));
  208990. owner.setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner.getWidth(), owner.getHeight()));
  208991. }
  208992. }
  208993. void componentPeerChanged()
  208994. {
  208995. componentMovedOrResized (true, true);
  208996. }
  208997. void componentVisibilityChanged()
  208998. {
  208999. owner.setControlVisible (owner.isShowing());
  209000. componentPeerChanged();
  209001. }
  209002. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  209003. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209004. {
  209005. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  209006. {
  209007. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  209008. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  209009. {
  209010. switch (message)
  209011. {
  209012. case WM_MOUSEMOVE:
  209013. case WM_LBUTTONDOWN:
  209014. case WM_MBUTTONDOWN:
  209015. case WM_RBUTTONDOWN:
  209016. case WM_LBUTTONUP:
  209017. case WM_MBUTTONUP:
  209018. case WM_RBUTTONUP:
  209019. case WM_LBUTTONDBLCLK:
  209020. case WM_MBUTTONDBLCLK:
  209021. case WM_RBUTTONDBLCLK:
  209022. if (ax->isShowing())
  209023. {
  209024. ComponentPeer* const peer = ax->getPeer();
  209025. if (peer != 0)
  209026. {
  209027. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209028. if (! ax->areMouseEventsAllowed())
  209029. return 0;
  209030. }
  209031. }
  209032. break;
  209033. default:
  209034. break;
  209035. }
  209036. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209037. }
  209038. }
  209039. return DefWindowProc (hwnd, message, wParam, lParam);
  209040. }
  209041. private:
  209042. ActiveXControlComponent& owner;
  209043. public:
  209044. HWND controlHWND;
  209045. IStorage* storage;
  209046. IOleClientSite* clientSite;
  209047. IOleObject* control;
  209048. };
  209049. ActiveXControlComponent::ActiveXControlComponent()
  209050. : originalWndProc (0),
  209051. mouseEventsAllowed (true)
  209052. {
  209053. ActiveXHelpers::activeXComps.add (this);
  209054. }
  209055. ActiveXControlComponent::~ActiveXControlComponent()
  209056. {
  209057. deleteControl();
  209058. ActiveXHelpers::activeXComps.removeValue (this);
  209059. }
  209060. void ActiveXControlComponent::paint (Graphics& g)
  209061. {
  209062. if (control == 0)
  209063. g.fillAll (Colours::lightgrey);
  209064. }
  209065. bool ActiveXControlComponent::createControl (const void* controlIID)
  209066. {
  209067. deleteControl();
  209068. ComponentPeer* const peer = getPeer();
  209069. // the component must have already been added to a real window when you call this!
  209070. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209071. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209072. {
  209073. const Point<int> pos (getTopLevelComponent()->getLocalPoint (this, Point<int>()));
  209074. HWND hwnd = (HWND) peer->getNativeHandle();
  209075. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, *this));
  209076. HRESULT hr;
  209077. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209078. newControl->clientSite, newControl->storage,
  209079. (void**) &(newControl->control))) == S_OK)
  209080. {
  209081. newControl->control->SetHostNames (L"Juce", 0);
  209082. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209083. {
  209084. RECT rect;
  209085. rect.left = pos.getX();
  209086. rect.top = pos.getY();
  209087. rect.right = pos.getX() + getWidth();
  209088. rect.bottom = pos.getY() + getHeight();
  209089. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209090. {
  209091. control = newControl;
  209092. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209093. control->controlHWND = ActiveXHelpers::getHWND (this);
  209094. if (control->controlHWND != 0)
  209095. {
  209096. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209097. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209098. }
  209099. return true;
  209100. }
  209101. }
  209102. }
  209103. }
  209104. return false;
  209105. }
  209106. void ActiveXControlComponent::deleteControl()
  209107. {
  209108. control = 0;
  209109. originalWndProc = 0;
  209110. }
  209111. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209112. {
  209113. void* result = 0;
  209114. if (control != 0 && control->control != 0
  209115. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209116. return result;
  209117. return 0;
  209118. }
  209119. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209120. {
  209121. if (control->controlHWND != 0)
  209122. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209123. }
  209124. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209125. {
  209126. if (control->controlHWND != 0)
  209127. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209128. }
  209129. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209130. {
  209131. mouseEventsAllowed = eventsCanReachControl;
  209132. }
  209133. #endif
  209134. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209135. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209136. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209137. // compiled on its own).
  209138. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209139. using namespace QTOLibrary;
  209140. using namespace QTOControlLib;
  209141. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209142. static bool isQTAvailable = false;
  209143. class QuickTimeMovieComponent::Pimpl
  209144. {
  209145. public:
  209146. Pimpl() : dataHandle (0)
  209147. {
  209148. }
  209149. ~Pimpl()
  209150. {
  209151. clearHandle();
  209152. }
  209153. void clearHandle()
  209154. {
  209155. if (dataHandle != 0)
  209156. {
  209157. DisposeHandle (dataHandle);
  209158. dataHandle = 0;
  209159. }
  209160. }
  209161. IQTControlPtr qtControl;
  209162. IQTMoviePtr qtMovie;
  209163. Handle dataHandle;
  209164. };
  209165. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209166. : movieLoaded (false),
  209167. controllerVisible (true)
  209168. {
  209169. pimpl = new Pimpl();
  209170. setMouseEventsAllowed (false);
  209171. }
  209172. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209173. {
  209174. closeMovie();
  209175. pimpl->qtControl = 0;
  209176. deleteControl();
  209177. pimpl = 0;
  209178. }
  209179. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209180. {
  209181. if (! isQTAvailable)
  209182. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209183. return isQTAvailable;
  209184. }
  209185. void QuickTimeMovieComponent::createControlIfNeeded()
  209186. {
  209187. if (isShowing() && ! isControlCreated())
  209188. {
  209189. const IID qtIID = __uuidof (QTControl);
  209190. if (createControl (&qtIID))
  209191. {
  209192. const IID qtInterfaceIID = __uuidof (IQTControl);
  209193. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209194. if (pimpl->qtControl != 0)
  209195. {
  209196. pimpl->qtControl->Release(); // it has one ref too many at this point
  209197. pimpl->qtControl->QuickTimeInitialize();
  209198. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209199. if (movieFile != File::nonexistent)
  209200. loadMovie (movieFile, controllerVisible);
  209201. }
  209202. }
  209203. }
  209204. }
  209205. bool QuickTimeMovieComponent::isControlCreated() const
  209206. {
  209207. return isControlOpen();
  209208. }
  209209. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209210. const bool isControllerVisible)
  209211. {
  209212. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209213. movieFile = File::nonexistent;
  209214. movieLoaded = false;
  209215. pimpl->qtMovie = 0;
  209216. controllerVisible = isControllerVisible;
  209217. createControlIfNeeded();
  209218. if (isControlCreated())
  209219. {
  209220. if (pimpl->qtControl != 0)
  209221. {
  209222. pimpl->qtControl->Put_MovieHandle (0);
  209223. pimpl->clearHandle();
  209224. Movie movie;
  209225. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209226. {
  209227. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209228. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209229. if (pimpl->qtMovie != 0)
  209230. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209231. : qtMovieControllerTypeNone);
  209232. }
  209233. if (movie == 0)
  209234. pimpl->clearHandle();
  209235. }
  209236. movieLoaded = (pimpl->qtMovie != 0);
  209237. }
  209238. else
  209239. {
  209240. // You're trying to open a movie when the control hasn't yet been created, probably because
  209241. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209242. jassertfalse;
  209243. }
  209244. return movieLoaded;
  209245. }
  209246. void QuickTimeMovieComponent::closeMovie()
  209247. {
  209248. stop();
  209249. movieFile = File::nonexistent;
  209250. movieLoaded = false;
  209251. pimpl->qtMovie = 0;
  209252. if (pimpl->qtControl != 0)
  209253. pimpl->qtControl->Put_MovieHandle (0);
  209254. pimpl->clearHandle();
  209255. }
  209256. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209257. {
  209258. return movieFile;
  209259. }
  209260. bool QuickTimeMovieComponent::isMovieOpen() const
  209261. {
  209262. return movieLoaded;
  209263. }
  209264. double QuickTimeMovieComponent::getMovieDuration() const
  209265. {
  209266. if (pimpl->qtMovie != 0)
  209267. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209268. return 0.0;
  209269. }
  209270. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209271. {
  209272. if (pimpl->qtMovie != 0)
  209273. {
  209274. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209275. width = r.right - r.left;
  209276. height = r.bottom - r.top;
  209277. }
  209278. else
  209279. {
  209280. width = height = 0;
  209281. }
  209282. }
  209283. void QuickTimeMovieComponent::play()
  209284. {
  209285. if (pimpl->qtMovie != 0)
  209286. pimpl->qtMovie->Play();
  209287. }
  209288. void QuickTimeMovieComponent::stop()
  209289. {
  209290. if (pimpl->qtMovie != 0)
  209291. pimpl->qtMovie->Stop();
  209292. }
  209293. bool QuickTimeMovieComponent::isPlaying() const
  209294. {
  209295. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209296. }
  209297. void QuickTimeMovieComponent::setPosition (const double seconds)
  209298. {
  209299. if (pimpl->qtMovie != 0)
  209300. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209301. }
  209302. double QuickTimeMovieComponent::getPosition() const
  209303. {
  209304. if (pimpl->qtMovie != 0)
  209305. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209306. return 0.0;
  209307. }
  209308. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209309. {
  209310. if (pimpl->qtMovie != 0)
  209311. pimpl->qtMovie->PutRate (newSpeed);
  209312. }
  209313. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209314. {
  209315. if (pimpl->qtMovie != 0)
  209316. {
  209317. pimpl->qtMovie->PutAudioVolume (newVolume);
  209318. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209319. }
  209320. }
  209321. float QuickTimeMovieComponent::getMovieVolume() const
  209322. {
  209323. if (pimpl->qtMovie != 0)
  209324. return pimpl->qtMovie->GetAudioVolume();
  209325. return 0.0f;
  209326. }
  209327. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209328. {
  209329. if (pimpl->qtMovie != 0)
  209330. pimpl->qtMovie->PutLoop (shouldLoop);
  209331. }
  209332. bool QuickTimeMovieComponent::isLooping() const
  209333. {
  209334. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209335. }
  209336. bool QuickTimeMovieComponent::isControllerVisible() const
  209337. {
  209338. return controllerVisible;
  209339. }
  209340. void QuickTimeMovieComponent::parentHierarchyChanged()
  209341. {
  209342. createControlIfNeeded();
  209343. QTCompBaseClass::parentHierarchyChanged();
  209344. }
  209345. void QuickTimeMovieComponent::visibilityChanged()
  209346. {
  209347. createControlIfNeeded();
  209348. QTCompBaseClass::visibilityChanged();
  209349. }
  209350. void QuickTimeMovieComponent::paint (Graphics& g)
  209351. {
  209352. if (! isControlCreated())
  209353. g.fillAll (Colours::black);
  209354. }
  209355. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209356. {
  209357. Handle dataRef = 0;
  209358. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209359. if (err == noErr)
  209360. {
  209361. Str255 suffix;
  209362. strncpy ((char*) suffix, fileName, 128);
  209363. StringPtr name = suffix;
  209364. err = PtrAndHand (name, dataRef, name[0] + 1);
  209365. if (err == noErr)
  209366. {
  209367. long atoms[3];
  209368. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209369. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209370. atoms[2] = EndianU32_NtoB (MovieFileType);
  209371. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209372. if (err == noErr)
  209373. return dataRef;
  209374. }
  209375. DisposeHandle (dataRef);
  209376. }
  209377. return 0;
  209378. }
  209379. static CFStringRef juceStringToCFString (const String& s)
  209380. {
  209381. return CFStringCreateWithCString (kCFAllocatorDefault, s.toUTF8(), kCFStringEncodingUTF8);
  209382. }
  209383. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209384. {
  209385. Boolean trueBool = true;
  209386. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209387. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209388. props[prop].propValueSize = sizeof (trueBool);
  209389. props[prop].propValueAddress = &trueBool;
  209390. ++prop;
  209391. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209392. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209393. props[prop].propValueSize = sizeof (trueBool);
  209394. props[prop].propValueAddress = &trueBool;
  209395. ++prop;
  209396. Boolean isActive = true;
  209397. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209398. props[prop].propID = kQTNewMoviePropertyID_Active;
  209399. props[prop].propValueSize = sizeof (isActive);
  209400. props[prop].propValueAddress = &isActive;
  209401. ++prop;
  209402. MacSetPort (0);
  209403. jassert (prop <= 5);
  209404. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209405. return err == noErr;
  209406. }
  209407. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209408. {
  209409. if (input == 0)
  209410. return false;
  209411. dataHandle = 0;
  209412. bool ok = false;
  209413. QTNewMoviePropertyElement props[5];
  209414. zeromem (props, sizeof (props));
  209415. int prop = 0;
  209416. DataReferenceRecord dr;
  209417. props[prop].propClass = kQTPropertyClass_DataLocation;
  209418. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209419. props[prop].propValueSize = sizeof (dr);
  209420. props[prop].propValueAddress = &dr;
  209421. ++prop;
  209422. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209423. if (fin != 0)
  209424. {
  209425. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209426. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209427. &dr.dataRef, &dr.dataRefType);
  209428. ok = openMovie (props, prop, movie);
  209429. DisposeHandle (dr.dataRef);
  209430. CFRelease (filePath);
  209431. }
  209432. else
  209433. {
  209434. // sanity-check because this currently needs to load the whole stream into memory..
  209435. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209436. dataHandle = NewHandle ((Size) input->getTotalLength());
  209437. HLock (dataHandle);
  209438. // read the entire stream into memory - this is a pain, but can't get it to work
  209439. // properly using a custom callback to supply the data.
  209440. input->read (*dataHandle, (int) input->getTotalLength());
  209441. HUnlock (dataHandle);
  209442. // different types to get QT to try. (We should really be a bit smarter here by
  209443. // working out in advance which one the stream contains, rather than just trying
  209444. // each one)
  209445. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209446. "\04.avi", "\04.m4a" };
  209447. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209448. {
  209449. /* // this fails for some bizarre reason - it can be bodged to work with
  209450. // movies, but can't seem to do it for other file types..
  209451. QTNewMovieUserProcRecord procInfo;
  209452. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209453. procInfo.getMovieUserProcRefcon = this;
  209454. procInfo.defaultDataRef.dataRef = dataRef;
  209455. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209456. props[prop].propClass = kQTPropertyClass_DataLocation;
  209457. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209458. props[prop].propValueSize = sizeof (procInfo);
  209459. props[prop].propValueAddress = (void*) &procInfo;
  209460. ++prop; */
  209461. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209462. dr.dataRefType = HandleDataHandlerSubType;
  209463. ok = openMovie (props, prop, movie);
  209464. DisposeHandle (dr.dataRef);
  209465. }
  209466. }
  209467. return ok;
  209468. }
  209469. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209470. const bool isControllerVisible)
  209471. {
  209472. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209473. movieFile = movieFile_;
  209474. return ok;
  209475. }
  209476. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209477. const bool isControllerVisible)
  209478. {
  209479. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  209480. }
  209481. void QuickTimeMovieComponent::goToStart()
  209482. {
  209483. setPosition (0.0);
  209484. }
  209485. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  209486. const RectanglePlacement& placement)
  209487. {
  209488. int normalWidth, normalHeight;
  209489. getMovieNormalSize (normalWidth, normalHeight);
  209490. const Rectangle<int> normalSize (0, 0, normalWidth, normalHeight);
  209491. if (! (spaceToFitWithin.isEmpty() || normalSize.isEmpty()))
  209492. setBounds (placement.appliedTo (normalSize, spaceToFitWithin));
  209493. else
  209494. setBounds (spaceToFitWithin);
  209495. }
  209496. #endif
  209497. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209498. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209499. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209500. // compiled on its own).
  209501. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  209502. class WebBrowserComponentInternal : public ActiveXControlComponent
  209503. {
  209504. public:
  209505. WebBrowserComponentInternal()
  209506. : browser (0),
  209507. connectionPoint (0),
  209508. adviseCookie (0)
  209509. {
  209510. }
  209511. ~WebBrowserComponentInternal()
  209512. {
  209513. if (connectionPoint != 0)
  209514. connectionPoint->Unadvise (adviseCookie);
  209515. if (browser != 0)
  209516. browser->Release();
  209517. }
  209518. void createBrowser()
  209519. {
  209520. createControl (&CLSID_WebBrowser);
  209521. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  209522. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  209523. if (connectionPointContainer != 0)
  209524. {
  209525. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  209526. &connectionPoint);
  209527. if (connectionPoint != 0)
  209528. {
  209529. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  209530. jassert (owner != 0);
  209531. EventHandler* handler = new EventHandler (*owner);
  209532. connectionPoint->Advise (handler, &adviseCookie);
  209533. handler->Release();
  209534. }
  209535. }
  209536. }
  209537. void goToURL (const String& url,
  209538. const StringArray* headers,
  209539. const MemoryBlock* postData)
  209540. {
  209541. if (browser != 0)
  209542. {
  209543. LPSAFEARRAY sa = 0;
  209544. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  209545. VariantInit (&flags);
  209546. VariantInit (&frame);
  209547. VariantInit (&postDataVar);
  209548. VariantInit (&headersVar);
  209549. if (headers != 0)
  209550. {
  209551. V_VT (&headersVar) = VT_BSTR;
  209552. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n").toUTF16().getAddress());
  209553. }
  209554. if (postData != 0 && postData->getSize() > 0)
  209555. {
  209556. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  209557. if (sa != 0)
  209558. {
  209559. void* data = 0;
  209560. SafeArrayAccessData (sa, &data);
  209561. jassert (data != 0);
  209562. if (data != 0)
  209563. {
  209564. postData->copyTo (data, 0, postData->getSize());
  209565. SafeArrayUnaccessData (sa);
  209566. VARIANT postDataVar2;
  209567. VariantInit (&postDataVar2);
  209568. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  209569. V_ARRAY (&postDataVar2) = sa;
  209570. postDataVar = postDataVar2;
  209571. }
  209572. }
  209573. }
  209574. browser->Navigate ((BSTR) (const OLECHAR*) url.toUTF16().getAddress(),
  209575. &flags, &frame,
  209576. &postDataVar, &headersVar);
  209577. if (sa != 0)
  209578. SafeArrayDestroy (sa);
  209579. VariantClear (&flags);
  209580. VariantClear (&frame);
  209581. VariantClear (&postDataVar);
  209582. VariantClear (&headersVar);
  209583. }
  209584. }
  209585. IWebBrowser2* browser;
  209586. private:
  209587. IConnectionPoint* connectionPoint;
  209588. DWORD adviseCookie;
  209589. class EventHandler : public ComBaseClassHelper <IDispatch>,
  209590. public ComponentMovementWatcher
  209591. {
  209592. public:
  209593. EventHandler (WebBrowserComponent& owner_)
  209594. : ComponentMovementWatcher (&owner_),
  209595. owner (owner_)
  209596. {
  209597. }
  209598. HRESULT __stdcall GetTypeInfoCount (UINT*) { return E_NOTIMPL; }
  209599. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo**) { return E_NOTIMPL; }
  209600. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR*, UINT, LCID, DISPID*) { return E_NOTIMPL; }
  209601. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/, WORD /*wFlags*/, DISPPARAMS* pDispParams,
  209602. VARIANT* /*pVarResult*/, EXCEPINFO* /*pExcepInfo*/, UINT* /*puArgErr*/)
  209603. {
  209604. if (dispIdMember == DISPID_BEFORENAVIGATE2)
  209605. {
  209606. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  209607. String url;
  209608. if ((vurl->vt & VT_BYREF) != 0)
  209609. url = *vurl->pbstrVal;
  209610. else
  209611. url = vurl->bstrVal;
  209612. *pDispParams->rgvarg->pboolVal
  209613. = owner.pageAboutToLoad (url) ? VARIANT_FALSE
  209614. : VARIANT_TRUE;
  209615. return S_OK;
  209616. }
  209617. return E_NOTIMPL;
  209618. }
  209619. void componentMovedOrResized (bool, bool ) {}
  209620. void componentPeerChanged() {}
  209621. void componentVisibilityChanged() { owner.visibilityChanged(); }
  209622. private:
  209623. WebBrowserComponent& owner;
  209624. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EventHandler);
  209625. };
  209626. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebBrowserComponentInternal);
  209627. };
  209628. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  209629. : browser (0),
  209630. blankPageShown (false),
  209631. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  209632. {
  209633. setOpaque (true);
  209634. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  209635. }
  209636. WebBrowserComponent::~WebBrowserComponent()
  209637. {
  209638. delete browser;
  209639. }
  209640. void WebBrowserComponent::goToURL (const String& url,
  209641. const StringArray* headers,
  209642. const MemoryBlock* postData)
  209643. {
  209644. lastURL = url;
  209645. lastHeaders.clear();
  209646. if (headers != 0)
  209647. lastHeaders = *headers;
  209648. lastPostData.setSize (0);
  209649. if (postData != 0)
  209650. lastPostData = *postData;
  209651. blankPageShown = false;
  209652. browser->goToURL (url, headers, postData);
  209653. }
  209654. void WebBrowserComponent::stop()
  209655. {
  209656. if (browser->browser != 0)
  209657. browser->browser->Stop();
  209658. }
  209659. void WebBrowserComponent::goBack()
  209660. {
  209661. lastURL = String::empty;
  209662. blankPageShown = false;
  209663. if (browser->browser != 0)
  209664. browser->browser->GoBack();
  209665. }
  209666. void WebBrowserComponent::goForward()
  209667. {
  209668. lastURL = String::empty;
  209669. if (browser->browser != 0)
  209670. browser->browser->GoForward();
  209671. }
  209672. void WebBrowserComponent::refresh()
  209673. {
  209674. if (browser->browser != 0)
  209675. browser->browser->Refresh();
  209676. }
  209677. void WebBrowserComponent::paint (Graphics& g)
  209678. {
  209679. if (browser->browser == 0)
  209680. g.fillAll (Colours::white);
  209681. }
  209682. void WebBrowserComponent::checkWindowAssociation()
  209683. {
  209684. if (isShowing())
  209685. {
  209686. if (browser->browser == 0 && getPeer() != 0)
  209687. {
  209688. browser->createBrowser();
  209689. reloadLastURL();
  209690. }
  209691. else
  209692. {
  209693. if (blankPageShown)
  209694. goBack();
  209695. }
  209696. }
  209697. else
  209698. {
  209699. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  209700. {
  209701. // when the component becomes invisible, some stuff like flash
  209702. // carries on playing audio, so we need to force it onto a blank
  209703. // page to avoid this..
  209704. blankPageShown = true;
  209705. browser->goToURL ("about:blank", 0, 0);
  209706. }
  209707. }
  209708. }
  209709. void WebBrowserComponent::reloadLastURL()
  209710. {
  209711. if (lastURL.isNotEmpty())
  209712. {
  209713. goToURL (lastURL, &lastHeaders, &lastPostData);
  209714. lastURL = String::empty;
  209715. }
  209716. }
  209717. void WebBrowserComponent::parentHierarchyChanged()
  209718. {
  209719. checkWindowAssociation();
  209720. }
  209721. void WebBrowserComponent::resized()
  209722. {
  209723. browser->setSize (getWidth(), getHeight());
  209724. }
  209725. void WebBrowserComponent::visibilityChanged()
  209726. {
  209727. checkWindowAssociation();
  209728. }
  209729. bool WebBrowserComponent::pageAboutToLoad (const String&)
  209730. {
  209731. return true;
  209732. }
  209733. #endif
  209734. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209735. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  209736. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209737. // compiled on its own).
  209738. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  209739. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  209740. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  209741. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  209742. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  209743. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  209744. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  209745. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  209746. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  209747. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  209748. #define WGL_ACCELERATION_ARB 0x2003
  209749. #define WGL_SWAP_METHOD_ARB 0x2007
  209750. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  209751. #define WGL_PIXEL_TYPE_ARB 0x2013
  209752. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  209753. #define WGL_COLOR_BITS_ARB 0x2014
  209754. #define WGL_RED_BITS_ARB 0x2015
  209755. #define WGL_GREEN_BITS_ARB 0x2017
  209756. #define WGL_BLUE_BITS_ARB 0x2019
  209757. #define WGL_ALPHA_BITS_ARB 0x201B
  209758. #define WGL_DEPTH_BITS_ARB 0x2022
  209759. #define WGL_STENCIL_BITS_ARB 0x2023
  209760. #define WGL_FULL_ACCELERATION_ARB 0x2027
  209761. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  209762. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  209763. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  209764. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  209765. #define WGL_STEREO_ARB 0x2012
  209766. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  209767. #define WGL_SAMPLES_ARB 0x2042
  209768. #define WGL_TYPE_RGBA_ARB 0x202B
  209769. static void getWglExtensions (HDC dc, StringArray& result) throw()
  209770. {
  209771. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  209772. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  209773. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  209774. else
  209775. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  209776. }
  209777. class WindowedGLContext : public OpenGLContext
  209778. {
  209779. public:
  209780. WindowedGLContext (Component* const component_,
  209781. HGLRC contextToShareWith,
  209782. const OpenGLPixelFormat& pixelFormat)
  209783. : renderContext (0),
  209784. component (component_),
  209785. dc (0)
  209786. {
  209787. jassert (component != 0);
  209788. createNativeWindow();
  209789. // Use a default pixel format that should be supported everywhere
  209790. PIXELFORMATDESCRIPTOR pfd;
  209791. zerostruct (pfd);
  209792. pfd.nSize = sizeof (pfd);
  209793. pfd.nVersion = 1;
  209794. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  209795. pfd.iPixelType = PFD_TYPE_RGBA;
  209796. pfd.cColorBits = 24;
  209797. pfd.cDepthBits = 16;
  209798. const int format = ChoosePixelFormat (dc, &pfd);
  209799. if (format != 0)
  209800. SetPixelFormat (dc, format, &pfd);
  209801. renderContext = wglCreateContext (dc);
  209802. makeActive();
  209803. setPixelFormat (pixelFormat);
  209804. if (contextToShareWith != 0 && renderContext != 0)
  209805. wglShareLists (contextToShareWith, renderContext);
  209806. }
  209807. ~WindowedGLContext()
  209808. {
  209809. deleteContext();
  209810. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  209811. nativeWindow = 0;
  209812. }
  209813. void deleteContext()
  209814. {
  209815. makeInactive();
  209816. if (renderContext != 0)
  209817. {
  209818. wglDeleteContext (renderContext);
  209819. renderContext = 0;
  209820. }
  209821. }
  209822. bool makeActive() const throw()
  209823. {
  209824. jassert (renderContext != 0);
  209825. return wglMakeCurrent (dc, renderContext) != 0;
  209826. }
  209827. bool makeInactive() const throw()
  209828. {
  209829. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  209830. }
  209831. bool isActive() const throw()
  209832. {
  209833. return wglGetCurrentContext() == renderContext;
  209834. }
  209835. const OpenGLPixelFormat getPixelFormat() const
  209836. {
  209837. OpenGLPixelFormat pf;
  209838. makeActive();
  209839. StringArray availableExtensions;
  209840. getWglExtensions (dc, availableExtensions);
  209841. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  209842. return pf;
  209843. }
  209844. void* getRawContext() const throw()
  209845. {
  209846. return renderContext;
  209847. }
  209848. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  209849. {
  209850. makeActive();
  209851. PIXELFORMATDESCRIPTOR pfd;
  209852. zerostruct (pfd);
  209853. pfd.nSize = sizeof (pfd);
  209854. pfd.nVersion = 1;
  209855. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  209856. pfd.iPixelType = PFD_TYPE_RGBA;
  209857. pfd.iLayerType = PFD_MAIN_PLANE;
  209858. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  209859. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  209860. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  209861. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  209862. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  209863. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  209864. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  209865. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  209866. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  209867. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  209868. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  209869. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  209870. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  209871. int format = 0;
  209872. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  209873. StringArray availableExtensions;
  209874. getWglExtensions (dc, availableExtensions);
  209875. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  209876. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  209877. {
  209878. int attributes[64];
  209879. int n = 0;
  209880. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  209881. attributes[n++] = GL_TRUE;
  209882. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  209883. attributes[n++] = GL_TRUE;
  209884. attributes[n++] = WGL_ACCELERATION_ARB;
  209885. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  209886. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  209887. attributes[n++] = GL_TRUE;
  209888. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  209889. attributes[n++] = WGL_TYPE_RGBA_ARB;
  209890. attributes[n++] = WGL_COLOR_BITS_ARB;
  209891. attributes[n++] = pfd.cColorBits;
  209892. attributes[n++] = WGL_RED_BITS_ARB;
  209893. attributes[n++] = pixelFormat.redBits;
  209894. attributes[n++] = WGL_GREEN_BITS_ARB;
  209895. attributes[n++] = pixelFormat.greenBits;
  209896. attributes[n++] = WGL_BLUE_BITS_ARB;
  209897. attributes[n++] = pixelFormat.blueBits;
  209898. attributes[n++] = WGL_ALPHA_BITS_ARB;
  209899. attributes[n++] = pixelFormat.alphaBits;
  209900. attributes[n++] = WGL_DEPTH_BITS_ARB;
  209901. attributes[n++] = pixelFormat.depthBufferBits;
  209902. if (pixelFormat.stencilBufferBits > 0)
  209903. {
  209904. attributes[n++] = WGL_STENCIL_BITS_ARB;
  209905. attributes[n++] = pixelFormat.stencilBufferBits;
  209906. }
  209907. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  209908. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  209909. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  209910. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  209911. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  209912. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  209913. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  209914. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  209915. if (availableExtensions.contains ("WGL_ARB_multisample")
  209916. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  209917. {
  209918. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  209919. attributes[n++] = 1;
  209920. attributes[n++] = WGL_SAMPLES_ARB;
  209921. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  209922. }
  209923. attributes[n++] = 0;
  209924. UINT formatsCount;
  209925. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  209926. (void) ok;
  209927. jassert (ok);
  209928. }
  209929. else
  209930. {
  209931. format = ChoosePixelFormat (dc, &pfd);
  209932. }
  209933. if (format != 0)
  209934. {
  209935. makeInactive();
  209936. // win32 can't change the pixel format of a window, so need to delete the
  209937. // old one and create a new one..
  209938. jassert (nativeWindow != 0);
  209939. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  209940. nativeWindow = 0;
  209941. createNativeWindow();
  209942. if (SetPixelFormat (dc, format, &pfd))
  209943. {
  209944. wglDeleteContext (renderContext);
  209945. renderContext = wglCreateContext (dc);
  209946. jassert (renderContext != 0);
  209947. return renderContext != 0;
  209948. }
  209949. }
  209950. return false;
  209951. }
  209952. void updateWindowPosition (int x, int y, int w, int h, int)
  209953. {
  209954. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  209955. x, y, w, h,
  209956. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  209957. }
  209958. void repaint()
  209959. {
  209960. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  209961. }
  209962. void swapBuffers()
  209963. {
  209964. SwapBuffers (dc);
  209965. }
  209966. bool setSwapInterval (int numFramesPerSwap)
  209967. {
  209968. makeActive();
  209969. StringArray availableExtensions;
  209970. getWglExtensions (dc, availableExtensions);
  209971. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  209972. return availableExtensions.contains ("WGL_EXT_swap_control")
  209973. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  209974. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  209975. }
  209976. int getSwapInterval() const
  209977. {
  209978. makeActive();
  209979. StringArray availableExtensions;
  209980. getWglExtensions (dc, availableExtensions);
  209981. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  209982. if (availableExtensions.contains ("WGL_EXT_swap_control")
  209983. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  209984. return wglGetSwapIntervalEXT();
  209985. return 0;
  209986. }
  209987. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  209988. {
  209989. jassert (isActive());
  209990. StringArray availableExtensions;
  209991. getWglExtensions (dc, availableExtensions);
  209992. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  209993. int numTypes = 0;
  209994. if (availableExtensions.contains("WGL_ARB_pixel_format")
  209995. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  209996. {
  209997. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  209998. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  209999. jassertfalse;
  210000. }
  210001. else
  210002. {
  210003. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  210004. }
  210005. OpenGLPixelFormat pf;
  210006. for (int i = 0; i < numTypes; ++i)
  210007. {
  210008. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210009. {
  210010. bool alreadyListed = false;
  210011. for (int j = results.size(); --j >= 0;)
  210012. if (pf == *results.getUnchecked(j))
  210013. alreadyListed = true;
  210014. if (! alreadyListed)
  210015. results.add (new OpenGLPixelFormat (pf));
  210016. }
  210017. }
  210018. }
  210019. void* getNativeWindowHandle() const
  210020. {
  210021. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210022. }
  210023. HGLRC renderContext;
  210024. private:
  210025. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210026. Component* const component;
  210027. HDC dc;
  210028. void createNativeWindow()
  210029. {
  210030. Win32ComponentPeer* topLevelPeer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210031. nativeWindow = new Win32ComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  210032. topLevelPeer == 0 ? 0 : (HWND) topLevelPeer->getNativeHandle());
  210033. nativeWindow->dontRepaint = true;
  210034. nativeWindow->setVisible (true);
  210035. dc = GetDC ((HWND) nativeWindow->getNativeHandle());
  210036. }
  210037. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210038. OpenGLPixelFormat& result,
  210039. const StringArray& availableExtensions) const throw()
  210040. {
  210041. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210042. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210043. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210044. {
  210045. int attributes[32];
  210046. int numAttributes = 0;
  210047. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210048. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210049. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210050. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210051. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210052. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210053. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210054. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210055. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210056. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210057. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210058. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210059. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210060. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210061. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210062. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210063. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210064. int values[32];
  210065. zeromem (values, sizeof (values));
  210066. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210067. {
  210068. int n = 0;
  210069. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210070. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210071. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210072. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210073. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210074. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210075. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210076. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210077. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210078. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210079. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210080. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210081. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210082. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210083. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210084. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210085. return isValidFormat;
  210086. }
  210087. else
  210088. {
  210089. jassertfalse;
  210090. }
  210091. }
  210092. else
  210093. {
  210094. PIXELFORMATDESCRIPTOR pfd;
  210095. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210096. {
  210097. result.redBits = pfd.cRedBits;
  210098. result.greenBits = pfd.cGreenBits;
  210099. result.blueBits = pfd.cBlueBits;
  210100. result.alphaBits = pfd.cAlphaBits;
  210101. result.depthBufferBits = pfd.cDepthBits;
  210102. result.stencilBufferBits = pfd.cStencilBits;
  210103. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210104. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210105. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210106. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210107. result.fullSceneAntiAliasingNumSamples = 0;
  210108. return true;
  210109. }
  210110. else
  210111. {
  210112. jassertfalse;
  210113. }
  210114. }
  210115. return false;
  210116. }
  210117. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  210118. };
  210119. OpenGLContext* OpenGLComponent::createContext()
  210120. {
  210121. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210122. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210123. preferredPixelFormat));
  210124. return (c->renderContext != 0) ? c.release() : 0;
  210125. }
  210126. void* OpenGLComponent::getNativeWindowHandle() const
  210127. {
  210128. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210129. }
  210130. void juce_glViewport (const int w, const int h)
  210131. {
  210132. glViewport (0, 0, w, h);
  210133. }
  210134. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210135. OwnedArray <OpenGLPixelFormat>& results)
  210136. {
  210137. Component tempComp;
  210138. {
  210139. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210140. wc.makeActive();
  210141. wc.findAlternativeOpenGLPixelFormats (results);
  210142. }
  210143. }
  210144. #endif
  210145. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210146. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210147. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210148. // compiled on its own).
  210149. #if JUCE_INCLUDED_FILE
  210150. #if JUCE_USE_CDREADER
  210151. namespace CDReaderHelpers
  210152. {
  210153. #define FILE_ANY_ACCESS 0
  210154. #ifndef FILE_READ_ACCESS
  210155. #define FILE_READ_ACCESS 1
  210156. #endif
  210157. #ifndef FILE_WRITE_ACCESS
  210158. #define FILE_WRITE_ACCESS 2
  210159. #endif
  210160. #define METHOD_BUFFERED 0
  210161. #define IOCTL_SCSI_BASE 4
  210162. #define SCSI_IOCTL_DATA_OUT 0
  210163. #define SCSI_IOCTL_DATA_IN 1
  210164. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210165. #define CTL_CODE2(DevType, Function, Method, Access) (((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method))
  210166. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210167. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210168. #define SENSE_LEN 14
  210169. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210170. #define SRB_DIR_IN 0x08
  210171. #define SRB_DIR_OUT 0x10
  210172. #define SRB_EVENT_NOTIFY 0x40
  210173. #define SC_HA_INQUIRY 0x00
  210174. #define SC_GET_DEV_TYPE 0x01
  210175. #define SC_EXEC_SCSI_CMD 0x02
  210176. #define SS_PENDING 0x00
  210177. #define SS_COMP 0x01
  210178. #define SS_ERR 0x04
  210179. enum
  210180. {
  210181. READTYPE_ANY = 0,
  210182. READTYPE_ATAPI1 = 1,
  210183. READTYPE_ATAPI2 = 2,
  210184. READTYPE_READ6 = 3,
  210185. READTYPE_READ10 = 4,
  210186. READTYPE_READ_D8 = 5,
  210187. READTYPE_READ_D4 = 6,
  210188. READTYPE_READ_D4_1 = 7,
  210189. READTYPE_READ10_2 = 8
  210190. };
  210191. struct SCSI_PASS_THROUGH
  210192. {
  210193. USHORT Length;
  210194. UCHAR ScsiStatus;
  210195. UCHAR PathId;
  210196. UCHAR TargetId;
  210197. UCHAR Lun;
  210198. UCHAR CdbLength;
  210199. UCHAR SenseInfoLength;
  210200. UCHAR DataIn;
  210201. ULONG DataTransferLength;
  210202. ULONG TimeOutValue;
  210203. ULONG DataBufferOffset;
  210204. ULONG SenseInfoOffset;
  210205. UCHAR Cdb[16];
  210206. };
  210207. struct SCSI_PASS_THROUGH_DIRECT
  210208. {
  210209. USHORT Length;
  210210. UCHAR ScsiStatus;
  210211. UCHAR PathId;
  210212. UCHAR TargetId;
  210213. UCHAR Lun;
  210214. UCHAR CdbLength;
  210215. UCHAR SenseInfoLength;
  210216. UCHAR DataIn;
  210217. ULONG DataTransferLength;
  210218. ULONG TimeOutValue;
  210219. PVOID DataBuffer;
  210220. ULONG SenseInfoOffset;
  210221. UCHAR Cdb[16];
  210222. };
  210223. struct SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER
  210224. {
  210225. SCSI_PASS_THROUGH_DIRECT spt;
  210226. ULONG Filler;
  210227. UCHAR ucSenseBuf[32];
  210228. };
  210229. struct SCSI_ADDRESS
  210230. {
  210231. ULONG Length;
  210232. UCHAR PortNumber;
  210233. UCHAR PathId;
  210234. UCHAR TargetId;
  210235. UCHAR Lun;
  210236. };
  210237. #pragma pack(1)
  210238. struct SRB_GDEVBlock
  210239. {
  210240. BYTE SRB_Cmd;
  210241. BYTE SRB_Status;
  210242. BYTE SRB_HaID;
  210243. BYTE SRB_Flags;
  210244. DWORD SRB_Hdr_Rsvd;
  210245. BYTE SRB_Target;
  210246. BYTE SRB_Lun;
  210247. BYTE SRB_DeviceType;
  210248. BYTE SRB_Rsvd1;
  210249. BYTE pad[68];
  210250. };
  210251. struct SRB_ExecSCSICmd
  210252. {
  210253. BYTE SRB_Cmd;
  210254. BYTE SRB_Status;
  210255. BYTE SRB_HaID;
  210256. BYTE SRB_Flags;
  210257. DWORD SRB_Hdr_Rsvd;
  210258. BYTE SRB_Target;
  210259. BYTE SRB_Lun;
  210260. WORD SRB_Rsvd1;
  210261. DWORD SRB_BufLen;
  210262. BYTE *SRB_BufPointer;
  210263. BYTE SRB_SenseLen;
  210264. BYTE SRB_CDBLen;
  210265. BYTE SRB_HaStat;
  210266. BYTE SRB_TargStat;
  210267. VOID *SRB_PostProc;
  210268. BYTE SRB_Rsvd2[20];
  210269. BYTE CDBByte[16];
  210270. BYTE SenseArea[SENSE_LEN + 2];
  210271. };
  210272. struct SRB
  210273. {
  210274. BYTE SRB_Cmd;
  210275. BYTE SRB_Status;
  210276. BYTE SRB_HaId;
  210277. BYTE SRB_Flags;
  210278. DWORD SRB_Hdr_Rsvd;
  210279. };
  210280. struct TOCTRACK
  210281. {
  210282. BYTE rsvd;
  210283. BYTE ADR;
  210284. BYTE trackNumber;
  210285. BYTE rsvd2;
  210286. BYTE addr[4];
  210287. };
  210288. struct TOC
  210289. {
  210290. WORD tocLen;
  210291. BYTE firstTrack;
  210292. BYTE lastTrack;
  210293. TOCTRACK tracks[100];
  210294. };
  210295. #pragma pack()
  210296. struct CDDeviceDescription
  210297. {
  210298. CDDeviceDescription() : ha (0), tgt (0), lun (0), scsiDriveLetter (0)
  210299. {
  210300. }
  210301. void createDescription (const char* data)
  210302. {
  210303. description << String (data + 8, 8).trim() // vendor
  210304. << ' ' << String (data + 16, 16).trim() // product id
  210305. << ' ' << String (data + 32, 4).trim(); // rev
  210306. }
  210307. String description;
  210308. BYTE ha, tgt, lun;
  210309. char scsiDriveLetter; // will be 0 if not using scsi
  210310. };
  210311. class CDReadBuffer
  210312. {
  210313. public:
  210314. CDReadBuffer (const int numberOfFrames)
  210315. : startFrame (0), numFrames (0), dataStartOffset (0),
  210316. dataLength (0), bufferSize (2352 * numberOfFrames), index (0),
  210317. buffer (bufferSize), wantsIndex (false)
  210318. {
  210319. }
  210320. bool isZero() const throw()
  210321. {
  210322. for (int i = 0; i < dataLength; ++i)
  210323. if (buffer [dataStartOffset + i] != 0)
  210324. return false;
  210325. return true;
  210326. }
  210327. int startFrame, numFrames, dataStartOffset;
  210328. int dataLength, bufferSize, index;
  210329. HeapBlock<BYTE> buffer;
  210330. bool wantsIndex;
  210331. };
  210332. class CDDeviceHandle;
  210333. class CDController
  210334. {
  210335. public:
  210336. CDController() : initialised (false) {}
  210337. virtual ~CDController() {}
  210338. virtual bool read (CDReadBuffer&) = 0;
  210339. virtual void shutDown() {}
  210340. bool readAudio (CDReadBuffer& rb, CDReadBuffer* overlapBuffer = 0);
  210341. int getLastIndex();
  210342. public:
  210343. CDDeviceHandle* deviceInfo;
  210344. int framesToCheck, framesOverlap;
  210345. bool initialised;
  210346. void prepare (SRB_ExecSCSICmd& s);
  210347. void perform (SRB_ExecSCSICmd& s);
  210348. void setPaused (bool paused);
  210349. };
  210350. class CDDeviceHandle
  210351. {
  210352. public:
  210353. CDDeviceHandle (const CDDeviceDescription& device, HANDLE scsiHandle_)
  210354. : info (device), scsiHandle (scsiHandle_), readType (READTYPE_ANY)
  210355. {
  210356. }
  210357. ~CDDeviceHandle()
  210358. {
  210359. if (controller != 0)
  210360. {
  210361. controller->shutDown();
  210362. controller = 0;
  210363. }
  210364. if (scsiHandle != 0)
  210365. CloseHandle (scsiHandle);
  210366. }
  210367. bool readTOC (TOC* lpToc);
  210368. bool readAudio (CDReadBuffer& buffer, CDReadBuffer* overlapBuffer = 0);
  210369. void openDrawer (bool shouldBeOpen);
  210370. void performScsiCommand (HANDLE event, SRB_ExecSCSICmd& s);
  210371. CDDeviceDescription info;
  210372. HANDLE scsiHandle;
  210373. BYTE readType;
  210374. private:
  210375. ScopedPointer<CDController> controller;
  210376. bool testController (int readType, CDController* newController, CDReadBuffer& bufferToUse);
  210377. };
  210378. HANDLE createSCSIDeviceHandle (const char driveLetter)
  210379. {
  210380. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  210381. DWORD flags = GENERIC_READ | GENERIC_WRITE;
  210382. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210383. if (h == INVALID_HANDLE_VALUE)
  210384. {
  210385. flags ^= GENERIC_WRITE;
  210386. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210387. }
  210388. return h;
  210389. }
  210390. void findCDDevices (Array<CDDeviceDescription>& list)
  210391. {
  210392. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  210393. {
  210394. TCHAR drivePath[] = { driveLetter, ':', '\\', 0, 0 };
  210395. if (GetDriveType (drivePath) == DRIVE_CDROM)
  210396. {
  210397. HANDLE h = createSCSIDeviceHandle (driveLetter);
  210398. if (h != INVALID_HANDLE_VALUE)
  210399. {
  210400. char buffer[100];
  210401. zeromem (buffer, sizeof (buffer));
  210402. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p;
  210403. zerostruct (p);
  210404. p.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210405. p.spt.CdbLength = 6;
  210406. p.spt.SenseInfoLength = 24;
  210407. p.spt.DataIn = SCSI_IOCTL_DATA_IN;
  210408. p.spt.DataTransferLength = sizeof (buffer);
  210409. p.spt.TimeOutValue = 2;
  210410. p.spt.DataBuffer = buffer;
  210411. p.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210412. p.spt.Cdb[0] = 0x12;
  210413. p.spt.Cdb[4] = 100;
  210414. DWORD bytesReturned = 0;
  210415. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210416. &p, sizeof (p), &p, sizeof (p),
  210417. &bytesReturned, 0) != 0)
  210418. {
  210419. CDDeviceDescription dev;
  210420. dev.scsiDriveLetter = driveLetter;
  210421. dev.createDescription (buffer);
  210422. SCSI_ADDRESS scsiAddr;
  210423. zerostruct (scsiAddr);
  210424. scsiAddr.Length = sizeof (scsiAddr);
  210425. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  210426. 0, 0, &scsiAddr, sizeof (scsiAddr),
  210427. &bytesReturned, 0) != 0)
  210428. {
  210429. dev.ha = scsiAddr.PortNumber;
  210430. dev.tgt = scsiAddr.TargetId;
  210431. dev.lun = scsiAddr.Lun;
  210432. list.add (dev);
  210433. }
  210434. }
  210435. CloseHandle (h);
  210436. }
  210437. }
  210438. }
  210439. }
  210440. DWORD performScsiPassThroughCommand (SRB_ExecSCSICmd* const srb, const char driveLetter,
  210441. HANDLE& deviceHandle, const bool retryOnFailure)
  210442. {
  210443. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  210444. zerostruct (s);
  210445. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210446. s.spt.CdbLength = srb->SRB_CDBLen;
  210447. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  210448. ? SCSI_IOCTL_DATA_IN
  210449. : ((srb->SRB_Flags & SRB_DIR_OUT)
  210450. ? SCSI_IOCTL_DATA_OUT
  210451. : SCSI_IOCTL_DATA_UNSPECIFIED));
  210452. s.spt.DataTransferLength = srb->SRB_BufLen;
  210453. s.spt.TimeOutValue = 5;
  210454. s.spt.DataBuffer = srb->SRB_BufPointer;
  210455. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210456. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  210457. srb->SRB_Status = SS_ERR;
  210458. srb->SRB_TargStat = 0x0004;
  210459. DWORD bytesReturned = 0;
  210460. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210461. &s, sizeof (s), &s, sizeof (s), &bytesReturned, 0) != 0)
  210462. {
  210463. srb->SRB_Status = SS_COMP;
  210464. }
  210465. else if (retryOnFailure)
  210466. {
  210467. const DWORD error = GetLastError();
  210468. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  210469. {
  210470. if (error != ERROR_INVALID_HANDLE)
  210471. CloseHandle (deviceHandle);
  210472. deviceHandle = createSCSIDeviceHandle (driveLetter);
  210473. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  210474. }
  210475. }
  210476. return srb->SRB_Status;
  210477. }
  210478. // Controller types..
  210479. class ControllerType1 : public CDController
  210480. {
  210481. public:
  210482. ControllerType1() {}
  210483. bool read (CDReadBuffer& rb)
  210484. {
  210485. if (rb.numFrames * 2352 > rb.bufferSize)
  210486. return false;
  210487. SRB_ExecSCSICmd s;
  210488. prepare (s);
  210489. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210490. s.SRB_BufLen = rb.bufferSize;
  210491. s.SRB_BufPointer = rb.buffer;
  210492. s.SRB_CDBLen = 12;
  210493. s.CDBByte[0] = 0xBE;
  210494. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210495. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210496. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210497. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  210498. s.CDBByte[9] = (BYTE) (deviceInfo->readType == READTYPE_ATAPI1 ? 0x10 : 0xF0);
  210499. perform (s);
  210500. if (s.SRB_Status != SS_COMP)
  210501. return false;
  210502. rb.dataLength = rb.numFrames * 2352;
  210503. rb.dataStartOffset = 0;
  210504. return true;
  210505. }
  210506. };
  210507. class ControllerType2 : public CDController
  210508. {
  210509. public:
  210510. ControllerType2() {}
  210511. void shutDown()
  210512. {
  210513. if (initialised)
  210514. {
  210515. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  210516. SRB_ExecSCSICmd s;
  210517. prepare (s);
  210518. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  210519. s.SRB_BufLen = 0x0C;
  210520. s.SRB_BufPointer = bufPointer;
  210521. s.SRB_CDBLen = 6;
  210522. s.CDBByte[0] = 0x15;
  210523. s.CDBByte[4] = 0x0C;
  210524. perform (s);
  210525. }
  210526. }
  210527. bool init()
  210528. {
  210529. SRB_ExecSCSICmd s;
  210530. s.SRB_Status = SS_ERR;
  210531. if (deviceInfo->readType == READTYPE_READ10_2)
  210532. {
  210533. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  210534. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  210535. for (int i = 0; i < 2; ++i)
  210536. {
  210537. prepare (s);
  210538. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210539. s.SRB_BufLen = 0x14;
  210540. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  210541. s.SRB_CDBLen = 6;
  210542. s.CDBByte[0] = 0x15;
  210543. s.CDBByte[1] = 0x10;
  210544. s.CDBByte[4] = 0x14;
  210545. perform (s);
  210546. if (s.SRB_Status != SS_COMP)
  210547. return false;
  210548. }
  210549. }
  210550. else
  210551. {
  210552. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  210553. prepare (s);
  210554. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210555. s.SRB_BufLen = 0x0C;
  210556. s.SRB_BufPointer = bufPointer;
  210557. s.SRB_CDBLen = 6;
  210558. s.CDBByte[0] = 0x15;
  210559. s.CDBByte[4] = 0x0C;
  210560. perform (s);
  210561. }
  210562. return s.SRB_Status == SS_COMP;
  210563. }
  210564. bool read (CDReadBuffer& rb)
  210565. {
  210566. if (rb.numFrames * 2352 > rb.bufferSize)
  210567. return false;
  210568. if (! initialised)
  210569. {
  210570. initialised = init();
  210571. if (! initialised)
  210572. return false;
  210573. }
  210574. SRB_ExecSCSICmd s;
  210575. prepare (s);
  210576. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210577. s.SRB_BufLen = rb.bufferSize;
  210578. s.SRB_BufPointer = rb.buffer;
  210579. s.SRB_CDBLen = 10;
  210580. s.CDBByte[0] = 0x28;
  210581. s.CDBByte[1] = (BYTE) (deviceInfo->info.lun << 5);
  210582. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210583. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210584. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210585. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  210586. perform (s);
  210587. if (s.SRB_Status != SS_COMP)
  210588. return false;
  210589. rb.dataLength = rb.numFrames * 2352;
  210590. rb.dataStartOffset = 0;
  210591. return true;
  210592. }
  210593. };
  210594. class ControllerType3 : public CDController
  210595. {
  210596. public:
  210597. ControllerType3() {}
  210598. bool read (CDReadBuffer& rb)
  210599. {
  210600. if (rb.numFrames * 2352 > rb.bufferSize)
  210601. return false;
  210602. if (! initialised)
  210603. {
  210604. setPaused (false);
  210605. initialised = true;
  210606. }
  210607. SRB_ExecSCSICmd s;
  210608. prepare (s);
  210609. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210610. s.SRB_BufLen = rb.numFrames * 2352;
  210611. s.SRB_BufPointer = rb.buffer;
  210612. s.SRB_CDBLen = 12;
  210613. s.CDBByte[0] = 0xD8;
  210614. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210615. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210616. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210617. s.CDBByte[9] = (BYTE) (rb.numFrames & 0xFF);
  210618. perform (s);
  210619. if (s.SRB_Status != SS_COMP)
  210620. return false;
  210621. rb.dataLength = rb.numFrames * 2352;
  210622. rb.dataStartOffset = 0;
  210623. return true;
  210624. }
  210625. };
  210626. class ControllerType4 : public CDController
  210627. {
  210628. public:
  210629. ControllerType4() {}
  210630. bool selectD4Mode()
  210631. {
  210632. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  210633. SRB_ExecSCSICmd s;
  210634. prepare (s);
  210635. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210636. s.SRB_CDBLen = 6;
  210637. s.SRB_BufLen = 12;
  210638. s.SRB_BufPointer = bufPointer;
  210639. s.CDBByte[0] = 0x15;
  210640. s.CDBByte[1] = 0x10;
  210641. s.CDBByte[4] = 0x08;
  210642. perform (s);
  210643. return s.SRB_Status == SS_COMP;
  210644. }
  210645. bool read (CDReadBuffer& rb)
  210646. {
  210647. if (rb.numFrames * 2352 > rb.bufferSize)
  210648. return false;
  210649. if (! initialised)
  210650. {
  210651. setPaused (true);
  210652. if (deviceInfo->readType == READTYPE_READ_D4_1)
  210653. selectD4Mode();
  210654. initialised = true;
  210655. }
  210656. SRB_ExecSCSICmd s;
  210657. prepare (s);
  210658. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210659. s.SRB_BufLen = rb.bufferSize;
  210660. s.SRB_BufPointer = rb.buffer;
  210661. s.SRB_CDBLen = 10;
  210662. s.CDBByte[0] = 0xD4;
  210663. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210664. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210665. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210666. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  210667. perform (s);
  210668. if (s.SRB_Status != SS_COMP)
  210669. return false;
  210670. rb.dataLength = rb.numFrames * 2352;
  210671. rb.dataStartOffset = 0;
  210672. return true;
  210673. }
  210674. };
  210675. void CDController::prepare (SRB_ExecSCSICmd& s)
  210676. {
  210677. zerostruct (s);
  210678. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210679. s.SRB_HaID = deviceInfo->info.ha;
  210680. s.SRB_Target = deviceInfo->info.tgt;
  210681. s.SRB_Lun = deviceInfo->info.lun;
  210682. s.SRB_SenseLen = SENSE_LEN;
  210683. }
  210684. void CDController::perform (SRB_ExecSCSICmd& s)
  210685. {
  210686. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  210687. deviceInfo->performScsiCommand (s.SRB_PostProc, s);
  210688. }
  210689. void CDController::setPaused (bool paused)
  210690. {
  210691. SRB_ExecSCSICmd s;
  210692. prepare (s);
  210693. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210694. s.SRB_CDBLen = 10;
  210695. s.CDBByte[0] = 0x4B;
  210696. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  210697. perform (s);
  210698. }
  210699. bool CDController::readAudio (CDReadBuffer& rb, CDReadBuffer* overlapBuffer)
  210700. {
  210701. if (overlapBuffer != 0)
  210702. {
  210703. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  210704. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  210705. if (doJitter
  210706. && overlapBuffer->startFrame > 0
  210707. && overlapBuffer->numFrames > 0
  210708. && overlapBuffer->dataLength > 0)
  210709. {
  210710. const int numFrames = rb.numFrames;
  210711. if (overlapBuffer->startFrame == (rb.startFrame - framesToCheck))
  210712. {
  210713. rb.startFrame -= framesOverlap;
  210714. if (framesToCheck < framesOverlap
  210715. && numFrames + framesOverlap <= rb.bufferSize / 2352)
  210716. rb.numFrames += framesOverlap;
  210717. }
  210718. else
  210719. {
  210720. overlapBuffer->dataLength = 0;
  210721. overlapBuffer->startFrame = 0;
  210722. overlapBuffer->numFrames = 0;
  210723. }
  210724. }
  210725. if (! read (rb))
  210726. return false;
  210727. if (doJitter)
  210728. {
  210729. const int checkLen = framesToCheck * 2352;
  210730. const int maxToCheck = rb.dataLength - checkLen;
  210731. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  210732. return true;
  210733. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  210734. bool found = false;
  210735. for (int i = 0; i < maxToCheck; ++i)
  210736. {
  210737. if (memcmp (p, rb.buffer + i, checkLen) == 0)
  210738. {
  210739. i += checkLen;
  210740. rb.dataStartOffset = i;
  210741. rb.dataLength -= i;
  210742. rb.startFrame = overlapBuffer->startFrame + framesToCheck;
  210743. found = true;
  210744. break;
  210745. }
  210746. }
  210747. rb.numFrames = rb.dataLength / 2352;
  210748. rb.dataLength = 2352 * rb.numFrames;
  210749. if (! found)
  210750. return false;
  210751. }
  210752. if (canDoJitter)
  210753. {
  210754. memcpy (overlapBuffer->buffer,
  210755. rb.buffer + rb.dataStartOffset + 2352 * (rb.numFrames - framesToCheck),
  210756. 2352 * framesToCheck);
  210757. overlapBuffer->startFrame = rb.startFrame + rb.numFrames - framesToCheck;
  210758. overlapBuffer->numFrames = framesToCheck;
  210759. overlapBuffer->dataLength = 2352 * framesToCheck;
  210760. overlapBuffer->dataStartOffset = 0;
  210761. }
  210762. else
  210763. {
  210764. overlapBuffer->startFrame = 0;
  210765. overlapBuffer->numFrames = 0;
  210766. overlapBuffer->dataLength = 0;
  210767. }
  210768. return true;
  210769. }
  210770. return read (rb);
  210771. }
  210772. int CDController::getLastIndex()
  210773. {
  210774. char qdata[100];
  210775. SRB_ExecSCSICmd s;
  210776. prepare (s);
  210777. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210778. s.SRB_BufLen = sizeof (qdata);
  210779. s.SRB_BufPointer = (BYTE*) qdata;
  210780. s.SRB_CDBLen = 12;
  210781. s.CDBByte[0] = 0x42;
  210782. s.CDBByte[1] = (BYTE) (deviceInfo->info.lun << 5);
  210783. s.CDBByte[2] = 64;
  210784. s.CDBByte[3] = 1; // get current position
  210785. s.CDBByte[7] = 0;
  210786. s.CDBByte[8] = (BYTE) sizeof (qdata);
  210787. perform (s);
  210788. return s.SRB_Status == SS_COMP ? qdata[7] : 0;
  210789. }
  210790. bool CDDeviceHandle::readTOC (TOC* lpToc)
  210791. {
  210792. SRB_ExecSCSICmd s;
  210793. zerostruct (s);
  210794. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210795. s.SRB_HaID = info.ha;
  210796. s.SRB_Target = info.tgt;
  210797. s.SRB_Lun = info.lun;
  210798. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210799. s.SRB_BufLen = 0x324;
  210800. s.SRB_BufPointer = (BYTE*) lpToc;
  210801. s.SRB_SenseLen = 0x0E;
  210802. s.SRB_CDBLen = 0x0A;
  210803. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  210804. s.CDBByte[0] = 0x43;
  210805. s.CDBByte[1] = 0x00;
  210806. s.CDBByte[7] = 0x03;
  210807. s.CDBByte[8] = 0x24;
  210808. performScsiCommand (s.SRB_PostProc, s);
  210809. return (s.SRB_Status == SS_COMP);
  210810. }
  210811. void CDDeviceHandle::performScsiCommand (HANDLE event, SRB_ExecSCSICmd& s)
  210812. {
  210813. ResetEvent (event);
  210814. DWORD status = performScsiPassThroughCommand ((SRB_ExecSCSICmd*) &s, info.scsiDriveLetter, scsiHandle, true);
  210815. if (status == SS_PENDING)
  210816. WaitForSingleObject (event, 4000);
  210817. CloseHandle (event);
  210818. }
  210819. bool CDDeviceHandle::readAudio (CDReadBuffer& buffer, CDReadBuffer* overlapBuffer)
  210820. {
  210821. if (controller == 0)
  210822. {
  210823. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  210824. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  210825. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  210826. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  210827. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  210828. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  210829. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  210830. }
  210831. buffer.index = 0;
  210832. if (controller != 0 && controller->readAudio (buffer, overlapBuffer))
  210833. {
  210834. if (buffer.wantsIndex)
  210835. buffer.index = controller->getLastIndex();
  210836. return true;
  210837. }
  210838. return false;
  210839. }
  210840. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  210841. {
  210842. if (shouldBeOpen)
  210843. {
  210844. if (controller != 0)
  210845. {
  210846. controller->shutDown();
  210847. controller = 0;
  210848. }
  210849. if (scsiHandle != 0)
  210850. {
  210851. CloseHandle (scsiHandle);
  210852. scsiHandle = 0;
  210853. }
  210854. }
  210855. SRB_ExecSCSICmd s;
  210856. zerostruct (s);
  210857. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210858. s.SRB_HaID = info.ha;
  210859. s.SRB_Target = info.tgt;
  210860. s.SRB_Lun = info.lun;
  210861. s.SRB_SenseLen = SENSE_LEN;
  210862. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210863. s.SRB_BufLen = 0;
  210864. s.SRB_BufPointer = 0;
  210865. s.SRB_CDBLen = 12;
  210866. s.CDBByte[0] = 0x1b;
  210867. s.CDBByte[1] = (BYTE) (info.lun << 5);
  210868. s.CDBByte[4] = (BYTE) (shouldBeOpen ? 2 : 3);
  210869. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  210870. performScsiCommand (s.SRB_PostProc, s);
  210871. }
  210872. bool CDDeviceHandle::testController (const int type, CDController* const newController, CDReadBuffer& rb)
  210873. {
  210874. controller = newController;
  210875. readType = (BYTE) type;
  210876. controller->deviceInfo = this;
  210877. controller->framesToCheck = 1;
  210878. controller->framesOverlap = 3;
  210879. bool passed = false;
  210880. memset (rb.buffer, 0xcd, rb.bufferSize);
  210881. if (controller->read (rb))
  210882. {
  210883. passed = true;
  210884. int* p = (int*) (rb.buffer + rb.dataStartOffset);
  210885. int wrong = 0;
  210886. for (int i = rb.dataLength / 4; --i >= 0;)
  210887. {
  210888. if (*p++ == (int) 0xcdcdcdcd)
  210889. {
  210890. if (++wrong == 4)
  210891. {
  210892. passed = false;
  210893. break;
  210894. }
  210895. }
  210896. else
  210897. {
  210898. wrong = 0;
  210899. }
  210900. }
  210901. }
  210902. if (! passed)
  210903. {
  210904. controller->shutDown();
  210905. controller = 0;
  210906. }
  210907. return passed;
  210908. }
  210909. struct CDDeviceWrapper
  210910. {
  210911. CDDeviceWrapper (const CDDeviceDescription& device, HANDLE scsiHandle)
  210912. : deviceHandle (device, scsiHandle), overlapBuffer (3), jitter (false)
  210913. {
  210914. // xxx jitter never seemed to actually be enabled (??)
  210915. }
  210916. CDDeviceHandle deviceHandle;
  210917. CDReadBuffer overlapBuffer;
  210918. bool jitter;
  210919. };
  210920. int getAddressOfTrack (const TOCTRACK& t) throw()
  210921. {
  210922. return (((DWORD) t.addr[0]) << 24) + (((DWORD) t.addr[1]) << 16)
  210923. + (((DWORD) t.addr[2]) << 8) + ((DWORD) t.addr[3]);
  210924. }
  210925. const int samplesPerFrame = 44100 / 75;
  210926. const int bytesPerFrame = samplesPerFrame * 4;
  210927. const int framesPerIndexRead = 4;
  210928. }
  210929. const StringArray AudioCDReader::getAvailableCDNames()
  210930. {
  210931. using namespace CDReaderHelpers;
  210932. StringArray results;
  210933. Array<CDDeviceDescription> list;
  210934. findCDDevices (list);
  210935. for (int i = 0; i < list.size(); ++i)
  210936. {
  210937. String s;
  210938. if (list[i].scsiDriveLetter > 0)
  210939. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  210940. s << list[i].description;
  210941. results.add (s);
  210942. }
  210943. return results;
  210944. }
  210945. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  210946. {
  210947. using namespace CDReaderHelpers;
  210948. Array<CDDeviceDescription> list;
  210949. findCDDevices (list);
  210950. if (isPositiveAndBelow (deviceIndex, list.size()))
  210951. {
  210952. HANDLE h = createSCSIDeviceHandle (list [deviceIndex].scsiDriveLetter);
  210953. if (h != INVALID_HANDLE_VALUE)
  210954. return new AudioCDReader (new CDDeviceWrapper (list [deviceIndex], h));
  210955. }
  210956. return 0;
  210957. }
  210958. AudioCDReader::AudioCDReader (void* handle_)
  210959. : AudioFormatReader (0, "CD Audio"),
  210960. handle (handle_),
  210961. indexingEnabled (false),
  210962. lastIndex (0),
  210963. firstFrameInBuffer (0),
  210964. samplesInBuffer (0)
  210965. {
  210966. using namespace CDReaderHelpers;
  210967. jassert (handle_ != 0);
  210968. refreshTrackLengths();
  210969. sampleRate = 44100.0;
  210970. bitsPerSample = 16;
  210971. numChannels = 2;
  210972. usesFloatingPointData = false;
  210973. buffer.setSize (4 * bytesPerFrame, true);
  210974. }
  210975. AudioCDReader::~AudioCDReader()
  210976. {
  210977. using namespace CDReaderHelpers;
  210978. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  210979. delete device;
  210980. }
  210981. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  210982. int64 startSampleInFile, int numSamples)
  210983. {
  210984. using namespace CDReaderHelpers;
  210985. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  210986. bool ok = true;
  210987. while (numSamples > 0)
  210988. {
  210989. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  210990. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  210991. if (startSampleInFile >= bufferStartSample
  210992. && startSampleInFile < bufferEndSample)
  210993. {
  210994. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  210995. int* const l = destSamples[0] + startOffsetInDestBuffer;
  210996. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  210997. const short* src = (const short*) buffer.getData();
  210998. src += 2 * (startSampleInFile - bufferStartSample);
  210999. for (int i = 0; i < toDo; ++i)
  211000. {
  211001. l[i] = src [i << 1] << 16;
  211002. if (r != 0)
  211003. r[i] = src [(i << 1) + 1] << 16;
  211004. }
  211005. startOffsetInDestBuffer += toDo;
  211006. startSampleInFile += toDo;
  211007. numSamples -= toDo;
  211008. }
  211009. else
  211010. {
  211011. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  211012. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  211013. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  211014. {
  211015. device->overlapBuffer.dataLength = 0;
  211016. device->overlapBuffer.startFrame = 0;
  211017. device->overlapBuffer.numFrames = 0;
  211018. device->jitter = false;
  211019. }
  211020. firstFrameInBuffer = frameNeeded;
  211021. lastIndex = 0;
  211022. CDReadBuffer readBuffer (framesInBuffer + 4);
  211023. readBuffer.wantsIndex = indexingEnabled;
  211024. int i;
  211025. for (i = 5; --i >= 0;)
  211026. {
  211027. readBuffer.startFrame = frameNeeded;
  211028. readBuffer.numFrames = framesInBuffer;
  211029. if (device->deviceHandle.readAudio (readBuffer, device->jitter ? &device->overlapBuffer : 0))
  211030. break;
  211031. else
  211032. device->overlapBuffer.dataLength = 0;
  211033. }
  211034. if (i >= 0)
  211035. {
  211036. buffer.copyFrom (readBuffer.buffer + readBuffer.dataStartOffset, 0, readBuffer.dataLength);
  211037. samplesInBuffer = readBuffer.dataLength >> 2;
  211038. lastIndex = readBuffer.index;
  211039. }
  211040. else
  211041. {
  211042. int* l = destSamples[0] + startOffsetInDestBuffer;
  211043. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211044. while (--numSamples >= 0)
  211045. {
  211046. *l++ = 0;
  211047. if (r != 0)
  211048. *r++ = 0;
  211049. }
  211050. // sometimes the read fails for just the very last couple of blocks, so
  211051. // we'll ignore and errors in the last half-second of the disk..
  211052. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  211053. break;
  211054. }
  211055. }
  211056. }
  211057. return ok;
  211058. }
  211059. bool AudioCDReader::isCDStillPresent() const
  211060. {
  211061. using namespace CDReaderHelpers;
  211062. TOC toc;
  211063. zerostruct (toc);
  211064. return static_cast <CDDeviceWrapper*> (handle)->deviceHandle.readTOC (&toc);
  211065. }
  211066. void AudioCDReader::refreshTrackLengths()
  211067. {
  211068. using namespace CDReaderHelpers;
  211069. trackStartSamples.clear();
  211070. zeromem (audioTracks, sizeof (audioTracks));
  211071. TOC toc;
  211072. zerostruct (toc);
  211073. if (static_cast <CDDeviceWrapper*> (handle)->deviceHandle.readTOC (&toc))
  211074. {
  211075. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  211076. for (int i = 0; i <= numTracks; ++i)
  211077. {
  211078. trackStartSamples.add (samplesPerFrame * getAddressOfTrack (toc.tracks [i]));
  211079. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  211080. }
  211081. }
  211082. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  211083. }
  211084. bool AudioCDReader::isTrackAudio (int trackNum) const
  211085. {
  211086. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  211087. }
  211088. void AudioCDReader::enableIndexScanning (bool b)
  211089. {
  211090. indexingEnabled = b;
  211091. }
  211092. int AudioCDReader::getLastIndex() const
  211093. {
  211094. return lastIndex;
  211095. }
  211096. int AudioCDReader::getIndexAt (int samplePos)
  211097. {
  211098. using namespace CDReaderHelpers;
  211099. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211100. const int frameNeeded = samplePos / samplesPerFrame;
  211101. device->overlapBuffer.dataLength = 0;
  211102. device->overlapBuffer.startFrame = 0;
  211103. device->overlapBuffer.numFrames = 0;
  211104. device->jitter = false;
  211105. firstFrameInBuffer = 0;
  211106. lastIndex = 0;
  211107. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  211108. readBuffer.wantsIndex = true;
  211109. int i;
  211110. for (i = 5; --i >= 0;)
  211111. {
  211112. readBuffer.startFrame = frameNeeded;
  211113. readBuffer.numFrames = framesPerIndexRead;
  211114. if (device->deviceHandle.readAudio (readBuffer))
  211115. break;
  211116. }
  211117. if (i >= 0)
  211118. return readBuffer.index;
  211119. return -1;
  211120. }
  211121. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  211122. {
  211123. using namespace CDReaderHelpers;
  211124. Array <int> indexes;
  211125. const int trackStart = getPositionOfTrackStart (trackNumber);
  211126. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  211127. bool needToScan = true;
  211128. if (trackEnd - trackStart > 20 * 44100)
  211129. {
  211130. // check the end of the track for indexes before scanning the whole thing
  211131. needToScan = false;
  211132. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  211133. bool seenAnIndex = false;
  211134. while (pos <= trackEnd - samplesPerFrame)
  211135. {
  211136. const int index = getIndexAt (pos);
  211137. if (index == 0)
  211138. {
  211139. // lead-out, so skip back a bit if we've not found any indexes yet..
  211140. if (seenAnIndex)
  211141. break;
  211142. pos -= 44100 * 5;
  211143. if (pos < trackStart)
  211144. break;
  211145. }
  211146. else
  211147. {
  211148. if (index > 0)
  211149. seenAnIndex = true;
  211150. if (index > 1)
  211151. {
  211152. needToScan = true;
  211153. break;
  211154. }
  211155. pos += samplesPerFrame * framesPerIndexRead;
  211156. }
  211157. }
  211158. }
  211159. if (needToScan)
  211160. {
  211161. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211162. int pos = trackStart;
  211163. int last = -1;
  211164. while (pos < trackEnd - samplesPerFrame * 10)
  211165. {
  211166. const int frameNeeded = pos / samplesPerFrame;
  211167. device->overlapBuffer.dataLength = 0;
  211168. device->overlapBuffer.startFrame = 0;
  211169. device->overlapBuffer.numFrames = 0;
  211170. device->jitter = false;
  211171. firstFrameInBuffer = 0;
  211172. CDReadBuffer readBuffer (4);
  211173. readBuffer.wantsIndex = true;
  211174. int i;
  211175. for (i = 5; --i >= 0;)
  211176. {
  211177. readBuffer.startFrame = frameNeeded;
  211178. readBuffer.numFrames = framesPerIndexRead;
  211179. if (device->deviceHandle.readAudio (readBuffer))
  211180. break;
  211181. }
  211182. if (i < 0)
  211183. break;
  211184. if (readBuffer.index > last && readBuffer.index > 1)
  211185. {
  211186. last = readBuffer.index;
  211187. indexes.add (pos);
  211188. }
  211189. pos += samplesPerFrame * framesPerIndexRead;
  211190. }
  211191. indexes.removeValue (trackStart);
  211192. }
  211193. return indexes;
  211194. }
  211195. void AudioCDReader::ejectDisk()
  211196. {
  211197. using namespace CDReaderHelpers;
  211198. static_cast <CDDeviceWrapper*> (handle)->deviceHandle.openDrawer (true);
  211199. }
  211200. #endif
  211201. #if JUCE_USE_CDBURNER
  211202. namespace CDBurnerHelpers
  211203. {
  211204. IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  211205. {
  211206. CoInitialize (0);
  211207. IDiscMaster* dm;
  211208. IDiscRecorder* result = 0;
  211209. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  211210. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  211211. IID_IDiscMaster,
  211212. (void**) &dm)))
  211213. {
  211214. if (SUCCEEDED (dm->Open()))
  211215. {
  211216. IEnumDiscRecorders* drEnum = 0;
  211217. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  211218. {
  211219. IDiscRecorder* dr = 0;
  211220. DWORD dummy;
  211221. int index = 0;
  211222. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  211223. {
  211224. if (indexToOpen == index)
  211225. {
  211226. result = dr;
  211227. break;
  211228. }
  211229. else if (list != 0)
  211230. {
  211231. BSTR path;
  211232. if (SUCCEEDED (dr->GetPath (&path)))
  211233. list->add ((const WCHAR*) path);
  211234. }
  211235. ++index;
  211236. dr->Release();
  211237. }
  211238. drEnum->Release();
  211239. }
  211240. if (master == 0)
  211241. dm->Close();
  211242. }
  211243. if (master != 0)
  211244. *master = dm;
  211245. else
  211246. dm->Release();
  211247. }
  211248. return result;
  211249. }
  211250. }
  211251. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  211252. public Timer
  211253. {
  211254. public:
  211255. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  211256. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  211257. listener (0), progress (0), shouldCancel (false)
  211258. {
  211259. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  211260. jassert (SUCCEEDED (hr));
  211261. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  211262. //jassert (SUCCEEDED (hr));
  211263. lastState = getDiskState();
  211264. startTimer (2000);
  211265. }
  211266. ~Pimpl() {}
  211267. void releaseObjects()
  211268. {
  211269. discRecorder->Close();
  211270. if (redbook != 0)
  211271. redbook->Release();
  211272. discRecorder->Release();
  211273. discMaster->Release();
  211274. Release();
  211275. }
  211276. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  211277. {
  211278. if (listener != 0 && ! shouldCancel)
  211279. shouldCancel = listener->audioCDBurnProgress (progress);
  211280. *pbCancel = shouldCancel;
  211281. return S_OK;
  211282. }
  211283. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  211284. {
  211285. progress = nCompleted / (float) nTotal;
  211286. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  211287. return E_NOTIMPL;
  211288. }
  211289. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  211290. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  211291. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  211292. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211293. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211294. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211295. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211296. class ScopedDiscOpener
  211297. {
  211298. public:
  211299. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  211300. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  211301. private:
  211302. Pimpl& pimpl;
  211303. JUCE_DECLARE_NON_COPYABLE (ScopedDiscOpener);
  211304. };
  211305. DiskState getDiskState()
  211306. {
  211307. const ScopedDiscOpener opener (*this);
  211308. long type, flags;
  211309. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  211310. if (FAILED (hr))
  211311. return unknown;
  211312. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  211313. return writableDiskPresent;
  211314. if (type == 0)
  211315. return noDisc;
  211316. else
  211317. return readOnlyDiskPresent;
  211318. }
  211319. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  211320. {
  211321. ComSmartPtr<IPropertyStorage> prop;
  211322. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  211323. return defaultReturn;
  211324. PROPSPEC iPropSpec;
  211325. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211326. iPropSpec.lpwstr = name;
  211327. PROPVARIANT iPropVariant;
  211328. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  211329. ? defaultReturn : (int) iPropVariant.lVal;
  211330. }
  211331. bool setIntProperty (const LPOLESTR name, const int value) const
  211332. {
  211333. ComSmartPtr<IPropertyStorage> prop;
  211334. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  211335. return false;
  211336. PROPSPEC iPropSpec;
  211337. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211338. iPropSpec.lpwstr = name;
  211339. PROPVARIANT iPropVariant;
  211340. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  211341. return false;
  211342. iPropVariant.lVal = (long) value;
  211343. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  211344. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  211345. }
  211346. void timerCallback()
  211347. {
  211348. const DiskState state = getDiskState();
  211349. if (state != lastState)
  211350. {
  211351. lastState = state;
  211352. owner.sendChangeMessage();
  211353. }
  211354. }
  211355. AudioCDBurner& owner;
  211356. DiskState lastState;
  211357. IDiscMaster* discMaster;
  211358. IDiscRecorder* discRecorder;
  211359. IRedbookDiscMaster* redbook;
  211360. AudioCDBurner::BurnProgressListener* listener;
  211361. float progress;
  211362. bool shouldCancel;
  211363. };
  211364. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  211365. {
  211366. IDiscMaster* discMaster = 0;
  211367. IDiscRecorder* discRecorder = CDBurnerHelpers::enumCDBurners (0, deviceIndex, &discMaster);
  211368. if (discRecorder != 0)
  211369. pimpl = new Pimpl (*this, discMaster, discRecorder);
  211370. }
  211371. AudioCDBurner::~AudioCDBurner()
  211372. {
  211373. if (pimpl != 0)
  211374. pimpl.release()->releaseObjects();
  211375. }
  211376. const StringArray AudioCDBurner::findAvailableDevices()
  211377. {
  211378. StringArray devs;
  211379. CDBurnerHelpers::enumCDBurners (&devs, -1, 0);
  211380. return devs;
  211381. }
  211382. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  211383. {
  211384. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  211385. if (b->pimpl == 0)
  211386. b = 0;
  211387. return b.release();
  211388. }
  211389. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  211390. {
  211391. return pimpl->getDiskState();
  211392. }
  211393. bool AudioCDBurner::isDiskPresent() const
  211394. {
  211395. return getDiskState() == writableDiskPresent;
  211396. }
  211397. bool AudioCDBurner::openTray()
  211398. {
  211399. const Pimpl::ScopedDiscOpener opener (*pimpl);
  211400. return SUCCEEDED (pimpl->discRecorder->Eject());
  211401. }
  211402. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  211403. {
  211404. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  211405. DiskState oldState = getDiskState();
  211406. DiskState newState = oldState;
  211407. while (newState == oldState && Time::currentTimeMillis() < timeout)
  211408. {
  211409. newState = getDiskState();
  211410. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  211411. }
  211412. return newState;
  211413. }
  211414. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  211415. {
  211416. Array<int> results;
  211417. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  211418. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  211419. for (int i = 0; i < numElementsInArray (speeds); ++i)
  211420. if (speeds[i] <= maxSpeed)
  211421. results.add (speeds[i]);
  211422. results.addIfNotAlreadyThere (maxSpeed);
  211423. return results;
  211424. }
  211425. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  211426. {
  211427. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  211428. return false;
  211429. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  211430. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  211431. }
  211432. int AudioCDBurner::getNumAvailableAudioBlocks() const
  211433. {
  211434. long blocksFree = 0;
  211435. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  211436. return blocksFree;
  211437. }
  211438. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  211439. bool performFakeBurnForTesting, int writeSpeed)
  211440. {
  211441. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  211442. pimpl->listener = listener;
  211443. pimpl->progress = 0;
  211444. pimpl->shouldCancel = false;
  211445. UINT_PTR cookie;
  211446. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  211447. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  211448. ejectDiscAfterwards);
  211449. String error;
  211450. if (hr != S_OK)
  211451. {
  211452. const char* e = "Couldn't open or write to the CD device";
  211453. if (hr == IMAPI_E_USERABORT)
  211454. e = "User cancelled the write operation";
  211455. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  211456. e = "No Disk present";
  211457. error = e;
  211458. }
  211459. pimpl->discMaster->ProgressUnadvise (cookie);
  211460. pimpl->listener = 0;
  211461. return error;
  211462. }
  211463. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  211464. {
  211465. if (audioSource == 0)
  211466. return false;
  211467. ScopedPointer<AudioSource> source (audioSource);
  211468. long bytesPerBlock;
  211469. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  211470. const int samplesPerBlock = bytesPerBlock / 4;
  211471. bool ok = true;
  211472. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  211473. HeapBlock <byte> buffer (bytesPerBlock);
  211474. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  211475. int samplesDone = 0;
  211476. source->prepareToPlay (samplesPerBlock, 44100.0);
  211477. while (ok)
  211478. {
  211479. {
  211480. AudioSourceChannelInfo info;
  211481. info.buffer = &sourceBuffer;
  211482. info.numSamples = samplesPerBlock;
  211483. info.startSample = 0;
  211484. sourceBuffer.clear();
  211485. source->getNextAudioBlock (info);
  211486. }
  211487. zeromem (buffer, bytesPerBlock);
  211488. typedef AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian,
  211489. AudioData::Interleaved, AudioData::NonConst> CDSampleFormat;
  211490. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian,
  211491. AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat;
  211492. CDSampleFormat left (buffer, 2);
  211493. left.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (0)), samplesPerBlock);
  211494. CDSampleFormat right (buffer + 2, 2);
  211495. right.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (1)), samplesPerBlock);
  211496. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  211497. if (FAILED (hr))
  211498. ok = false;
  211499. samplesDone += samplesPerBlock;
  211500. if (samplesDone >= numSamples)
  211501. break;
  211502. }
  211503. hr = pimpl->redbook->CloseAudioTrack();
  211504. return ok && hr == S_OK;
  211505. }
  211506. #endif
  211507. #endif
  211508. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  211509. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  211510. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211511. // compiled on its own).
  211512. #if JUCE_INCLUDED_FILE
  211513. class MidiInCollector
  211514. {
  211515. public:
  211516. MidiInCollector (MidiInput* const input_,
  211517. MidiInputCallback& callback_)
  211518. : deviceHandle (0),
  211519. input (input_),
  211520. callback (callback_),
  211521. concatenator (4096),
  211522. isStarted (false),
  211523. startTime (0)
  211524. {
  211525. }
  211526. ~MidiInCollector()
  211527. {
  211528. stop();
  211529. if (deviceHandle != 0)
  211530. {
  211531. int count = 5;
  211532. while (--count >= 0)
  211533. {
  211534. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  211535. break;
  211536. Sleep (20);
  211537. }
  211538. }
  211539. }
  211540. void handleMessage (const uint32 message, const uint32 timeStamp)
  211541. {
  211542. if ((message & 0xff) >= 0x80 && isStarted)
  211543. {
  211544. concatenator.pushMidiData (&message, 3, convertTimeStamp (timeStamp), input, callback);
  211545. writeFinishedBlocks();
  211546. }
  211547. }
  211548. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  211549. {
  211550. if (isStarted)
  211551. {
  211552. concatenator.pushMidiData (hdr->lpData, hdr->dwBytesRecorded, convertTimeStamp (timeStamp), input, callback);
  211553. writeFinishedBlocks();
  211554. }
  211555. }
  211556. void start()
  211557. {
  211558. jassert (deviceHandle != 0);
  211559. if (deviceHandle != 0 && ! isStarted)
  211560. {
  211561. activeMidiCollectors.addIfNotAlreadyThere (this);
  211562. for (int i = 0; i < (int) numHeaders; ++i)
  211563. headers[i].write (deviceHandle);
  211564. startTime = Time::getMillisecondCounter();
  211565. MMRESULT res = midiInStart (deviceHandle);
  211566. if (res == MMSYSERR_NOERROR)
  211567. {
  211568. concatenator.reset();
  211569. isStarted = true;
  211570. }
  211571. else
  211572. {
  211573. unprepareAllHeaders();
  211574. }
  211575. }
  211576. }
  211577. void stop()
  211578. {
  211579. if (isStarted)
  211580. {
  211581. isStarted = false;
  211582. midiInReset (deviceHandle);
  211583. midiInStop (deviceHandle);
  211584. activeMidiCollectors.removeValue (this);
  211585. unprepareAllHeaders();
  211586. concatenator.reset();
  211587. }
  211588. }
  211589. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  211590. {
  211591. MidiInCollector* const collector = reinterpret_cast <MidiInCollector*> (dwInstance);
  211592. if (activeMidiCollectors.contains (collector))
  211593. {
  211594. if (uMsg == MIM_DATA)
  211595. collector->handleMessage ((uint32) midiMessage, (uint32) timeStamp);
  211596. else if (uMsg == MIM_LONGDATA)
  211597. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  211598. }
  211599. }
  211600. HMIDIIN deviceHandle;
  211601. private:
  211602. static Array <MidiInCollector*, CriticalSection> activeMidiCollectors;
  211603. MidiInput* input;
  211604. MidiInputCallback& callback;
  211605. MidiDataConcatenator concatenator;
  211606. bool volatile isStarted;
  211607. uint32 startTime;
  211608. class MidiHeader
  211609. {
  211610. public:
  211611. MidiHeader()
  211612. {
  211613. zerostruct (hdr);
  211614. hdr.lpData = data;
  211615. hdr.dwBufferLength = numElementsInArray (data);
  211616. }
  211617. void write (HMIDIIN deviceHandle)
  211618. {
  211619. hdr.dwBytesRecorded = 0;
  211620. MMRESULT res = midiInPrepareHeader (deviceHandle, &hdr, sizeof (hdr));
  211621. res = midiInAddBuffer (deviceHandle, &hdr, sizeof (hdr));
  211622. }
  211623. void writeIfFinished (HMIDIIN deviceHandle)
  211624. {
  211625. if ((hdr.dwFlags & WHDR_DONE) != 0)
  211626. {
  211627. MMRESULT res = midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr));
  211628. (void) res;
  211629. write (deviceHandle);
  211630. }
  211631. }
  211632. void unprepare (HMIDIIN deviceHandle)
  211633. {
  211634. if ((hdr.dwFlags & WHDR_DONE) != 0)
  211635. {
  211636. int c = 10;
  211637. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  211638. Thread::sleep (20);
  211639. jassert (c >= 0);
  211640. }
  211641. }
  211642. private:
  211643. MIDIHDR hdr;
  211644. char data [256];
  211645. JUCE_DECLARE_NON_COPYABLE (MidiHeader);
  211646. };
  211647. enum { numHeaders = 32 };
  211648. MidiHeader headers [numHeaders];
  211649. void writeFinishedBlocks()
  211650. {
  211651. for (int i = 0; i < (int) numHeaders; ++i)
  211652. headers[i].writeIfFinished (deviceHandle);
  211653. }
  211654. void unprepareAllHeaders()
  211655. {
  211656. for (int i = 0; i < (int) numHeaders; ++i)
  211657. headers[i].unprepare (deviceHandle);
  211658. }
  211659. double convertTimeStamp (uint32 timeStamp)
  211660. {
  211661. timeStamp += startTime;
  211662. const uint32 now = Time::getMillisecondCounter();
  211663. if (timeStamp > now)
  211664. {
  211665. if (timeStamp > now + 2)
  211666. --startTime;
  211667. timeStamp = now;
  211668. }
  211669. return timeStamp * 0.001;
  211670. }
  211671. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInCollector);
  211672. };
  211673. Array <MidiInCollector*, CriticalSection> MidiInCollector::activeMidiCollectors;
  211674. const StringArray MidiInput::getDevices()
  211675. {
  211676. StringArray s;
  211677. const int num = midiInGetNumDevs();
  211678. for (int i = 0; i < num; ++i)
  211679. {
  211680. MIDIINCAPS mc;
  211681. zerostruct (mc);
  211682. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211683. s.add (String (mc.szPname, sizeof (mc.szPname)));
  211684. }
  211685. return s;
  211686. }
  211687. int MidiInput::getDefaultDeviceIndex()
  211688. {
  211689. return 0;
  211690. }
  211691. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  211692. {
  211693. if (callback == 0)
  211694. return 0;
  211695. UINT deviceId = MIDI_MAPPER;
  211696. int n = 0;
  211697. String name;
  211698. const int num = midiInGetNumDevs();
  211699. for (int i = 0; i < num; ++i)
  211700. {
  211701. MIDIINCAPS mc;
  211702. zerostruct (mc);
  211703. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211704. {
  211705. if (index == n)
  211706. {
  211707. deviceId = i;
  211708. name = String (mc.szPname, numElementsInArray (mc.szPname));
  211709. break;
  211710. }
  211711. ++n;
  211712. }
  211713. }
  211714. ScopedPointer <MidiInput> in (new MidiInput (name));
  211715. ScopedPointer <MidiInCollector> collector (new MidiInCollector (in, *callback));
  211716. HMIDIIN h;
  211717. HRESULT err = midiInOpen (&h, deviceId,
  211718. (DWORD_PTR) &MidiInCollector::midiInCallback,
  211719. (DWORD_PTR) (MidiInCollector*) collector,
  211720. CALLBACK_FUNCTION);
  211721. if (err == MMSYSERR_NOERROR)
  211722. {
  211723. collector->deviceHandle = h;
  211724. in->internal = collector.release();
  211725. return in.release();
  211726. }
  211727. return 0;
  211728. }
  211729. MidiInput::MidiInput (const String& name_)
  211730. : name (name_),
  211731. internal (0)
  211732. {
  211733. }
  211734. MidiInput::~MidiInput()
  211735. {
  211736. delete static_cast <MidiInCollector*> (internal);
  211737. }
  211738. void MidiInput::start()
  211739. {
  211740. static_cast <MidiInCollector*> (internal)->start();
  211741. }
  211742. void MidiInput::stop()
  211743. {
  211744. static_cast <MidiInCollector*> (internal)->stop();
  211745. }
  211746. struct MidiOutHandle
  211747. {
  211748. int refCount;
  211749. UINT deviceId;
  211750. HMIDIOUT handle;
  211751. static Array<MidiOutHandle*> activeHandles;
  211752. private:
  211753. JUCE_LEAK_DETECTOR (MidiOutHandle);
  211754. };
  211755. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  211756. const StringArray MidiOutput::getDevices()
  211757. {
  211758. StringArray s;
  211759. const int num = midiOutGetNumDevs();
  211760. for (int i = 0; i < num; ++i)
  211761. {
  211762. MIDIOUTCAPS mc;
  211763. zerostruct (mc);
  211764. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211765. s.add (String (mc.szPname, sizeof (mc.szPname)));
  211766. }
  211767. return s;
  211768. }
  211769. int MidiOutput::getDefaultDeviceIndex()
  211770. {
  211771. const int num = midiOutGetNumDevs();
  211772. int n = 0;
  211773. for (int i = 0; i < num; ++i)
  211774. {
  211775. MIDIOUTCAPS mc;
  211776. zerostruct (mc);
  211777. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211778. {
  211779. if ((mc.wTechnology & MOD_MAPPER) != 0)
  211780. return n;
  211781. ++n;
  211782. }
  211783. }
  211784. return 0;
  211785. }
  211786. MidiOutput* MidiOutput::openDevice (int index)
  211787. {
  211788. UINT deviceId = MIDI_MAPPER;
  211789. const int num = midiOutGetNumDevs();
  211790. int i, n = 0;
  211791. for (i = 0; i < num; ++i)
  211792. {
  211793. MIDIOUTCAPS mc;
  211794. zerostruct (mc);
  211795. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211796. {
  211797. // use the microsoft sw synth as a default - best not to allow deviceId
  211798. // to be MIDI_MAPPER, or else device sharing breaks
  211799. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  211800. deviceId = i;
  211801. if (index == n)
  211802. {
  211803. deviceId = i;
  211804. break;
  211805. }
  211806. ++n;
  211807. }
  211808. }
  211809. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  211810. {
  211811. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  211812. if (han != 0 && han->deviceId == deviceId)
  211813. {
  211814. han->refCount++;
  211815. MidiOutput* const out = new MidiOutput();
  211816. out->internal = han;
  211817. return out;
  211818. }
  211819. }
  211820. for (i = 4; --i >= 0;)
  211821. {
  211822. HMIDIOUT h = 0;
  211823. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  211824. if (res == MMSYSERR_NOERROR)
  211825. {
  211826. MidiOutHandle* const han = new MidiOutHandle();
  211827. han->deviceId = deviceId;
  211828. han->refCount = 1;
  211829. han->handle = h;
  211830. MidiOutHandle::activeHandles.add (han);
  211831. MidiOutput* const out = new MidiOutput();
  211832. out->internal = han;
  211833. return out;
  211834. }
  211835. else if (res == MMSYSERR_ALLOCATED)
  211836. {
  211837. Sleep (100);
  211838. }
  211839. else
  211840. {
  211841. break;
  211842. }
  211843. }
  211844. return 0;
  211845. }
  211846. MidiOutput::~MidiOutput()
  211847. {
  211848. stopBackgroundThread();
  211849. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  211850. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  211851. {
  211852. midiOutClose (h->handle);
  211853. MidiOutHandle::activeHandles.removeValue (h);
  211854. delete h;
  211855. }
  211856. }
  211857. void MidiOutput::reset()
  211858. {
  211859. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  211860. midiOutReset (h->handle);
  211861. }
  211862. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  211863. {
  211864. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  211865. DWORD n;
  211866. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  211867. {
  211868. const unsigned short* const nn = reinterpret_cast<const unsigned short*> (&n);
  211869. rightVol = nn[0] / (float) 0xffff;
  211870. leftVol = nn[1] / (float) 0xffff;
  211871. return true;
  211872. }
  211873. else
  211874. {
  211875. rightVol = leftVol = 1.0f;
  211876. return false;
  211877. }
  211878. }
  211879. void MidiOutput::setVolume (float leftVol, float rightVol)
  211880. {
  211881. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  211882. DWORD n;
  211883. unsigned short* const nn = reinterpret_cast<unsigned short*> (&n);
  211884. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  211885. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  211886. midiOutSetVolume (handle->handle, n);
  211887. }
  211888. void MidiOutput::sendMessageNow (const MidiMessage& message)
  211889. {
  211890. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  211891. if (message.getRawDataSize() > 3
  211892. || message.isSysEx())
  211893. {
  211894. MIDIHDR h;
  211895. zerostruct (h);
  211896. h.lpData = (char*) message.getRawData();
  211897. h.dwBufferLength = message.getRawDataSize();
  211898. h.dwBytesRecorded = message.getRawDataSize();
  211899. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  211900. {
  211901. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  211902. if (res == MMSYSERR_NOERROR)
  211903. {
  211904. while ((h.dwFlags & MHDR_DONE) == 0)
  211905. Sleep (1);
  211906. int count = 500; // 1 sec timeout
  211907. while (--count >= 0)
  211908. {
  211909. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  211910. if (res == MIDIERR_STILLPLAYING)
  211911. Sleep (2);
  211912. else
  211913. break;
  211914. }
  211915. }
  211916. }
  211917. }
  211918. else
  211919. {
  211920. midiOutShortMsg (handle->handle,
  211921. *(unsigned int*) message.getRawData());
  211922. }
  211923. }
  211924. #endif
  211925. /*** End of inlined file: juce_win32_Midi.cpp ***/
  211926. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  211927. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211928. // compiled on its own).
  211929. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  211930. #undef WINDOWS
  211931. // #define ASIO_DEBUGGING 1
  211932. #undef log
  211933. #if ASIO_DEBUGGING
  211934. #define log(a) { Logger::writeToLog (a); DBG (a) }
  211935. #else
  211936. #define log(a) {}
  211937. #endif
  211938. /* The ASIO SDK *should* declare its callback functions as being __cdecl, but different versions seem
  211939. to be pretty random about whether or not they do this. If you hit an error using these functions
  211940. it'll be because you're trying to build using __stdcall, in which case you'd need to either get hold of
  211941. an ASIO SDK which correctly specifies __cdecl, or add the __cdecl keyword to its functions yourself.
  211942. */
  211943. #define JUCE_ASIOCALLBACK __cdecl
  211944. namespace ASIODebugging
  211945. {
  211946. #if ASIO_DEBUGGING
  211947. static void log (const String& context, long error)
  211948. {
  211949. String err ("unknown error");
  211950. if (error == ASE_NotPresent) err = "Not Present";
  211951. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  211952. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  211953. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  211954. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  211955. else if (error == ASE_NoClock) err = "No Clock";
  211956. else if (error == ASE_NoMemory) err = "Out of memory";
  211957. log ("!!error: " + context + " - " + err);
  211958. }
  211959. #define logError(a, b) ASIODebugging::log ((a), (b))
  211960. #else
  211961. #define logError(a, b) {}
  211962. #endif
  211963. }
  211964. class ASIOAudioIODevice;
  211965. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  211966. static const int maxASIOChannels = 160;
  211967. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  211968. private Timer
  211969. {
  211970. public:
  211971. Component ourWindow;
  211972. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  211973. const String& optionalDllForDirectLoading_)
  211974. : AudioIODevice (name_, "ASIO"),
  211975. asioObject (0),
  211976. classId (classId_),
  211977. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  211978. currentBitDepth (16),
  211979. currentSampleRate (0),
  211980. isOpen_ (false),
  211981. isStarted (false),
  211982. postOutput (true),
  211983. insideControlPanelModalLoop (false),
  211984. shouldUsePreferredSize (false)
  211985. {
  211986. name = name_;
  211987. ourWindow.addToDesktop (0);
  211988. windowHandle = ourWindow.getWindowHandle();
  211989. jassert (currentASIODev [slotNumber] == 0);
  211990. currentASIODev [slotNumber] = this;
  211991. openDevice();
  211992. }
  211993. ~ASIOAudioIODevice()
  211994. {
  211995. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  211996. if (currentASIODev[i] == this)
  211997. currentASIODev[i] = 0;
  211998. close();
  211999. log ("ASIO - exiting");
  212000. removeCurrentDriver();
  212001. }
  212002. void updateSampleRates()
  212003. {
  212004. // find a list of sample rates..
  212005. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  212006. sampleRates.clear();
  212007. if (asioObject != 0)
  212008. {
  212009. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  212010. {
  212011. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  212012. if (err == 0)
  212013. {
  212014. sampleRates.add ((int) possibleSampleRates[index]);
  212015. log ("rate: " + String ((int) possibleSampleRates[index]));
  212016. }
  212017. else if (err != ASE_NoClock)
  212018. {
  212019. logError ("CanSampleRate", err);
  212020. }
  212021. }
  212022. if (sampleRates.size() == 0)
  212023. {
  212024. double cr = 0;
  212025. const long err = asioObject->getSampleRate (&cr);
  212026. log ("No sample rates supported - current rate: " + String ((int) cr));
  212027. if (err == 0)
  212028. sampleRates.add ((int) cr);
  212029. }
  212030. }
  212031. }
  212032. const StringArray getOutputChannelNames() { return outputChannelNames; }
  212033. const StringArray getInputChannelNames() { return inputChannelNames; }
  212034. int getNumSampleRates() { return sampleRates.size(); }
  212035. double getSampleRate (int index) { return sampleRates [index]; }
  212036. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  212037. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  212038. int getDefaultBufferSize() { return preferredSize; }
  212039. const String open (const BigInteger& inputChannels,
  212040. const BigInteger& outputChannels,
  212041. double sr,
  212042. int bufferSizeSamples)
  212043. {
  212044. close();
  212045. currentCallback = 0;
  212046. if (bufferSizeSamples <= 0)
  212047. shouldUsePreferredSize = true;
  212048. if (asioObject == 0 || ! isASIOOpen)
  212049. {
  212050. log ("Warning: device not open");
  212051. const String err (openDevice());
  212052. if (asioObject == 0 || ! isASIOOpen)
  212053. return err;
  212054. }
  212055. isStarted = false;
  212056. bufferIndex = -1;
  212057. long err = 0;
  212058. long newPreferredSize = 0;
  212059. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  212060. minSize = 0;
  212061. maxSize = 0;
  212062. newPreferredSize = 0;
  212063. granularity = 0;
  212064. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  212065. {
  212066. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  212067. shouldUsePreferredSize = true;
  212068. preferredSize = newPreferredSize;
  212069. }
  212070. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  212071. // dynamic changes to the buffer size...
  212072. shouldUsePreferredSize = shouldUsePreferredSize
  212073. || getName().containsIgnoreCase ("Digidesign");
  212074. if (shouldUsePreferredSize)
  212075. {
  212076. log ("Using preferred size for buffer..");
  212077. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212078. {
  212079. bufferSizeSamples = preferredSize;
  212080. }
  212081. else
  212082. {
  212083. bufferSizeSamples = 1024;
  212084. logError ("GetBufferSize1", err);
  212085. }
  212086. shouldUsePreferredSize = false;
  212087. }
  212088. int sampleRate = roundDoubleToInt (sr);
  212089. currentSampleRate = sampleRate;
  212090. currentBlockSizeSamples = bufferSizeSamples;
  212091. currentChansOut.clear();
  212092. currentChansIn.clear();
  212093. zeromem (inBuffers, sizeof (inBuffers));
  212094. zeromem (outBuffers, sizeof (outBuffers));
  212095. updateSampleRates();
  212096. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  212097. sampleRate = sampleRates[0];
  212098. jassert (sampleRate != 0);
  212099. if (sampleRate == 0)
  212100. sampleRate = 44100;
  212101. long numSources = 32;
  212102. ASIOClockSource clocks[32];
  212103. zeromem (clocks, sizeof (clocks));
  212104. asioObject->getClockSources (clocks, &numSources);
  212105. bool isSourceSet = false;
  212106. // careful not to remove this loop because it does more than just logging!
  212107. int i;
  212108. for (i = 0; i < numSources; ++i)
  212109. {
  212110. String s ("clock: ");
  212111. s += clocks[i].name;
  212112. if (clocks[i].isCurrentSource)
  212113. {
  212114. isSourceSet = true;
  212115. s << " (cur)";
  212116. }
  212117. log (s);
  212118. }
  212119. if (numSources > 1 && ! isSourceSet)
  212120. {
  212121. log ("setting clock source");
  212122. asioObject->setClockSource (clocks[0].index);
  212123. Thread::sleep (20);
  212124. }
  212125. else
  212126. {
  212127. if (numSources == 0)
  212128. {
  212129. log ("ASIO - no clock sources!");
  212130. }
  212131. }
  212132. double cr = 0;
  212133. err = asioObject->getSampleRate (&cr);
  212134. if (err == 0)
  212135. {
  212136. currentSampleRate = cr;
  212137. }
  212138. else
  212139. {
  212140. logError ("GetSampleRate", err);
  212141. currentSampleRate = 0;
  212142. }
  212143. error = String::empty;
  212144. needToReset = false;
  212145. isReSync = false;
  212146. err = 0;
  212147. bool buffersCreated = false;
  212148. if (currentSampleRate != sampleRate)
  212149. {
  212150. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  212151. err = asioObject->setSampleRate (sampleRate);
  212152. if (err == ASE_NoClock && numSources > 0)
  212153. {
  212154. log ("trying to set a clock source..");
  212155. Thread::sleep (10);
  212156. err = asioObject->setClockSource (clocks[0].index);
  212157. if (err != 0)
  212158. {
  212159. logError ("SetClock", err);
  212160. }
  212161. Thread::sleep (10);
  212162. err = asioObject->setSampleRate (sampleRate);
  212163. }
  212164. }
  212165. if (err == 0)
  212166. {
  212167. currentSampleRate = sampleRate;
  212168. if (needToReset)
  212169. {
  212170. if (isReSync)
  212171. {
  212172. log ("Resync request");
  212173. }
  212174. log ("! Resetting ASIO after sample rate change");
  212175. removeCurrentDriver();
  212176. loadDriver();
  212177. const String error (initDriver());
  212178. if (error.isNotEmpty())
  212179. {
  212180. log ("ASIOInit: " + error);
  212181. }
  212182. needToReset = false;
  212183. isReSync = false;
  212184. }
  212185. numActiveInputChans = 0;
  212186. numActiveOutputChans = 0;
  212187. ASIOBufferInfo* info = bufferInfos;
  212188. int i;
  212189. for (i = 0; i < totalNumInputChans; ++i)
  212190. {
  212191. if (inputChannels[i])
  212192. {
  212193. currentChansIn.setBit (i);
  212194. info->isInput = 1;
  212195. info->channelNum = i;
  212196. info->buffers[0] = info->buffers[1] = 0;
  212197. ++info;
  212198. ++numActiveInputChans;
  212199. }
  212200. }
  212201. for (i = 0; i < totalNumOutputChans; ++i)
  212202. {
  212203. if (outputChannels[i])
  212204. {
  212205. currentChansOut.setBit (i);
  212206. info->isInput = 0;
  212207. info->channelNum = i;
  212208. info->buffers[0] = info->buffers[1] = 0;
  212209. ++info;
  212210. ++numActiveOutputChans;
  212211. }
  212212. }
  212213. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  212214. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212215. if (currentASIODev[0] == this)
  212216. {
  212217. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212218. callbacks.asioMessage = &asioMessagesCallback0;
  212219. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212220. }
  212221. else if (currentASIODev[1] == this)
  212222. {
  212223. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212224. callbacks.asioMessage = &asioMessagesCallback1;
  212225. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212226. }
  212227. else if (currentASIODev[2] == this)
  212228. {
  212229. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212230. callbacks.asioMessage = &asioMessagesCallback2;
  212231. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212232. }
  212233. else
  212234. {
  212235. jassertfalse;
  212236. }
  212237. log ("disposing buffers");
  212238. err = asioObject->disposeBuffers();
  212239. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  212240. err = asioObject->createBuffers (bufferInfos,
  212241. totalBuffers,
  212242. currentBlockSizeSamples,
  212243. &callbacks);
  212244. if (err != 0)
  212245. {
  212246. currentBlockSizeSamples = preferredSize;
  212247. logError ("create buffers 2", err);
  212248. asioObject->disposeBuffers();
  212249. err = asioObject->createBuffers (bufferInfos,
  212250. totalBuffers,
  212251. currentBlockSizeSamples,
  212252. &callbacks);
  212253. }
  212254. if (err == 0)
  212255. {
  212256. buffersCreated = true;
  212257. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  212258. int n = 0;
  212259. Array <int> types;
  212260. currentBitDepth = 16;
  212261. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  212262. {
  212263. if (inputChannels[i])
  212264. {
  212265. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  212266. ASIOChannelInfo channelInfo;
  212267. zerostruct (channelInfo);
  212268. channelInfo.channel = i;
  212269. channelInfo.isInput = 1;
  212270. asioObject->getChannelInfo (&channelInfo);
  212271. types.addIfNotAlreadyThere (channelInfo.type);
  212272. typeToFormatParameters (channelInfo.type,
  212273. inputChannelBitDepths[n],
  212274. inputChannelBytesPerSample[n],
  212275. inputChannelIsFloat[n],
  212276. inputChannelLittleEndian[n]);
  212277. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  212278. ++n;
  212279. }
  212280. }
  212281. jassert (numActiveInputChans == n);
  212282. n = 0;
  212283. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  212284. {
  212285. if (outputChannels[i])
  212286. {
  212287. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  212288. ASIOChannelInfo channelInfo;
  212289. zerostruct (channelInfo);
  212290. channelInfo.channel = i;
  212291. channelInfo.isInput = 0;
  212292. asioObject->getChannelInfo (&channelInfo);
  212293. types.addIfNotAlreadyThere (channelInfo.type);
  212294. typeToFormatParameters (channelInfo.type,
  212295. outputChannelBitDepths[n],
  212296. outputChannelBytesPerSample[n],
  212297. outputChannelIsFloat[n],
  212298. outputChannelLittleEndian[n]);
  212299. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  212300. ++n;
  212301. }
  212302. }
  212303. jassert (numActiveOutputChans == n);
  212304. for (i = types.size(); --i >= 0;)
  212305. {
  212306. log ("channel format: " + String (types[i]));
  212307. }
  212308. jassert (n <= totalBuffers);
  212309. for (i = 0; i < numActiveOutputChans; ++i)
  212310. {
  212311. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  212312. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  212313. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  212314. {
  212315. log ("!! Null buffers");
  212316. }
  212317. else
  212318. {
  212319. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  212320. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  212321. }
  212322. }
  212323. inputLatency = outputLatency = 0;
  212324. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  212325. {
  212326. log ("ASIO - no latencies");
  212327. }
  212328. else
  212329. {
  212330. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  212331. }
  212332. isOpen_ = true;
  212333. log ("starting ASIO");
  212334. calledback = false;
  212335. err = asioObject->start();
  212336. if (err != 0)
  212337. {
  212338. isOpen_ = false;
  212339. log ("ASIO - stop on failure");
  212340. Thread::sleep (10);
  212341. asioObject->stop();
  212342. error = "Can't start device";
  212343. Thread::sleep (10);
  212344. }
  212345. else
  212346. {
  212347. int count = 300;
  212348. while (--count > 0 && ! calledback)
  212349. Thread::sleep (10);
  212350. isStarted = true;
  212351. if (! calledback)
  212352. {
  212353. error = "Device didn't start correctly";
  212354. log ("ASIO didn't callback - stopping..");
  212355. asioObject->stop();
  212356. }
  212357. }
  212358. }
  212359. else
  212360. {
  212361. error = "Can't create i/o buffers";
  212362. }
  212363. }
  212364. else
  212365. {
  212366. error = "Can't set sample rate: ";
  212367. error << sampleRate;
  212368. }
  212369. if (error.isNotEmpty())
  212370. {
  212371. logError (error, err);
  212372. if (asioObject != 0 && buffersCreated)
  212373. asioObject->disposeBuffers();
  212374. Thread::sleep (20);
  212375. isStarted = false;
  212376. isOpen_ = false;
  212377. const String errorCopy (error);
  212378. close(); // (this resets the error string)
  212379. error = errorCopy;
  212380. }
  212381. needToReset = false;
  212382. isReSync = false;
  212383. return error;
  212384. }
  212385. void close()
  212386. {
  212387. error = String::empty;
  212388. stopTimer();
  212389. stop();
  212390. if (isASIOOpen && isOpen_)
  212391. {
  212392. const ScopedLock sl (callbackLock);
  212393. isOpen_ = false;
  212394. isStarted = false;
  212395. needToReset = false;
  212396. isReSync = false;
  212397. log ("ASIO - stopping");
  212398. if (asioObject != 0)
  212399. {
  212400. Thread::sleep (20);
  212401. asioObject->stop();
  212402. Thread::sleep (10);
  212403. asioObject->disposeBuffers();
  212404. }
  212405. Thread::sleep (10);
  212406. }
  212407. }
  212408. bool isOpen() { return isOpen_ || insideControlPanelModalLoop; }
  212409. bool isPlaying() { return isASIOOpen && (currentCallback != 0); }
  212410. int getCurrentBufferSizeSamples() { return currentBlockSizeSamples; }
  212411. double getCurrentSampleRate() { return currentSampleRate; }
  212412. int getCurrentBitDepth() { return currentBitDepth; }
  212413. const BigInteger getActiveOutputChannels() const { return currentChansOut; }
  212414. const BigInteger getActiveInputChannels() const { return currentChansIn; }
  212415. int getOutputLatencyInSamples() { return outputLatency + currentBlockSizeSamples / 4; }
  212416. int getInputLatencyInSamples() { return inputLatency + currentBlockSizeSamples / 4; }
  212417. void start (AudioIODeviceCallback* callback)
  212418. {
  212419. if (callback != 0)
  212420. {
  212421. callback->audioDeviceAboutToStart (this);
  212422. const ScopedLock sl (callbackLock);
  212423. currentCallback = callback;
  212424. }
  212425. }
  212426. void stop()
  212427. {
  212428. AudioIODeviceCallback* const lastCallback = currentCallback;
  212429. {
  212430. const ScopedLock sl (callbackLock);
  212431. currentCallback = 0;
  212432. }
  212433. if (lastCallback != 0)
  212434. lastCallback->audioDeviceStopped();
  212435. }
  212436. const String getLastError() { return error; }
  212437. bool hasControlPanel() const { return true; }
  212438. bool showControlPanel()
  212439. {
  212440. log ("ASIO - showing control panel");
  212441. Component modalWindow (String::empty);
  212442. modalWindow.setOpaque (true);
  212443. modalWindow.addToDesktop (0);
  212444. modalWindow.enterModalState();
  212445. bool done = false;
  212446. JUCE_TRY
  212447. {
  212448. // are there are devices that need to be closed before showing their control panel?
  212449. // close();
  212450. insideControlPanelModalLoop = true;
  212451. const uint32 started = Time::getMillisecondCounter();
  212452. if (asioObject != 0)
  212453. {
  212454. asioObject->controlPanel();
  212455. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  212456. log ("spent: " + String (spent));
  212457. if (spent > 300)
  212458. {
  212459. shouldUsePreferredSize = true;
  212460. done = true;
  212461. }
  212462. }
  212463. }
  212464. JUCE_CATCH_ALL
  212465. insideControlPanelModalLoop = false;
  212466. return done;
  212467. }
  212468. void resetRequest() throw()
  212469. {
  212470. needToReset = true;
  212471. }
  212472. void resyncRequest() throw()
  212473. {
  212474. needToReset = true;
  212475. isReSync = true;
  212476. }
  212477. void timerCallback()
  212478. {
  212479. if (! insideControlPanelModalLoop)
  212480. {
  212481. stopTimer();
  212482. // used to cause a reset
  212483. log ("! ASIO restart request!");
  212484. if (isOpen_)
  212485. {
  212486. AudioIODeviceCallback* const oldCallback = currentCallback;
  212487. close();
  212488. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  212489. currentSampleRate, currentBlockSizeSamples);
  212490. if (oldCallback != 0)
  212491. start (oldCallback);
  212492. }
  212493. }
  212494. else
  212495. {
  212496. startTimer (100);
  212497. }
  212498. }
  212499. private:
  212500. IASIO* volatile asioObject;
  212501. ASIOCallbacks callbacks;
  212502. void* windowHandle;
  212503. CLSID classId;
  212504. const String optionalDllForDirectLoading;
  212505. String error;
  212506. long totalNumInputChans, totalNumOutputChans;
  212507. StringArray inputChannelNames, outputChannelNames;
  212508. Array<int> sampleRates, bufferSizes;
  212509. long inputLatency, outputLatency;
  212510. long minSize, maxSize, preferredSize, granularity;
  212511. int volatile currentBlockSizeSamples;
  212512. int volatile currentBitDepth;
  212513. double volatile currentSampleRate;
  212514. BigInteger currentChansOut, currentChansIn;
  212515. AudioIODeviceCallback* volatile currentCallback;
  212516. CriticalSection callbackLock;
  212517. ASIOBufferInfo bufferInfos [maxASIOChannels];
  212518. float* inBuffers [maxASIOChannels];
  212519. float* outBuffers [maxASIOChannels];
  212520. int inputChannelBitDepths [maxASIOChannels];
  212521. int outputChannelBitDepths [maxASIOChannels];
  212522. int inputChannelBytesPerSample [maxASIOChannels];
  212523. int outputChannelBytesPerSample [maxASIOChannels];
  212524. bool inputChannelIsFloat [maxASIOChannels];
  212525. bool outputChannelIsFloat [maxASIOChannels];
  212526. bool inputChannelLittleEndian [maxASIOChannels];
  212527. bool outputChannelLittleEndian [maxASIOChannels];
  212528. WaitableEvent event1;
  212529. HeapBlock <float> tempBuffer;
  212530. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  212531. bool isOpen_, isStarted;
  212532. bool volatile isASIOOpen;
  212533. bool volatile calledback;
  212534. bool volatile littleEndian, postOutput, needToReset, isReSync;
  212535. bool volatile insideControlPanelModalLoop;
  212536. bool volatile shouldUsePreferredSize;
  212537. void removeCurrentDriver()
  212538. {
  212539. if (asioObject != 0)
  212540. {
  212541. asioObject->Release();
  212542. asioObject = 0;
  212543. }
  212544. }
  212545. bool loadDriver()
  212546. {
  212547. removeCurrentDriver();
  212548. JUCE_TRY
  212549. {
  212550. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  212551. classId, (void**) &asioObject) == S_OK)
  212552. {
  212553. return true;
  212554. }
  212555. // If a class isn't registered but we have a path for it, we can fallback to
  212556. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  212557. if (optionalDllForDirectLoading.isNotEmpty())
  212558. {
  212559. HMODULE h = LoadLibrary (optionalDllForDirectLoading.toUTF16());
  212560. if (h != 0)
  212561. {
  212562. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  212563. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  212564. if (dllGetClassObject != 0)
  212565. {
  212566. IClassFactory* classFactory = 0;
  212567. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  212568. if (classFactory != 0)
  212569. {
  212570. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  212571. classFactory->Release();
  212572. }
  212573. return asioObject != 0;
  212574. }
  212575. }
  212576. }
  212577. }
  212578. JUCE_CATCH_ALL
  212579. asioObject = 0;
  212580. return false;
  212581. }
  212582. const String initDriver()
  212583. {
  212584. if (asioObject != 0)
  212585. {
  212586. char buffer [256];
  212587. zeromem (buffer, sizeof (buffer));
  212588. if (! asioObject->init (windowHandle))
  212589. {
  212590. asioObject->getErrorMessage (buffer);
  212591. return String (buffer, sizeof (buffer) - 1);
  212592. }
  212593. // just in case any daft drivers expect this to be called..
  212594. asioObject->getDriverName (buffer);
  212595. return String::empty;
  212596. }
  212597. return "No Driver";
  212598. }
  212599. const String openDevice()
  212600. {
  212601. // use this in case the driver starts opening dialog boxes..
  212602. Component modalWindow (String::empty);
  212603. modalWindow.setOpaque (true);
  212604. modalWindow.addToDesktop (0);
  212605. modalWindow.enterModalState();
  212606. // open the device and get its info..
  212607. log ("opening ASIO device: " + getName());
  212608. needToReset = false;
  212609. isReSync = false;
  212610. outputChannelNames.clear();
  212611. inputChannelNames.clear();
  212612. bufferSizes.clear();
  212613. sampleRates.clear();
  212614. isASIOOpen = false;
  212615. isOpen_ = false;
  212616. totalNumInputChans = 0;
  212617. totalNumOutputChans = 0;
  212618. numActiveInputChans = 0;
  212619. numActiveOutputChans = 0;
  212620. currentCallback = 0;
  212621. error = String::empty;
  212622. if (getName().isEmpty())
  212623. return error;
  212624. long err = 0;
  212625. if (loadDriver())
  212626. {
  212627. if ((error = initDriver()).isEmpty())
  212628. {
  212629. numActiveInputChans = 0;
  212630. numActiveOutputChans = 0;
  212631. totalNumInputChans = 0;
  212632. totalNumOutputChans = 0;
  212633. if (asioObject != 0
  212634. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  212635. {
  212636. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  212637. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212638. {
  212639. // find a list of buffer sizes..
  212640. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  212641. if (granularity >= 0)
  212642. {
  212643. granularity = jmax (1, (int) granularity);
  212644. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  212645. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  212646. }
  212647. else if (granularity < 0)
  212648. {
  212649. for (int i = 0; i < 18; ++i)
  212650. {
  212651. const int s = (1 << i);
  212652. if (s >= minSize && s <= maxSize)
  212653. bufferSizes.add (s);
  212654. }
  212655. }
  212656. if (! bufferSizes.contains (preferredSize))
  212657. bufferSizes.insert (0, preferredSize);
  212658. double currentRate = 0;
  212659. asioObject->getSampleRate (&currentRate);
  212660. if (currentRate <= 0.0 || currentRate > 192001.0)
  212661. {
  212662. log ("setting sample rate");
  212663. err = asioObject->setSampleRate (44100.0);
  212664. if (err != 0)
  212665. {
  212666. logError ("setting sample rate", err);
  212667. }
  212668. asioObject->getSampleRate (&currentRate);
  212669. }
  212670. currentSampleRate = currentRate;
  212671. postOutput = (asioObject->outputReady() == 0);
  212672. if (postOutput)
  212673. {
  212674. log ("ASIO outputReady = ok");
  212675. }
  212676. updateSampleRates();
  212677. // ..because cubase does it at this point
  212678. inputLatency = outputLatency = 0;
  212679. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  212680. {
  212681. log ("ASIO - no latencies");
  212682. }
  212683. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  212684. // create some dummy buffers now.. because cubase does..
  212685. numActiveInputChans = 0;
  212686. numActiveOutputChans = 0;
  212687. ASIOBufferInfo* info = bufferInfos;
  212688. int i, numChans = 0;
  212689. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  212690. {
  212691. info->isInput = 1;
  212692. info->channelNum = i;
  212693. info->buffers[0] = info->buffers[1] = 0;
  212694. ++info;
  212695. ++numChans;
  212696. }
  212697. const int outputBufferIndex = numChans;
  212698. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  212699. {
  212700. info->isInput = 0;
  212701. info->channelNum = i;
  212702. info->buffers[0] = info->buffers[1] = 0;
  212703. ++info;
  212704. ++numChans;
  212705. }
  212706. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212707. if (currentASIODev[0] == this)
  212708. {
  212709. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212710. callbacks.asioMessage = &asioMessagesCallback0;
  212711. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212712. }
  212713. else if (currentASIODev[1] == this)
  212714. {
  212715. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212716. callbacks.asioMessage = &asioMessagesCallback1;
  212717. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212718. }
  212719. else if (currentASIODev[2] == this)
  212720. {
  212721. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212722. callbacks.asioMessage = &asioMessagesCallback2;
  212723. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212724. }
  212725. else
  212726. {
  212727. jassertfalse;
  212728. }
  212729. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  212730. if (preferredSize > 0)
  212731. {
  212732. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  212733. if (err != 0)
  212734. {
  212735. logError ("dummy buffers", err);
  212736. }
  212737. }
  212738. long newInps = 0, newOuts = 0;
  212739. asioObject->getChannels (&newInps, &newOuts);
  212740. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  212741. {
  212742. totalNumInputChans = newInps;
  212743. totalNumOutputChans = newOuts;
  212744. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  212745. }
  212746. updateSampleRates();
  212747. ASIOChannelInfo channelInfo;
  212748. channelInfo.type = 0;
  212749. for (i = 0; i < totalNumInputChans; ++i)
  212750. {
  212751. zerostruct (channelInfo);
  212752. channelInfo.channel = i;
  212753. channelInfo.isInput = 1;
  212754. asioObject->getChannelInfo (&channelInfo);
  212755. inputChannelNames.add (String (channelInfo.name));
  212756. }
  212757. for (i = 0; i < totalNumOutputChans; ++i)
  212758. {
  212759. zerostruct (channelInfo);
  212760. channelInfo.channel = i;
  212761. channelInfo.isInput = 0;
  212762. asioObject->getChannelInfo (&channelInfo);
  212763. outputChannelNames.add (String (channelInfo.name));
  212764. typeToFormatParameters (channelInfo.type,
  212765. outputChannelBitDepths[i],
  212766. outputChannelBytesPerSample[i],
  212767. outputChannelIsFloat[i],
  212768. outputChannelLittleEndian[i]);
  212769. if (i < 2)
  212770. {
  212771. // clear the channels that are used with the dummy stuff
  212772. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  212773. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  212774. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  212775. }
  212776. }
  212777. outputChannelNames.trim();
  212778. inputChannelNames.trim();
  212779. outputChannelNames.appendNumbersToDuplicates (false, true);
  212780. inputChannelNames.appendNumbersToDuplicates (false, true);
  212781. // start and stop because cubase does it..
  212782. asioObject->getLatencies (&inputLatency, &outputLatency);
  212783. if ((err = asioObject->start()) != 0)
  212784. {
  212785. // ignore an error here, as it might start later after setting other stuff up
  212786. logError ("ASIO start", err);
  212787. }
  212788. Thread::sleep (100);
  212789. asioObject->stop();
  212790. }
  212791. else
  212792. {
  212793. error = "Can't detect buffer sizes";
  212794. }
  212795. }
  212796. else
  212797. {
  212798. error = "Can't detect asio channels";
  212799. }
  212800. }
  212801. }
  212802. else
  212803. {
  212804. error = "No such device";
  212805. }
  212806. if (error.isNotEmpty())
  212807. {
  212808. logError (error, err);
  212809. if (asioObject != 0)
  212810. asioObject->disposeBuffers();
  212811. removeCurrentDriver();
  212812. isASIOOpen = false;
  212813. }
  212814. else
  212815. {
  212816. isASIOOpen = true;
  212817. log ("ASIO device open");
  212818. }
  212819. isOpen_ = false;
  212820. needToReset = false;
  212821. isReSync = false;
  212822. return error;
  212823. }
  212824. void JUCE_ASIOCALLBACK callback (const long index)
  212825. {
  212826. if (isStarted)
  212827. {
  212828. bufferIndex = index;
  212829. processBuffer();
  212830. }
  212831. else
  212832. {
  212833. if (postOutput && (asioObject != 0))
  212834. asioObject->outputReady();
  212835. }
  212836. calledback = true;
  212837. }
  212838. void processBuffer()
  212839. {
  212840. const ASIOBufferInfo* const infos = bufferInfos;
  212841. const int bi = bufferIndex;
  212842. const ScopedLock sl (callbackLock);
  212843. if (needToReset)
  212844. {
  212845. needToReset = false;
  212846. if (isReSync)
  212847. {
  212848. log ("! ASIO resync");
  212849. isReSync = false;
  212850. }
  212851. else
  212852. {
  212853. startTimer (20);
  212854. }
  212855. }
  212856. if (bi >= 0)
  212857. {
  212858. const int samps = currentBlockSizeSamples;
  212859. if (currentCallback != 0)
  212860. {
  212861. int i;
  212862. for (i = 0; i < numActiveInputChans; ++i)
  212863. {
  212864. float* const dst = inBuffers[i];
  212865. jassert (dst != 0);
  212866. const char* const src = (const char*) (infos[i].buffers[bi]);
  212867. if (inputChannelIsFloat[i])
  212868. {
  212869. memcpy (dst, src, samps * sizeof (float));
  212870. }
  212871. else
  212872. {
  212873. jassert (dst == tempBuffer + (samps * i));
  212874. switch (inputChannelBitDepths[i])
  212875. {
  212876. case 16:
  212877. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  212878. samps, inputChannelLittleEndian[i]);
  212879. break;
  212880. case 24:
  212881. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  212882. samps, inputChannelLittleEndian[i]);
  212883. break;
  212884. case 32:
  212885. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  212886. samps, inputChannelLittleEndian[i]);
  212887. break;
  212888. case 64:
  212889. jassertfalse;
  212890. break;
  212891. }
  212892. }
  212893. }
  212894. currentCallback->audioDeviceIOCallback ((const float**) inBuffers, numActiveInputChans,
  212895. outBuffers, numActiveOutputChans, samps);
  212896. for (i = 0; i < numActiveOutputChans; ++i)
  212897. {
  212898. float* const src = outBuffers[i];
  212899. jassert (src != 0);
  212900. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  212901. if (outputChannelIsFloat[i])
  212902. {
  212903. memcpy (dst, src, samps * sizeof (float));
  212904. }
  212905. else
  212906. {
  212907. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  212908. switch (outputChannelBitDepths[i])
  212909. {
  212910. case 16:
  212911. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  212912. samps, outputChannelLittleEndian[i]);
  212913. break;
  212914. case 24:
  212915. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  212916. samps, outputChannelLittleEndian[i]);
  212917. break;
  212918. case 32:
  212919. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  212920. samps, outputChannelLittleEndian[i]);
  212921. break;
  212922. case 64:
  212923. jassertfalse;
  212924. break;
  212925. }
  212926. }
  212927. }
  212928. }
  212929. else
  212930. {
  212931. for (int i = 0; i < numActiveOutputChans; ++i)
  212932. {
  212933. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  212934. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  212935. }
  212936. }
  212937. }
  212938. if (postOutput)
  212939. asioObject->outputReady();
  212940. }
  212941. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  212942. {
  212943. if (currentASIODev[0] != 0)
  212944. currentASIODev[0]->callback (index);
  212945. return 0;
  212946. }
  212947. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  212948. {
  212949. if (currentASIODev[1] != 0)
  212950. currentASIODev[1]->callback (index);
  212951. return 0;
  212952. }
  212953. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  212954. {
  212955. if (currentASIODev[2] != 0)
  212956. currentASIODev[2]->callback (index);
  212957. return 0;
  212958. }
  212959. static void JUCE_ASIOCALLBACK bufferSwitchCallback0 (long index, long)
  212960. {
  212961. if (currentASIODev[0] != 0)
  212962. currentASIODev[0]->callback (index);
  212963. }
  212964. static void JUCE_ASIOCALLBACK bufferSwitchCallback1 (long index, long)
  212965. {
  212966. if (currentASIODev[1] != 0)
  212967. currentASIODev[1]->callback (index);
  212968. }
  212969. static void JUCE_ASIOCALLBACK bufferSwitchCallback2 (long index, long)
  212970. {
  212971. if (currentASIODev[2] != 0)
  212972. currentASIODev[2]->callback (index);
  212973. }
  212974. static long JUCE_ASIOCALLBACK asioMessagesCallback0 (long selector, long value, void*, double*)
  212975. {
  212976. return asioMessagesCallback (selector, value, 0);
  212977. }
  212978. static long JUCE_ASIOCALLBACK asioMessagesCallback1 (long selector, long value, void*, double*)
  212979. {
  212980. return asioMessagesCallback (selector, value, 1);
  212981. }
  212982. static long JUCE_ASIOCALLBACK asioMessagesCallback2 (long selector, long value, void*, double*)
  212983. {
  212984. return asioMessagesCallback (selector, value, 2);
  212985. }
  212986. static long JUCE_ASIOCALLBACK asioMessagesCallback (long selector, long value, const int deviceIndex)
  212987. {
  212988. switch (selector)
  212989. {
  212990. case kAsioSelectorSupported:
  212991. if (value == kAsioResetRequest
  212992. || value == kAsioEngineVersion
  212993. || value == kAsioResyncRequest
  212994. || value == kAsioLatenciesChanged
  212995. || value == kAsioSupportsInputMonitor)
  212996. return 1;
  212997. break;
  212998. case kAsioBufferSizeChange:
  212999. break;
  213000. case kAsioResetRequest:
  213001. if (currentASIODev[deviceIndex] != 0)
  213002. currentASIODev[deviceIndex]->resetRequest();
  213003. return 1;
  213004. case kAsioResyncRequest:
  213005. if (currentASIODev[deviceIndex] != 0)
  213006. currentASIODev[deviceIndex]->resyncRequest();
  213007. return 1;
  213008. case kAsioLatenciesChanged:
  213009. return 1;
  213010. case kAsioEngineVersion:
  213011. return 2;
  213012. case kAsioSupportsTimeInfo:
  213013. case kAsioSupportsTimeCode:
  213014. return 0;
  213015. }
  213016. return 0;
  213017. }
  213018. static void JUCE_ASIOCALLBACK sampleRateChangedCallback (ASIOSampleRate)
  213019. {
  213020. }
  213021. static void convertInt16ToFloat (const char* src,
  213022. float* dest,
  213023. const int srcStrideBytes,
  213024. int numSamples,
  213025. const bool littleEndian) throw()
  213026. {
  213027. const double g = 1.0 / 32768.0;
  213028. if (littleEndian)
  213029. {
  213030. while (--numSamples >= 0)
  213031. {
  213032. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  213033. src += srcStrideBytes;
  213034. }
  213035. }
  213036. else
  213037. {
  213038. while (--numSamples >= 0)
  213039. {
  213040. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  213041. src += srcStrideBytes;
  213042. }
  213043. }
  213044. }
  213045. static void convertFloatToInt16 (const float* src,
  213046. char* dest,
  213047. const int dstStrideBytes,
  213048. int numSamples,
  213049. const bool littleEndian) throw()
  213050. {
  213051. const double maxVal = (double) 0x7fff;
  213052. if (littleEndian)
  213053. {
  213054. while (--numSamples >= 0)
  213055. {
  213056. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213057. dest += dstStrideBytes;
  213058. }
  213059. }
  213060. else
  213061. {
  213062. while (--numSamples >= 0)
  213063. {
  213064. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213065. dest += dstStrideBytes;
  213066. }
  213067. }
  213068. }
  213069. static void convertInt24ToFloat (const char* src,
  213070. float* dest,
  213071. const int srcStrideBytes,
  213072. int numSamples,
  213073. const bool littleEndian) throw()
  213074. {
  213075. const double g = 1.0 / 0x7fffff;
  213076. if (littleEndian)
  213077. {
  213078. while (--numSamples >= 0)
  213079. {
  213080. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  213081. src += srcStrideBytes;
  213082. }
  213083. }
  213084. else
  213085. {
  213086. while (--numSamples >= 0)
  213087. {
  213088. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  213089. src += srcStrideBytes;
  213090. }
  213091. }
  213092. }
  213093. static void convertFloatToInt24 (const float* src,
  213094. char* dest,
  213095. const int dstStrideBytes,
  213096. int numSamples,
  213097. const bool littleEndian) throw()
  213098. {
  213099. const double maxVal = (double) 0x7fffff;
  213100. if (littleEndian)
  213101. {
  213102. while (--numSamples >= 0)
  213103. {
  213104. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213105. dest += dstStrideBytes;
  213106. }
  213107. }
  213108. else
  213109. {
  213110. while (--numSamples >= 0)
  213111. {
  213112. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213113. dest += dstStrideBytes;
  213114. }
  213115. }
  213116. }
  213117. static void convertInt32ToFloat (const char* src,
  213118. float* dest,
  213119. const int srcStrideBytes,
  213120. int numSamples,
  213121. const bool littleEndian) throw()
  213122. {
  213123. const double g = 1.0 / 0x7fffffff;
  213124. if (littleEndian)
  213125. {
  213126. while (--numSamples >= 0)
  213127. {
  213128. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  213129. src += srcStrideBytes;
  213130. }
  213131. }
  213132. else
  213133. {
  213134. while (--numSamples >= 0)
  213135. {
  213136. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  213137. src += srcStrideBytes;
  213138. }
  213139. }
  213140. }
  213141. static void convertFloatToInt32 (const float* src,
  213142. char* dest,
  213143. const int dstStrideBytes,
  213144. int numSamples,
  213145. const bool littleEndian) throw()
  213146. {
  213147. const double maxVal = (double) 0x7fffffff;
  213148. if (littleEndian)
  213149. {
  213150. while (--numSamples >= 0)
  213151. {
  213152. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213153. dest += dstStrideBytes;
  213154. }
  213155. }
  213156. else
  213157. {
  213158. while (--numSamples >= 0)
  213159. {
  213160. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213161. dest += dstStrideBytes;
  213162. }
  213163. }
  213164. }
  213165. static void typeToFormatParameters (const long type,
  213166. int& bitDepth,
  213167. int& byteStride,
  213168. bool& formatIsFloat,
  213169. bool& littleEndian) throw()
  213170. {
  213171. bitDepth = 0;
  213172. littleEndian = false;
  213173. formatIsFloat = false;
  213174. switch (type)
  213175. {
  213176. case ASIOSTInt16MSB:
  213177. case ASIOSTInt16LSB:
  213178. case ASIOSTInt32MSB16:
  213179. case ASIOSTInt32LSB16:
  213180. bitDepth = 16; break;
  213181. case ASIOSTFloat32MSB:
  213182. case ASIOSTFloat32LSB:
  213183. formatIsFloat = true;
  213184. bitDepth = 32; break;
  213185. case ASIOSTInt32MSB:
  213186. case ASIOSTInt32LSB:
  213187. bitDepth = 32; break;
  213188. case ASIOSTInt24MSB:
  213189. case ASIOSTInt24LSB:
  213190. case ASIOSTInt32MSB24:
  213191. case ASIOSTInt32LSB24:
  213192. case ASIOSTInt32MSB18:
  213193. case ASIOSTInt32MSB20:
  213194. case ASIOSTInt32LSB18:
  213195. case ASIOSTInt32LSB20:
  213196. bitDepth = 24; break;
  213197. case ASIOSTFloat64MSB:
  213198. case ASIOSTFloat64LSB:
  213199. default:
  213200. bitDepth = 64;
  213201. break;
  213202. }
  213203. switch (type)
  213204. {
  213205. case ASIOSTInt16MSB:
  213206. case ASIOSTInt32MSB16:
  213207. case ASIOSTFloat32MSB:
  213208. case ASIOSTFloat64MSB:
  213209. case ASIOSTInt32MSB:
  213210. case ASIOSTInt32MSB18:
  213211. case ASIOSTInt32MSB20:
  213212. case ASIOSTInt32MSB24:
  213213. case ASIOSTInt24MSB:
  213214. littleEndian = false; break;
  213215. case ASIOSTInt16LSB:
  213216. case ASIOSTInt32LSB16:
  213217. case ASIOSTFloat32LSB:
  213218. case ASIOSTFloat64LSB:
  213219. case ASIOSTInt32LSB:
  213220. case ASIOSTInt32LSB18:
  213221. case ASIOSTInt32LSB20:
  213222. case ASIOSTInt32LSB24:
  213223. case ASIOSTInt24LSB:
  213224. littleEndian = true; break;
  213225. default:
  213226. break;
  213227. }
  213228. switch (type)
  213229. {
  213230. case ASIOSTInt16LSB:
  213231. case ASIOSTInt16MSB:
  213232. byteStride = 2; break;
  213233. case ASIOSTInt24LSB:
  213234. case ASIOSTInt24MSB:
  213235. byteStride = 3; break;
  213236. case ASIOSTInt32MSB16:
  213237. case ASIOSTInt32LSB16:
  213238. case ASIOSTInt32MSB:
  213239. case ASIOSTInt32MSB18:
  213240. case ASIOSTInt32MSB20:
  213241. case ASIOSTInt32MSB24:
  213242. case ASIOSTInt32LSB:
  213243. case ASIOSTInt32LSB18:
  213244. case ASIOSTInt32LSB20:
  213245. case ASIOSTInt32LSB24:
  213246. case ASIOSTFloat32LSB:
  213247. case ASIOSTFloat32MSB:
  213248. byteStride = 4; break;
  213249. case ASIOSTFloat64MSB:
  213250. case ASIOSTFloat64LSB:
  213251. byteStride = 8; break;
  213252. default:
  213253. break;
  213254. }
  213255. }
  213256. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODevice);
  213257. };
  213258. class ASIOAudioIODeviceType : public AudioIODeviceType
  213259. {
  213260. public:
  213261. ASIOAudioIODeviceType()
  213262. : AudioIODeviceType ("ASIO"),
  213263. hasScanned (false)
  213264. {
  213265. CoInitialize (0);
  213266. }
  213267. ~ASIOAudioIODeviceType()
  213268. {
  213269. }
  213270. void scanForDevices()
  213271. {
  213272. hasScanned = true;
  213273. deviceNames.clear();
  213274. classIds.clear();
  213275. HKEY hk = 0;
  213276. int index = 0;
  213277. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  213278. {
  213279. for (;;)
  213280. {
  213281. char name [256];
  213282. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  213283. {
  213284. addDriverInfo (name, hk);
  213285. }
  213286. else
  213287. {
  213288. break;
  213289. }
  213290. }
  213291. RegCloseKey (hk);
  213292. }
  213293. }
  213294. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  213295. {
  213296. jassert (hasScanned); // need to call scanForDevices() before doing this
  213297. return deviceNames;
  213298. }
  213299. int getDefaultDeviceIndex (bool) const
  213300. {
  213301. jassert (hasScanned); // need to call scanForDevices() before doing this
  213302. for (int i = deviceNames.size(); --i >= 0;)
  213303. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  213304. return i; // asio4all is a safe choice for a default..
  213305. #if JUCE_DEBUG
  213306. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  213307. return 1; // (the digi m-box driver crashes the app when you run
  213308. // it in the debugger, which can be a bit annoying)
  213309. #endif
  213310. return 0;
  213311. }
  213312. static int findFreeSlot()
  213313. {
  213314. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  213315. if (currentASIODev[i] == 0)
  213316. return i;
  213317. jassertfalse; // unfortunately you can only have a finite number
  213318. // of ASIO devices open at the same time..
  213319. return -1;
  213320. }
  213321. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  213322. {
  213323. jassert (hasScanned); // need to call scanForDevices() before doing this
  213324. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  213325. }
  213326. bool hasSeparateInputsAndOutputs() const { return false; }
  213327. AudioIODevice* createDevice (const String& outputDeviceName,
  213328. const String& inputDeviceName)
  213329. {
  213330. // ASIO can't open two different devices for input and output - they must be the same one.
  213331. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  213332. jassert (hasScanned); // need to call scanForDevices() before doing this
  213333. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  213334. : inputDeviceName);
  213335. if (index >= 0)
  213336. {
  213337. const int freeSlot = findFreeSlot();
  213338. if (freeSlot >= 0)
  213339. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  213340. }
  213341. return 0;
  213342. }
  213343. private:
  213344. StringArray deviceNames;
  213345. OwnedArray <CLSID> classIds;
  213346. bool hasScanned;
  213347. static bool checkClassIsOk (const String& classId)
  213348. {
  213349. HKEY hk = 0;
  213350. bool ok = false;
  213351. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  213352. {
  213353. int index = 0;
  213354. for (;;)
  213355. {
  213356. WCHAR buf [512];
  213357. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  213358. {
  213359. if (classId.equalsIgnoreCase (buf))
  213360. {
  213361. HKEY subKey, pathKey;
  213362. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  213363. {
  213364. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  213365. {
  213366. WCHAR pathName [1024];
  213367. DWORD dtype = REG_SZ;
  213368. DWORD dsize = sizeof (pathName);
  213369. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  213370. ok = File (pathName).exists();
  213371. RegCloseKey (pathKey);
  213372. }
  213373. RegCloseKey (subKey);
  213374. }
  213375. break;
  213376. }
  213377. }
  213378. else
  213379. {
  213380. break;
  213381. }
  213382. }
  213383. RegCloseKey (hk);
  213384. }
  213385. return ok;
  213386. }
  213387. void addDriverInfo (const String& keyName, HKEY hk)
  213388. {
  213389. HKEY subKey;
  213390. if (RegOpenKeyEx (hk, keyName.toUTF16(), 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  213391. {
  213392. WCHAR buf [256];
  213393. zerostruct (buf);
  213394. DWORD dtype = REG_SZ;
  213395. DWORD dsize = sizeof (buf);
  213396. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  213397. {
  213398. if (dsize > 0 && checkClassIsOk (buf))
  213399. {
  213400. CLSID classId;
  213401. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  213402. {
  213403. dtype = REG_SZ;
  213404. dsize = sizeof (buf);
  213405. String deviceName;
  213406. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  213407. deviceName = buf;
  213408. else
  213409. deviceName = keyName;
  213410. log ("found " + deviceName);
  213411. deviceNames.add (deviceName);
  213412. classIds.add (new CLSID (classId));
  213413. }
  213414. }
  213415. RegCloseKey (subKey);
  213416. }
  213417. }
  213418. }
  213419. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODeviceType);
  213420. };
  213421. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  213422. {
  213423. return new ASIOAudioIODeviceType();
  213424. }
  213425. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  213426. void* guid,
  213427. const String& optionalDllForDirectLoading)
  213428. {
  213429. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  213430. if (freeSlot < 0)
  213431. return 0;
  213432. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  213433. }
  213434. #undef logError
  213435. #undef log
  213436. #endif
  213437. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  213438. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  213439. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  213440. // compiled on its own).
  213441. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  213442. END_JUCE_NAMESPACE
  213443. extern "C"
  213444. {
  213445. // Declare just the minimum number of interfaces for the DSound objects that we need..
  213446. typedef struct typeDSBUFFERDESC
  213447. {
  213448. DWORD dwSize;
  213449. DWORD dwFlags;
  213450. DWORD dwBufferBytes;
  213451. DWORD dwReserved;
  213452. LPWAVEFORMATEX lpwfxFormat;
  213453. GUID guid3DAlgorithm;
  213454. } DSBUFFERDESC;
  213455. struct IDirectSoundBuffer;
  213456. #undef INTERFACE
  213457. #define INTERFACE IDirectSound
  213458. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  213459. {
  213460. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213461. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213462. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213463. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  213464. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213465. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  213466. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  213467. STDMETHOD(Compact) (THIS) PURE;
  213468. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  213469. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  213470. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213471. };
  213472. #undef INTERFACE
  213473. #define INTERFACE IDirectSoundBuffer
  213474. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  213475. {
  213476. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213477. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213478. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213479. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213480. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  213481. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  213482. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  213483. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  213484. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  213485. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  213486. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  213487. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  213488. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  213489. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  213490. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  213491. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  213492. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  213493. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  213494. STDMETHOD(Stop) (THIS) PURE;
  213495. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  213496. STDMETHOD(Restore) (THIS) PURE;
  213497. };
  213498. typedef struct typeDSCBUFFERDESC
  213499. {
  213500. DWORD dwSize;
  213501. DWORD dwFlags;
  213502. DWORD dwBufferBytes;
  213503. DWORD dwReserved;
  213504. LPWAVEFORMATEX lpwfxFormat;
  213505. } DSCBUFFERDESC;
  213506. struct IDirectSoundCaptureBuffer;
  213507. #undef INTERFACE
  213508. #define INTERFACE IDirectSoundCapture
  213509. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  213510. {
  213511. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213512. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213513. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213514. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  213515. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213516. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213517. };
  213518. #undef INTERFACE
  213519. #define INTERFACE IDirectSoundCaptureBuffer
  213520. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  213521. {
  213522. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213523. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213524. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213525. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213526. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  213527. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  213528. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  213529. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  213530. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  213531. STDMETHOD(Start) (THIS_ DWORD) PURE;
  213532. STDMETHOD(Stop) (THIS) PURE;
  213533. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  213534. };
  213535. };
  213536. BEGIN_JUCE_NAMESPACE
  213537. namespace
  213538. {
  213539. const String getDSErrorMessage (HRESULT hr)
  213540. {
  213541. const char* result = 0;
  213542. switch (hr)
  213543. {
  213544. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  213545. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  213546. case E_INVALIDARG: result = "Invalid parameter"; break;
  213547. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  213548. case E_FAIL: result = "Generic error"; break;
  213549. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  213550. case E_OUTOFMEMORY: result = "Out of memory"; break;
  213551. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  213552. case E_NOTIMPL: result = "Unsupported function"; break;
  213553. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  213554. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  213555. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  213556. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  213557. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  213558. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  213559. case E_NOINTERFACE: result = "No interface"; break;
  213560. case S_OK: result = "No error"; break;
  213561. default: return "Unknown error: " + String ((int) hr);
  213562. }
  213563. return result;
  213564. }
  213565. #define DS_DEBUGGING 1
  213566. #ifdef DS_DEBUGGING
  213567. #define CATCH JUCE_CATCH_EXCEPTION
  213568. #undef log
  213569. #define log(a) Logger::writeToLog(a);
  213570. #undef logError
  213571. #define logError(a) logDSError(a, __LINE__);
  213572. static void logDSError (HRESULT hr, int lineNum)
  213573. {
  213574. if (hr != S_OK)
  213575. {
  213576. String error ("DS error at line ");
  213577. error << lineNum << " - " << getDSErrorMessage (hr);
  213578. log (error);
  213579. }
  213580. }
  213581. #else
  213582. #define CATCH JUCE_CATCH_ALL
  213583. #define log(a)
  213584. #define logError(a)
  213585. #endif
  213586. #define DSOUND_FUNCTION(functionName, params) \
  213587. typedef HRESULT (WINAPI *type##functionName) params; \
  213588. static type##functionName ds##functionName = 0;
  213589. #define DSOUND_FUNCTION_LOAD(functionName) \
  213590. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  213591. jassert (ds##functionName != 0);
  213592. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  213593. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  213594. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  213595. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  213596. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  213597. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  213598. void initialiseDSoundFunctions()
  213599. {
  213600. if (dsDirectSoundCreate == 0)
  213601. {
  213602. HMODULE h = LoadLibraryA ("dsound.dll");
  213603. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  213604. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  213605. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  213606. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  213607. }
  213608. }
  213609. }
  213610. class DSoundInternalOutChannel
  213611. {
  213612. public:
  213613. DSoundInternalOutChannel (const String& name_, LPGUID guid_, int rate,
  213614. int bufferSize, float* left, float* right)
  213615. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  213616. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  213617. pDirectSound (0), pOutputBuffer (0)
  213618. {
  213619. }
  213620. ~DSoundInternalOutChannel()
  213621. {
  213622. close();
  213623. }
  213624. void close()
  213625. {
  213626. HRESULT hr;
  213627. if (pOutputBuffer != 0)
  213628. {
  213629. log ("closing dsound out: " + name);
  213630. hr = pOutputBuffer->Stop();
  213631. logError (hr);
  213632. hr = pOutputBuffer->Release();
  213633. pOutputBuffer = 0;
  213634. logError (hr);
  213635. }
  213636. if (pDirectSound != 0)
  213637. {
  213638. hr = pDirectSound->Release();
  213639. pDirectSound = 0;
  213640. logError (hr);
  213641. }
  213642. }
  213643. const String open()
  213644. {
  213645. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  213646. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  213647. pDirectSound = 0;
  213648. pOutputBuffer = 0;
  213649. writeOffset = 0;
  213650. String error;
  213651. HRESULT hr = E_NOINTERFACE;
  213652. if (dsDirectSoundCreate != 0)
  213653. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  213654. if (hr == S_OK)
  213655. {
  213656. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213657. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213658. const int numChannels = 2;
  213659. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  213660. logError (hr);
  213661. if (hr == S_OK)
  213662. {
  213663. IDirectSoundBuffer* pPrimaryBuffer;
  213664. DSBUFFERDESC primaryDesc;
  213665. zerostruct (primaryDesc);
  213666. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  213667. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  213668. primaryDesc.dwBufferBytes = 0;
  213669. primaryDesc.lpwfxFormat = 0;
  213670. log ("opening dsound out step 2");
  213671. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  213672. logError (hr);
  213673. if (hr == S_OK)
  213674. {
  213675. WAVEFORMATEX wfFormat;
  213676. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213677. wfFormat.nChannels = (unsigned short) numChannels;
  213678. wfFormat.nSamplesPerSec = sampleRate;
  213679. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  213680. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  213681. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213682. wfFormat.cbSize = 0;
  213683. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  213684. logError (hr);
  213685. if (hr == S_OK)
  213686. {
  213687. DSBUFFERDESC secondaryDesc;
  213688. zerostruct (secondaryDesc);
  213689. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  213690. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  213691. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  213692. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  213693. secondaryDesc.lpwfxFormat = &wfFormat;
  213694. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  213695. logError (hr);
  213696. if (hr == S_OK)
  213697. {
  213698. log ("opening dsound out step 3");
  213699. DWORD dwDataLen;
  213700. unsigned char* pDSBuffData;
  213701. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  213702. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  213703. logError (hr);
  213704. if (hr == S_OK)
  213705. {
  213706. zeromem (pDSBuffData, dwDataLen);
  213707. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  213708. if (hr == S_OK)
  213709. {
  213710. hr = pOutputBuffer->SetCurrentPosition (0);
  213711. if (hr == S_OK)
  213712. {
  213713. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  213714. if (hr == S_OK)
  213715. return String::empty;
  213716. }
  213717. }
  213718. }
  213719. }
  213720. }
  213721. }
  213722. }
  213723. }
  213724. error = getDSErrorMessage (hr);
  213725. close();
  213726. return error;
  213727. }
  213728. void synchronisePosition()
  213729. {
  213730. if (pOutputBuffer != 0)
  213731. {
  213732. DWORD playCursor;
  213733. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  213734. }
  213735. }
  213736. bool service()
  213737. {
  213738. if (pOutputBuffer == 0)
  213739. return true;
  213740. DWORD playCursor, writeCursor;
  213741. for (;;)
  213742. {
  213743. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  213744. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213745. {
  213746. pOutputBuffer->Restore();
  213747. continue;
  213748. }
  213749. if (hr == S_OK)
  213750. break;
  213751. logError (hr);
  213752. jassertfalse;
  213753. return true;
  213754. }
  213755. int playWriteGap = writeCursor - playCursor;
  213756. if (playWriteGap < 0)
  213757. playWriteGap += totalBytesPerBuffer;
  213758. int bytesEmpty = playCursor - writeOffset;
  213759. if (bytesEmpty < 0)
  213760. bytesEmpty += totalBytesPerBuffer;
  213761. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  213762. {
  213763. writeOffset = writeCursor;
  213764. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  213765. }
  213766. if (bytesEmpty >= bytesPerBuffer)
  213767. {
  213768. void* lpbuf1 = 0;
  213769. void* lpbuf2 = 0;
  213770. DWORD dwSize1 = 0;
  213771. DWORD dwSize2 = 0;
  213772. HRESULT hr = pOutputBuffer->Lock (writeOffset, bytesPerBuffer,
  213773. &lpbuf1, &dwSize1,
  213774. &lpbuf2, &dwSize2, 0);
  213775. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213776. {
  213777. pOutputBuffer->Restore();
  213778. hr = pOutputBuffer->Lock (writeOffset, bytesPerBuffer,
  213779. &lpbuf1, &dwSize1,
  213780. &lpbuf2, &dwSize2, 0);
  213781. }
  213782. if (hr == S_OK)
  213783. {
  213784. if (bitDepth == 16)
  213785. {
  213786. int* dest = static_cast<int*> (lpbuf1);
  213787. const float* left = leftBuffer;
  213788. const float* right = rightBuffer;
  213789. int samples1 = dwSize1 >> 2;
  213790. int samples2 = dwSize2 >> 2;
  213791. if (left == 0)
  213792. {
  213793. while (--samples1 >= 0)
  213794. *dest++ = (convertInputValue (*right++) << 16);
  213795. dest = static_cast<int*> (lpbuf2);
  213796. while (--samples2 >= 0)
  213797. *dest++ = (convertInputValue (*right++) << 16);
  213798. }
  213799. else if (right == 0)
  213800. {
  213801. while (--samples1 >= 0)
  213802. *dest++ = (0xffff & convertInputValue (*left++));
  213803. dest = static_cast<int*> (lpbuf2);
  213804. while (--samples2 >= 0)
  213805. *dest++ = (0xffff & convertInputValue (*left++));
  213806. }
  213807. else
  213808. {
  213809. while (--samples1 >= 0)
  213810. {
  213811. const int l = convertInputValue (*left++);
  213812. const int r = convertInputValue (*right++);
  213813. *dest++ = (r << 16) | (0xffff & l);
  213814. }
  213815. dest = static_cast<int*> (lpbuf2);
  213816. while (--samples2 >= 0)
  213817. {
  213818. const int l = convertInputValue (*left++);
  213819. const int r = convertInputValue (*right++);
  213820. *dest++ = (r << 16) | (0xffff & l);
  213821. }
  213822. }
  213823. }
  213824. else
  213825. {
  213826. jassertfalse;
  213827. }
  213828. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  213829. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  213830. }
  213831. else
  213832. {
  213833. jassertfalse;
  213834. logError (hr);
  213835. }
  213836. bytesEmpty -= bytesPerBuffer;
  213837. return true;
  213838. }
  213839. else
  213840. {
  213841. return false;
  213842. }
  213843. }
  213844. int bitDepth;
  213845. bool doneFlag;
  213846. private:
  213847. String name;
  213848. LPGUID guid;
  213849. int sampleRate, bufferSizeSamples;
  213850. float* leftBuffer;
  213851. float* rightBuffer;
  213852. IDirectSound* pDirectSound;
  213853. IDirectSoundBuffer* pOutputBuffer;
  213854. DWORD writeOffset;
  213855. int totalBytesPerBuffer, bytesPerBuffer;
  213856. unsigned int lastPlayCursor;
  213857. static inline int convertInputValue (const float v) throw()
  213858. {
  213859. return jlimit (-32768, 32767, roundToInt (32767.0f * v));
  213860. }
  213861. JUCE_DECLARE_NON_COPYABLE (DSoundInternalOutChannel);
  213862. };
  213863. struct DSoundInternalInChannel
  213864. {
  213865. public:
  213866. DSoundInternalInChannel (const String& name_, LPGUID guid_, int rate,
  213867. int bufferSize, float* left, float* right)
  213868. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  213869. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  213870. pDirectSound (0), pDirectSoundCapture (0), pInputBuffer (0)
  213871. {
  213872. }
  213873. ~DSoundInternalInChannel()
  213874. {
  213875. close();
  213876. }
  213877. void close()
  213878. {
  213879. HRESULT hr;
  213880. if (pInputBuffer != 0)
  213881. {
  213882. log ("closing dsound in: " + name);
  213883. hr = pInputBuffer->Stop();
  213884. logError (hr);
  213885. hr = pInputBuffer->Release();
  213886. pInputBuffer = 0;
  213887. logError (hr);
  213888. }
  213889. if (pDirectSoundCapture != 0)
  213890. {
  213891. hr = pDirectSoundCapture->Release();
  213892. pDirectSoundCapture = 0;
  213893. logError (hr);
  213894. }
  213895. if (pDirectSound != 0)
  213896. {
  213897. hr = pDirectSound->Release();
  213898. pDirectSound = 0;
  213899. logError (hr);
  213900. }
  213901. }
  213902. const String open()
  213903. {
  213904. log ("opening dsound in device: " + name
  213905. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  213906. pDirectSound = 0;
  213907. pDirectSoundCapture = 0;
  213908. pInputBuffer = 0;
  213909. readOffset = 0;
  213910. totalBytesPerBuffer = 0;
  213911. String error;
  213912. HRESULT hr = E_NOINTERFACE;
  213913. if (dsDirectSoundCaptureCreate != 0)
  213914. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  213915. logError (hr);
  213916. if (hr == S_OK)
  213917. {
  213918. const int numChannels = 2;
  213919. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213920. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213921. WAVEFORMATEX wfFormat;
  213922. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213923. wfFormat.nChannels = (unsigned short)numChannels;
  213924. wfFormat.nSamplesPerSec = sampleRate;
  213925. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  213926. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  213927. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213928. wfFormat.cbSize = 0;
  213929. DSCBUFFERDESC captureDesc;
  213930. zerostruct (captureDesc);
  213931. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  213932. captureDesc.dwFlags = 0;
  213933. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  213934. captureDesc.lpwfxFormat = &wfFormat;
  213935. log ("opening dsound in step 2");
  213936. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  213937. logError (hr);
  213938. if (hr == S_OK)
  213939. {
  213940. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  213941. logError (hr);
  213942. if (hr == S_OK)
  213943. return String::empty;
  213944. }
  213945. }
  213946. error = getDSErrorMessage (hr);
  213947. close();
  213948. return error;
  213949. }
  213950. void synchronisePosition()
  213951. {
  213952. if (pInputBuffer != 0)
  213953. {
  213954. DWORD capturePos;
  213955. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  213956. }
  213957. }
  213958. bool service()
  213959. {
  213960. if (pInputBuffer == 0)
  213961. return true;
  213962. DWORD capturePos, readPos;
  213963. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  213964. logError (hr);
  213965. if (hr != S_OK)
  213966. return true;
  213967. int bytesFilled = readPos - readOffset;
  213968. if (bytesFilled < 0)
  213969. bytesFilled += totalBytesPerBuffer;
  213970. if (bytesFilled >= bytesPerBuffer)
  213971. {
  213972. LPBYTE lpbuf1 = 0;
  213973. LPBYTE lpbuf2 = 0;
  213974. DWORD dwsize1 = 0;
  213975. DWORD dwsize2 = 0;
  213976. HRESULT hr = pInputBuffer->Lock (readOffset, bytesPerBuffer,
  213977. (void**) &lpbuf1, &dwsize1,
  213978. (void**) &lpbuf2, &dwsize2, 0);
  213979. if (hr == S_OK)
  213980. {
  213981. if (bitDepth == 16)
  213982. {
  213983. const float g = 1.0f / 32768.0f;
  213984. float* destL = leftBuffer;
  213985. float* destR = rightBuffer;
  213986. int samples1 = dwsize1 >> 2;
  213987. int samples2 = dwsize2 >> 2;
  213988. const short* src = (const short*)lpbuf1;
  213989. if (destL == 0)
  213990. {
  213991. while (--samples1 >= 0)
  213992. {
  213993. ++src;
  213994. *destR++ = *src++ * g;
  213995. }
  213996. src = (const short*)lpbuf2;
  213997. while (--samples2 >= 0)
  213998. {
  213999. ++src;
  214000. *destR++ = *src++ * g;
  214001. }
  214002. }
  214003. else if (destR == 0)
  214004. {
  214005. while (--samples1 >= 0)
  214006. {
  214007. *destL++ = *src++ * g;
  214008. ++src;
  214009. }
  214010. src = (const short*)lpbuf2;
  214011. while (--samples2 >= 0)
  214012. {
  214013. *destL++ = *src++ * g;
  214014. ++src;
  214015. }
  214016. }
  214017. else
  214018. {
  214019. while (--samples1 >= 0)
  214020. {
  214021. *destL++ = *src++ * g;
  214022. *destR++ = *src++ * g;
  214023. }
  214024. src = (const short*)lpbuf2;
  214025. while (--samples2 >= 0)
  214026. {
  214027. *destL++ = *src++ * g;
  214028. *destR++ = *src++ * g;
  214029. }
  214030. }
  214031. }
  214032. else
  214033. {
  214034. jassertfalse;
  214035. }
  214036. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  214037. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  214038. }
  214039. else
  214040. {
  214041. logError (hr);
  214042. jassertfalse;
  214043. }
  214044. bytesFilled -= bytesPerBuffer;
  214045. return true;
  214046. }
  214047. else
  214048. {
  214049. return false;
  214050. }
  214051. }
  214052. unsigned int readOffset;
  214053. int bytesPerBuffer, totalBytesPerBuffer;
  214054. int bitDepth;
  214055. bool doneFlag;
  214056. private:
  214057. String name;
  214058. LPGUID guid;
  214059. int sampleRate, bufferSizeSamples;
  214060. float* leftBuffer;
  214061. float* rightBuffer;
  214062. IDirectSound* pDirectSound;
  214063. IDirectSoundCapture* pDirectSoundCapture;
  214064. IDirectSoundCaptureBuffer* pInputBuffer;
  214065. JUCE_DECLARE_NON_COPYABLE (DSoundInternalInChannel);
  214066. };
  214067. class DSoundAudioIODevice : public AudioIODevice,
  214068. public Thread
  214069. {
  214070. public:
  214071. DSoundAudioIODevice (const String& deviceName,
  214072. const int outputDeviceIndex_,
  214073. const int inputDeviceIndex_)
  214074. : AudioIODevice (deviceName, "DirectSound"),
  214075. Thread ("Juce DSound"),
  214076. outputDeviceIndex (outputDeviceIndex_),
  214077. inputDeviceIndex (inputDeviceIndex_),
  214078. isOpen_ (false),
  214079. isStarted (false),
  214080. bufferSizeSamples (0),
  214081. totalSamplesOut (0),
  214082. sampleRate (0.0),
  214083. inputBuffers (1, 1),
  214084. outputBuffers (1, 1),
  214085. callback (0)
  214086. {
  214087. if (outputDeviceIndex_ >= 0)
  214088. {
  214089. outChannels.add (TRANS("Left"));
  214090. outChannels.add (TRANS("Right"));
  214091. }
  214092. if (inputDeviceIndex_ >= 0)
  214093. {
  214094. inChannels.add (TRANS("Left"));
  214095. inChannels.add (TRANS("Right"));
  214096. }
  214097. }
  214098. ~DSoundAudioIODevice()
  214099. {
  214100. close();
  214101. }
  214102. const String open (const BigInteger& inputChannels,
  214103. const BigInteger& outputChannels,
  214104. double sampleRate, int bufferSizeSamples)
  214105. {
  214106. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  214107. isOpen_ = lastError.isEmpty();
  214108. return lastError;
  214109. }
  214110. void close()
  214111. {
  214112. stop();
  214113. if (isOpen_)
  214114. {
  214115. closeDevice();
  214116. isOpen_ = false;
  214117. }
  214118. }
  214119. bool isOpen() { return isOpen_ && isThreadRunning(); }
  214120. int getCurrentBufferSizeSamples() { return bufferSizeSamples; }
  214121. double getCurrentSampleRate() { return sampleRate; }
  214122. const BigInteger getActiveOutputChannels() const { return enabledOutputs; }
  214123. const BigInteger getActiveInputChannels() const { return enabledInputs; }
  214124. int getOutputLatencyInSamples() { return (int) (getCurrentBufferSizeSamples() * 1.5); }
  214125. int getInputLatencyInSamples() { return getOutputLatencyInSamples(); }
  214126. const StringArray getOutputChannelNames() { return outChannels; }
  214127. const StringArray getInputChannelNames() { return inChannels; }
  214128. int getNumSampleRates() { return 4; }
  214129. int getDefaultBufferSize() { return 2560; }
  214130. int getNumBufferSizesAvailable() { return 50; }
  214131. double getSampleRate (int index)
  214132. {
  214133. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214134. return samps [jlimit (0, 3, index)];
  214135. }
  214136. int getBufferSizeSamples (int index)
  214137. {
  214138. int n = 64;
  214139. for (int i = 0; i < index; ++i)
  214140. n += (n < 512) ? 32
  214141. : ((n < 1024) ? 64
  214142. : ((n < 2048) ? 128 : 256));
  214143. return n;
  214144. }
  214145. int getCurrentBitDepth()
  214146. {
  214147. int i, bits = 256;
  214148. for (i = inChans.size(); --i >= 0;)
  214149. bits = jmin (bits, inChans[i]->bitDepth);
  214150. for (i = outChans.size(); --i >= 0;)
  214151. bits = jmin (bits, outChans[i]->bitDepth);
  214152. if (bits > 32)
  214153. bits = 16;
  214154. return bits;
  214155. }
  214156. void start (AudioIODeviceCallback* call)
  214157. {
  214158. if (isOpen_ && call != 0 && ! isStarted)
  214159. {
  214160. if (! isThreadRunning())
  214161. {
  214162. // something gone wrong and the thread's stopped..
  214163. isOpen_ = false;
  214164. return;
  214165. }
  214166. call->audioDeviceAboutToStart (this);
  214167. const ScopedLock sl (startStopLock);
  214168. callback = call;
  214169. isStarted = true;
  214170. }
  214171. }
  214172. void stop()
  214173. {
  214174. if (isStarted)
  214175. {
  214176. AudioIODeviceCallback* const callbackLocal = callback;
  214177. {
  214178. const ScopedLock sl (startStopLock);
  214179. isStarted = false;
  214180. }
  214181. if (callbackLocal != 0)
  214182. callbackLocal->audioDeviceStopped();
  214183. }
  214184. }
  214185. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  214186. const String getLastError() { return lastError; }
  214187. StringArray inChannels, outChannels;
  214188. int outputDeviceIndex, inputDeviceIndex;
  214189. private:
  214190. bool isOpen_;
  214191. bool isStarted;
  214192. String lastError;
  214193. OwnedArray <DSoundInternalInChannel> inChans;
  214194. OwnedArray <DSoundInternalOutChannel> outChans;
  214195. WaitableEvent startEvent;
  214196. int bufferSizeSamples;
  214197. int volatile totalSamplesOut;
  214198. int64 volatile lastBlockTime;
  214199. double sampleRate;
  214200. BigInteger enabledInputs, enabledOutputs;
  214201. AudioSampleBuffer inputBuffers, outputBuffers;
  214202. AudioIODeviceCallback* callback;
  214203. CriticalSection startStopLock;
  214204. const String openDevice (const BigInteger& inputChannels,
  214205. const BigInteger& outputChannels,
  214206. double sampleRate_, int bufferSizeSamples_);
  214207. void closeDevice()
  214208. {
  214209. isStarted = false;
  214210. stopThread (5000);
  214211. inChans.clear();
  214212. outChans.clear();
  214213. inputBuffers.setSize (1, 1);
  214214. outputBuffers.setSize (1, 1);
  214215. }
  214216. void resync()
  214217. {
  214218. if (! threadShouldExit())
  214219. {
  214220. sleep (5);
  214221. int i;
  214222. for (i = 0; i < outChans.size(); ++i)
  214223. outChans.getUnchecked(i)->synchronisePosition();
  214224. for (i = 0; i < inChans.size(); ++i)
  214225. inChans.getUnchecked(i)->synchronisePosition();
  214226. }
  214227. }
  214228. public:
  214229. void run()
  214230. {
  214231. while (! threadShouldExit())
  214232. {
  214233. if (wait (100))
  214234. break;
  214235. }
  214236. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  214237. const int maxTimeMS = jmax (5, 3 * latencyMs);
  214238. while (! threadShouldExit())
  214239. {
  214240. int numToDo = 0;
  214241. uint32 startTime = Time::getMillisecondCounter();
  214242. int i;
  214243. for (i = inChans.size(); --i >= 0;)
  214244. {
  214245. inChans.getUnchecked(i)->doneFlag = false;
  214246. ++numToDo;
  214247. }
  214248. for (i = outChans.size(); --i >= 0;)
  214249. {
  214250. outChans.getUnchecked(i)->doneFlag = false;
  214251. ++numToDo;
  214252. }
  214253. if (numToDo > 0)
  214254. {
  214255. const int maxCount = 3;
  214256. int count = maxCount;
  214257. for (;;)
  214258. {
  214259. for (i = inChans.size(); --i >= 0;)
  214260. {
  214261. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  214262. if ((! in->doneFlag) && in->service())
  214263. {
  214264. in->doneFlag = true;
  214265. --numToDo;
  214266. }
  214267. }
  214268. for (i = outChans.size(); --i >= 0;)
  214269. {
  214270. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  214271. if ((! out->doneFlag) && out->service())
  214272. {
  214273. out->doneFlag = true;
  214274. --numToDo;
  214275. }
  214276. }
  214277. if (numToDo <= 0)
  214278. break;
  214279. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  214280. {
  214281. resync();
  214282. break;
  214283. }
  214284. if (--count <= 0)
  214285. {
  214286. Sleep (1);
  214287. count = maxCount;
  214288. }
  214289. if (threadShouldExit())
  214290. return;
  214291. }
  214292. }
  214293. else
  214294. {
  214295. sleep (1);
  214296. }
  214297. const ScopedLock sl (startStopLock);
  214298. if (isStarted)
  214299. {
  214300. JUCE_TRY
  214301. {
  214302. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  214303. inputBuffers.getNumChannels(),
  214304. outputBuffers.getArrayOfChannels(),
  214305. outputBuffers.getNumChannels(),
  214306. bufferSizeSamples);
  214307. }
  214308. JUCE_CATCH_EXCEPTION
  214309. totalSamplesOut += bufferSizeSamples;
  214310. }
  214311. else
  214312. {
  214313. outputBuffers.clear();
  214314. totalSamplesOut = 0;
  214315. sleep (1);
  214316. }
  214317. }
  214318. }
  214319. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODevice);
  214320. };
  214321. class DSoundAudioIODeviceType : public AudioIODeviceType
  214322. {
  214323. public:
  214324. DSoundAudioIODeviceType()
  214325. : AudioIODeviceType ("DirectSound"),
  214326. hasScanned (false)
  214327. {
  214328. initialiseDSoundFunctions();
  214329. }
  214330. void scanForDevices()
  214331. {
  214332. hasScanned = true;
  214333. outputDeviceNames.clear();
  214334. outputGuids.clear();
  214335. inputDeviceNames.clear();
  214336. inputGuids.clear();
  214337. if (dsDirectSoundEnumerateW != 0)
  214338. {
  214339. dsDirectSoundEnumerateW (outputEnumProcW, this);
  214340. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  214341. }
  214342. }
  214343. const StringArray getDeviceNames (bool wantInputNames) const
  214344. {
  214345. jassert (hasScanned); // need to call scanForDevices() before doing this
  214346. return wantInputNames ? inputDeviceNames
  214347. : outputDeviceNames;
  214348. }
  214349. int getDefaultDeviceIndex (bool /*forInput*/) const
  214350. {
  214351. jassert (hasScanned); // need to call scanForDevices() before doing this
  214352. return 0;
  214353. }
  214354. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  214355. {
  214356. jassert (hasScanned); // need to call scanForDevices() before doing this
  214357. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  214358. if (d == 0)
  214359. return -1;
  214360. return asInput ? d->inputDeviceIndex
  214361. : d->outputDeviceIndex;
  214362. }
  214363. bool hasSeparateInputsAndOutputs() const { return true; }
  214364. AudioIODevice* createDevice (const String& outputDeviceName,
  214365. const String& inputDeviceName)
  214366. {
  214367. jassert (hasScanned); // need to call scanForDevices() before doing this
  214368. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  214369. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  214370. if (outputIndex >= 0 || inputIndex >= 0)
  214371. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  214372. : inputDeviceName,
  214373. outputIndex, inputIndex);
  214374. return 0;
  214375. }
  214376. StringArray outputDeviceNames, inputDeviceNames;
  214377. OwnedArray <GUID> outputGuids, inputGuids;
  214378. private:
  214379. bool hasScanned;
  214380. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  214381. {
  214382. desc = desc.trim();
  214383. if (desc.isNotEmpty())
  214384. {
  214385. const String origDesc (desc);
  214386. int n = 2;
  214387. while (outputDeviceNames.contains (desc))
  214388. desc = origDesc + " (" + String (n++) + ")";
  214389. outputDeviceNames.add (desc);
  214390. if (lpGUID != 0)
  214391. outputGuids.add (new GUID (*lpGUID));
  214392. else
  214393. outputGuids.add (0);
  214394. }
  214395. return TRUE;
  214396. }
  214397. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214398. {
  214399. return ((DSoundAudioIODeviceType*) object)
  214400. ->outputEnumProc (lpGUID, String (description));
  214401. }
  214402. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214403. {
  214404. return ((DSoundAudioIODeviceType*) object)
  214405. ->outputEnumProc (lpGUID, String (description));
  214406. }
  214407. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  214408. {
  214409. desc = desc.trim();
  214410. if (desc.isNotEmpty())
  214411. {
  214412. const String origDesc (desc);
  214413. int n = 2;
  214414. while (inputDeviceNames.contains (desc))
  214415. desc = origDesc + " (" + String (n++) + ")";
  214416. inputDeviceNames.add (desc);
  214417. if (lpGUID != 0)
  214418. inputGuids.add (new GUID (*lpGUID));
  214419. else
  214420. inputGuids.add (0);
  214421. }
  214422. return TRUE;
  214423. }
  214424. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214425. {
  214426. return ((DSoundAudioIODeviceType*) object)
  214427. ->inputEnumProc (lpGUID, String (description));
  214428. }
  214429. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214430. {
  214431. return ((DSoundAudioIODeviceType*) object)
  214432. ->inputEnumProc (lpGUID, String (description));
  214433. }
  214434. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODeviceType);
  214435. };
  214436. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  214437. const BigInteger& outputChannels,
  214438. double sampleRate_, int bufferSizeSamples_)
  214439. {
  214440. closeDevice();
  214441. totalSamplesOut = 0;
  214442. sampleRate = sampleRate_;
  214443. if (bufferSizeSamples_ <= 0)
  214444. bufferSizeSamples_ = 960; // use as a default size if none is set.
  214445. bufferSizeSamples = bufferSizeSamples_ & ~7;
  214446. DSoundAudioIODeviceType dlh;
  214447. dlh.scanForDevices();
  214448. enabledInputs = inputChannels;
  214449. enabledInputs.setRange (inChannels.size(),
  214450. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  214451. false);
  214452. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  214453. inputBuffers.clear();
  214454. int i, numIns = 0;
  214455. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  214456. {
  214457. float* left = 0;
  214458. if (enabledInputs[i])
  214459. left = inputBuffers.getSampleData (numIns++);
  214460. float* right = 0;
  214461. if (enabledInputs[i + 1])
  214462. right = inputBuffers.getSampleData (numIns++);
  214463. if (left != 0 || right != 0)
  214464. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  214465. dlh.inputGuids [inputDeviceIndex],
  214466. (int) sampleRate, bufferSizeSamples,
  214467. left, right));
  214468. }
  214469. enabledOutputs = outputChannels;
  214470. enabledOutputs.setRange (outChannels.size(),
  214471. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  214472. false);
  214473. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  214474. outputBuffers.clear();
  214475. int numOuts = 0;
  214476. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  214477. {
  214478. float* left = 0;
  214479. if (enabledOutputs[i])
  214480. left = outputBuffers.getSampleData (numOuts++);
  214481. float* right = 0;
  214482. if (enabledOutputs[i + 1])
  214483. right = outputBuffers.getSampleData (numOuts++);
  214484. if (left != 0 || right != 0)
  214485. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  214486. dlh.outputGuids [outputDeviceIndex],
  214487. (int) sampleRate, bufferSizeSamples,
  214488. left, right));
  214489. }
  214490. String error;
  214491. // boost our priority while opening the devices to try to get better sync between them
  214492. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  214493. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  214494. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  214495. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  214496. for (i = 0; i < outChans.size(); ++i)
  214497. {
  214498. error = outChans[i]->open();
  214499. if (error.isNotEmpty())
  214500. {
  214501. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  214502. break;
  214503. }
  214504. }
  214505. if (error.isEmpty())
  214506. {
  214507. for (i = 0; i < inChans.size(); ++i)
  214508. {
  214509. error = inChans[i]->open();
  214510. if (error.isNotEmpty())
  214511. {
  214512. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  214513. break;
  214514. }
  214515. }
  214516. }
  214517. if (error.isEmpty())
  214518. {
  214519. totalSamplesOut = 0;
  214520. for (i = 0; i < outChans.size(); ++i)
  214521. outChans.getUnchecked(i)->synchronisePosition();
  214522. for (i = 0; i < inChans.size(); ++i)
  214523. inChans.getUnchecked(i)->synchronisePosition();
  214524. startThread (9);
  214525. sleep (10);
  214526. notify();
  214527. }
  214528. else
  214529. {
  214530. log (error);
  214531. }
  214532. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  214533. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  214534. return error;
  214535. }
  214536. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  214537. {
  214538. return new DSoundAudioIODeviceType();
  214539. }
  214540. #undef log
  214541. #endif
  214542. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  214543. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  214544. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214545. // compiled on its own).
  214546. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  214547. #ifndef WASAPI_ENABLE_LOGGING
  214548. #define WASAPI_ENABLE_LOGGING 0
  214549. #endif
  214550. namespace WasapiClasses
  214551. {
  214552. void logFailure (HRESULT hr)
  214553. {
  214554. (void) hr;
  214555. #if WASAPI_ENABLE_LOGGING
  214556. if (FAILED (hr))
  214557. {
  214558. String e;
  214559. e << Time::getCurrentTime().toString (true, true, true, true)
  214560. << " -- WASAPI error: ";
  214561. switch (hr)
  214562. {
  214563. case E_POINTER: e << "E_POINTER"; break;
  214564. case E_INVALIDARG: e << "E_INVALIDARG"; break;
  214565. case AUDCLNT_E_NOT_INITIALIZED: e << "AUDCLNT_E_NOT_INITIALIZED"; break;
  214566. case AUDCLNT_E_ALREADY_INITIALIZED: e << "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  214567. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e << "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  214568. case AUDCLNT_E_DEVICE_INVALIDATED: e << "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  214569. case AUDCLNT_E_NOT_STOPPED: e << "AUDCLNT_E_NOT_STOPPED"; break;
  214570. case AUDCLNT_E_BUFFER_TOO_LARGE: e << "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  214571. case AUDCLNT_E_OUT_OF_ORDER: e << "AUDCLNT_E_OUT_OF_ORDER"; break;
  214572. case AUDCLNT_E_UNSUPPORTED_FORMAT: e << "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  214573. case AUDCLNT_E_INVALID_SIZE: e << "AUDCLNT_E_INVALID_SIZE"; break;
  214574. case AUDCLNT_E_DEVICE_IN_USE: e << "AUDCLNT_E_DEVICE_IN_USE"; break;
  214575. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e << "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  214576. case AUDCLNT_E_THREAD_NOT_REGISTERED: e << "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  214577. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e << "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  214578. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e << "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  214579. case AUDCLNT_E_SERVICE_NOT_RUNNING: e << "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  214580. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e << "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  214581. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e << "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  214582. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e << "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  214583. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e << "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  214584. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e << "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  214585. case AUDCLNT_E_BUFFER_SIZE_ERROR: e << "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  214586. case AUDCLNT_S_BUFFER_EMPTY: e << "AUDCLNT_S_BUFFER_EMPTY"; break;
  214587. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e << "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  214588. default: e << String::toHexString ((int) hr); break;
  214589. }
  214590. DBG (e);
  214591. jassertfalse;
  214592. }
  214593. #endif
  214594. }
  214595. #undef check
  214596. bool check (HRESULT hr)
  214597. {
  214598. logFailure (hr);
  214599. return SUCCEEDED (hr);
  214600. }
  214601. const String getDeviceID (IMMDevice* const device)
  214602. {
  214603. String s;
  214604. WCHAR* deviceId = 0;
  214605. if (check (device->GetId (&deviceId)))
  214606. {
  214607. s = String (deviceId);
  214608. CoTaskMemFree (deviceId);
  214609. }
  214610. return s;
  214611. }
  214612. EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  214613. {
  214614. EDataFlow flow = eRender;
  214615. ComSmartPtr <IMMEndpoint> endPoint;
  214616. if (check (device.QueryInterface (__uuidof (IMMEndpoint), endPoint)))
  214617. (void) check (endPoint->GetDataFlow (&flow));
  214618. return flow;
  214619. }
  214620. int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  214621. {
  214622. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  214623. }
  214624. void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  214625. {
  214626. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  214627. : sizeof (WAVEFORMATEX));
  214628. }
  214629. class WASAPIDeviceBase
  214630. {
  214631. public:
  214632. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214633. : device (device_),
  214634. sampleRate (0),
  214635. defaultSampleRate (0),
  214636. numChannels (0),
  214637. actualNumChannels (0),
  214638. minBufferSize (0),
  214639. defaultBufferSize (0),
  214640. latencySamples (0),
  214641. useExclusiveMode (useExclusiveMode_)
  214642. {
  214643. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  214644. ComSmartPtr <IAudioClient> tempClient (createClient());
  214645. if (tempClient == 0)
  214646. return;
  214647. REFERENCE_TIME defaultPeriod, minPeriod;
  214648. if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  214649. return;
  214650. WAVEFORMATEX* mixFormat = 0;
  214651. if (! check (tempClient->GetMixFormat (&mixFormat)))
  214652. return;
  214653. WAVEFORMATEXTENSIBLE format;
  214654. copyWavFormat (format, mixFormat);
  214655. CoTaskMemFree (mixFormat);
  214656. actualNumChannels = numChannels = format.Format.nChannels;
  214657. defaultSampleRate = format.Format.nSamplesPerSec;
  214658. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  214659. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  214660. rates.addUsingDefaultSort (defaultSampleRate);
  214661. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214662. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  214663. {
  214664. if (ratesToTest[i] == defaultSampleRate)
  214665. continue;
  214666. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  214667. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214668. (WAVEFORMATEX*) &format, 0)))
  214669. if (! rates.contains (ratesToTest[i]))
  214670. rates.addUsingDefaultSort (ratesToTest[i]);
  214671. }
  214672. }
  214673. ~WASAPIDeviceBase()
  214674. {
  214675. device = 0;
  214676. CloseHandle (clientEvent);
  214677. }
  214678. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  214679. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  214680. {
  214681. sampleRate = newSampleRate;
  214682. channels = newChannels;
  214683. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  214684. numChannels = channels.getHighestBit() + 1;
  214685. if (numChannels == 0)
  214686. return true;
  214687. client = createClient();
  214688. if (client != 0
  214689. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  214690. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  214691. {
  214692. channelMaps.clear();
  214693. for (int i = 0; i <= channels.getHighestBit(); ++i)
  214694. if (channels[i])
  214695. channelMaps.add (i);
  214696. REFERENCE_TIME latency;
  214697. if (check (client->GetStreamLatency (&latency)))
  214698. latencySamples = refTimeToSamples (latency, sampleRate);
  214699. (void) check (client->GetBufferSize (&actualBufferSize));
  214700. return check (client->SetEventHandle (clientEvent));
  214701. }
  214702. return false;
  214703. }
  214704. void closeClient()
  214705. {
  214706. if (client != 0)
  214707. client->Stop();
  214708. client = 0;
  214709. ResetEvent (clientEvent);
  214710. }
  214711. ComSmartPtr <IMMDevice> device;
  214712. ComSmartPtr <IAudioClient> client;
  214713. double sampleRate, defaultSampleRate;
  214714. int numChannels, actualNumChannels;
  214715. int minBufferSize, defaultBufferSize, latencySamples;
  214716. const bool useExclusiveMode;
  214717. Array <double> rates;
  214718. HANDLE clientEvent;
  214719. BigInteger channels;
  214720. Array <int> channelMaps;
  214721. UINT32 actualBufferSize;
  214722. int bytesPerSample;
  214723. virtual void updateFormat (bool isFloat) = 0;
  214724. private:
  214725. const ComSmartPtr <IAudioClient> createClient()
  214726. {
  214727. ComSmartPtr <IAudioClient> client;
  214728. if (device != 0)
  214729. {
  214730. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) client.resetAndGetPointerAddress());
  214731. logFailure (hr);
  214732. }
  214733. return client;
  214734. }
  214735. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  214736. {
  214737. WAVEFORMATEXTENSIBLE format;
  214738. zerostruct (format);
  214739. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  214740. {
  214741. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  214742. }
  214743. else
  214744. {
  214745. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  214746. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  214747. }
  214748. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  214749. format.Format.nChannels = (WORD) numChannels;
  214750. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  214751. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  214752. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  214753. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  214754. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  214755. switch (numChannels)
  214756. {
  214757. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  214758. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  214759. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214760. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214761. 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;
  214762. default: break;
  214763. }
  214764. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  214765. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214766. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  214767. logFailure (hr);
  214768. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  214769. {
  214770. copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  214771. hr = S_OK;
  214772. }
  214773. CoTaskMemFree (nearestFormat);
  214774. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  214775. if (useExclusiveMode)
  214776. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  214777. GUID session;
  214778. if (hr == S_OK
  214779. && check (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214780. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  214781. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  214782. {
  214783. actualNumChannels = format.Format.nChannels;
  214784. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  214785. bytesPerSample = format.Format.wBitsPerSample / 8;
  214786. updateFormat (isFloat);
  214787. return true;
  214788. }
  214789. return false;
  214790. }
  214791. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIDeviceBase);
  214792. };
  214793. class WASAPIInputDevice : public WASAPIDeviceBase
  214794. {
  214795. public:
  214796. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214797. : WASAPIDeviceBase (device_, useExclusiveMode_),
  214798. reservoir (1, 1)
  214799. {
  214800. }
  214801. ~WASAPIInputDevice()
  214802. {
  214803. close();
  214804. }
  214805. bool open (const double newSampleRate, const BigInteger& newChannels)
  214806. {
  214807. reservoirSize = 0;
  214808. reservoirCapacity = 16384;
  214809. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  214810. return openClient (newSampleRate, newChannels)
  214811. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient),
  214812. (void**) captureClient.resetAndGetPointerAddress())));
  214813. }
  214814. void close()
  214815. {
  214816. closeClient();
  214817. captureClient = 0;
  214818. reservoir.setSize (0);
  214819. }
  214820. template <class SourceType>
  214821. void updateFormatWithType (SourceType*)
  214822. {
  214823. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> NativeType;
  214824. converter = new AudioData::ConverterInstance <AudioData::Pointer <SourceType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  214825. }
  214826. void updateFormat (bool isFloat)
  214827. {
  214828. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  214829. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  214830. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  214831. else updateFormatWithType ((AudioData::Int16*) 0);
  214832. }
  214833. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  214834. {
  214835. if (numChannels <= 0)
  214836. return;
  214837. int offset = 0;
  214838. while (bufferSize > 0)
  214839. {
  214840. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  214841. {
  214842. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  214843. for (int i = 0; i < numDestBuffers; ++i)
  214844. converter->convertSamples (destBuffers[i] + offset, 0, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo);
  214845. bufferSize -= samplesToDo;
  214846. offset += samplesToDo;
  214847. reservoirSize = 0;
  214848. }
  214849. else
  214850. {
  214851. UINT32 packetLength = 0;
  214852. if (! check (captureClient->GetNextPacketSize (&packetLength)))
  214853. break;
  214854. if (packetLength == 0)
  214855. {
  214856. if (thread.threadShouldExit()
  214857. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  214858. break;
  214859. continue;
  214860. }
  214861. uint8* inputData;
  214862. UINT32 numSamplesAvailable;
  214863. DWORD flags;
  214864. if (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  214865. {
  214866. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  214867. for (int i = 0; i < numDestBuffers; ++i)
  214868. converter->convertSamples (destBuffers[i] + offset, 0, inputData, channelMaps.getUnchecked(i), samplesToDo);
  214869. bufferSize -= samplesToDo;
  214870. offset += samplesToDo;
  214871. if (samplesToDo < (int) numSamplesAvailable)
  214872. {
  214873. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  214874. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  214875. bytesPerSample * actualNumChannels * reservoirSize);
  214876. }
  214877. captureClient->ReleaseBuffer (numSamplesAvailable);
  214878. }
  214879. }
  214880. }
  214881. }
  214882. ComSmartPtr <IAudioCaptureClient> captureClient;
  214883. MemoryBlock reservoir;
  214884. int reservoirSize, reservoirCapacity;
  214885. ScopedPointer <AudioData::Converter> converter;
  214886. private:
  214887. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIInputDevice);
  214888. };
  214889. class WASAPIOutputDevice : public WASAPIDeviceBase
  214890. {
  214891. public:
  214892. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214893. : WASAPIDeviceBase (device_, useExclusiveMode_)
  214894. {
  214895. }
  214896. ~WASAPIOutputDevice()
  214897. {
  214898. close();
  214899. }
  214900. bool open (const double newSampleRate, const BigInteger& newChannels)
  214901. {
  214902. return openClient (newSampleRate, newChannels)
  214903. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient), (void**) renderClient.resetAndGetPointerAddress())));
  214904. }
  214905. void close()
  214906. {
  214907. closeClient();
  214908. renderClient = 0;
  214909. }
  214910. template <class DestType>
  214911. void updateFormatWithType (DestType*)
  214912. {
  214913. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> NativeType;
  214914. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <DestType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  214915. }
  214916. void updateFormat (bool isFloat)
  214917. {
  214918. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  214919. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  214920. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  214921. else updateFormatWithType ((AudioData::Int16*) 0);
  214922. }
  214923. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  214924. {
  214925. if (numChannels <= 0)
  214926. return;
  214927. int offset = 0;
  214928. while (bufferSize > 0)
  214929. {
  214930. UINT32 padding = 0;
  214931. if (! check (client->GetCurrentPadding (&padding)))
  214932. return;
  214933. int samplesToDo = useExclusiveMode ? bufferSize
  214934. : jmin ((int) (actualBufferSize - padding), bufferSize);
  214935. if (samplesToDo <= 0)
  214936. {
  214937. if (thread.threadShouldExit()
  214938. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  214939. break;
  214940. continue;
  214941. }
  214942. uint8* outputData = 0;
  214943. if (check (renderClient->GetBuffer (samplesToDo, &outputData)))
  214944. {
  214945. for (int i = 0; i < numSrcBuffers; ++i)
  214946. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i] + offset, 0, samplesToDo);
  214947. renderClient->ReleaseBuffer (samplesToDo, 0);
  214948. offset += samplesToDo;
  214949. bufferSize -= samplesToDo;
  214950. }
  214951. }
  214952. }
  214953. ComSmartPtr <IAudioRenderClient> renderClient;
  214954. ScopedPointer <AudioData::Converter> converter;
  214955. private:
  214956. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIOutputDevice);
  214957. };
  214958. class WASAPIAudioIODevice : public AudioIODevice,
  214959. public Thread
  214960. {
  214961. public:
  214962. WASAPIAudioIODevice (const String& deviceName,
  214963. const String& outputDeviceId_,
  214964. const String& inputDeviceId_,
  214965. const bool useExclusiveMode_)
  214966. : AudioIODevice (deviceName, "Windows Audio"),
  214967. Thread ("Juce WASAPI"),
  214968. outputDeviceId (outputDeviceId_),
  214969. inputDeviceId (inputDeviceId_),
  214970. useExclusiveMode (useExclusiveMode_),
  214971. isOpen_ (false),
  214972. isStarted (false),
  214973. currentBufferSizeSamples (0),
  214974. currentSampleRate (0),
  214975. callback (0)
  214976. {
  214977. }
  214978. ~WASAPIAudioIODevice()
  214979. {
  214980. close();
  214981. }
  214982. bool initialise()
  214983. {
  214984. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  214985. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  214986. latencyIn = latencyOut = 0;
  214987. Array <double> ratesIn, ratesOut;
  214988. if (createDevices())
  214989. {
  214990. jassert (inputDevice != 0 || outputDevice != 0);
  214991. if (inputDevice != 0 && outputDevice != 0)
  214992. {
  214993. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  214994. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  214995. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  214996. sampleRates = inputDevice->rates;
  214997. sampleRates.removeValuesNotIn (outputDevice->rates);
  214998. }
  214999. else
  215000. {
  215001. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  215002. : static_cast<WASAPIDeviceBase*> (outputDevice);
  215003. defaultSampleRate = d->defaultSampleRate;
  215004. minBufferSize = d->minBufferSize;
  215005. defaultBufferSize = d->defaultBufferSize;
  215006. sampleRates = d->rates;
  215007. }
  215008. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  215009. if (minBufferSize != defaultBufferSize)
  215010. bufferSizes.addUsingDefaultSort (minBufferSize);
  215011. int n = 64;
  215012. for (int i = 0; i < 40; ++i)
  215013. {
  215014. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  215015. bufferSizes.addUsingDefaultSort (n);
  215016. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  215017. }
  215018. return true;
  215019. }
  215020. return false;
  215021. }
  215022. const StringArray getOutputChannelNames()
  215023. {
  215024. StringArray outChannels;
  215025. if (outputDevice != 0)
  215026. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  215027. outChannels.add ("Output channel " + String (i));
  215028. return outChannels;
  215029. }
  215030. const StringArray getInputChannelNames()
  215031. {
  215032. StringArray inChannels;
  215033. if (inputDevice != 0)
  215034. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  215035. inChannels.add ("Input channel " + String (i));
  215036. return inChannels;
  215037. }
  215038. int getNumSampleRates() { return sampleRates.size(); }
  215039. double getSampleRate (int index) { return sampleRates [index]; }
  215040. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  215041. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  215042. int getDefaultBufferSize() { return defaultBufferSize; }
  215043. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  215044. double getCurrentSampleRate() { return currentSampleRate; }
  215045. int getCurrentBitDepth() { return 32; }
  215046. int getOutputLatencyInSamples() { return latencyOut; }
  215047. int getInputLatencyInSamples() { return latencyIn; }
  215048. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  215049. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  215050. const String getLastError() { return lastError; }
  215051. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  215052. double sampleRate, int bufferSizeSamples)
  215053. {
  215054. close();
  215055. lastError = String::empty;
  215056. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  215057. {
  215058. lastError = "The input and output devices don't share a common sample rate!";
  215059. return lastError;
  215060. }
  215061. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  215062. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  215063. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  215064. {
  215065. lastError = "Couldn't open the input device!";
  215066. return lastError;
  215067. }
  215068. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  215069. {
  215070. close();
  215071. lastError = "Couldn't open the output device!";
  215072. return lastError;
  215073. }
  215074. if (inputDevice != 0) ResetEvent (inputDevice->clientEvent);
  215075. if (outputDevice != 0) ResetEvent (outputDevice->clientEvent);
  215076. startThread (8);
  215077. Thread::sleep (5);
  215078. if (inputDevice != 0 && inputDevice->client != 0)
  215079. {
  215080. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  215081. HRESULT hr = inputDevice->client->Start();
  215082. logFailure (hr); //xxx handle this
  215083. }
  215084. if (outputDevice != 0 && outputDevice->client != 0)
  215085. {
  215086. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  215087. HRESULT hr = outputDevice->client->Start();
  215088. logFailure (hr); //xxx handle this
  215089. }
  215090. isOpen_ = true;
  215091. return lastError;
  215092. }
  215093. void close()
  215094. {
  215095. stop();
  215096. signalThreadShouldExit();
  215097. if (inputDevice != 0) SetEvent (inputDevice->clientEvent);
  215098. if (outputDevice != 0) SetEvent (outputDevice->clientEvent);
  215099. stopThread (5000);
  215100. if (inputDevice != 0) inputDevice->close();
  215101. if (outputDevice != 0) outputDevice->close();
  215102. isOpen_ = false;
  215103. }
  215104. bool isOpen() { return isOpen_ && isThreadRunning(); }
  215105. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  215106. void start (AudioIODeviceCallback* call)
  215107. {
  215108. if (isOpen_ && call != 0 && ! isStarted)
  215109. {
  215110. if (! isThreadRunning())
  215111. {
  215112. // something's gone wrong and the thread's stopped..
  215113. isOpen_ = false;
  215114. return;
  215115. }
  215116. call->audioDeviceAboutToStart (this);
  215117. const ScopedLock sl (startStopLock);
  215118. callback = call;
  215119. isStarted = true;
  215120. }
  215121. }
  215122. void stop()
  215123. {
  215124. if (isStarted)
  215125. {
  215126. AudioIODeviceCallback* const callbackLocal = callback;
  215127. {
  215128. const ScopedLock sl (startStopLock);
  215129. isStarted = false;
  215130. }
  215131. if (callbackLocal != 0)
  215132. callbackLocal->audioDeviceStopped();
  215133. }
  215134. }
  215135. void setMMThreadPriority()
  215136. {
  215137. DynamicLibraryLoader dll ("avrt.dll");
  215138. DynamicLibraryImport (AvSetMmThreadCharacteristicsW, avSetMmThreadCharacteristics, HANDLE, dll, (LPCWSTR, LPDWORD))
  215139. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  215140. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  215141. {
  215142. DWORD dummy = 0;
  215143. HANDLE h = avSetMmThreadCharacteristics (L"Pro Audio", &dummy);
  215144. if (h != 0)
  215145. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  215146. }
  215147. }
  215148. void run()
  215149. {
  215150. setMMThreadPriority();
  215151. const int bufferSize = currentBufferSizeSamples;
  215152. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  215153. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  215154. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  215155. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  215156. float** const inputBuffers = ins.getArrayOfChannels();
  215157. float** const outputBuffers = outs.getArrayOfChannels();
  215158. ins.clear();
  215159. while (! threadShouldExit())
  215160. {
  215161. if (inputDevice != 0)
  215162. {
  215163. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  215164. if (threadShouldExit())
  215165. break;
  215166. }
  215167. JUCE_TRY
  215168. {
  215169. const ScopedLock sl (startStopLock);
  215170. if (isStarted)
  215171. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers), numInputBuffers,
  215172. outputBuffers, numOutputBuffers, bufferSize);
  215173. else
  215174. outs.clear();
  215175. }
  215176. JUCE_CATCH_EXCEPTION
  215177. if (outputDevice != 0)
  215178. outputDevice->copyBuffers (const_cast <const float**> (outputBuffers), numOutputBuffers, bufferSize, *this);
  215179. }
  215180. }
  215181. String outputDeviceId, inputDeviceId;
  215182. String lastError;
  215183. private:
  215184. // Device stats...
  215185. ScopedPointer<WASAPIInputDevice> inputDevice;
  215186. ScopedPointer<WASAPIOutputDevice> outputDevice;
  215187. const bool useExclusiveMode;
  215188. double defaultSampleRate;
  215189. int minBufferSize, defaultBufferSize;
  215190. int latencyIn, latencyOut;
  215191. Array <double> sampleRates;
  215192. Array <int> bufferSizes;
  215193. // Active state...
  215194. bool isOpen_, isStarted;
  215195. int currentBufferSizeSamples;
  215196. double currentSampleRate;
  215197. AudioIODeviceCallback* callback;
  215198. CriticalSection startStopLock;
  215199. bool createDevices()
  215200. {
  215201. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  215202. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  215203. return false;
  215204. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215205. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  215206. return false;
  215207. UINT32 numDevices = 0;
  215208. if (! check (deviceCollection->GetCount (&numDevices)))
  215209. return false;
  215210. for (UINT32 i = 0; i < numDevices; ++i)
  215211. {
  215212. ComSmartPtr <IMMDevice> device;
  215213. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  215214. continue;
  215215. const String deviceId (getDeviceID (device));
  215216. if (deviceId.isEmpty())
  215217. continue;
  215218. const EDataFlow flow = getDataFlow (device);
  215219. if (deviceId == inputDeviceId && flow == eCapture)
  215220. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  215221. else if (deviceId == outputDeviceId && flow == eRender)
  215222. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  215223. }
  215224. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  215225. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  215226. }
  215227. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODevice);
  215228. };
  215229. class WASAPIAudioIODeviceType : public AudioIODeviceType
  215230. {
  215231. public:
  215232. WASAPIAudioIODeviceType()
  215233. : AudioIODeviceType ("Windows Audio"),
  215234. hasScanned (false)
  215235. {
  215236. }
  215237. ~WASAPIAudioIODeviceType()
  215238. {
  215239. }
  215240. void scanForDevices()
  215241. {
  215242. hasScanned = true;
  215243. outputDeviceNames.clear();
  215244. inputDeviceNames.clear();
  215245. outputDeviceIds.clear();
  215246. inputDeviceIds.clear();
  215247. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  215248. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  215249. return;
  215250. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  215251. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  215252. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215253. UINT32 numDevices = 0;
  215254. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  215255. && check (deviceCollection->GetCount (&numDevices))))
  215256. return;
  215257. for (UINT32 i = 0; i < numDevices; ++i)
  215258. {
  215259. ComSmartPtr <IMMDevice> device;
  215260. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  215261. continue;
  215262. const String deviceId (getDeviceID (device));
  215263. DWORD state = 0;
  215264. if (! check (device->GetState (&state)))
  215265. continue;
  215266. if (state != DEVICE_STATE_ACTIVE)
  215267. continue;
  215268. String name;
  215269. {
  215270. ComSmartPtr <IPropertyStore> properties;
  215271. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  215272. continue;
  215273. PROPVARIANT value;
  215274. PropVariantInit (&value);
  215275. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  215276. name = value.pwszVal;
  215277. PropVariantClear (&value);
  215278. }
  215279. const EDataFlow flow = getDataFlow (device);
  215280. if (flow == eRender)
  215281. {
  215282. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  215283. outputDeviceIds.insert (index, deviceId);
  215284. outputDeviceNames.insert (index, name);
  215285. }
  215286. else if (flow == eCapture)
  215287. {
  215288. const int index = (deviceId == defaultCapture) ? 0 : -1;
  215289. inputDeviceIds.insert (index, deviceId);
  215290. inputDeviceNames.insert (index, name);
  215291. }
  215292. }
  215293. inputDeviceNames.appendNumbersToDuplicates (false, false);
  215294. outputDeviceNames.appendNumbersToDuplicates (false, false);
  215295. }
  215296. const StringArray getDeviceNames (bool wantInputNames) const
  215297. {
  215298. jassert (hasScanned); // need to call scanForDevices() before doing this
  215299. return wantInputNames ? inputDeviceNames
  215300. : outputDeviceNames;
  215301. }
  215302. int getDefaultDeviceIndex (bool /*forInput*/) const
  215303. {
  215304. jassert (hasScanned); // need to call scanForDevices() before doing this
  215305. return 0;
  215306. }
  215307. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215308. {
  215309. jassert (hasScanned); // need to call scanForDevices() before doing this
  215310. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  215311. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  215312. : outputDeviceIds.indexOf (d->outputDeviceId));
  215313. }
  215314. bool hasSeparateInputsAndOutputs() const { return true; }
  215315. AudioIODevice* createDevice (const String& outputDeviceName,
  215316. const String& inputDeviceName)
  215317. {
  215318. jassert (hasScanned); // need to call scanForDevices() before doing this
  215319. const bool useExclusiveMode = false;
  215320. ScopedPointer<WASAPIAudioIODevice> device;
  215321. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215322. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215323. if (outputIndex >= 0 || inputIndex >= 0)
  215324. {
  215325. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215326. : inputDeviceName,
  215327. outputDeviceIds [outputIndex],
  215328. inputDeviceIds [inputIndex],
  215329. useExclusiveMode);
  215330. if (! device->initialise())
  215331. device = 0;
  215332. }
  215333. return device.release();
  215334. }
  215335. StringArray outputDeviceNames, outputDeviceIds;
  215336. StringArray inputDeviceNames, inputDeviceIds;
  215337. private:
  215338. bool hasScanned;
  215339. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  215340. {
  215341. String s;
  215342. IMMDevice* dev = 0;
  215343. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  215344. eMultimedia, &dev)))
  215345. {
  215346. WCHAR* deviceId = 0;
  215347. if (check (dev->GetId (&deviceId)))
  215348. {
  215349. s = String (deviceId);
  215350. CoTaskMemFree (deviceId);
  215351. }
  215352. dev->Release();
  215353. }
  215354. return s;
  215355. }
  215356. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODeviceType);
  215357. };
  215358. }
  215359. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  215360. {
  215361. return new WasapiClasses::WASAPIAudioIODeviceType();
  215362. }
  215363. #endif
  215364. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  215365. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  215366. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215367. // compiled on its own).
  215368. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  215369. class DShowCameraDeviceInteral : public ChangeBroadcaster
  215370. {
  215371. public:
  215372. DShowCameraDeviceInteral (CameraDevice* const owner_,
  215373. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  215374. const ComSmartPtr <IBaseFilter>& filter_,
  215375. int minWidth, int minHeight,
  215376. int maxWidth, int maxHeight)
  215377. : owner (owner_),
  215378. captureGraphBuilder (captureGraphBuilder_),
  215379. filter (filter_),
  215380. ok (false),
  215381. imageNeedsFlipping (false),
  215382. width (0),
  215383. height (0),
  215384. activeUsers (0),
  215385. recordNextFrameTime (false),
  215386. previewMaxFPS (60)
  215387. {
  215388. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  215389. if (FAILED (hr))
  215390. return;
  215391. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  215392. if (FAILED (hr))
  215393. return;
  215394. hr = graphBuilder.QueryInterface (IID_IMediaControl, mediaControl);
  215395. if (FAILED (hr))
  215396. return;
  215397. {
  215398. ComSmartPtr <IAMStreamConfig> streamConfig;
  215399. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  215400. IID_IAMStreamConfig, (void**) streamConfig.resetAndGetPointerAddress());
  215401. if (streamConfig != 0)
  215402. {
  215403. getVideoSizes (streamConfig);
  215404. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  215405. return;
  215406. }
  215407. }
  215408. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  215409. if (FAILED (hr))
  215410. return;
  215411. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  215412. if (FAILED (hr))
  215413. return;
  215414. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  215415. if (FAILED (hr))
  215416. return;
  215417. if (! connectFilters (filter, smartTee))
  215418. return;
  215419. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  215420. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  215421. if (FAILED (hr))
  215422. return;
  215423. hr = sampleGrabberBase.QueryInterface (IID_ISampleGrabber, sampleGrabber);
  215424. if (FAILED (hr))
  215425. return;
  215426. AM_MEDIA_TYPE mt;
  215427. zerostruct (mt);
  215428. mt.majortype = MEDIATYPE_Video;
  215429. mt.subtype = MEDIASUBTYPE_RGB24;
  215430. mt.formattype = FORMAT_VideoInfo;
  215431. sampleGrabber->SetMediaType (&mt);
  215432. callback = new GrabberCallback (*this);
  215433. hr = sampleGrabber->SetCallback (callback, 1);
  215434. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  215435. if (FAILED (hr))
  215436. return;
  215437. ComSmartPtr <IPin> grabberInputPin;
  215438. if (! (getPin (smartTee, PINDIR_OUTPUT, smartTeeCaptureOutputPin, "capture")
  215439. && getPin (smartTee, PINDIR_OUTPUT, smartTeePreviewOutputPin, "preview")
  215440. && getPin (sampleGrabberBase, PINDIR_INPUT, grabberInputPin)))
  215441. return;
  215442. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  215443. if (FAILED (hr))
  215444. return;
  215445. zerostruct (mt);
  215446. hr = sampleGrabber->GetConnectedMediaType (&mt);
  215447. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  215448. width = pVih->bmiHeader.biWidth;
  215449. height = pVih->bmiHeader.biHeight;
  215450. ComSmartPtr <IBaseFilter> nullFilter;
  215451. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  215452. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  215453. if (connectFilters (sampleGrabberBase, nullFilter)
  215454. && addGraphToRot())
  215455. {
  215456. activeImage = Image (Image::RGB, width, height, true);
  215457. loadingImage = Image (Image::RGB, width, height, true);
  215458. ok = true;
  215459. }
  215460. }
  215461. ~DShowCameraDeviceInteral()
  215462. {
  215463. if (mediaControl != 0)
  215464. mediaControl->Stop();
  215465. removeGraphFromRot();
  215466. for (int i = viewerComps.size(); --i >= 0;)
  215467. viewerComps.getUnchecked(i)->ownerDeleted();
  215468. callback = 0;
  215469. graphBuilder = 0;
  215470. sampleGrabber = 0;
  215471. mediaControl = 0;
  215472. filter = 0;
  215473. captureGraphBuilder = 0;
  215474. smartTee = 0;
  215475. smartTeePreviewOutputPin = 0;
  215476. smartTeeCaptureOutputPin = 0;
  215477. asfWriter = 0;
  215478. }
  215479. void addUser()
  215480. {
  215481. if (ok && activeUsers++ == 0)
  215482. mediaControl->Run();
  215483. }
  215484. void removeUser()
  215485. {
  215486. if (ok && --activeUsers == 0)
  215487. mediaControl->Stop();
  215488. }
  215489. int getPreviewMaxFPS() const
  215490. {
  215491. return previewMaxFPS;
  215492. }
  215493. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  215494. {
  215495. if (recordNextFrameTime)
  215496. {
  215497. const double defaultCameraLatency = 0.1;
  215498. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  215499. recordNextFrameTime = false;
  215500. ComSmartPtr <IPin> pin;
  215501. if (getPin (filter, PINDIR_OUTPUT, pin))
  215502. {
  215503. ComSmartPtr <IAMPushSource> pushSource;
  215504. HRESULT hr = pin.QueryInterface (IID_IAMPushSource, pushSource);
  215505. if (pushSource != 0)
  215506. {
  215507. REFERENCE_TIME latency = 0;
  215508. hr = pushSource->GetLatency (&latency);
  215509. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  215510. }
  215511. }
  215512. }
  215513. {
  215514. const int lineStride = width * 3;
  215515. const ScopedLock sl (imageSwapLock);
  215516. {
  215517. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  215518. for (int i = 0; i < height; ++i)
  215519. memcpy (destData.getLinePointer ((height - 1) - i),
  215520. buffer + lineStride * i,
  215521. lineStride);
  215522. }
  215523. imageNeedsFlipping = true;
  215524. }
  215525. if (listeners.size() > 0)
  215526. callListeners (loadingImage);
  215527. sendChangeMessage();
  215528. }
  215529. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  215530. {
  215531. if (imageNeedsFlipping)
  215532. {
  215533. const ScopedLock sl (imageSwapLock);
  215534. swapVariables (loadingImage, activeImage);
  215535. imageNeedsFlipping = false;
  215536. }
  215537. RectanglePlacement rp (RectanglePlacement::centred);
  215538. double dx = 0, dy = 0, dw = width, dh = height;
  215539. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  215540. const int rx = roundToInt (dx), ry = roundToInt (dy);
  215541. const int rw = roundToInt (dw), rh = roundToInt (dh);
  215542. {
  215543. Graphics::ScopedSaveState ss (g);
  215544. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  215545. g.fillAll (Colours::black);
  215546. }
  215547. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  215548. }
  215549. bool createFileCaptureFilter (const File& file, int quality)
  215550. {
  215551. removeFileCaptureFilter();
  215552. file.deleteFile();
  215553. mediaControl->Stop();
  215554. firstRecordedTime = Time();
  215555. recordNextFrameTime = true;
  215556. previewMaxFPS = 60;
  215557. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  215558. if (SUCCEEDED (hr))
  215559. {
  215560. ComSmartPtr <IFileSinkFilter> fileSink;
  215561. hr = asfWriter.QueryInterface (IID_IFileSinkFilter, fileSink);
  215562. if (SUCCEEDED (hr))
  215563. {
  215564. hr = fileSink->SetFileName (file.getFullPathName().toUTF16(), 0);
  215565. if (SUCCEEDED (hr))
  215566. {
  215567. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  215568. if (SUCCEEDED (hr))
  215569. {
  215570. ComSmartPtr <IConfigAsfWriter> asfConfig;
  215571. hr = asfWriter.QueryInterface (IID_IConfigAsfWriter, asfConfig);
  215572. asfConfig->SetIndexMode (true);
  215573. ComSmartPtr <IWMProfileManager> profileManager;
  215574. hr = WMCreateProfileManager (profileManager.resetAndGetPointerAddress());
  215575. // This gibberish is the DirectShow profile for a video-only wmv file.
  215576. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\">"
  215577. "<streamconfig majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" "
  215578. "streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  215579. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\">"
  215580. "<videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  215581. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" "
  215582. "btemporalcompression=\"1\" lsamplesize=\"0\">"
  215583. "<videoinfoheader dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"$AVGTIMEPERFRAME\">"
  215584. "<rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  215585. "<rctarget left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  215586. "<bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  215587. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" "
  215588. "biclrused=\"0\" biclrimportant=\"0\"/>"
  215589. "</videoinfoheader>"
  215590. "</wmmediatype>"
  215591. "</streamconfig>"
  215592. "</profile>");
  215593. const int fps[] = { 10, 15, 30 };
  215594. int maxFramesPerSecond = fps [jlimit (0, numElementsInArray (fps) - 1, quality & 0xff)];
  215595. if ((quality & 0xff000000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  215596. maxFramesPerSecond = (quality >> 24) & 0xff;
  215597. prof = prof.replace ("$WIDTH", String (width))
  215598. .replace ("$HEIGHT", String (height))
  215599. .replace ("$AVGTIMEPERFRAME", String (10000000 / maxFramesPerSecond));
  215600. ComSmartPtr <IWMProfile> currentProfile;
  215601. hr = profileManager->LoadProfileByData (prof.toUTF16(), currentProfile.resetAndGetPointerAddress());
  215602. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  215603. if (SUCCEEDED (hr))
  215604. {
  215605. ComSmartPtr <IPin> asfWriterInputPin;
  215606. if (getPin (asfWriter, PINDIR_INPUT, asfWriterInputPin, "Video Input 01"))
  215607. {
  215608. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  215609. if (SUCCEEDED (hr) && ok && activeUsers > 0
  215610. && SUCCEEDED (mediaControl->Run()))
  215611. {
  215612. previewMaxFPS = (quality < 2) ? 15 : 25; // throttle back the preview comps to try to leave the cpu free for encoding
  215613. if ((quality & 0x00ff0000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  215614. previewMaxFPS = (quality >> 16) & 0xff;
  215615. return true;
  215616. }
  215617. }
  215618. }
  215619. }
  215620. }
  215621. }
  215622. }
  215623. removeFileCaptureFilter();
  215624. if (ok && activeUsers > 0)
  215625. mediaControl->Run();
  215626. return false;
  215627. }
  215628. void removeFileCaptureFilter()
  215629. {
  215630. mediaControl->Stop();
  215631. if (asfWriter != 0)
  215632. {
  215633. graphBuilder->RemoveFilter (asfWriter);
  215634. asfWriter = 0;
  215635. }
  215636. if (ok && activeUsers > 0)
  215637. mediaControl->Run();
  215638. previewMaxFPS = 60;
  215639. }
  215640. void addListener (CameraDevice::Listener* listenerToAdd)
  215641. {
  215642. const ScopedLock sl (listenerLock);
  215643. if (listeners.size() == 0)
  215644. addUser();
  215645. listeners.addIfNotAlreadyThere (listenerToAdd);
  215646. }
  215647. void removeListener (CameraDevice::Listener* listenerToRemove)
  215648. {
  215649. const ScopedLock sl (listenerLock);
  215650. listeners.removeValue (listenerToRemove);
  215651. if (listeners.size() == 0)
  215652. removeUser();
  215653. }
  215654. void callListeners (const Image& image)
  215655. {
  215656. const ScopedLock sl (listenerLock);
  215657. for (int i = listeners.size(); --i >= 0;)
  215658. {
  215659. CameraDevice::Listener* const l = listeners[i];
  215660. if (l != 0)
  215661. l->imageReceived (image);
  215662. }
  215663. }
  215664. class DShowCaptureViewerComp : public Component,
  215665. public ChangeListener
  215666. {
  215667. public:
  215668. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  215669. : owner (owner_), maxFPS (15), lastRepaintTime (0)
  215670. {
  215671. setOpaque (true);
  215672. owner->addChangeListener (this);
  215673. owner->addUser();
  215674. owner->viewerComps.add (this);
  215675. setSize (owner->width, owner->height);
  215676. }
  215677. ~DShowCaptureViewerComp()
  215678. {
  215679. if (owner != 0)
  215680. {
  215681. owner->viewerComps.removeValue (this);
  215682. owner->removeUser();
  215683. owner->removeChangeListener (this);
  215684. }
  215685. }
  215686. void ownerDeleted()
  215687. {
  215688. owner = 0;
  215689. }
  215690. void paint (Graphics& g)
  215691. {
  215692. g.setColour (Colours::black);
  215693. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  215694. if (owner != 0)
  215695. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  215696. else
  215697. g.fillAll (Colours::black);
  215698. }
  215699. void changeListenerCallback (ChangeBroadcaster*)
  215700. {
  215701. const int64 now = Time::currentTimeMillis();
  215702. if (now >= lastRepaintTime + (1000 / maxFPS))
  215703. {
  215704. lastRepaintTime = now;
  215705. repaint();
  215706. if (owner != 0)
  215707. maxFPS = owner->getPreviewMaxFPS();
  215708. }
  215709. }
  215710. private:
  215711. DShowCameraDeviceInteral* owner;
  215712. int maxFPS;
  215713. int64 lastRepaintTime;
  215714. };
  215715. bool ok;
  215716. int width, height;
  215717. Time firstRecordedTime;
  215718. Array <DShowCaptureViewerComp*> viewerComps;
  215719. private:
  215720. CameraDevice* const owner;
  215721. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215722. ComSmartPtr <IBaseFilter> filter;
  215723. ComSmartPtr <IBaseFilter> smartTee;
  215724. ComSmartPtr <IGraphBuilder> graphBuilder;
  215725. ComSmartPtr <ISampleGrabber> sampleGrabber;
  215726. ComSmartPtr <IMediaControl> mediaControl;
  215727. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  215728. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  215729. ComSmartPtr <IBaseFilter> asfWriter;
  215730. int activeUsers;
  215731. Array <int> widths, heights;
  215732. DWORD graphRegistrationID;
  215733. CriticalSection imageSwapLock;
  215734. bool imageNeedsFlipping;
  215735. Image loadingImage;
  215736. Image activeImage;
  215737. bool recordNextFrameTime;
  215738. int previewMaxFPS;
  215739. void getVideoSizes (IAMStreamConfig* const streamConfig)
  215740. {
  215741. widths.clear();
  215742. heights.clear();
  215743. int count = 0, size = 0;
  215744. streamConfig->GetNumberOfCapabilities (&count, &size);
  215745. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215746. {
  215747. for (int i = 0; i < count; ++i)
  215748. {
  215749. VIDEO_STREAM_CONFIG_CAPS scc;
  215750. AM_MEDIA_TYPE* config;
  215751. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215752. if (SUCCEEDED (hr))
  215753. {
  215754. const int w = scc.InputSize.cx;
  215755. const int h = scc.InputSize.cy;
  215756. bool duplicate = false;
  215757. for (int j = widths.size(); --j >= 0;)
  215758. {
  215759. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  215760. {
  215761. duplicate = true;
  215762. break;
  215763. }
  215764. }
  215765. if (! duplicate)
  215766. {
  215767. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  215768. widths.add (w);
  215769. heights.add (h);
  215770. }
  215771. deleteMediaType (config);
  215772. }
  215773. }
  215774. }
  215775. }
  215776. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  215777. const int minWidth, const int minHeight,
  215778. const int maxWidth, const int maxHeight)
  215779. {
  215780. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  215781. streamConfig->GetNumberOfCapabilities (&count, &size);
  215782. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215783. {
  215784. AM_MEDIA_TYPE* config;
  215785. VIDEO_STREAM_CONFIG_CAPS scc;
  215786. for (int i = 0; i < count; ++i)
  215787. {
  215788. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215789. if (SUCCEEDED (hr))
  215790. {
  215791. if (scc.InputSize.cx >= minWidth
  215792. && scc.InputSize.cy >= minHeight
  215793. && scc.InputSize.cx <= maxWidth
  215794. && scc.InputSize.cy <= maxHeight)
  215795. {
  215796. int area = scc.InputSize.cx * scc.InputSize.cy;
  215797. if (area > bestArea)
  215798. {
  215799. bestIndex = i;
  215800. bestArea = area;
  215801. }
  215802. }
  215803. deleteMediaType (config);
  215804. }
  215805. }
  215806. if (bestIndex >= 0)
  215807. {
  215808. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  215809. hr = streamConfig->SetFormat (config);
  215810. deleteMediaType (config);
  215811. return SUCCEEDED (hr);
  215812. }
  215813. }
  215814. return false;
  215815. }
  215816. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, ComSmartPtr<IPin>& result, const char* pinName = 0)
  215817. {
  215818. ComSmartPtr <IEnumPins> enumerator;
  215819. ComSmartPtr <IPin> pin;
  215820. filter->EnumPins (enumerator.resetAndGetPointerAddress());
  215821. while (enumerator->Next (1, pin.resetAndGetPointerAddress(), 0) == S_OK)
  215822. {
  215823. PIN_DIRECTION dir;
  215824. pin->QueryDirection (&dir);
  215825. if (wantedDirection == dir)
  215826. {
  215827. PIN_INFO info;
  215828. zerostruct (info);
  215829. pin->QueryPinInfo (&info);
  215830. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  215831. {
  215832. result = pin;
  215833. return true;
  215834. }
  215835. }
  215836. }
  215837. return false;
  215838. }
  215839. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  215840. {
  215841. ComSmartPtr <IPin> in, out;
  215842. return getPin (first, PINDIR_OUTPUT, out)
  215843. && getPin (second, PINDIR_INPUT, in)
  215844. && SUCCEEDED (graphBuilder->Connect (out, in));
  215845. }
  215846. bool addGraphToRot()
  215847. {
  215848. ComSmartPtr <IRunningObjectTable> rot;
  215849. if (FAILED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  215850. return false;
  215851. ComSmartPtr <IMoniker> moniker;
  215852. WCHAR buffer[128];
  215853. HRESULT hr = CreateItemMoniker (_T("!"), buffer, moniker.resetAndGetPointerAddress());
  215854. if (FAILED (hr))
  215855. return false;
  215856. graphRegistrationID = 0;
  215857. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  215858. }
  215859. void removeGraphFromRot()
  215860. {
  215861. ComSmartPtr <IRunningObjectTable> rot;
  215862. if (SUCCEEDED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  215863. rot->Revoke (graphRegistrationID);
  215864. }
  215865. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  215866. {
  215867. if (pmt->cbFormat != 0)
  215868. CoTaskMemFree ((PVOID) pmt->pbFormat);
  215869. if (pmt->pUnk != 0)
  215870. pmt->pUnk->Release();
  215871. CoTaskMemFree (pmt);
  215872. }
  215873. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  215874. {
  215875. public:
  215876. GrabberCallback (DShowCameraDeviceInteral& owner_)
  215877. : owner (owner_)
  215878. {
  215879. }
  215880. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  215881. {
  215882. return E_FAIL;
  215883. }
  215884. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  215885. {
  215886. owner.handleFrame (time, buffer, bufferSize);
  215887. return S_OK;
  215888. }
  215889. private:
  215890. DShowCameraDeviceInteral& owner;
  215891. GrabberCallback (const GrabberCallback&);
  215892. GrabberCallback& operator= (const GrabberCallback&);
  215893. };
  215894. ComSmartPtr <GrabberCallback> callback;
  215895. Array <CameraDevice::Listener*> listeners;
  215896. CriticalSection listenerLock;
  215897. JUCE_DECLARE_NON_COPYABLE (DShowCameraDeviceInteral);
  215898. };
  215899. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  215900. : name (name_)
  215901. {
  215902. isRecording = false;
  215903. }
  215904. CameraDevice::~CameraDevice()
  215905. {
  215906. stopRecording();
  215907. delete static_cast <DShowCameraDeviceInteral*> (internal);
  215908. internal = 0;
  215909. }
  215910. Component* CameraDevice::createViewerComponent()
  215911. {
  215912. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  215913. }
  215914. const String CameraDevice::getFileExtension()
  215915. {
  215916. return ".wmv";
  215917. }
  215918. void CameraDevice::startRecordingToFile (const File& file, int quality)
  215919. {
  215920. stopRecording();
  215921. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215922. d->addUser();
  215923. isRecording = d->createFileCaptureFilter (file, quality);
  215924. }
  215925. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  215926. {
  215927. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215928. return d->firstRecordedTime;
  215929. }
  215930. void CameraDevice::stopRecording()
  215931. {
  215932. if (isRecording)
  215933. {
  215934. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215935. d->removeFileCaptureFilter();
  215936. d->removeUser();
  215937. isRecording = false;
  215938. }
  215939. }
  215940. void CameraDevice::addListener (Listener* listenerToAdd)
  215941. {
  215942. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215943. if (listenerToAdd != 0)
  215944. d->addListener (listenerToAdd);
  215945. }
  215946. void CameraDevice::removeListener (Listener* listenerToRemove)
  215947. {
  215948. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215949. if (listenerToRemove != 0)
  215950. d->removeListener (listenerToRemove);
  215951. }
  215952. namespace
  215953. {
  215954. ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  215955. const int deviceIndexToOpen,
  215956. String& name)
  215957. {
  215958. int index = 0;
  215959. ComSmartPtr <IBaseFilter> result;
  215960. ComSmartPtr <ICreateDevEnum> pDevEnum;
  215961. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  215962. if (SUCCEEDED (hr))
  215963. {
  215964. ComSmartPtr <IEnumMoniker> enumerator;
  215965. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0);
  215966. if (SUCCEEDED (hr) && enumerator != 0)
  215967. {
  215968. ComSmartPtr <IMoniker> moniker;
  215969. ULONG fetched;
  215970. while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK)
  215971. {
  215972. ComSmartPtr <IBaseFilter> captureFilter;
  215973. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress());
  215974. if (SUCCEEDED (hr))
  215975. {
  215976. ComSmartPtr <IPropertyBag> propertyBag;
  215977. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress());
  215978. if (SUCCEEDED (hr))
  215979. {
  215980. VARIANT var;
  215981. var.vt = VT_BSTR;
  215982. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  215983. propertyBag = 0;
  215984. if (SUCCEEDED (hr))
  215985. {
  215986. if (names != 0)
  215987. names->add (var.bstrVal);
  215988. if (index == deviceIndexToOpen)
  215989. {
  215990. name = var.bstrVal;
  215991. result = captureFilter;
  215992. break;
  215993. }
  215994. ++index;
  215995. }
  215996. }
  215997. }
  215998. }
  215999. }
  216000. }
  216001. return result;
  216002. }
  216003. }
  216004. const StringArray CameraDevice::getAvailableDevices()
  216005. {
  216006. StringArray devs;
  216007. String dummy;
  216008. enumerateCameras (&devs, -1, dummy);
  216009. return devs;
  216010. }
  216011. CameraDevice* CameraDevice::openDevice (int index,
  216012. int minWidth, int minHeight,
  216013. int maxWidth, int maxHeight)
  216014. {
  216015. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216016. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  216017. if (SUCCEEDED (hr))
  216018. {
  216019. String name;
  216020. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  216021. if (filter != 0)
  216022. {
  216023. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  216024. DShowCameraDeviceInteral* const intern
  216025. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  216026. minWidth, minHeight, maxWidth, maxHeight);
  216027. cam->internal = intern;
  216028. if (intern->ok)
  216029. return cam.release();
  216030. }
  216031. }
  216032. return 0;
  216033. }
  216034. #endif
  216035. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  216036. #endif
  216037. // Auto-link the other win32 libs that are needed by library calls..
  216038. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  216039. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216040. // Auto-links to various win32 libs that are needed by library calls..
  216041. #pragma comment(lib, "kernel32.lib")
  216042. #pragma comment(lib, "user32.lib")
  216043. #pragma comment(lib, "shell32.lib")
  216044. #pragma comment(lib, "gdi32.lib")
  216045. #pragma comment(lib, "vfw32.lib")
  216046. #pragma comment(lib, "comdlg32.lib")
  216047. #pragma comment(lib, "winmm.lib")
  216048. #pragma comment(lib, "wininet.lib")
  216049. #pragma comment(lib, "ole32.lib")
  216050. #pragma comment(lib, "oleaut32.lib")
  216051. #pragma comment(lib, "advapi32.lib")
  216052. #pragma comment(lib, "ws2_32.lib")
  216053. #pragma comment(lib, "version.lib")
  216054. #pragma comment(lib, "shlwapi.lib")
  216055. #ifdef _NATIVE_WCHAR_T_DEFINED
  216056. #ifdef _DEBUG
  216057. #pragma comment(lib, "comsuppwd.lib")
  216058. #else
  216059. #pragma comment(lib, "comsuppw.lib")
  216060. #endif
  216061. #else
  216062. #ifdef _DEBUG
  216063. #pragma comment(lib, "comsuppd.lib")
  216064. #else
  216065. #pragma comment(lib, "comsupp.lib")
  216066. #endif
  216067. #endif
  216068. #if JUCE_OPENGL
  216069. #pragma comment(lib, "OpenGL32.Lib")
  216070. #pragma comment(lib, "GlU32.Lib")
  216071. #endif
  216072. #if JUCE_QUICKTIME
  216073. #pragma comment (lib, "QTMLClient.lib")
  216074. #endif
  216075. #if JUCE_USE_CAMERA
  216076. #pragma comment (lib, "Strmiids.lib")
  216077. #pragma comment (lib, "wmvcore.lib")
  216078. #endif
  216079. #if JUCE_DIRECT2D
  216080. #pragma comment (lib, "Dwrite.lib")
  216081. #pragma comment (lib, "D2d1.lib")
  216082. #endif
  216083. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216084. #endif
  216085. END_JUCE_NAMESPACE
  216086. #endif
  216087. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  216088. #elif JUCE_LINUX
  216089. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  216090. /*
  216091. This file wraps together all the mac-specific code, so that
  216092. we can include all the native headers just once, and compile all our
  216093. platform-specific stuff in one big lump, keeping it out of the way of
  216094. the rest of the codebase.
  216095. */
  216096. #if JUCE_LINUX
  216097. #undef JUCE_BUILD_NATIVE
  216098. #define JUCE_BUILD_NATIVE 1
  216099. BEGIN_JUCE_NAMESPACE
  216100. #define JUCE_INCLUDED_FILE 1
  216101. // Now include the actual code files..
  216102. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  216103. /*
  216104. This file contains posix routines that are common to both the Linux and Mac builds.
  216105. It gets included directly in the cpp files for these platforms.
  216106. */
  216107. CriticalSection::CriticalSection() throw()
  216108. {
  216109. pthread_mutexattr_t atts;
  216110. pthread_mutexattr_init (&atts);
  216111. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  216112. #if ! JUCE_ANDROID
  216113. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216114. #endif
  216115. pthread_mutex_init (&internal, &atts);
  216116. }
  216117. CriticalSection::~CriticalSection() throw()
  216118. {
  216119. pthread_mutex_destroy (&internal);
  216120. }
  216121. void CriticalSection::enter() const throw()
  216122. {
  216123. pthread_mutex_lock (&internal);
  216124. }
  216125. bool CriticalSection::tryEnter() const throw()
  216126. {
  216127. return pthread_mutex_trylock (&internal) == 0;
  216128. }
  216129. void CriticalSection::exit() const throw()
  216130. {
  216131. pthread_mutex_unlock (&internal);
  216132. }
  216133. class WaitableEventImpl
  216134. {
  216135. public:
  216136. WaitableEventImpl (const bool manualReset_)
  216137. : triggered (false),
  216138. manualReset (manualReset_)
  216139. {
  216140. pthread_cond_init (&condition, 0);
  216141. pthread_mutexattr_t atts;
  216142. pthread_mutexattr_init (&atts);
  216143. #if ! JUCE_ANDROID
  216144. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216145. #endif
  216146. pthread_mutex_init (&mutex, &atts);
  216147. }
  216148. ~WaitableEventImpl()
  216149. {
  216150. pthread_cond_destroy (&condition);
  216151. pthread_mutex_destroy (&mutex);
  216152. }
  216153. bool wait (const int timeOutMillisecs) throw()
  216154. {
  216155. pthread_mutex_lock (&mutex);
  216156. if (! triggered)
  216157. {
  216158. if (timeOutMillisecs < 0)
  216159. {
  216160. do
  216161. {
  216162. pthread_cond_wait (&condition, &mutex);
  216163. }
  216164. while (! triggered);
  216165. }
  216166. else
  216167. {
  216168. struct timeval now;
  216169. gettimeofday (&now, 0);
  216170. struct timespec time;
  216171. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  216172. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  216173. if (time.tv_nsec >= 1000000000)
  216174. {
  216175. time.tv_nsec -= 1000000000;
  216176. time.tv_sec++;
  216177. }
  216178. do
  216179. {
  216180. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  216181. {
  216182. pthread_mutex_unlock (&mutex);
  216183. return false;
  216184. }
  216185. }
  216186. while (! triggered);
  216187. }
  216188. }
  216189. if (! manualReset)
  216190. triggered = false;
  216191. pthread_mutex_unlock (&mutex);
  216192. return true;
  216193. }
  216194. void signal() throw()
  216195. {
  216196. pthread_mutex_lock (&mutex);
  216197. triggered = true;
  216198. pthread_cond_broadcast (&condition);
  216199. pthread_mutex_unlock (&mutex);
  216200. }
  216201. void reset() throw()
  216202. {
  216203. pthread_mutex_lock (&mutex);
  216204. triggered = false;
  216205. pthread_mutex_unlock (&mutex);
  216206. }
  216207. private:
  216208. pthread_cond_t condition;
  216209. pthread_mutex_t mutex;
  216210. bool triggered;
  216211. const bool manualReset;
  216212. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  216213. };
  216214. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  216215. : internal (new WaitableEventImpl (manualReset))
  216216. {
  216217. }
  216218. WaitableEvent::~WaitableEvent() throw()
  216219. {
  216220. delete static_cast <WaitableEventImpl*> (internal);
  216221. }
  216222. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  216223. {
  216224. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  216225. }
  216226. void WaitableEvent::signal() const throw()
  216227. {
  216228. static_cast <WaitableEventImpl*> (internal)->signal();
  216229. }
  216230. void WaitableEvent::reset() const throw()
  216231. {
  216232. static_cast <WaitableEventImpl*> (internal)->reset();
  216233. }
  216234. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  216235. {
  216236. struct timespec time;
  216237. time.tv_sec = millisecs / 1000;
  216238. time.tv_nsec = (millisecs % 1000) * 1000000;
  216239. nanosleep (&time, 0);
  216240. }
  216241. const juce_wchar File::separator = '/';
  216242. const String File::separatorString ("/");
  216243. const File File::getCurrentWorkingDirectory()
  216244. {
  216245. HeapBlock<char> heapBuffer;
  216246. char localBuffer [1024];
  216247. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  216248. int bufferSize = 4096;
  216249. while (cwd == 0 && errno == ERANGE)
  216250. {
  216251. heapBuffer.malloc (bufferSize);
  216252. cwd = getcwd (heapBuffer, bufferSize - 1);
  216253. bufferSize += 1024;
  216254. }
  216255. return File (String::fromUTF8 (cwd));
  216256. }
  216257. bool File::setAsCurrentWorkingDirectory() const
  216258. {
  216259. return chdir (getFullPathName().toUTF8()) == 0;
  216260. }
  216261. namespace
  216262. {
  216263. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216264. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  216265. #else
  216266. typedef struct stat juce_statStruct;
  216267. #endif
  216268. bool juce_stat (const String& fileName, juce_statStruct& info)
  216269. {
  216270. return fileName.isNotEmpty()
  216271. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216272. && (stat64 (fileName.toUTF8(), &info) == 0);
  216273. #else
  216274. && (stat (fileName.toUTF8(), &info) == 0);
  216275. #endif
  216276. }
  216277. // if this file doesn't exist, find a parent of it that does..
  216278. bool juce_doStatFS (File f, struct statfs& result)
  216279. {
  216280. for (int i = 5; --i >= 0;)
  216281. {
  216282. if (f.exists())
  216283. break;
  216284. f = f.getParentDirectory();
  216285. }
  216286. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  216287. }
  216288. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  216289. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216290. {
  216291. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  216292. {
  216293. juce_statStruct info;
  216294. const bool statOk = juce_stat (path, info);
  216295. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  216296. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  216297. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  216298. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  216299. }
  216300. if (isReadOnly != 0)
  216301. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  216302. }
  216303. }
  216304. bool File::isDirectory() const
  216305. {
  216306. juce_statStruct info;
  216307. return fullPath.isEmpty()
  216308. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  216309. }
  216310. bool File::exists() const
  216311. {
  216312. juce_statStruct info;
  216313. return fullPath.isNotEmpty()
  216314. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216315. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  216316. #else
  216317. && (lstat (fullPath.toUTF8(), &info) == 0);
  216318. #endif
  216319. }
  216320. bool File::existsAsFile() const
  216321. {
  216322. return exists() && ! isDirectory();
  216323. }
  216324. int64 File::getSize() const
  216325. {
  216326. juce_statStruct info;
  216327. return juce_stat (fullPath, info) ? info.st_size : 0;
  216328. }
  216329. bool File::hasWriteAccess() const
  216330. {
  216331. if (exists())
  216332. return access (fullPath.toUTF8(), W_OK) == 0;
  216333. if ((! isDirectory()) && fullPath.containsChar (separator))
  216334. return getParentDirectory().hasWriteAccess();
  216335. return false;
  216336. }
  216337. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  216338. {
  216339. juce_statStruct info;
  216340. if (! juce_stat (fullPath, info))
  216341. return false;
  216342. info.st_mode &= 0777; // Just permissions
  216343. if (shouldBeReadOnly)
  216344. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  216345. else
  216346. // Give everybody write permission?
  216347. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  216348. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  216349. }
  216350. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  216351. {
  216352. modificationTime = 0;
  216353. accessTime = 0;
  216354. creationTime = 0;
  216355. juce_statStruct info;
  216356. if (juce_stat (fullPath, info))
  216357. {
  216358. modificationTime = (int64) info.st_mtime * 1000;
  216359. accessTime = (int64) info.st_atime * 1000;
  216360. creationTime = (int64) info.st_ctime * 1000;
  216361. }
  216362. }
  216363. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  216364. {
  216365. juce_statStruct info;
  216366. if ((modificationTime != 0 || accessTime != 0) && juce_stat (fullPath, info))
  216367. {
  216368. struct utimbuf times;
  216369. times.actime = accessTime != 0 ? (time_t) (accessTime / 1000) : info.st_atime;
  216370. times.modtime = modificationTime != 0 ? (time_t) (modificationTime / 1000) : info.st_mtime;
  216371. return utime (fullPath.toUTF8(), &times) == 0;
  216372. }
  216373. return false;
  216374. }
  216375. bool File::deleteFile() const
  216376. {
  216377. if (! exists())
  216378. return true;
  216379. if (isDirectory())
  216380. return rmdir (fullPath.toUTF8()) == 0;
  216381. return remove (fullPath.toUTF8()) == 0;
  216382. }
  216383. bool File::moveInternal (const File& dest) const
  216384. {
  216385. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  216386. return true;
  216387. if (hasWriteAccess() && copyInternal (dest))
  216388. {
  216389. if (deleteFile())
  216390. return true;
  216391. dest.deleteFile();
  216392. }
  216393. return false;
  216394. }
  216395. void File::createDirectoryInternal (const String& fileName) const
  216396. {
  216397. mkdir (fileName.toUTF8(), 0777);
  216398. }
  216399. int64 juce_fileSetPosition (void* handle, int64 pos)
  216400. {
  216401. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  216402. return pos;
  216403. return -1;
  216404. }
  216405. void FileInputStream::openHandle()
  216406. {
  216407. totalSize = file.getSize();
  216408. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  216409. if (f != -1)
  216410. fileHandle = (void*) f;
  216411. }
  216412. void FileInputStream::closeHandle()
  216413. {
  216414. if (fileHandle != 0)
  216415. {
  216416. close ((int) (pointer_sized_int) fileHandle);
  216417. fileHandle = 0;
  216418. }
  216419. }
  216420. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  216421. {
  216422. if (fileHandle != 0)
  216423. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  216424. return 0;
  216425. }
  216426. void FileOutputStream::openHandle()
  216427. {
  216428. if (file.exists())
  216429. {
  216430. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  216431. if (f != -1)
  216432. {
  216433. currentPosition = lseek (f, 0, SEEK_END);
  216434. if (currentPosition >= 0)
  216435. fileHandle = (void*) f;
  216436. else
  216437. close (f);
  216438. }
  216439. }
  216440. else
  216441. {
  216442. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  216443. if (f != -1)
  216444. fileHandle = (void*) f;
  216445. }
  216446. }
  216447. void FileOutputStream::closeHandle()
  216448. {
  216449. if (fileHandle != 0)
  216450. {
  216451. close ((int) (pointer_sized_int) fileHandle);
  216452. fileHandle = 0;
  216453. }
  216454. }
  216455. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  216456. {
  216457. if (fileHandle != 0)
  216458. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  216459. return 0;
  216460. }
  216461. void FileOutputStream::flushInternal()
  216462. {
  216463. if (fileHandle != 0)
  216464. fsync ((int) (pointer_sized_int) fileHandle);
  216465. }
  216466. const File juce_getExecutableFile()
  216467. {
  216468. #if JUCE_ANDROID
  216469. // TODO
  216470. return File::nonexistent;
  216471. #else
  216472. Dl_info exeInfo;
  216473. dladdr ((void*) juce_getExecutableFile, &exeInfo); // (can't be a const void* on android)
  216474. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  216475. #endif
  216476. }
  216477. int64 File::getBytesFreeOnVolume() const
  216478. {
  216479. struct statfs buf;
  216480. if (juce_doStatFS (*this, buf))
  216481. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  216482. return 0;
  216483. }
  216484. int64 File::getVolumeTotalSize() const
  216485. {
  216486. struct statfs buf;
  216487. if (juce_doStatFS (*this, buf))
  216488. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  216489. return 0;
  216490. }
  216491. const String File::getVolumeLabel() const
  216492. {
  216493. #if JUCE_MAC
  216494. struct VolAttrBuf
  216495. {
  216496. u_int32_t length;
  216497. attrreference_t mountPointRef;
  216498. char mountPointSpace [MAXPATHLEN];
  216499. } attrBuf;
  216500. struct attrlist attrList;
  216501. zerostruct (attrList);
  216502. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  216503. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  216504. File f (*this);
  216505. for (;;)
  216506. {
  216507. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  216508. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  216509. (int) attrBuf.mountPointRef.attr_length);
  216510. const File parent (f.getParentDirectory());
  216511. if (f == parent)
  216512. break;
  216513. f = parent;
  216514. }
  216515. #endif
  216516. return String::empty;
  216517. }
  216518. int File::getVolumeSerialNumber() const
  216519. {
  216520. int result = 0;
  216521. /* int fd = open (getFullPathName().toUTF8(), O_RDONLY | O_NONBLOCK);
  216522. char info [512];
  216523. #ifndef HDIO_GET_IDENTITY
  216524. #define HDIO_GET_IDENTITY 0x030d
  216525. #endif
  216526. if (ioctl (fd, HDIO_GET_IDENTITY, info) == 0)
  216527. {
  216528. DBG (String (info + 20, 20));
  216529. result = String (info + 20, 20).trim().getIntValue();
  216530. }
  216531. close (fd);*/
  216532. return result;
  216533. }
  216534. void juce_runSystemCommand (const String& command)
  216535. {
  216536. int result = system (command.toUTF8());
  216537. (void) result;
  216538. }
  216539. const String juce_getOutputFromCommand (const String& command)
  216540. {
  216541. // slight bodge here, as we just pipe the output into a temp file and read it...
  216542. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  216543. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  216544. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  216545. String result (tempFile.loadFileAsString());
  216546. tempFile.deleteFile();
  216547. return result;
  216548. }
  216549. class InterProcessLock::Pimpl
  216550. {
  216551. public:
  216552. Pimpl (const String& name, const int timeOutMillisecs)
  216553. : handle (0), refCount (1)
  216554. {
  216555. #if JUCE_MAC
  216556. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  216557. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  216558. #else
  216559. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  216560. #endif
  216561. temp.create();
  216562. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  216563. if (handle != 0)
  216564. {
  216565. struct flock fl;
  216566. zerostruct (fl);
  216567. fl.l_whence = SEEK_SET;
  216568. fl.l_type = F_WRLCK;
  216569. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  216570. for (;;)
  216571. {
  216572. const int result = fcntl (handle, F_SETLK, &fl);
  216573. if (result >= 0)
  216574. return;
  216575. if (errno != EINTR)
  216576. {
  216577. if (timeOutMillisecs == 0
  216578. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  216579. break;
  216580. Thread::sleep (10);
  216581. }
  216582. }
  216583. }
  216584. closeFile();
  216585. }
  216586. ~Pimpl()
  216587. {
  216588. closeFile();
  216589. }
  216590. void closeFile()
  216591. {
  216592. if (handle != 0)
  216593. {
  216594. struct flock fl;
  216595. zerostruct (fl);
  216596. fl.l_whence = SEEK_SET;
  216597. fl.l_type = F_UNLCK;
  216598. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  216599. {}
  216600. close (handle);
  216601. handle = 0;
  216602. }
  216603. }
  216604. int handle, refCount;
  216605. };
  216606. InterProcessLock::InterProcessLock (const String& name_)
  216607. : name (name_)
  216608. {
  216609. }
  216610. InterProcessLock::~InterProcessLock()
  216611. {
  216612. }
  216613. bool InterProcessLock::enter (const int timeOutMillisecs)
  216614. {
  216615. const ScopedLock sl (lock);
  216616. if (pimpl == 0)
  216617. {
  216618. pimpl = new Pimpl (name, timeOutMillisecs);
  216619. if (pimpl->handle == 0)
  216620. pimpl = 0;
  216621. }
  216622. else
  216623. {
  216624. pimpl->refCount++;
  216625. }
  216626. return pimpl != 0;
  216627. }
  216628. void InterProcessLock::exit()
  216629. {
  216630. const ScopedLock sl (lock);
  216631. // Trying to release the lock too many times!
  216632. jassert (pimpl != 0);
  216633. if (pimpl != 0 && --(pimpl->refCount) == 0)
  216634. pimpl = 0;
  216635. }
  216636. void JUCE_API juce_threadEntryPoint (void*);
  216637. void* threadEntryProc (void* userData)
  216638. {
  216639. JUCE_AUTORELEASEPOOL
  216640. juce_threadEntryPoint (userData);
  216641. return 0;
  216642. }
  216643. void Thread::launchThread()
  216644. {
  216645. threadHandle_ = 0;
  216646. pthread_t handle = 0;
  216647. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  216648. {
  216649. pthread_detach (handle);
  216650. threadHandle_ = (void*) handle;
  216651. threadId_ = (ThreadID) threadHandle_;
  216652. }
  216653. }
  216654. void Thread::closeThreadHandle()
  216655. {
  216656. threadId_ = 0;
  216657. threadHandle_ = 0;
  216658. }
  216659. void Thread::killThread()
  216660. {
  216661. if (threadHandle_ != 0)
  216662. {
  216663. #if JUCE_ANDROID
  216664. jassertfalse; // pthread_cancel not available!
  216665. #else
  216666. pthread_cancel ((pthread_t) threadHandle_);
  216667. #endif
  216668. }
  216669. }
  216670. void Thread::setCurrentThreadName (const String& name)
  216671. {
  216672. #if JUCE_MAC
  216673. pthread_setname_np (name.toUTF8());
  216674. #elif JUCE_LINUX
  216675. prctl (PR_SET_NAME, name.toUTF8().getAddress(), 0, 0, 0);
  216676. #endif
  216677. }
  216678. bool Thread::setThreadPriority (void* handle, int priority)
  216679. {
  216680. struct sched_param param;
  216681. int policy;
  216682. priority = jlimit (0, 10, priority);
  216683. if (handle == 0)
  216684. handle = (void*) pthread_self();
  216685. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  216686. return false;
  216687. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  216688. const int minPriority = sched_get_priority_min (policy);
  216689. const int maxPriority = sched_get_priority_max (policy);
  216690. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  216691. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  216692. }
  216693. Thread::ThreadID Thread::getCurrentThreadId()
  216694. {
  216695. return (ThreadID) pthread_self();
  216696. }
  216697. void Thread::yield()
  216698. {
  216699. sched_yield();
  216700. }
  216701. /* Remove this macro if you're having problems compiling the cpu affinity
  216702. calls (the API for these has changed about quite a bit in various Linux
  216703. versions, and a lot of distros seem to ship with obsolete versions)
  216704. */
  216705. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  216706. #define SUPPORT_AFFINITIES 1
  216707. #endif
  216708. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  216709. {
  216710. #if SUPPORT_AFFINITIES
  216711. cpu_set_t affinity;
  216712. CPU_ZERO (&affinity);
  216713. for (int i = 0; i < 32; ++i)
  216714. if ((affinityMask & (1 << i)) != 0)
  216715. CPU_SET (i, &affinity);
  216716. /*
  216717. N.B. If this line causes a compile error, then you've probably not got the latest
  216718. version of glibc installed.
  216719. If you don't want to update your copy of glibc and don't care about cpu affinities,
  216720. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  216721. */
  216722. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  216723. sched_yield();
  216724. #else
  216725. /* affinities aren't supported because either the appropriate header files weren't found,
  216726. or the SUPPORT_AFFINITIES macro was turned off
  216727. */
  216728. jassertfalse;
  216729. (void) affinityMask;
  216730. #endif
  216731. }
  216732. /*** End of inlined file: juce_posix_SharedCode.h ***/
  216733. /*** Start of inlined file: juce_linux_Files.cpp ***/
  216734. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216735. // compiled on its own).
  216736. #if JUCE_INCLUDED_FILE
  216737. enum
  216738. {
  216739. U_ISOFS_SUPER_MAGIC = 0x9660, // linux/iso_fs.h
  216740. U_MSDOS_SUPER_MAGIC = 0x4d44, // linux/msdos_fs.h
  216741. U_NFS_SUPER_MAGIC = 0x6969, // linux/nfs_fs.h
  216742. U_SMB_SUPER_MAGIC = 0x517B // linux/smb_fs.h
  216743. };
  216744. bool File::copyInternal (const File& dest) const
  216745. {
  216746. FileInputStream in (*this);
  216747. if (dest.deleteFile())
  216748. {
  216749. {
  216750. FileOutputStream out (dest);
  216751. if (out.failedToOpen())
  216752. return false;
  216753. if (out.writeFromInputStream (in, -1) == getSize())
  216754. return true;
  216755. }
  216756. dest.deleteFile();
  216757. }
  216758. return false;
  216759. }
  216760. void File::findFileSystemRoots (Array<File>& destArray)
  216761. {
  216762. destArray.add (File ("/"));
  216763. }
  216764. bool File::isOnCDRomDrive() const
  216765. {
  216766. struct statfs buf;
  216767. return statfs (getFullPathName().toUTF8(), &buf) == 0
  216768. && buf.f_type == (short) U_ISOFS_SUPER_MAGIC;
  216769. }
  216770. bool File::isOnHardDisk() const
  216771. {
  216772. struct statfs buf;
  216773. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  216774. {
  216775. switch (buf.f_type)
  216776. {
  216777. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  216778. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  216779. case U_NFS_SUPER_MAGIC: // Network NFS
  216780. case U_SMB_SUPER_MAGIC: // Network Samba
  216781. return false;
  216782. default:
  216783. // Assume anything else is a hard-disk (but note it could
  216784. // be a RAM disk. There isn't a good way of determining
  216785. // this for sure)
  216786. return true;
  216787. }
  216788. }
  216789. // Assume so if this fails for some reason
  216790. return true;
  216791. }
  216792. bool File::isOnRemovableDrive() const
  216793. {
  216794. jassertfalse; // xxx not implemented for linux!
  216795. return false;
  216796. }
  216797. bool File::isHidden() const
  216798. {
  216799. return getFileName().startsWithChar ('.');
  216800. }
  216801. namespace
  216802. {
  216803. const File juce_readlink (const String& file, const File& defaultFile)
  216804. {
  216805. const int size = 8192;
  216806. HeapBlock<char> buffer;
  216807. buffer.malloc (size + 4);
  216808. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  216809. if (numBytes > 0 && numBytes <= size)
  216810. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  216811. return defaultFile;
  216812. }
  216813. }
  216814. const File File::getLinkedTarget() const
  216815. {
  216816. return juce_readlink (getFullPathName().toUTF8(), *this);
  216817. }
  216818. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  216819. const File File::getSpecialLocation (const SpecialLocationType type)
  216820. {
  216821. switch (type)
  216822. {
  216823. case userHomeDirectory:
  216824. {
  216825. const char* homeDir = getenv ("HOME");
  216826. if (homeDir == 0)
  216827. {
  216828. struct passwd* const pw = getpwuid (getuid());
  216829. if (pw != 0)
  216830. homeDir = pw->pw_dir;
  216831. }
  216832. return File (String::fromUTF8 (homeDir));
  216833. }
  216834. case userDocumentsDirectory:
  216835. case userMusicDirectory:
  216836. case userMoviesDirectory:
  216837. case userApplicationDataDirectory:
  216838. return File ("~");
  216839. case userDesktopDirectory:
  216840. return File ("~/Desktop");
  216841. case commonApplicationDataDirectory:
  216842. return File ("/var");
  216843. case globalApplicationsDirectory:
  216844. return File ("/usr");
  216845. case tempDirectory:
  216846. {
  216847. File tmp ("/var/tmp");
  216848. if (! tmp.isDirectory())
  216849. {
  216850. tmp = "/tmp";
  216851. if (! tmp.isDirectory())
  216852. tmp = File::getCurrentWorkingDirectory();
  216853. }
  216854. return tmp;
  216855. }
  216856. case invokedExecutableFile:
  216857. if (juce_Argv0 != 0)
  216858. return File (String::fromUTF8 (juce_Argv0));
  216859. // deliberate fall-through...
  216860. case currentExecutableFile:
  216861. case currentApplicationFile:
  216862. return juce_getExecutableFile();
  216863. case hostApplicationPath:
  216864. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  216865. default:
  216866. jassertfalse; // unknown type?
  216867. break;
  216868. }
  216869. return File::nonexistent;
  216870. }
  216871. const String File::getVersion() const
  216872. {
  216873. return String::empty; // xxx not yet implemented
  216874. }
  216875. bool File::moveToTrash() const
  216876. {
  216877. if (! exists())
  216878. return true;
  216879. File trashCan ("~/.Trash");
  216880. if (! trashCan.isDirectory())
  216881. trashCan = "~/.local/share/Trash/files";
  216882. if (! trashCan.isDirectory())
  216883. return false;
  216884. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  216885. getFileExtension()));
  216886. }
  216887. class DirectoryIterator::NativeIterator::Pimpl
  216888. {
  216889. public:
  216890. Pimpl (const File& directory, const String& wildCard_)
  216891. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  216892. wildCard (wildCard_),
  216893. dir (opendir (directory.getFullPathName().toUTF8()))
  216894. {
  216895. wildcardUTF8 = wildCard.toUTF8();
  216896. }
  216897. ~Pimpl()
  216898. {
  216899. if (dir != 0)
  216900. closedir (dir);
  216901. }
  216902. bool next (String& filenameFound,
  216903. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216904. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216905. {
  216906. if (dir != 0)
  216907. {
  216908. for (;;)
  216909. {
  216910. struct dirent* const de = readdir (dir);
  216911. if (de == 0)
  216912. break;
  216913. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  216914. {
  216915. filenameFound = String::fromUTF8 (de->d_name);
  216916. updateStatInfoForFile (parentDir + filenameFound, isDir, fileSize, modTime, creationTime, isReadOnly);
  216917. if (isHidden != 0)
  216918. *isHidden = filenameFound.startsWithChar ('.');
  216919. return true;
  216920. }
  216921. }
  216922. }
  216923. return false;
  216924. }
  216925. private:
  216926. String parentDir, wildCard;
  216927. const char* wildcardUTF8;
  216928. DIR* dir;
  216929. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  216930. };
  216931. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  216932. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  216933. {
  216934. }
  216935. DirectoryIterator::NativeIterator::~NativeIterator()
  216936. {
  216937. }
  216938. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  216939. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216940. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216941. {
  216942. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  216943. }
  216944. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  216945. {
  216946. String cmdString (fileName.replace (" ", "\\ ",false));
  216947. cmdString << " " << parameters;
  216948. if (URL::isProbablyAWebsiteURL (fileName)
  216949. || cmdString.startsWithIgnoreCase ("file:")
  216950. || URL::isProbablyAnEmailAddress (fileName))
  216951. {
  216952. // create a command that tries to launch a bunch of likely browsers
  216953. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  216954. StringArray cmdLines;
  216955. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  216956. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  216957. cmdString = cmdLines.joinIntoString (" || ");
  216958. }
  216959. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  216960. const int cpid = fork();
  216961. if (cpid == 0)
  216962. {
  216963. setsid();
  216964. // Child process
  216965. execve (argv[0], (char**) argv, environ);
  216966. exit (0);
  216967. }
  216968. return cpid >= 0;
  216969. }
  216970. void File::revealToUser() const
  216971. {
  216972. if (isDirectory())
  216973. startAsProcess();
  216974. else if (getParentDirectory().exists())
  216975. getParentDirectory().startAsProcess();
  216976. }
  216977. #endif
  216978. /*** End of inlined file: juce_linux_Files.cpp ***/
  216979. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  216980. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  216981. // compiled on its own).
  216982. #if JUCE_INCLUDED_FILE
  216983. struct NamedPipeInternal
  216984. {
  216985. String pipeInName, pipeOutName;
  216986. int pipeIn, pipeOut;
  216987. bool volatile createdPipe, blocked, stopReadOperation;
  216988. static void signalHandler (int) {}
  216989. };
  216990. void NamedPipe::cancelPendingReads()
  216991. {
  216992. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  216993. {
  216994. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  216995. intern->stopReadOperation = true;
  216996. char buffer [1] = { 0 };
  216997. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  216998. (void) bytesWritten;
  216999. int timeout = 2000;
  217000. while (intern->blocked && --timeout >= 0)
  217001. Thread::sleep (2);
  217002. intern->stopReadOperation = false;
  217003. }
  217004. }
  217005. void NamedPipe::close()
  217006. {
  217007. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217008. if (intern != 0)
  217009. {
  217010. internal = 0;
  217011. if (intern->pipeIn != -1)
  217012. ::close (intern->pipeIn);
  217013. if (intern->pipeOut != -1)
  217014. ::close (intern->pipeOut);
  217015. if (intern->createdPipe)
  217016. {
  217017. unlink (intern->pipeInName.toUTF8());
  217018. unlink (intern->pipeOutName.toUTF8());
  217019. }
  217020. delete intern;
  217021. }
  217022. }
  217023. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  217024. {
  217025. close();
  217026. NamedPipeInternal* const intern = new NamedPipeInternal();
  217027. internal = intern;
  217028. intern->createdPipe = createPipe;
  217029. intern->blocked = false;
  217030. intern->stopReadOperation = false;
  217031. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  217032. siginterrupt (SIGPIPE, 1);
  217033. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  217034. intern->pipeInName = pipePath + "_in";
  217035. intern->pipeOutName = pipePath + "_out";
  217036. intern->pipeIn = -1;
  217037. intern->pipeOut = -1;
  217038. if (createPipe)
  217039. {
  217040. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  217041. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  217042. {
  217043. delete intern;
  217044. internal = 0;
  217045. return false;
  217046. }
  217047. }
  217048. return true;
  217049. }
  217050. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  217051. {
  217052. int bytesRead = -1;
  217053. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217054. if (intern != 0)
  217055. {
  217056. intern->blocked = true;
  217057. if (intern->pipeIn == -1)
  217058. {
  217059. if (intern->createdPipe)
  217060. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  217061. else
  217062. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  217063. if (intern->pipeIn == -1)
  217064. {
  217065. intern->blocked = false;
  217066. return -1;
  217067. }
  217068. }
  217069. bytesRead = 0;
  217070. char* p = static_cast<char*> (destBuffer);
  217071. while (bytesRead < maxBytesToRead)
  217072. {
  217073. const int bytesThisTime = maxBytesToRead - bytesRead;
  217074. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  217075. if (numRead <= 0 || intern->stopReadOperation)
  217076. {
  217077. bytesRead = -1;
  217078. break;
  217079. }
  217080. bytesRead += numRead;
  217081. p += bytesRead;
  217082. }
  217083. intern->blocked = false;
  217084. }
  217085. return bytesRead;
  217086. }
  217087. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  217088. {
  217089. int bytesWritten = -1;
  217090. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217091. if (intern != 0)
  217092. {
  217093. if (intern->pipeOut == -1)
  217094. {
  217095. if (intern->createdPipe)
  217096. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  217097. else
  217098. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  217099. if (intern->pipeOut == -1)
  217100. {
  217101. return -1;
  217102. }
  217103. }
  217104. const char* p = static_cast<const char*> (sourceBuffer);
  217105. bytesWritten = 0;
  217106. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  217107. while (bytesWritten < numBytesToWrite
  217108. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  217109. {
  217110. const int bytesThisTime = numBytesToWrite - bytesWritten;
  217111. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  217112. if (numWritten <= 0)
  217113. {
  217114. bytesWritten = -1;
  217115. break;
  217116. }
  217117. bytesWritten += numWritten;
  217118. p += bytesWritten;
  217119. }
  217120. }
  217121. return bytesWritten;
  217122. }
  217123. #endif
  217124. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  217125. /*** Start of inlined file: juce_linux_Network.cpp ***/
  217126. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217127. // compiled on its own).
  217128. #if JUCE_INCLUDED_FILE
  217129. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  217130. {
  217131. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  217132. if (s != -1)
  217133. {
  217134. char buf [1024];
  217135. struct ifconf ifc;
  217136. ifc.ifc_len = sizeof (buf);
  217137. ifc.ifc_buf = buf;
  217138. ioctl (s, SIOCGIFCONF, &ifc);
  217139. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  217140. {
  217141. struct ifreq ifr;
  217142. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  217143. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  217144. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  217145. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0)
  217146. {
  217147. result.addIfNotAlreadyThere (MACAddress ((const uint8*) ifr.ifr_hwaddr.sa_data));
  217148. }
  217149. }
  217150. close (s);
  217151. }
  217152. }
  217153. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  217154. const String& emailSubject,
  217155. const String& bodyText,
  217156. const StringArray& filesToAttach)
  217157. {
  217158. jassertfalse; // xxx todo
  217159. return false;
  217160. }
  217161. class WebInputStream : public InputStream
  217162. {
  217163. public:
  217164. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  217165. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  217166. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  217167. : socketHandle (-1), levelsOfRedirection (0),
  217168. address (address_), headers (headers_), postData (postData_), position (0),
  217169. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  217170. {
  217171. createConnection (progressCallback, progressCallbackContext);
  217172. if (responseHeaders != 0 && ! isError())
  217173. {
  217174. for (int i = 0; i < headerLines.size(); ++i)
  217175. {
  217176. const String& headersEntry = headerLines[i];
  217177. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  217178. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  217179. const String previousValue ((*responseHeaders) [key]);
  217180. responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  217181. }
  217182. }
  217183. }
  217184. ~WebInputStream()
  217185. {
  217186. closeSocket();
  217187. }
  217188. bool isError() const { return socketHandle < 0; }
  217189. bool isExhausted() { return finished; }
  217190. int64 getPosition() { return position; }
  217191. int64 getTotalLength()
  217192. {
  217193. jassertfalse; //xxx to do
  217194. return -1;
  217195. }
  217196. int read (void* buffer, int bytesToRead)
  217197. {
  217198. if (finished || isError())
  217199. return 0;
  217200. fd_set readbits;
  217201. FD_ZERO (&readbits);
  217202. FD_SET (socketHandle, &readbits);
  217203. struct timeval tv;
  217204. tv.tv_sec = jmax (1, timeOutMs / 1000);
  217205. tv.tv_usec = 0;
  217206. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217207. return 0; // (timeout)
  217208. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  217209. if (bytesRead == 0)
  217210. finished = true;
  217211. position += bytesRead;
  217212. return bytesRead;
  217213. }
  217214. bool setPosition (int64 wantedPos)
  217215. {
  217216. if (isError())
  217217. return false;
  217218. if (wantedPos != position)
  217219. {
  217220. finished = false;
  217221. if (wantedPos < position)
  217222. {
  217223. closeSocket();
  217224. position = 0;
  217225. createConnection (0, 0);
  217226. }
  217227. skipNextBytes (wantedPos - position);
  217228. }
  217229. return true;
  217230. }
  217231. private:
  217232. int socketHandle, levelsOfRedirection;
  217233. StringArray headerLines;
  217234. String address, headers;
  217235. MemoryBlock postData;
  217236. int64 position;
  217237. bool finished;
  217238. const bool isPost;
  217239. const int timeOutMs;
  217240. void closeSocket()
  217241. {
  217242. if (socketHandle >= 0)
  217243. close (socketHandle);
  217244. socketHandle = -1;
  217245. levelsOfRedirection = 0;
  217246. }
  217247. void createConnection (URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
  217248. {
  217249. closeSocket();
  217250. uint32 timeOutTime = Time::getMillisecondCounter();
  217251. if (timeOutMs == 0)
  217252. timeOutTime += 60000;
  217253. else if (timeOutMs < 0)
  217254. timeOutTime = 0xffffffff;
  217255. else
  217256. timeOutTime += timeOutMs;
  217257. String hostName, hostPath;
  217258. int hostPort;
  217259. if (! decomposeURL (address, hostName, hostPath, hostPort))
  217260. return;
  217261. const struct hostent* host = 0;
  217262. int port = 0;
  217263. String proxyName, proxyPath;
  217264. int proxyPort = 0;
  217265. String proxyURL (getenv ("http_proxy"));
  217266. if (proxyURL.startsWithIgnoreCase ("http://"))
  217267. {
  217268. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  217269. return;
  217270. host = gethostbyname (proxyName.toUTF8());
  217271. port = proxyPort;
  217272. }
  217273. else
  217274. {
  217275. host = gethostbyname (hostName.toUTF8());
  217276. port = hostPort;
  217277. }
  217278. if (host == 0)
  217279. return;
  217280. {
  217281. struct sockaddr_in socketAddress;
  217282. zerostruct (socketAddress);
  217283. memcpy (&socketAddress.sin_addr, host->h_addr, host->h_length);
  217284. socketAddress.sin_family = host->h_addrtype;
  217285. socketAddress.sin_port = htons (port);
  217286. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  217287. if (socketHandle == -1)
  217288. return;
  217289. int receiveBufferSize = 16384;
  217290. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  217291. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  217292. #if JUCE_MAC
  217293. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  217294. #endif
  217295. if (connect (socketHandle, (struct sockaddr*) &socketAddress, sizeof (socketAddress)) == -1)
  217296. {
  217297. closeSocket();
  217298. return;
  217299. }
  217300. }
  217301. {
  217302. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort, proxyName, proxyPort,
  217303. hostPath, address, headers, postData, isPost));
  217304. if (! sendHeader (socketHandle, requestHeader, timeOutTime, progressCallback, progressCallbackContext))
  217305. {
  217306. closeSocket();
  217307. return;
  217308. }
  217309. }
  217310. const String responseHeader (readResponse (socketHandle, timeOutTime));
  217311. if (responseHeader.isNotEmpty())
  217312. {
  217313. headerLines.clear();
  217314. headerLines.addLines (responseHeader);
  217315. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  217316. .substring (0, 3).getIntValue();
  217317. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  217318. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  217319. String location (findHeaderItem (headerLines, "Location:"));
  217320. if (statusCode >= 300 && statusCode < 400 && location.isNotEmpty())
  217321. {
  217322. if (! location.startsWithIgnoreCase ("http://"))
  217323. location = "http://" + location;
  217324. if (++levelsOfRedirection <= 3)
  217325. {
  217326. address = location;
  217327. createConnection (progressCallback, progressCallbackContext);
  217328. return;
  217329. }
  217330. }
  217331. else
  217332. {
  217333. levelsOfRedirection = 0;
  217334. return;
  217335. }
  217336. }
  217337. closeSocket();
  217338. }
  217339. static const String readResponse (const int socketHandle, const uint32 timeOutTime)
  217340. {
  217341. int bytesRead = 0, numConsecutiveLFs = 0;
  217342. MemoryBlock buffer (1024, true);
  217343. while (numConsecutiveLFs < 2 && bytesRead < 32768
  217344. && Time::getMillisecondCounter() <= timeOutTime)
  217345. {
  217346. fd_set readbits;
  217347. FD_ZERO (&readbits);
  217348. FD_SET (socketHandle, &readbits);
  217349. struct timeval tv;
  217350. tv.tv_sec = jmax (1, (int) (timeOutTime - Time::getMillisecondCounter()) / 1000);
  217351. tv.tv_usec = 0;
  217352. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217353. return String::empty; // (timeout)
  217354. buffer.ensureSize (bytesRead + 8, true);
  217355. char* const dest = (char*) buffer.getData() + bytesRead;
  217356. if (recv (socketHandle, dest, 1, 0) == -1)
  217357. return String::empty;
  217358. const char lastByte = *dest;
  217359. ++bytesRead;
  217360. if (lastByte == '\n')
  217361. ++numConsecutiveLFs;
  217362. else if (lastByte != '\r')
  217363. numConsecutiveLFs = 0;
  217364. }
  217365. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  217366. if (header.startsWithIgnoreCase ("HTTP/"))
  217367. return header.trimEnd();
  217368. return String::empty;
  217369. }
  217370. static const MemoryBlock createRequestHeader (const String& hostName, const int hostPort,
  217371. const String& proxyName, const int proxyPort,
  217372. const String& hostPath, const String& originalURL,
  217373. const String& headers, const MemoryBlock& postData,
  217374. const bool isPost)
  217375. {
  217376. String header (isPost ? "POST " : "GET ");
  217377. if (proxyName.isEmpty())
  217378. {
  217379. header << hostPath << " HTTP/1.0\r\nHost: "
  217380. << hostName << ':' << hostPort;
  217381. }
  217382. else
  217383. {
  217384. header << originalURL << " HTTP/1.0\r\nHost: "
  217385. << proxyName << ':' << proxyPort;
  217386. }
  217387. header << "\r\nUser-Agent: JUCE/" << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  217388. << "\r\nConnection: Close\r\nContent-Length: "
  217389. << (int) postData.getSize() << "\r\n"
  217390. << headers << "\r\n";
  217391. MemoryBlock mb;
  217392. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  217393. mb.append (postData.getData(), postData.getSize());
  217394. return mb;
  217395. }
  217396. static bool sendHeader (int socketHandle, const MemoryBlock& requestHeader, const uint32 timeOutTime,
  217397. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
  217398. {
  217399. size_t totalHeaderSent = 0;
  217400. while (totalHeaderSent < requestHeader.getSize())
  217401. {
  217402. if (Time::getMillisecondCounter() > timeOutTime)
  217403. return false;
  217404. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  217405. if (send (socketHandle, static_cast <const char*> (requestHeader.getData()) + totalHeaderSent, numToSend, 0) != numToSend)
  217406. return false;
  217407. totalHeaderSent += numToSend;
  217408. if (progressCallback != 0 && ! progressCallback (progressCallbackContext, totalHeaderSent, requestHeader.getSize()))
  217409. return false;
  217410. }
  217411. return true;
  217412. }
  217413. static bool decomposeURL (const String& url, String& host, String& path, int& port)
  217414. {
  217415. if (! url.startsWithIgnoreCase ("http://"))
  217416. return false;
  217417. const int nextSlash = url.indexOfChar (7, '/');
  217418. int nextColon = url.indexOfChar (7, ':');
  217419. if (nextColon > nextSlash && nextSlash > 0)
  217420. nextColon = -1;
  217421. if (nextColon >= 0)
  217422. {
  217423. host = url.substring (7, nextColon);
  217424. if (nextSlash >= 0)
  217425. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  217426. else
  217427. port = url.substring (nextColon + 1).getIntValue();
  217428. }
  217429. else
  217430. {
  217431. port = 80;
  217432. if (nextSlash >= 0)
  217433. host = url.substring (7, nextSlash);
  217434. else
  217435. host = url.substring (7);
  217436. }
  217437. if (nextSlash >= 0)
  217438. path = url.substring (nextSlash);
  217439. else
  217440. path = "/";
  217441. return true;
  217442. }
  217443. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  217444. {
  217445. for (int i = 0; i < lines.size(); ++i)
  217446. if (lines[i].startsWithIgnoreCase (itemName))
  217447. return lines[i].substring (itemName.length()).trim();
  217448. return String::empty;
  217449. }
  217450. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  217451. };
  217452. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  217453. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  217454. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  217455. {
  217456. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  217457. progressCallback, progressCallbackContext,
  217458. headers, timeOutMs, responseHeaders));
  217459. return wi->isError() ? 0 : wi.release();
  217460. }
  217461. #endif
  217462. /*** End of inlined file: juce_linux_Network.cpp ***/
  217463. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  217464. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217465. // compiled on its own).
  217466. #if JUCE_INCLUDED_FILE
  217467. void Logger::outputDebugString (const String& text)
  217468. {
  217469. std::cerr << text << std::endl;
  217470. }
  217471. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  217472. {
  217473. return Linux;
  217474. }
  217475. const String SystemStats::getOperatingSystemName()
  217476. {
  217477. return "Linux";
  217478. }
  217479. bool SystemStats::isOperatingSystem64Bit()
  217480. {
  217481. #if JUCE_64BIT
  217482. return true;
  217483. #else
  217484. //xxx not sure how to find this out?..
  217485. return false;
  217486. #endif
  217487. }
  217488. namespace LinuxStatsHelpers
  217489. {
  217490. const String getCpuInfo (const char* const key)
  217491. {
  217492. StringArray lines;
  217493. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  217494. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  217495. if (lines[i].startsWithIgnoreCase (key))
  217496. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  217497. return String::empty;
  217498. }
  217499. }
  217500. const String SystemStats::getCpuVendor()
  217501. {
  217502. return LinuxStatsHelpers::getCpuInfo ("vendor_id");
  217503. }
  217504. int SystemStats::getCpuSpeedInMegaherz()
  217505. {
  217506. return roundToInt (LinuxStatsHelpers::getCpuInfo ("cpu MHz").getFloatValue());
  217507. }
  217508. int SystemStats::getMemorySizeInMegabytes()
  217509. {
  217510. struct sysinfo sysi;
  217511. if (sysinfo (&sysi) == 0)
  217512. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  217513. return 0;
  217514. }
  217515. int SystemStats::getPageSize()
  217516. {
  217517. return sysconf (_SC_PAGESIZE);
  217518. }
  217519. const String SystemStats::getLogonName()
  217520. {
  217521. const char* user = getenv ("USER");
  217522. if (user == 0)
  217523. {
  217524. struct passwd* const pw = getpwuid (getuid());
  217525. if (pw != 0)
  217526. user = pw->pw_name;
  217527. }
  217528. return String::fromUTF8 (user);
  217529. }
  217530. const String SystemStats::getFullUserName()
  217531. {
  217532. return getLogonName();
  217533. }
  217534. void SystemStats::initialiseStats()
  217535. {
  217536. const String flags (LinuxStatsHelpers::getCpuInfo ("flags"));
  217537. cpuFlags.hasMMX = flags.contains ("mmx");
  217538. cpuFlags.hasSSE = flags.contains ("sse");
  217539. cpuFlags.hasSSE2 = flags.contains ("sse2");
  217540. cpuFlags.has3DNow = flags.contains ("3dnow");
  217541. cpuFlags.numCpus = LinuxStatsHelpers::getCpuInfo ("processor").getIntValue() + 1;
  217542. }
  217543. void PlatformUtilities::fpuReset()
  217544. {
  217545. }
  217546. uint32 juce_millisecondsSinceStartup() throw()
  217547. {
  217548. timespec t;
  217549. clock_gettime (CLOCK_MONOTONIC, &t);
  217550. return t.tv_sec * 1000 + t.tv_nsec / 1000000;
  217551. }
  217552. int64 Time::getHighResolutionTicks() throw()
  217553. {
  217554. timespec t;
  217555. clock_gettime (CLOCK_MONOTONIC, &t);
  217556. return (t.tv_sec * (int64) 1000000) + (t.tv_nsec / (int64) 1000);
  217557. }
  217558. int64 Time::getHighResolutionTicksPerSecond() throw()
  217559. {
  217560. return 1000000; // (microseconds)
  217561. }
  217562. double Time::getMillisecondCounterHiRes() throw()
  217563. {
  217564. return getHighResolutionTicks() * 0.001;
  217565. }
  217566. bool Time::setSystemTimeToThisTime() const
  217567. {
  217568. timeval t;
  217569. t.tv_sec = millisSinceEpoch / 1000;
  217570. t.tv_usec = (millisSinceEpoch - t.tv_sec * 1000) * 1000;
  217571. return settimeofday (&t, 0) == 0;
  217572. }
  217573. #endif
  217574. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  217575. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  217576. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217577. // compiled on its own).
  217578. #if JUCE_INCLUDED_FILE
  217579. /*
  217580. Note that a lot of methods that you'd expect to find in this file actually
  217581. live in juce_posix_SharedCode.h!
  217582. */
  217583. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  217584. void Process::setPriority (ProcessPriority prior)
  217585. {
  217586. struct sched_param param;
  217587. int policy, maxp, minp;
  217588. const int p = (int) prior;
  217589. if (p <= 1)
  217590. policy = SCHED_OTHER;
  217591. else
  217592. policy = SCHED_RR;
  217593. minp = sched_get_priority_min (policy);
  217594. maxp = sched_get_priority_max (policy);
  217595. if (p < 2)
  217596. param.sched_priority = 0;
  217597. else if (p == 2 )
  217598. // Set to middle of lower realtime priority range
  217599. param.sched_priority = minp + (maxp - minp) / 4;
  217600. else
  217601. // Set to middle of higher realtime priority range
  217602. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  217603. pthread_setschedparam (pthread_self(), policy, &param);
  217604. }
  217605. void Process::terminate()
  217606. {
  217607. exit (0);
  217608. }
  217609. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  217610. {
  217611. static char testResult = 0;
  217612. if (testResult == 0)
  217613. {
  217614. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  217615. if (testResult >= 0)
  217616. {
  217617. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  217618. testResult = 1;
  217619. }
  217620. }
  217621. return testResult < 0;
  217622. }
  217623. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  217624. {
  217625. return juce_isRunningUnderDebugger();
  217626. }
  217627. void Process::raisePrivilege()
  217628. {
  217629. // If running suid root, change effective user
  217630. // to root
  217631. if (geteuid() != 0 && getuid() == 0)
  217632. {
  217633. setreuid (geteuid(), getuid());
  217634. setregid (getegid(), getgid());
  217635. }
  217636. }
  217637. void Process::lowerPrivilege()
  217638. {
  217639. // If runing suid root, change effective user
  217640. // back to real user
  217641. if (geteuid() == 0 && getuid() != 0)
  217642. {
  217643. setreuid (geteuid(), getuid());
  217644. setregid (getegid(), getgid());
  217645. }
  217646. }
  217647. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217648. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  217649. {
  217650. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  217651. }
  217652. void PlatformUtilities::freeDynamicLibrary (void* handle)
  217653. {
  217654. dlclose(handle);
  217655. }
  217656. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  217657. {
  217658. return dlsym (libraryHandle, procedureName.toCString());
  217659. }
  217660. #endif
  217661. #endif
  217662. /*** End of inlined file: juce_linux_Threads.cpp ***/
  217663. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217664. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  217665. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217666. // compiled on its own).
  217667. #if JUCE_INCLUDED_FILE
  217668. extern Display* display;
  217669. extern Window juce_messageWindowHandle;
  217670. namespace ClipboardHelpers
  217671. {
  217672. static String localClipboardContent;
  217673. static Atom atom_UTF8_STRING;
  217674. static Atom atom_CLIPBOARD;
  217675. static Atom atom_TARGETS;
  217676. static void initSelectionAtoms()
  217677. {
  217678. static bool isInitialised = false;
  217679. if (! isInitialised)
  217680. {
  217681. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  217682. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  217683. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  217684. }
  217685. }
  217686. // Read the content of a window property as either a locale-dependent string or an utf8 string
  217687. // works only for strings shorter than 1000000 bytes
  217688. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  217689. {
  217690. String returnData;
  217691. char* clipData;
  217692. Atom actualType;
  217693. int actualFormat;
  217694. unsigned long numItems, bytesLeft;
  217695. if (XGetWindowProperty (display, window, prop,
  217696. 0L /* offset */, 1000000 /* length (max) */, False,
  217697. AnyPropertyType /* format */,
  217698. &actualType, &actualFormat, &numItems, &bytesLeft,
  217699. (unsigned char**) &clipData) == Success)
  217700. {
  217701. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  217702. returnData = String::fromUTF8 (clipData, numItems);
  217703. else if (actualType == XA_STRING && actualFormat == 8)
  217704. returnData = String (clipData, numItems);
  217705. if (clipData != 0)
  217706. XFree (clipData);
  217707. jassert (bytesLeft == 0 || numItems == 1000000);
  217708. }
  217709. XDeleteProperty (display, window, prop);
  217710. return returnData;
  217711. }
  217712. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  217713. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  217714. {
  217715. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  217716. // The selection owner will be asked to set the JUCE_SEL property on the
  217717. // juce_messageWindowHandle with the selection content
  217718. XConvertSelection (display, selection, requestedFormat, property_name,
  217719. juce_messageWindowHandle, CurrentTime);
  217720. int count = 50; // will wait at most for 200 ms
  217721. while (--count >= 0)
  217722. {
  217723. XEvent event;
  217724. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  217725. {
  217726. if (event.xselection.property == property_name)
  217727. {
  217728. jassert (event.xselection.requestor == juce_messageWindowHandle);
  217729. selectionContent = readWindowProperty (event.xselection.requestor,
  217730. event.xselection.property,
  217731. requestedFormat);
  217732. return true;
  217733. }
  217734. else
  217735. {
  217736. return false; // the format we asked for was denied.. (event.xselection.property == None)
  217737. }
  217738. }
  217739. // not very elegant.. we could do a select() or something like that...
  217740. // however clipboard content requesting is inherently slow on x11, it
  217741. // often takes 50ms or more so...
  217742. Thread::sleep (4);
  217743. }
  217744. return false;
  217745. }
  217746. }
  217747. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  217748. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  217749. {
  217750. ClipboardHelpers::initSelectionAtoms();
  217751. // the selection content is sent to the target window as a window property
  217752. XSelectionEvent reply;
  217753. reply.type = SelectionNotify;
  217754. reply.display = evt.display;
  217755. reply.requestor = evt.requestor;
  217756. reply.selection = evt.selection;
  217757. reply.target = evt.target;
  217758. reply.property = None; // == "fail"
  217759. reply.time = evt.time;
  217760. HeapBlock <char> data;
  217761. int propertyFormat = 0, numDataItems = 0;
  217762. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  217763. {
  217764. if (evt.target == XA_STRING)
  217765. {
  217766. // format data according to system locale
  217767. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  217768. data.calloc (numDataItems + 1);
  217769. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  217770. propertyFormat = 8; // bits/item
  217771. }
  217772. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  217773. {
  217774. // translate to utf8
  217775. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  217776. data.calloc (numDataItems + 1);
  217777. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  217778. propertyFormat = 8; // bits/item
  217779. }
  217780. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  217781. {
  217782. // another application wants to know what we are able to send
  217783. numDataItems = 2;
  217784. propertyFormat = 32; // atoms are 32-bit
  217785. data.calloc (numDataItems * 4);
  217786. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  217787. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  217788. atoms[1] = XA_STRING;
  217789. }
  217790. }
  217791. else
  217792. {
  217793. DBG ("requested unsupported clipboard");
  217794. }
  217795. if (data != 0)
  217796. {
  217797. const int maxReasonableSelectionSize = 1000000;
  217798. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  217799. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  217800. {
  217801. XChangeProperty (evt.display, evt.requestor,
  217802. evt.property, evt.target,
  217803. propertyFormat /* 8 or 32 */, PropModeReplace,
  217804. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  217805. reply.property = evt.property; // " == success"
  217806. }
  217807. }
  217808. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  217809. }
  217810. void SystemClipboard::copyTextToClipboard (const String& clipText)
  217811. {
  217812. ClipboardHelpers::initSelectionAtoms();
  217813. ClipboardHelpers::localClipboardContent = clipText;
  217814. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  217815. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  217816. }
  217817. const String SystemClipboard::getTextFromClipboard()
  217818. {
  217819. ClipboardHelpers::initSelectionAtoms();
  217820. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  217821. level" clipboard that is supposed to be filled by ctrl-C
  217822. etc). When a clipboard manager is running, the content of this
  217823. selection is preserved even when the original selection owner
  217824. exits.
  217825. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  217826. filled by good old x11 apps such as xterm)
  217827. */
  217828. String content;
  217829. Atom selection = XA_PRIMARY;
  217830. Window selectionOwner = None;
  217831. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  217832. {
  217833. selection = ClipboardHelpers::atom_CLIPBOARD;
  217834. selectionOwner = XGetSelectionOwner (display, selection);
  217835. }
  217836. if (selectionOwner != None)
  217837. {
  217838. if (selectionOwner == juce_messageWindowHandle)
  217839. {
  217840. content = ClipboardHelpers::localClipboardContent;
  217841. }
  217842. else
  217843. {
  217844. // first try: we want an utf8 string
  217845. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  217846. if (! ok)
  217847. {
  217848. // second chance, ask for a good old locale-dependent string ..
  217849. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  217850. }
  217851. }
  217852. }
  217853. return content;
  217854. }
  217855. #endif
  217856. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  217857. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  217858. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217859. // compiled on its own).
  217860. #if JUCE_INCLUDED_FILE
  217861. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  217862. #define JUCE_DEBUG_XERRORS 1
  217863. #endif
  217864. Display* display = 0;
  217865. Window juce_messageWindowHandle = None;
  217866. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  217867. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  217868. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  217869. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  217870. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  217871. class InternalMessageQueue
  217872. {
  217873. public:
  217874. InternalMessageQueue()
  217875. : bytesInSocket (0),
  217876. totalEventCount (0)
  217877. {
  217878. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  217879. (void) ret; jassert (ret == 0);
  217880. //setNonBlocking (fd[0]);
  217881. //setNonBlocking (fd[1]);
  217882. }
  217883. ~InternalMessageQueue()
  217884. {
  217885. close (fd[0]);
  217886. close (fd[1]);
  217887. clearSingletonInstance();
  217888. }
  217889. void postMessage (Message* msg)
  217890. {
  217891. const int maxBytesInSocketQueue = 128;
  217892. ScopedLock sl (lock);
  217893. queue.add (msg);
  217894. if (bytesInSocket < maxBytesInSocketQueue)
  217895. {
  217896. ++bytesInSocket;
  217897. ScopedUnlock ul (lock);
  217898. const unsigned char x = 0xff;
  217899. size_t bytesWritten = write (fd[0], &x, 1);
  217900. (void) bytesWritten;
  217901. }
  217902. }
  217903. bool isEmpty() const
  217904. {
  217905. ScopedLock sl (lock);
  217906. return queue.size() == 0;
  217907. }
  217908. bool dispatchNextEvent()
  217909. {
  217910. // This alternates between giving priority to XEvents or internal messages,
  217911. // to keep everything running smoothly..
  217912. if ((++totalEventCount & 1) != 0)
  217913. return dispatchNextXEvent() || dispatchNextInternalMessage();
  217914. else
  217915. return dispatchNextInternalMessage() || dispatchNextXEvent();
  217916. }
  217917. // Wait for an event (either XEvent, or an internal Message)
  217918. bool sleepUntilEvent (const int timeoutMs)
  217919. {
  217920. if (! isEmpty())
  217921. return true;
  217922. if (display != 0)
  217923. {
  217924. ScopedXLock xlock;
  217925. if (XPending (display))
  217926. return true;
  217927. }
  217928. struct timeval tv;
  217929. tv.tv_sec = 0;
  217930. tv.tv_usec = timeoutMs * 1000;
  217931. int fd0 = getWaitHandle();
  217932. int fdmax = fd0;
  217933. fd_set readset;
  217934. FD_ZERO (&readset);
  217935. FD_SET (fd0, &readset);
  217936. if (display != 0)
  217937. {
  217938. ScopedXLock xlock;
  217939. int fd1 = XConnectionNumber (display);
  217940. FD_SET (fd1, &readset);
  217941. fdmax = jmax (fd0, fd1);
  217942. }
  217943. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  217944. return (ret > 0); // ret <= 0 if error or timeout
  217945. }
  217946. struct MessageThreadFuncCall
  217947. {
  217948. enum { uniqueID = 0x73774623 };
  217949. MessageCallbackFunction* func;
  217950. void* parameter;
  217951. void* result;
  217952. CriticalSection lock;
  217953. WaitableEvent event;
  217954. };
  217955. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  217956. private:
  217957. CriticalSection lock;
  217958. ReferenceCountedArray <Message> queue;
  217959. int fd[2];
  217960. int bytesInSocket;
  217961. int totalEventCount;
  217962. int getWaitHandle() const throw() { return fd[1]; }
  217963. static bool setNonBlocking (int handle)
  217964. {
  217965. int socketFlags = fcntl (handle, F_GETFL, 0);
  217966. if (socketFlags == -1)
  217967. return false;
  217968. socketFlags |= O_NONBLOCK;
  217969. return fcntl (handle, F_SETFL, socketFlags) == 0;
  217970. }
  217971. static bool dispatchNextXEvent()
  217972. {
  217973. if (display == 0)
  217974. return false;
  217975. XEvent evt;
  217976. {
  217977. ScopedXLock xlock;
  217978. if (! XPending (display))
  217979. return false;
  217980. XNextEvent (display, &evt);
  217981. }
  217982. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  217983. juce_handleSelectionRequest (evt.xselectionrequest);
  217984. else if (evt.xany.window != juce_messageWindowHandle)
  217985. juce_windowMessageReceive (&evt);
  217986. return true;
  217987. }
  217988. const Message::Ptr popNextMessage()
  217989. {
  217990. const ScopedLock sl (lock);
  217991. if (bytesInSocket > 0)
  217992. {
  217993. --bytesInSocket;
  217994. const ScopedUnlock ul (lock);
  217995. unsigned char x;
  217996. size_t numBytes = read (fd[1], &x, 1);
  217997. (void) numBytes;
  217998. }
  217999. return queue.removeAndReturn (0);
  218000. }
  218001. bool dispatchNextInternalMessage()
  218002. {
  218003. const Message::Ptr msg (popNextMessage());
  218004. if (msg == 0)
  218005. return false;
  218006. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  218007. {
  218008. // Handle callback message
  218009. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  218010. call->result = (*(call->func)) (call->parameter);
  218011. call->event.signal();
  218012. }
  218013. else
  218014. {
  218015. // Handle "normal" messages
  218016. MessageManager::getInstance()->deliverMessage (msg);
  218017. }
  218018. return true;
  218019. }
  218020. };
  218021. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  218022. namespace LinuxErrorHandling
  218023. {
  218024. static bool errorOccurred = false;
  218025. static bool keyboardBreakOccurred = false;
  218026. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  218027. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  218028. // Usually happens when client-server connection is broken
  218029. static int ioErrorHandler (Display* display)
  218030. {
  218031. DBG ("ERROR: connection to X server broken.. terminating.");
  218032. if (JUCEApplication::isStandaloneApp())
  218033. MessageManager::getInstance()->stopDispatchLoop();
  218034. errorOccurred = true;
  218035. return 0;
  218036. }
  218037. // A protocol error has occurred
  218038. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  218039. {
  218040. #if JUCE_DEBUG_XERRORS
  218041. char errorStr[64] = { 0 };
  218042. char requestStr[64] = { 0 };
  218043. XGetErrorText (display, event->error_code, errorStr, 64);
  218044. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  218045. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  218046. #endif
  218047. return 0;
  218048. }
  218049. static void installXErrorHandlers()
  218050. {
  218051. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  218052. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  218053. }
  218054. static void removeXErrorHandlers()
  218055. {
  218056. if (JUCEApplication::isStandaloneApp())
  218057. {
  218058. XSetIOErrorHandler (oldIOErrorHandler);
  218059. oldIOErrorHandler = 0;
  218060. XSetErrorHandler (oldErrorHandler);
  218061. oldErrorHandler = 0;
  218062. }
  218063. }
  218064. static void keyboardBreakSignalHandler (int sig)
  218065. {
  218066. if (sig == SIGINT)
  218067. keyboardBreakOccurred = true;
  218068. }
  218069. static void installKeyboardBreakHandler()
  218070. {
  218071. struct sigaction saction;
  218072. sigset_t maskSet;
  218073. sigemptyset (&maskSet);
  218074. saction.sa_handler = keyboardBreakSignalHandler;
  218075. saction.sa_mask = maskSet;
  218076. saction.sa_flags = 0;
  218077. sigaction (SIGINT, &saction, 0);
  218078. }
  218079. }
  218080. void MessageManager::doPlatformSpecificInitialisation()
  218081. {
  218082. if (JUCEApplication::isStandaloneApp())
  218083. {
  218084. // Initialise xlib for multiple thread support
  218085. static bool initThreadCalled = false;
  218086. if (! initThreadCalled)
  218087. {
  218088. if (! XInitThreads())
  218089. {
  218090. // This is fatal! Print error and closedown
  218091. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  218092. Process::terminate();
  218093. return;
  218094. }
  218095. initThreadCalled = true;
  218096. }
  218097. LinuxErrorHandling::installXErrorHandlers();
  218098. LinuxErrorHandling::installKeyboardBreakHandler();
  218099. }
  218100. // Create the internal message queue
  218101. InternalMessageQueue::getInstance();
  218102. // Try to connect to a display
  218103. String displayName (getenv ("DISPLAY"));
  218104. if (displayName.isEmpty())
  218105. displayName = ":0.0";
  218106. display = XOpenDisplay (displayName.toCString());
  218107. if (display != 0) // This is not fatal! we can run headless.
  218108. {
  218109. // Create a context to store user data associated with Windows we create in WindowDriver
  218110. windowHandleXContext = XUniqueContext();
  218111. // We're only interested in client messages for this window, which are always sent
  218112. XSetWindowAttributes swa;
  218113. swa.event_mask = NoEventMask;
  218114. // Create our message window (this will never be mapped)
  218115. const int screen = DefaultScreen (display);
  218116. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  218117. 0, 0, 1, 1, 0, 0, InputOnly,
  218118. DefaultVisual (display, screen),
  218119. CWEventMask, &swa);
  218120. }
  218121. }
  218122. void MessageManager::doPlatformSpecificShutdown()
  218123. {
  218124. InternalMessageQueue::deleteInstance();
  218125. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  218126. {
  218127. XDestroyWindow (display, juce_messageWindowHandle);
  218128. XCloseDisplay (display);
  218129. juce_messageWindowHandle = 0;
  218130. display = 0;
  218131. LinuxErrorHandling::removeXErrorHandlers();
  218132. }
  218133. }
  218134. bool juce_postMessageToSystemQueue (Message* message)
  218135. {
  218136. if (LinuxErrorHandling::errorOccurred)
  218137. return false;
  218138. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  218139. return true;
  218140. }
  218141. void MessageManager::broadcastMessage (const String& value)
  218142. {
  218143. /* TODO */
  218144. }
  218145. class AsyncFunctionCaller : public AsyncUpdater
  218146. {
  218147. public:
  218148. static void* call (MessageCallbackFunction* func_, void* parameter_)
  218149. {
  218150. if (MessageManager::getInstance()->isThisTheMessageThread())
  218151. return func_ (parameter_);
  218152. AsyncFunctionCaller caller (func_, parameter_);
  218153. caller.triggerAsyncUpdate();
  218154. caller.finished.wait();
  218155. return caller.result;
  218156. }
  218157. void handleAsyncUpdate()
  218158. {
  218159. result = (*func) (parameter);
  218160. finished.signal();
  218161. }
  218162. private:
  218163. WaitableEvent finished;
  218164. MessageCallbackFunction* func;
  218165. void* parameter;
  218166. void* volatile result;
  218167. AsyncFunctionCaller (MessageCallbackFunction* func_, void* parameter_)
  218168. : result (0), func (func_), parameter (parameter_)
  218169. {}
  218170. JUCE_DECLARE_NON_COPYABLE (AsyncFunctionCaller);
  218171. };
  218172. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  218173. {
  218174. if (LinuxErrorHandling::errorOccurred)
  218175. return 0;
  218176. return AsyncFunctionCaller::call (func, parameter);
  218177. }
  218178. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  218179. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  218180. {
  218181. while (! LinuxErrorHandling::errorOccurred)
  218182. {
  218183. if (LinuxErrorHandling::keyboardBreakOccurred)
  218184. {
  218185. LinuxErrorHandling::errorOccurred = true;
  218186. if (JUCEApplication::isStandaloneApp())
  218187. Process::terminate();
  218188. break;
  218189. }
  218190. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  218191. return true;
  218192. if (returnIfNoPendingMessages)
  218193. break;
  218194. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  218195. }
  218196. return false;
  218197. }
  218198. #endif
  218199. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  218200. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  218201. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218202. // compiled on its own).
  218203. #if JUCE_INCLUDED_FILE
  218204. class FreeTypeFontFace
  218205. {
  218206. public:
  218207. enum FontStyle
  218208. {
  218209. Plain = 0,
  218210. Bold = 1,
  218211. Italic = 2
  218212. };
  218213. FreeTypeFontFace (const String& familyName)
  218214. : hasSerif (false),
  218215. monospaced (false)
  218216. {
  218217. family = familyName;
  218218. }
  218219. void setFileName (const String& name, const int faceIndex, FontStyle style)
  218220. {
  218221. if (names [(int) style].fileName.isEmpty())
  218222. {
  218223. names [(int) style].fileName = name;
  218224. names [(int) style].faceIndex = faceIndex;
  218225. }
  218226. }
  218227. const String& getFamilyName() const throw() { return family; }
  218228. const String& getFileName (const int style, int& faceIndex) const throw()
  218229. {
  218230. faceIndex = names[style].faceIndex;
  218231. return names[style].fileName;
  218232. }
  218233. void setMonospaced (bool mono) throw() { monospaced = mono; }
  218234. bool getMonospaced() const throw() { return monospaced; }
  218235. void setSerif (const bool serif) throw() { hasSerif = serif; }
  218236. bool getSerif() const throw() { return hasSerif; }
  218237. private:
  218238. String family;
  218239. struct FontNameIndex
  218240. {
  218241. String fileName;
  218242. int faceIndex;
  218243. };
  218244. FontNameIndex names[4];
  218245. bool hasSerif, monospaced;
  218246. };
  218247. class FreeTypeInterface : public DeletedAtShutdown
  218248. {
  218249. public:
  218250. FreeTypeInterface()
  218251. : ftLib (0),
  218252. lastFace (0),
  218253. lastBold (false),
  218254. lastItalic (false)
  218255. {
  218256. if (FT_Init_FreeType (&ftLib) != 0)
  218257. {
  218258. ftLib = 0;
  218259. DBG ("Failed to initialize FreeType");
  218260. }
  218261. StringArray fontDirs;
  218262. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  218263. fontDirs.removeEmptyStrings (true);
  218264. if (fontDirs.size() == 0)
  218265. {
  218266. const ScopedPointer<XmlElement> fontsInfo (XmlDocument::parse (File ("/etc/fonts/fonts.conf")));
  218267. if (fontsInfo != 0)
  218268. {
  218269. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  218270. {
  218271. fontDirs.add (e->getAllSubText().trim());
  218272. }
  218273. }
  218274. }
  218275. if (fontDirs.size() == 0)
  218276. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  218277. for (int i = 0; i < fontDirs.size(); ++i)
  218278. enumerateFaces (fontDirs[i]);
  218279. }
  218280. ~FreeTypeInterface()
  218281. {
  218282. if (lastFace != 0)
  218283. FT_Done_Face (lastFace);
  218284. if (ftLib != 0)
  218285. FT_Done_FreeType (ftLib);
  218286. clearSingletonInstance();
  218287. }
  218288. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  218289. {
  218290. for (int i = 0; i < faces.size(); i++)
  218291. if (faces[i]->getFamilyName() == familyName)
  218292. return faces[i];
  218293. if (! create)
  218294. return 0;
  218295. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  218296. faces.add (newFace);
  218297. return newFace;
  218298. }
  218299. // Enumerate all font faces available in a given directory
  218300. void enumerateFaces (const String& path)
  218301. {
  218302. File dirPath (path);
  218303. if (path.isEmpty() || ! dirPath.isDirectory())
  218304. return;
  218305. DirectoryIterator di (dirPath, true);
  218306. while (di.next())
  218307. {
  218308. File possible (di.getFile());
  218309. if (possible.hasFileExtension ("ttf")
  218310. || possible.hasFileExtension ("pfb")
  218311. || possible.hasFileExtension ("pcf"))
  218312. {
  218313. FT_Face face;
  218314. int faceIndex = 0;
  218315. int numFaces = 0;
  218316. do
  218317. {
  218318. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  218319. faceIndex, &face) == 0)
  218320. {
  218321. if (faceIndex == 0)
  218322. numFaces = face->num_faces;
  218323. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  218324. {
  218325. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  218326. int style = (int) FreeTypeFontFace::Plain;
  218327. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  218328. style |= (int) FreeTypeFontFace::Bold;
  218329. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  218330. style |= (int) FreeTypeFontFace::Italic;
  218331. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  218332. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  218333. // Surely there must be a better way to do this?
  218334. const String name (face->family_name);
  218335. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  218336. || name.containsIgnoreCase ("Verdana")
  218337. || name.containsIgnoreCase ("Arial")));
  218338. }
  218339. FT_Done_Face (face);
  218340. }
  218341. ++faceIndex;
  218342. }
  218343. while (faceIndex < numFaces);
  218344. }
  218345. }
  218346. }
  218347. // Create a FreeType face object for a given font
  218348. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  218349. {
  218350. FT_Face face = 0;
  218351. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  218352. {
  218353. face = lastFace;
  218354. }
  218355. else
  218356. {
  218357. if (lastFace != 0)
  218358. {
  218359. FT_Done_Face (lastFace);
  218360. lastFace = 0;
  218361. }
  218362. lastFontName = fontName;
  218363. lastBold = bold;
  218364. lastItalic = italic;
  218365. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  218366. if (ftFace != 0)
  218367. {
  218368. int style = (int) FreeTypeFontFace::Plain;
  218369. if (bold)
  218370. style |= (int) FreeTypeFontFace::Bold;
  218371. if (italic)
  218372. style |= (int) FreeTypeFontFace::Italic;
  218373. int faceIndex;
  218374. String fileName (ftFace->getFileName (style, faceIndex));
  218375. if (fileName.isEmpty())
  218376. {
  218377. style ^= (int) FreeTypeFontFace::Bold;
  218378. fileName = ftFace->getFileName (style, faceIndex);
  218379. if (fileName.isEmpty())
  218380. {
  218381. style ^= (int) FreeTypeFontFace::Bold;
  218382. style ^= (int) FreeTypeFontFace::Italic;
  218383. fileName = ftFace->getFileName (style, faceIndex);
  218384. if (! fileName.length())
  218385. {
  218386. style ^= (int) FreeTypeFontFace::Bold;
  218387. fileName = ftFace->getFileName (style, faceIndex);
  218388. }
  218389. }
  218390. }
  218391. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  218392. {
  218393. face = lastFace;
  218394. // If there isn't a unicode charmap then select the first one.
  218395. if (FT_Select_Charmap (face, ft_encoding_unicode))
  218396. FT_Set_Charmap (face, face->charmaps[0]);
  218397. }
  218398. }
  218399. }
  218400. return face;
  218401. }
  218402. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  218403. {
  218404. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  218405. const float height = (float) (face->ascender - face->descender);
  218406. const float scaleX = 1.0f / height;
  218407. const float scaleY = -1.0f / height;
  218408. Path destShape;
  218409. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  218410. || face->glyph->format != ft_glyph_format_outline)
  218411. {
  218412. return false;
  218413. }
  218414. const FT_Outline* const outline = &face->glyph->outline;
  218415. const short* const contours = outline->contours;
  218416. const char* const tags = outline->tags;
  218417. FT_Vector* const points = outline->points;
  218418. for (int c = 0; c < outline->n_contours; c++)
  218419. {
  218420. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  218421. const int endPoint = contours[c];
  218422. for (int p = startPoint; p <= endPoint; p++)
  218423. {
  218424. const float x = scaleX * points[p].x;
  218425. const float y = scaleY * points[p].y;
  218426. if (p == startPoint)
  218427. {
  218428. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218429. {
  218430. float x2 = scaleX * points [endPoint].x;
  218431. float y2 = scaleY * points [endPoint].y;
  218432. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  218433. {
  218434. x2 = (x + x2) * 0.5f;
  218435. y2 = (y + y2) * 0.5f;
  218436. }
  218437. destShape.startNewSubPath (x2, y2);
  218438. }
  218439. else
  218440. {
  218441. destShape.startNewSubPath (x, y);
  218442. }
  218443. }
  218444. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  218445. {
  218446. if (p != startPoint)
  218447. destShape.lineTo (x, y);
  218448. }
  218449. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218450. {
  218451. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  218452. float x2 = scaleX * points [nextIndex].x;
  218453. float y2 = scaleY * points [nextIndex].y;
  218454. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  218455. {
  218456. x2 = (x + x2) * 0.5f;
  218457. y2 = (y + y2) * 0.5f;
  218458. }
  218459. else
  218460. {
  218461. ++p;
  218462. }
  218463. destShape.quadraticTo (x, y, x2, y2);
  218464. }
  218465. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  218466. {
  218467. if (p >= endPoint)
  218468. return false;
  218469. const int next1 = p + 1;
  218470. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  218471. const float x2 = scaleX * points [next1].x;
  218472. const float y2 = scaleY * points [next1].y;
  218473. const float x3 = scaleX * points [next2].x;
  218474. const float y3 = scaleY * points [next2].y;
  218475. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  218476. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  218477. return false;
  218478. destShape.cubicTo (x, y, x2, y2, x3, y3);
  218479. p += 2;
  218480. }
  218481. }
  218482. destShape.closeSubPath();
  218483. }
  218484. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  218485. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  218486. addKerning (face, dest, character, glyphIndex);
  218487. return true;
  218488. }
  218489. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  218490. {
  218491. const float height = (float) (face->ascender - face->descender);
  218492. uint32 rightGlyphIndex;
  218493. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  218494. while (rightGlyphIndex != 0)
  218495. {
  218496. FT_Vector kerning;
  218497. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  218498. {
  218499. if (kerning.x != 0)
  218500. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  218501. }
  218502. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  218503. }
  218504. }
  218505. // Add a glyph to a font
  218506. bool addGlyphToFont (const uint32 character, const String& fontName,
  218507. bool bold, bool italic, CustomTypeface& dest)
  218508. {
  218509. FT_Face face = createFT_Face (fontName, bold, italic);
  218510. return face != 0 && addGlyph (face, dest, character);
  218511. }
  218512. void getFamilyNames (StringArray& familyNames) const
  218513. {
  218514. for (int i = 0; i < faces.size(); i++)
  218515. familyNames.add (faces[i]->getFamilyName());
  218516. }
  218517. void getMonospacedNames (StringArray& monoSpaced) const
  218518. {
  218519. for (int i = 0; i < faces.size(); i++)
  218520. if (faces[i]->getMonospaced())
  218521. monoSpaced.add (faces[i]->getFamilyName());
  218522. }
  218523. void getSerifNames (StringArray& serif) const
  218524. {
  218525. for (int i = 0; i < faces.size(); i++)
  218526. if (faces[i]->getSerif())
  218527. serif.add (faces[i]->getFamilyName());
  218528. }
  218529. void getSansSerifNames (StringArray& sansSerif) const
  218530. {
  218531. for (int i = 0; i < faces.size(); i++)
  218532. if (! faces[i]->getSerif())
  218533. sansSerif.add (faces[i]->getFamilyName());
  218534. }
  218535. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  218536. private:
  218537. FT_Library ftLib;
  218538. FT_Face lastFace;
  218539. String lastFontName;
  218540. bool lastBold, lastItalic;
  218541. OwnedArray<FreeTypeFontFace> faces;
  218542. };
  218543. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  218544. class FreetypeTypeface : public CustomTypeface
  218545. {
  218546. public:
  218547. FreetypeTypeface (const Font& font)
  218548. {
  218549. FT_Face face = FreeTypeInterface::getInstance()
  218550. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  218551. if (face == 0)
  218552. {
  218553. #if JUCE_DEBUG
  218554. String msg ("Failed to create typeface: ");
  218555. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  218556. DBG (msg);
  218557. #endif
  218558. }
  218559. else
  218560. {
  218561. setCharacteristics (font.getTypefaceName(),
  218562. face->ascender / (float) (face->ascender - face->descender),
  218563. font.isBold(), font.isItalic(),
  218564. L' ');
  218565. }
  218566. }
  218567. bool loadGlyphIfPossible (juce_wchar character)
  218568. {
  218569. return FreeTypeInterface::getInstance()
  218570. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  218571. }
  218572. };
  218573. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  218574. {
  218575. return new FreetypeTypeface (font);
  218576. }
  218577. const StringArray Font::findAllTypefaceNames()
  218578. {
  218579. StringArray s;
  218580. FreeTypeInterface::getInstance()->getFamilyNames (s);
  218581. s.sort (true);
  218582. return s;
  218583. }
  218584. namespace
  218585. {
  218586. const String pickBestFont (const StringArray& names,
  218587. const char* const choicesString)
  218588. {
  218589. StringArray choices;
  218590. choices.addTokens (String (choicesString), ",", String::empty);
  218591. choices.trim();
  218592. choices.removeEmptyStrings();
  218593. int i, j;
  218594. for (j = 0; j < choices.size(); ++j)
  218595. if (names.contains (choices[j], true))
  218596. return choices[j];
  218597. for (j = 0; j < choices.size(); ++j)
  218598. for (i = 0; i < names.size(); i++)
  218599. if (names[i].startsWithIgnoreCase (choices[j]))
  218600. return names[i];
  218601. for (j = 0; j < choices.size(); ++j)
  218602. for (i = 0; i < names.size(); i++)
  218603. if (names[i].containsIgnoreCase (choices[j]))
  218604. return names[i];
  218605. return names[0];
  218606. }
  218607. const String linux_getDefaultSansSerifFontName()
  218608. {
  218609. StringArray allFonts;
  218610. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  218611. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  218612. }
  218613. const String linux_getDefaultSerifFontName()
  218614. {
  218615. StringArray allFonts;
  218616. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  218617. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  218618. }
  218619. const String linux_getDefaultMonospacedFontName()
  218620. {
  218621. StringArray allFonts;
  218622. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  218623. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  218624. }
  218625. }
  218626. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& /*defaultFallback*/)
  218627. {
  218628. defaultSans = linux_getDefaultSansSerifFontName();
  218629. defaultSerif = linux_getDefaultSerifFontName();
  218630. defaultFixed = linux_getDefaultMonospacedFontName();
  218631. }
  218632. #endif
  218633. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  218634. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  218635. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218636. // compiled on its own).
  218637. #if JUCE_INCLUDED_FILE
  218638. // These are defined in juce_linux_Messaging.cpp
  218639. extern Display* display;
  218640. extern XContext windowHandleXContext;
  218641. namespace Atoms
  218642. {
  218643. enum ProtocolItems
  218644. {
  218645. TAKE_FOCUS = 0,
  218646. DELETE_WINDOW = 1,
  218647. PING = 2
  218648. };
  218649. static Atom Protocols, ProtocolList[3], ChangeState, State,
  218650. ActiveWin, Pid, WindowType, WindowState,
  218651. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  218652. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  218653. XdndActionDescription, XdndActionCopy,
  218654. allowedActions[5],
  218655. allowedMimeTypes[2];
  218656. const unsigned long DndVersion = 3;
  218657. static void initialiseAtoms()
  218658. {
  218659. static bool atomsInitialised = false;
  218660. if (! atomsInitialised)
  218661. {
  218662. atomsInitialised = true;
  218663. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  218664. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  218665. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  218666. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  218667. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  218668. State = XInternAtom (display, "WM_STATE", True);
  218669. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  218670. Pid = XInternAtom (display, "_NET_WM_PID", False);
  218671. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  218672. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  218673. XdndAware = XInternAtom (display, "XdndAware", False);
  218674. XdndEnter = XInternAtom (display, "XdndEnter", False);
  218675. XdndLeave = XInternAtom (display, "XdndLeave", False);
  218676. XdndPosition = XInternAtom (display, "XdndPosition", False);
  218677. XdndStatus = XInternAtom (display, "XdndStatus", False);
  218678. XdndDrop = XInternAtom (display, "XdndDrop", False);
  218679. XdndFinished = XInternAtom (display, "XdndFinished", False);
  218680. XdndSelection = XInternAtom (display, "XdndSelection", False);
  218681. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  218682. XdndActionList = XInternAtom (display, "XdndActionList", False);
  218683. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  218684. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  218685. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  218686. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  218687. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  218688. allowedActions[1] = XdndActionCopy;
  218689. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  218690. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  218691. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  218692. }
  218693. }
  218694. }
  218695. namespace Keys
  218696. {
  218697. enum MouseButtons
  218698. {
  218699. NoButton = 0,
  218700. LeftButton = 1,
  218701. MiddleButton = 2,
  218702. RightButton = 3,
  218703. WheelUp = 4,
  218704. WheelDown = 5
  218705. };
  218706. static int AltMask = 0;
  218707. static int NumLockMask = 0;
  218708. static bool numLock = false;
  218709. static bool capsLock = false;
  218710. static char keyStates [32];
  218711. static const int extendedKeyModifier = 0x10000000;
  218712. }
  218713. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  218714. {
  218715. int keysym;
  218716. if (keyCode & Keys::extendedKeyModifier)
  218717. {
  218718. keysym = 0xff00 | (keyCode & 0xff);
  218719. }
  218720. else
  218721. {
  218722. keysym = keyCode;
  218723. if (keysym == (XK_Tab & 0xff)
  218724. || keysym == (XK_Return & 0xff)
  218725. || keysym == (XK_Escape & 0xff)
  218726. || keysym == (XK_BackSpace & 0xff))
  218727. {
  218728. keysym |= 0xff00;
  218729. }
  218730. }
  218731. ScopedXLock xlock;
  218732. const int keycode = XKeysymToKeycode (display, keysym);
  218733. const int keybyte = keycode >> 3;
  218734. const int keybit = (1 << (keycode & 7));
  218735. return (Keys::keyStates [keybyte] & keybit) != 0;
  218736. }
  218737. #if JUCE_USE_XSHM
  218738. namespace XSHMHelpers
  218739. {
  218740. static int trappedErrorCode = 0;
  218741. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  218742. {
  218743. trappedErrorCode = err->error_code;
  218744. return 0;
  218745. }
  218746. static bool isShmAvailable() throw()
  218747. {
  218748. static bool isChecked = false;
  218749. static bool isAvailable = false;
  218750. if (! isChecked)
  218751. {
  218752. isChecked = true;
  218753. int major, minor;
  218754. Bool pixmaps;
  218755. ScopedXLock xlock;
  218756. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  218757. {
  218758. trappedErrorCode = 0;
  218759. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  218760. XShmSegmentInfo segmentInfo;
  218761. zerostruct (segmentInfo);
  218762. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  218763. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  218764. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218765. xImage->bytes_per_line * xImage->height,
  218766. IPC_CREAT | 0777)) >= 0)
  218767. {
  218768. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218769. if (segmentInfo.shmaddr != (void*) -1)
  218770. {
  218771. segmentInfo.readOnly = False;
  218772. xImage->data = segmentInfo.shmaddr;
  218773. XSync (display, False);
  218774. if (XShmAttach (display, &segmentInfo) != 0)
  218775. {
  218776. XSync (display, False);
  218777. XShmDetach (display, &segmentInfo);
  218778. isAvailable = true;
  218779. }
  218780. }
  218781. XFlush (display);
  218782. XDestroyImage (xImage);
  218783. shmdt (segmentInfo.shmaddr);
  218784. }
  218785. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218786. XSetErrorHandler (oldHandler);
  218787. if (trappedErrorCode != 0)
  218788. isAvailable = false;
  218789. }
  218790. }
  218791. return isAvailable;
  218792. }
  218793. }
  218794. #endif
  218795. #if JUCE_USE_XRENDER
  218796. namespace XRender
  218797. {
  218798. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  218799. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  218800. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  218801. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  218802. static tXRenderQueryVersion xRenderQueryVersion = 0;
  218803. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  218804. static tXRenderFindFormat xRenderFindFormat = 0;
  218805. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  218806. static bool isAvailable()
  218807. {
  218808. static bool hasLoaded = false;
  218809. if (! hasLoaded)
  218810. {
  218811. ScopedXLock xlock;
  218812. hasLoaded = true;
  218813. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  218814. if (h != 0)
  218815. {
  218816. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  218817. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  218818. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  218819. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  218820. }
  218821. if (xRenderQueryVersion != 0
  218822. && xRenderFindStandardFormat != 0
  218823. && xRenderFindFormat != 0
  218824. && xRenderFindVisualFormat != 0)
  218825. {
  218826. int major, minor;
  218827. if (xRenderQueryVersion (display, &major, &minor))
  218828. return true;
  218829. }
  218830. xRenderQueryVersion = 0;
  218831. }
  218832. return xRenderQueryVersion != 0;
  218833. }
  218834. static XRenderPictFormat* findPictureFormat()
  218835. {
  218836. ScopedXLock xlock;
  218837. XRenderPictFormat* pictFormat = 0;
  218838. if (isAvailable())
  218839. {
  218840. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  218841. if (pictFormat == 0)
  218842. {
  218843. XRenderPictFormat desiredFormat;
  218844. desiredFormat.type = PictTypeDirect;
  218845. desiredFormat.depth = 32;
  218846. desiredFormat.direct.alphaMask = 0xff;
  218847. desiredFormat.direct.redMask = 0xff;
  218848. desiredFormat.direct.greenMask = 0xff;
  218849. desiredFormat.direct.blueMask = 0xff;
  218850. desiredFormat.direct.alpha = 24;
  218851. desiredFormat.direct.red = 16;
  218852. desiredFormat.direct.green = 8;
  218853. desiredFormat.direct.blue = 0;
  218854. pictFormat = xRenderFindFormat (display,
  218855. PictFormatType | PictFormatDepth
  218856. | PictFormatRedMask | PictFormatRed
  218857. | PictFormatGreenMask | PictFormatGreen
  218858. | PictFormatBlueMask | PictFormatBlue
  218859. | PictFormatAlphaMask | PictFormatAlpha,
  218860. &desiredFormat,
  218861. 0);
  218862. }
  218863. }
  218864. return pictFormat;
  218865. }
  218866. }
  218867. #endif
  218868. namespace Visuals
  218869. {
  218870. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  218871. {
  218872. ScopedXLock xlock;
  218873. Visual* visual = 0;
  218874. int numVisuals = 0;
  218875. long desiredMask = VisualNoMask;
  218876. XVisualInfo desiredVisual;
  218877. desiredVisual.screen = DefaultScreen (display);
  218878. desiredVisual.depth = desiredDepth;
  218879. desiredMask = VisualScreenMask | VisualDepthMask;
  218880. if (desiredDepth == 32)
  218881. {
  218882. desiredVisual.c_class = TrueColor;
  218883. desiredVisual.red_mask = 0x00FF0000;
  218884. desiredVisual.green_mask = 0x0000FF00;
  218885. desiredVisual.blue_mask = 0x000000FF;
  218886. desiredVisual.bits_per_rgb = 8;
  218887. desiredMask |= VisualClassMask;
  218888. desiredMask |= VisualRedMaskMask;
  218889. desiredMask |= VisualGreenMaskMask;
  218890. desiredMask |= VisualBlueMaskMask;
  218891. desiredMask |= VisualBitsPerRGBMask;
  218892. }
  218893. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218894. desiredMask,
  218895. &desiredVisual,
  218896. &numVisuals);
  218897. if (xvinfos != 0)
  218898. {
  218899. for (int i = 0; i < numVisuals; i++)
  218900. {
  218901. if (xvinfos[i].depth == desiredDepth)
  218902. {
  218903. visual = xvinfos[i].visual;
  218904. break;
  218905. }
  218906. }
  218907. XFree (xvinfos);
  218908. }
  218909. return visual;
  218910. }
  218911. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  218912. {
  218913. Visual* visual = 0;
  218914. if (desiredDepth == 32)
  218915. {
  218916. #if JUCE_USE_XSHM
  218917. if (XSHMHelpers::isShmAvailable())
  218918. {
  218919. #if JUCE_USE_XRENDER
  218920. if (XRender::isAvailable())
  218921. {
  218922. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  218923. if (pictFormat != 0)
  218924. {
  218925. int numVisuals = 0;
  218926. XVisualInfo desiredVisual;
  218927. desiredVisual.screen = DefaultScreen (display);
  218928. desiredVisual.depth = 32;
  218929. desiredVisual.bits_per_rgb = 8;
  218930. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218931. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  218932. &desiredVisual, &numVisuals);
  218933. if (xvinfos != 0)
  218934. {
  218935. for (int i = 0; i < numVisuals; ++i)
  218936. {
  218937. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  218938. if (pictVisualFormat != 0
  218939. && pictVisualFormat->type == PictTypeDirect
  218940. && pictVisualFormat->direct.alphaMask)
  218941. {
  218942. visual = xvinfos[i].visual;
  218943. matchedDepth = 32;
  218944. break;
  218945. }
  218946. }
  218947. XFree (xvinfos);
  218948. }
  218949. }
  218950. }
  218951. #endif
  218952. if (visual == 0)
  218953. {
  218954. visual = findVisualWithDepth (32);
  218955. if (visual != 0)
  218956. matchedDepth = 32;
  218957. }
  218958. }
  218959. #endif
  218960. }
  218961. if (visual == 0 && desiredDepth >= 24)
  218962. {
  218963. visual = findVisualWithDepth (24);
  218964. if (visual != 0)
  218965. matchedDepth = 24;
  218966. }
  218967. if (visual == 0 && desiredDepth >= 16)
  218968. {
  218969. visual = findVisualWithDepth (16);
  218970. if (visual != 0)
  218971. matchedDepth = 16;
  218972. }
  218973. return visual;
  218974. }
  218975. }
  218976. class XBitmapImage : public Image::SharedImage
  218977. {
  218978. public:
  218979. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  218980. const bool clearImage, const int imageDepth_, Visual* visual)
  218981. : Image::SharedImage (format_, w, h),
  218982. imageDepth (imageDepth_),
  218983. gc (None)
  218984. {
  218985. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  218986. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  218987. lineStride = ((w * pixelStride + 3) & ~3);
  218988. ScopedXLock xlock;
  218989. #if JUCE_USE_XSHM
  218990. usingXShm = false;
  218991. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  218992. {
  218993. zerostruct (segmentInfo);
  218994. segmentInfo.shmid = -1;
  218995. segmentInfo.shmaddr = (char *) -1;
  218996. segmentInfo.readOnly = False;
  218997. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  218998. if (xImage != 0)
  218999. {
  219000. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219001. xImage->bytes_per_line * xImage->height,
  219002. IPC_CREAT | 0777)) >= 0)
  219003. {
  219004. if (segmentInfo.shmid != -1)
  219005. {
  219006. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219007. if (segmentInfo.shmaddr != (void*) -1)
  219008. {
  219009. segmentInfo.readOnly = False;
  219010. xImage->data = segmentInfo.shmaddr;
  219011. imageData = (uint8*) segmentInfo.shmaddr;
  219012. if (XShmAttach (display, &segmentInfo) != 0)
  219013. usingXShm = true;
  219014. else
  219015. jassertfalse;
  219016. }
  219017. else
  219018. {
  219019. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219020. }
  219021. }
  219022. }
  219023. }
  219024. }
  219025. if (! usingXShm)
  219026. #endif
  219027. {
  219028. imageDataAllocated.malloc (lineStride * h);
  219029. imageData = imageDataAllocated;
  219030. if (format_ == Image::ARGB && clearImage)
  219031. zeromem (imageData, h * lineStride);
  219032. xImage = (XImage*) juce_calloc (sizeof (XImage));
  219033. xImage->width = w;
  219034. xImage->height = h;
  219035. xImage->xoffset = 0;
  219036. xImage->format = ZPixmap;
  219037. xImage->data = (char*) imageData;
  219038. xImage->byte_order = ImageByteOrder (display);
  219039. xImage->bitmap_unit = BitmapUnit (display);
  219040. xImage->bitmap_bit_order = BitmapBitOrder (display);
  219041. xImage->bitmap_pad = 32;
  219042. xImage->depth = pixelStride * 8;
  219043. xImage->bytes_per_line = lineStride;
  219044. xImage->bits_per_pixel = pixelStride * 8;
  219045. xImage->red_mask = 0x00FF0000;
  219046. xImage->green_mask = 0x0000FF00;
  219047. xImage->blue_mask = 0x000000FF;
  219048. if (imageDepth == 16)
  219049. {
  219050. const int pixelStride = 2;
  219051. const int lineStride = ((w * pixelStride + 3) & ~3);
  219052. imageData16Bit.malloc (lineStride * h);
  219053. xImage->data = imageData16Bit;
  219054. xImage->bitmap_pad = 16;
  219055. xImage->depth = pixelStride * 8;
  219056. xImage->bytes_per_line = lineStride;
  219057. xImage->bits_per_pixel = pixelStride * 8;
  219058. xImage->red_mask = visual->red_mask;
  219059. xImage->green_mask = visual->green_mask;
  219060. xImage->blue_mask = visual->blue_mask;
  219061. }
  219062. if (! XInitImage (xImage))
  219063. jassertfalse;
  219064. }
  219065. }
  219066. ~XBitmapImage()
  219067. {
  219068. ScopedXLock xlock;
  219069. if (gc != None)
  219070. XFreeGC (display, gc);
  219071. #if JUCE_USE_XSHM
  219072. if (usingXShm)
  219073. {
  219074. XShmDetach (display, &segmentInfo);
  219075. XFlush (display);
  219076. XDestroyImage (xImage);
  219077. shmdt (segmentInfo.shmaddr);
  219078. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219079. }
  219080. else
  219081. #endif
  219082. {
  219083. xImage->data = 0;
  219084. XDestroyImage (xImage);
  219085. }
  219086. }
  219087. Image::ImageType getType() const { return Image::NativeImage; }
  219088. LowLevelGraphicsContext* createLowLevelContext()
  219089. {
  219090. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  219091. }
  219092. SharedImage* clone()
  219093. {
  219094. jassertfalse;
  219095. return 0;
  219096. }
  219097. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  219098. {
  219099. ScopedXLock xlock;
  219100. if (gc == None)
  219101. {
  219102. XGCValues gcvalues;
  219103. gcvalues.foreground = None;
  219104. gcvalues.background = None;
  219105. gcvalues.function = GXcopy;
  219106. gcvalues.plane_mask = AllPlanes;
  219107. gcvalues.clip_mask = None;
  219108. gcvalues.graphics_exposures = False;
  219109. gc = XCreateGC (display, window,
  219110. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  219111. &gcvalues);
  219112. }
  219113. if (imageDepth == 16)
  219114. {
  219115. const uint32 rMask = xImage->red_mask;
  219116. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  219117. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  219118. const uint32 gMask = xImage->green_mask;
  219119. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  219120. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  219121. const uint32 bMask = xImage->blue_mask;
  219122. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  219123. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  219124. const Image::BitmapData srcData (Image (this), false);
  219125. for (int y = sy; y < sy + dh; ++y)
  219126. {
  219127. const uint8* p = srcData.getPixelPointer (sx, y);
  219128. for (int x = sx; x < sx + dw; ++x)
  219129. {
  219130. const PixelRGB* const pixel = (const PixelRGB*) p;
  219131. p += srcData.pixelStride;
  219132. XPutPixel (xImage, x, y,
  219133. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  219134. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  219135. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  219136. }
  219137. }
  219138. }
  219139. // blit results to screen.
  219140. #if JUCE_USE_XSHM
  219141. if (usingXShm)
  219142. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  219143. else
  219144. #endif
  219145. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  219146. }
  219147. private:
  219148. XImage* xImage;
  219149. const int imageDepth;
  219150. HeapBlock <uint8> imageDataAllocated;
  219151. HeapBlock <char> imageData16Bit;
  219152. GC gc;
  219153. #if JUCE_USE_XSHM
  219154. XShmSegmentInfo segmentInfo;
  219155. bool usingXShm;
  219156. #endif
  219157. static int getShiftNeeded (const uint32 mask) throw()
  219158. {
  219159. for (int i = 32; --i >= 0;)
  219160. if (((mask >> i) & 1) != 0)
  219161. return i - 7;
  219162. jassertfalse;
  219163. return 0;
  219164. }
  219165. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XBitmapImage);
  219166. };
  219167. namespace PixmapHelpers
  219168. {
  219169. Pixmap createColourPixmapFromImage (Display* display, const Image& image)
  219170. {
  219171. ScopedXLock xlock;
  219172. const int width = image.getWidth();
  219173. const int height = image.getHeight();
  219174. HeapBlock <uint32> colour (width * height);
  219175. int index = 0;
  219176. for (int y = 0; y < height; ++y)
  219177. for (int x = 0; x < width; ++x)
  219178. colour[index++] = image.getPixelAt (x, y).getARGB();
  219179. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  219180. 0, reinterpret_cast<char*> (colour.getData()),
  219181. width, height, 32, 0);
  219182. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  219183. width, height, 24);
  219184. GC gc = XCreateGC (display, pixmap, 0, 0);
  219185. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  219186. XFreeGC (display, gc);
  219187. return pixmap;
  219188. }
  219189. Pixmap createMaskPixmapFromImage (Display* display, const Image& image)
  219190. {
  219191. ScopedXLock xlock;
  219192. const int width = image.getWidth();
  219193. const int height = image.getHeight();
  219194. const int stride = (width + 7) >> 3;
  219195. HeapBlock <char> mask;
  219196. mask.calloc (stride * height);
  219197. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  219198. for (int y = 0; y < height; ++y)
  219199. {
  219200. for (int x = 0; x < width; ++x)
  219201. {
  219202. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  219203. const int offset = y * stride + (x >> 3);
  219204. if (image.getPixelAt (x, y).getAlpha() >= 128)
  219205. mask[offset] |= bit;
  219206. }
  219207. }
  219208. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  219209. mask.getData(), width, height, 1, 0, 1);
  219210. }
  219211. }
  219212. class LinuxComponentPeer : public ComponentPeer
  219213. {
  219214. public:
  219215. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  219216. : ComponentPeer (component, windowStyleFlags),
  219217. windowH (0),
  219218. parentWindow (0),
  219219. wx (0),
  219220. wy (0),
  219221. ww (0),
  219222. wh (0),
  219223. fullScreen (false),
  219224. mapped (false),
  219225. visual (0),
  219226. depth (0)
  219227. {
  219228. // it's dangerous to create a window on a thread other than the message thread..
  219229. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  219230. repainter = new LinuxRepaintManager (this);
  219231. createWindow();
  219232. setTitle (component->getName());
  219233. }
  219234. ~LinuxComponentPeer()
  219235. {
  219236. // it's dangerous to delete a window on a thread other than the message thread..
  219237. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  219238. deleteIconPixmaps();
  219239. destroyWindow();
  219240. windowH = 0;
  219241. }
  219242. void* getNativeHandle() const
  219243. {
  219244. return (void*) windowH;
  219245. }
  219246. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  219247. {
  219248. XPointer peer = 0;
  219249. ScopedXLock xlock;
  219250. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  219251. {
  219252. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  219253. peer = 0;
  219254. }
  219255. return (LinuxComponentPeer*) peer;
  219256. }
  219257. void setVisible (bool shouldBeVisible)
  219258. {
  219259. ScopedXLock xlock;
  219260. if (shouldBeVisible)
  219261. XMapWindow (display, windowH);
  219262. else
  219263. XUnmapWindow (display, windowH);
  219264. }
  219265. void setTitle (const String& title)
  219266. {
  219267. XTextProperty nameProperty;
  219268. char* strings[] = { const_cast <char*> (title.toUTF8().getAddress()) };
  219269. ScopedXLock xlock;
  219270. if (XStringListToTextProperty (strings, 1, &nameProperty))
  219271. {
  219272. XSetWMName (display, windowH, &nameProperty);
  219273. XSetWMIconName (display, windowH, &nameProperty);
  219274. XFree (nameProperty.value);
  219275. }
  219276. }
  219277. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  219278. {
  219279. fullScreen = isNowFullScreen;
  219280. if (windowH != 0)
  219281. {
  219282. WeakReference<Component> deletionChecker (component);
  219283. wx = x;
  219284. wy = y;
  219285. ww = jmax (1, w);
  219286. wh = jmax (1, h);
  219287. ScopedXLock xlock;
  219288. // Make sure the Window manager does what we want
  219289. XSizeHints* hints = XAllocSizeHints();
  219290. hints->flags = USSize | USPosition;
  219291. hints->width = ww;
  219292. hints->height = wh;
  219293. hints->x = wx;
  219294. hints->y = wy;
  219295. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  219296. {
  219297. hints->min_width = hints->max_width = hints->width;
  219298. hints->min_height = hints->max_height = hints->height;
  219299. hints->flags |= PMinSize | PMaxSize;
  219300. }
  219301. XSetWMNormalHints (display, windowH, hints);
  219302. XFree (hints);
  219303. XMoveResizeWindow (display, windowH,
  219304. wx - windowBorder.getLeft(),
  219305. wy - windowBorder.getTop(), ww, wh);
  219306. if (deletionChecker != 0)
  219307. {
  219308. updateBorderSize();
  219309. handleMovedOrResized();
  219310. }
  219311. }
  219312. }
  219313. void setPosition (int x, int y) { setBounds (x, y, ww, wh, false); }
  219314. void setSize (int w, int h) { setBounds (wx, wy, w, h, false); }
  219315. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  219316. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  219317. const Point<int> localToGlobal (const Point<int>& relativePosition)
  219318. {
  219319. return relativePosition + getScreenPosition();
  219320. }
  219321. const Point<int> globalToLocal (const Point<int>& screenPosition)
  219322. {
  219323. return screenPosition - getScreenPosition();
  219324. }
  219325. void setAlpha (float newAlpha)
  219326. {
  219327. //xxx todo!
  219328. }
  219329. void setMinimised (bool shouldBeMinimised)
  219330. {
  219331. if (shouldBeMinimised)
  219332. {
  219333. Window root = RootWindow (display, DefaultScreen (display));
  219334. XClientMessageEvent clientMsg;
  219335. clientMsg.display = display;
  219336. clientMsg.window = windowH;
  219337. clientMsg.type = ClientMessage;
  219338. clientMsg.format = 32;
  219339. clientMsg.message_type = Atoms::ChangeState;
  219340. clientMsg.data.l[0] = IconicState;
  219341. ScopedXLock xlock;
  219342. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  219343. }
  219344. else
  219345. {
  219346. setVisible (true);
  219347. }
  219348. }
  219349. bool isMinimised() const
  219350. {
  219351. bool minimised = false;
  219352. unsigned char* stateProp;
  219353. unsigned long nitems, bytesLeft;
  219354. Atom actualType;
  219355. int actualFormat;
  219356. ScopedXLock xlock;
  219357. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  219358. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  219359. &stateProp) == Success
  219360. && actualType == Atoms::State
  219361. && actualFormat == 32
  219362. && nitems > 0)
  219363. {
  219364. if (((unsigned long*) stateProp)[0] == IconicState)
  219365. minimised = true;
  219366. XFree (stateProp);
  219367. }
  219368. return minimised;
  219369. }
  219370. void setFullScreen (const bool shouldBeFullScreen)
  219371. {
  219372. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  219373. setMinimised (false);
  219374. if (fullScreen != shouldBeFullScreen)
  219375. {
  219376. if (shouldBeFullScreen)
  219377. r = Desktop::getInstance().getMainMonitorArea();
  219378. if (! r.isEmpty())
  219379. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  219380. getComponent()->repaint();
  219381. }
  219382. }
  219383. bool isFullScreen() const
  219384. {
  219385. return fullScreen;
  219386. }
  219387. bool isChildWindowOf (Window possibleParent) const
  219388. {
  219389. Window* windowList = 0;
  219390. uint32 windowListSize = 0;
  219391. Window parent, root;
  219392. ScopedXLock xlock;
  219393. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  219394. {
  219395. if (windowList != 0)
  219396. XFree (windowList);
  219397. return parent == possibleParent;
  219398. }
  219399. return false;
  219400. }
  219401. bool isFrontWindow() const
  219402. {
  219403. Window* windowList = 0;
  219404. uint32 windowListSize = 0;
  219405. bool result = false;
  219406. ScopedXLock xlock;
  219407. Window parent, root = RootWindow (display, DefaultScreen (display));
  219408. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  219409. {
  219410. for (int i = windowListSize; --i >= 0;)
  219411. {
  219412. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  219413. if (peer != 0)
  219414. {
  219415. result = (peer == this);
  219416. break;
  219417. }
  219418. }
  219419. }
  219420. if (windowList != 0)
  219421. XFree (windowList);
  219422. return result;
  219423. }
  219424. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  219425. {
  219426. if (! (isPositiveAndBelow (position.getX(), ww) && isPositiveAndBelow (position.getY(), wh)))
  219427. return false;
  219428. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  219429. {
  219430. Component* const c = Desktop::getInstance().getComponent (i);
  219431. if (c == getComponent())
  219432. break;
  219433. if (c->contains (position + Point<int> (wx, wy) - c->getScreenPosition()))
  219434. return false;
  219435. }
  219436. if (trueIfInAChildWindow)
  219437. return true;
  219438. ::Window root, child;
  219439. unsigned int bw, depth;
  219440. int wx, wy, w, h;
  219441. ScopedXLock xlock;
  219442. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  219443. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  219444. &bw, &depth))
  219445. {
  219446. return false;
  219447. }
  219448. if (! XTranslateCoordinates (display, windowH, windowH, position.getX(), position.getY(), &wx, &wy, &child))
  219449. return false;
  219450. return child == None;
  219451. }
  219452. const BorderSize<int> getFrameSize() const
  219453. {
  219454. return BorderSize<int>();
  219455. }
  219456. bool setAlwaysOnTop (bool alwaysOnTop)
  219457. {
  219458. return false;
  219459. }
  219460. void toFront (bool makeActive)
  219461. {
  219462. if (makeActive)
  219463. {
  219464. setVisible (true);
  219465. grabFocus();
  219466. }
  219467. XEvent ev;
  219468. ev.xclient.type = ClientMessage;
  219469. ev.xclient.serial = 0;
  219470. ev.xclient.send_event = True;
  219471. ev.xclient.message_type = Atoms::ActiveWin;
  219472. ev.xclient.window = windowH;
  219473. ev.xclient.format = 32;
  219474. ev.xclient.data.l[0] = 2;
  219475. ev.xclient.data.l[1] = CurrentTime;
  219476. ev.xclient.data.l[2] = 0;
  219477. ev.xclient.data.l[3] = 0;
  219478. ev.xclient.data.l[4] = 0;
  219479. {
  219480. ScopedXLock xlock;
  219481. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  219482. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  219483. XWindowAttributes attr;
  219484. XGetWindowAttributes (display, windowH, &attr);
  219485. if (component->isAlwaysOnTop())
  219486. XRaiseWindow (display, windowH);
  219487. XSync (display, False);
  219488. }
  219489. handleBroughtToFront();
  219490. }
  219491. void toBehind (ComponentPeer* other)
  219492. {
  219493. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  219494. jassert (otherPeer != 0); // wrong type of window?
  219495. if (otherPeer != 0)
  219496. {
  219497. setMinimised (false);
  219498. Window newStack[] = { otherPeer->windowH, windowH };
  219499. ScopedXLock xlock;
  219500. XRestackWindows (display, newStack, 2);
  219501. }
  219502. }
  219503. bool isFocused() const
  219504. {
  219505. int revert = 0;
  219506. Window focusedWindow = 0;
  219507. ScopedXLock xlock;
  219508. XGetInputFocus (display, &focusedWindow, &revert);
  219509. return focusedWindow == windowH;
  219510. }
  219511. void grabFocus()
  219512. {
  219513. XWindowAttributes atts;
  219514. ScopedXLock xlock;
  219515. if (windowH != 0
  219516. && XGetWindowAttributes (display, windowH, &atts)
  219517. && atts.map_state == IsViewable
  219518. && ! isFocused())
  219519. {
  219520. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  219521. isActiveApplication = true;
  219522. }
  219523. }
  219524. void textInputRequired (const Point<int>&)
  219525. {
  219526. }
  219527. void repaint (const Rectangle<int>& area)
  219528. {
  219529. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  219530. }
  219531. void performAnyPendingRepaintsNow()
  219532. {
  219533. repainter->performAnyPendingRepaintsNow();
  219534. }
  219535. void setIcon (const Image& newIcon)
  219536. {
  219537. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  219538. HeapBlock <unsigned long> data (dataSize);
  219539. int index = 0;
  219540. data[index++] = newIcon.getWidth();
  219541. data[index++] = newIcon.getHeight();
  219542. for (int y = 0; y < newIcon.getHeight(); ++y)
  219543. for (int x = 0; x < newIcon.getWidth(); ++x)
  219544. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  219545. ScopedXLock xlock;
  219546. XChangeProperty (display, windowH,
  219547. XInternAtom (display, "_NET_WM_ICON", False),
  219548. XA_CARDINAL, 32, PropModeReplace,
  219549. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  219550. deleteIconPixmaps();
  219551. XWMHints* wmHints = XGetWMHints (display, windowH);
  219552. if (wmHints == 0)
  219553. wmHints = XAllocWMHints();
  219554. wmHints->flags |= IconPixmapHint | IconMaskHint;
  219555. wmHints->icon_pixmap = PixmapHelpers::createColourPixmapFromImage (display, newIcon);
  219556. wmHints->icon_mask = PixmapHelpers::createMaskPixmapFromImage (display, newIcon);
  219557. XSetWMHints (display, windowH, wmHints);
  219558. XFree (wmHints);
  219559. XSync (display, False);
  219560. }
  219561. void deleteIconPixmaps()
  219562. {
  219563. ScopedXLock xlock;
  219564. XWMHints* wmHints = XGetWMHints (display, windowH);
  219565. if (wmHints != 0)
  219566. {
  219567. if ((wmHints->flags & IconPixmapHint) != 0)
  219568. {
  219569. wmHints->flags &= ~IconPixmapHint;
  219570. XFreePixmap (display, wmHints->icon_pixmap);
  219571. }
  219572. if ((wmHints->flags & IconMaskHint) != 0)
  219573. {
  219574. wmHints->flags &= ~IconMaskHint;
  219575. XFreePixmap (display, wmHints->icon_mask);
  219576. }
  219577. XSetWMHints (display, windowH, wmHints);
  219578. XFree (wmHints);
  219579. }
  219580. }
  219581. void handleWindowMessage (XEvent* event)
  219582. {
  219583. switch (event->xany.type)
  219584. {
  219585. case 2: /* KeyPress */ handleKeyPressEvent ((XKeyEvent*) &event->xkey); break;
  219586. case KeyRelease: handleKeyReleaseEvent ((const XKeyEvent*) &event->xkey); break;
  219587. case ButtonPress: handleButtonPressEvent ((const XButtonPressedEvent*) &event->xbutton); break;
  219588. case ButtonRelease: handleButtonReleaseEvent ((const XButtonReleasedEvent*) &event->xbutton); break;
  219589. case MotionNotify: handleMotionNotifyEvent ((const XPointerMovedEvent*) &event->xmotion); break;
  219590. case EnterNotify: handleEnterNotifyEvent ((const XEnterWindowEvent*) &event->xcrossing); break;
  219591. case LeaveNotify: handleLeaveNotifyEvent ((const XLeaveWindowEvent*) &event->xcrossing); break;
  219592. case FocusIn: handleFocusInEvent(); break;
  219593. case FocusOut: handleFocusOutEvent(); break;
  219594. case Expose: handleExposeEvent ((XExposeEvent*) &event->xexpose); break;
  219595. case MappingNotify: handleMappingNotify ((XMappingEvent*) &event->xmapping); break;
  219596. case ClientMessage: handleClientMessageEvent ((XClientMessageEvent*) &event->xclient, event); break;
  219597. case SelectionNotify: handleDragAndDropSelection (event); break;
  219598. case ConfigureNotify: handleConfigureNotifyEvent ((XConfigureEvent*) &event->xconfigure); break;
  219599. case ReparentNotify: handleReparentNotifyEvent(); break;
  219600. case GravityNotify: handleGravityNotify(); break;
  219601. case CirculateNotify:
  219602. case CreateNotify:
  219603. case DestroyNotify:
  219604. // Think we can ignore these
  219605. break;
  219606. case MapNotify:
  219607. mapped = true;
  219608. handleBroughtToFront();
  219609. break;
  219610. case UnmapNotify:
  219611. mapped = false;
  219612. break;
  219613. case SelectionClear:
  219614. case SelectionRequest:
  219615. break;
  219616. default:
  219617. #if JUCE_USE_XSHM
  219618. {
  219619. ScopedXLock xlock;
  219620. if (event->xany.type == XShmGetEventBase (display))
  219621. repainter->notifyPaintCompleted();
  219622. }
  219623. #endif
  219624. break;
  219625. }
  219626. }
  219627. void handleKeyPressEvent (XKeyEvent* const keyEvent)
  219628. {
  219629. char utf8 [64] = { 0 };
  219630. juce_wchar unicodeChar = 0;
  219631. int keyCode = 0;
  219632. bool keyDownChange = false;
  219633. KeySym sym;
  219634. {
  219635. ScopedXLock xlock;
  219636. updateKeyStates (keyEvent->keycode, true);
  219637. const char* oldLocale = ::setlocale (LC_ALL, 0);
  219638. ::setlocale (LC_ALL, "");
  219639. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  219640. ::setlocale (LC_ALL, oldLocale);
  219641. unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  219642. keyCode = (int) unicodeChar;
  219643. if (keyCode < 0x20)
  219644. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  219645. keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  219646. }
  219647. const ModifierKeys oldMods (currentModifiers);
  219648. bool keyPressed = false;
  219649. if ((sym & 0xff00) == 0xff00)
  219650. {
  219651. switch (sym) // Translate keypad
  219652. {
  219653. case XK_KP_Divide: keyCode = XK_slash; break;
  219654. case XK_KP_Multiply: keyCode = XK_asterisk; break;
  219655. case XK_KP_Subtract: keyCode = XK_hyphen; break;
  219656. case XK_KP_Add: keyCode = XK_plus; break;
  219657. case XK_KP_Enter: keyCode = XK_Return; break;
  219658. case XK_KP_Decimal: keyCode = Keys::numLock ? XK_period : XK_Delete; break;
  219659. case XK_KP_0: keyCode = Keys::numLock ? XK_0 : XK_Insert; break;
  219660. case XK_KP_1: keyCode = Keys::numLock ? XK_1 : XK_End; break;
  219661. case XK_KP_2: keyCode = Keys::numLock ? XK_2 : XK_Down; break;
  219662. case XK_KP_3: keyCode = Keys::numLock ? XK_3 : XK_Page_Down; break;
  219663. case XK_KP_4: keyCode = Keys::numLock ? XK_4 : XK_Left; break;
  219664. case XK_KP_5: keyCode = XK_5; break;
  219665. case XK_KP_6: keyCode = Keys::numLock ? XK_6 : XK_Right; break;
  219666. case XK_KP_7: keyCode = Keys::numLock ? XK_7 : XK_Home; break;
  219667. case XK_KP_8: keyCode = Keys::numLock ? XK_8 : XK_Up; break;
  219668. case XK_KP_9: keyCode = Keys::numLock ? XK_9 : XK_Page_Up; break;
  219669. default: break;
  219670. }
  219671. switch (sym)
  219672. {
  219673. case XK_Left:
  219674. case XK_Right:
  219675. case XK_Up:
  219676. case XK_Down:
  219677. case XK_Page_Up:
  219678. case XK_Page_Down:
  219679. case XK_End:
  219680. case XK_Home:
  219681. case XK_Delete:
  219682. case XK_Insert:
  219683. keyPressed = true;
  219684. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219685. break;
  219686. case XK_Tab:
  219687. case XK_Return:
  219688. case XK_Escape:
  219689. case XK_BackSpace:
  219690. keyPressed = true;
  219691. keyCode &= 0xff;
  219692. break;
  219693. default:
  219694. if (sym >= XK_F1 && sym <= XK_F16)
  219695. {
  219696. keyPressed = true;
  219697. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219698. }
  219699. break;
  219700. }
  219701. }
  219702. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  219703. keyPressed = true;
  219704. if (oldMods != currentModifiers)
  219705. handleModifierKeysChange();
  219706. if (keyDownChange)
  219707. handleKeyUpOrDown (true);
  219708. if (keyPressed)
  219709. handleKeyPress (keyCode, unicodeChar);
  219710. }
  219711. void handleKeyReleaseEvent (const XKeyEvent* const keyEvent)
  219712. {
  219713. updateKeyStates (keyEvent->keycode, false);
  219714. KeySym sym;
  219715. {
  219716. ScopedXLock xlock;
  219717. sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  219718. }
  219719. const ModifierKeys oldMods (currentModifiers);
  219720. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  219721. if (oldMods != currentModifiers)
  219722. handleModifierKeysChange();
  219723. if (keyDownChange)
  219724. handleKeyUpOrDown (false);
  219725. }
  219726. void handleButtonPressEvent (const XButtonPressedEvent* const buttonPressEvent)
  219727. {
  219728. updateKeyModifiers (buttonPressEvent->state);
  219729. bool buttonMsg = false;
  219730. const int map = pointerMap [buttonPressEvent->button - Button1];
  219731. if (map == Keys::WheelUp || map == Keys::WheelDown)
  219732. {
  219733. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  219734. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  219735. }
  219736. if (map == Keys::LeftButton)
  219737. {
  219738. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  219739. buttonMsg = true;
  219740. }
  219741. else if (map == Keys::RightButton)
  219742. {
  219743. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  219744. buttonMsg = true;
  219745. }
  219746. else if (map == Keys::MiddleButton)
  219747. {
  219748. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  219749. buttonMsg = true;
  219750. }
  219751. if (buttonMsg)
  219752. {
  219753. toFront (true);
  219754. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  219755. getEventTime (buttonPressEvent->time));
  219756. }
  219757. clearLastMousePos();
  219758. }
  219759. void handleButtonReleaseEvent (const XButtonReleasedEvent* const buttonRelEvent)
  219760. {
  219761. updateKeyModifiers (buttonRelEvent->state);
  219762. const int map = pointerMap [buttonRelEvent->button - Button1];
  219763. if (map == Keys::LeftButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  219764. else if (map == Keys::RightButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  219765. else if (map == Keys::MiddleButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  219766. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  219767. getEventTime (buttonRelEvent->time));
  219768. clearLastMousePos();
  219769. }
  219770. void handleMotionNotifyEvent (const XPointerMovedEvent* const movedEvent)
  219771. {
  219772. updateKeyModifiers (movedEvent->state);
  219773. const Point<int> mousePos (movedEvent->x_root, movedEvent->y_root);
  219774. if (lastMousePos != mousePos)
  219775. {
  219776. lastMousePos = mousePos;
  219777. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  219778. {
  219779. Window wRoot = 0, wParent = 0;
  219780. {
  219781. ScopedXLock xlock;
  219782. unsigned int numChildren;
  219783. Window* wChild = 0;
  219784. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  219785. }
  219786. if (wParent != 0
  219787. && wParent != windowH
  219788. && wParent != wRoot)
  219789. {
  219790. parentWindow = wParent;
  219791. updateBounds();
  219792. }
  219793. else
  219794. {
  219795. parentWindow = 0;
  219796. }
  219797. }
  219798. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  219799. }
  219800. }
  219801. void handleEnterNotifyEvent (const XEnterWindowEvent* const enterEvent)
  219802. {
  219803. clearLastMousePos();
  219804. if (! currentModifiers.isAnyMouseButtonDown())
  219805. {
  219806. updateKeyModifiers (enterEvent->state);
  219807. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  219808. }
  219809. }
  219810. void handleLeaveNotifyEvent (const XLeaveWindowEvent* const leaveEvent)
  219811. {
  219812. // Suppress the normal leave if we've got a pointer grab, or if
  219813. // it's a bogus one caused by clicking a mouse button when running
  219814. // in a Window manager
  219815. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  219816. || leaveEvent->mode == NotifyUngrab)
  219817. {
  219818. updateKeyModifiers (leaveEvent->state);
  219819. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  219820. }
  219821. }
  219822. void handleFocusInEvent()
  219823. {
  219824. isActiveApplication = true;
  219825. if (isFocused())
  219826. handleFocusGain();
  219827. }
  219828. void handleFocusOutEvent()
  219829. {
  219830. isActiveApplication = false;
  219831. if (! isFocused())
  219832. handleFocusLoss();
  219833. }
  219834. void handleExposeEvent (XExposeEvent* exposeEvent)
  219835. {
  219836. // Batch together all pending expose events
  219837. XEvent nextEvent;
  219838. ScopedXLock xlock;
  219839. if (exposeEvent->window != windowH)
  219840. {
  219841. Window child;
  219842. XTranslateCoordinates (display, exposeEvent->window, windowH,
  219843. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  219844. &child);
  219845. }
  219846. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  219847. exposeEvent->width, exposeEvent->height));
  219848. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  219849. {
  219850. XPeekEvent (display, (XEvent*) &nextEvent);
  219851. if (nextEvent.type != Expose || nextEvent.xany.window != exposeEvent->window)
  219852. break;
  219853. XNextEvent (display, (XEvent*) &nextEvent);
  219854. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  219855. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  219856. nextExposeEvent->width, nextExposeEvent->height));
  219857. }
  219858. }
  219859. void handleConfigureNotifyEvent (XConfigureEvent* const confEvent)
  219860. {
  219861. updateBounds();
  219862. updateBorderSize();
  219863. handleMovedOrResized();
  219864. // if the native title bar is dragged, need to tell any active menus, etc.
  219865. if ((styleFlags & windowHasTitleBar) != 0
  219866. && component->isCurrentlyBlockedByAnotherModalComponent())
  219867. {
  219868. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  219869. if (currentModalComp != 0)
  219870. currentModalComp->inputAttemptWhenModal();
  219871. }
  219872. if (confEvent->window == windowH
  219873. && confEvent->above != 0
  219874. && isFrontWindow())
  219875. {
  219876. handleBroughtToFront();
  219877. }
  219878. }
  219879. void handleReparentNotifyEvent()
  219880. {
  219881. parentWindow = 0;
  219882. Window wRoot = 0;
  219883. Window* wChild = 0;
  219884. unsigned int numChildren;
  219885. {
  219886. ScopedXLock xlock;
  219887. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  219888. }
  219889. if (parentWindow == windowH || parentWindow == wRoot)
  219890. parentWindow = 0;
  219891. handleGravityNotify();
  219892. }
  219893. void handleGravityNotify()
  219894. {
  219895. updateBounds();
  219896. updateBorderSize();
  219897. handleMovedOrResized();
  219898. }
  219899. void handleMappingNotify (XMappingEvent* const mappingEvent)
  219900. {
  219901. if (mappingEvent->request != MappingPointer)
  219902. {
  219903. // Deal with modifier/keyboard mapping
  219904. ScopedXLock xlock;
  219905. XRefreshKeyboardMapping (mappingEvent);
  219906. updateModifierMappings();
  219907. }
  219908. }
  219909. void handleClientMessageEvent (XClientMessageEvent* const clientMsg, XEvent* event)
  219910. {
  219911. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  219912. {
  219913. const Atom atom = (Atom) clientMsg->data.l[0];
  219914. if (atom == Atoms::ProtocolList [Atoms::PING])
  219915. {
  219916. Window root = RootWindow (display, DefaultScreen (display));
  219917. clientMsg->window = root;
  219918. XSendEvent (display, root, False, NoEventMask, event);
  219919. XFlush (display);
  219920. }
  219921. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  219922. {
  219923. XWindowAttributes atts;
  219924. ScopedXLock xlock;
  219925. if (clientMsg->window != 0
  219926. && XGetWindowAttributes (display, clientMsg->window, &atts))
  219927. {
  219928. if (atts.map_state == IsViewable)
  219929. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  219930. }
  219931. }
  219932. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  219933. {
  219934. handleUserClosingWindow();
  219935. }
  219936. }
  219937. else if (clientMsg->message_type == Atoms::XdndEnter)
  219938. {
  219939. handleDragAndDropEnter (clientMsg);
  219940. }
  219941. else if (clientMsg->message_type == Atoms::XdndLeave)
  219942. {
  219943. resetDragAndDrop();
  219944. }
  219945. else if (clientMsg->message_type == Atoms::XdndPosition)
  219946. {
  219947. handleDragAndDropPosition (clientMsg);
  219948. }
  219949. else if (clientMsg->message_type == Atoms::XdndDrop)
  219950. {
  219951. handleDragAndDropDrop (clientMsg);
  219952. }
  219953. else if (clientMsg->message_type == Atoms::XdndStatus)
  219954. {
  219955. handleDragAndDropStatus (clientMsg);
  219956. }
  219957. else if (clientMsg->message_type == Atoms::XdndFinished)
  219958. {
  219959. resetDragAndDrop();
  219960. }
  219961. }
  219962. void showMouseCursor (Cursor cursor) throw()
  219963. {
  219964. ScopedXLock xlock;
  219965. XDefineCursor (display, windowH, cursor);
  219966. }
  219967. void setTaskBarIcon (const Image& image)
  219968. {
  219969. ScopedXLock xlock;
  219970. taskbarImage = image;
  219971. Screen* const screen = XDefaultScreenOfDisplay (display);
  219972. const int screenNumber = XScreenNumberOfScreen (screen);
  219973. String screenAtom ("_NET_SYSTEM_TRAY_S");
  219974. screenAtom << screenNumber;
  219975. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  219976. XGrabServer (display);
  219977. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  219978. if (managerWin != None)
  219979. XSelectInput (display, managerWin, StructureNotifyMask);
  219980. XUngrabServer (display);
  219981. XFlush (display);
  219982. if (managerWin != None)
  219983. {
  219984. XEvent ev;
  219985. zerostruct (ev);
  219986. ev.xclient.type = ClientMessage;
  219987. ev.xclient.window = managerWin;
  219988. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  219989. ev.xclient.format = 32;
  219990. ev.xclient.data.l[0] = CurrentTime;
  219991. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  219992. ev.xclient.data.l[2] = windowH;
  219993. ev.xclient.data.l[3] = 0;
  219994. ev.xclient.data.l[4] = 0;
  219995. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  219996. XSync (display, False);
  219997. }
  219998. // For older KDE's ...
  219999. long atomData = 1;
  220000. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  220001. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  220002. // For more recent KDE's...
  220003. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  220004. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  220005. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  220006. XSizeHints* hints = XAllocSizeHints();
  220007. hints->flags = PMinSize;
  220008. hints->min_width = 22;
  220009. hints->min_height = 22;
  220010. XSetWMNormalHints (display, windowH, hints);
  220011. XFree (hints);
  220012. }
  220013. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  220014. bool dontRepaint;
  220015. static ModifierKeys currentModifiers;
  220016. static bool isActiveApplication;
  220017. private:
  220018. class LinuxRepaintManager : public Timer
  220019. {
  220020. public:
  220021. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  220022. : peer (peer_),
  220023. lastTimeImageUsed (0)
  220024. {
  220025. #if JUCE_USE_XSHM
  220026. shmCompletedDrawing = true;
  220027. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  220028. if (useARGBImagesForRendering)
  220029. {
  220030. ScopedXLock xlock;
  220031. XShmSegmentInfo segmentinfo;
  220032. XImage* const testImage
  220033. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  220034. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  220035. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  220036. XDestroyImage (testImage);
  220037. }
  220038. #endif
  220039. }
  220040. void timerCallback()
  220041. {
  220042. #if JUCE_USE_XSHM
  220043. if (! shmCompletedDrawing)
  220044. return;
  220045. #endif
  220046. if (! regionsNeedingRepaint.isEmpty())
  220047. {
  220048. stopTimer();
  220049. performAnyPendingRepaintsNow();
  220050. }
  220051. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  220052. {
  220053. stopTimer();
  220054. image = Image::null;
  220055. }
  220056. }
  220057. void repaint (const Rectangle<int>& area)
  220058. {
  220059. if (! isTimerRunning())
  220060. startTimer (repaintTimerPeriod);
  220061. regionsNeedingRepaint.add (area);
  220062. }
  220063. void performAnyPendingRepaintsNow()
  220064. {
  220065. #if JUCE_USE_XSHM
  220066. if (! shmCompletedDrawing)
  220067. {
  220068. startTimer (repaintTimerPeriod);
  220069. return;
  220070. }
  220071. #endif
  220072. peer->clearMaskedRegion();
  220073. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  220074. regionsNeedingRepaint.clear();
  220075. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  220076. if (! totalArea.isEmpty())
  220077. {
  220078. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  220079. || image.getHeight() < totalArea.getHeight())
  220080. {
  220081. #if JUCE_USE_XSHM
  220082. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  220083. : Image::RGB,
  220084. #else
  220085. image = Image (new XBitmapImage (Image::RGB,
  220086. #endif
  220087. (totalArea.getWidth() + 31) & ~31,
  220088. (totalArea.getHeight() + 31) & ~31,
  220089. false, peer->depth, peer->visual));
  220090. }
  220091. startTimer (repaintTimerPeriod);
  220092. RectangleList adjustedList (originalRepaintRegion);
  220093. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  220094. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  220095. if (peer->depth == 32)
  220096. {
  220097. RectangleList::Iterator i (originalRepaintRegion);
  220098. while (i.next())
  220099. image.clear (*i.getRectangle() - totalArea.getPosition());
  220100. }
  220101. peer->handlePaint (context);
  220102. if (! peer->maskedRegion.isEmpty())
  220103. originalRepaintRegion.subtract (peer->maskedRegion);
  220104. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  220105. {
  220106. #if JUCE_USE_XSHM
  220107. shmCompletedDrawing = false;
  220108. #endif
  220109. const Rectangle<int>& r = *i.getRectangle();
  220110. static_cast<XBitmapImage*> (image.getSharedImage())
  220111. ->blitToWindow (peer->windowH,
  220112. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  220113. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  220114. }
  220115. }
  220116. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  220117. startTimer (repaintTimerPeriod);
  220118. }
  220119. #if JUCE_USE_XSHM
  220120. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  220121. #endif
  220122. private:
  220123. enum { repaintTimerPeriod = 1000 / 100 };
  220124. LinuxComponentPeer* const peer;
  220125. Image image;
  220126. uint32 lastTimeImageUsed;
  220127. RectangleList regionsNeedingRepaint;
  220128. #if JUCE_USE_XSHM
  220129. bool useARGBImagesForRendering, shmCompletedDrawing;
  220130. #endif
  220131. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager);
  220132. };
  220133. ScopedPointer <LinuxRepaintManager> repainter;
  220134. friend class LinuxRepaintManager;
  220135. Window windowH, parentWindow;
  220136. int wx, wy, ww, wh;
  220137. Image taskbarImage;
  220138. bool fullScreen, mapped;
  220139. Visual* visual;
  220140. int depth;
  220141. BorderSize<int> windowBorder;
  220142. struct MotifWmHints
  220143. {
  220144. unsigned long flags;
  220145. unsigned long functions;
  220146. unsigned long decorations;
  220147. long input_mode;
  220148. unsigned long status;
  220149. };
  220150. static void updateKeyStates (const int keycode, const bool press) throw()
  220151. {
  220152. const int keybyte = keycode >> 3;
  220153. const int keybit = (1 << (keycode & 7));
  220154. if (press)
  220155. Keys::keyStates [keybyte] |= keybit;
  220156. else
  220157. Keys::keyStates [keybyte] &= ~keybit;
  220158. }
  220159. static void updateKeyModifiers (const int status) throw()
  220160. {
  220161. int keyMods = 0;
  220162. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  220163. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  220164. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  220165. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  220166. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  220167. Keys::capsLock = ((status & LockMask) != 0);
  220168. }
  220169. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  220170. {
  220171. int modifier = 0;
  220172. bool isModifier = true;
  220173. switch (sym)
  220174. {
  220175. case XK_Shift_L:
  220176. case XK_Shift_R:
  220177. modifier = ModifierKeys::shiftModifier;
  220178. break;
  220179. case XK_Control_L:
  220180. case XK_Control_R:
  220181. modifier = ModifierKeys::ctrlModifier;
  220182. break;
  220183. case XK_Alt_L:
  220184. case XK_Alt_R:
  220185. modifier = ModifierKeys::altModifier;
  220186. break;
  220187. case XK_Num_Lock:
  220188. if (press)
  220189. Keys::numLock = ! Keys::numLock;
  220190. break;
  220191. case XK_Caps_Lock:
  220192. if (press)
  220193. Keys::capsLock = ! Keys::capsLock;
  220194. break;
  220195. case XK_Scroll_Lock:
  220196. break;
  220197. default:
  220198. isModifier = false;
  220199. break;
  220200. }
  220201. if (modifier != 0)
  220202. {
  220203. if (press)
  220204. currentModifiers = currentModifiers.withFlags (modifier);
  220205. else
  220206. currentModifiers = currentModifiers.withoutFlags (modifier);
  220207. }
  220208. return isModifier;
  220209. }
  220210. // Alt and Num lock are not defined by standard X
  220211. // modifier constants: check what they're mapped to
  220212. static void updateModifierMappings() throw()
  220213. {
  220214. ScopedXLock xlock;
  220215. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  220216. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  220217. Keys::AltMask = 0;
  220218. Keys::NumLockMask = 0;
  220219. XModifierKeymap* mapping = XGetModifierMapping (display);
  220220. if (mapping)
  220221. {
  220222. for (int i = 0; i < 8; i++)
  220223. {
  220224. if (mapping->modifiermap [i << 1] == altLeftCode)
  220225. Keys::AltMask = 1 << i;
  220226. else if (mapping->modifiermap [i << 1] == numLockCode)
  220227. Keys::NumLockMask = 1 << i;
  220228. }
  220229. XFreeModifiermap (mapping);
  220230. }
  220231. }
  220232. void removeWindowDecorations (Window wndH)
  220233. {
  220234. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  220235. if (hints != None)
  220236. {
  220237. MotifWmHints motifHints;
  220238. zerostruct (motifHints);
  220239. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  220240. motifHints.decorations = 0;
  220241. ScopedXLock xlock;
  220242. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220243. (unsigned char*) &motifHints, 4);
  220244. }
  220245. hints = XInternAtom (display, "_WIN_HINTS", True);
  220246. if (hints != None)
  220247. {
  220248. long gnomeHints = 0;
  220249. ScopedXLock xlock;
  220250. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220251. (unsigned char*) &gnomeHints, 1);
  220252. }
  220253. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  220254. if (hints != None)
  220255. {
  220256. long kwmHints = 2; /*KDE_tinyDecoration*/
  220257. ScopedXLock xlock;
  220258. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220259. (unsigned char*) &kwmHints, 1);
  220260. }
  220261. }
  220262. void addWindowButtons (Window wndH)
  220263. {
  220264. ScopedXLock xlock;
  220265. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  220266. if (hints != None)
  220267. {
  220268. MotifWmHints motifHints;
  220269. zerostruct (motifHints);
  220270. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  220271. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  220272. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  220273. if ((styleFlags & windowHasCloseButton) != 0)
  220274. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  220275. if ((styleFlags & windowHasMinimiseButton) != 0)
  220276. {
  220277. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  220278. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  220279. }
  220280. if ((styleFlags & windowHasMaximiseButton) != 0)
  220281. {
  220282. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  220283. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  220284. }
  220285. if ((styleFlags & windowIsResizable) != 0)
  220286. {
  220287. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  220288. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  220289. }
  220290. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  220291. }
  220292. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  220293. if (hints != None)
  220294. {
  220295. int netHints [6];
  220296. int num = 0;
  220297. if ((styleFlags & windowIsResizable) != 0)
  220298. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  220299. if ((styleFlags & windowHasMaximiseButton) != 0)
  220300. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  220301. if ((styleFlags & windowHasMinimiseButton) != 0)
  220302. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  220303. if ((styleFlags & windowHasCloseButton) != 0)
  220304. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  220305. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  220306. }
  220307. }
  220308. void setWindowType()
  220309. {
  220310. int netHints [2];
  220311. int numHints = 0;
  220312. if ((styleFlags & windowIsTemporary) != 0
  220313. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  220314. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  220315. else
  220316. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  220317. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  220318. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  220319. (unsigned char*) &netHints, numHints);
  220320. numHints = 0;
  220321. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  220322. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  220323. if (component->isAlwaysOnTop())
  220324. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  220325. if (numHints > 0)
  220326. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  220327. (unsigned char*) &netHints, numHints);
  220328. }
  220329. void createWindow()
  220330. {
  220331. ScopedXLock xlock;
  220332. Atoms::initialiseAtoms();
  220333. resetDragAndDrop();
  220334. // Get defaults for various properties
  220335. const int screen = DefaultScreen (display);
  220336. Window root = RootWindow (display, screen);
  220337. // Try to obtain a 32-bit visual or fallback to 24 or 16
  220338. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  220339. if (visual == 0)
  220340. {
  220341. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  220342. Process::terminate();
  220343. }
  220344. // Create and install a colormap suitable fr our visual
  220345. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  220346. XInstallColormap (display, colormap);
  220347. // Set up the window attributes
  220348. XSetWindowAttributes swa;
  220349. swa.border_pixel = 0;
  220350. swa.background_pixmap = None;
  220351. swa.colormap = colormap;
  220352. swa.event_mask = getAllEventsMask();
  220353. windowH = XCreateWindow (display, root,
  220354. 0, 0, 1, 1,
  220355. 0, depth, InputOutput, visual,
  220356. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  220357. &swa);
  220358. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  220359. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  220360. GrabModeAsync, GrabModeAsync, None, None);
  220361. // Set the window context to identify the window handle object
  220362. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  220363. {
  220364. // Failed
  220365. jassertfalse;
  220366. Logger::outputDebugString ("Failed to create context information for window.\n");
  220367. XDestroyWindow (display, windowH);
  220368. windowH = 0;
  220369. return;
  220370. }
  220371. // Set window manager hints
  220372. XWMHints* wmHints = XAllocWMHints();
  220373. wmHints->flags = InputHint | StateHint;
  220374. wmHints->input = True; // Locally active input model
  220375. wmHints->initial_state = NormalState;
  220376. XSetWMHints (display, windowH, wmHints);
  220377. XFree (wmHints);
  220378. // Set the window type
  220379. setWindowType();
  220380. // Define decoration
  220381. if ((styleFlags & windowHasTitleBar) == 0)
  220382. removeWindowDecorations (windowH);
  220383. else
  220384. addWindowButtons (windowH);
  220385. setTitle (getComponent()->getName());
  220386. // Associate the PID, allowing to be shut down when something goes wrong
  220387. unsigned long pid = getpid();
  220388. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  220389. (unsigned char*) &pid, 1);
  220390. // Set window manager protocols
  220391. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  220392. (unsigned char*) Atoms::ProtocolList, 2);
  220393. // Set drag and drop flags
  220394. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  220395. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  220396. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  220397. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  220398. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  220399. (const unsigned char*) "", 0);
  220400. unsigned long dndVersion = Atoms::DndVersion;
  220401. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  220402. (const unsigned char*) &dndVersion, 1);
  220403. // Initialise the pointer and keyboard mapping
  220404. // This is not the same as the logical pointer mapping the X server uses:
  220405. // we don't mess with this.
  220406. static bool mappingInitialised = false;
  220407. if (! mappingInitialised)
  220408. {
  220409. mappingInitialised = true;
  220410. const int numButtons = XGetPointerMapping (display, 0, 0);
  220411. if (numButtons == 2)
  220412. {
  220413. pointerMap[0] = Keys::LeftButton;
  220414. pointerMap[1] = Keys::RightButton;
  220415. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  220416. }
  220417. else if (numButtons >= 3)
  220418. {
  220419. pointerMap[0] = Keys::LeftButton;
  220420. pointerMap[1] = Keys::MiddleButton;
  220421. pointerMap[2] = Keys::RightButton;
  220422. if (numButtons >= 5)
  220423. {
  220424. pointerMap[3] = Keys::WheelUp;
  220425. pointerMap[4] = Keys::WheelDown;
  220426. }
  220427. }
  220428. updateModifierMappings();
  220429. }
  220430. }
  220431. void destroyWindow()
  220432. {
  220433. ScopedXLock xlock;
  220434. XPointer handlePointer;
  220435. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  220436. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  220437. XDestroyWindow (display, windowH);
  220438. // Wait for it to complete and then remove any events for this
  220439. // window from the event queue.
  220440. XSync (display, false);
  220441. XEvent event;
  220442. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  220443. {}
  220444. }
  220445. static int getAllEventsMask() throw()
  220446. {
  220447. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  220448. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  220449. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  220450. }
  220451. static int64 getEventTime (::Time t)
  220452. {
  220453. static int64 eventTimeOffset = 0x12345678;
  220454. const int64 thisMessageTime = t;
  220455. if (eventTimeOffset == 0x12345678)
  220456. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  220457. return eventTimeOffset + thisMessageTime;
  220458. }
  220459. void updateBorderSize()
  220460. {
  220461. if ((styleFlags & windowHasTitleBar) == 0)
  220462. {
  220463. windowBorder = BorderSize<int> (0);
  220464. }
  220465. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  220466. {
  220467. ScopedXLock xlock;
  220468. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  220469. if (hints != None)
  220470. {
  220471. unsigned char* data = 0;
  220472. unsigned long nitems, bytesLeft;
  220473. Atom actualType;
  220474. int actualFormat;
  220475. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  220476. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220477. &data) == Success)
  220478. {
  220479. const unsigned long* const sizes = (const unsigned long*) data;
  220480. if (actualFormat == 32)
  220481. windowBorder = BorderSize<int> ((int) sizes[2], (int) sizes[0],
  220482. (int) sizes[3], (int) sizes[1]);
  220483. XFree (data);
  220484. }
  220485. }
  220486. }
  220487. }
  220488. void updateBounds()
  220489. {
  220490. jassert (windowH != 0);
  220491. if (windowH != 0)
  220492. {
  220493. Window root, child;
  220494. unsigned int bw, depth;
  220495. ScopedXLock xlock;
  220496. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220497. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  220498. &bw, &depth))
  220499. {
  220500. wx = wy = ww = wh = 0;
  220501. }
  220502. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  220503. {
  220504. wx = wy = 0;
  220505. }
  220506. }
  220507. }
  220508. void resetDragAndDrop()
  220509. {
  220510. dragAndDropFiles.clear();
  220511. lastDropPos = Point<int> (-1, -1);
  220512. dragAndDropCurrentMimeType = 0;
  220513. dragAndDropSourceWindow = 0;
  220514. srcMimeTypeAtomList.clear();
  220515. }
  220516. void sendDragAndDropMessage (XClientMessageEvent& msg)
  220517. {
  220518. msg.type = ClientMessage;
  220519. msg.display = display;
  220520. msg.window = dragAndDropSourceWindow;
  220521. msg.format = 32;
  220522. msg.data.l[0] = windowH;
  220523. ScopedXLock xlock;
  220524. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  220525. }
  220526. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  220527. {
  220528. XClientMessageEvent msg;
  220529. zerostruct (msg);
  220530. msg.message_type = Atoms::XdndStatus;
  220531. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  220532. msg.data.l[4] = dropAction;
  220533. sendDragAndDropMessage (msg);
  220534. }
  220535. void sendDragAndDropLeave()
  220536. {
  220537. XClientMessageEvent msg;
  220538. zerostruct (msg);
  220539. msg.message_type = Atoms::XdndLeave;
  220540. sendDragAndDropMessage (msg);
  220541. }
  220542. void sendDragAndDropFinish()
  220543. {
  220544. XClientMessageEvent msg;
  220545. zerostruct (msg);
  220546. msg.message_type = Atoms::XdndFinished;
  220547. sendDragAndDropMessage (msg);
  220548. }
  220549. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  220550. {
  220551. if ((clientMsg->data.l[1] & 1) == 0)
  220552. {
  220553. sendDragAndDropLeave();
  220554. if (dragAndDropFiles.size() > 0)
  220555. handleFileDragExit (dragAndDropFiles);
  220556. dragAndDropFiles.clear();
  220557. }
  220558. }
  220559. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  220560. {
  220561. if (dragAndDropSourceWindow == 0)
  220562. return;
  220563. dragAndDropSourceWindow = clientMsg->data.l[0];
  220564. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  220565. (int) clientMsg->data.l[2] & 0xffff);
  220566. dropPos -= getScreenPosition();
  220567. if (lastDropPos != dropPos)
  220568. {
  220569. lastDropPos = dropPos;
  220570. dragAndDropTimestamp = clientMsg->data.l[3];
  220571. Atom targetAction = Atoms::XdndActionCopy;
  220572. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  220573. {
  220574. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  220575. {
  220576. targetAction = Atoms::allowedActions[i];
  220577. break;
  220578. }
  220579. }
  220580. sendDragAndDropStatus (true, targetAction);
  220581. if (dragAndDropFiles.size() == 0)
  220582. updateDraggedFileList (clientMsg);
  220583. if (dragAndDropFiles.size() > 0)
  220584. handleFileDragMove (dragAndDropFiles, dropPos);
  220585. }
  220586. }
  220587. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  220588. {
  220589. if (dragAndDropFiles.size() == 0)
  220590. updateDraggedFileList (clientMsg);
  220591. const StringArray files (dragAndDropFiles);
  220592. const Point<int> lastPos (lastDropPos);
  220593. sendDragAndDropFinish();
  220594. resetDragAndDrop();
  220595. if (files.size() > 0)
  220596. handleFileDragDrop (files, lastPos);
  220597. }
  220598. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  220599. {
  220600. dragAndDropFiles.clear();
  220601. srcMimeTypeAtomList.clear();
  220602. dragAndDropCurrentMimeType = 0;
  220603. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  220604. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  220605. {
  220606. dragAndDropSourceWindow = 0;
  220607. return;
  220608. }
  220609. dragAndDropSourceWindow = clientMsg->data.l[0];
  220610. if ((clientMsg->data.l[1] & 1) != 0)
  220611. {
  220612. Atom actual;
  220613. int format;
  220614. unsigned long count = 0, remaining = 0;
  220615. unsigned char* data = 0;
  220616. ScopedXLock xlock;
  220617. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  220618. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  220619. &count, &remaining, &data);
  220620. if (data != 0)
  220621. {
  220622. if (actual == XA_ATOM && format == 32 && count != 0)
  220623. {
  220624. const unsigned long* const types = (const unsigned long*) data;
  220625. for (unsigned int i = 0; i < count; ++i)
  220626. if (types[i] != None)
  220627. srcMimeTypeAtomList.add (types[i]);
  220628. }
  220629. XFree (data);
  220630. }
  220631. }
  220632. if (srcMimeTypeAtomList.size() == 0)
  220633. {
  220634. for (int i = 2; i < 5; ++i)
  220635. if (clientMsg->data.l[i] != None)
  220636. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  220637. if (srcMimeTypeAtomList.size() == 0)
  220638. {
  220639. dragAndDropSourceWindow = 0;
  220640. return;
  220641. }
  220642. }
  220643. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  220644. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  220645. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  220646. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  220647. handleDragAndDropPosition (clientMsg);
  220648. }
  220649. void handleDragAndDropSelection (const XEvent* const evt)
  220650. {
  220651. dragAndDropFiles.clear();
  220652. if (evt->xselection.property != 0)
  220653. {
  220654. StringArray lines;
  220655. {
  220656. MemoryBlock dropData;
  220657. for (;;)
  220658. {
  220659. Atom actual;
  220660. uint8* data = 0;
  220661. unsigned long count = 0, remaining = 0;
  220662. int format = 0;
  220663. ScopedXLock xlock;
  220664. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  220665. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  220666. &format, &count, &remaining, &data) == Success)
  220667. {
  220668. dropData.append (data, count * format / 8);
  220669. XFree (data);
  220670. if (remaining == 0)
  220671. break;
  220672. }
  220673. else
  220674. {
  220675. XFree (data);
  220676. break;
  220677. }
  220678. }
  220679. lines.addLines (dropData.toString());
  220680. }
  220681. for (int i = 0; i < lines.size(); ++i)
  220682. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  220683. dragAndDropFiles.trim();
  220684. dragAndDropFiles.removeEmptyStrings();
  220685. }
  220686. }
  220687. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  220688. {
  220689. dragAndDropFiles.clear();
  220690. if (dragAndDropSourceWindow != None
  220691. && dragAndDropCurrentMimeType != 0)
  220692. {
  220693. dragAndDropTimestamp = clientMsg->data.l[2];
  220694. ScopedXLock xlock;
  220695. XConvertSelection (display,
  220696. Atoms::XdndSelection,
  220697. dragAndDropCurrentMimeType,
  220698. XInternAtom (display, "JXSelectionWindowProperty", 0),
  220699. windowH,
  220700. dragAndDropTimestamp);
  220701. }
  220702. }
  220703. StringArray dragAndDropFiles;
  220704. int dragAndDropTimestamp;
  220705. Point<int> lastDropPos;
  220706. Atom dragAndDropCurrentMimeType;
  220707. Window dragAndDropSourceWindow;
  220708. Array <Atom> srcMimeTypeAtomList;
  220709. static int pointerMap[5];
  220710. static Point<int> lastMousePos;
  220711. static void clearLastMousePos() throw()
  220712. {
  220713. lastMousePos = Point<int> (0x100000, 0x100000);
  220714. }
  220715. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer);
  220716. };
  220717. ModifierKeys LinuxComponentPeer::currentModifiers;
  220718. bool LinuxComponentPeer::isActiveApplication = false;
  220719. int LinuxComponentPeer::pointerMap[5];
  220720. Point<int> LinuxComponentPeer::lastMousePos;
  220721. bool Process::isForegroundProcess()
  220722. {
  220723. return LinuxComponentPeer::isActiveApplication;
  220724. }
  220725. void ModifierKeys::updateCurrentModifiers() throw()
  220726. {
  220727. currentModifiers = LinuxComponentPeer::currentModifiers;
  220728. }
  220729. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  220730. {
  220731. Window root, child;
  220732. int x, y, winx, winy;
  220733. unsigned int mask;
  220734. int mouseMods = 0;
  220735. ScopedXLock xlock;
  220736. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  220737. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  220738. {
  220739. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  220740. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  220741. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  220742. }
  220743. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  220744. return LinuxComponentPeer::currentModifiers;
  220745. }
  220746. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  220747. {
  220748. if (enableOrDisable)
  220749. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  220750. }
  220751. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  220752. {
  220753. return new LinuxComponentPeer (this, styleFlags);
  220754. }
  220755. // (this callback is hooked up in the messaging code)
  220756. void juce_windowMessageReceive (XEvent* event)
  220757. {
  220758. if (event->xany.window != None)
  220759. {
  220760. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  220761. if (ComponentPeer::isValidPeer (peer))
  220762. peer->handleWindowMessage (event);
  220763. }
  220764. else
  220765. {
  220766. switch (event->xany.type)
  220767. {
  220768. case KeymapNotify:
  220769. {
  220770. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  220771. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  220772. break;
  220773. }
  220774. default:
  220775. break;
  220776. }
  220777. }
  220778. }
  220779. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  220780. {
  220781. if (display == 0)
  220782. return;
  220783. #if JUCE_USE_XINERAMA
  220784. int major_opcode, first_event, first_error;
  220785. ScopedXLock xlock;
  220786. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  220787. {
  220788. typedef Bool (*tXineramaIsActive) (Display*);
  220789. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  220790. static tXineramaIsActive xXineramaIsActive = 0;
  220791. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  220792. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  220793. {
  220794. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  220795. if (h == 0)
  220796. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  220797. if (h != 0)
  220798. {
  220799. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  220800. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  220801. }
  220802. }
  220803. if (xXineramaIsActive != 0
  220804. && xXineramaQueryScreens != 0
  220805. && xXineramaIsActive (display))
  220806. {
  220807. int numMonitors = 0;
  220808. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  220809. if (screens != 0)
  220810. {
  220811. for (int i = numMonitors; --i >= 0;)
  220812. {
  220813. int index = screens[i].screen_number;
  220814. if (index >= 0)
  220815. {
  220816. while (monitorCoords.size() < index)
  220817. monitorCoords.add (Rectangle<int>());
  220818. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  220819. screens[i].y_org,
  220820. screens[i].width,
  220821. screens[i].height));
  220822. }
  220823. }
  220824. XFree (screens);
  220825. }
  220826. }
  220827. }
  220828. if (monitorCoords.size() == 0)
  220829. #endif
  220830. {
  220831. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  220832. if (hints != None)
  220833. {
  220834. const int numMonitors = ScreenCount (display);
  220835. for (int i = 0; i < numMonitors; ++i)
  220836. {
  220837. Window root = RootWindow (display, i);
  220838. unsigned long nitems, bytesLeft;
  220839. Atom actualType;
  220840. int actualFormat;
  220841. unsigned char* data = 0;
  220842. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  220843. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220844. &data) == Success)
  220845. {
  220846. const long* const position = (const long*) data;
  220847. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  220848. monitorCoords.add (Rectangle<int> (position[0], position[1],
  220849. position[2], position[3]));
  220850. XFree (data);
  220851. }
  220852. }
  220853. }
  220854. if (monitorCoords.size() == 0)
  220855. {
  220856. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  220857. DisplayHeight (display, DefaultScreen (display))));
  220858. }
  220859. }
  220860. }
  220861. void Desktop::createMouseInputSources()
  220862. {
  220863. mouseSources.add (new MouseInputSource (0, true));
  220864. }
  220865. bool Desktop::canUseSemiTransparentWindows() throw()
  220866. {
  220867. int matchedDepth = 0;
  220868. const int desiredDepth = 32;
  220869. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  220870. && (matchedDepth == desiredDepth);
  220871. }
  220872. const Point<int> MouseInputSource::getCurrentMousePosition()
  220873. {
  220874. Window root, child;
  220875. int x, y, winx, winy;
  220876. unsigned int mask;
  220877. ScopedXLock xlock;
  220878. if (XQueryPointer (display,
  220879. RootWindow (display, DefaultScreen (display)),
  220880. &root, &child,
  220881. &x, &y, &winx, &winy, &mask) == False)
  220882. {
  220883. // Pointer not on the default screen
  220884. x = y = -1;
  220885. }
  220886. return Point<int> (x, y);
  220887. }
  220888. void Desktop::setMousePosition (const Point<int>& newPosition)
  220889. {
  220890. ScopedXLock xlock;
  220891. Window root = RootWindow (display, DefaultScreen (display));
  220892. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  220893. }
  220894. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  220895. {
  220896. return upright;
  220897. }
  220898. static bool screenSaverAllowed = true;
  220899. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  220900. {
  220901. if (screenSaverAllowed != isEnabled)
  220902. {
  220903. screenSaverAllowed = isEnabled;
  220904. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  220905. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  220906. if (xScreenSaverSuspend == 0)
  220907. {
  220908. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  220909. if (h != 0)
  220910. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  220911. }
  220912. ScopedXLock xlock;
  220913. if (xScreenSaverSuspend != 0)
  220914. xScreenSaverSuspend (display, ! isEnabled);
  220915. }
  220916. }
  220917. bool Desktop::isScreenSaverEnabled()
  220918. {
  220919. return screenSaverAllowed;
  220920. }
  220921. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  220922. {
  220923. ScopedXLock xlock;
  220924. const unsigned int imageW = image.getWidth();
  220925. const unsigned int imageH = image.getHeight();
  220926. #if JUCE_USE_XCURSOR
  220927. {
  220928. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  220929. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  220930. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  220931. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  220932. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  220933. static tXcursorImageCreate xXcursorImageCreate = 0;
  220934. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  220935. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  220936. static bool hasBeenLoaded = false;
  220937. if (! hasBeenLoaded)
  220938. {
  220939. hasBeenLoaded = true;
  220940. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  220941. if (h != 0)
  220942. {
  220943. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  220944. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  220945. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  220946. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  220947. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  220948. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  220949. || ! xXcursorSupportsARGB (display))
  220950. xXcursorSupportsARGB = 0;
  220951. }
  220952. }
  220953. if (xXcursorSupportsARGB != 0)
  220954. {
  220955. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  220956. if (xcImage != 0)
  220957. {
  220958. xcImage->xhot = hotspotX;
  220959. xcImage->yhot = hotspotY;
  220960. XcursorPixel* dest = xcImage->pixels;
  220961. for (int y = 0; y < (int) imageH; ++y)
  220962. for (int x = 0; x < (int) imageW; ++x)
  220963. *dest++ = image.getPixelAt (x, y).getARGB();
  220964. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  220965. xXcursorImageDestroy (xcImage);
  220966. if (result != 0)
  220967. return result;
  220968. }
  220969. }
  220970. }
  220971. #endif
  220972. Window root = RootWindow (display, DefaultScreen (display));
  220973. unsigned int cursorW, cursorH;
  220974. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  220975. return 0;
  220976. Image im (Image::ARGB, cursorW, cursorH, true);
  220977. {
  220978. Graphics g (im);
  220979. if (imageW > cursorW || imageH > cursorH)
  220980. {
  220981. hotspotX = (hotspotX * cursorW) / imageW;
  220982. hotspotY = (hotspotY * cursorH) / imageH;
  220983. g.drawImageWithin (image, 0, 0, imageW, imageH,
  220984. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  220985. false);
  220986. }
  220987. else
  220988. {
  220989. g.drawImageAt (image, 0, 0);
  220990. }
  220991. }
  220992. const int stride = (cursorW + 7) >> 3;
  220993. HeapBlock <char> maskPlane, sourcePlane;
  220994. maskPlane.calloc (stride * cursorH);
  220995. sourcePlane.calloc (stride * cursorH);
  220996. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220997. for (int y = cursorH; --y >= 0;)
  220998. {
  220999. for (int x = cursorW; --x >= 0;)
  221000. {
  221001. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  221002. const int offset = y * stride + (x >> 3);
  221003. const Colour c (im.getPixelAt (x, y));
  221004. if (c.getAlpha() >= 128)
  221005. maskPlane[offset] |= mask;
  221006. if (c.getBrightness() >= 0.5f)
  221007. sourcePlane[offset] |= mask;
  221008. }
  221009. }
  221010. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221011. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221012. XColor white, black;
  221013. black.red = black.green = black.blue = 0;
  221014. white.red = white.green = white.blue = 0xffff;
  221015. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  221016. XFreePixmap (display, sourcePixmap);
  221017. XFreePixmap (display, maskPixmap);
  221018. return result;
  221019. }
  221020. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  221021. {
  221022. ScopedXLock xlock;
  221023. if (cursorHandle != 0)
  221024. XFreeCursor (display, (Cursor) cursorHandle);
  221025. }
  221026. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  221027. {
  221028. unsigned int shape;
  221029. switch (type)
  221030. {
  221031. case NormalCursor: return None; // Use parent cursor
  221032. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  221033. case WaitCursor: shape = XC_watch; break;
  221034. case IBeamCursor: shape = XC_xterm; break;
  221035. case PointingHandCursor: shape = XC_hand2; break;
  221036. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  221037. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  221038. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  221039. case TopEdgeResizeCursor: shape = XC_top_side; break;
  221040. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  221041. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  221042. case RightEdgeResizeCursor: shape = XC_right_side; break;
  221043. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  221044. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  221045. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  221046. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  221047. case CrosshairCursor: shape = XC_crosshair; break;
  221048. case DraggingHandCursor:
  221049. {
  221050. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  221051. 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,
  221052. 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 };
  221053. const int dragHandDataSize = 99;
  221054. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  221055. }
  221056. case CopyingCursor:
  221057. {
  221058. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  221059. 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,
  221060. 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,
  221061. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  221062. const int copyCursorSize = 119;
  221063. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  221064. }
  221065. default:
  221066. jassertfalse;
  221067. return None;
  221068. }
  221069. ScopedXLock xlock;
  221070. return (void*) XCreateFontCursor (display, shape);
  221071. }
  221072. void MouseCursor::showInWindow (ComponentPeer* peer) const
  221073. {
  221074. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  221075. if (lp != 0)
  221076. lp->showMouseCursor ((Cursor) getHandle());
  221077. }
  221078. void MouseCursor::showInAllWindows() const
  221079. {
  221080. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  221081. showInWindow (ComponentPeer::getPeer (i));
  221082. }
  221083. const Image juce_createIconForFile (const File& file)
  221084. {
  221085. return Image::null;
  221086. }
  221087. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  221088. {
  221089. return createSoftwareImage (format, width, height, clearImage);
  221090. }
  221091. #if JUCE_OPENGL
  221092. class WindowedGLContext : public OpenGLContext
  221093. {
  221094. public:
  221095. WindowedGLContext (Component* const component,
  221096. const OpenGLPixelFormat& pixelFormat_,
  221097. GLXContext sharedContext)
  221098. : renderContext (0),
  221099. embeddedWindow (0),
  221100. pixelFormat (pixelFormat_),
  221101. swapInterval (0)
  221102. {
  221103. jassert (component != 0);
  221104. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  221105. if (peer == 0)
  221106. return;
  221107. ScopedXLock xlock;
  221108. XSync (display, False);
  221109. GLint attribs [64];
  221110. int n = 0;
  221111. attribs[n++] = GLX_RGBA;
  221112. attribs[n++] = GLX_DOUBLEBUFFER;
  221113. attribs[n++] = GLX_RED_SIZE;
  221114. attribs[n++] = pixelFormat.redBits;
  221115. attribs[n++] = GLX_GREEN_SIZE;
  221116. attribs[n++] = pixelFormat.greenBits;
  221117. attribs[n++] = GLX_BLUE_SIZE;
  221118. attribs[n++] = pixelFormat.blueBits;
  221119. attribs[n++] = GLX_ALPHA_SIZE;
  221120. attribs[n++] = pixelFormat.alphaBits;
  221121. attribs[n++] = GLX_DEPTH_SIZE;
  221122. attribs[n++] = pixelFormat.depthBufferBits;
  221123. attribs[n++] = GLX_STENCIL_SIZE;
  221124. attribs[n++] = pixelFormat.stencilBufferBits;
  221125. attribs[n++] = GLX_ACCUM_RED_SIZE;
  221126. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  221127. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  221128. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  221129. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  221130. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  221131. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  221132. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  221133. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  221134. attribs[n++] = None;
  221135. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  221136. if (bestVisual == 0)
  221137. return;
  221138. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  221139. Window windowH = (Window) peer->getNativeHandle();
  221140. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  221141. XSetWindowAttributes swa;
  221142. swa.colormap = colourMap;
  221143. swa.border_pixel = 0;
  221144. swa.event_mask = ExposureMask | StructureNotifyMask;
  221145. embeddedWindow = XCreateWindow (display, windowH,
  221146. 0, 0, 1, 1, 0,
  221147. bestVisual->depth,
  221148. InputOutput,
  221149. bestVisual->visual,
  221150. CWBorderPixel | CWColormap | CWEventMask,
  221151. &swa);
  221152. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  221153. XMapWindow (display, embeddedWindow);
  221154. XFreeColormap (display, colourMap);
  221155. XFree (bestVisual);
  221156. XSync (display, False);
  221157. }
  221158. ~WindowedGLContext()
  221159. {
  221160. ScopedXLock xlock;
  221161. deleteContext();
  221162. XUnmapWindow (display, embeddedWindow);
  221163. XDestroyWindow (display, embeddedWindow);
  221164. }
  221165. void deleteContext()
  221166. {
  221167. makeInactive();
  221168. if (renderContext != 0)
  221169. {
  221170. ScopedXLock xlock;
  221171. glXDestroyContext (display, renderContext);
  221172. renderContext = 0;
  221173. }
  221174. }
  221175. bool makeActive() const throw()
  221176. {
  221177. jassert (renderContext != 0);
  221178. ScopedXLock xlock;
  221179. return glXMakeCurrent (display, embeddedWindow, renderContext)
  221180. && XSync (display, False);
  221181. }
  221182. bool makeInactive() const throw()
  221183. {
  221184. ScopedXLock xlock;
  221185. return (! isActive()) || glXMakeCurrent (display, None, 0);
  221186. }
  221187. bool isActive() const throw()
  221188. {
  221189. ScopedXLock xlock;
  221190. return glXGetCurrentContext() == renderContext;
  221191. }
  221192. const OpenGLPixelFormat getPixelFormat() const
  221193. {
  221194. return pixelFormat;
  221195. }
  221196. void* getRawContext() const throw()
  221197. {
  221198. return renderContext;
  221199. }
  221200. void updateWindowPosition (int x, int y, int w, int h, int)
  221201. {
  221202. ScopedXLock xlock;
  221203. XMoveResizeWindow (display, embeddedWindow,
  221204. x, y, jmax (1, w), jmax (1, h));
  221205. }
  221206. void swapBuffers()
  221207. {
  221208. ScopedXLock xlock;
  221209. glXSwapBuffers (display, embeddedWindow);
  221210. }
  221211. bool setSwapInterval (const int numFramesPerSwap)
  221212. {
  221213. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  221214. if (GLXSwapIntervalSGI != 0)
  221215. {
  221216. swapInterval = numFramesPerSwap;
  221217. GLXSwapIntervalSGI (numFramesPerSwap);
  221218. return true;
  221219. }
  221220. return false;
  221221. }
  221222. int getSwapInterval() const
  221223. {
  221224. return swapInterval;
  221225. }
  221226. void repaint()
  221227. {
  221228. }
  221229. GLXContext renderContext;
  221230. private:
  221231. Window embeddedWindow;
  221232. OpenGLPixelFormat pixelFormat;
  221233. int swapInterval;
  221234. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  221235. };
  221236. OpenGLContext* OpenGLComponent::createContext()
  221237. {
  221238. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  221239. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  221240. return (c->renderContext != 0) ? c.release() : 0;
  221241. }
  221242. void juce_glViewport (const int w, const int h)
  221243. {
  221244. glViewport (0, 0, w, h);
  221245. }
  221246. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  221247. OwnedArray <OpenGLPixelFormat>& results)
  221248. {
  221249. results.add (new OpenGLPixelFormat()); // xxx
  221250. }
  221251. #endif
  221252. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  221253. {
  221254. jassertfalse; // not implemented!
  221255. return false;
  221256. }
  221257. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  221258. {
  221259. jassertfalse; // not implemented!
  221260. return false;
  221261. }
  221262. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  221263. {
  221264. if (! isOnDesktop ())
  221265. addToDesktop (0);
  221266. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  221267. if (wp != 0)
  221268. {
  221269. wp->setTaskBarIcon (newImage);
  221270. setVisible (true);
  221271. toFront (false);
  221272. repaint();
  221273. }
  221274. }
  221275. void SystemTrayIconComponent::paint (Graphics& g)
  221276. {
  221277. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  221278. if (wp != 0)
  221279. {
  221280. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  221281. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221282. false);
  221283. }
  221284. }
  221285. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  221286. {
  221287. // xxx not yet implemented!
  221288. }
  221289. void PlatformUtilities::beep()
  221290. {
  221291. std::cout << "\a" << std::flush;
  221292. }
  221293. bool AlertWindow::showNativeDialogBox (const String& title,
  221294. const String& bodyText,
  221295. bool isOkCancel)
  221296. {
  221297. // use a non-native one for the time being..
  221298. if (isOkCancel)
  221299. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  221300. else
  221301. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  221302. return true;
  221303. }
  221304. const int KeyPress::spaceKey = XK_space & 0xff;
  221305. const int KeyPress::returnKey = XK_Return & 0xff;
  221306. const int KeyPress::escapeKey = XK_Escape & 0xff;
  221307. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  221308. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  221309. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  221310. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  221311. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  221312. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  221313. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  221314. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  221315. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  221316. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  221317. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  221318. const int KeyPress::tabKey = XK_Tab & 0xff;
  221319. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  221320. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  221321. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  221322. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  221323. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  221324. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  221325. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  221326. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  221327. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  221328. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  221329. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  221330. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  221331. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  221332. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  221333. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  221334. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  221335. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  221336. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  221337. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  221338. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  221339. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  221340. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  221341. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  221342. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  221343. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  221344. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  221345. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  221346. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  221347. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  221348. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  221349. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  221350. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  221351. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  221352. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  221353. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  221354. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  221355. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  221356. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  221357. #endif
  221358. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  221359. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  221360. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221361. // compiled on its own).
  221362. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  221363. namespace
  221364. {
  221365. void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  221366. {
  221367. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  221368. snd_pcm_hw_params_t* hwParams;
  221369. snd_pcm_hw_params_alloca (&hwParams);
  221370. for (int i = 0; ratesToTry[i] != 0; ++i)
  221371. {
  221372. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  221373. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  221374. {
  221375. rates.addIfNotAlreadyThere (ratesToTry[i]);
  221376. }
  221377. }
  221378. }
  221379. void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  221380. {
  221381. snd_pcm_hw_params_t *params;
  221382. snd_pcm_hw_params_alloca (&params);
  221383. if (snd_pcm_hw_params_any (handle, params) >= 0)
  221384. {
  221385. snd_pcm_hw_params_get_channels_min (params, minChans);
  221386. snd_pcm_hw_params_get_channels_max (params, maxChans);
  221387. }
  221388. }
  221389. void getDeviceProperties (const String& deviceID,
  221390. unsigned int& minChansOut,
  221391. unsigned int& maxChansOut,
  221392. unsigned int& minChansIn,
  221393. unsigned int& maxChansIn,
  221394. Array <int>& rates)
  221395. {
  221396. if (deviceID.isEmpty())
  221397. return;
  221398. snd_ctl_t* handle;
  221399. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221400. {
  221401. snd_pcm_info_t* info;
  221402. snd_pcm_info_alloca (&info);
  221403. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  221404. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  221405. snd_pcm_info_set_subdevice (info, 0);
  221406. if (snd_ctl_pcm_info (handle, info) >= 0)
  221407. {
  221408. snd_pcm_t* pcmHandle;
  221409. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  221410. {
  221411. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  221412. getDeviceSampleRates (pcmHandle, rates);
  221413. snd_pcm_close (pcmHandle);
  221414. }
  221415. }
  221416. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  221417. if (snd_ctl_pcm_info (handle, info) >= 0)
  221418. {
  221419. snd_pcm_t* pcmHandle;
  221420. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  221421. {
  221422. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  221423. if (rates.size() == 0)
  221424. getDeviceSampleRates (pcmHandle, rates);
  221425. snd_pcm_close (pcmHandle);
  221426. }
  221427. }
  221428. snd_ctl_close (handle);
  221429. }
  221430. }
  221431. }
  221432. class ALSADevice
  221433. {
  221434. public:
  221435. ALSADevice (const String& deviceID, bool forInput)
  221436. : handle (0),
  221437. bitDepth (16),
  221438. numChannelsRunning (0),
  221439. latency (0),
  221440. isInput (forInput),
  221441. isInterleaved (true)
  221442. {
  221443. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  221444. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  221445. SND_PCM_ASYNC));
  221446. }
  221447. ~ALSADevice()
  221448. {
  221449. if (handle != 0)
  221450. snd_pcm_close (handle);
  221451. }
  221452. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  221453. {
  221454. if (handle == 0)
  221455. return false;
  221456. snd_pcm_hw_params_t* hwParams;
  221457. snd_pcm_hw_params_alloca (&hwParams);
  221458. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  221459. return false;
  221460. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  221461. isInterleaved = false;
  221462. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  221463. isInterleaved = true;
  221464. else
  221465. {
  221466. jassertfalse;
  221467. return false;
  221468. }
  221469. enum { isFloatBit = 1 << 16, isLittleEndianBit = 1 << 17 };
  221470. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32 | isFloatBit | isLittleEndianBit,
  221471. SND_PCM_FORMAT_FLOAT_BE, 32 | isFloatBit,
  221472. SND_PCM_FORMAT_S32_LE, 32 | isLittleEndianBit,
  221473. SND_PCM_FORMAT_S32_BE, 32,
  221474. SND_PCM_FORMAT_S24_3LE, 24 | isLittleEndianBit,
  221475. SND_PCM_FORMAT_S24_3BE, 24,
  221476. SND_PCM_FORMAT_S16_LE, 16 | isLittleEndianBit,
  221477. SND_PCM_FORMAT_S16_BE, 16 };
  221478. bitDepth = 0;
  221479. for (int i = 0; i < numElementsInArray (formatsToTry); i += 2)
  221480. {
  221481. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  221482. {
  221483. bitDepth = formatsToTry [i + 1] & 255;
  221484. const bool isFloat = (formatsToTry [i + 1] & isFloatBit) != 0;
  221485. const bool isLittleEndian = (formatsToTry [i + 1] & isLittleEndianBit) != 0;
  221486. converter = createConverter (isInput, bitDepth, isFloat, isLittleEndian, numChannels);
  221487. break;
  221488. }
  221489. }
  221490. if (bitDepth == 0)
  221491. {
  221492. error = "device doesn't support a compatible PCM format";
  221493. DBG ("ALSA error: " + error + "\n");
  221494. return false;
  221495. }
  221496. int dir = 0;
  221497. unsigned int periods = 4;
  221498. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  221499. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  221500. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  221501. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  221502. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  221503. || failed (snd_pcm_hw_params (handle, hwParams)))
  221504. {
  221505. return false;
  221506. }
  221507. snd_pcm_uframes_t frames = 0;
  221508. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  221509. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  221510. latency = 0;
  221511. else
  221512. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  221513. snd_pcm_sw_params_t* swParams;
  221514. snd_pcm_sw_params_alloca (&swParams);
  221515. snd_pcm_uframes_t boundary;
  221516. if (failed (snd_pcm_sw_params_current (handle, swParams))
  221517. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  221518. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  221519. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  221520. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  221521. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  221522. || failed (snd_pcm_sw_params (handle, swParams)))
  221523. {
  221524. return false;
  221525. }
  221526. #if 0
  221527. // enable this to dump the config of the devices that get opened
  221528. snd_output_t* out;
  221529. snd_output_stdio_attach (&out, stderr, 0);
  221530. snd_pcm_hw_params_dump (hwParams, out);
  221531. snd_pcm_sw_params_dump (swParams, out);
  221532. #endif
  221533. numChannelsRunning = numChannels;
  221534. return true;
  221535. }
  221536. bool writeToOutputDevice (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  221537. {
  221538. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  221539. float** const data = outputChannelBuffer.getArrayOfChannels();
  221540. snd_pcm_sframes_t numDone = 0;
  221541. if (isInterleaved)
  221542. {
  221543. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  221544. for (int i = 0; i < numChannelsRunning; ++i)
  221545. converter->convertSamples (scratch.getData(), i, data[i], 0, numSamples);
  221546. numDone = snd_pcm_writei (handle, scratch.getData(), numSamples);
  221547. }
  221548. else
  221549. {
  221550. for (int i = 0; i < numChannelsRunning; ++i)
  221551. converter->convertSamples (data[i], data[i], numSamples);
  221552. numDone = snd_pcm_writen (handle, (void**) data, numSamples);
  221553. }
  221554. if (failed (numDone))
  221555. {
  221556. if (numDone == -EPIPE)
  221557. {
  221558. if (failed (snd_pcm_prepare (handle)))
  221559. return false;
  221560. }
  221561. else if (numDone != -ESTRPIPE)
  221562. return false;
  221563. }
  221564. return true;
  221565. }
  221566. bool readFromInputDevice (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  221567. {
  221568. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  221569. float** const data = inputChannelBuffer.getArrayOfChannels();
  221570. if (isInterleaved)
  221571. {
  221572. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  221573. scratch.fillWith (0); // (not clearing this data causes warnings in valgrind)
  221574. snd_pcm_sframes_t num = snd_pcm_readi (handle, scratch.getData(), numSamples);
  221575. if (failed (num))
  221576. {
  221577. if (num == -EPIPE)
  221578. {
  221579. if (failed (snd_pcm_prepare (handle)))
  221580. return false;
  221581. }
  221582. else if (num != -ESTRPIPE)
  221583. return false;
  221584. }
  221585. for (int i = 0; i < numChannelsRunning; ++i)
  221586. converter->convertSamples (data[i], 0, scratch.getData(), i, numSamples);
  221587. }
  221588. else
  221589. {
  221590. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  221591. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  221592. return false;
  221593. for (int i = 0; i < numChannelsRunning; ++i)
  221594. converter->convertSamples (data[i], data[i], numSamples);
  221595. }
  221596. return true;
  221597. }
  221598. snd_pcm_t* handle;
  221599. String error;
  221600. int bitDepth, numChannelsRunning, latency;
  221601. private:
  221602. const bool isInput;
  221603. bool isInterleaved;
  221604. MemoryBlock scratch;
  221605. ScopedPointer<AudioData::Converter> converter;
  221606. template <class SampleType>
  221607. struct ConverterHelper
  221608. {
  221609. static AudioData::Converter* createConverter (const bool forInput, const bool isLittleEndian, const int numInterleavedChannels)
  221610. {
  221611. if (forInput)
  221612. {
  221613. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  221614. if (isLittleEndian)
  221615. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  221616. else
  221617. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  221618. }
  221619. else
  221620. {
  221621. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  221622. if (isLittleEndian)
  221623. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  221624. else
  221625. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  221626. }
  221627. }
  221628. };
  221629. static AudioData::Converter* createConverter (const bool forInput, const int bitDepth, const bool isFloat, const bool isLittleEndian, const int numInterleavedChannels)
  221630. {
  221631. switch (bitDepth)
  221632. {
  221633. case 16: return ConverterHelper <AudioData::Int16>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  221634. case 24: return ConverterHelper <AudioData::Int24>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  221635. case 32: return isFloat ? ConverterHelper <AudioData::Float32>::createConverter (forInput, isLittleEndian, numInterleavedChannels)
  221636. : ConverterHelper <AudioData::Int32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  221637. default: jassertfalse; break; // unsupported format!
  221638. }
  221639. return 0;
  221640. }
  221641. bool failed (const int errorNum)
  221642. {
  221643. if (errorNum >= 0)
  221644. return false;
  221645. error = snd_strerror (errorNum);
  221646. DBG ("ALSA error: " + error + "\n");
  221647. return true;
  221648. }
  221649. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSADevice);
  221650. };
  221651. class ALSAThread : public Thread
  221652. {
  221653. public:
  221654. ALSAThread (const String& inputId_,
  221655. const String& outputId_)
  221656. : Thread ("Juce ALSA"),
  221657. sampleRate (0),
  221658. bufferSize (0),
  221659. outputLatency (0),
  221660. inputLatency (0),
  221661. callback (0),
  221662. inputId (inputId_),
  221663. outputId (outputId_),
  221664. numCallbacks (0),
  221665. inputChannelBuffer (1, 1),
  221666. outputChannelBuffer (1, 1)
  221667. {
  221668. initialiseRatesAndChannels();
  221669. }
  221670. ~ALSAThread()
  221671. {
  221672. close();
  221673. }
  221674. void open (BigInteger inputChannels,
  221675. BigInteger outputChannels,
  221676. const double sampleRate_,
  221677. const int bufferSize_)
  221678. {
  221679. close();
  221680. error = String::empty;
  221681. sampleRate = sampleRate_;
  221682. bufferSize = bufferSize_;
  221683. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  221684. inputChannelBuffer.clear();
  221685. inputChannelDataForCallback.clear();
  221686. currentInputChans.clear();
  221687. if (inputChannels.getHighestBit() >= 0)
  221688. {
  221689. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  221690. {
  221691. if (inputChannels[i])
  221692. {
  221693. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  221694. currentInputChans.setBit (i);
  221695. }
  221696. }
  221697. }
  221698. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  221699. outputChannelBuffer.clear();
  221700. outputChannelDataForCallback.clear();
  221701. currentOutputChans.clear();
  221702. if (outputChannels.getHighestBit() >= 0)
  221703. {
  221704. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  221705. {
  221706. if (outputChannels[i])
  221707. {
  221708. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  221709. currentOutputChans.setBit (i);
  221710. }
  221711. }
  221712. }
  221713. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  221714. {
  221715. outputDevice = new ALSADevice (outputId, false);
  221716. if (outputDevice->error.isNotEmpty())
  221717. {
  221718. error = outputDevice->error;
  221719. outputDevice = 0;
  221720. return;
  221721. }
  221722. currentOutputChans.setRange (0, minChansOut, true);
  221723. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  221724. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  221725. bufferSize))
  221726. {
  221727. error = outputDevice->error;
  221728. outputDevice = 0;
  221729. return;
  221730. }
  221731. outputLatency = outputDevice->latency;
  221732. }
  221733. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  221734. {
  221735. inputDevice = new ALSADevice (inputId, true);
  221736. if (inputDevice->error.isNotEmpty())
  221737. {
  221738. error = inputDevice->error;
  221739. inputDevice = 0;
  221740. return;
  221741. }
  221742. currentInputChans.setRange (0, minChansIn, true);
  221743. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  221744. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  221745. bufferSize))
  221746. {
  221747. error = inputDevice->error;
  221748. inputDevice = 0;
  221749. return;
  221750. }
  221751. inputLatency = inputDevice->latency;
  221752. }
  221753. if (outputDevice == 0 && inputDevice == 0)
  221754. {
  221755. error = "no channels";
  221756. return;
  221757. }
  221758. if (outputDevice != 0 && inputDevice != 0)
  221759. {
  221760. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  221761. }
  221762. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  221763. return;
  221764. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  221765. return;
  221766. startThread (9);
  221767. int count = 1000;
  221768. while (numCallbacks == 0)
  221769. {
  221770. sleep (5);
  221771. if (--count < 0 || ! isThreadRunning())
  221772. {
  221773. error = "device didn't start";
  221774. break;
  221775. }
  221776. }
  221777. }
  221778. void close()
  221779. {
  221780. stopThread (6000);
  221781. inputDevice = 0;
  221782. outputDevice = 0;
  221783. inputChannelBuffer.setSize (1, 1);
  221784. outputChannelBuffer.setSize (1, 1);
  221785. numCallbacks = 0;
  221786. }
  221787. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  221788. {
  221789. const ScopedLock sl (callbackLock);
  221790. callback = newCallback;
  221791. }
  221792. void run()
  221793. {
  221794. while (! threadShouldExit())
  221795. {
  221796. if (inputDevice != 0)
  221797. {
  221798. if (! inputDevice->readFromInputDevice (inputChannelBuffer, bufferSize))
  221799. {
  221800. DBG ("ALSA: read failure");
  221801. break;
  221802. }
  221803. }
  221804. if (threadShouldExit())
  221805. break;
  221806. {
  221807. const ScopedLock sl (callbackLock);
  221808. ++numCallbacks;
  221809. if (callback != 0)
  221810. {
  221811. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  221812. inputChannelDataForCallback.size(),
  221813. outputChannelDataForCallback.getRawDataPointer(),
  221814. outputChannelDataForCallback.size(),
  221815. bufferSize);
  221816. }
  221817. else
  221818. {
  221819. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  221820. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  221821. }
  221822. }
  221823. if (outputDevice != 0)
  221824. {
  221825. failed (snd_pcm_wait (outputDevice->handle, 2000));
  221826. if (threadShouldExit())
  221827. break;
  221828. failed (snd_pcm_avail_update (outputDevice->handle));
  221829. if (! outputDevice->writeToOutputDevice (outputChannelBuffer, bufferSize))
  221830. {
  221831. DBG ("ALSA: write failure");
  221832. break;
  221833. }
  221834. }
  221835. }
  221836. }
  221837. int getBitDepth() const throw()
  221838. {
  221839. if (outputDevice != 0)
  221840. return outputDevice->bitDepth;
  221841. if (inputDevice != 0)
  221842. return inputDevice->bitDepth;
  221843. return 16;
  221844. }
  221845. String error;
  221846. double sampleRate;
  221847. int bufferSize, outputLatency, inputLatency;
  221848. BigInteger currentInputChans, currentOutputChans;
  221849. Array <int> sampleRates;
  221850. StringArray channelNamesOut, channelNamesIn;
  221851. AudioIODeviceCallback* callback;
  221852. private:
  221853. const String inputId, outputId;
  221854. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  221855. int numCallbacks;
  221856. CriticalSection callbackLock;
  221857. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  221858. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  221859. unsigned int minChansOut, maxChansOut;
  221860. unsigned int minChansIn, maxChansIn;
  221861. bool failed (const int errorNum)
  221862. {
  221863. if (errorNum >= 0)
  221864. return false;
  221865. error = snd_strerror (errorNum);
  221866. DBG ("ALSA error: " + error + "\n");
  221867. return true;
  221868. }
  221869. void initialiseRatesAndChannels()
  221870. {
  221871. sampleRates.clear();
  221872. channelNamesOut.clear();
  221873. channelNamesIn.clear();
  221874. minChansOut = 0;
  221875. maxChansOut = 0;
  221876. minChansIn = 0;
  221877. maxChansIn = 0;
  221878. unsigned int dummy = 0;
  221879. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  221880. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  221881. unsigned int i;
  221882. for (i = 0; i < maxChansOut; ++i)
  221883. channelNamesOut.add ("channel " + String ((int) i + 1));
  221884. for (i = 0; i < maxChansIn; ++i)
  221885. channelNamesIn.add ("channel " + String ((int) i + 1));
  221886. }
  221887. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAThread);
  221888. };
  221889. class ALSAAudioIODevice : public AudioIODevice
  221890. {
  221891. public:
  221892. ALSAAudioIODevice (const String& deviceName,
  221893. const String& inputId_,
  221894. const String& outputId_)
  221895. : AudioIODevice (deviceName, "ALSA"),
  221896. inputId (inputId_),
  221897. outputId (outputId_),
  221898. isOpen_ (false),
  221899. isStarted (false),
  221900. internal (inputId_, outputId_)
  221901. {
  221902. }
  221903. ~ALSAAudioIODevice()
  221904. {
  221905. }
  221906. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  221907. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  221908. int getNumSampleRates() { return internal.sampleRates.size(); }
  221909. double getSampleRate (int index) { return internal.sampleRates [index]; }
  221910. int getDefaultBufferSize() { return 512; }
  221911. int getNumBufferSizesAvailable() { return 50; }
  221912. int getBufferSizeSamples (int index)
  221913. {
  221914. int n = 16;
  221915. for (int i = 0; i < index; ++i)
  221916. n += n < 64 ? 16
  221917. : (n < 512 ? 32
  221918. : (n < 1024 ? 64
  221919. : (n < 2048 ? 128 : 256)));
  221920. return n;
  221921. }
  221922. const String open (const BigInteger& inputChannels,
  221923. const BigInteger& outputChannels,
  221924. double sampleRate,
  221925. int bufferSizeSamples)
  221926. {
  221927. close();
  221928. if (bufferSizeSamples <= 0)
  221929. bufferSizeSamples = getDefaultBufferSize();
  221930. if (sampleRate <= 0)
  221931. {
  221932. for (int i = 0; i < getNumSampleRates(); ++i)
  221933. {
  221934. if (getSampleRate (i) >= 44100)
  221935. {
  221936. sampleRate = getSampleRate (i);
  221937. break;
  221938. }
  221939. }
  221940. }
  221941. internal.open (inputChannels, outputChannels,
  221942. sampleRate, bufferSizeSamples);
  221943. isOpen_ = internal.error.isEmpty();
  221944. return internal.error;
  221945. }
  221946. void close()
  221947. {
  221948. stop();
  221949. internal.close();
  221950. isOpen_ = false;
  221951. }
  221952. bool isOpen() { return isOpen_; }
  221953. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  221954. const String getLastError() { return internal.error; }
  221955. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  221956. double getCurrentSampleRate() { return internal.sampleRate; }
  221957. int getCurrentBitDepth() { return internal.getBitDepth(); }
  221958. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  221959. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  221960. int getOutputLatencyInSamples() { return internal.outputLatency; }
  221961. int getInputLatencyInSamples() { return internal.inputLatency; }
  221962. void start (AudioIODeviceCallback* callback)
  221963. {
  221964. if (! isOpen_)
  221965. callback = 0;
  221966. if (callback != 0)
  221967. callback->audioDeviceAboutToStart (this);
  221968. internal.setCallback (callback);
  221969. isStarted = (callback != 0);
  221970. }
  221971. void stop()
  221972. {
  221973. AudioIODeviceCallback* const oldCallback = internal.callback;
  221974. start (0);
  221975. if (oldCallback != 0)
  221976. oldCallback->audioDeviceStopped();
  221977. }
  221978. String inputId, outputId;
  221979. private:
  221980. bool isOpen_, isStarted;
  221981. ALSAThread internal;
  221982. };
  221983. class ALSAAudioIODeviceType : public AudioIODeviceType
  221984. {
  221985. public:
  221986. ALSAAudioIODeviceType()
  221987. : AudioIODeviceType ("ALSA"),
  221988. hasScanned (false)
  221989. {
  221990. }
  221991. ~ALSAAudioIODeviceType()
  221992. {
  221993. }
  221994. void scanForDevices()
  221995. {
  221996. if (hasScanned)
  221997. return;
  221998. hasScanned = true;
  221999. inputNames.clear();
  222000. inputIds.clear();
  222001. outputNames.clear();
  222002. outputIds.clear();
  222003. /* void** hints = 0;
  222004. if (snd_device_name_hint (-1, "pcm", &hints) >= 0)
  222005. {
  222006. for (void** hint = hints; *hint != 0; ++hint)
  222007. {
  222008. const String name (getHint (*hint, "NAME"));
  222009. if (name.isNotEmpty())
  222010. {
  222011. const String ioid (getHint (*hint, "IOID"));
  222012. String desc (getHint (*hint, "DESC"));
  222013. if (desc.isEmpty())
  222014. desc = name;
  222015. desc = desc.replaceCharacters ("\n\r", " ");
  222016. DBG ("name: " << name << "\ndesc: " << desc << "\nIO: " << ioid);
  222017. if (ioid.isEmpty() || ioid == "Input")
  222018. {
  222019. inputNames.add (desc);
  222020. inputIds.add (name);
  222021. }
  222022. if (ioid.isEmpty() || ioid == "Output")
  222023. {
  222024. outputNames.add (desc);
  222025. outputIds.add (name);
  222026. }
  222027. }
  222028. }
  222029. snd_device_name_free_hint (hints);
  222030. }
  222031. */
  222032. snd_ctl_t* handle = 0;
  222033. snd_ctl_card_info_t* info = 0;
  222034. snd_ctl_card_info_alloca (&info);
  222035. int cardNum = -1;
  222036. while (outputIds.size() + inputIds.size() <= 32)
  222037. {
  222038. snd_card_next (&cardNum);
  222039. if (cardNum < 0)
  222040. break;
  222041. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222042. {
  222043. if (snd_ctl_card_info (handle, info) >= 0)
  222044. {
  222045. String cardId (snd_ctl_card_info_get_id (info));
  222046. if (cardId.removeCharacters ("0123456789").isEmpty())
  222047. cardId = String (cardNum);
  222048. int device = -1;
  222049. for (;;)
  222050. {
  222051. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  222052. break;
  222053. String id, name;
  222054. id << "hw:" << cardId << ',' << device;
  222055. bool isInput, isOutput;
  222056. if (testDevice (id, isInput, isOutput))
  222057. {
  222058. name << snd_ctl_card_info_get_name (info);
  222059. if (name.isEmpty())
  222060. name = id;
  222061. if (isInput)
  222062. {
  222063. inputNames.add (name);
  222064. inputIds.add (id);
  222065. }
  222066. if (isOutput)
  222067. {
  222068. outputNames.add (name);
  222069. outputIds.add (id);
  222070. }
  222071. }
  222072. }
  222073. }
  222074. snd_ctl_close (handle);
  222075. }
  222076. }
  222077. inputNames.appendNumbersToDuplicates (false, true);
  222078. outputNames.appendNumbersToDuplicates (false, true);
  222079. }
  222080. const StringArray getDeviceNames (bool wantInputNames) const
  222081. {
  222082. jassert (hasScanned); // need to call scanForDevices() before doing this
  222083. return wantInputNames ? inputNames : outputNames;
  222084. }
  222085. int getDefaultDeviceIndex (bool forInput) const
  222086. {
  222087. jassert (hasScanned); // need to call scanForDevices() before doing this
  222088. return 0;
  222089. }
  222090. bool hasSeparateInputsAndOutputs() const { return true; }
  222091. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222092. {
  222093. jassert (hasScanned); // need to call scanForDevices() before doing this
  222094. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  222095. if (d == 0)
  222096. return -1;
  222097. return asInput ? inputIds.indexOf (d->inputId)
  222098. : outputIds.indexOf (d->outputId);
  222099. }
  222100. AudioIODevice* createDevice (const String& outputDeviceName,
  222101. const String& inputDeviceName)
  222102. {
  222103. jassert (hasScanned); // need to call scanForDevices() before doing this
  222104. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222105. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222106. String deviceName (outputIndex >= 0 ? outputDeviceName
  222107. : inputDeviceName);
  222108. if (inputIndex >= 0 || outputIndex >= 0)
  222109. return new ALSAAudioIODevice (deviceName,
  222110. inputIds [inputIndex],
  222111. outputIds [outputIndex]);
  222112. return 0;
  222113. }
  222114. private:
  222115. StringArray inputNames, outputNames, inputIds, outputIds;
  222116. bool hasScanned;
  222117. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  222118. {
  222119. unsigned int minChansOut = 0, maxChansOut = 0;
  222120. unsigned int minChansIn = 0, maxChansIn = 0;
  222121. Array <int> rates;
  222122. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  222123. DBG ("ALSA device: " + id
  222124. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  222125. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  222126. + " rates=" + String (rates.size()));
  222127. isInput = maxChansIn > 0;
  222128. isOutput = maxChansOut > 0;
  222129. return (isInput || isOutput) && rates.size() > 0;
  222130. }
  222131. /*static const String getHint (void* hint, const char* type)
  222132. {
  222133. char* const n = snd_device_name_get_hint (hint, type);
  222134. const String s ((const char*) n);
  222135. free (n);
  222136. return s;
  222137. }*/
  222138. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAAudioIODeviceType);
  222139. };
  222140. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  222141. {
  222142. return new ALSAAudioIODeviceType();
  222143. }
  222144. #endif
  222145. /*** End of inlined file: juce_linux_Audio.cpp ***/
  222146. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  222147. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222148. // compiled on its own).
  222149. #ifdef JUCE_INCLUDED_FILE
  222150. #if JUCE_JACK
  222151. static void* juce_libjack_handle = 0;
  222152. void* juce_load_jack_function (const char* const name)
  222153. {
  222154. if (juce_libjack_handle == 0)
  222155. return 0;
  222156. return dlsym (juce_libjack_handle, name);
  222157. }
  222158. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  222159. typedef return_type (*fn_name##_ptr_t)argument_types; \
  222160. return_type fn_name argument_types { \
  222161. static fn_name##_ptr_t fn = 0; \
  222162. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222163. if (fn) return (*fn)arguments; \
  222164. else return 0; \
  222165. }
  222166. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  222167. typedef void (*fn_name##_ptr_t)argument_types; \
  222168. void fn_name argument_types { \
  222169. static fn_name##_ptr_t fn = 0; \
  222170. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222171. if (fn) (*fn)arguments; \
  222172. }
  222173. 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));
  222174. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  222175. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  222176. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  222177. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  222178. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  222179. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  222180. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  222181. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  222182. 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));
  222183. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  222184. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  222185. 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));
  222186. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  222187. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  222188. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  222189. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  222190. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  222191. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  222192. #if JUCE_DEBUG
  222193. #define JACK_LOGGING_ENABLED 1
  222194. #endif
  222195. #if JACK_LOGGING_ENABLED
  222196. namespace
  222197. {
  222198. void jack_Log (const String& s)
  222199. {
  222200. std::cerr << s << std::endl;
  222201. }
  222202. void dumpJackErrorMessage (const jack_status_t status)
  222203. {
  222204. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  222205. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  222206. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  222207. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  222208. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  222209. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  222210. }
  222211. }
  222212. #else
  222213. #define dumpJackErrorMessage(a) {}
  222214. #define jack_Log(...) {}
  222215. #endif
  222216. #ifndef JUCE_JACK_CLIENT_NAME
  222217. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  222218. #endif
  222219. class JackAudioIODevice : public AudioIODevice
  222220. {
  222221. public:
  222222. JackAudioIODevice (const String& deviceName,
  222223. const String& inputId_,
  222224. const String& outputId_)
  222225. : AudioIODevice (deviceName, "JACK"),
  222226. inputId (inputId_),
  222227. outputId (outputId_),
  222228. isOpen_ (false),
  222229. callback (0),
  222230. totalNumberOfInputChannels (0),
  222231. totalNumberOfOutputChannels (0)
  222232. {
  222233. jassert (deviceName.isNotEmpty());
  222234. jack_status_t status;
  222235. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  222236. if (client == 0)
  222237. {
  222238. dumpJackErrorMessage (status);
  222239. }
  222240. else
  222241. {
  222242. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  222243. // open input ports
  222244. const StringArray inputChannels (getInputChannelNames());
  222245. for (int i = 0; i < inputChannels.size(); i++)
  222246. {
  222247. String inputName;
  222248. inputName << "in_" << ++totalNumberOfInputChannels;
  222249. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  222250. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  222251. }
  222252. // open output ports
  222253. const StringArray outputChannels (getOutputChannelNames());
  222254. for (int i = 0; i < outputChannels.size (); i++)
  222255. {
  222256. String outputName;
  222257. outputName << "out_" << ++totalNumberOfOutputChannels;
  222258. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  222259. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  222260. }
  222261. inChans.calloc (totalNumberOfInputChannels + 2);
  222262. outChans.calloc (totalNumberOfOutputChannels + 2);
  222263. }
  222264. }
  222265. ~JackAudioIODevice()
  222266. {
  222267. close();
  222268. if (client != 0)
  222269. {
  222270. JUCE_NAMESPACE::jack_client_close (client);
  222271. client = 0;
  222272. }
  222273. }
  222274. const StringArray getChannelNames (bool forInput) const
  222275. {
  222276. StringArray names;
  222277. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  222278. forInput ? JackPortIsInput : JackPortIsOutput);
  222279. if (ports != 0)
  222280. {
  222281. int j = 0;
  222282. while (ports[j] != 0)
  222283. {
  222284. const String portName (ports [j++]);
  222285. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222286. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  222287. }
  222288. free (ports);
  222289. }
  222290. return names;
  222291. }
  222292. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  222293. const StringArray getInputChannelNames() { return getChannelNames (true); }
  222294. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  222295. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  222296. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  222297. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  222298. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  222299. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  222300. double sampleRate, int bufferSizeSamples)
  222301. {
  222302. if (client == 0)
  222303. {
  222304. lastError = "No JACK client running";
  222305. return lastError;
  222306. }
  222307. lastError = String::empty;
  222308. close();
  222309. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  222310. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  222311. JUCE_NAMESPACE::jack_activate (client);
  222312. isOpen_ = true;
  222313. if (! inputChannels.isZero())
  222314. {
  222315. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222316. if (ports != 0)
  222317. {
  222318. const int numInputChannels = inputChannels.getHighestBit() + 1;
  222319. for (int i = 0; i < numInputChannels; ++i)
  222320. {
  222321. const String portName (ports[i]);
  222322. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222323. {
  222324. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  222325. if (error != 0)
  222326. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222327. }
  222328. }
  222329. free (ports);
  222330. }
  222331. }
  222332. if (! outputChannels.isZero())
  222333. {
  222334. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222335. if (ports != 0)
  222336. {
  222337. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  222338. for (int i = 0; i < numOutputChannels; ++i)
  222339. {
  222340. const String portName (ports[i]);
  222341. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222342. {
  222343. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  222344. if (error != 0)
  222345. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222346. }
  222347. }
  222348. free (ports);
  222349. }
  222350. }
  222351. return lastError;
  222352. }
  222353. void close()
  222354. {
  222355. stop();
  222356. if (client != 0)
  222357. {
  222358. JUCE_NAMESPACE::jack_deactivate (client);
  222359. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  222360. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  222361. }
  222362. isOpen_ = false;
  222363. }
  222364. void start (AudioIODeviceCallback* newCallback)
  222365. {
  222366. if (isOpen_ && newCallback != callback)
  222367. {
  222368. if (newCallback != 0)
  222369. newCallback->audioDeviceAboutToStart (this);
  222370. AudioIODeviceCallback* const oldCallback = callback;
  222371. {
  222372. const ScopedLock sl (callbackLock);
  222373. callback = newCallback;
  222374. }
  222375. if (oldCallback != 0)
  222376. oldCallback->audioDeviceStopped();
  222377. }
  222378. }
  222379. void stop()
  222380. {
  222381. start (0);
  222382. }
  222383. bool isOpen() { return isOpen_; }
  222384. bool isPlaying() { return callback != 0; }
  222385. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  222386. double getCurrentSampleRate() { return getSampleRate (0); }
  222387. int getCurrentBitDepth() { return 32; }
  222388. const String getLastError() { return lastError; }
  222389. const BigInteger getActiveOutputChannels() const
  222390. {
  222391. BigInteger outputBits;
  222392. for (int i = 0; i < outputPorts.size(); i++)
  222393. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  222394. outputBits.setBit (i);
  222395. return outputBits;
  222396. }
  222397. const BigInteger getActiveInputChannels() const
  222398. {
  222399. BigInteger inputBits;
  222400. for (int i = 0; i < inputPorts.size(); i++)
  222401. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  222402. inputBits.setBit (i);
  222403. return inputBits;
  222404. }
  222405. int getOutputLatencyInSamples()
  222406. {
  222407. int latency = 0;
  222408. for (int i = 0; i < outputPorts.size(); i++)
  222409. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  222410. return latency;
  222411. }
  222412. int getInputLatencyInSamples()
  222413. {
  222414. int latency = 0;
  222415. for (int i = 0; i < inputPorts.size(); i++)
  222416. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  222417. return latency;
  222418. }
  222419. String inputId, outputId;
  222420. private:
  222421. void process (const int numSamples)
  222422. {
  222423. int i, numActiveInChans = 0, numActiveOutChans = 0;
  222424. for (i = 0; i < totalNumberOfInputChannels; ++i)
  222425. {
  222426. jack_default_audio_sample_t* in
  222427. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  222428. if (in != 0)
  222429. inChans [numActiveInChans++] = (float*) in;
  222430. }
  222431. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  222432. {
  222433. jack_default_audio_sample_t* out
  222434. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  222435. if (out != 0)
  222436. outChans [numActiveOutChans++] = (float*) out;
  222437. }
  222438. const ScopedLock sl (callbackLock);
  222439. if (callback != 0)
  222440. {
  222441. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  222442. outChans, numActiveOutChans, numSamples);
  222443. }
  222444. else
  222445. {
  222446. for (i = 0; i < numActiveOutChans; ++i)
  222447. zeromem (outChans[i], sizeof (float) * numSamples);
  222448. }
  222449. }
  222450. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  222451. {
  222452. if (callbackArgument != 0)
  222453. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  222454. return 0;
  222455. }
  222456. static void threadInitCallback (void* callbackArgument)
  222457. {
  222458. jack_Log ("JackAudioIODevice::initialise");
  222459. }
  222460. static void shutdownCallback (void* callbackArgument)
  222461. {
  222462. jack_Log ("JackAudioIODevice::shutdown");
  222463. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  222464. if (device != 0)
  222465. {
  222466. device->client = 0;
  222467. device->close();
  222468. }
  222469. }
  222470. static void errorCallback (const char* msg)
  222471. {
  222472. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  222473. }
  222474. bool isOpen_;
  222475. jack_client_t* client;
  222476. String lastError;
  222477. AudioIODeviceCallback* callback;
  222478. CriticalSection callbackLock;
  222479. HeapBlock <float*> inChans, outChans;
  222480. int totalNumberOfInputChannels;
  222481. int totalNumberOfOutputChannels;
  222482. Array<void*> inputPorts, outputPorts;
  222483. };
  222484. class JackAudioIODeviceType : public AudioIODeviceType
  222485. {
  222486. public:
  222487. JackAudioIODeviceType()
  222488. : AudioIODeviceType ("JACK"),
  222489. hasScanned (false)
  222490. {
  222491. }
  222492. ~JackAudioIODeviceType()
  222493. {
  222494. }
  222495. void scanForDevices()
  222496. {
  222497. hasScanned = true;
  222498. inputNames.clear();
  222499. inputIds.clear();
  222500. outputNames.clear();
  222501. outputIds.clear();
  222502. if (juce_libjack_handle == 0)
  222503. {
  222504. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  222505. if (juce_libjack_handle == 0)
  222506. return;
  222507. }
  222508. // open a dummy client
  222509. jack_status_t status;
  222510. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  222511. if (client == 0)
  222512. {
  222513. dumpJackErrorMessage (status);
  222514. }
  222515. else
  222516. {
  222517. // scan for output devices
  222518. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222519. if (ports != 0)
  222520. {
  222521. int j = 0;
  222522. while (ports[j] != 0)
  222523. {
  222524. String clientName (ports[j]);
  222525. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  222526. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222527. && ! inputNames.contains (clientName))
  222528. {
  222529. inputNames.add (clientName);
  222530. inputIds.add (ports [j]);
  222531. }
  222532. ++j;
  222533. }
  222534. free (ports);
  222535. }
  222536. // scan for input devices
  222537. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222538. if (ports != 0)
  222539. {
  222540. int j = 0;
  222541. while (ports[j] != 0)
  222542. {
  222543. String clientName (ports[j]);
  222544. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  222545. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222546. && ! outputNames.contains (clientName))
  222547. {
  222548. outputNames.add (clientName);
  222549. outputIds.add (ports [j]);
  222550. }
  222551. ++j;
  222552. }
  222553. free (ports);
  222554. }
  222555. JUCE_NAMESPACE::jack_client_close (client);
  222556. }
  222557. }
  222558. const StringArray getDeviceNames (bool wantInputNames) const
  222559. {
  222560. jassert (hasScanned); // need to call scanForDevices() before doing this
  222561. return wantInputNames ? inputNames : outputNames;
  222562. }
  222563. int getDefaultDeviceIndex (bool forInput) const
  222564. {
  222565. jassert (hasScanned); // need to call scanForDevices() before doing this
  222566. return 0;
  222567. }
  222568. bool hasSeparateInputsAndOutputs() const { return true; }
  222569. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222570. {
  222571. jassert (hasScanned); // need to call scanForDevices() before doing this
  222572. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  222573. if (d == 0)
  222574. return -1;
  222575. return asInput ? inputIds.indexOf (d->inputId)
  222576. : outputIds.indexOf (d->outputId);
  222577. }
  222578. AudioIODevice* createDevice (const String& outputDeviceName,
  222579. const String& inputDeviceName)
  222580. {
  222581. jassert (hasScanned); // need to call scanForDevices() before doing this
  222582. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222583. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222584. if (inputIndex >= 0 || outputIndex >= 0)
  222585. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  222586. : inputDeviceName,
  222587. inputIds [inputIndex],
  222588. outputIds [outputIndex]);
  222589. return 0;
  222590. }
  222591. private:
  222592. StringArray inputNames, outputNames, inputIds, outputIds;
  222593. bool hasScanned;
  222594. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JackAudioIODeviceType);
  222595. };
  222596. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  222597. {
  222598. return new JackAudioIODeviceType();
  222599. }
  222600. #else // if JACK is turned off..
  222601. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  222602. #endif
  222603. #endif
  222604. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  222605. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  222606. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222607. // compiled on its own).
  222608. #if JUCE_INCLUDED_FILE
  222609. #if JUCE_ALSA
  222610. namespace
  222611. {
  222612. snd_seq_t* iterateMidiDevices (const bool forInput,
  222613. StringArray& deviceNamesFound,
  222614. const int deviceIndexToOpen)
  222615. {
  222616. snd_seq_t* returnedHandle = 0;
  222617. snd_seq_t* seqHandle;
  222618. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222619. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222620. {
  222621. snd_seq_system_info_t* systemInfo;
  222622. snd_seq_client_info_t* clientInfo;
  222623. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  222624. {
  222625. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  222626. && snd_seq_client_info_malloc (&clientInfo) == 0)
  222627. {
  222628. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  222629. while (--numClients >= 0 && returnedHandle == 0)
  222630. {
  222631. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  222632. {
  222633. snd_seq_port_info_t* portInfo;
  222634. if (snd_seq_port_info_malloc (&portInfo) == 0)
  222635. {
  222636. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  222637. const int client = snd_seq_client_info_get_client (clientInfo);
  222638. snd_seq_port_info_set_client (portInfo, client);
  222639. snd_seq_port_info_set_port (portInfo, -1);
  222640. while (--numPorts >= 0)
  222641. {
  222642. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  222643. && (snd_seq_port_info_get_capability (portInfo)
  222644. & (forInput ? SND_SEQ_PORT_CAP_READ
  222645. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  222646. {
  222647. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  222648. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  222649. {
  222650. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  222651. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  222652. if (sourcePort != -1)
  222653. {
  222654. snd_seq_set_client_name (seqHandle,
  222655. forInput ? "Juce Midi Input"
  222656. : "Juce Midi Output");
  222657. const int portId
  222658. = snd_seq_create_simple_port (seqHandle,
  222659. forInput ? "Juce Midi In Port"
  222660. : "Juce Midi Out Port",
  222661. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222662. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222663. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222664. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  222665. returnedHandle = seqHandle;
  222666. }
  222667. }
  222668. }
  222669. }
  222670. snd_seq_port_info_free (portInfo);
  222671. }
  222672. }
  222673. }
  222674. snd_seq_client_info_free (clientInfo);
  222675. }
  222676. snd_seq_system_info_free (systemInfo);
  222677. }
  222678. if (returnedHandle == 0)
  222679. snd_seq_close (seqHandle);
  222680. }
  222681. deviceNamesFound.appendNumbersToDuplicates (true, true);
  222682. return returnedHandle;
  222683. }
  222684. snd_seq_t* createMidiDevice (const bool forInput, const String& deviceNameToOpen)
  222685. {
  222686. snd_seq_t* seqHandle = 0;
  222687. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222688. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222689. {
  222690. snd_seq_set_client_name (seqHandle,
  222691. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  222692. const int portId
  222693. = snd_seq_create_simple_port (seqHandle,
  222694. forInput ? "in"
  222695. : "out",
  222696. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222697. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222698. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  222699. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222700. if (portId < 0)
  222701. {
  222702. snd_seq_close (seqHandle);
  222703. seqHandle = 0;
  222704. }
  222705. }
  222706. return seqHandle;
  222707. }
  222708. }
  222709. class MidiOutputDevice
  222710. {
  222711. public:
  222712. MidiOutputDevice (MidiOutput* const midiOutput_,
  222713. snd_seq_t* const seqHandle_)
  222714. :
  222715. midiOutput (midiOutput_),
  222716. seqHandle (seqHandle_),
  222717. maxEventSize (16 * 1024)
  222718. {
  222719. jassert (seqHandle != 0 && midiOutput != 0);
  222720. snd_midi_event_new (maxEventSize, &midiParser);
  222721. }
  222722. ~MidiOutputDevice()
  222723. {
  222724. snd_midi_event_free (midiParser);
  222725. snd_seq_close (seqHandle);
  222726. }
  222727. void sendMessageNow (const MidiMessage& message)
  222728. {
  222729. if (message.getRawDataSize() > maxEventSize)
  222730. {
  222731. maxEventSize = message.getRawDataSize();
  222732. snd_midi_event_free (midiParser);
  222733. snd_midi_event_new (maxEventSize, &midiParser);
  222734. }
  222735. snd_seq_event_t event;
  222736. snd_seq_ev_clear (&event);
  222737. snd_midi_event_encode (midiParser,
  222738. message.getRawData(),
  222739. message.getRawDataSize(),
  222740. &event);
  222741. snd_midi_event_reset_encode (midiParser);
  222742. snd_seq_ev_set_source (&event, 0);
  222743. snd_seq_ev_set_subs (&event);
  222744. snd_seq_ev_set_direct (&event);
  222745. snd_seq_event_output (seqHandle, &event);
  222746. snd_seq_drain_output (seqHandle);
  222747. }
  222748. private:
  222749. MidiOutput* const midiOutput;
  222750. snd_seq_t* const seqHandle;
  222751. snd_midi_event_t* midiParser;
  222752. int maxEventSize;
  222753. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutputDevice);
  222754. };
  222755. const StringArray MidiOutput::getDevices()
  222756. {
  222757. StringArray devices;
  222758. iterateMidiDevices (false, devices, -1);
  222759. return devices;
  222760. }
  222761. int MidiOutput::getDefaultDeviceIndex()
  222762. {
  222763. return 0;
  222764. }
  222765. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  222766. {
  222767. MidiOutput* newDevice = 0;
  222768. StringArray devices;
  222769. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  222770. if (handle != 0)
  222771. {
  222772. newDevice = new MidiOutput();
  222773. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222774. }
  222775. return newDevice;
  222776. }
  222777. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  222778. {
  222779. MidiOutput* newDevice = 0;
  222780. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  222781. if (handle != 0)
  222782. {
  222783. newDevice = new MidiOutput();
  222784. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222785. }
  222786. return newDevice;
  222787. }
  222788. MidiOutput::~MidiOutput()
  222789. {
  222790. delete static_cast <MidiOutputDevice*> (internal);
  222791. }
  222792. void MidiOutput::reset()
  222793. {
  222794. }
  222795. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  222796. {
  222797. return false;
  222798. }
  222799. void MidiOutput::setVolume (float leftVol, float rightVol)
  222800. {
  222801. }
  222802. void MidiOutput::sendMessageNow (const MidiMessage& message)
  222803. {
  222804. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  222805. }
  222806. class MidiInputThread : public Thread
  222807. {
  222808. public:
  222809. MidiInputThread (MidiInput* const midiInput_,
  222810. snd_seq_t* const seqHandle_,
  222811. MidiInputCallback* const callback_)
  222812. : Thread ("Juce MIDI Input"),
  222813. midiInput (midiInput_),
  222814. seqHandle (seqHandle_),
  222815. callback (callback_)
  222816. {
  222817. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  222818. }
  222819. ~MidiInputThread()
  222820. {
  222821. snd_seq_close (seqHandle);
  222822. }
  222823. void run()
  222824. {
  222825. const int maxEventSize = 16 * 1024;
  222826. snd_midi_event_t* midiParser;
  222827. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  222828. {
  222829. HeapBlock <uint8> buffer (maxEventSize);
  222830. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  222831. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  222832. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  222833. while (! threadShouldExit())
  222834. {
  222835. if (poll (pfd, numPfds, 500) > 0)
  222836. {
  222837. snd_seq_event_t* inputEvent = 0;
  222838. snd_seq_nonblock (seqHandle, 1);
  222839. do
  222840. {
  222841. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  222842. {
  222843. // xxx what about SYSEXes that are too big for the buffer?
  222844. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  222845. snd_midi_event_reset_decode (midiParser);
  222846. if (numBytes > 0)
  222847. {
  222848. const MidiMessage message ((const uint8*) buffer,
  222849. numBytes,
  222850. Time::getMillisecondCounter() * 0.001);
  222851. callback->handleIncomingMidiMessage (midiInput, message);
  222852. }
  222853. snd_seq_free_event (inputEvent);
  222854. }
  222855. }
  222856. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  222857. snd_seq_free_event (inputEvent);
  222858. }
  222859. }
  222860. snd_midi_event_free (midiParser);
  222861. }
  222862. };
  222863. private:
  222864. MidiInput* const midiInput;
  222865. snd_seq_t* const seqHandle;
  222866. MidiInputCallback* const callback;
  222867. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputThread);
  222868. };
  222869. MidiInput::MidiInput (const String& name_)
  222870. : name (name_),
  222871. internal (0)
  222872. {
  222873. }
  222874. MidiInput::~MidiInput()
  222875. {
  222876. stop();
  222877. delete static_cast <MidiInputThread*> (internal);
  222878. }
  222879. void MidiInput::start()
  222880. {
  222881. static_cast <MidiInputThread*> (internal)->startThread();
  222882. }
  222883. void MidiInput::stop()
  222884. {
  222885. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  222886. }
  222887. int MidiInput::getDefaultDeviceIndex()
  222888. {
  222889. return 0;
  222890. }
  222891. const StringArray MidiInput::getDevices()
  222892. {
  222893. StringArray devices;
  222894. iterateMidiDevices (true, devices, -1);
  222895. return devices;
  222896. }
  222897. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  222898. {
  222899. MidiInput* newDevice = 0;
  222900. StringArray devices;
  222901. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  222902. if (handle != 0)
  222903. {
  222904. newDevice = new MidiInput (devices [deviceIndex]);
  222905. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222906. }
  222907. return newDevice;
  222908. }
  222909. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  222910. {
  222911. MidiInput* newDevice = 0;
  222912. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  222913. if (handle != 0)
  222914. {
  222915. newDevice = new MidiInput (deviceName);
  222916. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222917. }
  222918. return newDevice;
  222919. }
  222920. #else
  222921. // (These are just stub functions if ALSA is unavailable...)
  222922. const StringArray MidiOutput::getDevices() { return StringArray(); }
  222923. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  222924. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  222925. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  222926. MidiOutput::~MidiOutput() {}
  222927. void MidiOutput::reset() {}
  222928. bool MidiOutput::getVolume (float&, float&) { return false; }
  222929. void MidiOutput::setVolume (float, float) {}
  222930. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  222931. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  222932. MidiInput::~MidiInput() {}
  222933. void MidiInput::start() {}
  222934. void MidiInput::stop() {}
  222935. int MidiInput::getDefaultDeviceIndex() { return 0; }
  222936. const StringArray MidiInput::getDevices() { return StringArray(); }
  222937. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  222938. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  222939. #endif
  222940. #endif
  222941. /*** End of inlined file: juce_linux_Midi.cpp ***/
  222942. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  222943. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222944. // compiled on its own).
  222945. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  222946. AudioCDReader::AudioCDReader()
  222947. : AudioFormatReader (0, "CD Audio")
  222948. {
  222949. }
  222950. const StringArray AudioCDReader::getAvailableCDNames()
  222951. {
  222952. StringArray names;
  222953. return names;
  222954. }
  222955. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  222956. {
  222957. return 0;
  222958. }
  222959. AudioCDReader::~AudioCDReader()
  222960. {
  222961. }
  222962. void AudioCDReader::refreshTrackLengths()
  222963. {
  222964. }
  222965. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  222966. int64 startSampleInFile, int numSamples)
  222967. {
  222968. return false;
  222969. }
  222970. bool AudioCDReader::isCDStillPresent() const
  222971. {
  222972. return false;
  222973. }
  222974. bool AudioCDReader::isTrackAudio (int trackNum) const
  222975. {
  222976. return false;
  222977. }
  222978. void AudioCDReader::enableIndexScanning (bool b)
  222979. {
  222980. }
  222981. int AudioCDReader::getLastIndex() const
  222982. {
  222983. return 0;
  222984. }
  222985. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  222986. {
  222987. return Array<int>();
  222988. }
  222989. #endif
  222990. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  222991. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  222992. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222993. // compiled on its own).
  222994. #if JUCE_INCLUDED_FILE
  222995. void FileChooser::showPlatformDialog (Array<File>& results,
  222996. const String& title,
  222997. const File& file,
  222998. const String& filters,
  222999. bool isDirectory,
  223000. bool selectsFiles,
  223001. bool isSave,
  223002. bool warnAboutOverwritingExistingFiles,
  223003. bool selectMultipleFiles,
  223004. FilePreviewComponent* previewComponent)
  223005. {
  223006. const String separator (":");
  223007. String command ("zenity --file-selection");
  223008. if (title.isNotEmpty())
  223009. command << " --title=\"" << title << "\"";
  223010. if (file != File::nonexistent)
  223011. command << " --filename=\"" << file.getFullPathName () << "\"";
  223012. if (isDirectory)
  223013. command << " --directory";
  223014. if (isSave)
  223015. command << " --save";
  223016. if (selectMultipleFiles)
  223017. command << " --multiple --separator=\"" << separator << "\"";
  223018. command << " 2>&1";
  223019. MemoryOutputStream result;
  223020. int status = -1;
  223021. FILE* stream = popen (command.toUTF8(), "r");
  223022. if (stream != 0)
  223023. {
  223024. for (;;)
  223025. {
  223026. char buffer [1024];
  223027. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  223028. if (bytesRead <= 0)
  223029. break;
  223030. result.write (buffer, bytesRead);
  223031. }
  223032. status = pclose (stream);
  223033. }
  223034. if (status == 0)
  223035. {
  223036. StringArray tokens;
  223037. if (selectMultipleFiles)
  223038. tokens.addTokens (result.toUTF8(), separator, String::empty);
  223039. else
  223040. tokens.add (result.toUTF8());
  223041. for (int i = 0; i < tokens.size(); i++)
  223042. results.add (File (tokens[i]));
  223043. return;
  223044. }
  223045. //xxx ain't got one!
  223046. jassertfalse;
  223047. }
  223048. #endif
  223049. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  223050. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223051. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223052. // compiled on its own).
  223053. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  223054. /*
  223055. Sorry.. This class isn't implemented on Linux!
  223056. */
  223057. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  223058. : browser (0),
  223059. blankPageShown (false),
  223060. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  223061. {
  223062. setOpaque (true);
  223063. }
  223064. WebBrowserComponent::~WebBrowserComponent()
  223065. {
  223066. }
  223067. void WebBrowserComponent::goToURL (const String& url,
  223068. const StringArray* headers,
  223069. const MemoryBlock* postData)
  223070. {
  223071. lastURL = url;
  223072. lastHeaders.clear();
  223073. if (headers != 0)
  223074. lastHeaders = *headers;
  223075. lastPostData.setSize (0);
  223076. if (postData != 0)
  223077. lastPostData = *postData;
  223078. blankPageShown = false;
  223079. }
  223080. void WebBrowserComponent::stop()
  223081. {
  223082. }
  223083. void WebBrowserComponent::goBack()
  223084. {
  223085. lastURL = String::empty;
  223086. blankPageShown = false;
  223087. }
  223088. void WebBrowserComponent::goForward()
  223089. {
  223090. lastURL = String::empty;
  223091. }
  223092. void WebBrowserComponent::refresh()
  223093. {
  223094. }
  223095. void WebBrowserComponent::paint (Graphics& g)
  223096. {
  223097. g.fillAll (Colours::white);
  223098. }
  223099. void WebBrowserComponent::checkWindowAssociation()
  223100. {
  223101. }
  223102. void WebBrowserComponent::reloadLastURL()
  223103. {
  223104. if (lastURL.isNotEmpty())
  223105. {
  223106. goToURL (lastURL, &lastHeaders, &lastPostData);
  223107. lastURL = String::empty;
  223108. }
  223109. }
  223110. void WebBrowserComponent::parentHierarchyChanged()
  223111. {
  223112. checkWindowAssociation();
  223113. }
  223114. void WebBrowserComponent::resized()
  223115. {
  223116. }
  223117. void WebBrowserComponent::visibilityChanged()
  223118. {
  223119. checkWindowAssociation();
  223120. }
  223121. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  223122. {
  223123. return true;
  223124. }
  223125. #endif
  223126. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223127. #endif
  223128. END_JUCE_NAMESPACE
  223129. #endif
  223130. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  223131. #elif JUCE_MAC || JUCE_IOS
  223132. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  223133. /*
  223134. This file wraps together all the mac-specific code, so that
  223135. we can include all the native headers just once, and compile all our
  223136. platform-specific stuff in one big lump, keeping it out of the way of
  223137. the rest of the codebase.
  223138. */
  223139. #if JUCE_MAC || JUCE_IOS
  223140. #undef JUCE_BUILD_NATIVE
  223141. #define JUCE_BUILD_NATIVE 1
  223142. BEGIN_JUCE_NAMESPACE
  223143. #undef Point
  223144. namespace
  223145. {
  223146. template <class RectType>
  223147. const Rectangle<int> convertToRectInt (const RectType& r)
  223148. {
  223149. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  223150. }
  223151. template <class RectType>
  223152. const Rectangle<float> convertToRectFloat (const RectType& r)
  223153. {
  223154. return Rectangle<float> (r.origin.x, r.origin.y, r.size.width, r.size.height);
  223155. }
  223156. template <class RectType>
  223157. CGRect convertToCGRect (const RectType& r)
  223158. {
  223159. return CGRectMake ((CGFloat) r.getX(), (CGFloat) r.getY(), (CGFloat) r.getWidth(), (CGFloat) r.getHeight());
  223160. }
  223161. }
  223162. class MessageQueue
  223163. {
  223164. public:
  223165. MessageQueue()
  223166. {
  223167. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4 && ! JUCE_IOS
  223168. runLoop = CFRunLoopGetMain();
  223169. #else
  223170. runLoop = CFRunLoopGetCurrent();
  223171. #endif
  223172. CFRunLoopSourceContext sourceContext;
  223173. zerostruct (sourceContext);
  223174. sourceContext.info = this;
  223175. sourceContext.perform = runLoopSourceCallback;
  223176. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  223177. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  223178. }
  223179. ~MessageQueue()
  223180. {
  223181. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  223182. CFRunLoopSourceInvalidate (runLoopSource);
  223183. CFRelease (runLoopSource);
  223184. }
  223185. void post (Message* const message)
  223186. {
  223187. messages.add (message);
  223188. CFRunLoopSourceSignal (runLoopSource);
  223189. CFRunLoopWakeUp (runLoop);
  223190. }
  223191. private:
  223192. ReferenceCountedArray <Message, CriticalSection> messages;
  223193. CriticalSection lock;
  223194. CFRunLoopRef runLoop;
  223195. CFRunLoopSourceRef runLoopSource;
  223196. bool deliverNextMessage()
  223197. {
  223198. const Message::Ptr nextMessage (messages.removeAndReturn (0));
  223199. if (nextMessage == 0)
  223200. return false;
  223201. const ScopedAutoReleasePool pool;
  223202. MessageManager::getInstance()->deliverMessage (nextMessage);
  223203. return true;
  223204. }
  223205. void runLoopCallback()
  223206. {
  223207. for (int i = 4; --i >= 0;)
  223208. if (! deliverNextMessage())
  223209. return;
  223210. CFRunLoopSourceSignal (runLoopSource);
  223211. CFRunLoopWakeUp (runLoop);
  223212. }
  223213. static void runLoopSourceCallback (void* info)
  223214. {
  223215. static_cast <MessageQueue*> (info)->runLoopCallback();
  223216. }
  223217. };
  223218. #define JUCE_INCLUDED_FILE 1
  223219. // Now include the actual code files..
  223220. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  223221. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  223222. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  223223. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  223224. cross-linked so that when you make a call to a class that you thought was private, it ends up
  223225. actually calling into a similarly named class in the other module's address space.
  223226. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  223227. have unique names, and should avoid this problem.
  223228. If you're using the amalgamated version, you can just set this macro to something unique before
  223229. you include juce_amalgamated.cpp.
  223230. */
  223231. #ifndef JUCE_ObjCExtraSuffix
  223232. #define JUCE_ObjCExtraSuffix 3
  223233. #endif
  223234. #ifndef DOXYGEN
  223235. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  223236. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  223237. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  223238. #endif
  223239. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  223240. /*** Start of inlined file: juce_mac_Strings.mm ***/
  223241. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223242. // compiled on its own).
  223243. #if JUCE_INCLUDED_FILE
  223244. namespace
  223245. {
  223246. const String nsStringToJuce (NSString* s)
  223247. {
  223248. return String::fromUTF8 ([s UTF8String]);
  223249. }
  223250. NSString* juceStringToNS (const String& s)
  223251. {
  223252. return [NSString stringWithUTF8String: s.toUTF8()];
  223253. }
  223254. const String convertUTF16ToString (const UniChar* utf16)
  223255. {
  223256. String s;
  223257. while (*utf16 != 0)
  223258. s += (juce_wchar) *utf16++;
  223259. return s;
  223260. }
  223261. }
  223262. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  223263. {
  223264. String result;
  223265. if (cfString != 0)
  223266. {
  223267. CFRange range = { 0, CFStringGetLength (cfString) };
  223268. HeapBlock <UniChar> u (range.length + 1);
  223269. CFStringGetCharacters (cfString, range, u);
  223270. u[range.length] = 0;
  223271. result = convertUTF16ToString (u);
  223272. }
  223273. return result;
  223274. }
  223275. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  223276. {
  223277. const int len = s.length();
  223278. HeapBlock <UniChar> temp (len + 2);
  223279. for (int i = 0; i <= len; ++i)
  223280. temp[i] = s[i];
  223281. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  223282. }
  223283. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  223284. {
  223285. #if JUCE_IOS
  223286. const ScopedAutoReleasePool pool;
  223287. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  223288. #else
  223289. UnicodeMapping map;
  223290. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223291. kUnicodeNoSubset,
  223292. kTextEncodingDefaultFormat);
  223293. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223294. kUnicodeCanonicalCompVariant,
  223295. kTextEncodingDefaultFormat);
  223296. map.mappingVersion = kUnicodeUseLatestMapping;
  223297. UnicodeToTextInfo conversionInfo = 0;
  223298. String result;
  223299. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  223300. {
  223301. const int bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (s.getCharPointer());
  223302. HeapBlock <char> tempOut;
  223303. tempOut.calloc (bytesNeeded + 4);
  223304. ByteCount bytesRead = 0;
  223305. ByteCount outputBufferSize = 0;
  223306. if (ConvertFromUnicodeToText (conversionInfo,
  223307. bytesNeeded, (ConstUniCharArrayPtr) s.toUTF16().getAddress(),
  223308. kUnicodeDefaultDirectionMask,
  223309. 0, 0, 0, 0,
  223310. bytesNeeded, &bytesRead,
  223311. &outputBufferSize, tempOut) == noErr)
  223312. {
  223313. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  223314. CharPointer_UTF32 dest (result.getCharPointer());
  223315. dest.writeAll (CharPointer_UTF16 ((CharPointer_UTF16::CharType*) tempOut.getData()));
  223316. }
  223317. DisposeUnicodeToTextInfo (&conversionInfo);
  223318. }
  223319. return result;
  223320. #endif
  223321. }
  223322. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  223323. void SystemClipboard::copyTextToClipboard (const String& text)
  223324. {
  223325. #if JUCE_IOS
  223326. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  223327. forPasteboardType: @"public.text"];
  223328. #else
  223329. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  223330. owner: nil];
  223331. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  223332. forType: NSStringPboardType];
  223333. #endif
  223334. }
  223335. const String SystemClipboard::getTextFromClipboard()
  223336. {
  223337. #if JUCE_IOS
  223338. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  223339. #else
  223340. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  223341. #endif
  223342. return text == 0 ? String::empty
  223343. : nsStringToJuce (text);
  223344. }
  223345. #endif
  223346. #endif
  223347. /*** End of inlined file: juce_mac_Strings.mm ***/
  223348. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  223349. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223350. // compiled on its own).
  223351. #if JUCE_INCLUDED_FILE
  223352. namespace SystemStatsHelpers
  223353. {
  223354. static int64 highResTimerFrequency = 0;
  223355. static double highResTimerToMillisecRatio = 0;
  223356. #if JUCE_INTEL
  223357. void doCPUID (uint32& a, uint32& b, uint32& c, uint32& d, uint32 type)
  223358. {
  223359. uint32 la = a, lb = b, lc = c, ld = d;
  223360. asm ("mov %%ebx, %%esi \n\t"
  223361. "cpuid \n\t"
  223362. "xchg %%esi, %%ebx"
  223363. : "=a" (la), "=S" (lb), "=c" (lc), "=d" (ld) : "a" (type)
  223364. #if JUCE_64BIT
  223365. , "b" (lb), "c" (lc), "d" (ld)
  223366. #endif
  223367. );
  223368. a = la; b = lb; c = lc; d = ld;
  223369. }
  223370. #endif
  223371. }
  223372. void SystemStats::initialiseStats()
  223373. {
  223374. using namespace SystemStatsHelpers;
  223375. static bool initialised = false;
  223376. if (! initialised)
  223377. {
  223378. initialised = true;
  223379. #if JUCE_MAC
  223380. [NSApplication sharedApplication];
  223381. #endif
  223382. #if JUCE_INTEL
  223383. uint32 familyModel = 0, extFeatures = 0, features = 0, dummy = 0;
  223384. doCPUID (familyModel, extFeatures, dummy, features, 1);
  223385. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  223386. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  223387. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  223388. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  223389. #else
  223390. cpuFlags.hasMMX = false;
  223391. cpuFlags.hasSSE = false;
  223392. cpuFlags.hasSSE2 = false;
  223393. cpuFlags.has3DNow = false;
  223394. #endif
  223395. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  223396. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  223397. #else
  223398. cpuFlags.numCpus = (int) MPProcessors();
  223399. #endif
  223400. mach_timebase_info_data_t timebase;
  223401. (void) mach_timebase_info (&timebase);
  223402. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  223403. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  223404. String s (SystemStats::getJUCEVersion());
  223405. rlimit lim;
  223406. getrlimit (RLIMIT_NOFILE, &lim);
  223407. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  223408. setrlimit (RLIMIT_NOFILE, &lim);
  223409. }
  223410. }
  223411. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  223412. {
  223413. return MacOSX;
  223414. }
  223415. const String SystemStats::getOperatingSystemName()
  223416. {
  223417. return "Mac OS X";
  223418. }
  223419. #if ! JUCE_IOS
  223420. int PlatformUtilities::getOSXMinorVersionNumber()
  223421. {
  223422. SInt32 versionMinor = 0;
  223423. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  223424. (void) err;
  223425. jassert (err == noErr);
  223426. return (int) versionMinor;
  223427. }
  223428. #endif
  223429. bool SystemStats::isOperatingSystem64Bit()
  223430. {
  223431. #if JUCE_IOS
  223432. return false;
  223433. #elif JUCE_64BIT
  223434. return true;
  223435. #else
  223436. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  223437. #endif
  223438. }
  223439. int SystemStats::getMemorySizeInMegabytes()
  223440. {
  223441. uint64 mem = 0;
  223442. size_t memSize = sizeof (mem);
  223443. int mib[] = { CTL_HW, HW_MEMSIZE };
  223444. sysctl (mib, 2, &mem, &memSize, 0, 0);
  223445. return (int) (mem / (1024 * 1024));
  223446. }
  223447. const String SystemStats::getCpuVendor()
  223448. {
  223449. #if JUCE_INTEL
  223450. uint32 dummy = 0;
  223451. uint32 vendor[4];
  223452. zerostruct (vendor);
  223453. SystemStatsHelpers::doCPUID (dummy, vendor[0], vendor[2], vendor[1], 0);
  223454. return String (reinterpret_cast <const char*> (vendor), 12);
  223455. #else
  223456. return String::empty;
  223457. #endif
  223458. }
  223459. int SystemStats::getCpuSpeedInMegaherz()
  223460. {
  223461. uint64 speedHz = 0;
  223462. size_t speedSize = sizeof (speedHz);
  223463. int mib[] = { CTL_HW, HW_CPU_FREQ };
  223464. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  223465. #if JUCE_BIG_ENDIAN
  223466. if (speedSize == 4)
  223467. speedHz >>= 32;
  223468. #endif
  223469. return (int) (speedHz / 1000000);
  223470. }
  223471. const String SystemStats::getLogonName()
  223472. {
  223473. return nsStringToJuce (NSUserName());
  223474. }
  223475. const String SystemStats::getFullUserName()
  223476. {
  223477. return nsStringToJuce (NSFullUserName());
  223478. }
  223479. uint32 juce_millisecondsSinceStartup() throw()
  223480. {
  223481. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  223482. }
  223483. double Time::getMillisecondCounterHiRes() throw()
  223484. {
  223485. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  223486. }
  223487. int64 Time::getHighResolutionTicks() throw()
  223488. {
  223489. return (int64) mach_absolute_time();
  223490. }
  223491. int64 Time::getHighResolutionTicksPerSecond() throw()
  223492. {
  223493. return SystemStatsHelpers::highResTimerFrequency;
  223494. }
  223495. bool Time::setSystemTimeToThisTime() const
  223496. {
  223497. jassertfalse;
  223498. return false;
  223499. }
  223500. int SystemStats::getPageSize()
  223501. {
  223502. return (int) NSPageSize();
  223503. }
  223504. void PlatformUtilities::fpuReset()
  223505. {
  223506. }
  223507. #endif
  223508. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  223509. /*** Start of inlined file: juce_mac_Network.mm ***/
  223510. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223511. // compiled on its own).
  223512. #if JUCE_INCLUDED_FILE
  223513. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  223514. {
  223515. ifaddrs* addrs = 0;
  223516. if (getifaddrs (&addrs) == 0)
  223517. {
  223518. for (const ifaddrs* cursor = addrs; cursor != 0; cursor = cursor->ifa_next)
  223519. {
  223520. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  223521. if (sto->ss_family == AF_LINK)
  223522. {
  223523. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  223524. #ifndef IFT_ETHER
  223525. #define IFT_ETHER 6
  223526. #endif
  223527. if (sadd->sdl_type == IFT_ETHER)
  223528. result.addIfNotAlreadyThere (MACAddress (((const uint8*) sadd->sdl_data) + sadd->sdl_nlen));
  223529. }
  223530. }
  223531. freeifaddrs (addrs);
  223532. }
  223533. }
  223534. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  223535. const String& emailSubject,
  223536. const String& bodyText,
  223537. const StringArray& filesToAttach)
  223538. {
  223539. #if JUCE_IOS
  223540. //xxx probably need to use MFMailComposeViewController
  223541. jassertfalse;
  223542. return false;
  223543. #else
  223544. const ScopedAutoReleasePool pool;
  223545. String script;
  223546. script << "tell application \"Mail\"\r\n"
  223547. "set newMessage to make new outgoing message with properties {subject:\""
  223548. << emailSubject.replace ("\"", "\\\"")
  223549. << "\", content:\""
  223550. << bodyText.replace ("\"", "\\\"")
  223551. << "\" & return & return}\r\n"
  223552. "tell newMessage\r\n"
  223553. "set visible to true\r\n"
  223554. "set sender to \"sdfsdfsdfewf\"\r\n"
  223555. "make new to recipient at end of to recipients with properties {address:\""
  223556. << targetEmailAddress
  223557. << "\"}\r\n";
  223558. for (int i = 0; i < filesToAttach.size(); ++i)
  223559. {
  223560. script << "tell content\r\n"
  223561. "make new attachment with properties {file name:\""
  223562. << filesToAttach[i].replace ("\"", "\\\"")
  223563. << "\"} at after the last paragraph\r\n"
  223564. "end tell\r\n";
  223565. }
  223566. script << "end tell\r\n"
  223567. "end tell\r\n";
  223568. NSAppleScript* s = [[NSAppleScript alloc]
  223569. initWithSource: juceStringToNS (script)];
  223570. NSDictionary* error = 0;
  223571. const bool ok = [s executeAndReturnError: &error] != nil;
  223572. [s release];
  223573. return ok;
  223574. #endif
  223575. }
  223576. END_JUCE_NAMESPACE
  223577. using namespace JUCE_NAMESPACE;
  223578. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  223579. @interface JuceURLConnection : NSObject
  223580. {
  223581. @public
  223582. NSURLRequest* request;
  223583. NSURLConnection* connection;
  223584. NSMutableData* data;
  223585. Thread* runLoopThread;
  223586. bool initialised, hasFailed, hasFinished;
  223587. int position;
  223588. int64 contentLength;
  223589. NSDictionary* headers;
  223590. NSLock* dataLock;
  223591. }
  223592. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  223593. - (void) dealloc;
  223594. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  223595. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  223596. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  223597. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  223598. - (BOOL) isOpen;
  223599. - (int) read: (char*) dest numBytes: (int) num;
  223600. - (int) readPosition;
  223601. - (void) stop;
  223602. - (void) createConnection;
  223603. @end
  223604. class JuceURLConnectionMessageThread : public Thread
  223605. {
  223606. public:
  223607. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  223608. : Thread ("http connection"),
  223609. owner (owner_)
  223610. {
  223611. }
  223612. ~JuceURLConnectionMessageThread()
  223613. {
  223614. stopThread (10000);
  223615. }
  223616. void run()
  223617. {
  223618. [owner createConnection];
  223619. while (! threadShouldExit())
  223620. {
  223621. const ScopedAutoReleasePool pool;
  223622. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  223623. }
  223624. }
  223625. private:
  223626. JuceURLConnection* owner;
  223627. };
  223628. @implementation JuceURLConnection
  223629. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  223630. withCallback: (URL::OpenStreamProgressCallback*) callback
  223631. withContext: (void*) context;
  223632. {
  223633. [super init];
  223634. request = req;
  223635. [request retain];
  223636. data = [[NSMutableData data] retain];
  223637. dataLock = [[NSLock alloc] init];
  223638. connection = 0;
  223639. initialised = false;
  223640. hasFailed = false;
  223641. hasFinished = false;
  223642. contentLength = -1;
  223643. headers = 0;
  223644. runLoopThread = new JuceURLConnectionMessageThread (self);
  223645. runLoopThread->startThread();
  223646. while (runLoopThread->isThreadRunning() && ! initialised)
  223647. {
  223648. if (callback != 0)
  223649. callback (context, -1, (int) [[request HTTPBody] length]);
  223650. Thread::sleep (1);
  223651. }
  223652. return self;
  223653. }
  223654. - (void) dealloc
  223655. {
  223656. [self stop];
  223657. deleteAndZero (runLoopThread);
  223658. [connection release];
  223659. [data release];
  223660. [dataLock release];
  223661. [request release];
  223662. [headers release];
  223663. [super dealloc];
  223664. }
  223665. - (void) createConnection
  223666. {
  223667. NSUInteger oldRetainCount = [self retainCount];
  223668. connection = [[NSURLConnection alloc] initWithRequest: request
  223669. delegate: self];
  223670. if (oldRetainCount == [self retainCount])
  223671. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  223672. if (connection == nil)
  223673. runLoopThread->signalThreadShouldExit();
  223674. }
  223675. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  223676. {
  223677. (void) conn;
  223678. [dataLock lock];
  223679. [data setLength: 0];
  223680. [dataLock unlock];
  223681. initialised = true;
  223682. contentLength = [response expectedContentLength];
  223683. [headers release];
  223684. headers = 0;
  223685. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  223686. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  223687. }
  223688. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  223689. {
  223690. (void) conn;
  223691. DBG (nsStringToJuce ([error description]));
  223692. hasFailed = true;
  223693. initialised = true;
  223694. if (runLoopThread != 0)
  223695. runLoopThread->signalThreadShouldExit();
  223696. }
  223697. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  223698. {
  223699. (void) conn;
  223700. [dataLock lock];
  223701. [data appendData: newData];
  223702. [dataLock unlock];
  223703. initialised = true;
  223704. }
  223705. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  223706. {
  223707. (void) conn;
  223708. hasFinished = true;
  223709. initialised = true;
  223710. if (runLoopThread != 0)
  223711. runLoopThread->signalThreadShouldExit();
  223712. }
  223713. - (BOOL) isOpen
  223714. {
  223715. return connection != 0 && ! hasFailed;
  223716. }
  223717. - (int) readPosition
  223718. {
  223719. return position;
  223720. }
  223721. - (int) read: (char*) dest numBytes: (int) numNeeded
  223722. {
  223723. int numDone = 0;
  223724. while (numNeeded > 0)
  223725. {
  223726. int available = jmin (numNeeded, (int) [data length]);
  223727. if (available > 0)
  223728. {
  223729. [dataLock lock];
  223730. [data getBytes: dest length: available];
  223731. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  223732. [dataLock unlock];
  223733. numDone += available;
  223734. numNeeded -= available;
  223735. dest += available;
  223736. }
  223737. else
  223738. {
  223739. if (hasFailed || hasFinished)
  223740. break;
  223741. Thread::sleep (1);
  223742. }
  223743. }
  223744. position += numDone;
  223745. return numDone;
  223746. }
  223747. - (void) stop
  223748. {
  223749. [connection cancel];
  223750. if (runLoopThread != 0)
  223751. runLoopThread->stopThread (10000);
  223752. }
  223753. @end
  223754. BEGIN_JUCE_NAMESPACE
  223755. class WebInputStream : public InputStream
  223756. {
  223757. public:
  223758. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  223759. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  223760. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  223761. : connection (nil),
  223762. address (address_), headers (headers_), postData (postData_), position (0),
  223763. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  223764. {
  223765. JUCE_AUTORELEASEPOOL
  223766. connection = createConnection (progressCallback, progressCallbackContext);
  223767. if (responseHeaders != 0 && connection != 0 && connection->headers != 0)
  223768. {
  223769. NSEnumerator* enumerator = [connection->headers keyEnumerator];
  223770. NSString* key;
  223771. while ((key = [enumerator nextObject]) != nil)
  223772. responseHeaders->set (nsStringToJuce (key),
  223773. nsStringToJuce ((NSString*) [connection->headers objectForKey: key]));
  223774. }
  223775. }
  223776. ~WebInputStream()
  223777. {
  223778. close();
  223779. }
  223780. bool isError() const { return connection == nil; }
  223781. int64 getTotalLength() { return connection == nil ? -1 : connection->contentLength; }
  223782. bool isExhausted() { return finished; }
  223783. int64 getPosition() { return position; }
  223784. int read (void* buffer, int bytesToRead)
  223785. {
  223786. if (finished || isError())
  223787. {
  223788. return 0;
  223789. }
  223790. else
  223791. {
  223792. JUCE_AUTORELEASEPOOL
  223793. const int bytesRead = [connection read: static_cast <char*> (buffer) numBytes: bytesToRead];
  223794. position += bytesRead;
  223795. if (bytesRead == 0)
  223796. finished = true;
  223797. return bytesRead;
  223798. }
  223799. }
  223800. bool setPosition (int64 wantedPos)
  223801. {
  223802. if (wantedPos != position)
  223803. {
  223804. finished = false;
  223805. if (wantedPos < position)
  223806. {
  223807. close();
  223808. position = 0;
  223809. connection = createConnection (0, 0);
  223810. }
  223811. skipNextBytes (wantedPos - position);
  223812. }
  223813. return true;
  223814. }
  223815. private:
  223816. JuceURLConnection* connection;
  223817. String address, headers;
  223818. MemoryBlock postData;
  223819. int64 position;
  223820. bool finished;
  223821. const bool isPost;
  223822. const int timeOutMs;
  223823. void close()
  223824. {
  223825. [connection stop];
  223826. [connection release];
  223827. connection = nil;
  223828. }
  223829. JuceURLConnection* createConnection (URL::OpenStreamProgressCallback* progressCallback,
  223830. void* progressCallbackContext)
  223831. {
  223832. NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (address)]
  223833. cachePolicy: NSURLRequestUseProtocolCachePolicy
  223834. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  223835. if (req == nil)
  223836. return 0;
  223837. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  223838. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  223839. StringArray headerLines;
  223840. headerLines.addLines (headers);
  223841. headerLines.removeEmptyStrings (true);
  223842. for (int i = 0; i < headerLines.size(); ++i)
  223843. {
  223844. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  223845. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  223846. if (key.isNotEmpty() && value.isNotEmpty())
  223847. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  223848. }
  223849. if (isPost && postData.getSize() > 0)
  223850. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  223851. length: postData.getSize()]];
  223852. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  223853. withCallback: progressCallback
  223854. withContext: progressCallbackContext];
  223855. if ([s isOpen])
  223856. return s;
  223857. [s release];
  223858. return 0;
  223859. }
  223860. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  223861. };
  223862. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  223863. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  223864. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  223865. {
  223866. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  223867. progressCallback, progressCallbackContext,
  223868. headers, timeOutMs, responseHeaders));
  223869. return wi->isError() ? 0 : wi.release();
  223870. }
  223871. #endif
  223872. /*** End of inlined file: juce_mac_Network.mm ***/
  223873. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  223874. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223875. // compiled on its own).
  223876. #if JUCE_INCLUDED_FILE
  223877. struct NamedPipeInternal
  223878. {
  223879. String pipeInName, pipeOutName;
  223880. int pipeIn, pipeOut;
  223881. bool volatile createdPipe, blocked, stopReadOperation;
  223882. static void signalHandler (int) {}
  223883. };
  223884. void NamedPipe::cancelPendingReads()
  223885. {
  223886. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  223887. {
  223888. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  223889. intern->stopReadOperation = true;
  223890. char buffer [1] = { 0 };
  223891. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  223892. (void) bytesWritten;
  223893. int timeout = 2000;
  223894. while (intern->blocked && --timeout >= 0)
  223895. Thread::sleep (2);
  223896. intern->stopReadOperation = false;
  223897. }
  223898. }
  223899. void NamedPipe::close()
  223900. {
  223901. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  223902. if (intern != 0)
  223903. {
  223904. internal = 0;
  223905. if (intern->pipeIn != -1)
  223906. ::close (intern->pipeIn);
  223907. if (intern->pipeOut != -1)
  223908. ::close (intern->pipeOut);
  223909. if (intern->createdPipe)
  223910. {
  223911. unlink (intern->pipeInName.toUTF8());
  223912. unlink (intern->pipeOutName.toUTF8());
  223913. }
  223914. delete intern;
  223915. }
  223916. }
  223917. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  223918. {
  223919. close();
  223920. NamedPipeInternal* const intern = new NamedPipeInternal();
  223921. internal = intern;
  223922. intern->createdPipe = createPipe;
  223923. intern->blocked = false;
  223924. intern->stopReadOperation = false;
  223925. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  223926. siginterrupt (SIGPIPE, 1);
  223927. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  223928. intern->pipeInName = pipePath + "_in";
  223929. intern->pipeOutName = pipePath + "_out";
  223930. intern->pipeIn = -1;
  223931. intern->pipeOut = -1;
  223932. if (createPipe)
  223933. {
  223934. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  223935. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  223936. {
  223937. delete intern;
  223938. internal = 0;
  223939. return false;
  223940. }
  223941. }
  223942. return true;
  223943. }
  223944. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  223945. {
  223946. int bytesRead = -1;
  223947. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  223948. if (intern != 0)
  223949. {
  223950. intern->blocked = true;
  223951. if (intern->pipeIn == -1)
  223952. {
  223953. if (intern->createdPipe)
  223954. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  223955. else
  223956. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  223957. if (intern->pipeIn == -1)
  223958. {
  223959. intern->blocked = false;
  223960. return -1;
  223961. }
  223962. }
  223963. bytesRead = 0;
  223964. char* p = static_cast<char*> (destBuffer);
  223965. while (bytesRead < maxBytesToRead)
  223966. {
  223967. const int bytesThisTime = maxBytesToRead - bytesRead;
  223968. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  223969. if (numRead <= 0 || intern->stopReadOperation)
  223970. {
  223971. bytesRead = -1;
  223972. break;
  223973. }
  223974. bytesRead += numRead;
  223975. p += bytesRead;
  223976. }
  223977. intern->blocked = false;
  223978. }
  223979. return bytesRead;
  223980. }
  223981. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  223982. {
  223983. int bytesWritten = -1;
  223984. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  223985. if (intern != 0)
  223986. {
  223987. if (intern->pipeOut == -1)
  223988. {
  223989. if (intern->createdPipe)
  223990. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  223991. else
  223992. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  223993. if (intern->pipeOut == -1)
  223994. {
  223995. return -1;
  223996. }
  223997. }
  223998. const char* p = static_cast<const char*> (sourceBuffer);
  223999. bytesWritten = 0;
  224000. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  224001. while (bytesWritten < numBytesToWrite
  224002. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  224003. {
  224004. const int bytesThisTime = numBytesToWrite - bytesWritten;
  224005. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  224006. if (numWritten <= 0)
  224007. {
  224008. bytesWritten = -1;
  224009. break;
  224010. }
  224011. bytesWritten += numWritten;
  224012. p += bytesWritten;
  224013. }
  224014. }
  224015. return bytesWritten;
  224016. }
  224017. #endif
  224018. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  224019. /*** Start of inlined file: juce_mac_Threads.mm ***/
  224020. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224021. // compiled on its own).
  224022. #if JUCE_INCLUDED_FILE
  224023. /*
  224024. Note that a lot of methods that you'd expect to find in this file actually
  224025. live in juce_posix_SharedCode.h!
  224026. */
  224027. bool Process::isForegroundProcess()
  224028. {
  224029. #if JUCE_MAC
  224030. return [NSApp isActive];
  224031. #else
  224032. return true; // xxx change this if more than one app is ever possible on the iPhone!
  224033. #endif
  224034. }
  224035. void Process::raisePrivilege()
  224036. {
  224037. jassertfalse;
  224038. }
  224039. void Process::lowerPrivilege()
  224040. {
  224041. jassertfalse;
  224042. }
  224043. void Process::terminate()
  224044. {
  224045. exit (0);
  224046. }
  224047. void Process::setPriority (ProcessPriority)
  224048. {
  224049. // xxx
  224050. }
  224051. #endif
  224052. /*** End of inlined file: juce_mac_Threads.mm ***/
  224053. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  224054. /*
  224055. This file contains posix routines that are common to both the Linux and Mac builds.
  224056. It gets included directly in the cpp files for these platforms.
  224057. */
  224058. CriticalSection::CriticalSection() throw()
  224059. {
  224060. pthread_mutexattr_t atts;
  224061. pthread_mutexattr_init (&atts);
  224062. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  224063. #if ! JUCE_ANDROID
  224064. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224065. #endif
  224066. pthread_mutex_init (&internal, &atts);
  224067. }
  224068. CriticalSection::~CriticalSection() throw()
  224069. {
  224070. pthread_mutex_destroy (&internal);
  224071. }
  224072. void CriticalSection::enter() const throw()
  224073. {
  224074. pthread_mutex_lock (&internal);
  224075. }
  224076. bool CriticalSection::tryEnter() const throw()
  224077. {
  224078. return pthread_mutex_trylock (&internal) == 0;
  224079. }
  224080. void CriticalSection::exit() const throw()
  224081. {
  224082. pthread_mutex_unlock (&internal);
  224083. }
  224084. class WaitableEventImpl
  224085. {
  224086. public:
  224087. WaitableEventImpl (const bool manualReset_)
  224088. : triggered (false),
  224089. manualReset (manualReset_)
  224090. {
  224091. pthread_cond_init (&condition, 0);
  224092. pthread_mutexattr_t atts;
  224093. pthread_mutexattr_init (&atts);
  224094. #if ! JUCE_ANDROID
  224095. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224096. #endif
  224097. pthread_mutex_init (&mutex, &atts);
  224098. }
  224099. ~WaitableEventImpl()
  224100. {
  224101. pthread_cond_destroy (&condition);
  224102. pthread_mutex_destroy (&mutex);
  224103. }
  224104. bool wait (const int timeOutMillisecs) throw()
  224105. {
  224106. pthread_mutex_lock (&mutex);
  224107. if (! triggered)
  224108. {
  224109. if (timeOutMillisecs < 0)
  224110. {
  224111. do
  224112. {
  224113. pthread_cond_wait (&condition, &mutex);
  224114. }
  224115. while (! triggered);
  224116. }
  224117. else
  224118. {
  224119. struct timeval now;
  224120. gettimeofday (&now, 0);
  224121. struct timespec time;
  224122. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  224123. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  224124. if (time.tv_nsec >= 1000000000)
  224125. {
  224126. time.tv_nsec -= 1000000000;
  224127. time.tv_sec++;
  224128. }
  224129. do
  224130. {
  224131. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  224132. {
  224133. pthread_mutex_unlock (&mutex);
  224134. return false;
  224135. }
  224136. }
  224137. while (! triggered);
  224138. }
  224139. }
  224140. if (! manualReset)
  224141. triggered = false;
  224142. pthread_mutex_unlock (&mutex);
  224143. return true;
  224144. }
  224145. void signal() throw()
  224146. {
  224147. pthread_mutex_lock (&mutex);
  224148. triggered = true;
  224149. pthread_cond_broadcast (&condition);
  224150. pthread_mutex_unlock (&mutex);
  224151. }
  224152. void reset() throw()
  224153. {
  224154. pthread_mutex_lock (&mutex);
  224155. triggered = false;
  224156. pthread_mutex_unlock (&mutex);
  224157. }
  224158. private:
  224159. pthread_cond_t condition;
  224160. pthread_mutex_t mutex;
  224161. bool triggered;
  224162. const bool manualReset;
  224163. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  224164. };
  224165. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  224166. : internal (new WaitableEventImpl (manualReset))
  224167. {
  224168. }
  224169. WaitableEvent::~WaitableEvent() throw()
  224170. {
  224171. delete static_cast <WaitableEventImpl*> (internal);
  224172. }
  224173. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  224174. {
  224175. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  224176. }
  224177. void WaitableEvent::signal() const throw()
  224178. {
  224179. static_cast <WaitableEventImpl*> (internal)->signal();
  224180. }
  224181. void WaitableEvent::reset() const throw()
  224182. {
  224183. static_cast <WaitableEventImpl*> (internal)->reset();
  224184. }
  224185. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  224186. {
  224187. struct timespec time;
  224188. time.tv_sec = millisecs / 1000;
  224189. time.tv_nsec = (millisecs % 1000) * 1000000;
  224190. nanosleep (&time, 0);
  224191. }
  224192. const juce_wchar File::separator = '/';
  224193. const String File::separatorString ("/");
  224194. const File File::getCurrentWorkingDirectory()
  224195. {
  224196. HeapBlock<char> heapBuffer;
  224197. char localBuffer [1024];
  224198. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  224199. int bufferSize = 4096;
  224200. while (cwd == 0 && errno == ERANGE)
  224201. {
  224202. heapBuffer.malloc (bufferSize);
  224203. cwd = getcwd (heapBuffer, bufferSize - 1);
  224204. bufferSize += 1024;
  224205. }
  224206. return File (String::fromUTF8 (cwd));
  224207. }
  224208. bool File::setAsCurrentWorkingDirectory() const
  224209. {
  224210. return chdir (getFullPathName().toUTF8()) == 0;
  224211. }
  224212. namespace
  224213. {
  224214. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224215. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  224216. #else
  224217. typedef struct stat juce_statStruct;
  224218. #endif
  224219. bool juce_stat (const String& fileName, juce_statStruct& info)
  224220. {
  224221. return fileName.isNotEmpty()
  224222. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224223. && (stat64 (fileName.toUTF8(), &info) == 0);
  224224. #else
  224225. && (stat (fileName.toUTF8(), &info) == 0);
  224226. #endif
  224227. }
  224228. // if this file doesn't exist, find a parent of it that does..
  224229. bool juce_doStatFS (File f, struct statfs& result)
  224230. {
  224231. for (int i = 5; --i >= 0;)
  224232. {
  224233. if (f.exists())
  224234. break;
  224235. f = f.getParentDirectory();
  224236. }
  224237. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  224238. }
  224239. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  224240. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224241. {
  224242. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  224243. {
  224244. juce_statStruct info;
  224245. const bool statOk = juce_stat (path, info);
  224246. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  224247. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  224248. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  224249. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  224250. }
  224251. if (isReadOnly != 0)
  224252. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  224253. }
  224254. }
  224255. bool File::isDirectory() const
  224256. {
  224257. juce_statStruct info;
  224258. return fullPath.isEmpty()
  224259. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  224260. }
  224261. bool File::exists() const
  224262. {
  224263. juce_statStruct info;
  224264. return fullPath.isNotEmpty()
  224265. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224266. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  224267. #else
  224268. && (lstat (fullPath.toUTF8(), &info) == 0);
  224269. #endif
  224270. }
  224271. bool File::existsAsFile() const
  224272. {
  224273. return exists() && ! isDirectory();
  224274. }
  224275. int64 File::getSize() const
  224276. {
  224277. juce_statStruct info;
  224278. return juce_stat (fullPath, info) ? info.st_size : 0;
  224279. }
  224280. bool File::hasWriteAccess() const
  224281. {
  224282. if (exists())
  224283. return access (fullPath.toUTF8(), W_OK) == 0;
  224284. if ((! isDirectory()) && fullPath.containsChar (separator))
  224285. return getParentDirectory().hasWriteAccess();
  224286. return false;
  224287. }
  224288. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  224289. {
  224290. juce_statStruct info;
  224291. if (! juce_stat (fullPath, info))
  224292. return false;
  224293. info.st_mode &= 0777; // Just permissions
  224294. if (shouldBeReadOnly)
  224295. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  224296. else
  224297. // Give everybody write permission?
  224298. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  224299. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  224300. }
  224301. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  224302. {
  224303. modificationTime = 0;
  224304. accessTime = 0;
  224305. creationTime = 0;
  224306. juce_statStruct info;
  224307. if (juce_stat (fullPath, info))
  224308. {
  224309. modificationTime = (int64) info.st_mtime * 1000;
  224310. accessTime = (int64) info.st_atime * 1000;
  224311. creationTime = (int64) info.st_ctime * 1000;
  224312. }
  224313. }
  224314. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  224315. {
  224316. juce_statStruct info;
  224317. if ((modificationTime != 0 || accessTime != 0) && juce_stat (fullPath, info))
  224318. {
  224319. struct utimbuf times;
  224320. times.actime = accessTime != 0 ? (time_t) (accessTime / 1000) : info.st_atime;
  224321. times.modtime = modificationTime != 0 ? (time_t) (modificationTime / 1000) : info.st_mtime;
  224322. return utime (fullPath.toUTF8(), &times) == 0;
  224323. }
  224324. return false;
  224325. }
  224326. bool File::deleteFile() const
  224327. {
  224328. if (! exists())
  224329. return true;
  224330. if (isDirectory())
  224331. return rmdir (fullPath.toUTF8()) == 0;
  224332. return remove (fullPath.toUTF8()) == 0;
  224333. }
  224334. bool File::moveInternal (const File& dest) const
  224335. {
  224336. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  224337. return true;
  224338. if (hasWriteAccess() && copyInternal (dest))
  224339. {
  224340. if (deleteFile())
  224341. return true;
  224342. dest.deleteFile();
  224343. }
  224344. return false;
  224345. }
  224346. void File::createDirectoryInternal (const String& fileName) const
  224347. {
  224348. mkdir (fileName.toUTF8(), 0777);
  224349. }
  224350. int64 juce_fileSetPosition (void* handle, int64 pos)
  224351. {
  224352. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  224353. return pos;
  224354. return -1;
  224355. }
  224356. void FileInputStream::openHandle()
  224357. {
  224358. totalSize = file.getSize();
  224359. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  224360. if (f != -1)
  224361. fileHandle = (void*) f;
  224362. }
  224363. void FileInputStream::closeHandle()
  224364. {
  224365. if (fileHandle != 0)
  224366. {
  224367. close ((int) (pointer_sized_int) fileHandle);
  224368. fileHandle = 0;
  224369. }
  224370. }
  224371. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  224372. {
  224373. if (fileHandle != 0)
  224374. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  224375. return 0;
  224376. }
  224377. void FileOutputStream::openHandle()
  224378. {
  224379. if (file.exists())
  224380. {
  224381. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  224382. if (f != -1)
  224383. {
  224384. currentPosition = lseek (f, 0, SEEK_END);
  224385. if (currentPosition >= 0)
  224386. fileHandle = (void*) f;
  224387. else
  224388. close (f);
  224389. }
  224390. }
  224391. else
  224392. {
  224393. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  224394. if (f != -1)
  224395. fileHandle = (void*) f;
  224396. }
  224397. }
  224398. void FileOutputStream::closeHandle()
  224399. {
  224400. if (fileHandle != 0)
  224401. {
  224402. close ((int) (pointer_sized_int) fileHandle);
  224403. fileHandle = 0;
  224404. }
  224405. }
  224406. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  224407. {
  224408. if (fileHandle != 0)
  224409. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  224410. return 0;
  224411. }
  224412. void FileOutputStream::flushInternal()
  224413. {
  224414. if (fileHandle != 0)
  224415. fsync ((int) (pointer_sized_int) fileHandle);
  224416. }
  224417. const File juce_getExecutableFile()
  224418. {
  224419. #if JUCE_ANDROID
  224420. // TODO
  224421. return File::nonexistent;
  224422. #else
  224423. Dl_info exeInfo;
  224424. dladdr ((void*) juce_getExecutableFile, &exeInfo); // (can't be a const void* on android)
  224425. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  224426. #endif
  224427. }
  224428. int64 File::getBytesFreeOnVolume() const
  224429. {
  224430. struct statfs buf;
  224431. if (juce_doStatFS (*this, buf))
  224432. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  224433. return 0;
  224434. }
  224435. int64 File::getVolumeTotalSize() const
  224436. {
  224437. struct statfs buf;
  224438. if (juce_doStatFS (*this, buf))
  224439. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  224440. return 0;
  224441. }
  224442. const String File::getVolumeLabel() const
  224443. {
  224444. #if JUCE_MAC
  224445. struct VolAttrBuf
  224446. {
  224447. u_int32_t length;
  224448. attrreference_t mountPointRef;
  224449. char mountPointSpace [MAXPATHLEN];
  224450. } attrBuf;
  224451. struct attrlist attrList;
  224452. zerostruct (attrList);
  224453. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  224454. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  224455. File f (*this);
  224456. for (;;)
  224457. {
  224458. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  224459. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  224460. (int) attrBuf.mountPointRef.attr_length);
  224461. const File parent (f.getParentDirectory());
  224462. if (f == parent)
  224463. break;
  224464. f = parent;
  224465. }
  224466. #endif
  224467. return String::empty;
  224468. }
  224469. int File::getVolumeSerialNumber() const
  224470. {
  224471. int result = 0;
  224472. /* int fd = open (getFullPathName().toUTF8(), O_RDONLY | O_NONBLOCK);
  224473. char info [512];
  224474. #ifndef HDIO_GET_IDENTITY
  224475. #define HDIO_GET_IDENTITY 0x030d
  224476. #endif
  224477. if (ioctl (fd, HDIO_GET_IDENTITY, info) == 0)
  224478. {
  224479. DBG (String (info + 20, 20));
  224480. result = String (info + 20, 20).trim().getIntValue();
  224481. }
  224482. close (fd);*/
  224483. return result;
  224484. }
  224485. void juce_runSystemCommand (const String& command)
  224486. {
  224487. int result = system (command.toUTF8());
  224488. (void) result;
  224489. }
  224490. const String juce_getOutputFromCommand (const String& command)
  224491. {
  224492. // slight bodge here, as we just pipe the output into a temp file and read it...
  224493. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  224494. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  224495. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  224496. String result (tempFile.loadFileAsString());
  224497. tempFile.deleteFile();
  224498. return result;
  224499. }
  224500. class InterProcessLock::Pimpl
  224501. {
  224502. public:
  224503. Pimpl (const String& name, const int timeOutMillisecs)
  224504. : handle (0), refCount (1)
  224505. {
  224506. #if JUCE_MAC
  224507. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  224508. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  224509. #else
  224510. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  224511. #endif
  224512. temp.create();
  224513. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  224514. if (handle != 0)
  224515. {
  224516. struct flock fl;
  224517. zerostruct (fl);
  224518. fl.l_whence = SEEK_SET;
  224519. fl.l_type = F_WRLCK;
  224520. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  224521. for (;;)
  224522. {
  224523. const int result = fcntl (handle, F_SETLK, &fl);
  224524. if (result >= 0)
  224525. return;
  224526. if (errno != EINTR)
  224527. {
  224528. if (timeOutMillisecs == 0
  224529. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  224530. break;
  224531. Thread::sleep (10);
  224532. }
  224533. }
  224534. }
  224535. closeFile();
  224536. }
  224537. ~Pimpl()
  224538. {
  224539. closeFile();
  224540. }
  224541. void closeFile()
  224542. {
  224543. if (handle != 0)
  224544. {
  224545. struct flock fl;
  224546. zerostruct (fl);
  224547. fl.l_whence = SEEK_SET;
  224548. fl.l_type = F_UNLCK;
  224549. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  224550. {}
  224551. close (handle);
  224552. handle = 0;
  224553. }
  224554. }
  224555. int handle, refCount;
  224556. };
  224557. InterProcessLock::InterProcessLock (const String& name_)
  224558. : name (name_)
  224559. {
  224560. }
  224561. InterProcessLock::~InterProcessLock()
  224562. {
  224563. }
  224564. bool InterProcessLock::enter (const int timeOutMillisecs)
  224565. {
  224566. const ScopedLock sl (lock);
  224567. if (pimpl == 0)
  224568. {
  224569. pimpl = new Pimpl (name, timeOutMillisecs);
  224570. if (pimpl->handle == 0)
  224571. pimpl = 0;
  224572. }
  224573. else
  224574. {
  224575. pimpl->refCount++;
  224576. }
  224577. return pimpl != 0;
  224578. }
  224579. void InterProcessLock::exit()
  224580. {
  224581. const ScopedLock sl (lock);
  224582. // Trying to release the lock too many times!
  224583. jassert (pimpl != 0);
  224584. if (pimpl != 0 && --(pimpl->refCount) == 0)
  224585. pimpl = 0;
  224586. }
  224587. void JUCE_API juce_threadEntryPoint (void*);
  224588. void* threadEntryProc (void* userData)
  224589. {
  224590. JUCE_AUTORELEASEPOOL
  224591. juce_threadEntryPoint (userData);
  224592. return 0;
  224593. }
  224594. void Thread::launchThread()
  224595. {
  224596. threadHandle_ = 0;
  224597. pthread_t handle = 0;
  224598. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  224599. {
  224600. pthread_detach (handle);
  224601. threadHandle_ = (void*) handle;
  224602. threadId_ = (ThreadID) threadHandle_;
  224603. }
  224604. }
  224605. void Thread::closeThreadHandle()
  224606. {
  224607. threadId_ = 0;
  224608. threadHandle_ = 0;
  224609. }
  224610. void Thread::killThread()
  224611. {
  224612. if (threadHandle_ != 0)
  224613. {
  224614. #if JUCE_ANDROID
  224615. jassertfalse; // pthread_cancel not available!
  224616. #else
  224617. pthread_cancel ((pthread_t) threadHandle_);
  224618. #endif
  224619. }
  224620. }
  224621. void Thread::setCurrentThreadName (const String& name)
  224622. {
  224623. #if JUCE_MAC
  224624. pthread_setname_np (name.toUTF8());
  224625. #elif JUCE_LINUX
  224626. prctl (PR_SET_NAME, name.toUTF8().getAddress(), 0, 0, 0);
  224627. #endif
  224628. }
  224629. bool Thread::setThreadPriority (void* handle, int priority)
  224630. {
  224631. struct sched_param param;
  224632. int policy;
  224633. priority = jlimit (0, 10, priority);
  224634. if (handle == 0)
  224635. handle = (void*) pthread_self();
  224636. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  224637. return false;
  224638. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  224639. const int minPriority = sched_get_priority_min (policy);
  224640. const int maxPriority = sched_get_priority_max (policy);
  224641. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  224642. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  224643. }
  224644. Thread::ThreadID Thread::getCurrentThreadId()
  224645. {
  224646. return (ThreadID) pthread_self();
  224647. }
  224648. void Thread::yield()
  224649. {
  224650. sched_yield();
  224651. }
  224652. /* Remove this macro if you're having problems compiling the cpu affinity
  224653. calls (the API for these has changed about quite a bit in various Linux
  224654. versions, and a lot of distros seem to ship with obsolete versions)
  224655. */
  224656. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  224657. #define SUPPORT_AFFINITIES 1
  224658. #endif
  224659. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  224660. {
  224661. #if SUPPORT_AFFINITIES
  224662. cpu_set_t affinity;
  224663. CPU_ZERO (&affinity);
  224664. for (int i = 0; i < 32; ++i)
  224665. if ((affinityMask & (1 << i)) != 0)
  224666. CPU_SET (i, &affinity);
  224667. /*
  224668. N.B. If this line causes a compile error, then you've probably not got the latest
  224669. version of glibc installed.
  224670. If you don't want to update your copy of glibc and don't care about cpu affinities,
  224671. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  224672. */
  224673. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  224674. sched_yield();
  224675. #else
  224676. /* affinities aren't supported because either the appropriate header files weren't found,
  224677. or the SUPPORT_AFFINITIES macro was turned off
  224678. */
  224679. jassertfalse;
  224680. (void) affinityMask;
  224681. #endif
  224682. }
  224683. /*** End of inlined file: juce_posix_SharedCode.h ***/
  224684. /*** Start of inlined file: juce_mac_Files.mm ***/
  224685. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224686. // compiled on its own).
  224687. #if JUCE_INCLUDED_FILE
  224688. /*
  224689. Note that a lot of methods that you'd expect to find in this file actually
  224690. live in juce_posix_SharedCode.h!
  224691. */
  224692. bool File::copyInternal (const File& dest) const
  224693. {
  224694. const ScopedAutoReleasePool pool;
  224695. NSFileManager* fm = [NSFileManager defaultManager];
  224696. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  224697. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  224698. && [fm copyItemAtPath: juceStringToNS (fullPath)
  224699. toPath: juceStringToNS (dest.getFullPathName())
  224700. error: nil];
  224701. #else
  224702. && [fm copyPath: juceStringToNS (fullPath)
  224703. toPath: juceStringToNS (dest.getFullPathName())
  224704. handler: nil];
  224705. #endif
  224706. }
  224707. void File::findFileSystemRoots (Array<File>& destArray)
  224708. {
  224709. destArray.add (File ("/"));
  224710. }
  224711. namespace FileHelpers
  224712. {
  224713. bool isFileOnDriveType (const File& f, const char* const* types)
  224714. {
  224715. struct statfs buf;
  224716. if (juce_doStatFS (f, buf))
  224717. {
  224718. const String type (buf.f_fstypename);
  224719. while (*types != 0)
  224720. if (type.equalsIgnoreCase (*types++))
  224721. return true;
  224722. }
  224723. return false;
  224724. }
  224725. bool isHiddenFile (const String& path)
  224726. {
  224727. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  224728. const ScopedAutoReleasePool pool;
  224729. NSNumber* hidden = nil;
  224730. NSError* err = nil;
  224731. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  224732. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  224733. && [hidden boolValue];
  224734. #else
  224735. #if JUCE_IOS
  224736. return File (path).getFileName().startsWithChar ('.');
  224737. #else
  224738. FSRef ref;
  224739. LSItemInfoRecord info;
  224740. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8().getAddress(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  224741. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  224742. && (info.flags & kLSItemInfoIsInvisible) != 0;
  224743. #endif
  224744. #endif
  224745. }
  224746. #if JUCE_IOS
  224747. const String getIOSSystemLocation (NSSearchPathDirectory type)
  224748. {
  224749. return nsStringToJuce ([NSSearchPathForDirectoriesInDomains (type, NSUserDomainMask, YES)
  224750. objectAtIndex: 0]);
  224751. }
  224752. #endif
  224753. bool launchExecutable (const String& pathAndArguments)
  224754. {
  224755. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  224756. const int cpid = fork();
  224757. if (cpid == 0)
  224758. {
  224759. // Child process
  224760. if (execve (argv[0], (char**) argv, 0) < 0)
  224761. exit (0);
  224762. }
  224763. else
  224764. {
  224765. if (cpid < 0)
  224766. return false;
  224767. }
  224768. return true;
  224769. }
  224770. }
  224771. bool File::isOnCDRomDrive() const
  224772. {
  224773. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  224774. return FileHelpers::isFileOnDriveType (*this, cdTypes);
  224775. }
  224776. bool File::isOnHardDisk() const
  224777. {
  224778. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  224779. return ! (isOnCDRomDrive() || FileHelpers::isFileOnDriveType (*this, nonHDTypes));
  224780. }
  224781. bool File::isOnRemovableDrive() const
  224782. {
  224783. #if JUCE_IOS
  224784. return false; // xxx is this possible?
  224785. #else
  224786. const ScopedAutoReleasePool pool;
  224787. BOOL removable = false;
  224788. [[NSWorkspace sharedWorkspace]
  224789. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  224790. isRemovable: &removable
  224791. isWritable: nil
  224792. isUnmountable: nil
  224793. description: nil
  224794. type: nil];
  224795. return removable;
  224796. #endif
  224797. }
  224798. bool File::isHidden() const
  224799. {
  224800. return FileHelpers::isHiddenFile (getFullPathName());
  224801. }
  224802. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  224803. const File File::getSpecialLocation (const SpecialLocationType type)
  224804. {
  224805. const ScopedAutoReleasePool pool;
  224806. String resultPath;
  224807. switch (type)
  224808. {
  224809. case userHomeDirectory: resultPath = nsStringToJuce (NSHomeDirectory()); break;
  224810. #if JUCE_IOS
  224811. case userDocumentsDirectory: resultPath = FileHelpers::getIOSSystemLocation (NSDocumentDirectory); break;
  224812. case userDesktopDirectory: resultPath = FileHelpers::getIOSSystemLocation (NSDesktopDirectory); break;
  224813. case tempDirectory:
  224814. {
  224815. File tmp (FileHelpers::getIOSSystemLocation (NSCachesDirectory));
  224816. tmp = tmp.getChildFile (juce_getExecutableFile().getFileNameWithoutExtension());
  224817. tmp.createDirectory();
  224818. return tmp.getFullPathName();
  224819. }
  224820. #else
  224821. case userDocumentsDirectory: resultPath = "~/Documents"; break;
  224822. case userDesktopDirectory: resultPath = "~/Desktop"; break;
  224823. case tempDirectory:
  224824. {
  224825. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  224826. tmp.createDirectory();
  224827. return tmp.getFullPathName();
  224828. }
  224829. #endif
  224830. case userMusicDirectory: resultPath = "~/Music"; break;
  224831. case userMoviesDirectory: resultPath = "~/Movies"; break;
  224832. case userApplicationDataDirectory: resultPath = "~/Library"; break;
  224833. case commonApplicationDataDirectory: resultPath = "/Library"; break;
  224834. case globalApplicationsDirectory: resultPath = "/Applications"; break;
  224835. case invokedExecutableFile:
  224836. if (juce_Argv0 != 0)
  224837. return File (String::fromUTF8 (juce_Argv0));
  224838. // deliberate fall-through...
  224839. case currentExecutableFile:
  224840. return juce_getExecutableFile();
  224841. case currentApplicationFile:
  224842. {
  224843. const File exe (juce_getExecutableFile());
  224844. const File parent (exe.getParentDirectory());
  224845. #if JUCE_IOS
  224846. return parent;
  224847. #else
  224848. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  224849. ? parent.getParentDirectory().getParentDirectory()
  224850. : exe;
  224851. #endif
  224852. }
  224853. case hostApplicationPath:
  224854. {
  224855. unsigned int size = 8192;
  224856. HeapBlock<char> buffer;
  224857. buffer.calloc (size + 8);
  224858. _NSGetExecutablePath (buffer.getData(), &size);
  224859. return String::fromUTF8 (buffer, size);
  224860. }
  224861. default:
  224862. jassertfalse; // unknown type?
  224863. break;
  224864. }
  224865. if (resultPath.isNotEmpty())
  224866. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  224867. return File::nonexistent;
  224868. }
  224869. const String File::getVersion() const
  224870. {
  224871. const ScopedAutoReleasePool pool;
  224872. String result;
  224873. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  224874. if (bundle != 0)
  224875. {
  224876. NSDictionary* info = [bundle infoDictionary];
  224877. if (info != 0)
  224878. {
  224879. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  224880. if (name != nil)
  224881. result = nsStringToJuce (name);
  224882. }
  224883. }
  224884. return result;
  224885. }
  224886. const File File::getLinkedTarget() const
  224887. {
  224888. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  224889. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  224890. #else
  224891. // (the cast here avoids a deprecation warning)
  224892. NSString* dest = [((id) [NSFileManager defaultManager]) pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  224893. #endif
  224894. if (dest != nil)
  224895. return File (nsStringToJuce (dest));
  224896. return *this;
  224897. }
  224898. bool File::moveToTrash() const
  224899. {
  224900. if (! exists())
  224901. return true;
  224902. #if JUCE_IOS
  224903. return deleteFile(); //xxx is there a trashcan on the iPhone?
  224904. #else
  224905. const ScopedAutoReleasePool pool;
  224906. NSString* p = juceStringToNS (getFullPathName());
  224907. return [[NSWorkspace sharedWorkspace]
  224908. performFileOperation: NSWorkspaceRecycleOperation
  224909. source: [p stringByDeletingLastPathComponent]
  224910. destination: @""
  224911. files: [NSArray arrayWithObject: [p lastPathComponent]]
  224912. tag: nil ];
  224913. #endif
  224914. }
  224915. class DirectoryIterator::NativeIterator::Pimpl
  224916. {
  224917. public:
  224918. Pimpl (const File& directory, const String& wildCard_)
  224919. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  224920. wildCard (wildCard_),
  224921. enumerator (0)
  224922. {
  224923. const ScopedAutoReleasePool pool;
  224924. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  224925. wildcardUTF8 = wildCard.toUTF8();
  224926. }
  224927. ~Pimpl()
  224928. {
  224929. [enumerator release];
  224930. }
  224931. bool next (String& filenameFound,
  224932. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224933. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224934. {
  224935. const ScopedAutoReleasePool pool;
  224936. for (;;)
  224937. {
  224938. NSString* file;
  224939. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  224940. return false;
  224941. [enumerator skipDescendents];
  224942. filenameFound = nsStringToJuce (file);
  224943. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  224944. continue;
  224945. const String path (parentDir + filenameFound);
  224946. updateStatInfoForFile (path, isDir, fileSize, modTime, creationTime, isReadOnly);
  224947. if (isHidden != 0)
  224948. *isHidden = FileHelpers::isHiddenFile (path);
  224949. return true;
  224950. }
  224951. }
  224952. private:
  224953. String parentDir, wildCard;
  224954. const char* wildcardUTF8;
  224955. NSDirectoryEnumerator* enumerator;
  224956. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  224957. };
  224958. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  224959. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  224960. {
  224961. }
  224962. DirectoryIterator::NativeIterator::~NativeIterator()
  224963. {
  224964. }
  224965. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  224966. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224967. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224968. {
  224969. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  224970. }
  224971. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  224972. {
  224973. #if JUCE_IOS
  224974. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  224975. #else
  224976. const ScopedAutoReleasePool pool;
  224977. if (parameters.isEmpty())
  224978. {
  224979. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  224980. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  224981. }
  224982. bool ok = false;
  224983. if (PlatformUtilities::isBundle (fileName))
  224984. {
  224985. NSMutableArray* urls = [NSMutableArray array];
  224986. StringArray docs;
  224987. docs.addTokens (parameters, true);
  224988. for (int i = 0; i < docs.size(); ++i)
  224989. [urls addObject: juceStringToNS (docs[i])];
  224990. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  224991. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  224992. options: 0
  224993. additionalEventParamDescriptor: nil
  224994. launchIdentifiers: nil];
  224995. }
  224996. else if (File (fileName).exists())
  224997. {
  224998. ok = FileHelpers::launchExecutable ("\"" + fileName + "\" " + parameters);
  224999. }
  225000. return ok;
  225001. #endif
  225002. }
  225003. void File::revealToUser() const
  225004. {
  225005. #if ! JUCE_IOS
  225006. if (exists())
  225007. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  225008. else if (getParentDirectory().exists())
  225009. getParentDirectory().revealToUser();
  225010. #endif
  225011. }
  225012. #if ! JUCE_IOS
  225013. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  225014. {
  225015. return FSPathMakeRef (reinterpret_cast <const UInt8*> (path.toUTF8().getAddress()), destFSRef, 0) == noErr;
  225016. }
  225017. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  225018. {
  225019. char path [2048];
  225020. zerostruct (path);
  225021. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  225022. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  225023. return String::empty;
  225024. }
  225025. #endif
  225026. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  225027. {
  225028. const ScopedAutoReleasePool pool;
  225029. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225030. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  225031. #else
  225032. // (the cast here avoids a deprecation warning)
  225033. NSDictionary* fileDict = [((id) [NSFileManager defaultManager]) fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  225034. #endif
  225035. return [fileDict fileHFSTypeCode];
  225036. }
  225037. bool PlatformUtilities::isBundle (const String& filename)
  225038. {
  225039. #if JUCE_IOS
  225040. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  225041. #else
  225042. const ScopedAutoReleasePool pool;
  225043. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  225044. #endif
  225045. }
  225046. #endif
  225047. /*** End of inlined file: juce_mac_Files.mm ***/
  225048. #if JUCE_IOS
  225049. /*** Start of inlined file: juce_ios_MiscUtilities.mm ***/
  225050. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225051. // compiled on its own).
  225052. #if JUCE_INCLUDED_FILE
  225053. END_JUCE_NAMESPACE
  225054. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  225055. {
  225056. }
  225057. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  225058. - (void) applicationWillTerminate: (UIApplication*) application;
  225059. @end
  225060. @implementation JuceAppStartupDelegate
  225061. - (void) applicationDidFinishLaunching: (UIApplication*) application
  225062. {
  225063. initialiseJuce_GUI();
  225064. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  225065. exit (0);
  225066. }
  225067. - (void) applicationWillTerminate: (UIApplication*) application
  225068. {
  225069. JUCEApplication::appWillTerminateByForce();
  225070. }
  225071. @end
  225072. BEGIN_JUCE_NAMESPACE
  225073. int juce_iOSMain (int argc, const char* argv[])
  225074. {
  225075. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  225076. }
  225077. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225078. {
  225079. pool = [[NSAutoreleasePool alloc] init];
  225080. }
  225081. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225082. {
  225083. [((NSAutoreleasePool*) pool) release];
  225084. }
  225085. void PlatformUtilities::beep()
  225086. {
  225087. //xxx
  225088. //AudioServicesPlaySystemSound ();
  225089. }
  225090. void PlatformUtilities::addItemToDock (const File& file)
  225091. {
  225092. }
  225093. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225094. END_JUCE_NAMESPACE
  225095. @interface JuceAlertBoxDelegate : NSObject
  225096. {
  225097. @public
  225098. bool clickedOk;
  225099. }
  225100. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  225101. @end
  225102. @implementation JuceAlertBoxDelegate
  225103. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  225104. {
  225105. clickedOk = (buttonIndex == 0);
  225106. alertView.hidden = true;
  225107. }
  225108. @end
  225109. BEGIN_JUCE_NAMESPACE
  225110. // (This function is used directly by other bits of code)
  225111. bool juce_iPhoneShowModalAlert (const String& title,
  225112. const String& bodyText,
  225113. NSString* okButtonText,
  225114. NSString* cancelButtonText)
  225115. {
  225116. const ScopedAutoReleasePool pool;
  225117. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  225118. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  225119. message: juceStringToNS (bodyText)
  225120. delegate: callback
  225121. cancelButtonTitle: okButtonText
  225122. otherButtonTitles: cancelButtonText, nil];
  225123. [alert retain];
  225124. [alert show];
  225125. while (! alert.hidden && alert.superview != nil)
  225126. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  225127. const bool result = callback->clickedOk;
  225128. [alert release];
  225129. [callback release];
  225130. return result;
  225131. }
  225132. bool AlertWindow::showNativeDialogBox (const String& title,
  225133. const String& bodyText,
  225134. bool isOkCancel)
  225135. {
  225136. return juce_iPhoneShowModalAlert (title, bodyText,
  225137. @"OK",
  225138. isOkCancel ? @"Cancel" : nil);
  225139. }
  225140. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  225141. {
  225142. jassertfalse; // no such thing on the iphone!
  225143. return false;
  225144. }
  225145. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  225146. {
  225147. jassertfalse; // no such thing on the iphone!
  225148. return false;
  225149. }
  225150. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225151. {
  225152. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  225153. }
  225154. bool Desktop::isScreenSaverEnabled()
  225155. {
  225156. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  225157. }
  225158. #endif
  225159. #endif
  225160. /*** End of inlined file: juce_ios_MiscUtilities.mm ***/
  225161. #else
  225162. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  225163. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225164. // compiled on its own).
  225165. #if JUCE_INCLUDED_FILE
  225166. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225167. {
  225168. pool = [[NSAutoreleasePool alloc] init];
  225169. }
  225170. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225171. {
  225172. [((NSAutoreleasePool*) pool) release];
  225173. }
  225174. void PlatformUtilities::beep()
  225175. {
  225176. NSBeep();
  225177. }
  225178. void PlatformUtilities::addItemToDock (const File& file)
  225179. {
  225180. // check that it's not already there...
  225181. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  225182. .containsIgnoreCase (file.getFullPathName()))
  225183. {
  225184. 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>"
  225185. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  225186. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  225187. }
  225188. }
  225189. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225190. bool AlertWindow::showNativeDialogBox (const String& title,
  225191. const String& bodyText,
  225192. bool isOkCancel)
  225193. {
  225194. const ScopedAutoReleasePool pool;
  225195. return NSRunAlertPanel (juceStringToNS (title),
  225196. juceStringToNS (bodyText),
  225197. @"Ok",
  225198. isOkCancel ? @"Cancel" : nil,
  225199. nil) == NSAlertDefaultReturn;
  225200. }
  225201. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  225202. {
  225203. if (files.size() == 0)
  225204. return false;
  225205. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  225206. if (draggingSource == 0)
  225207. {
  225208. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225209. return false;
  225210. }
  225211. Component* sourceComp = draggingSource->getComponentUnderMouse();
  225212. if (sourceComp == 0)
  225213. {
  225214. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225215. return false;
  225216. }
  225217. const ScopedAutoReleasePool pool;
  225218. NSView* view = (NSView*) sourceComp->getWindowHandle();
  225219. if (view == 0)
  225220. return false;
  225221. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  225222. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  225223. owner: nil];
  225224. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  225225. for (int i = 0; i < files.size(); ++i)
  225226. [filesArray addObject: juceStringToNS (files[i])];
  225227. [pboard setPropertyList: filesArray
  225228. forType: NSFilenamesPboardType];
  225229. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  225230. fromView: nil];
  225231. dragPosition.x -= 16;
  225232. dragPosition.y -= 16;
  225233. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  225234. at: dragPosition
  225235. offset: NSMakeSize (0, 0)
  225236. event: [[view window] currentEvent]
  225237. pasteboard: pboard
  225238. source: view
  225239. slideBack: YES];
  225240. return true;
  225241. }
  225242. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  225243. {
  225244. jassertfalse; // not implemented!
  225245. return false;
  225246. }
  225247. bool Desktop::canUseSemiTransparentWindows() throw()
  225248. {
  225249. return true;
  225250. }
  225251. const Point<int> MouseInputSource::getCurrentMousePosition()
  225252. {
  225253. const ScopedAutoReleasePool pool;
  225254. const NSPoint p ([NSEvent mouseLocation]);
  225255. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  225256. }
  225257. void Desktop::setMousePosition (const Point<int>& newPosition)
  225258. {
  225259. // this rubbish needs to be done around the warp call, to avoid causing a
  225260. // bizarre glitch..
  225261. CGAssociateMouseAndMouseCursorPosition (false);
  225262. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  225263. CGAssociateMouseAndMouseCursorPosition (true);
  225264. }
  225265. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  225266. {
  225267. return upright;
  225268. }
  225269. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225270. class ScreenSaverDefeater : public Timer,
  225271. public DeletedAtShutdown
  225272. {
  225273. public:
  225274. ScreenSaverDefeater()
  225275. {
  225276. startTimer (10000);
  225277. timerCallback();
  225278. }
  225279. ~ScreenSaverDefeater() {}
  225280. void timerCallback()
  225281. {
  225282. if (Process::isForegroundProcess())
  225283. UpdateSystemActivity (UsrActivity);
  225284. }
  225285. };
  225286. static ScreenSaverDefeater* screenSaverDefeater = 0;
  225287. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225288. {
  225289. if (isEnabled)
  225290. deleteAndZero (screenSaverDefeater);
  225291. else if (screenSaverDefeater == 0)
  225292. screenSaverDefeater = new ScreenSaverDefeater();
  225293. }
  225294. bool Desktop::isScreenSaverEnabled()
  225295. {
  225296. return screenSaverDefeater == 0;
  225297. }
  225298. #else
  225299. static IOPMAssertionID screenSaverDisablerID = 0;
  225300. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225301. {
  225302. if (isEnabled)
  225303. {
  225304. if (screenSaverDisablerID != 0)
  225305. {
  225306. IOPMAssertionRelease (screenSaverDisablerID);
  225307. screenSaverDisablerID = 0;
  225308. }
  225309. }
  225310. else
  225311. {
  225312. if (screenSaverDisablerID == 0)
  225313. {
  225314. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225315. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225316. CFSTR ("Juce"), &screenSaverDisablerID);
  225317. #else
  225318. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225319. &screenSaverDisablerID);
  225320. #endif
  225321. }
  225322. }
  225323. }
  225324. bool Desktop::isScreenSaverEnabled()
  225325. {
  225326. return screenSaverDisablerID == 0;
  225327. }
  225328. #endif
  225329. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  225330. {
  225331. const ScopedAutoReleasePool pool;
  225332. monitorCoords.clear();
  225333. NSArray* screens = [NSScreen screens];
  225334. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  225335. for (unsigned int i = 0; i < [screens count]; ++i)
  225336. {
  225337. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  225338. NSRect r = clipToWorkArea ? [s visibleFrame]
  225339. : [s frame];
  225340. r.origin.y = mainScreenBottom - (r.origin.y + r.size.height);
  225341. monitorCoords.add (convertToRectInt (r));
  225342. }
  225343. jassert (monitorCoords.size() > 0);
  225344. }
  225345. #endif
  225346. #endif
  225347. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  225348. #endif
  225349. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  225350. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225351. // compiled on its own).
  225352. #if JUCE_INCLUDED_FILE
  225353. void Logger::outputDebugString (const String& text)
  225354. {
  225355. std::cerr << text << std::endl;
  225356. }
  225357. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  225358. {
  225359. static char testResult = 0;
  225360. if (testResult == 0)
  225361. {
  225362. struct kinfo_proc info;
  225363. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  225364. size_t sz = sizeof (info);
  225365. sysctl (m, 4, &info, &sz, 0, 0);
  225366. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  225367. }
  225368. return testResult > 0;
  225369. }
  225370. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  225371. {
  225372. return juce_isRunningUnderDebugger();
  225373. }
  225374. #endif
  225375. /*** End of inlined file: juce_mac_Debugging.mm ***/
  225376. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225377. #if JUCE_IOS
  225378. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  225379. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225380. // compiled on its own).
  225381. #if JUCE_INCLUDED_FILE
  225382. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225383. #define SUPPORT_10_4_FONTS 1
  225384. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  225385. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  225386. #define SUPPORT_ONLY_10_4_FONTS 1
  225387. #endif
  225388. END_JUCE_NAMESPACE
  225389. @interface NSFont (PrivateHack)
  225390. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  225391. @end
  225392. BEGIN_JUCE_NAMESPACE
  225393. #endif
  225394. class MacTypeface : public Typeface
  225395. {
  225396. public:
  225397. MacTypeface (const Font& font)
  225398. : Typeface (font.getTypefaceName())
  225399. {
  225400. const ScopedAutoReleasePool pool;
  225401. renderingTransform = CGAffineTransformIdentity;
  225402. bool needsItalicTransform = false;
  225403. #if JUCE_IOS
  225404. NSString* fontName = juceStringToNS (font.getTypefaceName());
  225405. if (font.isItalic() || font.isBold())
  225406. {
  225407. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  225408. for (NSString* i in familyFonts)
  225409. {
  225410. const String fn (nsStringToJuce (i));
  225411. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  225412. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  225413. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  225414. || afterDash.containsIgnoreCase ("italic")
  225415. || fn.endsWithIgnoreCase ("oblique")
  225416. || fn.endsWithIgnoreCase ("italic");
  225417. if (probablyBold == font.isBold()
  225418. && probablyItalic == font.isItalic())
  225419. {
  225420. fontName = i;
  225421. needsItalicTransform = false;
  225422. break;
  225423. }
  225424. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  225425. {
  225426. fontName = i;
  225427. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  225428. }
  225429. }
  225430. if (needsItalicTransform)
  225431. renderingTransform.c = 0.15f;
  225432. }
  225433. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  225434. const int ascender = abs (CGFontGetAscent (fontRef));
  225435. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  225436. ascent = ascender / totalHeight;
  225437. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225438. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  225439. #else
  225440. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  225441. if (font.isItalic())
  225442. {
  225443. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  225444. toHaveTrait: NSItalicFontMask];
  225445. if (newFont == nsFont)
  225446. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  225447. nsFont = newFont;
  225448. }
  225449. if (font.isBold())
  225450. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  225451. [nsFont retain];
  225452. ascent = std::abs ((float) [nsFont ascender]);
  225453. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  225454. ascent /= totalSize;
  225455. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  225456. if (needsItalicTransform)
  225457. {
  225458. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  225459. renderingTransform.c = 0.15f;
  225460. }
  225461. #if SUPPORT_ONLY_10_4_FONTS
  225462. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225463. if (atsFont == 0)
  225464. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225465. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225466. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  225467. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225468. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225469. #else
  225470. #if SUPPORT_10_4_FONTS
  225471. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225472. {
  225473. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225474. if (atsFont == 0)
  225475. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225476. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225477. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  225478. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225479. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225480. }
  225481. else
  225482. #endif
  225483. {
  225484. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  225485. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  225486. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225487. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  225488. }
  225489. #endif
  225490. #endif
  225491. }
  225492. ~MacTypeface()
  225493. {
  225494. #if ! JUCE_IOS
  225495. [nsFont release];
  225496. #endif
  225497. if (fontRef != 0)
  225498. CGFontRelease (fontRef);
  225499. }
  225500. float getAscent() const
  225501. {
  225502. return ascent;
  225503. }
  225504. float getDescent() const
  225505. {
  225506. return 1.0f - ascent;
  225507. }
  225508. float getStringWidth (const String& text)
  225509. {
  225510. if (fontRef == 0 || text.isEmpty())
  225511. return 0;
  225512. const int length = text.length();
  225513. HeapBlock <CGGlyph> glyphs;
  225514. createGlyphsForString (text.getCharPointer(), length, glyphs);
  225515. float x = 0;
  225516. #if SUPPORT_ONLY_10_4_FONTS
  225517. HeapBlock <NSSize> advances (length);
  225518. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225519. for (int i = 0; i < length; ++i)
  225520. x += advances[i].width;
  225521. #else
  225522. #if SUPPORT_10_4_FONTS
  225523. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225524. {
  225525. HeapBlock <NSSize> advances (length);
  225526. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  225527. for (int i = 0; i < length; ++i)
  225528. x += advances[i].width;
  225529. }
  225530. else
  225531. #endif
  225532. {
  225533. HeapBlock <int> advances (length);
  225534. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225535. for (int i = 0; i < length; ++i)
  225536. x += advances[i];
  225537. }
  225538. #endif
  225539. return x * unitsToHeightScaleFactor;
  225540. }
  225541. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  225542. {
  225543. xOffsets.add (0);
  225544. if (fontRef == 0 || text.isEmpty())
  225545. return;
  225546. const int length = text.length();
  225547. HeapBlock <CGGlyph> glyphs;
  225548. createGlyphsForString (text.getCharPointer(), length, glyphs);
  225549. #if SUPPORT_ONLY_10_4_FONTS
  225550. HeapBlock <NSSize> advances (length);
  225551. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225552. int x = 0;
  225553. for (int i = 0; i < length; ++i)
  225554. {
  225555. x += advances[i].width;
  225556. xOffsets.add (x * unitsToHeightScaleFactor);
  225557. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  225558. }
  225559. #else
  225560. #if SUPPORT_10_4_FONTS
  225561. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225562. {
  225563. HeapBlock <NSSize> advances (length);
  225564. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  225565. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  225566. float x = 0;
  225567. for (int i = 0; i < length; ++i)
  225568. {
  225569. x += advances[i].width;
  225570. xOffsets.add (x * unitsToHeightScaleFactor);
  225571. resultGlyphs.add (nsGlyphs[i]);
  225572. }
  225573. }
  225574. else
  225575. #endif
  225576. {
  225577. HeapBlock <int> advances (length);
  225578. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225579. {
  225580. int x = 0;
  225581. for (int i = 0; i < length; ++i)
  225582. {
  225583. x += advances [i];
  225584. xOffsets.add (x * unitsToHeightScaleFactor);
  225585. resultGlyphs.add (glyphs[i]);
  225586. }
  225587. }
  225588. }
  225589. #endif
  225590. }
  225591. bool getOutlineForGlyph (int glyphNumber, Path& path)
  225592. {
  225593. #if JUCE_IOS
  225594. return false;
  225595. #else
  225596. if (nsFont == 0)
  225597. return false;
  225598. // we might need to apply a transform to the path, so it mustn't have anything else in it
  225599. jassert (path.isEmpty());
  225600. const ScopedAutoReleasePool pool;
  225601. NSBezierPath* bez = [NSBezierPath bezierPath];
  225602. [bez moveToPoint: NSMakePoint (0, 0)];
  225603. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  225604. inFont: nsFont];
  225605. for (int i = 0; i < [bez elementCount]; ++i)
  225606. {
  225607. NSPoint p[3];
  225608. switch ([bez elementAtIndex: i associatedPoints: p])
  225609. {
  225610. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  225611. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  225612. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  225613. (float) p[1].x, (float) -p[1].y,
  225614. (float) p[2].x, (float) -p[2].y); break;
  225615. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  225616. default: jassertfalse; break;
  225617. }
  225618. }
  225619. path.applyTransform (pathTransform);
  225620. return true;
  225621. #endif
  225622. }
  225623. CGFontRef fontRef;
  225624. float fontHeightToCGSizeFactor;
  225625. CGAffineTransform renderingTransform;
  225626. private:
  225627. float ascent, unitsToHeightScaleFactor;
  225628. #if JUCE_IOS
  225629. #else
  225630. NSFont* nsFont;
  225631. AffineTransform pathTransform;
  225632. #endif
  225633. void createGlyphsForString (String::CharPointerType text, const int length, HeapBlock <CGGlyph>& glyphs)
  225634. {
  225635. #if SUPPORT_10_4_FONTS
  225636. #if ! SUPPORT_ONLY_10_4_FONTS
  225637. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225638. #endif
  225639. {
  225640. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  225641. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  225642. for (int i = 0; i < length; ++i)
  225643. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text.getAndAdvance()];
  225644. return;
  225645. }
  225646. #endif
  225647. #if ! SUPPORT_ONLY_10_4_FONTS
  225648. if (charToGlyphMapper == 0)
  225649. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  225650. glyphs.malloc (length);
  225651. for (int i = 0; i < length; ++i)
  225652. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text.getAndAdvance());
  225653. #endif
  225654. }
  225655. #if ! SUPPORT_ONLY_10_4_FONTS
  225656. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  225657. class CharToGlyphMapper
  225658. {
  225659. public:
  225660. CharToGlyphMapper (CGFontRef fontRef)
  225661. : segCount (0), endCode (0), startCode (0), idDelta (0),
  225662. idRangeOffset (0), glyphIndexes (0)
  225663. {
  225664. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  225665. if (cmapTable != 0)
  225666. {
  225667. const int numSubtables = getValue16 (cmapTable, 2);
  225668. for (int i = 0; i < numSubtables; ++i)
  225669. {
  225670. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  225671. {
  225672. const int offset = getValue32 (cmapTable, i * 8 + 8);
  225673. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  225674. {
  225675. const int length = getValue16 (cmapTable, offset + 2);
  225676. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  225677. segCount = segCountX2 / 2;
  225678. const int endCodeOffset = offset + 14;
  225679. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  225680. const int idDeltaOffset = startCodeOffset + segCountX2;
  225681. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  225682. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  225683. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  225684. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  225685. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  225686. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  225687. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  225688. }
  225689. break;
  225690. }
  225691. }
  225692. CFRelease (cmapTable);
  225693. }
  225694. }
  225695. ~CharToGlyphMapper()
  225696. {
  225697. if (endCode != 0)
  225698. {
  225699. CFRelease (endCode);
  225700. CFRelease (startCode);
  225701. CFRelease (idDelta);
  225702. CFRelease (idRangeOffset);
  225703. CFRelease (glyphIndexes);
  225704. }
  225705. }
  225706. int getGlyphForCharacter (const juce_wchar c) const
  225707. {
  225708. for (int i = 0; i < segCount; ++i)
  225709. {
  225710. if (getValue16 (endCode, i * 2) >= c)
  225711. {
  225712. const int start = getValue16 (startCode, i * 2);
  225713. if (start > c)
  225714. break;
  225715. const int delta = getValue16 (idDelta, i * 2);
  225716. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  225717. if (rangeOffset == 0)
  225718. return delta + c;
  225719. else
  225720. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  225721. }
  225722. }
  225723. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  225724. return jmax (-1, (int) c - 29);
  225725. }
  225726. private:
  225727. int segCount;
  225728. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  225729. static uint16 getValue16 (CFDataRef data, const int index)
  225730. {
  225731. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  225732. }
  225733. static uint32 getValue32 (CFDataRef data, const int index)
  225734. {
  225735. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  225736. }
  225737. };
  225738. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  225739. #endif
  225740. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  225741. };
  225742. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  225743. {
  225744. return new MacTypeface (font);
  225745. }
  225746. const StringArray Font::findAllTypefaceNames()
  225747. {
  225748. StringArray names;
  225749. const ScopedAutoReleasePool pool;
  225750. #if JUCE_IOS
  225751. NSArray* fonts = [UIFont familyNames];
  225752. #else
  225753. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  225754. #endif
  225755. for (unsigned int i = 0; i < [fonts count]; ++i)
  225756. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  225757. names.sort (true);
  225758. return names;
  225759. }
  225760. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  225761. {
  225762. #if JUCE_IOS
  225763. defaultSans = "Helvetica";
  225764. defaultSerif = "Times New Roman";
  225765. defaultFixed = "Courier New";
  225766. #else
  225767. defaultSans = "Lucida Grande";
  225768. defaultSerif = "Times New Roman";
  225769. defaultFixed = "Monaco";
  225770. #endif
  225771. defaultFallback = "Arial Unicode MS";
  225772. }
  225773. #endif
  225774. /*** End of inlined file: juce_mac_Fonts.mm ***/
  225775. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  225776. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225777. // compiled on its own).
  225778. #if JUCE_INCLUDED_FILE
  225779. class CoreGraphicsImage : public Image::SharedImage
  225780. {
  225781. public:
  225782. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  225783. : Image::SharedImage (format_, width_, height_)
  225784. {
  225785. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  225786. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  225787. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  225788. imageData = imageDataAllocated;
  225789. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  225790. : CGColorSpaceCreateDeviceRGB();
  225791. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  225792. colourSpace, getCGImageFlags (format_));
  225793. CGColorSpaceRelease (colourSpace);
  225794. }
  225795. ~CoreGraphicsImage()
  225796. {
  225797. CGContextRelease (context);
  225798. }
  225799. Image::ImageType getType() const { return Image::NativeImage; }
  225800. LowLevelGraphicsContext* createLowLevelContext();
  225801. SharedImage* clone()
  225802. {
  225803. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  225804. memcpy (im->imageData, imageData, lineStride * height);
  225805. return im;
  225806. }
  225807. static CGImageRef createImage (const Image& juceImage, const bool forAlpha,
  225808. CGColorSpaceRef colourSpace, const bool mustOutliveSource)
  225809. {
  225810. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  225811. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  225812. {
  225813. return CGBitmapContextCreateImage (nativeImage->context);
  225814. }
  225815. else
  225816. {
  225817. const Image::BitmapData srcData (juceImage, false);
  225818. CGDataProviderRef provider;
  225819. if (mustOutliveSource)
  225820. {
  225821. CFDataRef data = CFDataCreate (0, (const UInt8*) srcData.data, (CFIndex) (srcData.lineStride * srcData.height));
  225822. provider = CGDataProviderCreateWithCFData (data);
  225823. CFRelease (data);
  225824. }
  225825. else
  225826. {
  225827. provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  225828. }
  225829. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  225830. 8, srcData.pixelStride * 8, srcData.lineStride,
  225831. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  225832. 0, true, kCGRenderingIntentDefault);
  225833. CGDataProviderRelease (provider);
  225834. return imageRef;
  225835. }
  225836. }
  225837. #if JUCE_MAC
  225838. static NSImage* createNSImage (const Image& image)
  225839. {
  225840. const ScopedAutoReleasePool pool;
  225841. NSImage* im = [[NSImage alloc] init];
  225842. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  225843. [im lockFocus];
  225844. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  225845. CGImageRef imageRef = createImage (image, false, colourSpace, false);
  225846. CGColorSpaceRelease (colourSpace);
  225847. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  225848. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  225849. CGImageRelease (imageRef);
  225850. [im unlockFocus];
  225851. return im;
  225852. }
  225853. #endif
  225854. CGContextRef context;
  225855. HeapBlock<uint8> imageDataAllocated;
  225856. private:
  225857. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  225858. {
  225859. #if JUCE_BIG_ENDIAN
  225860. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  225861. #else
  225862. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  225863. #endif
  225864. }
  225865. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsImage);
  225866. };
  225867. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  225868. {
  225869. #if USE_COREGRAPHICS_RENDERING
  225870. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  225871. #else
  225872. return createSoftwareImage (format, width, height, clearImage);
  225873. #endif
  225874. }
  225875. class CoreGraphicsContext : public LowLevelGraphicsContext
  225876. {
  225877. public:
  225878. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  225879. : context (context_),
  225880. flipHeight (flipHeight_),
  225881. lastClipRectIsValid (false),
  225882. state (new SavedState()),
  225883. numGradientLookupEntries (0)
  225884. {
  225885. CGContextRetain (context);
  225886. CGContextSaveGState(context);
  225887. CGContextSetShouldSmoothFonts (context, true);
  225888. CGContextSetShouldAntialias (context, true);
  225889. CGContextSetBlendMode (context, kCGBlendModeNormal);
  225890. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  225891. greyColourSpace = CGColorSpaceCreateDeviceGray();
  225892. gradientCallbacks.version = 0;
  225893. gradientCallbacks.evaluate = gradientCallback;
  225894. gradientCallbacks.releaseInfo = 0;
  225895. setFont (Font());
  225896. }
  225897. ~CoreGraphicsContext()
  225898. {
  225899. CGContextRestoreGState (context);
  225900. CGContextRelease (context);
  225901. CGColorSpaceRelease (rgbColourSpace);
  225902. CGColorSpaceRelease (greyColourSpace);
  225903. }
  225904. bool isVectorDevice() const { return false; }
  225905. void setOrigin (int x, int y)
  225906. {
  225907. CGContextTranslateCTM (context, x, -y);
  225908. if (lastClipRectIsValid)
  225909. lastClipRect.translate (-x, -y);
  225910. }
  225911. void addTransform (const AffineTransform& transform)
  225912. {
  225913. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  225914. .translated (0, flipHeight)
  225915. .followedBy (transform)
  225916. .translated (0, -flipHeight)
  225917. .scaled (1.0f, -1.0f));
  225918. lastClipRectIsValid = false;
  225919. }
  225920. float getScaleFactor()
  225921. {
  225922. CGAffineTransform t = CGContextGetCTM (context);
  225923. return (float) juce_hypot (t.a + t.c, t.b + t.d);
  225924. }
  225925. bool clipToRectangle (const Rectangle<int>& r)
  225926. {
  225927. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  225928. if (lastClipRectIsValid)
  225929. {
  225930. // This is actually incorrect, because the actual clip region may be complex, and
  225931. // clipping its bounds to a rect may not be right... But, removing this shortcut
  225932. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  225933. // when calculating the resultant clip bounds, and makes the same mistake!
  225934. lastClipRect = lastClipRect.getIntersection (r);
  225935. return ! lastClipRect.isEmpty();
  225936. }
  225937. return ! isClipEmpty();
  225938. }
  225939. bool clipToRectangleList (const RectangleList& clipRegion)
  225940. {
  225941. if (clipRegion.isEmpty())
  225942. {
  225943. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  225944. lastClipRectIsValid = true;
  225945. lastClipRect = Rectangle<int>();
  225946. return false;
  225947. }
  225948. else
  225949. {
  225950. const int numRects = clipRegion.getNumRectangles();
  225951. HeapBlock <CGRect> rects (numRects);
  225952. for (int i = 0; i < numRects; ++i)
  225953. {
  225954. const Rectangle<int>& r = clipRegion.getRectangle(i);
  225955. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  225956. }
  225957. CGContextClipToRects (context, rects, numRects);
  225958. lastClipRectIsValid = false;
  225959. return ! isClipEmpty();
  225960. }
  225961. }
  225962. void excludeClipRectangle (const Rectangle<int>& r)
  225963. {
  225964. RectangleList remaining (getClipBounds());
  225965. remaining.subtract (r);
  225966. clipToRectangleList (remaining);
  225967. lastClipRectIsValid = false;
  225968. }
  225969. void clipToPath (const Path& path, const AffineTransform& transform)
  225970. {
  225971. createPath (path, transform);
  225972. CGContextClip (context);
  225973. lastClipRectIsValid = false;
  225974. }
  225975. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  225976. {
  225977. if (! transform.isSingularity())
  225978. {
  225979. Image singleChannelImage (sourceImage);
  225980. if (sourceImage.getFormat() != Image::SingleChannel)
  225981. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  225982. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace, true);
  225983. flip();
  225984. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  225985. applyTransform (t);
  225986. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  225987. CGContextClipToMask (context, r, image);
  225988. applyTransform (t.inverted());
  225989. flip();
  225990. CGImageRelease (image);
  225991. lastClipRectIsValid = false;
  225992. }
  225993. }
  225994. bool clipRegionIntersects (const Rectangle<int>& r)
  225995. {
  225996. return getClipBounds().intersects (r);
  225997. }
  225998. const Rectangle<int> getClipBounds() const
  225999. {
  226000. if (! lastClipRectIsValid)
  226001. {
  226002. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226003. lastClipRectIsValid = true;
  226004. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  226005. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  226006. roundToInt (bounds.size.width),
  226007. roundToInt (bounds.size.height));
  226008. }
  226009. return lastClipRect;
  226010. }
  226011. bool isClipEmpty() const
  226012. {
  226013. return getClipBounds().isEmpty();
  226014. }
  226015. void saveState()
  226016. {
  226017. CGContextSaveGState (context);
  226018. stateStack.add (new SavedState (*state));
  226019. }
  226020. void restoreState()
  226021. {
  226022. CGContextRestoreGState (context);
  226023. SavedState* const top = stateStack.getLast();
  226024. if (top != 0)
  226025. {
  226026. state = top;
  226027. stateStack.removeLast (1, false);
  226028. lastClipRectIsValid = false;
  226029. }
  226030. else
  226031. {
  226032. jassertfalse; // trying to pop with an empty stack!
  226033. }
  226034. }
  226035. void beginTransparencyLayer (float opacity)
  226036. {
  226037. saveState();
  226038. CGContextSetAlpha (context, opacity);
  226039. CGContextBeginTransparencyLayer (context, 0);
  226040. }
  226041. void endTransparencyLayer()
  226042. {
  226043. CGContextEndTransparencyLayer (context);
  226044. restoreState();
  226045. }
  226046. void setFill (const FillType& fillType)
  226047. {
  226048. state->fillType = fillType;
  226049. if (fillType.isColour())
  226050. {
  226051. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  226052. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  226053. CGContextSetAlpha (context, 1.0f);
  226054. }
  226055. }
  226056. void setOpacity (float newOpacity)
  226057. {
  226058. state->fillType.setOpacity (newOpacity);
  226059. setFill (state->fillType);
  226060. }
  226061. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  226062. {
  226063. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  226064. ? kCGInterpolationLow
  226065. : kCGInterpolationHigh);
  226066. }
  226067. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  226068. {
  226069. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  226070. }
  226071. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  226072. {
  226073. if (replaceExistingContents)
  226074. {
  226075. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226076. CGContextClearRect (context, cgRect);
  226077. #else
  226078. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226079. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  226080. CGContextClearRect (context, cgRect);
  226081. else
  226082. #endif
  226083. CGContextSetBlendMode (context, kCGBlendModeCopy);
  226084. #endif
  226085. fillCGRect (cgRect, false);
  226086. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226087. }
  226088. else
  226089. {
  226090. if (state->fillType.isColour())
  226091. {
  226092. CGContextFillRect (context, cgRect);
  226093. }
  226094. else if (state->fillType.isGradient())
  226095. {
  226096. CGContextSaveGState (context);
  226097. CGContextClipToRect (context, cgRect);
  226098. drawGradient();
  226099. CGContextRestoreGState (context);
  226100. }
  226101. else
  226102. {
  226103. CGContextSaveGState (context);
  226104. CGContextClipToRect (context, cgRect);
  226105. drawImage (state->fillType.image, state->fillType.transform, true);
  226106. CGContextRestoreGState (context);
  226107. }
  226108. }
  226109. }
  226110. void fillPath (const Path& path, const AffineTransform& transform)
  226111. {
  226112. CGContextSaveGState (context);
  226113. if (state->fillType.isColour())
  226114. {
  226115. flip();
  226116. applyTransform (transform);
  226117. createPath (path);
  226118. if (path.isUsingNonZeroWinding())
  226119. CGContextFillPath (context);
  226120. else
  226121. CGContextEOFillPath (context);
  226122. }
  226123. else
  226124. {
  226125. createPath (path, transform);
  226126. if (path.isUsingNonZeroWinding())
  226127. CGContextClip (context);
  226128. else
  226129. CGContextEOClip (context);
  226130. if (state->fillType.isGradient())
  226131. drawGradient();
  226132. else
  226133. drawImage (state->fillType.image, state->fillType.transform, true);
  226134. }
  226135. CGContextRestoreGState (context);
  226136. }
  226137. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  226138. {
  226139. const int iw = sourceImage.getWidth();
  226140. const int ih = sourceImage.getHeight();
  226141. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace, false);
  226142. CGContextSaveGState (context);
  226143. CGContextSetAlpha (context, state->fillType.getOpacity());
  226144. flip();
  226145. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  226146. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  226147. if (fillEntireClipAsTiles)
  226148. {
  226149. #if JUCE_IOS
  226150. CGContextDrawTiledImage (context, imageRect, image);
  226151. #else
  226152. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  226153. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  226154. // if it's doing a transformation - it's quicker to just draw lots of images manually
  226155. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  226156. CGContextDrawTiledImage (context, imageRect, image);
  226157. else
  226158. #endif
  226159. {
  226160. // Fallback to manually doing a tiled fill on 10.4
  226161. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226162. int x = 0, y = 0;
  226163. while (x > clip.origin.x) x -= iw;
  226164. while (y > clip.origin.y) y -= ih;
  226165. const int right = (int) (clip.origin.x + clip.size.width);
  226166. const int bottom = (int) (clip.origin.y + clip.size.height);
  226167. while (y < bottom)
  226168. {
  226169. for (int x2 = x; x2 < right; x2 += iw)
  226170. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  226171. y += ih;
  226172. }
  226173. }
  226174. #endif
  226175. }
  226176. else
  226177. {
  226178. CGContextDrawImage (context, imageRect, image);
  226179. }
  226180. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  226181. CGContextRestoreGState (context);
  226182. }
  226183. void drawLine (const Line<float>& line)
  226184. {
  226185. if (state->fillType.isColour())
  226186. {
  226187. CGContextSetLineCap (context, kCGLineCapSquare);
  226188. CGContextSetLineWidth (context, 1.0f);
  226189. CGContextSetRGBStrokeColor (context,
  226190. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  226191. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  226192. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  226193. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  226194. CGContextStrokeLineSegments (context, cgLine, 1);
  226195. }
  226196. else
  226197. {
  226198. Path p;
  226199. p.addLineSegment (line, 1.0f);
  226200. fillPath (p, AffineTransform::identity);
  226201. }
  226202. }
  226203. void drawVerticalLine (const int x, float top, float bottom)
  226204. {
  226205. if (state->fillType.isColour())
  226206. {
  226207. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226208. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  226209. #else
  226210. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226211. // the x co-ord slightly to trick it..
  226212. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  226213. #endif
  226214. }
  226215. else
  226216. {
  226217. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  226218. }
  226219. }
  226220. void drawHorizontalLine (const int y, float left, float right)
  226221. {
  226222. if (state->fillType.isColour())
  226223. {
  226224. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226225. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  226226. #else
  226227. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226228. // the x co-ord slightly to trick it..
  226229. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  226230. #endif
  226231. }
  226232. else
  226233. {
  226234. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  226235. }
  226236. }
  226237. void setFont (const Font& newFont)
  226238. {
  226239. if (state->font != newFont)
  226240. {
  226241. state->fontRef = 0;
  226242. state->font = newFont;
  226243. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  226244. if (mf != 0)
  226245. {
  226246. state->fontRef = mf->fontRef;
  226247. CGContextSetFont (context, state->fontRef);
  226248. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  226249. state->fontTransform = mf->renderingTransform;
  226250. state->fontTransform.a *= state->font.getHorizontalScale();
  226251. CGContextSetTextMatrix (context, state->fontTransform);
  226252. }
  226253. }
  226254. }
  226255. const Font getFont()
  226256. {
  226257. return state->font;
  226258. }
  226259. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  226260. {
  226261. if (state->fontRef != 0 && state->fillType.isColour())
  226262. {
  226263. if (transform.isOnlyTranslation())
  226264. {
  226265. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  226266. CGGlyph g = glyphNumber;
  226267. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  226268. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  226269. }
  226270. else
  226271. {
  226272. CGContextSaveGState (context);
  226273. flip();
  226274. applyTransform (transform);
  226275. CGAffineTransform t = state->fontTransform;
  226276. t.d = -t.d;
  226277. CGContextSetTextMatrix (context, t);
  226278. CGGlyph g = glyphNumber;
  226279. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  226280. CGContextRestoreGState (context);
  226281. }
  226282. }
  226283. else
  226284. {
  226285. Path p;
  226286. Font& f = state->font;
  226287. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  226288. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  226289. .followedBy (transform));
  226290. }
  226291. }
  226292. private:
  226293. CGContextRef context;
  226294. const CGFloat flipHeight;
  226295. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  226296. CGFunctionCallbacks gradientCallbacks;
  226297. mutable Rectangle<int> lastClipRect;
  226298. mutable bool lastClipRectIsValid;
  226299. struct SavedState
  226300. {
  226301. SavedState()
  226302. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  226303. {
  226304. }
  226305. SavedState (const SavedState& other)
  226306. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  226307. fontTransform (other.fontTransform)
  226308. {
  226309. }
  226310. FillType fillType;
  226311. Font font;
  226312. CGFontRef fontRef;
  226313. CGAffineTransform fontTransform;
  226314. };
  226315. ScopedPointer <SavedState> state;
  226316. OwnedArray <SavedState> stateStack;
  226317. HeapBlock <PixelARGB> gradientLookupTable;
  226318. int numGradientLookupEntries;
  226319. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  226320. {
  226321. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  226322. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  226323. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  226324. colour.unpremultiply();
  226325. outData[0] = colour.getRed() / 255.0f;
  226326. outData[1] = colour.getGreen() / 255.0f;
  226327. outData[2] = colour.getBlue() / 255.0f;
  226328. outData[3] = colour.getAlpha() / 255.0f;
  226329. }
  226330. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  226331. {
  226332. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable) - 1;
  226333. CGShadingRef result = 0;
  226334. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  226335. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  226336. if (gradient.isRadial)
  226337. {
  226338. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  226339. p1, gradient.point1.getDistanceFrom (gradient.point2),
  226340. function, true, true);
  226341. }
  226342. else
  226343. {
  226344. result = CGShadingCreateAxial (rgbColourSpace, p1,
  226345. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  226346. function, true, true);
  226347. }
  226348. CGFunctionRelease (function);
  226349. return result;
  226350. }
  226351. void drawGradient()
  226352. {
  226353. flip();
  226354. applyTransform (state->fillType.transform);
  226355. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  226356. // you draw a gradient with high quality interp enabled).
  226357. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  226358. CGContextSetAlpha (context, state->fillType.getOpacity());
  226359. CGContextDrawShading (context, shading);
  226360. CGShadingRelease (shading);
  226361. }
  226362. void createPath (const Path& path) const
  226363. {
  226364. CGContextBeginPath (context);
  226365. Path::Iterator i (path);
  226366. while (i.next())
  226367. {
  226368. switch (i.elementType)
  226369. {
  226370. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  226371. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  226372. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  226373. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  226374. case Path::Iterator::closePath: CGContextClosePath (context); break;
  226375. default: jassertfalse; break;
  226376. }
  226377. }
  226378. }
  226379. void createPath (const Path& path, const AffineTransform& transform) const
  226380. {
  226381. CGContextBeginPath (context);
  226382. Path::Iterator i (path);
  226383. while (i.next())
  226384. {
  226385. switch (i.elementType)
  226386. {
  226387. case Path::Iterator::startNewSubPath:
  226388. transform.transformPoint (i.x1, i.y1);
  226389. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  226390. break;
  226391. case Path::Iterator::lineTo:
  226392. transform.transformPoint (i.x1, i.y1);
  226393. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  226394. break;
  226395. case Path::Iterator::quadraticTo:
  226396. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  226397. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  226398. break;
  226399. case Path::Iterator::cubicTo:
  226400. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  226401. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  226402. break;
  226403. case Path::Iterator::closePath:
  226404. CGContextClosePath (context); break;
  226405. default:
  226406. jassertfalse;
  226407. break;
  226408. }
  226409. }
  226410. }
  226411. void flip() const
  226412. {
  226413. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  226414. }
  226415. void applyTransform (const AffineTransform& transform) const
  226416. {
  226417. CGAffineTransform t;
  226418. t.a = transform.mat00;
  226419. t.b = transform.mat10;
  226420. t.c = transform.mat01;
  226421. t.d = transform.mat11;
  226422. t.tx = transform.mat02;
  226423. t.ty = transform.mat12;
  226424. CGContextConcatCTM (context, t);
  226425. }
  226426. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext);
  226427. };
  226428. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  226429. {
  226430. return new CoreGraphicsContext (context, height);
  226431. }
  226432. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  226433. const Image juce_loadWithCoreImage (InputStream& input)
  226434. {
  226435. MemoryBlock data;
  226436. input.readIntoMemoryBlock (data, -1);
  226437. #if JUCE_IOS
  226438. JUCE_AUTORELEASEPOOL
  226439. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  226440. length: data.getSize()
  226441. freeWhenDone: NO]];
  226442. if (image != nil)
  226443. {
  226444. CGImageRef loadedImage = image.CGImage;
  226445. #else
  226446. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  226447. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  226448. CGDataProviderRelease (provider);
  226449. if (imageSource != 0)
  226450. {
  226451. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  226452. CFRelease (imageSource);
  226453. #endif
  226454. if (loadedImage != 0)
  226455. {
  226456. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  226457. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  226458. && alphaInfo != kCGImageAlphaNoneSkipLast
  226459. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  226460. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  226461. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  226462. hasAlphaChan, Image::NativeImage);
  226463. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  226464. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  226465. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  226466. CGContextFlush (cgImage->context);
  226467. #if ! JUCE_IOS
  226468. CFRelease (loadedImage);
  226469. #endif
  226470. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  226471. // to find out whether the file they just loaded the image from had an alpha channel or not.
  226472. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  226473. return image;
  226474. }
  226475. }
  226476. return Image::null;
  226477. }
  226478. #endif
  226479. #endif
  226480. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226481. /*** Start of inlined file: juce_ios_UIViewComponentPeer.mm ***/
  226482. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226483. // compiled on its own).
  226484. #if JUCE_INCLUDED_FILE
  226485. class UIViewComponentPeer;
  226486. END_JUCE_NAMESPACE
  226487. #define JuceUIView MakeObjCClassName(JuceUIView)
  226488. @interface JuceUIView : UIView <UITextViewDelegate>
  226489. {
  226490. @public
  226491. UIViewComponentPeer* owner;
  226492. UITextView* hiddenTextView;
  226493. }
  226494. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  226495. - (void) dealloc;
  226496. - (void) drawRect: (CGRect) r;
  226497. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  226498. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  226499. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  226500. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  226501. - (BOOL) becomeFirstResponder;
  226502. - (BOOL) resignFirstResponder;
  226503. - (BOOL) canBecomeFirstResponder;
  226504. - (void) asyncRepaint: (id) rect;
  226505. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  226506. @end
  226507. #define JuceUIViewController MakeObjCClassName(JuceUIViewController)
  226508. @interface JuceUIViewController : UIViewController
  226509. {
  226510. }
  226511. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation;
  226512. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation;
  226513. @end
  226514. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  226515. @interface JuceUIWindow : UIWindow
  226516. {
  226517. @private
  226518. UIViewComponentPeer* owner;
  226519. bool isZooming;
  226520. }
  226521. - (void) setOwner: (UIViewComponentPeer*) owner;
  226522. - (void) becomeKeyWindow;
  226523. @end
  226524. BEGIN_JUCE_NAMESPACE
  226525. class UIViewComponentPeer : public ComponentPeer,
  226526. public FocusChangeListener
  226527. {
  226528. public:
  226529. UIViewComponentPeer (Component* const component,
  226530. const int windowStyleFlags,
  226531. UIView* viewToAttachTo);
  226532. ~UIViewComponentPeer();
  226533. void* getNativeHandle() const;
  226534. void setVisible (bool shouldBeVisible);
  226535. void setTitle (const String& title);
  226536. void setPosition (int x, int y);
  226537. void setSize (int w, int h);
  226538. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  226539. const Rectangle<int> getBounds() const;
  226540. const Rectangle<int> getBounds (const bool global) const;
  226541. const Point<int> getScreenPosition() const;
  226542. const Point<int> localToGlobal (const Point<int>& relativePosition);
  226543. const Point<int> globalToLocal (const Point<int>& screenPosition);
  226544. void setAlpha (float newAlpha);
  226545. void setMinimised (bool shouldBeMinimised);
  226546. bool isMinimised() const;
  226547. void setFullScreen (bool shouldBeFullScreen);
  226548. bool isFullScreen() const;
  226549. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  226550. const BorderSize<int> getFrameSize() const;
  226551. bool setAlwaysOnTop (bool alwaysOnTop);
  226552. void toFront (bool makeActiveWindow);
  226553. void toBehind (ComponentPeer* other);
  226554. void setIcon (const Image& newIcon);
  226555. virtual void drawRect (CGRect r);
  226556. virtual bool canBecomeKeyWindow();
  226557. virtual bool windowShouldClose();
  226558. virtual void redirectMovedOrResized();
  226559. virtual CGRect constrainRect (CGRect r);
  226560. virtual void viewFocusGain();
  226561. virtual void viewFocusLoss();
  226562. bool isFocused() const;
  226563. void grabFocus();
  226564. void textInputRequired (const Point<int>& position);
  226565. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  226566. void updateHiddenTextContent (TextInputTarget* target);
  226567. void globalFocusChanged (Component*);
  226568. virtual BOOL shouldRotate (UIInterfaceOrientation interfaceOrientation);
  226569. virtual void displayRotated();
  226570. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  226571. void repaint (const Rectangle<int>& area);
  226572. void performAnyPendingRepaintsNow();
  226573. UIWindow* window;
  226574. JuceUIView* view;
  226575. JuceUIViewController* controller;
  226576. bool isSharedWindow, fullScreen, insideDrawRect;
  226577. static ModifierKeys currentModifiers;
  226578. static int64 getMouseTime (UIEvent* e)
  226579. {
  226580. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  226581. + (int64) ([e timestamp] * 1000.0);
  226582. }
  226583. static const Rectangle<int> rotatedScreenPosToReal (const Rectangle<int>& r)
  226584. {
  226585. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  226586. switch ([[UIApplication sharedApplication] statusBarOrientation])
  226587. {
  226588. case UIInterfaceOrientationPortrait:
  226589. return r;
  226590. case UIInterfaceOrientationPortraitUpsideDown:
  226591. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  226592. r.getWidth(), r.getHeight());
  226593. case UIInterfaceOrientationLandscapeLeft:
  226594. return Rectangle<int> (r.getY(), screen.getHeight() - r.getRight(),
  226595. r.getHeight(), r.getWidth());
  226596. case UIInterfaceOrientationLandscapeRight:
  226597. return Rectangle<int> (screen.getWidth() - r.getBottom(), r.getX(),
  226598. r.getHeight(), r.getWidth());
  226599. default: jassertfalse; // unknown orientation!
  226600. }
  226601. return r;
  226602. }
  226603. static const Rectangle<int> realScreenPosToRotated (const Rectangle<int>& r)
  226604. {
  226605. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  226606. switch ([[UIApplication sharedApplication] statusBarOrientation])
  226607. {
  226608. case UIInterfaceOrientationPortrait:
  226609. return r;
  226610. case UIInterfaceOrientationPortraitUpsideDown:
  226611. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  226612. r.getWidth(), r.getHeight());
  226613. case UIInterfaceOrientationLandscapeLeft:
  226614. return Rectangle<int> (screen.getHeight() - r.getBottom(), r.getX(),
  226615. r.getHeight(), r.getWidth());
  226616. case UIInterfaceOrientationLandscapeRight:
  226617. return Rectangle<int> (r.getY(), screen.getWidth() - r.getRight(),
  226618. r.getHeight(), r.getWidth());
  226619. default: jassertfalse; // unknown orientation!
  226620. }
  226621. return r;
  226622. }
  226623. Array <UITouch*> currentTouches;
  226624. private:
  226625. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIViewComponentPeer);
  226626. };
  226627. END_JUCE_NAMESPACE
  226628. @implementation JuceUIViewController
  226629. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
  226630. {
  226631. JuceUIView* juceView = (JuceUIView*) [self view];
  226632. jassert (juceView != 0 && juceView->owner != 0);
  226633. return juceView->owner->shouldRotate (interfaceOrientation);
  226634. }
  226635. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation
  226636. {
  226637. JuceUIView* juceView = (JuceUIView*) [self view];
  226638. jassert (juceView != 0 && juceView->owner != 0);
  226639. juceView->owner->displayRotated();
  226640. }
  226641. @end
  226642. @implementation JuceUIView
  226643. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  226644. withFrame: (CGRect) frame
  226645. {
  226646. [super initWithFrame: frame];
  226647. owner = owner_;
  226648. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  226649. [self addSubview: hiddenTextView];
  226650. hiddenTextView.delegate = self;
  226651. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  226652. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  226653. return self;
  226654. }
  226655. - (void) dealloc
  226656. {
  226657. [hiddenTextView removeFromSuperview];
  226658. [hiddenTextView release];
  226659. [super dealloc];
  226660. }
  226661. - (void) drawRect: (CGRect) r
  226662. {
  226663. if (owner != 0)
  226664. owner->drawRect (r);
  226665. }
  226666. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  226667. {
  226668. return false;
  226669. }
  226670. ModifierKeys UIViewComponentPeer::currentModifiers;
  226671. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  226672. {
  226673. return UIViewComponentPeer::currentModifiers;
  226674. }
  226675. void ModifierKeys::updateCurrentModifiers() throw()
  226676. {
  226677. currentModifiers = UIViewComponentPeer::currentModifiers;
  226678. }
  226679. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  226680. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  226681. {
  226682. if (owner != 0)
  226683. owner->handleTouches (event, true, false, false);
  226684. }
  226685. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  226686. {
  226687. if (owner != 0)
  226688. owner->handleTouches (event, false, false, false);
  226689. }
  226690. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  226691. {
  226692. if (owner != 0)
  226693. owner->handleTouches (event, false, true, false);
  226694. }
  226695. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  226696. {
  226697. if (owner != 0)
  226698. owner->handleTouches (event, false, true, true);
  226699. [self touchesEnded: touches withEvent: event];
  226700. }
  226701. - (BOOL) becomeFirstResponder
  226702. {
  226703. if (owner != 0)
  226704. owner->viewFocusGain();
  226705. return true;
  226706. }
  226707. - (BOOL) resignFirstResponder
  226708. {
  226709. if (owner != 0)
  226710. owner->viewFocusLoss();
  226711. return true;
  226712. }
  226713. - (BOOL) canBecomeFirstResponder
  226714. {
  226715. return owner != 0 && owner->canBecomeKeyWindow();
  226716. }
  226717. - (void) asyncRepaint: (id) rect
  226718. {
  226719. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  226720. [self setNeedsDisplayInRect: *r];
  226721. }
  226722. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  226723. {
  226724. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  226725. nsStringToJuce (text));
  226726. }
  226727. @end
  226728. @implementation JuceUIWindow
  226729. - (void) setOwner: (UIViewComponentPeer*) owner_
  226730. {
  226731. owner = owner_;
  226732. isZooming = false;
  226733. }
  226734. - (void) becomeKeyWindow
  226735. {
  226736. [super becomeKeyWindow];
  226737. if (owner != 0)
  226738. owner->grabFocus();
  226739. }
  226740. @end
  226741. BEGIN_JUCE_NAMESPACE
  226742. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  226743. const int windowStyleFlags,
  226744. UIView* viewToAttachTo)
  226745. : ComponentPeer (component, windowStyleFlags),
  226746. window (0),
  226747. view (0), controller (0),
  226748. isSharedWindow (viewToAttachTo != 0),
  226749. fullScreen (false),
  226750. insideDrawRect (false)
  226751. {
  226752. CGRect r = convertToCGRect (component->getLocalBounds());
  226753. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  226754. if (isSharedWindow)
  226755. {
  226756. window = [viewToAttachTo window];
  226757. [viewToAttachTo addSubview: view];
  226758. setVisible (component->isVisible());
  226759. }
  226760. else
  226761. {
  226762. controller = [[JuceUIViewController alloc] init];
  226763. controller.view = view;
  226764. r = convertToCGRect (rotatedScreenPosToReal (component->getBounds()));
  226765. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  226766. window = [[JuceUIWindow alloc] init];
  226767. window.frame = r;
  226768. window.opaque = component->isOpaque();
  226769. view.opaque = component->isOpaque();
  226770. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  226771. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  226772. [((JuceUIWindow*) window) setOwner: this];
  226773. if (component->isAlwaysOnTop())
  226774. window.windowLevel = UIWindowLevelAlert;
  226775. [window addSubview: view];
  226776. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  226777. view.hidden = ! component->isVisible();
  226778. window.hidden = ! component->isVisible();
  226779. view.multipleTouchEnabled = YES;
  226780. }
  226781. setTitle (component->getName());
  226782. Desktop::getInstance().addFocusChangeListener (this);
  226783. }
  226784. UIViewComponentPeer::~UIViewComponentPeer()
  226785. {
  226786. Desktop::getInstance().removeFocusChangeListener (this);
  226787. view->owner = 0;
  226788. [view removeFromSuperview];
  226789. [view release];
  226790. [controller release];
  226791. if (! isSharedWindow)
  226792. {
  226793. [((JuceUIWindow*) window) setOwner: 0];
  226794. [window release];
  226795. }
  226796. }
  226797. void* UIViewComponentPeer::getNativeHandle() const
  226798. {
  226799. return view;
  226800. }
  226801. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  226802. {
  226803. view.hidden = ! shouldBeVisible;
  226804. if (! isSharedWindow)
  226805. window.hidden = ! shouldBeVisible;
  226806. }
  226807. void UIViewComponentPeer::setTitle (const String& title)
  226808. {
  226809. // xxx is this possible?
  226810. }
  226811. void UIViewComponentPeer::setPosition (int x, int y)
  226812. {
  226813. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  226814. }
  226815. void UIViewComponentPeer::setSize (int w, int h)
  226816. {
  226817. setBounds (component->getX(), component->getY(), w, h, false);
  226818. }
  226819. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  226820. {
  226821. fullScreen = isNowFullScreen;
  226822. w = jmax (0, w);
  226823. h = jmax (0, h);
  226824. if (isSharedWindow)
  226825. {
  226826. CGRect r = CGRectMake ((float) x, (float) y, (float) w, (float) h);
  226827. if ([view frame].size.width != r.size.width
  226828. || [view frame].size.height != r.size.height)
  226829. [view setNeedsDisplay];
  226830. view.frame = r;
  226831. }
  226832. else
  226833. {
  226834. const Rectangle<int> bounds (rotatedScreenPosToReal (Rectangle<int> (x, y, w, h)));
  226835. window.frame = convertToCGRect (bounds);
  226836. view.frame = CGRectMake (0, 0, (float) bounds.getWidth(), (float) bounds.getHeight());
  226837. handleMovedOrResized();
  226838. }
  226839. }
  226840. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  226841. {
  226842. CGRect r = [view frame];
  226843. if (global && [view window] != 0)
  226844. {
  226845. r = [view convertRect: r toView: nil];
  226846. CGRect wr = [[view window] frame];
  226847. const Rectangle<int> windowBounds (realScreenPosToRotated (convertToRectInt (wr)));
  226848. r.origin.x = windowBounds.getX();
  226849. r.origin.y = windowBounds.getY();
  226850. }
  226851. return convertToRectInt (r);
  226852. }
  226853. const Rectangle<int> UIViewComponentPeer::getBounds() const
  226854. {
  226855. return getBounds (! isSharedWindow);
  226856. }
  226857. const Point<int> UIViewComponentPeer::getScreenPosition() const
  226858. {
  226859. return getBounds (true).getPosition();
  226860. }
  226861. const Point<int> UIViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  226862. {
  226863. return relativePosition + getScreenPosition();
  226864. }
  226865. const Point<int> UIViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  226866. {
  226867. return screenPosition - getScreenPosition();
  226868. }
  226869. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  226870. {
  226871. if (constrainer != 0)
  226872. {
  226873. CGRect current = [window frame];
  226874. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  226875. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  226876. Rectangle<int> pos (convertToRectInt (r));
  226877. Rectangle<int> original (convertToRectInt (current));
  226878. constrainer->checkBounds (pos, original,
  226879. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  226880. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  226881. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  226882. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  226883. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  226884. r.origin.x = pos.getX();
  226885. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  226886. r.size.width = pos.getWidth();
  226887. r.size.height = pos.getHeight();
  226888. }
  226889. return r;
  226890. }
  226891. void UIViewComponentPeer::setAlpha (float newAlpha)
  226892. {
  226893. [[view window] setAlpha: (CGFloat) newAlpha];
  226894. }
  226895. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  226896. {
  226897. }
  226898. bool UIViewComponentPeer::isMinimised() const
  226899. {
  226900. return false;
  226901. }
  226902. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  226903. {
  226904. if (! isSharedWindow)
  226905. {
  226906. Rectangle<int> r (shouldBeFullScreen ? Desktop::getInstance().getMainMonitorArea()
  226907. : lastNonFullscreenBounds);
  226908. if ((! shouldBeFullScreen) && r.isEmpty())
  226909. r = getBounds();
  226910. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  226911. if (! r.isEmpty())
  226912. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  226913. component->repaint();
  226914. }
  226915. }
  226916. bool UIViewComponentPeer::isFullScreen() const
  226917. {
  226918. return fullScreen;
  226919. }
  226920. namespace
  226921. {
  226922. Desktop::DisplayOrientation convertToJuceOrientation (UIInterfaceOrientation interfaceOrientation)
  226923. {
  226924. switch (interfaceOrientation)
  226925. {
  226926. case UIInterfaceOrientationPortrait: return Desktop::upright;
  226927. case UIInterfaceOrientationPortraitUpsideDown: return Desktop::upsideDown;
  226928. case UIInterfaceOrientationLandscapeLeft: return Desktop::rotatedClockwise;
  226929. case UIInterfaceOrientationLandscapeRight: return Desktop::rotatedAntiClockwise;
  226930. default: jassertfalse; // unknown orientation!
  226931. }
  226932. return Desktop::upright;
  226933. }
  226934. }
  226935. BOOL UIViewComponentPeer::shouldRotate (UIInterfaceOrientation interfaceOrientation)
  226936. {
  226937. return Desktop::getInstance().isOrientationEnabled (convertToJuceOrientation (interfaceOrientation));
  226938. }
  226939. void UIViewComponentPeer::displayRotated()
  226940. {
  226941. const Rectangle<int> oldArea (component->getBounds());
  226942. const Rectangle<int> oldDesktop (Desktop::getInstance().getMainMonitorArea());
  226943. Desktop::getInstance().refreshMonitorSizes();
  226944. if (fullScreen)
  226945. {
  226946. fullScreen = false;
  226947. setFullScreen (true);
  226948. }
  226949. else
  226950. {
  226951. const float l = oldArea.getX() / (float) oldDesktop.getWidth();
  226952. const float r = oldArea.getRight() / (float) oldDesktop.getWidth();
  226953. const float t = oldArea.getY() / (float) oldDesktop.getHeight();
  226954. const float b = oldArea.getBottom() / (float) oldDesktop.getHeight();
  226955. const Rectangle<int> newDesktop (Desktop::getInstance().getMainMonitorArea());
  226956. setBounds ((int) (l * newDesktop.getWidth()),
  226957. (int) (t * newDesktop.getHeight()),
  226958. (int) ((r - l) * newDesktop.getWidth()),
  226959. (int) ((b - t) * newDesktop.getHeight()),
  226960. false);
  226961. }
  226962. }
  226963. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  226964. {
  226965. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  226966. && isPositiveAndBelow (position.getY(), component->getHeight())))
  226967. return false;
  226968. UIView* v = [view hitTest: CGPointMake ((float) position.getX(), (float) position.getY())
  226969. withEvent: nil];
  226970. if (trueIfInAChildWindow)
  226971. return v != nil;
  226972. return v == view;
  226973. }
  226974. const BorderSize<int> UIViewComponentPeer::getFrameSize() const
  226975. {
  226976. return BorderSize<int>();
  226977. }
  226978. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  226979. {
  226980. if (! isSharedWindow)
  226981. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  226982. return true;
  226983. }
  226984. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  226985. {
  226986. if (isSharedWindow)
  226987. [[view superview] bringSubviewToFront: view];
  226988. if (window != 0 && component->isVisible())
  226989. [window makeKeyAndVisible];
  226990. }
  226991. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  226992. {
  226993. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  226994. jassert (otherPeer != 0); // wrong type of window?
  226995. if (otherPeer != 0)
  226996. {
  226997. if (isSharedWindow)
  226998. {
  226999. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  227000. }
  227001. else
  227002. {
  227003. jassertfalse; // don't know how to do this
  227004. }
  227005. }
  227006. }
  227007. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  227008. {
  227009. // to do..
  227010. }
  227011. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  227012. {
  227013. NSArray* touches = [[event touchesForView: view] allObjects];
  227014. for (unsigned int i = 0; i < [touches count]; ++i)
  227015. {
  227016. UITouch* touch = [touches objectAtIndex: i];
  227017. CGPoint p = [touch locationInView: view];
  227018. const Point<int> pos ((int) p.x, (int) p.y);
  227019. juce_lastMousePos = pos + getScreenPosition();
  227020. const int64 time = getMouseTime (event);
  227021. int touchIndex = currentTouches.indexOf (touch);
  227022. if (touchIndex < 0)
  227023. {
  227024. touchIndex = currentTouches.size();
  227025. currentTouches.add (touch);
  227026. }
  227027. if (isDown)
  227028. {
  227029. currentModifiers = currentModifiers.withoutMouseButtons();
  227030. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227031. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  227032. }
  227033. else if (isUp)
  227034. {
  227035. currentModifiers = currentModifiers.withoutMouseButtons();
  227036. currentTouches.remove (touchIndex);
  227037. }
  227038. if (isCancel)
  227039. currentTouches.clear();
  227040. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227041. }
  227042. }
  227043. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  227044. void UIViewComponentPeer::viewFocusGain()
  227045. {
  227046. if (currentlyFocusedPeer != this)
  227047. {
  227048. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  227049. currentlyFocusedPeer->handleFocusLoss();
  227050. currentlyFocusedPeer = this;
  227051. handleFocusGain();
  227052. }
  227053. }
  227054. void UIViewComponentPeer::viewFocusLoss()
  227055. {
  227056. if (currentlyFocusedPeer == this)
  227057. {
  227058. currentlyFocusedPeer = 0;
  227059. handleFocusLoss();
  227060. }
  227061. }
  227062. void juce_HandleProcessFocusChange()
  227063. {
  227064. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  227065. {
  227066. if (Process::isForegroundProcess())
  227067. {
  227068. currentlyFocusedPeer->handleFocusGain();
  227069. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  227070. }
  227071. else
  227072. {
  227073. currentlyFocusedPeer->handleFocusLoss();
  227074. // turn kiosk mode off if we lose focus..
  227075. Desktop::getInstance().setKioskModeComponent (0);
  227076. }
  227077. }
  227078. }
  227079. bool UIViewComponentPeer::isFocused() const
  227080. {
  227081. return isSharedWindow ? this == currentlyFocusedPeer
  227082. : (window != 0 && [window isKeyWindow]);
  227083. }
  227084. void UIViewComponentPeer::grabFocus()
  227085. {
  227086. if (window != 0)
  227087. {
  227088. [window makeKeyWindow];
  227089. viewFocusGain();
  227090. }
  227091. }
  227092. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  227093. {
  227094. }
  227095. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  227096. {
  227097. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  227098. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  227099. }
  227100. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  227101. {
  227102. TextInputTarget* const target = findCurrentTextInputTarget();
  227103. if (target != 0)
  227104. {
  227105. const Range<int> currentSelection (target->getHighlightedRegion());
  227106. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  227107. if (currentSelection.isEmpty())
  227108. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  227109. target->insertTextAtCaret (text);
  227110. updateHiddenTextContent (target);
  227111. }
  227112. return NO;
  227113. }
  227114. void UIViewComponentPeer::globalFocusChanged (Component*)
  227115. {
  227116. TextInputTarget* const target = findCurrentTextInputTarget();
  227117. if (target != 0)
  227118. {
  227119. Component* comp = dynamic_cast<Component*> (target);
  227120. Point<int> pos (component->getLocalPoint (comp, Point<int>()));
  227121. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  227122. updateHiddenTextContent (target);
  227123. [view->hiddenTextView becomeFirstResponder];
  227124. }
  227125. else
  227126. {
  227127. [view->hiddenTextView resignFirstResponder];
  227128. }
  227129. }
  227130. void UIViewComponentPeer::drawRect (CGRect r)
  227131. {
  227132. if (r.size.width < 1.0f || r.size.height < 1.0f)
  227133. return;
  227134. CGContextRef cg = UIGraphicsGetCurrentContext();
  227135. if (! component->isOpaque())
  227136. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  227137. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  227138. CoreGraphicsContext g (cg, view.bounds.size.height);
  227139. insideDrawRect = true;
  227140. handlePaint (g);
  227141. insideDrawRect = false;
  227142. }
  227143. bool UIViewComponentPeer::canBecomeKeyWindow()
  227144. {
  227145. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  227146. }
  227147. bool UIViewComponentPeer::windowShouldClose()
  227148. {
  227149. if (! isValidPeer (this))
  227150. return YES;
  227151. handleUserClosingWindow();
  227152. return NO;
  227153. }
  227154. void UIViewComponentPeer::redirectMovedOrResized()
  227155. {
  227156. handleMovedOrResized();
  227157. }
  227158. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  227159. {
  227160. }
  227161. class AsyncRepaintMessage : public CallbackMessage
  227162. {
  227163. public:
  227164. UIViewComponentPeer* const peer;
  227165. const Rectangle<int> rect;
  227166. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  227167. : peer (peer_), rect (rect_)
  227168. {
  227169. }
  227170. void messageCallback()
  227171. {
  227172. if (ComponentPeer::isValidPeer (peer))
  227173. peer->repaint (rect);
  227174. }
  227175. };
  227176. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  227177. {
  227178. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  227179. {
  227180. (new AsyncRepaintMessage (this, area))->post();
  227181. }
  227182. else
  227183. {
  227184. [view setNeedsDisplayInRect: convertToCGRect (area)];
  227185. }
  227186. }
  227187. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  227188. {
  227189. }
  227190. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  227191. {
  227192. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  227193. }
  227194. const Image juce_createIconForFile (const File& file)
  227195. {
  227196. return Image::null;
  227197. }
  227198. void Desktop::createMouseInputSources()
  227199. {
  227200. for (int i = 0; i < 10; ++i)
  227201. mouseSources.add (new MouseInputSource (i, false));
  227202. }
  227203. bool Desktop::canUseSemiTransparentWindows() throw()
  227204. {
  227205. return true;
  227206. }
  227207. const Point<int> MouseInputSource::getCurrentMousePosition()
  227208. {
  227209. return juce_lastMousePos;
  227210. }
  227211. void Desktop::setMousePosition (const Point<int>&)
  227212. {
  227213. }
  227214. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  227215. {
  227216. return convertToJuceOrientation ([[UIApplication sharedApplication] statusBarOrientation]);
  227217. }
  227218. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  227219. {
  227220. const ScopedAutoReleasePool pool;
  227221. monitorCoords.clear();
  227222. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  227223. : [[UIScreen mainScreen] bounds];
  227224. monitorCoords.add (UIViewComponentPeer::realScreenPosToRotated (convertToRectInt (r)));
  227225. }
  227226. const int KeyPress::spaceKey = ' ';
  227227. const int KeyPress::returnKey = 0x0d;
  227228. const int KeyPress::escapeKey = 0x1b;
  227229. const int KeyPress::backspaceKey = 0x7f;
  227230. const int KeyPress::leftKey = 0x1000;
  227231. const int KeyPress::rightKey = 0x1001;
  227232. const int KeyPress::upKey = 0x1002;
  227233. const int KeyPress::downKey = 0x1003;
  227234. const int KeyPress::pageUpKey = 0x1004;
  227235. const int KeyPress::pageDownKey = 0x1005;
  227236. const int KeyPress::endKey = 0x1006;
  227237. const int KeyPress::homeKey = 0x1007;
  227238. const int KeyPress::deleteKey = 0x1008;
  227239. const int KeyPress::insertKey = -1;
  227240. const int KeyPress::tabKey = 9;
  227241. const int KeyPress::F1Key = 0x2001;
  227242. const int KeyPress::F2Key = 0x2002;
  227243. const int KeyPress::F3Key = 0x2003;
  227244. const int KeyPress::F4Key = 0x2004;
  227245. const int KeyPress::F5Key = 0x2005;
  227246. const int KeyPress::F6Key = 0x2006;
  227247. const int KeyPress::F7Key = 0x2007;
  227248. const int KeyPress::F8Key = 0x2008;
  227249. const int KeyPress::F9Key = 0x2009;
  227250. const int KeyPress::F10Key = 0x200a;
  227251. const int KeyPress::F11Key = 0x200b;
  227252. const int KeyPress::F12Key = 0x200c;
  227253. const int KeyPress::F13Key = 0x200d;
  227254. const int KeyPress::F14Key = 0x200e;
  227255. const int KeyPress::F15Key = 0x200f;
  227256. const int KeyPress::F16Key = 0x2010;
  227257. const int KeyPress::numberPad0 = 0x30020;
  227258. const int KeyPress::numberPad1 = 0x30021;
  227259. const int KeyPress::numberPad2 = 0x30022;
  227260. const int KeyPress::numberPad3 = 0x30023;
  227261. const int KeyPress::numberPad4 = 0x30024;
  227262. const int KeyPress::numberPad5 = 0x30025;
  227263. const int KeyPress::numberPad6 = 0x30026;
  227264. const int KeyPress::numberPad7 = 0x30027;
  227265. const int KeyPress::numberPad8 = 0x30028;
  227266. const int KeyPress::numberPad9 = 0x30029;
  227267. const int KeyPress::numberPadAdd = 0x3002a;
  227268. const int KeyPress::numberPadSubtract = 0x3002b;
  227269. const int KeyPress::numberPadMultiply = 0x3002c;
  227270. const int KeyPress::numberPadDivide = 0x3002d;
  227271. const int KeyPress::numberPadSeparator = 0x3002e;
  227272. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  227273. const int KeyPress::numberPadEquals = 0x30030;
  227274. const int KeyPress::numberPadDelete = 0x30031;
  227275. const int KeyPress::playKey = 0x30000;
  227276. const int KeyPress::stopKey = 0x30001;
  227277. const int KeyPress::fastForwardKey = 0x30002;
  227278. const int KeyPress::rewindKey = 0x30003;
  227279. #endif
  227280. /*** End of inlined file: juce_ios_UIViewComponentPeer.mm ***/
  227281. /*** Start of inlined file: juce_ios_MessageManager.mm ***/
  227282. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227283. // compiled on its own).
  227284. #if JUCE_INCLUDED_FILE
  227285. struct CallbackMessagePayload
  227286. {
  227287. MessageCallbackFunction* function;
  227288. void* parameter;
  227289. void* volatile result;
  227290. bool volatile hasBeenExecuted;
  227291. };
  227292. END_JUCE_NAMESPACE
  227293. @interface JuceCustomMessageHandler : NSObject
  227294. {
  227295. }
  227296. - (void) performCallback: (id) info;
  227297. @end
  227298. @implementation JuceCustomMessageHandler
  227299. - (void) performCallback: (id) info
  227300. {
  227301. if ([info isKindOfClass: [NSData class]])
  227302. {
  227303. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  227304. if (pl != 0)
  227305. {
  227306. pl->result = (*pl->function) (pl->parameter);
  227307. pl->hasBeenExecuted = true;
  227308. }
  227309. }
  227310. else
  227311. {
  227312. jassertfalse; // should never get here!
  227313. }
  227314. }
  227315. @end
  227316. BEGIN_JUCE_NAMESPACE
  227317. void MessageManager::runDispatchLoop()
  227318. {
  227319. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227320. runDispatchLoopUntil (-1);
  227321. }
  227322. void MessageManager::stopDispatchLoop()
  227323. {
  227324. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  227325. exit (0); // iPhone apps get no mercy..
  227326. }
  227327. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  227328. {
  227329. const ScopedAutoReleasePool pool;
  227330. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227331. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  227332. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  227333. while (! quitMessagePosted)
  227334. {
  227335. const ScopedAutoReleasePool pool;
  227336. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  227337. beforeDate: endDate];
  227338. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  227339. break;
  227340. }
  227341. return ! quitMessagePosted;
  227342. }
  227343. struct MessageDispatchSystem
  227344. {
  227345. MessageDispatchSystem()
  227346. : juceCustomMessageHandler (0)
  227347. {
  227348. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  227349. }
  227350. ~MessageDispatchSystem()
  227351. {
  227352. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  227353. [juceCustomMessageHandler release];
  227354. }
  227355. JuceCustomMessageHandler* juceCustomMessageHandler;
  227356. MessageQueue messageQueue;
  227357. };
  227358. static MessageDispatchSystem* dispatcher = 0;
  227359. void MessageManager::doPlatformSpecificInitialisation()
  227360. {
  227361. if (dispatcher == 0)
  227362. dispatcher = new MessageDispatchSystem();
  227363. }
  227364. void MessageManager::doPlatformSpecificShutdown()
  227365. {
  227366. deleteAndZero (dispatcher);
  227367. }
  227368. bool juce_postMessageToSystemQueue (Message* message)
  227369. {
  227370. if (dispatcher != 0)
  227371. dispatcher->messageQueue.post (message);
  227372. return true;
  227373. }
  227374. void MessageManager::broadcastMessage (const String& value)
  227375. {
  227376. }
  227377. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  227378. {
  227379. if (isThisTheMessageThread())
  227380. {
  227381. return (*callback) (data);
  227382. }
  227383. else
  227384. {
  227385. jassert (dispatcher != 0); // trying to call this when the juce system isn't initialised..
  227386. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  227387. // deadlock because the message manager is blocked from running, so can never
  227388. // call your function..
  227389. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  227390. const ScopedAutoReleasePool pool;
  227391. CallbackMessagePayload cmp;
  227392. cmp.function = callback;
  227393. cmp.parameter = data;
  227394. cmp.result = 0;
  227395. cmp.hasBeenExecuted = false;
  227396. [dispatcher->juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  227397. withObject: [NSData dataWithBytesNoCopy: &cmp
  227398. length: sizeof (cmp)
  227399. freeWhenDone: NO]
  227400. waitUntilDone: YES];
  227401. return cmp.result;
  227402. }
  227403. }
  227404. #endif
  227405. /*** End of inlined file: juce_ios_MessageManager.mm ***/
  227406. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  227407. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227408. // compiled on its own).
  227409. #if JUCE_INCLUDED_FILE
  227410. #if JUCE_MAC
  227411. END_JUCE_NAMESPACE
  227412. using namespace JUCE_NAMESPACE;
  227413. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  227414. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  227415. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  227416. #else
  227417. @interface JuceFileChooserDelegate : NSObject
  227418. #endif
  227419. {
  227420. StringArray* filters;
  227421. }
  227422. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  227423. - (void) dealloc;
  227424. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  227425. @end
  227426. @implementation JuceFileChooserDelegate
  227427. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  227428. {
  227429. [super init];
  227430. filters = filters_;
  227431. return self;
  227432. }
  227433. - (void) dealloc
  227434. {
  227435. delete filters;
  227436. [super dealloc];
  227437. }
  227438. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  227439. {
  227440. (void) sender;
  227441. const File f (nsStringToJuce (filename));
  227442. for (int i = filters->size(); --i >= 0;)
  227443. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  227444. return true;
  227445. return f.isDirectory();
  227446. }
  227447. @end
  227448. BEGIN_JUCE_NAMESPACE
  227449. void FileChooser::showPlatformDialog (Array<File>& results,
  227450. const String& title,
  227451. const File& currentFileOrDirectory,
  227452. const String& filter,
  227453. bool selectsDirectory,
  227454. bool selectsFiles,
  227455. bool isSaveDialogue,
  227456. bool /*warnAboutOverwritingExistingFiles*/,
  227457. bool selectMultipleFiles,
  227458. FilePreviewComponent* /*extraInfoComponent*/)
  227459. {
  227460. const ScopedAutoReleasePool pool;
  227461. StringArray* filters = new StringArray();
  227462. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  227463. filters->trim();
  227464. filters->removeEmptyStrings();
  227465. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  227466. [delegate autorelease];
  227467. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  227468. : [NSOpenPanel openPanel];
  227469. [panel setTitle: juceStringToNS (title)];
  227470. if (! isSaveDialogue)
  227471. {
  227472. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  227473. [openPanel setCanChooseDirectories: selectsDirectory];
  227474. [openPanel setCanChooseFiles: selectsFiles];
  227475. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  227476. }
  227477. [panel setDelegate: delegate];
  227478. if (isSaveDialogue || selectsDirectory)
  227479. [panel setCanCreateDirectories: YES];
  227480. String directory, filename;
  227481. if (currentFileOrDirectory.isDirectory())
  227482. {
  227483. directory = currentFileOrDirectory.getFullPathName();
  227484. }
  227485. else
  227486. {
  227487. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  227488. filename = currentFileOrDirectory.getFileName();
  227489. }
  227490. if ([panel runModalForDirectory: juceStringToNS (directory)
  227491. file: juceStringToNS (filename)]
  227492. == NSOKButton)
  227493. {
  227494. if (isSaveDialogue)
  227495. {
  227496. results.add (File (nsStringToJuce ([panel filename])));
  227497. }
  227498. else
  227499. {
  227500. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  227501. NSArray* urls = [openPanel filenames];
  227502. for (unsigned int i = 0; i < [urls count]; ++i)
  227503. {
  227504. NSString* f = [urls objectAtIndex: i];
  227505. results.add (File (nsStringToJuce (f)));
  227506. }
  227507. }
  227508. }
  227509. [panel setDelegate: nil];
  227510. }
  227511. #else
  227512. void FileChooser::showPlatformDialog (Array<File>& results,
  227513. const String& title,
  227514. const File& currentFileOrDirectory,
  227515. const String& filter,
  227516. bool selectsDirectory,
  227517. bool selectsFiles,
  227518. bool isSaveDialogue,
  227519. bool warnAboutOverwritingExistingFiles,
  227520. bool selectMultipleFiles,
  227521. FilePreviewComponent* extraInfoComponent)
  227522. {
  227523. const ScopedAutoReleasePool pool;
  227524. jassertfalse; //xxx to do
  227525. }
  227526. #endif
  227527. #endif
  227528. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  227529. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  227530. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227531. // compiled on its own).
  227532. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  227533. #if JUCE_MAC
  227534. END_JUCE_NAMESPACE
  227535. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  227536. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  227537. {
  227538. CriticalSection* contextLock;
  227539. bool needsUpdate;
  227540. }
  227541. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  227542. - (bool) makeActive;
  227543. - (void) makeInactive;
  227544. - (void) reshape;
  227545. - (void) rightMouseDown: (NSEvent*) ev;
  227546. - (void) rightMouseUp: (NSEvent*) ev;
  227547. @end
  227548. @implementation ThreadSafeNSOpenGLView
  227549. - (id) initWithFrame: (NSRect) frameRect
  227550. pixelFormat: (NSOpenGLPixelFormat*) format
  227551. {
  227552. contextLock = new CriticalSection();
  227553. self = [super initWithFrame: frameRect pixelFormat: format];
  227554. if (self != nil)
  227555. [[NSNotificationCenter defaultCenter] addObserver: self
  227556. selector: @selector (_surfaceNeedsUpdate:)
  227557. name: NSViewGlobalFrameDidChangeNotification
  227558. object: self];
  227559. return self;
  227560. }
  227561. - (void) dealloc
  227562. {
  227563. [[NSNotificationCenter defaultCenter] removeObserver: self];
  227564. delete contextLock;
  227565. [super dealloc];
  227566. }
  227567. - (bool) makeActive
  227568. {
  227569. const ScopedLock sl (*contextLock);
  227570. if ([self openGLContext] == 0)
  227571. return false;
  227572. [[self openGLContext] makeCurrentContext];
  227573. if (needsUpdate)
  227574. {
  227575. [super update];
  227576. needsUpdate = false;
  227577. }
  227578. return true;
  227579. }
  227580. - (void) makeInactive
  227581. {
  227582. const ScopedLock sl (*contextLock);
  227583. [NSOpenGLContext clearCurrentContext];
  227584. }
  227585. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  227586. {
  227587. (void) notification;
  227588. const ScopedLock sl (*contextLock);
  227589. needsUpdate = true;
  227590. }
  227591. - (void) update
  227592. {
  227593. const ScopedLock sl (*contextLock);
  227594. needsUpdate = true;
  227595. }
  227596. - (void) reshape
  227597. {
  227598. const ScopedLock sl (*contextLock);
  227599. needsUpdate = true;
  227600. }
  227601. - (void) rightMouseDown: (NSEvent*) ev
  227602. {
  227603. [[self superview] rightMouseDown: ev];
  227604. }
  227605. - (void) rightMouseUp: (NSEvent*) ev
  227606. {
  227607. [[self superview] rightMouseUp: ev];
  227608. }
  227609. @end
  227610. BEGIN_JUCE_NAMESPACE
  227611. class WindowedGLContext : public OpenGLContext
  227612. {
  227613. public:
  227614. WindowedGLContext (Component& component,
  227615. const OpenGLPixelFormat& pixelFormat_,
  227616. NSOpenGLContext* sharedContext)
  227617. : renderContext (0),
  227618. pixelFormat (pixelFormat_)
  227619. {
  227620. NSOpenGLPixelFormatAttribute attribs [64];
  227621. int n = 0;
  227622. attribs[n++] = NSOpenGLPFADoubleBuffer;
  227623. attribs[n++] = NSOpenGLPFAAccelerated;
  227624. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  227625. attribs[n++] = NSOpenGLPFAColorSize;
  227626. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  227627. pixelFormat.greenBits,
  227628. pixelFormat.blueBits);
  227629. attribs[n++] = NSOpenGLPFAAlphaSize;
  227630. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  227631. attribs[n++] = NSOpenGLPFADepthSize;
  227632. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  227633. attribs[n++] = NSOpenGLPFAStencilSize;
  227634. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  227635. attribs[n++] = NSOpenGLPFAAccumSize;
  227636. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  227637. pixelFormat.accumulationBufferGreenBits,
  227638. pixelFormat.accumulationBufferBlueBits,
  227639. pixelFormat.accumulationBufferAlphaBits);
  227640. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  227641. attribs[n++] = NSOpenGLPFASampleBuffers;
  227642. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  227643. attribs[n++] = NSOpenGLPFAClosestPolicy;
  227644. attribs[n++] = NSOpenGLPFANoRecovery;
  227645. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  227646. NSOpenGLPixelFormat* format
  227647. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  227648. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  227649. pixelFormat: format];
  227650. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  227651. shareContext: sharedContext] autorelease];
  227652. const GLint swapInterval = 1;
  227653. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  227654. [view setOpenGLContext: renderContext];
  227655. [format release];
  227656. viewHolder = new NSViewComponentInternal (view, component);
  227657. }
  227658. ~WindowedGLContext()
  227659. {
  227660. deleteContext();
  227661. viewHolder = 0;
  227662. }
  227663. void deleteContext()
  227664. {
  227665. makeInactive();
  227666. [renderContext clearDrawable];
  227667. [renderContext setView: nil];
  227668. [view setOpenGLContext: nil];
  227669. renderContext = nil;
  227670. }
  227671. bool makeActive() const throw()
  227672. {
  227673. jassert (renderContext != 0);
  227674. if ([renderContext view] != view)
  227675. [renderContext setView: view];
  227676. [view makeActive];
  227677. return isActive();
  227678. }
  227679. bool makeInactive() const throw()
  227680. {
  227681. [view makeInactive];
  227682. return true;
  227683. }
  227684. bool isActive() const throw()
  227685. {
  227686. return [NSOpenGLContext currentContext] == renderContext;
  227687. }
  227688. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  227689. void* getRawContext() const throw() { return renderContext; }
  227690. void updateWindowPosition (int /*x*/, int /*y*/, int /*w*/, int /*h*/, int /*outerWindowHeight*/)
  227691. {
  227692. }
  227693. void swapBuffers()
  227694. {
  227695. [renderContext flushBuffer];
  227696. }
  227697. bool setSwapInterval (const int numFramesPerSwap)
  227698. {
  227699. [renderContext setValues: (const GLint*) &numFramesPerSwap
  227700. forParameter: NSOpenGLCPSwapInterval];
  227701. return true;
  227702. }
  227703. int getSwapInterval() const
  227704. {
  227705. GLint numFrames = 0;
  227706. [renderContext getValues: &numFrames
  227707. forParameter: NSOpenGLCPSwapInterval];
  227708. return numFrames;
  227709. }
  227710. void repaint()
  227711. {
  227712. // we need to invalidate the juce view that holds this gl view, to make it
  227713. // cause a repaint callback
  227714. NSView* v = (NSView*) viewHolder->view;
  227715. NSRect r = [v frame];
  227716. // bit of a bodge here.. if we only invalidate the area of the gl component,
  227717. // it's completely covered by the NSOpenGLView, so the OS throws away the
  227718. // repaint message, thus never causing our paint() callback, and never repainting
  227719. // the comp. So invalidating just a little bit around the edge helps..
  227720. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  227721. }
  227722. void* getNativeWindowHandle() const { return viewHolder->view; }
  227723. NSOpenGLContext* renderContext;
  227724. ThreadSafeNSOpenGLView* view;
  227725. private:
  227726. OpenGLPixelFormat pixelFormat;
  227727. ScopedPointer <NSViewComponentInternal> viewHolder;
  227728. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  227729. };
  227730. OpenGLContext* OpenGLComponent::createContext()
  227731. {
  227732. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (*this, preferredPixelFormat,
  227733. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  227734. return (c->renderContext != 0) ? c.release() : 0;
  227735. }
  227736. void* OpenGLComponent::getNativeWindowHandle() const
  227737. {
  227738. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  227739. : 0;
  227740. }
  227741. void juce_glViewport (const int w, const int h)
  227742. {
  227743. glViewport (0, 0, w, h);
  227744. }
  227745. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  227746. OwnedArray <OpenGLPixelFormat>& /*results*/)
  227747. {
  227748. /* GLint attribs [64];
  227749. int n = 0;
  227750. attribs[n++] = AGL_RGBA;
  227751. attribs[n++] = AGL_DOUBLEBUFFER;
  227752. attribs[n++] = AGL_ACCELERATED;
  227753. attribs[n++] = AGL_NO_RECOVERY;
  227754. attribs[n++] = AGL_NONE;
  227755. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  227756. while (p != 0)
  227757. {
  227758. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  227759. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  227760. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  227761. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  227762. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  227763. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  227764. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  227765. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  227766. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  227767. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  227768. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  227769. results.add (pf);
  227770. p = aglNextPixelFormat (p);
  227771. }*/
  227772. //jassertfalse // can't see how you do this in cocoa!
  227773. }
  227774. #else
  227775. END_JUCE_NAMESPACE
  227776. @interface JuceGLView : UIView
  227777. {
  227778. }
  227779. + (Class) layerClass;
  227780. @end
  227781. @implementation JuceGLView
  227782. + (Class) layerClass
  227783. {
  227784. return [CAEAGLLayer class];
  227785. }
  227786. @end
  227787. BEGIN_JUCE_NAMESPACE
  227788. class GLESContext : public OpenGLContext
  227789. {
  227790. public:
  227791. GLESContext (UIViewComponentPeer* peer,
  227792. Component* const component_,
  227793. const OpenGLPixelFormat& pixelFormat_,
  227794. const GLESContext* const sharedContext,
  227795. NSUInteger apiType)
  227796. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  227797. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  227798. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  227799. {
  227800. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  227801. view.opaque = YES;
  227802. view.hidden = NO;
  227803. view.backgroundColor = [UIColor blackColor];
  227804. view.userInteractionEnabled = NO;
  227805. glLayer = (CAEAGLLayer*) [view layer];
  227806. [peer->view addSubview: view];
  227807. if (sharedContext != 0)
  227808. context = [[EAGLContext alloc] initWithAPI: apiType
  227809. sharegroup: [sharedContext->context sharegroup]];
  227810. else
  227811. context = [[EAGLContext alloc] initWithAPI: apiType];
  227812. createGLBuffers();
  227813. }
  227814. ~GLESContext()
  227815. {
  227816. deleteContext();
  227817. [view removeFromSuperview];
  227818. [view release];
  227819. freeGLBuffers();
  227820. }
  227821. void deleteContext()
  227822. {
  227823. makeInactive();
  227824. [context release];
  227825. context = nil;
  227826. }
  227827. bool makeActive() const throw()
  227828. {
  227829. jassert (context != 0);
  227830. [EAGLContext setCurrentContext: context];
  227831. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  227832. return true;
  227833. }
  227834. void swapBuffers()
  227835. {
  227836. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227837. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  227838. }
  227839. bool makeInactive() const throw()
  227840. {
  227841. return [EAGLContext setCurrentContext: nil];
  227842. }
  227843. bool isActive() const throw()
  227844. {
  227845. return [EAGLContext currentContext] == context;
  227846. }
  227847. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  227848. void* getRawContext() const throw() { return glLayer; }
  227849. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  227850. {
  227851. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  227852. if (lastWidth != w || lastHeight != h)
  227853. {
  227854. lastWidth = w;
  227855. lastHeight = h;
  227856. freeGLBuffers();
  227857. createGLBuffers();
  227858. }
  227859. }
  227860. bool setSwapInterval (const int numFramesPerSwap)
  227861. {
  227862. numFrames = numFramesPerSwap;
  227863. return true;
  227864. }
  227865. int getSwapInterval() const
  227866. {
  227867. return numFrames;
  227868. }
  227869. void repaint()
  227870. {
  227871. }
  227872. void createGLBuffers()
  227873. {
  227874. makeActive();
  227875. glGenFramebuffersOES (1, &frameBufferHandle);
  227876. glGenRenderbuffersOES (1, &colorBufferHandle);
  227877. glGenRenderbuffersOES (1, &depthBufferHandle);
  227878. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227879. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  227880. GLint width, height;
  227881. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  227882. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  227883. if (useDepthBuffer)
  227884. {
  227885. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  227886. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  227887. }
  227888. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227889. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  227890. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  227891. if (useDepthBuffer)
  227892. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  227893. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  227894. }
  227895. void freeGLBuffers()
  227896. {
  227897. if (frameBufferHandle != 0)
  227898. {
  227899. glDeleteFramebuffersOES (1, &frameBufferHandle);
  227900. frameBufferHandle = 0;
  227901. }
  227902. if (colorBufferHandle != 0)
  227903. {
  227904. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  227905. colorBufferHandle = 0;
  227906. }
  227907. if (depthBufferHandle != 0)
  227908. {
  227909. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  227910. depthBufferHandle = 0;
  227911. }
  227912. }
  227913. private:
  227914. WeakReference<Component> component;
  227915. OpenGLPixelFormat pixelFormat;
  227916. JuceGLView* view;
  227917. CAEAGLLayer* glLayer;
  227918. EAGLContext* context;
  227919. bool useDepthBuffer;
  227920. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  227921. int numFrames;
  227922. int lastWidth, lastHeight;
  227923. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  227924. };
  227925. OpenGLContext* OpenGLComponent::createContext()
  227926. {
  227927. ScopedAutoReleasePool pool;
  227928. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  227929. if (peer != 0)
  227930. return new GLESContext (peer, this, preferredPixelFormat,
  227931. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  227932. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  227933. return 0;
  227934. }
  227935. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  227936. OwnedArray <OpenGLPixelFormat>& /*results*/)
  227937. {
  227938. }
  227939. void juce_glViewport (const int w, const int h)
  227940. {
  227941. glViewport (0, 0, w, h);
  227942. }
  227943. #endif
  227944. #endif
  227945. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  227946. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  227947. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227948. // compiled on its own).
  227949. #if JUCE_INCLUDED_FILE
  227950. #if JUCE_MAC
  227951. namespace MouseCursorHelpers
  227952. {
  227953. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  227954. {
  227955. NSImage* im = CoreGraphicsImage::createNSImage (image);
  227956. NSCursor* c = [[NSCursor alloc] initWithImage: im
  227957. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  227958. [im release];
  227959. return c;
  227960. }
  227961. static void* fromWebKitFile (const char* filename, float hx, float hy)
  227962. {
  227963. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  227964. BufferedInputStream buf (fileStream, 4096);
  227965. PNGImageFormat pngFormat;
  227966. Image im (pngFormat.decodeImage (buf));
  227967. if (im.isValid())
  227968. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  227969. jassertfalse;
  227970. return 0;
  227971. }
  227972. }
  227973. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  227974. {
  227975. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  227976. }
  227977. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  227978. {
  227979. const ScopedAutoReleasePool pool;
  227980. NSCursor* c = 0;
  227981. switch (type)
  227982. {
  227983. case NormalCursor: c = [NSCursor arrowCursor]; break;
  227984. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  227985. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  227986. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  227987. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  227988. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  227989. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  227990. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  227991. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  227992. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  227993. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  227994. case UpDownResizeCursor:
  227995. case TopEdgeResizeCursor:
  227996. case BottomEdgeResizeCursor:
  227997. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  227998. case TopLeftCornerResizeCursor:
  227999. case BottomRightCornerResizeCursor:
  228000. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  228001. case TopRightCornerResizeCursor:
  228002. case BottomLeftCornerResizeCursor:
  228003. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  228004. case UpDownLeftRightResizeCursor:
  228005. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  228006. default:
  228007. jassertfalse;
  228008. break;
  228009. }
  228010. [c retain];
  228011. return c;
  228012. }
  228013. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  228014. {
  228015. [((NSCursor*) cursorHandle) release];
  228016. }
  228017. void MouseCursor::showInAllWindows() const
  228018. {
  228019. showInWindow (0);
  228020. }
  228021. void MouseCursor::showInWindow (ComponentPeer*) const
  228022. {
  228023. NSCursor* c = (NSCursor*) getHandle();
  228024. if (c == 0)
  228025. c = [NSCursor arrowCursor];
  228026. [c set];
  228027. }
  228028. #else
  228029. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  228030. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  228031. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  228032. void MouseCursor::showInAllWindows() const {}
  228033. void MouseCursor::showInWindow (ComponentPeer*) const {}
  228034. #endif
  228035. #endif
  228036. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  228037. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228038. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228039. // compiled on its own).
  228040. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  228041. #if JUCE_MAC
  228042. END_JUCE_NAMESPACE
  228043. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  228044. @interface DownloadClickDetector : NSObject
  228045. {
  228046. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  228047. }
  228048. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  228049. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228050. request: (NSURLRequest*) request
  228051. frame: (WebFrame*) frame
  228052. decisionListener: (id<WebPolicyDecisionListener>) listener;
  228053. @end
  228054. @implementation DownloadClickDetector
  228055. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  228056. {
  228057. [super init];
  228058. ownerComponent = ownerComponent_;
  228059. return self;
  228060. }
  228061. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228062. request: (NSURLRequest*) request
  228063. frame: (WebFrame*) frame
  228064. decisionListener: (id <WebPolicyDecisionListener>) listener
  228065. {
  228066. (void) sender;
  228067. (void) request;
  228068. (void) frame;
  228069. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  228070. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  228071. [listener use];
  228072. else
  228073. [listener ignore];
  228074. }
  228075. @end
  228076. BEGIN_JUCE_NAMESPACE
  228077. class WebBrowserComponentInternal : public NSViewComponent
  228078. {
  228079. public:
  228080. WebBrowserComponentInternal (WebBrowserComponent* owner)
  228081. {
  228082. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228083. frameName: @""
  228084. groupName: @""];
  228085. setView (webView);
  228086. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  228087. [webView setPolicyDelegate: clickListener];
  228088. }
  228089. ~WebBrowserComponentInternal()
  228090. {
  228091. [webView setPolicyDelegate: nil];
  228092. [clickListener release];
  228093. setView (0);
  228094. }
  228095. void goToURL (const String& url,
  228096. const StringArray* headers,
  228097. const MemoryBlock* postData)
  228098. {
  228099. NSMutableURLRequest* r
  228100. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  228101. cachePolicy: NSURLRequestUseProtocolCachePolicy
  228102. timeoutInterval: 30.0];
  228103. if (postData != 0 && postData->getSize() > 0)
  228104. {
  228105. [r setHTTPMethod: @"POST"];
  228106. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  228107. length: postData->getSize()]];
  228108. }
  228109. if (headers != 0)
  228110. {
  228111. for (int i = 0; i < headers->size(); ++i)
  228112. {
  228113. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  228114. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  228115. [r setValue: juceStringToNS (headerValue)
  228116. forHTTPHeaderField: juceStringToNS (headerName)];
  228117. }
  228118. }
  228119. stop();
  228120. [[webView mainFrame] loadRequest: r];
  228121. }
  228122. void goBack()
  228123. {
  228124. [webView goBack];
  228125. }
  228126. void goForward()
  228127. {
  228128. [webView goForward];
  228129. }
  228130. void stop()
  228131. {
  228132. [webView stopLoading: nil];
  228133. }
  228134. void refresh()
  228135. {
  228136. [webView reload: nil];
  228137. }
  228138. void mouseMove (const MouseEvent&)
  228139. {
  228140. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  228141. // them work is to push them via this non-public method..
  228142. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  228143. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  228144. }
  228145. private:
  228146. WebView* webView;
  228147. DownloadClickDetector* clickListener;
  228148. };
  228149. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228150. : browser (0),
  228151. blankPageShown (false),
  228152. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  228153. {
  228154. setOpaque (true);
  228155. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  228156. }
  228157. WebBrowserComponent::~WebBrowserComponent()
  228158. {
  228159. deleteAndZero (browser);
  228160. }
  228161. void WebBrowserComponent::goToURL (const String& url,
  228162. const StringArray* headers,
  228163. const MemoryBlock* postData)
  228164. {
  228165. lastURL = url;
  228166. lastHeaders.clear();
  228167. if (headers != 0)
  228168. lastHeaders = *headers;
  228169. lastPostData.setSize (0);
  228170. if (postData != 0)
  228171. lastPostData = *postData;
  228172. blankPageShown = false;
  228173. browser->goToURL (url, headers, postData);
  228174. }
  228175. void WebBrowserComponent::stop()
  228176. {
  228177. browser->stop();
  228178. }
  228179. void WebBrowserComponent::goBack()
  228180. {
  228181. lastURL = String::empty;
  228182. blankPageShown = false;
  228183. browser->goBack();
  228184. }
  228185. void WebBrowserComponent::goForward()
  228186. {
  228187. lastURL = String::empty;
  228188. browser->goForward();
  228189. }
  228190. void WebBrowserComponent::refresh()
  228191. {
  228192. browser->refresh();
  228193. }
  228194. void WebBrowserComponent::paint (Graphics&)
  228195. {
  228196. }
  228197. void WebBrowserComponent::checkWindowAssociation()
  228198. {
  228199. if (isShowing())
  228200. {
  228201. if (blankPageShown)
  228202. goBack();
  228203. }
  228204. else
  228205. {
  228206. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  228207. {
  228208. // when the component becomes invisible, some stuff like flash
  228209. // carries on playing audio, so we need to force it onto a blank
  228210. // page to avoid this, (and send it back when it's made visible again).
  228211. blankPageShown = true;
  228212. browser->goToURL ("about:blank", 0, 0);
  228213. }
  228214. }
  228215. }
  228216. void WebBrowserComponent::reloadLastURL()
  228217. {
  228218. if (lastURL.isNotEmpty())
  228219. {
  228220. goToURL (lastURL, &lastHeaders, &lastPostData);
  228221. lastURL = String::empty;
  228222. }
  228223. }
  228224. void WebBrowserComponent::parentHierarchyChanged()
  228225. {
  228226. checkWindowAssociation();
  228227. }
  228228. void WebBrowserComponent::resized()
  228229. {
  228230. browser->setSize (getWidth(), getHeight());
  228231. }
  228232. void WebBrowserComponent::visibilityChanged()
  228233. {
  228234. checkWindowAssociation();
  228235. }
  228236. bool WebBrowserComponent::pageAboutToLoad (const String&)
  228237. {
  228238. return true;
  228239. }
  228240. #else
  228241. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228242. {
  228243. }
  228244. WebBrowserComponent::~WebBrowserComponent()
  228245. {
  228246. }
  228247. void WebBrowserComponent::goToURL (const String& url,
  228248. const StringArray* headers,
  228249. const MemoryBlock* postData)
  228250. {
  228251. }
  228252. void WebBrowserComponent::stop()
  228253. {
  228254. }
  228255. void WebBrowserComponent::goBack()
  228256. {
  228257. }
  228258. void WebBrowserComponent::goForward()
  228259. {
  228260. }
  228261. void WebBrowserComponent::refresh()
  228262. {
  228263. }
  228264. void WebBrowserComponent::paint (Graphics& g)
  228265. {
  228266. }
  228267. void WebBrowserComponent::checkWindowAssociation()
  228268. {
  228269. }
  228270. void WebBrowserComponent::reloadLastURL()
  228271. {
  228272. }
  228273. void WebBrowserComponent::parentHierarchyChanged()
  228274. {
  228275. }
  228276. void WebBrowserComponent::resized()
  228277. {
  228278. }
  228279. void WebBrowserComponent::visibilityChanged()
  228280. {
  228281. }
  228282. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  228283. {
  228284. return true;
  228285. }
  228286. #endif
  228287. #endif
  228288. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228289. /*** Start of inlined file: juce_ios_Audio.cpp ***/
  228290. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228291. // compiled on its own).
  228292. #if JUCE_INCLUDED_FILE
  228293. class IPhoneAudioIODevice : public AudioIODevice
  228294. {
  228295. public:
  228296. IPhoneAudioIODevice (const String& deviceName)
  228297. : AudioIODevice (deviceName, "Audio"),
  228298. actualBufferSize (0),
  228299. isRunning (false),
  228300. audioUnit (0),
  228301. callback (0),
  228302. floatData (1, 2)
  228303. {
  228304. numInputChannels = 2;
  228305. numOutputChannels = 2;
  228306. preferredBufferSize = 0;
  228307. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  228308. updateDeviceInfo();
  228309. }
  228310. ~IPhoneAudioIODevice()
  228311. {
  228312. close();
  228313. }
  228314. const StringArray getOutputChannelNames()
  228315. {
  228316. StringArray s;
  228317. s.add ("Left");
  228318. s.add ("Right");
  228319. return s;
  228320. }
  228321. const StringArray getInputChannelNames()
  228322. {
  228323. StringArray s;
  228324. if (audioInputIsAvailable)
  228325. {
  228326. s.add ("Left");
  228327. s.add ("Right");
  228328. }
  228329. return s;
  228330. }
  228331. int getNumSampleRates()
  228332. {
  228333. return 1;
  228334. }
  228335. double getSampleRate (int index)
  228336. {
  228337. return sampleRate;
  228338. }
  228339. int getNumBufferSizesAvailable()
  228340. {
  228341. return 1;
  228342. }
  228343. int getBufferSizeSamples (int index)
  228344. {
  228345. return getDefaultBufferSize();
  228346. }
  228347. int getDefaultBufferSize()
  228348. {
  228349. return 1024;
  228350. }
  228351. const String open (const BigInteger& inputChannels,
  228352. const BigInteger& outputChannels,
  228353. double sampleRate,
  228354. int bufferSize)
  228355. {
  228356. close();
  228357. lastError = String::empty;
  228358. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  228359. // xxx set up channel mapping
  228360. activeOutputChans = outputChannels;
  228361. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  228362. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  228363. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  228364. activeInputChans = inputChannels;
  228365. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  228366. numInputChannels = activeInputChans.countNumberOfSetBits();
  228367. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  228368. AudioSessionSetActive (true);
  228369. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  228370. : kAudioSessionCategory_MediaPlayback;
  228371. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  228372. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  228373. fixAudioRouteIfSetToReceiver();
  228374. updateDeviceInfo();
  228375. Float32 bufferDuration = preferredBufferSize / sampleRate;
  228376. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  228377. actualBufferSize = preferredBufferSize;
  228378. prepareFloatBuffers();
  228379. isRunning = true;
  228380. propertyChanged (0, 0, 0); // creates and starts the AU
  228381. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  228382. return lastError;
  228383. }
  228384. void close()
  228385. {
  228386. if (isRunning)
  228387. {
  228388. isRunning = false;
  228389. AudioSessionSetActive (false);
  228390. if (audioUnit != 0)
  228391. {
  228392. AudioComponentInstanceDispose (audioUnit);
  228393. audioUnit = 0;
  228394. }
  228395. }
  228396. }
  228397. bool isOpen()
  228398. {
  228399. return isRunning;
  228400. }
  228401. int getCurrentBufferSizeSamples()
  228402. {
  228403. return actualBufferSize;
  228404. }
  228405. double getCurrentSampleRate()
  228406. {
  228407. return sampleRate;
  228408. }
  228409. int getCurrentBitDepth()
  228410. {
  228411. return 16;
  228412. }
  228413. const BigInteger getActiveOutputChannels() const
  228414. {
  228415. return activeOutputChans;
  228416. }
  228417. const BigInteger getActiveInputChannels() const
  228418. {
  228419. return activeInputChans;
  228420. }
  228421. int getOutputLatencyInSamples()
  228422. {
  228423. return 0; //xxx
  228424. }
  228425. int getInputLatencyInSamples()
  228426. {
  228427. return 0; //xxx
  228428. }
  228429. void start (AudioIODeviceCallback* callback_)
  228430. {
  228431. if (isRunning && callback != callback_)
  228432. {
  228433. if (callback_ != 0)
  228434. callback_->audioDeviceAboutToStart (this);
  228435. const ScopedLock sl (callbackLock);
  228436. callback = callback_;
  228437. }
  228438. }
  228439. void stop()
  228440. {
  228441. if (isRunning)
  228442. {
  228443. AudioIODeviceCallback* lastCallback;
  228444. {
  228445. const ScopedLock sl (callbackLock);
  228446. lastCallback = callback;
  228447. callback = 0;
  228448. }
  228449. if (lastCallback != 0)
  228450. lastCallback->audioDeviceStopped();
  228451. }
  228452. }
  228453. bool isPlaying()
  228454. {
  228455. return isRunning && callback != 0;
  228456. }
  228457. const String getLastError()
  228458. {
  228459. return lastError;
  228460. }
  228461. private:
  228462. CriticalSection callbackLock;
  228463. Float64 sampleRate;
  228464. int numInputChannels, numOutputChannels;
  228465. int preferredBufferSize;
  228466. int actualBufferSize;
  228467. bool isRunning;
  228468. String lastError;
  228469. AudioStreamBasicDescription format;
  228470. AudioUnit audioUnit;
  228471. UInt32 audioInputIsAvailable;
  228472. AudioIODeviceCallback* callback;
  228473. BigInteger activeOutputChans, activeInputChans;
  228474. AudioSampleBuffer floatData;
  228475. float* inputChannels[3];
  228476. float* outputChannels[3];
  228477. bool monoInputChannelNumber, monoOutputChannelNumber;
  228478. void prepareFloatBuffers()
  228479. {
  228480. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  228481. zerostruct (inputChannels);
  228482. zerostruct (outputChannels);
  228483. for (int i = 0; i < numInputChannels; ++i)
  228484. inputChannels[i] = floatData.getSampleData (i);
  228485. for (int i = 0; i < numOutputChannels; ++i)
  228486. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  228487. }
  228488. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  228489. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  228490. {
  228491. OSStatus err = noErr;
  228492. if (audioInputIsAvailable)
  228493. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  228494. const ScopedLock sl (callbackLock);
  228495. if (callback != 0)
  228496. {
  228497. if (audioInputIsAvailable && numInputChannels > 0)
  228498. {
  228499. short* shortData = (short*) ioData->mBuffers[0].mData;
  228500. if (numInputChannels >= 2)
  228501. {
  228502. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228503. {
  228504. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  228505. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  228506. }
  228507. }
  228508. else
  228509. {
  228510. if (monoInputChannelNumber > 0)
  228511. ++shortData;
  228512. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228513. {
  228514. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  228515. ++shortData;
  228516. }
  228517. }
  228518. }
  228519. else
  228520. {
  228521. for (int i = numInputChannels; --i >= 0;)
  228522. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  228523. }
  228524. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  228525. outputChannels, numOutputChannels,
  228526. (int) inNumberFrames);
  228527. short* shortData = (short*) ioData->mBuffers[0].mData;
  228528. int n = 0;
  228529. if (numOutputChannels >= 2)
  228530. {
  228531. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228532. {
  228533. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  228534. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  228535. }
  228536. }
  228537. else if (numOutputChannels == 1)
  228538. {
  228539. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228540. {
  228541. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  228542. shortData [n++] = s;
  228543. shortData [n++] = s;
  228544. }
  228545. }
  228546. else
  228547. {
  228548. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  228549. }
  228550. }
  228551. else
  228552. {
  228553. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  228554. }
  228555. return err;
  228556. }
  228557. void updateDeviceInfo()
  228558. {
  228559. UInt32 size = sizeof (sampleRate);
  228560. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  228561. size = sizeof (audioInputIsAvailable);
  228562. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  228563. }
  228564. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  228565. {
  228566. if (! isRunning)
  228567. return;
  228568. if (inPropertyValue != 0)
  228569. {
  228570. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  228571. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  228572. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  228573. SInt32 routeChangeReason;
  228574. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  228575. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  228576. fixAudioRouteIfSetToReceiver();
  228577. }
  228578. updateDeviceInfo();
  228579. createAudioUnit();
  228580. AudioSessionSetActive (true);
  228581. if (audioUnit != 0)
  228582. {
  228583. UInt32 formatSize = sizeof (format);
  228584. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  228585. Float32 bufferDuration = preferredBufferSize / sampleRate;
  228586. UInt32 bufferDurationSize = sizeof (bufferDuration);
  228587. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  228588. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  228589. AudioOutputUnitStart (audioUnit);
  228590. }
  228591. }
  228592. void interruptionListener (UInt32 inInterruption)
  228593. {
  228594. /*if (inInterruption == kAudioSessionBeginInterruption)
  228595. {
  228596. isRunning = false;
  228597. AudioOutputUnitStop (audioUnit);
  228598. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  228599. "This could have been interrupted by another application or by unplugging a headset",
  228600. @"Resume",
  228601. @"Cancel"))
  228602. {
  228603. isRunning = true;
  228604. propertyChanged (0, 0, 0);
  228605. }
  228606. }*/
  228607. if (inInterruption == kAudioSessionEndInterruption)
  228608. {
  228609. isRunning = true;
  228610. AudioSessionSetActive (true);
  228611. AudioOutputUnitStart (audioUnit);
  228612. }
  228613. }
  228614. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  228615. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  228616. {
  228617. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  228618. }
  228619. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  228620. {
  228621. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  228622. }
  228623. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  228624. {
  228625. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  228626. }
  228627. void resetFormat (const int numChannels)
  228628. {
  228629. memset (&format, 0, sizeof (format));
  228630. format.mFormatID = kAudioFormatLinearPCM;
  228631. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  228632. format.mBitsPerChannel = 8 * sizeof (short);
  228633. format.mChannelsPerFrame = 2;
  228634. format.mFramesPerPacket = 1;
  228635. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  228636. }
  228637. bool createAudioUnit()
  228638. {
  228639. if (audioUnit != 0)
  228640. {
  228641. AudioComponentInstanceDispose (audioUnit);
  228642. audioUnit = 0;
  228643. }
  228644. resetFormat (2);
  228645. AudioComponentDescription desc;
  228646. desc.componentType = kAudioUnitType_Output;
  228647. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  228648. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  228649. desc.componentFlags = 0;
  228650. desc.componentFlagsMask = 0;
  228651. AudioComponent comp = AudioComponentFindNext (0, &desc);
  228652. AudioComponentInstanceNew (comp, &audioUnit);
  228653. if (audioUnit == 0)
  228654. return false;
  228655. const UInt32 one = 1;
  228656. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  228657. AudioChannelLayout layout;
  228658. layout.mChannelBitmap = 0;
  228659. layout.mNumberChannelDescriptions = 0;
  228660. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  228661. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  228662. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  228663. AURenderCallbackStruct inputProc;
  228664. inputProc.inputProc = processStatic;
  228665. inputProc.inputProcRefCon = this;
  228666. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  228667. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  228668. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  228669. AudioUnitInitialize (audioUnit);
  228670. return true;
  228671. }
  228672. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  228673. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  228674. static void fixAudioRouteIfSetToReceiver()
  228675. {
  228676. CFStringRef audioRoute = 0;
  228677. UInt32 propertySize = sizeof (audioRoute);
  228678. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  228679. {
  228680. NSString* route = (NSString*) audioRoute;
  228681. //DBG ("audio route: " + nsStringToJuce (route));
  228682. if ([route hasPrefix: @"Receiver"])
  228683. {
  228684. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  228685. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  228686. }
  228687. CFRelease (audioRoute);
  228688. }
  228689. }
  228690. JUCE_DECLARE_NON_COPYABLE (IPhoneAudioIODevice);
  228691. };
  228692. class IPhoneAudioIODeviceType : public AudioIODeviceType
  228693. {
  228694. public:
  228695. IPhoneAudioIODeviceType()
  228696. : AudioIODeviceType ("iPhone Audio")
  228697. {
  228698. }
  228699. void scanForDevices()
  228700. {
  228701. }
  228702. const StringArray getDeviceNames (bool wantInputNames) const
  228703. {
  228704. StringArray s;
  228705. s.add ("iPhone Audio");
  228706. return s;
  228707. }
  228708. int getDefaultDeviceIndex (bool forInput) const
  228709. {
  228710. return 0;
  228711. }
  228712. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  228713. {
  228714. return device != 0 ? 0 : -1;
  228715. }
  228716. bool hasSeparateInputsAndOutputs() const { return false; }
  228717. AudioIODevice* createDevice (const String& outputDeviceName,
  228718. const String& inputDeviceName)
  228719. {
  228720. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  228721. {
  228722. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  228723. : inputDeviceName);
  228724. }
  228725. return 0;
  228726. }
  228727. private:
  228728. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IPhoneAudioIODeviceType);
  228729. };
  228730. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  228731. {
  228732. return new IPhoneAudioIODeviceType();
  228733. }
  228734. #endif
  228735. /*** End of inlined file: juce_ios_Audio.cpp ***/
  228736. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  228737. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228738. // compiled on its own).
  228739. #if JUCE_INCLUDED_FILE
  228740. #if JUCE_MAC
  228741. namespace CoreMidiHelpers
  228742. {
  228743. bool logError (const OSStatus err, const int lineNum)
  228744. {
  228745. if (err == noErr)
  228746. return true;
  228747. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  228748. jassertfalse;
  228749. return false;
  228750. }
  228751. #undef CHECK_ERROR
  228752. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  228753. const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  228754. {
  228755. String result;
  228756. CFStringRef str = 0;
  228757. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  228758. if (str != 0)
  228759. {
  228760. result = PlatformUtilities::cfStringToJuceString (str);
  228761. CFRelease (str);
  228762. str = 0;
  228763. }
  228764. MIDIEntityRef entity = 0;
  228765. MIDIEndpointGetEntity (endpoint, &entity);
  228766. if (entity == 0)
  228767. return result; // probably virtual
  228768. if (result.isEmpty())
  228769. {
  228770. // endpoint name has zero length - try the entity
  228771. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  228772. if (str != 0)
  228773. {
  228774. result += PlatformUtilities::cfStringToJuceString (str);
  228775. CFRelease (str);
  228776. str = 0;
  228777. }
  228778. }
  228779. // now consider the device's name
  228780. MIDIDeviceRef device = 0;
  228781. MIDIEntityGetDevice (entity, &device);
  228782. if (device == 0)
  228783. return result;
  228784. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  228785. if (str != 0)
  228786. {
  228787. const String s (PlatformUtilities::cfStringToJuceString (str));
  228788. CFRelease (str);
  228789. // if an external device has only one entity, throw away
  228790. // the endpoint name and just use the device name
  228791. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  228792. {
  228793. result = s;
  228794. }
  228795. else if (! result.startsWithIgnoreCase (s))
  228796. {
  228797. // prepend the device name to the entity name
  228798. result = (s + " " + result).trimEnd();
  228799. }
  228800. }
  228801. return result;
  228802. }
  228803. const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  228804. {
  228805. String result;
  228806. // Does the endpoint have connections?
  228807. CFDataRef connections = 0;
  228808. int numConnections = 0;
  228809. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  228810. if (connections != 0)
  228811. {
  228812. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  228813. if (numConnections > 0)
  228814. {
  228815. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  228816. for (int i = 0; i < numConnections; ++i, ++pid)
  228817. {
  228818. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  228819. MIDIObjectRef connObject;
  228820. MIDIObjectType connObjectType;
  228821. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  228822. if (err == noErr)
  228823. {
  228824. String s;
  228825. if (connObjectType == kMIDIObjectType_ExternalSource
  228826. || connObjectType == kMIDIObjectType_ExternalDestination)
  228827. {
  228828. // Connected to an external device's endpoint (10.3 and later).
  228829. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  228830. }
  228831. else
  228832. {
  228833. // Connected to an external device (10.2) (or something else, catch-all)
  228834. CFStringRef str = 0;
  228835. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  228836. if (str != 0)
  228837. {
  228838. s = PlatformUtilities::cfStringToJuceString (str);
  228839. CFRelease (str);
  228840. }
  228841. }
  228842. if (s.isNotEmpty())
  228843. {
  228844. if (result.isNotEmpty())
  228845. result += ", ";
  228846. result += s;
  228847. }
  228848. }
  228849. }
  228850. }
  228851. CFRelease (connections);
  228852. }
  228853. if (result.isNotEmpty())
  228854. return result;
  228855. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  228856. return getEndpointName (endpoint, false);
  228857. }
  228858. MIDIClientRef getGlobalMidiClient()
  228859. {
  228860. static MIDIClientRef globalMidiClient = 0;
  228861. if (globalMidiClient == 0)
  228862. {
  228863. String name ("JUCE");
  228864. if (JUCEApplication::getInstance() != 0)
  228865. name = JUCEApplication::getInstance()->getApplicationName();
  228866. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  228867. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  228868. CFRelease (appName);
  228869. }
  228870. return globalMidiClient;
  228871. }
  228872. class MidiPortAndEndpoint
  228873. {
  228874. public:
  228875. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  228876. : port (port_), endPoint (endPoint_)
  228877. {
  228878. }
  228879. ~MidiPortAndEndpoint()
  228880. {
  228881. if (port != 0)
  228882. MIDIPortDispose (port);
  228883. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  228884. MIDIEndpointDispose (endPoint);
  228885. }
  228886. void send (const MIDIPacketList* const packets)
  228887. {
  228888. if (port != 0)
  228889. MIDISend (port, endPoint, packets);
  228890. else
  228891. MIDIReceived (endPoint, packets);
  228892. }
  228893. MIDIPortRef port;
  228894. MIDIEndpointRef endPoint;
  228895. };
  228896. class MidiPortAndCallback;
  228897. CriticalSection callbackLock;
  228898. Array<MidiPortAndCallback*> activeCallbacks;
  228899. class MidiPortAndCallback
  228900. {
  228901. public:
  228902. MidiPortAndCallback (MidiInputCallback& callback_)
  228903. : input (0), active (false), callback (callback_), concatenator (2048)
  228904. {
  228905. }
  228906. ~MidiPortAndCallback()
  228907. {
  228908. active = false;
  228909. {
  228910. const ScopedLock sl (callbackLock);
  228911. activeCallbacks.removeValue (this);
  228912. }
  228913. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  228914. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  228915. }
  228916. void handlePackets (const MIDIPacketList* const pktlist)
  228917. {
  228918. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  228919. const ScopedLock sl (callbackLock);
  228920. if (activeCallbacks.contains (this) && active)
  228921. {
  228922. const MIDIPacket* packet = &pktlist->packet[0];
  228923. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  228924. {
  228925. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  228926. input, callback);
  228927. packet = MIDIPacketNext (packet);
  228928. }
  228929. }
  228930. }
  228931. MidiInput* input;
  228932. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  228933. volatile bool active;
  228934. private:
  228935. MidiInputCallback& callback;
  228936. MidiDataConcatenator concatenator;
  228937. };
  228938. void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  228939. {
  228940. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  228941. }
  228942. }
  228943. const StringArray MidiOutput::getDevices()
  228944. {
  228945. StringArray s;
  228946. const ItemCount num = MIDIGetNumberOfDestinations();
  228947. for (ItemCount i = 0; i < num; ++i)
  228948. {
  228949. MIDIEndpointRef dest = MIDIGetDestination (i);
  228950. if (dest != 0)
  228951. {
  228952. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  228953. if (name.isEmpty())
  228954. name = "<error>";
  228955. s.add (name);
  228956. }
  228957. else
  228958. {
  228959. s.add ("<error>");
  228960. }
  228961. }
  228962. return s;
  228963. }
  228964. int MidiOutput::getDefaultDeviceIndex()
  228965. {
  228966. return 0;
  228967. }
  228968. MidiOutput* MidiOutput::openDevice (int index)
  228969. {
  228970. MidiOutput* mo = 0;
  228971. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfDestinations()))
  228972. {
  228973. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  228974. CFStringRef pname;
  228975. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  228976. {
  228977. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  228978. MIDIPortRef port;
  228979. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  228980. {
  228981. mo = new MidiOutput();
  228982. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  228983. }
  228984. CFRelease (pname);
  228985. }
  228986. }
  228987. return mo;
  228988. }
  228989. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  228990. {
  228991. MidiOutput* mo = 0;
  228992. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  228993. MIDIEndpointRef endPoint;
  228994. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  228995. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  228996. {
  228997. mo = new MidiOutput();
  228998. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  228999. }
  229000. CFRelease (name);
  229001. return mo;
  229002. }
  229003. MidiOutput::~MidiOutput()
  229004. {
  229005. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229006. }
  229007. void MidiOutput::reset()
  229008. {
  229009. }
  229010. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  229011. {
  229012. return false;
  229013. }
  229014. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  229015. {
  229016. }
  229017. void MidiOutput::sendMessageNow (const MidiMessage& message)
  229018. {
  229019. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229020. if (message.isSysEx())
  229021. {
  229022. const int maxPacketSize = 256;
  229023. int pos = 0, bytesLeft = message.getRawDataSize();
  229024. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  229025. HeapBlock <MIDIPacketList> packets;
  229026. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  229027. packets->numPackets = numPackets;
  229028. MIDIPacket* p = packets->packet;
  229029. for (int i = 0; i < numPackets; ++i)
  229030. {
  229031. p->timeStamp = AudioGetCurrentHostTime();
  229032. p->length = jmin (maxPacketSize, bytesLeft);
  229033. memcpy (p->data, message.getRawData() + pos, p->length);
  229034. pos += p->length;
  229035. bytesLeft -= p->length;
  229036. p = MIDIPacketNext (p);
  229037. }
  229038. mpe->send (packets);
  229039. }
  229040. else
  229041. {
  229042. MIDIPacketList packets;
  229043. packets.numPackets = 1;
  229044. packets.packet[0].timeStamp = AudioGetCurrentHostTime();
  229045. packets.packet[0].length = message.getRawDataSize();
  229046. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  229047. mpe->send (&packets);
  229048. }
  229049. }
  229050. const StringArray MidiInput::getDevices()
  229051. {
  229052. StringArray s;
  229053. const ItemCount num = MIDIGetNumberOfSources();
  229054. for (ItemCount i = 0; i < num; ++i)
  229055. {
  229056. MIDIEndpointRef source = MIDIGetSource (i);
  229057. if (source != 0)
  229058. {
  229059. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  229060. if (name.isEmpty())
  229061. name = "<error>";
  229062. s.add (name);
  229063. }
  229064. else
  229065. {
  229066. s.add ("<error>");
  229067. }
  229068. }
  229069. return s;
  229070. }
  229071. int MidiInput::getDefaultDeviceIndex()
  229072. {
  229073. return 0;
  229074. }
  229075. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  229076. {
  229077. jassert (callback != 0);
  229078. using namespace CoreMidiHelpers;
  229079. MidiInput* newInput = 0;
  229080. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
  229081. {
  229082. MIDIEndpointRef endPoint = MIDIGetSource (index);
  229083. if (endPoint != 0)
  229084. {
  229085. CFStringRef name;
  229086. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  229087. {
  229088. MIDIClientRef client = getGlobalMidiClient();
  229089. if (client != 0)
  229090. {
  229091. MIDIPortRef port;
  229092. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229093. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  229094. {
  229095. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  229096. {
  229097. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  229098. newInput = new MidiInput (getDevices() [index]);
  229099. mpc->input = newInput;
  229100. newInput->internal = mpc;
  229101. const ScopedLock sl (callbackLock);
  229102. activeCallbacks.add (mpc.release());
  229103. }
  229104. else
  229105. {
  229106. CHECK_ERROR (MIDIPortDispose (port));
  229107. }
  229108. }
  229109. }
  229110. }
  229111. CFRelease (name);
  229112. }
  229113. }
  229114. return newInput;
  229115. }
  229116. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  229117. {
  229118. jassert (callback != 0);
  229119. using namespace CoreMidiHelpers;
  229120. MidiInput* mi = 0;
  229121. MIDIClientRef client = getGlobalMidiClient();
  229122. if (client != 0)
  229123. {
  229124. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229125. mpc->active = false;
  229126. MIDIEndpointRef endPoint;
  229127. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  229128. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  229129. {
  229130. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  229131. mi = new MidiInput (deviceName);
  229132. mpc->input = mi;
  229133. mi->internal = mpc;
  229134. const ScopedLock sl (callbackLock);
  229135. activeCallbacks.add (mpc.release());
  229136. }
  229137. CFRelease (name);
  229138. }
  229139. return mi;
  229140. }
  229141. MidiInput::MidiInput (const String& name_)
  229142. : name (name_)
  229143. {
  229144. }
  229145. MidiInput::~MidiInput()
  229146. {
  229147. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  229148. }
  229149. void MidiInput::start()
  229150. {
  229151. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229152. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  229153. }
  229154. void MidiInput::stop()
  229155. {
  229156. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229157. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  229158. }
  229159. #undef CHECK_ERROR
  229160. #else // Stubs for iOS...
  229161. MidiOutput::~MidiOutput() {}
  229162. void MidiOutput::reset() {}
  229163. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  229164. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  229165. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  229166. const StringArray MidiOutput::getDevices() { return StringArray(); }
  229167. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  229168. const StringArray MidiInput::getDevices() { return StringArray(); }
  229169. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  229170. #endif
  229171. #endif
  229172. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  229173. #else
  229174. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  229175. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229176. // compiled on its own).
  229177. #if JUCE_INCLUDED_FILE
  229178. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229179. #define SUPPORT_10_4_FONTS 1
  229180. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  229181. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229182. #define SUPPORT_ONLY_10_4_FONTS 1
  229183. #endif
  229184. END_JUCE_NAMESPACE
  229185. @interface NSFont (PrivateHack)
  229186. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  229187. @end
  229188. BEGIN_JUCE_NAMESPACE
  229189. #endif
  229190. class MacTypeface : public Typeface
  229191. {
  229192. public:
  229193. MacTypeface (const Font& font)
  229194. : Typeface (font.getTypefaceName())
  229195. {
  229196. const ScopedAutoReleasePool pool;
  229197. renderingTransform = CGAffineTransformIdentity;
  229198. bool needsItalicTransform = false;
  229199. #if JUCE_IOS
  229200. NSString* fontName = juceStringToNS (font.getTypefaceName());
  229201. if (font.isItalic() || font.isBold())
  229202. {
  229203. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  229204. for (NSString* i in familyFonts)
  229205. {
  229206. const String fn (nsStringToJuce (i));
  229207. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  229208. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  229209. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  229210. || afterDash.containsIgnoreCase ("italic")
  229211. || fn.endsWithIgnoreCase ("oblique")
  229212. || fn.endsWithIgnoreCase ("italic");
  229213. if (probablyBold == font.isBold()
  229214. && probablyItalic == font.isItalic())
  229215. {
  229216. fontName = i;
  229217. needsItalicTransform = false;
  229218. break;
  229219. }
  229220. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  229221. {
  229222. fontName = i;
  229223. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  229224. }
  229225. }
  229226. if (needsItalicTransform)
  229227. renderingTransform.c = 0.15f;
  229228. }
  229229. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  229230. const int ascender = abs (CGFontGetAscent (fontRef));
  229231. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  229232. ascent = ascender / totalHeight;
  229233. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229234. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  229235. #else
  229236. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  229237. if (font.isItalic())
  229238. {
  229239. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  229240. toHaveTrait: NSItalicFontMask];
  229241. if (newFont == nsFont)
  229242. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  229243. nsFont = newFont;
  229244. }
  229245. if (font.isBold())
  229246. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  229247. [nsFont retain];
  229248. ascent = std::abs ((float) [nsFont ascender]);
  229249. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  229250. ascent /= totalSize;
  229251. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  229252. if (needsItalicTransform)
  229253. {
  229254. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  229255. renderingTransform.c = 0.15f;
  229256. }
  229257. #if SUPPORT_ONLY_10_4_FONTS
  229258. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229259. if (atsFont == 0)
  229260. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229261. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229262. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229263. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229264. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229265. #else
  229266. #if SUPPORT_10_4_FONTS
  229267. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229268. {
  229269. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229270. if (atsFont == 0)
  229271. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229272. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229273. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229274. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229275. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229276. }
  229277. else
  229278. #endif
  229279. {
  229280. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  229281. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  229282. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229283. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  229284. }
  229285. #endif
  229286. #endif
  229287. }
  229288. ~MacTypeface()
  229289. {
  229290. #if ! JUCE_IOS
  229291. [nsFont release];
  229292. #endif
  229293. if (fontRef != 0)
  229294. CGFontRelease (fontRef);
  229295. }
  229296. float getAscent() const
  229297. {
  229298. return ascent;
  229299. }
  229300. float getDescent() const
  229301. {
  229302. return 1.0f - ascent;
  229303. }
  229304. float getStringWidth (const String& text)
  229305. {
  229306. if (fontRef == 0 || text.isEmpty())
  229307. return 0;
  229308. const int length = text.length();
  229309. HeapBlock <CGGlyph> glyphs;
  229310. createGlyphsForString (text.getCharPointer(), length, glyphs);
  229311. float x = 0;
  229312. #if SUPPORT_ONLY_10_4_FONTS
  229313. HeapBlock <NSSize> advances (length);
  229314. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229315. for (int i = 0; i < length; ++i)
  229316. x += advances[i].width;
  229317. #else
  229318. #if SUPPORT_10_4_FONTS
  229319. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229320. {
  229321. HeapBlock <NSSize> advances (length);
  229322. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  229323. for (int i = 0; i < length; ++i)
  229324. x += advances[i].width;
  229325. }
  229326. else
  229327. #endif
  229328. {
  229329. HeapBlock <int> advances (length);
  229330. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229331. for (int i = 0; i < length; ++i)
  229332. x += advances[i];
  229333. }
  229334. #endif
  229335. return x * unitsToHeightScaleFactor;
  229336. }
  229337. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  229338. {
  229339. xOffsets.add (0);
  229340. if (fontRef == 0 || text.isEmpty())
  229341. return;
  229342. const int length = text.length();
  229343. HeapBlock <CGGlyph> glyphs;
  229344. createGlyphsForString (text.getCharPointer(), length, glyphs);
  229345. #if SUPPORT_ONLY_10_4_FONTS
  229346. HeapBlock <NSSize> advances (length);
  229347. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229348. int x = 0;
  229349. for (int i = 0; i < length; ++i)
  229350. {
  229351. x += advances[i].width;
  229352. xOffsets.add (x * unitsToHeightScaleFactor);
  229353. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  229354. }
  229355. #else
  229356. #if SUPPORT_10_4_FONTS
  229357. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229358. {
  229359. HeapBlock <NSSize> advances (length);
  229360. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  229361. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  229362. float x = 0;
  229363. for (int i = 0; i < length; ++i)
  229364. {
  229365. x += advances[i].width;
  229366. xOffsets.add (x * unitsToHeightScaleFactor);
  229367. resultGlyphs.add (nsGlyphs[i]);
  229368. }
  229369. }
  229370. else
  229371. #endif
  229372. {
  229373. HeapBlock <int> advances (length);
  229374. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229375. {
  229376. int x = 0;
  229377. for (int i = 0; i < length; ++i)
  229378. {
  229379. x += advances [i];
  229380. xOffsets.add (x * unitsToHeightScaleFactor);
  229381. resultGlyphs.add (glyphs[i]);
  229382. }
  229383. }
  229384. }
  229385. #endif
  229386. }
  229387. bool getOutlineForGlyph (int glyphNumber, Path& path)
  229388. {
  229389. #if JUCE_IOS
  229390. return false;
  229391. #else
  229392. if (nsFont == 0)
  229393. return false;
  229394. // we might need to apply a transform to the path, so it mustn't have anything else in it
  229395. jassert (path.isEmpty());
  229396. const ScopedAutoReleasePool pool;
  229397. NSBezierPath* bez = [NSBezierPath bezierPath];
  229398. [bez moveToPoint: NSMakePoint (0, 0)];
  229399. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  229400. inFont: nsFont];
  229401. for (int i = 0; i < [bez elementCount]; ++i)
  229402. {
  229403. NSPoint p[3];
  229404. switch ([bez elementAtIndex: i associatedPoints: p])
  229405. {
  229406. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  229407. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  229408. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  229409. (float) p[1].x, (float) -p[1].y,
  229410. (float) p[2].x, (float) -p[2].y); break;
  229411. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  229412. default: jassertfalse; break;
  229413. }
  229414. }
  229415. path.applyTransform (pathTransform);
  229416. return true;
  229417. #endif
  229418. }
  229419. CGFontRef fontRef;
  229420. float fontHeightToCGSizeFactor;
  229421. CGAffineTransform renderingTransform;
  229422. private:
  229423. float ascent, unitsToHeightScaleFactor;
  229424. #if JUCE_IOS
  229425. #else
  229426. NSFont* nsFont;
  229427. AffineTransform pathTransform;
  229428. #endif
  229429. void createGlyphsForString (String::CharPointerType text, const int length, HeapBlock <CGGlyph>& glyphs)
  229430. {
  229431. #if SUPPORT_10_4_FONTS
  229432. #if ! SUPPORT_ONLY_10_4_FONTS
  229433. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229434. #endif
  229435. {
  229436. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  229437. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  229438. for (int i = 0; i < length; ++i)
  229439. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text.getAndAdvance()];
  229440. return;
  229441. }
  229442. #endif
  229443. #if ! SUPPORT_ONLY_10_4_FONTS
  229444. if (charToGlyphMapper == 0)
  229445. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  229446. glyphs.malloc (length);
  229447. for (int i = 0; i < length; ++i)
  229448. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text.getAndAdvance());
  229449. #endif
  229450. }
  229451. #if ! SUPPORT_ONLY_10_4_FONTS
  229452. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  229453. class CharToGlyphMapper
  229454. {
  229455. public:
  229456. CharToGlyphMapper (CGFontRef fontRef)
  229457. : segCount (0), endCode (0), startCode (0), idDelta (0),
  229458. idRangeOffset (0), glyphIndexes (0)
  229459. {
  229460. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  229461. if (cmapTable != 0)
  229462. {
  229463. const int numSubtables = getValue16 (cmapTable, 2);
  229464. for (int i = 0; i < numSubtables; ++i)
  229465. {
  229466. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  229467. {
  229468. const int offset = getValue32 (cmapTable, i * 8 + 8);
  229469. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  229470. {
  229471. const int length = getValue16 (cmapTable, offset + 2);
  229472. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  229473. segCount = segCountX2 / 2;
  229474. const int endCodeOffset = offset + 14;
  229475. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  229476. const int idDeltaOffset = startCodeOffset + segCountX2;
  229477. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  229478. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  229479. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  229480. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  229481. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  229482. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  229483. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  229484. }
  229485. break;
  229486. }
  229487. }
  229488. CFRelease (cmapTable);
  229489. }
  229490. }
  229491. ~CharToGlyphMapper()
  229492. {
  229493. if (endCode != 0)
  229494. {
  229495. CFRelease (endCode);
  229496. CFRelease (startCode);
  229497. CFRelease (idDelta);
  229498. CFRelease (idRangeOffset);
  229499. CFRelease (glyphIndexes);
  229500. }
  229501. }
  229502. int getGlyphForCharacter (const juce_wchar c) const
  229503. {
  229504. for (int i = 0; i < segCount; ++i)
  229505. {
  229506. if (getValue16 (endCode, i * 2) >= c)
  229507. {
  229508. const int start = getValue16 (startCode, i * 2);
  229509. if (start > c)
  229510. break;
  229511. const int delta = getValue16 (idDelta, i * 2);
  229512. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  229513. if (rangeOffset == 0)
  229514. return delta + c;
  229515. else
  229516. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  229517. }
  229518. }
  229519. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  229520. return jmax (-1, (int) c - 29);
  229521. }
  229522. private:
  229523. int segCount;
  229524. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  229525. static uint16 getValue16 (CFDataRef data, const int index)
  229526. {
  229527. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  229528. }
  229529. static uint32 getValue32 (CFDataRef data, const int index)
  229530. {
  229531. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  229532. }
  229533. };
  229534. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  229535. #endif
  229536. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  229537. };
  229538. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  229539. {
  229540. return new MacTypeface (font);
  229541. }
  229542. const StringArray Font::findAllTypefaceNames()
  229543. {
  229544. StringArray names;
  229545. const ScopedAutoReleasePool pool;
  229546. #if JUCE_IOS
  229547. NSArray* fonts = [UIFont familyNames];
  229548. #else
  229549. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  229550. #endif
  229551. for (unsigned int i = 0; i < [fonts count]; ++i)
  229552. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  229553. names.sort (true);
  229554. return names;
  229555. }
  229556. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  229557. {
  229558. #if JUCE_IOS
  229559. defaultSans = "Helvetica";
  229560. defaultSerif = "Times New Roman";
  229561. defaultFixed = "Courier New";
  229562. #else
  229563. defaultSans = "Lucida Grande";
  229564. defaultSerif = "Times New Roman";
  229565. defaultFixed = "Monaco";
  229566. #endif
  229567. defaultFallback = "Arial Unicode MS";
  229568. }
  229569. #endif
  229570. /*** End of inlined file: juce_mac_Fonts.mm ***/
  229571. // (must go before juce_mac_CoreGraphicsContext.mm)
  229572. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  229573. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229574. // compiled on its own).
  229575. #if JUCE_INCLUDED_FILE
  229576. class CoreGraphicsImage : public Image::SharedImage
  229577. {
  229578. public:
  229579. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  229580. : Image::SharedImage (format_, width_, height_)
  229581. {
  229582. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  229583. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  229584. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  229585. imageData = imageDataAllocated;
  229586. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  229587. : CGColorSpaceCreateDeviceRGB();
  229588. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  229589. colourSpace, getCGImageFlags (format_));
  229590. CGColorSpaceRelease (colourSpace);
  229591. }
  229592. ~CoreGraphicsImage()
  229593. {
  229594. CGContextRelease (context);
  229595. }
  229596. Image::ImageType getType() const { return Image::NativeImage; }
  229597. LowLevelGraphicsContext* createLowLevelContext();
  229598. SharedImage* clone()
  229599. {
  229600. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  229601. memcpy (im->imageData, imageData, lineStride * height);
  229602. return im;
  229603. }
  229604. static CGImageRef createImage (const Image& juceImage, const bool forAlpha,
  229605. CGColorSpaceRef colourSpace, const bool mustOutliveSource)
  229606. {
  229607. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  229608. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  229609. {
  229610. return CGBitmapContextCreateImage (nativeImage->context);
  229611. }
  229612. else
  229613. {
  229614. const Image::BitmapData srcData (juceImage, false);
  229615. CGDataProviderRef provider;
  229616. if (mustOutliveSource)
  229617. {
  229618. CFDataRef data = CFDataCreate (0, (const UInt8*) srcData.data, (CFIndex) (srcData.lineStride * srcData.height));
  229619. provider = CGDataProviderCreateWithCFData (data);
  229620. CFRelease (data);
  229621. }
  229622. else
  229623. {
  229624. provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  229625. }
  229626. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  229627. 8, srcData.pixelStride * 8, srcData.lineStride,
  229628. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  229629. 0, true, kCGRenderingIntentDefault);
  229630. CGDataProviderRelease (provider);
  229631. return imageRef;
  229632. }
  229633. }
  229634. #if JUCE_MAC
  229635. static NSImage* createNSImage (const Image& image)
  229636. {
  229637. const ScopedAutoReleasePool pool;
  229638. NSImage* im = [[NSImage alloc] init];
  229639. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  229640. [im lockFocus];
  229641. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  229642. CGImageRef imageRef = createImage (image, false, colourSpace, false);
  229643. CGColorSpaceRelease (colourSpace);
  229644. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  229645. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  229646. CGImageRelease (imageRef);
  229647. [im unlockFocus];
  229648. return im;
  229649. }
  229650. #endif
  229651. CGContextRef context;
  229652. HeapBlock<uint8> imageDataAllocated;
  229653. private:
  229654. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  229655. {
  229656. #if JUCE_BIG_ENDIAN
  229657. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  229658. #else
  229659. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  229660. #endif
  229661. }
  229662. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsImage);
  229663. };
  229664. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  229665. {
  229666. #if USE_COREGRAPHICS_RENDERING
  229667. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  229668. #else
  229669. return createSoftwareImage (format, width, height, clearImage);
  229670. #endif
  229671. }
  229672. class CoreGraphicsContext : public LowLevelGraphicsContext
  229673. {
  229674. public:
  229675. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  229676. : context (context_),
  229677. flipHeight (flipHeight_),
  229678. lastClipRectIsValid (false),
  229679. state (new SavedState()),
  229680. numGradientLookupEntries (0)
  229681. {
  229682. CGContextRetain (context);
  229683. CGContextSaveGState(context);
  229684. CGContextSetShouldSmoothFonts (context, true);
  229685. CGContextSetShouldAntialias (context, true);
  229686. CGContextSetBlendMode (context, kCGBlendModeNormal);
  229687. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  229688. greyColourSpace = CGColorSpaceCreateDeviceGray();
  229689. gradientCallbacks.version = 0;
  229690. gradientCallbacks.evaluate = gradientCallback;
  229691. gradientCallbacks.releaseInfo = 0;
  229692. setFont (Font());
  229693. }
  229694. ~CoreGraphicsContext()
  229695. {
  229696. CGContextRestoreGState (context);
  229697. CGContextRelease (context);
  229698. CGColorSpaceRelease (rgbColourSpace);
  229699. CGColorSpaceRelease (greyColourSpace);
  229700. }
  229701. bool isVectorDevice() const { return false; }
  229702. void setOrigin (int x, int y)
  229703. {
  229704. CGContextTranslateCTM (context, x, -y);
  229705. if (lastClipRectIsValid)
  229706. lastClipRect.translate (-x, -y);
  229707. }
  229708. void addTransform (const AffineTransform& transform)
  229709. {
  229710. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  229711. .translated (0, flipHeight)
  229712. .followedBy (transform)
  229713. .translated (0, -flipHeight)
  229714. .scaled (1.0f, -1.0f));
  229715. lastClipRectIsValid = false;
  229716. }
  229717. float getScaleFactor()
  229718. {
  229719. CGAffineTransform t = CGContextGetCTM (context);
  229720. return (float) juce_hypot (t.a + t.c, t.b + t.d);
  229721. }
  229722. bool clipToRectangle (const Rectangle<int>& r)
  229723. {
  229724. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  229725. if (lastClipRectIsValid)
  229726. {
  229727. // This is actually incorrect, because the actual clip region may be complex, and
  229728. // clipping its bounds to a rect may not be right... But, removing this shortcut
  229729. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  229730. // when calculating the resultant clip bounds, and makes the same mistake!
  229731. lastClipRect = lastClipRect.getIntersection (r);
  229732. return ! lastClipRect.isEmpty();
  229733. }
  229734. return ! isClipEmpty();
  229735. }
  229736. bool clipToRectangleList (const RectangleList& clipRegion)
  229737. {
  229738. if (clipRegion.isEmpty())
  229739. {
  229740. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  229741. lastClipRectIsValid = true;
  229742. lastClipRect = Rectangle<int>();
  229743. return false;
  229744. }
  229745. else
  229746. {
  229747. const int numRects = clipRegion.getNumRectangles();
  229748. HeapBlock <CGRect> rects (numRects);
  229749. for (int i = 0; i < numRects; ++i)
  229750. {
  229751. const Rectangle<int>& r = clipRegion.getRectangle(i);
  229752. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  229753. }
  229754. CGContextClipToRects (context, rects, numRects);
  229755. lastClipRectIsValid = false;
  229756. return ! isClipEmpty();
  229757. }
  229758. }
  229759. void excludeClipRectangle (const Rectangle<int>& r)
  229760. {
  229761. RectangleList remaining (getClipBounds());
  229762. remaining.subtract (r);
  229763. clipToRectangleList (remaining);
  229764. lastClipRectIsValid = false;
  229765. }
  229766. void clipToPath (const Path& path, const AffineTransform& transform)
  229767. {
  229768. createPath (path, transform);
  229769. CGContextClip (context);
  229770. lastClipRectIsValid = false;
  229771. }
  229772. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  229773. {
  229774. if (! transform.isSingularity())
  229775. {
  229776. Image singleChannelImage (sourceImage);
  229777. if (sourceImage.getFormat() != Image::SingleChannel)
  229778. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  229779. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace, true);
  229780. flip();
  229781. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  229782. applyTransform (t);
  229783. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  229784. CGContextClipToMask (context, r, image);
  229785. applyTransform (t.inverted());
  229786. flip();
  229787. CGImageRelease (image);
  229788. lastClipRectIsValid = false;
  229789. }
  229790. }
  229791. bool clipRegionIntersects (const Rectangle<int>& r)
  229792. {
  229793. return getClipBounds().intersects (r);
  229794. }
  229795. const Rectangle<int> getClipBounds() const
  229796. {
  229797. if (! lastClipRectIsValid)
  229798. {
  229799. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  229800. lastClipRectIsValid = true;
  229801. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  229802. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  229803. roundToInt (bounds.size.width),
  229804. roundToInt (bounds.size.height));
  229805. }
  229806. return lastClipRect;
  229807. }
  229808. bool isClipEmpty() const
  229809. {
  229810. return getClipBounds().isEmpty();
  229811. }
  229812. void saveState()
  229813. {
  229814. CGContextSaveGState (context);
  229815. stateStack.add (new SavedState (*state));
  229816. }
  229817. void restoreState()
  229818. {
  229819. CGContextRestoreGState (context);
  229820. SavedState* const top = stateStack.getLast();
  229821. if (top != 0)
  229822. {
  229823. state = top;
  229824. stateStack.removeLast (1, false);
  229825. lastClipRectIsValid = false;
  229826. }
  229827. else
  229828. {
  229829. jassertfalse; // trying to pop with an empty stack!
  229830. }
  229831. }
  229832. void beginTransparencyLayer (float opacity)
  229833. {
  229834. saveState();
  229835. CGContextSetAlpha (context, opacity);
  229836. CGContextBeginTransparencyLayer (context, 0);
  229837. }
  229838. void endTransparencyLayer()
  229839. {
  229840. CGContextEndTransparencyLayer (context);
  229841. restoreState();
  229842. }
  229843. void setFill (const FillType& fillType)
  229844. {
  229845. state->fillType = fillType;
  229846. if (fillType.isColour())
  229847. {
  229848. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  229849. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  229850. CGContextSetAlpha (context, 1.0f);
  229851. }
  229852. }
  229853. void setOpacity (float newOpacity)
  229854. {
  229855. state->fillType.setOpacity (newOpacity);
  229856. setFill (state->fillType);
  229857. }
  229858. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  229859. {
  229860. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  229861. ? kCGInterpolationLow
  229862. : kCGInterpolationHigh);
  229863. }
  229864. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  229865. {
  229866. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  229867. }
  229868. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  229869. {
  229870. if (replaceExistingContents)
  229871. {
  229872. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229873. CGContextClearRect (context, cgRect);
  229874. #else
  229875. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229876. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  229877. CGContextClearRect (context, cgRect);
  229878. else
  229879. #endif
  229880. CGContextSetBlendMode (context, kCGBlendModeCopy);
  229881. #endif
  229882. fillCGRect (cgRect, false);
  229883. CGContextSetBlendMode (context, kCGBlendModeNormal);
  229884. }
  229885. else
  229886. {
  229887. if (state->fillType.isColour())
  229888. {
  229889. CGContextFillRect (context, cgRect);
  229890. }
  229891. else if (state->fillType.isGradient())
  229892. {
  229893. CGContextSaveGState (context);
  229894. CGContextClipToRect (context, cgRect);
  229895. drawGradient();
  229896. CGContextRestoreGState (context);
  229897. }
  229898. else
  229899. {
  229900. CGContextSaveGState (context);
  229901. CGContextClipToRect (context, cgRect);
  229902. drawImage (state->fillType.image, state->fillType.transform, true);
  229903. CGContextRestoreGState (context);
  229904. }
  229905. }
  229906. }
  229907. void fillPath (const Path& path, const AffineTransform& transform)
  229908. {
  229909. CGContextSaveGState (context);
  229910. if (state->fillType.isColour())
  229911. {
  229912. flip();
  229913. applyTransform (transform);
  229914. createPath (path);
  229915. if (path.isUsingNonZeroWinding())
  229916. CGContextFillPath (context);
  229917. else
  229918. CGContextEOFillPath (context);
  229919. }
  229920. else
  229921. {
  229922. createPath (path, transform);
  229923. if (path.isUsingNonZeroWinding())
  229924. CGContextClip (context);
  229925. else
  229926. CGContextEOClip (context);
  229927. if (state->fillType.isGradient())
  229928. drawGradient();
  229929. else
  229930. drawImage (state->fillType.image, state->fillType.transform, true);
  229931. }
  229932. CGContextRestoreGState (context);
  229933. }
  229934. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  229935. {
  229936. const int iw = sourceImage.getWidth();
  229937. const int ih = sourceImage.getHeight();
  229938. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace, false);
  229939. CGContextSaveGState (context);
  229940. CGContextSetAlpha (context, state->fillType.getOpacity());
  229941. flip();
  229942. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  229943. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  229944. if (fillEntireClipAsTiles)
  229945. {
  229946. #if JUCE_IOS
  229947. CGContextDrawTiledImage (context, imageRect, image);
  229948. #else
  229949. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  229950. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  229951. // if it's doing a transformation - it's quicker to just draw lots of images manually
  229952. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  229953. CGContextDrawTiledImage (context, imageRect, image);
  229954. else
  229955. #endif
  229956. {
  229957. // Fallback to manually doing a tiled fill on 10.4
  229958. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  229959. int x = 0, y = 0;
  229960. while (x > clip.origin.x) x -= iw;
  229961. while (y > clip.origin.y) y -= ih;
  229962. const int right = (int) (clip.origin.x + clip.size.width);
  229963. const int bottom = (int) (clip.origin.y + clip.size.height);
  229964. while (y < bottom)
  229965. {
  229966. for (int x2 = x; x2 < right; x2 += iw)
  229967. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  229968. y += ih;
  229969. }
  229970. }
  229971. #endif
  229972. }
  229973. else
  229974. {
  229975. CGContextDrawImage (context, imageRect, image);
  229976. }
  229977. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  229978. CGContextRestoreGState (context);
  229979. }
  229980. void drawLine (const Line<float>& line)
  229981. {
  229982. if (state->fillType.isColour())
  229983. {
  229984. CGContextSetLineCap (context, kCGLineCapSquare);
  229985. CGContextSetLineWidth (context, 1.0f);
  229986. CGContextSetRGBStrokeColor (context,
  229987. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  229988. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  229989. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  229990. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  229991. CGContextStrokeLineSegments (context, cgLine, 1);
  229992. }
  229993. else
  229994. {
  229995. Path p;
  229996. p.addLineSegment (line, 1.0f);
  229997. fillPath (p, AffineTransform::identity);
  229998. }
  229999. }
  230000. void drawVerticalLine (const int x, float top, float bottom)
  230001. {
  230002. if (state->fillType.isColour())
  230003. {
  230004. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230005. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  230006. #else
  230007. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230008. // the x co-ord slightly to trick it..
  230009. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  230010. #endif
  230011. }
  230012. else
  230013. {
  230014. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  230015. }
  230016. }
  230017. void drawHorizontalLine (const int y, float left, float right)
  230018. {
  230019. if (state->fillType.isColour())
  230020. {
  230021. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230022. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  230023. #else
  230024. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230025. // the x co-ord slightly to trick it..
  230026. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  230027. #endif
  230028. }
  230029. else
  230030. {
  230031. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  230032. }
  230033. }
  230034. void setFont (const Font& newFont)
  230035. {
  230036. if (state->font != newFont)
  230037. {
  230038. state->fontRef = 0;
  230039. state->font = newFont;
  230040. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  230041. if (mf != 0)
  230042. {
  230043. state->fontRef = mf->fontRef;
  230044. CGContextSetFont (context, state->fontRef);
  230045. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  230046. state->fontTransform = mf->renderingTransform;
  230047. state->fontTransform.a *= state->font.getHorizontalScale();
  230048. CGContextSetTextMatrix (context, state->fontTransform);
  230049. }
  230050. }
  230051. }
  230052. const Font getFont()
  230053. {
  230054. return state->font;
  230055. }
  230056. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  230057. {
  230058. if (state->fontRef != 0 && state->fillType.isColour())
  230059. {
  230060. if (transform.isOnlyTranslation())
  230061. {
  230062. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  230063. CGGlyph g = glyphNumber;
  230064. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  230065. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  230066. }
  230067. else
  230068. {
  230069. CGContextSaveGState (context);
  230070. flip();
  230071. applyTransform (transform);
  230072. CGAffineTransform t = state->fontTransform;
  230073. t.d = -t.d;
  230074. CGContextSetTextMatrix (context, t);
  230075. CGGlyph g = glyphNumber;
  230076. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  230077. CGContextRestoreGState (context);
  230078. }
  230079. }
  230080. else
  230081. {
  230082. Path p;
  230083. Font& f = state->font;
  230084. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  230085. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  230086. .followedBy (transform));
  230087. }
  230088. }
  230089. private:
  230090. CGContextRef context;
  230091. const CGFloat flipHeight;
  230092. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  230093. CGFunctionCallbacks gradientCallbacks;
  230094. mutable Rectangle<int> lastClipRect;
  230095. mutable bool lastClipRectIsValid;
  230096. struct SavedState
  230097. {
  230098. SavedState()
  230099. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  230100. {
  230101. }
  230102. SavedState (const SavedState& other)
  230103. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  230104. fontTransform (other.fontTransform)
  230105. {
  230106. }
  230107. FillType fillType;
  230108. Font font;
  230109. CGFontRef fontRef;
  230110. CGAffineTransform fontTransform;
  230111. };
  230112. ScopedPointer <SavedState> state;
  230113. OwnedArray <SavedState> stateStack;
  230114. HeapBlock <PixelARGB> gradientLookupTable;
  230115. int numGradientLookupEntries;
  230116. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  230117. {
  230118. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  230119. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  230120. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  230121. colour.unpremultiply();
  230122. outData[0] = colour.getRed() / 255.0f;
  230123. outData[1] = colour.getGreen() / 255.0f;
  230124. outData[2] = colour.getBlue() / 255.0f;
  230125. outData[3] = colour.getAlpha() / 255.0f;
  230126. }
  230127. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  230128. {
  230129. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable) - 1;
  230130. CGShadingRef result = 0;
  230131. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  230132. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  230133. if (gradient.isRadial)
  230134. {
  230135. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  230136. p1, gradient.point1.getDistanceFrom (gradient.point2),
  230137. function, true, true);
  230138. }
  230139. else
  230140. {
  230141. result = CGShadingCreateAxial (rgbColourSpace, p1,
  230142. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  230143. function, true, true);
  230144. }
  230145. CGFunctionRelease (function);
  230146. return result;
  230147. }
  230148. void drawGradient()
  230149. {
  230150. flip();
  230151. applyTransform (state->fillType.transform);
  230152. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  230153. // you draw a gradient with high quality interp enabled).
  230154. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  230155. CGContextSetAlpha (context, state->fillType.getOpacity());
  230156. CGContextDrawShading (context, shading);
  230157. CGShadingRelease (shading);
  230158. }
  230159. void createPath (const Path& path) const
  230160. {
  230161. CGContextBeginPath (context);
  230162. Path::Iterator i (path);
  230163. while (i.next())
  230164. {
  230165. switch (i.elementType)
  230166. {
  230167. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  230168. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  230169. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  230170. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  230171. case Path::Iterator::closePath: CGContextClosePath (context); break;
  230172. default: jassertfalse; break;
  230173. }
  230174. }
  230175. }
  230176. void createPath (const Path& path, const AffineTransform& transform) const
  230177. {
  230178. CGContextBeginPath (context);
  230179. Path::Iterator i (path);
  230180. while (i.next())
  230181. {
  230182. switch (i.elementType)
  230183. {
  230184. case Path::Iterator::startNewSubPath:
  230185. transform.transformPoint (i.x1, i.y1);
  230186. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  230187. break;
  230188. case Path::Iterator::lineTo:
  230189. transform.transformPoint (i.x1, i.y1);
  230190. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  230191. break;
  230192. case Path::Iterator::quadraticTo:
  230193. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  230194. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  230195. break;
  230196. case Path::Iterator::cubicTo:
  230197. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  230198. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  230199. break;
  230200. case Path::Iterator::closePath:
  230201. CGContextClosePath (context); break;
  230202. default:
  230203. jassertfalse;
  230204. break;
  230205. }
  230206. }
  230207. }
  230208. void flip() const
  230209. {
  230210. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  230211. }
  230212. void applyTransform (const AffineTransform& transform) const
  230213. {
  230214. CGAffineTransform t;
  230215. t.a = transform.mat00;
  230216. t.b = transform.mat10;
  230217. t.c = transform.mat01;
  230218. t.d = transform.mat11;
  230219. t.tx = transform.mat02;
  230220. t.ty = transform.mat12;
  230221. CGContextConcatCTM (context, t);
  230222. }
  230223. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext);
  230224. };
  230225. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  230226. {
  230227. return new CoreGraphicsContext (context, height);
  230228. }
  230229. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  230230. const Image juce_loadWithCoreImage (InputStream& input)
  230231. {
  230232. MemoryBlock data;
  230233. input.readIntoMemoryBlock (data, -1);
  230234. #if JUCE_IOS
  230235. JUCE_AUTORELEASEPOOL
  230236. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  230237. length: data.getSize()
  230238. freeWhenDone: NO]];
  230239. if (image != nil)
  230240. {
  230241. CGImageRef loadedImage = image.CGImage;
  230242. #else
  230243. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  230244. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  230245. CGDataProviderRelease (provider);
  230246. if (imageSource != 0)
  230247. {
  230248. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  230249. CFRelease (imageSource);
  230250. #endif
  230251. if (loadedImage != 0)
  230252. {
  230253. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  230254. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  230255. && alphaInfo != kCGImageAlphaNoneSkipLast
  230256. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  230257. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  230258. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  230259. hasAlphaChan, Image::NativeImage);
  230260. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  230261. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  230262. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  230263. CGContextFlush (cgImage->context);
  230264. #if ! JUCE_IOS
  230265. CFRelease (loadedImage);
  230266. #endif
  230267. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  230268. // to find out whether the file they just loaded the image from had an alpha channel or not.
  230269. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  230270. return image;
  230271. }
  230272. }
  230273. return Image::null;
  230274. }
  230275. #endif
  230276. #endif
  230277. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230278. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230279. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230280. // compiled on its own).
  230281. #if JUCE_INCLUDED_FILE
  230282. class NSViewComponentPeer;
  230283. END_JUCE_NAMESPACE
  230284. @interface NSEvent (JuceDeviceDelta)
  230285. - (float) deviceDeltaX;
  230286. - (float) deviceDeltaY;
  230287. @end
  230288. #define JuceNSView MakeObjCClassName(JuceNSView)
  230289. @interface JuceNSView : NSView<NSTextInput>
  230290. {
  230291. @public
  230292. NSViewComponentPeer* owner;
  230293. NSNotificationCenter* notificationCenter;
  230294. String* stringBeingComposed;
  230295. bool textWasInserted;
  230296. }
  230297. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  230298. - (void) dealloc;
  230299. - (BOOL) isOpaque;
  230300. - (void) drawRect: (NSRect) r;
  230301. - (void) mouseDown: (NSEvent*) ev;
  230302. - (void) asyncMouseDown: (NSEvent*) ev;
  230303. - (void) mouseUp: (NSEvent*) ev;
  230304. - (void) asyncMouseUp: (NSEvent*) ev;
  230305. - (void) mouseDragged: (NSEvent*) ev;
  230306. - (void) mouseMoved: (NSEvent*) ev;
  230307. - (void) mouseEntered: (NSEvent*) ev;
  230308. - (void) mouseExited: (NSEvent*) ev;
  230309. - (void) rightMouseDown: (NSEvent*) ev;
  230310. - (void) rightMouseDragged: (NSEvent*) ev;
  230311. - (void) rightMouseUp: (NSEvent*) ev;
  230312. - (void) otherMouseDown: (NSEvent*) ev;
  230313. - (void) otherMouseDragged: (NSEvent*) ev;
  230314. - (void) otherMouseUp: (NSEvent*) ev;
  230315. - (void) scrollWheel: (NSEvent*) ev;
  230316. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  230317. - (void) frameChanged: (NSNotification*) n;
  230318. - (void) viewDidMoveToWindow;
  230319. - (void) keyDown: (NSEvent*) ev;
  230320. - (void) keyUp: (NSEvent*) ev;
  230321. // NSTextInput Methods
  230322. - (void) insertText: (id) aString;
  230323. - (void) doCommandBySelector: (SEL) aSelector;
  230324. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  230325. - (void) unmarkText;
  230326. - (BOOL) hasMarkedText;
  230327. - (long) conversationIdentifier;
  230328. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  230329. - (NSRange) markedRange;
  230330. - (NSRange) selectedRange;
  230331. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  230332. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  230333. - (NSArray*) validAttributesForMarkedText;
  230334. - (void) flagsChanged: (NSEvent*) ev;
  230335. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230336. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  230337. #endif
  230338. - (BOOL) becomeFirstResponder;
  230339. - (BOOL) resignFirstResponder;
  230340. - (BOOL) acceptsFirstResponder;
  230341. - (void) asyncRepaint: (id) rect;
  230342. - (NSArray*) getSupportedDragTypes;
  230343. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  230344. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  230345. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  230346. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  230347. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  230348. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  230349. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  230350. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  230351. @end
  230352. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  230353. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  230354. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  230355. #else
  230356. @interface JuceNSWindow : NSWindow
  230357. #endif
  230358. {
  230359. @private
  230360. NSViewComponentPeer* owner;
  230361. bool isZooming;
  230362. }
  230363. - (void) setOwner: (NSViewComponentPeer*) owner;
  230364. - (BOOL) canBecomeKeyWindow;
  230365. - (void) becomeKeyWindow;
  230366. - (BOOL) windowShouldClose: (id) window;
  230367. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  230368. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  230369. - (void) zoom: (id) sender;
  230370. @end
  230371. BEGIN_JUCE_NAMESPACE
  230372. class NSViewComponentPeer : public ComponentPeer
  230373. {
  230374. public:
  230375. NSViewComponentPeer (Component* const component,
  230376. const int windowStyleFlags,
  230377. NSView* viewToAttachTo);
  230378. ~NSViewComponentPeer();
  230379. void* getNativeHandle() const;
  230380. void setVisible (bool shouldBeVisible);
  230381. void setTitle (const String& title);
  230382. void setPosition (int x, int y);
  230383. void setSize (int w, int h);
  230384. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  230385. const Rectangle<int> getBounds (const bool global) const;
  230386. const Rectangle<int> getBounds() const;
  230387. const Point<int> getScreenPosition() const;
  230388. const Point<int> localToGlobal (const Point<int>& relativePosition);
  230389. const Point<int> globalToLocal (const Point<int>& screenPosition);
  230390. void setAlpha (float newAlpha);
  230391. void setMinimised (bool shouldBeMinimised);
  230392. bool isMinimised() const;
  230393. void setFullScreen (bool shouldBeFullScreen);
  230394. bool isFullScreen() const;
  230395. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  230396. const BorderSize<int> getFrameSize() const;
  230397. bool setAlwaysOnTop (bool alwaysOnTop);
  230398. void toFront (bool makeActiveWindow);
  230399. void toBehind (ComponentPeer* other);
  230400. void setIcon (const Image& newIcon);
  230401. const StringArray getAvailableRenderingEngines();
  230402. int getCurrentRenderingEngine() throw();
  230403. void setCurrentRenderingEngine (int index);
  230404. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  230405. for example having more than one juce plugin loaded into a host, then when a
  230406. method is called, the actual code that runs might actually be in a different module
  230407. than the one you expect... So any calls to library functions or statics that are
  230408. made inside obj-c methods will probably end up getting executed in a different DLL's
  230409. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  230410. To work around this insanity, I'm only allowing obj-c methods to make calls to
  230411. virtual methods of an object that's known to live inside the right module's space.
  230412. */
  230413. virtual void redirectMouseDown (NSEvent* ev);
  230414. virtual void redirectMouseUp (NSEvent* ev);
  230415. virtual void redirectMouseDrag (NSEvent* ev);
  230416. virtual void redirectMouseMove (NSEvent* ev);
  230417. virtual void redirectMouseEnter (NSEvent* ev);
  230418. virtual void redirectMouseExit (NSEvent* ev);
  230419. virtual void redirectMouseWheel (NSEvent* ev);
  230420. void sendMouseEvent (NSEvent* ev);
  230421. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  230422. virtual bool redirectKeyDown (NSEvent* ev);
  230423. virtual bool redirectKeyUp (NSEvent* ev);
  230424. virtual void redirectModKeyChange (NSEvent* ev);
  230425. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230426. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  230427. #endif
  230428. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  230429. virtual bool isOpaque();
  230430. virtual void drawRect (NSRect r);
  230431. virtual bool canBecomeKeyWindow();
  230432. virtual bool windowShouldClose();
  230433. virtual void redirectMovedOrResized();
  230434. virtual void viewMovedToWindow();
  230435. virtual NSRect constrainRect (NSRect r);
  230436. static void showArrowCursorIfNeeded();
  230437. static void updateModifiers (NSEvent* e);
  230438. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  230439. static int getKeyCodeFromEvent (NSEvent* ev)
  230440. {
  230441. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  230442. int keyCode = unmodified[0];
  230443. if (keyCode == 0x19) // (backwards-tab)
  230444. keyCode = '\t';
  230445. else if (keyCode == 0x03) // (enter)
  230446. keyCode = '\r';
  230447. else
  230448. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  230449. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  230450. {
  230451. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  230452. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  230453. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  230454. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  230455. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  230456. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  230457. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  230458. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  230459. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  230460. if (keyCode == numPadConversions [i])
  230461. keyCode = numPadConversions [i + 1];
  230462. }
  230463. return keyCode;
  230464. }
  230465. static int64 getMouseTime (NSEvent* e)
  230466. {
  230467. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  230468. + (int64) ([e timestamp] * 1000.0);
  230469. }
  230470. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  230471. {
  230472. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  230473. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  230474. }
  230475. static int getModifierForButtonNumber (const NSInteger num)
  230476. {
  230477. return num == 0 ? ModifierKeys::leftButtonModifier
  230478. : (num == 1 ? ModifierKeys::rightButtonModifier
  230479. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  230480. }
  230481. virtual void viewFocusGain();
  230482. virtual void viewFocusLoss();
  230483. bool isFocused() const;
  230484. void grabFocus();
  230485. void textInputRequired (const Point<int>& position);
  230486. void repaint (const Rectangle<int>& area);
  230487. void performAnyPendingRepaintsNow();
  230488. NSWindow* window;
  230489. JuceNSView* view;
  230490. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  230491. static ModifierKeys currentModifiers;
  230492. static ComponentPeer* currentlyFocusedPeer;
  230493. static Array<int> keysCurrentlyDown;
  230494. private:
  230495. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer);
  230496. };
  230497. END_JUCE_NAMESPACE
  230498. @implementation JuceNSView
  230499. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  230500. withFrame: (NSRect) frame
  230501. {
  230502. [super initWithFrame: frame];
  230503. owner = owner_;
  230504. stringBeingComposed = 0;
  230505. textWasInserted = false;
  230506. notificationCenter = [NSNotificationCenter defaultCenter];
  230507. [notificationCenter addObserver: self
  230508. selector: @selector (frameChanged:)
  230509. name: NSViewFrameDidChangeNotification
  230510. object: self];
  230511. if (! owner_->isSharedWindow)
  230512. {
  230513. [notificationCenter addObserver: self
  230514. selector: @selector (frameChanged:)
  230515. name: NSWindowDidMoveNotification
  230516. object: owner_->window];
  230517. }
  230518. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  230519. return self;
  230520. }
  230521. - (void) dealloc
  230522. {
  230523. [notificationCenter removeObserver: self];
  230524. delete stringBeingComposed;
  230525. [super dealloc];
  230526. }
  230527. - (void) drawRect: (NSRect) r
  230528. {
  230529. if (owner != 0)
  230530. owner->drawRect (r);
  230531. }
  230532. - (BOOL) isOpaque
  230533. {
  230534. return owner == 0 || owner->isOpaque();
  230535. }
  230536. - (void) mouseDown: (NSEvent*) ev
  230537. {
  230538. if (JUCEApplication::isStandaloneApp())
  230539. [self asyncMouseDown: ev];
  230540. else
  230541. // In some host situations, the host will stop modal loops from working
  230542. // correctly if they're called from a mouse event, so we'll trigger
  230543. // the event asynchronously..
  230544. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  230545. withObject: ev
  230546. waitUntilDone: NO];
  230547. }
  230548. - (void) asyncMouseDown: (NSEvent*) ev
  230549. {
  230550. if (owner != 0)
  230551. owner->redirectMouseDown (ev);
  230552. }
  230553. - (void) mouseUp: (NSEvent*) ev
  230554. {
  230555. if (! JUCEApplication::isStandaloneApp())
  230556. [self asyncMouseUp: ev];
  230557. else
  230558. // In some host situations, the host will stop modal loops from working
  230559. // correctly if they're called from a mouse event, so we'll trigger
  230560. // the event asynchronously..
  230561. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  230562. withObject: ev
  230563. waitUntilDone: NO];
  230564. }
  230565. - (void) asyncMouseUp: (NSEvent*) ev
  230566. {
  230567. if (owner != 0)
  230568. owner->redirectMouseUp (ev);
  230569. }
  230570. - (void) mouseDragged: (NSEvent*) ev
  230571. {
  230572. if (owner != 0)
  230573. owner->redirectMouseDrag (ev);
  230574. }
  230575. - (void) mouseMoved: (NSEvent*) ev
  230576. {
  230577. if (owner != 0)
  230578. owner->redirectMouseMove (ev);
  230579. }
  230580. - (void) mouseEntered: (NSEvent*) ev
  230581. {
  230582. if (owner != 0)
  230583. owner->redirectMouseEnter (ev);
  230584. }
  230585. - (void) mouseExited: (NSEvent*) ev
  230586. {
  230587. if (owner != 0)
  230588. owner->redirectMouseExit (ev);
  230589. }
  230590. - (void) rightMouseDown: (NSEvent*) ev
  230591. {
  230592. [self mouseDown: ev];
  230593. }
  230594. - (void) rightMouseDragged: (NSEvent*) ev
  230595. {
  230596. [self mouseDragged: ev];
  230597. }
  230598. - (void) rightMouseUp: (NSEvent*) ev
  230599. {
  230600. [self mouseUp: ev];
  230601. }
  230602. - (void) otherMouseDown: (NSEvent*) ev
  230603. {
  230604. [self mouseDown: ev];
  230605. }
  230606. - (void) otherMouseDragged: (NSEvent*) ev
  230607. {
  230608. [self mouseDragged: ev];
  230609. }
  230610. - (void) otherMouseUp: (NSEvent*) ev
  230611. {
  230612. [self mouseUp: ev];
  230613. }
  230614. - (void) scrollWheel: (NSEvent*) ev
  230615. {
  230616. if (owner != 0)
  230617. owner->redirectMouseWheel (ev);
  230618. }
  230619. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  230620. {
  230621. (void) ev;
  230622. return YES;
  230623. }
  230624. - (void) frameChanged: (NSNotification*) n
  230625. {
  230626. (void) n;
  230627. if (owner != 0)
  230628. owner->redirectMovedOrResized();
  230629. }
  230630. - (void) viewDidMoveToWindow
  230631. {
  230632. if (owner != 0)
  230633. owner->viewMovedToWindow();
  230634. }
  230635. - (void) asyncRepaint: (id) rect
  230636. {
  230637. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  230638. [self setNeedsDisplayInRect: *r];
  230639. }
  230640. - (void) keyDown: (NSEvent*) ev
  230641. {
  230642. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230643. textWasInserted = false;
  230644. if (target != 0)
  230645. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  230646. else
  230647. deleteAndZero (stringBeingComposed);
  230648. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  230649. [super keyDown: ev];
  230650. }
  230651. - (void) keyUp: (NSEvent*) ev
  230652. {
  230653. if (owner == 0 || ! owner->redirectKeyUp (ev))
  230654. [super keyUp: ev];
  230655. }
  230656. - (void) insertText: (id) aString
  230657. {
  230658. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  230659. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  230660. if ([newText length] > 0)
  230661. {
  230662. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230663. if (target != 0)
  230664. {
  230665. target->insertTextAtCaret (nsStringToJuce (newText));
  230666. textWasInserted = true;
  230667. }
  230668. }
  230669. deleteAndZero (stringBeingComposed);
  230670. }
  230671. - (void) doCommandBySelector: (SEL) aSelector
  230672. {
  230673. (void) aSelector;
  230674. }
  230675. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  230676. {
  230677. (void) selectionRange;
  230678. if (stringBeingComposed == 0)
  230679. stringBeingComposed = new String();
  230680. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  230681. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230682. if (target != 0)
  230683. {
  230684. const Range<int> currentHighlight (target->getHighlightedRegion());
  230685. target->insertTextAtCaret (*stringBeingComposed);
  230686. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  230687. textWasInserted = true;
  230688. }
  230689. }
  230690. - (void) unmarkText
  230691. {
  230692. if (stringBeingComposed != 0)
  230693. {
  230694. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230695. if (target != 0)
  230696. {
  230697. target->insertTextAtCaret (*stringBeingComposed);
  230698. textWasInserted = true;
  230699. }
  230700. }
  230701. deleteAndZero (stringBeingComposed);
  230702. }
  230703. - (BOOL) hasMarkedText
  230704. {
  230705. return stringBeingComposed != 0;
  230706. }
  230707. - (long) conversationIdentifier
  230708. {
  230709. return (long) (pointer_sized_int) self;
  230710. }
  230711. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  230712. {
  230713. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230714. if (target != 0)
  230715. {
  230716. const Range<int> r ((int) theRange.location,
  230717. (int) (theRange.location + theRange.length));
  230718. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  230719. }
  230720. return nil;
  230721. }
  230722. - (NSRange) markedRange
  230723. {
  230724. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  230725. : NSMakeRange (NSNotFound, 0);
  230726. }
  230727. - (NSRange) selectedRange
  230728. {
  230729. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230730. if (target != 0)
  230731. {
  230732. const Range<int> highlight (target->getHighlightedRegion());
  230733. if (! highlight.isEmpty())
  230734. return NSMakeRange (highlight.getStart(), highlight.getLength());
  230735. }
  230736. return NSMakeRange (NSNotFound, 0);
  230737. }
  230738. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  230739. {
  230740. (void) theRange;
  230741. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  230742. if (comp == 0)
  230743. return NSMakeRect (0, 0, 0, 0);
  230744. const Rectangle<int> bounds (comp->getScreenBounds());
  230745. return NSMakeRect (bounds.getX(),
  230746. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  230747. bounds.getWidth(),
  230748. bounds.getHeight());
  230749. }
  230750. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  230751. {
  230752. (void) thePoint;
  230753. return NSNotFound;
  230754. }
  230755. - (NSArray*) validAttributesForMarkedText
  230756. {
  230757. return [NSArray array];
  230758. }
  230759. - (void) flagsChanged: (NSEvent*) ev
  230760. {
  230761. if (owner != 0)
  230762. owner->redirectModKeyChange (ev);
  230763. }
  230764. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230765. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  230766. {
  230767. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  230768. return true;
  230769. return [super performKeyEquivalent: ev];
  230770. }
  230771. #endif
  230772. - (BOOL) becomeFirstResponder
  230773. {
  230774. if (owner != 0)
  230775. owner->viewFocusGain();
  230776. return true;
  230777. }
  230778. - (BOOL) resignFirstResponder
  230779. {
  230780. if (owner != 0)
  230781. owner->viewFocusLoss();
  230782. return true;
  230783. }
  230784. - (BOOL) acceptsFirstResponder
  230785. {
  230786. return owner != 0 && owner->canBecomeKeyWindow();
  230787. }
  230788. - (NSArray*) getSupportedDragTypes
  230789. {
  230790. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  230791. }
  230792. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  230793. {
  230794. return owner != 0 && owner->sendDragCallback (type, sender);
  230795. }
  230796. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  230797. {
  230798. if ([self sendDragCallback: 0 sender: sender])
  230799. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  230800. else
  230801. return NSDragOperationNone;
  230802. }
  230803. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  230804. {
  230805. if ([self sendDragCallback: 0 sender: sender])
  230806. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  230807. else
  230808. return NSDragOperationNone;
  230809. }
  230810. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  230811. {
  230812. [self sendDragCallback: 1 sender: sender];
  230813. }
  230814. - (void) draggingExited: (id <NSDraggingInfo>) sender
  230815. {
  230816. [self sendDragCallback: 1 sender: sender];
  230817. }
  230818. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  230819. {
  230820. (void) sender;
  230821. return YES;
  230822. }
  230823. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  230824. {
  230825. return [self sendDragCallback: 2 sender: sender];
  230826. }
  230827. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  230828. {
  230829. (void) sender;
  230830. }
  230831. @end
  230832. @implementation JuceNSWindow
  230833. - (void) setOwner: (NSViewComponentPeer*) owner_
  230834. {
  230835. owner = owner_;
  230836. isZooming = false;
  230837. }
  230838. - (BOOL) canBecomeKeyWindow
  230839. {
  230840. return owner != 0 && owner->canBecomeKeyWindow();
  230841. }
  230842. - (void) becomeKeyWindow
  230843. {
  230844. [super becomeKeyWindow];
  230845. if (owner != 0)
  230846. owner->grabFocus();
  230847. }
  230848. - (BOOL) windowShouldClose: (id) window
  230849. {
  230850. (void) window;
  230851. return owner == 0 || owner->windowShouldClose();
  230852. }
  230853. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  230854. {
  230855. (void) screen;
  230856. if (owner != 0)
  230857. frameRect = owner->constrainRect (frameRect);
  230858. return frameRect;
  230859. }
  230860. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  230861. {
  230862. (void) window;
  230863. if (isZooming)
  230864. return proposedFrameSize;
  230865. NSRect frameRect = [self frame];
  230866. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  230867. frameRect.size = proposedFrameSize;
  230868. if (owner != 0)
  230869. frameRect = owner->constrainRect (frameRect);
  230870. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  230871. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  230872. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  230873. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  230874. return frameRect.size;
  230875. }
  230876. - (void) zoom: (id) sender
  230877. {
  230878. isZooming = true;
  230879. [super zoom: sender];
  230880. isZooming = false;
  230881. }
  230882. - (void) windowWillMove: (NSNotification*) notification
  230883. {
  230884. (void) notification;
  230885. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  230886. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  230887. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  230888. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  230889. }
  230890. @end
  230891. BEGIN_JUCE_NAMESPACE
  230892. ModifierKeys NSViewComponentPeer::currentModifiers;
  230893. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  230894. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  230895. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  230896. {
  230897. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  230898. return true;
  230899. if (keyCode >= 'A' && keyCode <= 'Z'
  230900. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  230901. return true;
  230902. if (keyCode >= 'a' && keyCode <= 'z'
  230903. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  230904. return true;
  230905. return false;
  230906. }
  230907. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  230908. {
  230909. int m = 0;
  230910. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  230911. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  230912. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  230913. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  230914. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  230915. }
  230916. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  230917. {
  230918. updateModifiers (ev);
  230919. int keyCode = getKeyCodeFromEvent (ev);
  230920. if (keyCode != 0)
  230921. {
  230922. if (isKeyDown)
  230923. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  230924. else
  230925. keysCurrentlyDown.removeValue (keyCode);
  230926. }
  230927. }
  230928. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  230929. {
  230930. return NSViewComponentPeer::currentModifiers;
  230931. }
  230932. void ModifierKeys::updateCurrentModifiers() throw()
  230933. {
  230934. currentModifiers = NSViewComponentPeer::currentModifiers;
  230935. }
  230936. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  230937. const int windowStyleFlags,
  230938. NSView* viewToAttachTo)
  230939. : ComponentPeer (component_, windowStyleFlags),
  230940. window (0),
  230941. view (0),
  230942. isSharedWindow (viewToAttachTo != 0),
  230943. fullScreen (false),
  230944. insideDrawRect (false),
  230945. #if USE_COREGRAPHICS_RENDERING
  230946. usingCoreGraphics (true),
  230947. #else
  230948. usingCoreGraphics (false),
  230949. #endif
  230950. recursiveToFrontCall (false)
  230951. {
  230952. NSRect r = NSMakeRect (0, 0, (float) component->getWidth(),(float) component->getHeight());
  230953. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  230954. [view setPostsFrameChangedNotifications: YES];
  230955. if (isSharedWindow)
  230956. {
  230957. window = [viewToAttachTo window];
  230958. [viewToAttachTo addSubview: view];
  230959. }
  230960. else
  230961. {
  230962. r.origin.x = (float) component->getX();
  230963. r.origin.y = (float) component->getY();
  230964. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  230965. unsigned int style = 0;
  230966. if ((windowStyleFlags & windowHasTitleBar) == 0)
  230967. style = NSBorderlessWindowMask;
  230968. else
  230969. style = NSTitledWindowMask;
  230970. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  230971. style |= NSMiniaturizableWindowMask;
  230972. if ((windowStyleFlags & windowHasCloseButton) != 0)
  230973. style |= NSClosableWindowMask;
  230974. if ((windowStyleFlags & windowIsResizable) != 0)
  230975. style |= NSResizableWindowMask;
  230976. window = [[JuceNSWindow alloc] initWithContentRect: r
  230977. styleMask: style
  230978. backing: NSBackingStoreBuffered
  230979. defer: YES];
  230980. [((JuceNSWindow*) window) setOwner: this];
  230981. [window orderOut: nil];
  230982. [window setDelegate: (JuceNSWindow*) window];
  230983. [window setOpaque: component->isOpaque()];
  230984. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  230985. if (component->isAlwaysOnTop())
  230986. [window setLevel: NSFloatingWindowLevel];
  230987. [window setContentView: view];
  230988. [window setAutodisplay: YES];
  230989. [window setAcceptsMouseMovedEvents: YES];
  230990. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  230991. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  230992. [window setReleasedWhenClosed: YES];
  230993. [window retain];
  230994. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  230995. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  230996. }
  230997. const float alpha = component->getAlpha();
  230998. if (alpha < 1.0f)
  230999. setAlpha (alpha);
  231000. setTitle (component->getName());
  231001. }
  231002. NSViewComponentPeer::~NSViewComponentPeer()
  231003. {
  231004. view->owner = 0;
  231005. [view removeFromSuperview];
  231006. [view release];
  231007. if (! isSharedWindow)
  231008. {
  231009. [((JuceNSWindow*) window) setOwner: 0];
  231010. [window close];
  231011. [window release];
  231012. }
  231013. }
  231014. void* NSViewComponentPeer::getNativeHandle() const
  231015. {
  231016. return view;
  231017. }
  231018. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  231019. {
  231020. if (isSharedWindow)
  231021. {
  231022. [view setHidden: ! shouldBeVisible];
  231023. }
  231024. else
  231025. {
  231026. if (shouldBeVisible)
  231027. {
  231028. [window orderFront: nil];
  231029. handleBroughtToFront();
  231030. }
  231031. else
  231032. {
  231033. [window orderOut: nil];
  231034. }
  231035. }
  231036. }
  231037. void NSViewComponentPeer::setTitle (const String& title)
  231038. {
  231039. const ScopedAutoReleasePool pool;
  231040. if (! isSharedWindow)
  231041. [window setTitle: juceStringToNS (title)];
  231042. }
  231043. void NSViewComponentPeer::setPosition (int x, int y)
  231044. {
  231045. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  231046. }
  231047. void NSViewComponentPeer::setSize (int w, int h)
  231048. {
  231049. setBounds (component->getX(), component->getY(), w, h, false);
  231050. }
  231051. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  231052. {
  231053. fullScreen = isNowFullScreen;
  231054. NSRect r = NSMakeRect ((float) x, (float) y, (float) jmax (0, w), (float) jmax (0, h));
  231055. if (isSharedWindow)
  231056. {
  231057. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231058. if ([view frame].size.width != r.size.width
  231059. || [view frame].size.height != r.size.height)
  231060. [view setNeedsDisplay: true];
  231061. [view setFrame: r];
  231062. }
  231063. else
  231064. {
  231065. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231066. [window setFrame: [window frameRectForContentRect: r]
  231067. display: true];
  231068. }
  231069. }
  231070. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  231071. {
  231072. NSRect r = [view frame];
  231073. if (global && [view window] != 0)
  231074. {
  231075. r = [view convertRect: r toView: nil];
  231076. NSRect wr = [[view window] frame];
  231077. r.origin.x += wr.origin.x;
  231078. r.origin.y += wr.origin.y;
  231079. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231080. }
  231081. else
  231082. {
  231083. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  231084. }
  231085. return Rectangle<int> (convertToRectInt (r));
  231086. }
  231087. const Rectangle<int> NSViewComponentPeer::getBounds() const
  231088. {
  231089. return getBounds (! isSharedWindow);
  231090. }
  231091. const Point<int> NSViewComponentPeer::getScreenPosition() const
  231092. {
  231093. return getBounds (true).getPosition();
  231094. }
  231095. const Point<int> NSViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  231096. {
  231097. return relativePosition + getScreenPosition();
  231098. }
  231099. const Point<int> NSViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  231100. {
  231101. return screenPosition - getScreenPosition();
  231102. }
  231103. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  231104. {
  231105. if (constrainer != 0)
  231106. {
  231107. NSRect current = [window frame];
  231108. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  231109. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231110. Rectangle<int> pos (convertToRectInt (r));
  231111. Rectangle<int> original (convertToRectInt (current));
  231112. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_6
  231113. if ([window inLiveResize])
  231114. #else
  231115. if ([window respondsToSelector: @selector (inLiveResize)]
  231116. && [window performSelector: @selector (inLiveResize)])
  231117. #endif
  231118. {
  231119. constrainer->checkBounds (pos, original,
  231120. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231121. false, false, true, true);
  231122. }
  231123. else
  231124. {
  231125. constrainer->checkBounds (pos, original,
  231126. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231127. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  231128. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  231129. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  231130. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  231131. }
  231132. r.origin.x = pos.getX();
  231133. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  231134. r.size.width = pos.getWidth();
  231135. r.size.height = pos.getHeight();
  231136. }
  231137. return r;
  231138. }
  231139. void NSViewComponentPeer::setAlpha (float newAlpha)
  231140. {
  231141. if (! isSharedWindow)
  231142. [window setAlphaValue: (CGFloat) newAlpha];
  231143. else
  231144. [view setAlphaValue: (CGFloat) newAlpha];
  231145. }
  231146. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  231147. {
  231148. if (! isSharedWindow)
  231149. {
  231150. if (shouldBeMinimised)
  231151. [window miniaturize: nil];
  231152. else
  231153. [window deminiaturize: nil];
  231154. }
  231155. }
  231156. bool NSViewComponentPeer::isMinimised() const
  231157. {
  231158. return window != 0 && [window isMiniaturized];
  231159. }
  231160. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  231161. {
  231162. if (! isSharedWindow)
  231163. {
  231164. Rectangle<int> r (lastNonFullscreenBounds);
  231165. setMinimised (false);
  231166. if (fullScreen != shouldBeFullScreen)
  231167. {
  231168. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  231169. {
  231170. fullScreen = true;
  231171. [window performZoom: nil];
  231172. }
  231173. else
  231174. {
  231175. if (shouldBeFullScreen)
  231176. r = Desktop::getInstance().getMainMonitorArea();
  231177. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  231178. if (r != getComponent()->getBounds() && ! r.isEmpty())
  231179. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  231180. }
  231181. }
  231182. }
  231183. }
  231184. bool NSViewComponentPeer::isFullScreen() const
  231185. {
  231186. return fullScreen;
  231187. }
  231188. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  231189. {
  231190. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  231191. && isPositiveAndBelow (position.getY(), component->getHeight())))
  231192. return false;
  231193. NSPoint p;
  231194. p.x = (float) position.getX();
  231195. p.y = (float) position.getY();
  231196. NSView* v = [view hitTest: p];
  231197. if (trueIfInAChildWindow)
  231198. return v != nil;
  231199. return v == view;
  231200. }
  231201. const BorderSize<int> NSViewComponentPeer::getFrameSize() const
  231202. {
  231203. BorderSize<int> b;
  231204. if (! isSharedWindow)
  231205. {
  231206. NSRect v = [view convertRect: [view frame] toView: nil];
  231207. NSRect w = [window frame];
  231208. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  231209. b.setBottom ((int) v.origin.y);
  231210. b.setLeft ((int) v.origin.x);
  231211. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  231212. }
  231213. return b;
  231214. }
  231215. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  231216. {
  231217. if (! isSharedWindow)
  231218. {
  231219. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  231220. : NSNormalWindowLevel];
  231221. }
  231222. return true;
  231223. }
  231224. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  231225. {
  231226. if (isSharedWindow)
  231227. {
  231228. [[view superview] addSubview: view
  231229. positioned: NSWindowAbove
  231230. relativeTo: nil];
  231231. }
  231232. if (window != 0 && component->isVisible())
  231233. {
  231234. if (makeActiveWindow)
  231235. [window makeKeyAndOrderFront: nil];
  231236. else
  231237. [window orderFront: nil];
  231238. if (! recursiveToFrontCall)
  231239. {
  231240. recursiveToFrontCall = true;
  231241. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231242. handleBroughtToFront();
  231243. recursiveToFrontCall = false;
  231244. }
  231245. }
  231246. }
  231247. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  231248. {
  231249. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  231250. jassert (otherPeer != 0); // wrong type of window?
  231251. if (otherPeer != 0)
  231252. {
  231253. if (isSharedWindow)
  231254. {
  231255. [[view superview] addSubview: view
  231256. positioned: NSWindowBelow
  231257. relativeTo: otherPeer->view];
  231258. }
  231259. else
  231260. {
  231261. [window orderWindow: NSWindowBelow
  231262. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  231263. : nil ];
  231264. }
  231265. }
  231266. }
  231267. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  231268. {
  231269. // to do..
  231270. }
  231271. void NSViewComponentPeer::viewFocusGain()
  231272. {
  231273. if (currentlyFocusedPeer != this)
  231274. {
  231275. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  231276. currentlyFocusedPeer->handleFocusLoss();
  231277. currentlyFocusedPeer = this;
  231278. handleFocusGain();
  231279. }
  231280. }
  231281. void NSViewComponentPeer::viewFocusLoss()
  231282. {
  231283. if (currentlyFocusedPeer == this)
  231284. {
  231285. currentlyFocusedPeer = 0;
  231286. handleFocusLoss();
  231287. }
  231288. }
  231289. void juce_HandleProcessFocusChange()
  231290. {
  231291. NSViewComponentPeer::keysCurrentlyDown.clear();
  231292. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  231293. {
  231294. if (Process::isForegroundProcess())
  231295. {
  231296. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  231297. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  231298. }
  231299. else
  231300. {
  231301. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  231302. // turn kiosk mode off if we lose focus..
  231303. Desktop::getInstance().setKioskModeComponent (0);
  231304. }
  231305. }
  231306. }
  231307. bool NSViewComponentPeer::isFocused() const
  231308. {
  231309. return isSharedWindow ? this == currentlyFocusedPeer
  231310. : (window != 0 && [window isKeyWindow]);
  231311. }
  231312. void NSViewComponentPeer::grabFocus()
  231313. {
  231314. if (window != 0)
  231315. {
  231316. [window makeKeyWindow];
  231317. [window makeFirstResponder: view];
  231318. viewFocusGain();
  231319. }
  231320. }
  231321. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  231322. {
  231323. }
  231324. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  231325. {
  231326. String unicode (nsStringToJuce ([ev characters]));
  231327. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231328. int keyCode = getKeyCodeFromEvent (ev);
  231329. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  231330. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  231331. if (unicode.isNotEmpty() || keyCode != 0)
  231332. {
  231333. if (isKeyDown)
  231334. {
  231335. bool used = false;
  231336. while (unicode.length() > 0)
  231337. {
  231338. juce_wchar textCharacter = unicode[0];
  231339. unicode = unicode.substring (1);
  231340. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231341. textCharacter = 0;
  231342. used = handleKeyUpOrDown (true) || used;
  231343. used = handleKeyPress (keyCode, textCharacter) || used;
  231344. }
  231345. return used;
  231346. }
  231347. else
  231348. {
  231349. if (handleKeyUpOrDown (false))
  231350. return true;
  231351. }
  231352. }
  231353. return false;
  231354. }
  231355. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  231356. {
  231357. updateKeysDown (ev, true);
  231358. bool used = handleKeyEvent (ev, true);
  231359. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231360. {
  231361. // for command keys, the key-up event is thrown away, so simulate one..
  231362. updateKeysDown (ev, false);
  231363. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  231364. }
  231365. // (If we're running modally, don't allow unused keystrokes to be passed
  231366. // along to other blocked views..)
  231367. if (Component::getCurrentlyModalComponent() != 0)
  231368. used = true;
  231369. return used;
  231370. }
  231371. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  231372. {
  231373. updateKeysDown (ev, false);
  231374. return handleKeyEvent (ev, false)
  231375. || Component::getCurrentlyModalComponent() != 0;
  231376. }
  231377. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  231378. {
  231379. keysCurrentlyDown.clear();
  231380. handleKeyUpOrDown (true);
  231381. updateModifiers (ev);
  231382. handleModifierKeysChange();
  231383. }
  231384. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231385. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  231386. {
  231387. if ([ev type] == NSKeyDown)
  231388. return redirectKeyDown (ev);
  231389. else if ([ev type] == NSKeyUp)
  231390. return redirectKeyUp (ev);
  231391. return false;
  231392. }
  231393. #endif
  231394. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  231395. {
  231396. updateModifiers (ev);
  231397. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  231398. }
  231399. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  231400. {
  231401. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231402. sendMouseEvent (ev);
  231403. }
  231404. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  231405. {
  231406. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231407. sendMouseEvent (ev);
  231408. showArrowCursorIfNeeded();
  231409. }
  231410. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  231411. {
  231412. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231413. sendMouseEvent (ev);
  231414. }
  231415. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  231416. {
  231417. currentModifiers = currentModifiers.withoutMouseButtons();
  231418. sendMouseEvent (ev);
  231419. showArrowCursorIfNeeded();
  231420. }
  231421. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  231422. {
  231423. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231424. currentModifiers = currentModifiers.withoutMouseButtons();
  231425. sendMouseEvent (ev);
  231426. }
  231427. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  231428. {
  231429. currentModifiers = currentModifiers.withoutMouseButtons();
  231430. sendMouseEvent (ev);
  231431. }
  231432. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  231433. {
  231434. updateModifiers (ev);
  231435. float x = 0, y = 0;
  231436. @try
  231437. {
  231438. x = [ev deviceDeltaX] * 0.5f;
  231439. y = [ev deviceDeltaY] * 0.5f;
  231440. }
  231441. @catch (...)
  231442. {}
  231443. if (x == 0 && y == 0)
  231444. {
  231445. x = [ev deltaX] * 10.0f;
  231446. y = [ev deltaY] * 10.0f;
  231447. }
  231448. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  231449. }
  231450. void NSViewComponentPeer::showArrowCursorIfNeeded()
  231451. {
  231452. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  231453. if (mouse.getComponentUnderMouse() == 0
  231454. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  231455. {
  231456. [[NSCursor arrowCursor] set];
  231457. }
  231458. }
  231459. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  231460. {
  231461. NSString* bestType
  231462. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  231463. if (bestType == nil)
  231464. return false;
  231465. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  231466. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  231467. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  231468. if (list == nil)
  231469. return false;
  231470. StringArray files;
  231471. if ([list isKindOfClass: [NSArray class]])
  231472. {
  231473. NSArray* items = (NSArray*) list;
  231474. for (unsigned int i = 0; i < [items count]; ++i)
  231475. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  231476. }
  231477. if (files.size() == 0)
  231478. return false;
  231479. if (type == 0)
  231480. handleFileDragMove (files, pos);
  231481. else if (type == 1)
  231482. handleFileDragExit (files);
  231483. else if (type == 2)
  231484. handleFileDragDrop (files, pos);
  231485. return true;
  231486. }
  231487. bool NSViewComponentPeer::isOpaque()
  231488. {
  231489. return component == 0 || component->isOpaque();
  231490. }
  231491. void NSViewComponentPeer::drawRect (NSRect r)
  231492. {
  231493. if (r.size.width < 1.0f || r.size.height < 1.0f)
  231494. return;
  231495. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  231496. if (! component->isOpaque())
  231497. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  231498. #if USE_COREGRAPHICS_RENDERING
  231499. if (usingCoreGraphics)
  231500. {
  231501. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  231502. insideDrawRect = true;
  231503. handlePaint (context);
  231504. insideDrawRect = false;
  231505. }
  231506. else
  231507. #endif
  231508. {
  231509. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  231510. (int) (r.size.width + 0.5f),
  231511. (int) (r.size.height + 0.5f),
  231512. ! getComponent()->isOpaque());
  231513. const int xOffset = -roundToInt (r.origin.x);
  231514. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  231515. const NSRect* rects = 0;
  231516. NSInteger numRects = 0;
  231517. [view getRectsBeingDrawn: &rects count: &numRects];
  231518. const Rectangle<int> clipBounds (temp.getBounds());
  231519. RectangleList clip;
  231520. for (int i = 0; i < numRects; ++i)
  231521. {
  231522. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  231523. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  231524. roundToInt (rects[i].size.width),
  231525. roundToInt (rects[i].size.height))));
  231526. }
  231527. if (! clip.isEmpty())
  231528. {
  231529. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  231530. insideDrawRect = true;
  231531. handlePaint (context);
  231532. insideDrawRect = false;
  231533. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  231534. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace, false);
  231535. CGColorSpaceRelease (colourSpace);
  231536. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  231537. CGImageRelease (image);
  231538. }
  231539. }
  231540. }
  231541. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  231542. {
  231543. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  231544. #if USE_COREGRAPHICS_RENDERING
  231545. s.add ("CoreGraphics Renderer");
  231546. #endif
  231547. return s;
  231548. }
  231549. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  231550. {
  231551. return usingCoreGraphics ? 1 : 0;
  231552. }
  231553. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  231554. {
  231555. #if USE_COREGRAPHICS_RENDERING
  231556. if (usingCoreGraphics != (index > 0))
  231557. {
  231558. usingCoreGraphics = index > 0;
  231559. [view setNeedsDisplay: true];
  231560. }
  231561. #endif
  231562. }
  231563. bool NSViewComponentPeer::canBecomeKeyWindow()
  231564. {
  231565. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  231566. }
  231567. bool NSViewComponentPeer::windowShouldClose()
  231568. {
  231569. if (! isValidPeer (this))
  231570. return YES;
  231571. handleUserClosingWindow();
  231572. return NO;
  231573. }
  231574. void NSViewComponentPeer::redirectMovedOrResized()
  231575. {
  231576. handleMovedOrResized();
  231577. }
  231578. void NSViewComponentPeer::viewMovedToWindow()
  231579. {
  231580. if (isSharedWindow)
  231581. window = [view window];
  231582. }
  231583. void Desktop::createMouseInputSources()
  231584. {
  231585. mouseSources.add (new MouseInputSource (0, true));
  231586. }
  231587. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  231588. {
  231589. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  231590. if (enableOrDisable)
  231591. {
  231592. [NSApp setPresentationOptions: (allowMenusAndBars ? (NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)
  231593. : (NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar))];
  231594. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  231595. }
  231596. else
  231597. {
  231598. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  231599. }
  231600. #else
  231601. if (enableOrDisable)
  231602. {
  231603. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  231604. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  231605. }
  231606. else
  231607. {
  231608. SetSystemUIMode (kUIModeNormal, 0);
  231609. }
  231610. #endif
  231611. }
  231612. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  231613. {
  231614. if (insideDrawRect)
  231615. {
  231616. class AsyncRepaintMessage : public CallbackMessage
  231617. {
  231618. public:
  231619. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  231620. : peer (peer_), rect (rect_)
  231621. {
  231622. }
  231623. void messageCallback()
  231624. {
  231625. if (ComponentPeer::isValidPeer (peer))
  231626. peer->repaint (rect);
  231627. }
  231628. private:
  231629. NSViewComponentPeer* const peer;
  231630. const Rectangle<int> rect;
  231631. };
  231632. (new AsyncRepaintMessage (this, area))->post();
  231633. }
  231634. else
  231635. {
  231636. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  231637. (float) area.getWidth(), (float) area.getHeight())];
  231638. }
  231639. }
  231640. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  231641. {
  231642. [view displayIfNeeded];
  231643. }
  231644. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  231645. {
  231646. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  231647. }
  231648. const Image juce_createIconForFile (const File& file)
  231649. {
  231650. const ScopedAutoReleasePool pool;
  231651. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  231652. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  231653. [NSGraphicsContext saveGraphicsState];
  231654. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  231655. [image drawAtPoint: NSMakePoint (0, 0)
  231656. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  231657. operation: NSCompositeSourceOver fraction: 1.0f];
  231658. [[NSGraphicsContext currentContext] flushGraphics];
  231659. [NSGraphicsContext restoreGraphicsState];
  231660. return Image (result);
  231661. }
  231662. const int KeyPress::spaceKey = ' ';
  231663. const int KeyPress::returnKey = 0x0d;
  231664. const int KeyPress::escapeKey = 0x1b;
  231665. const int KeyPress::backspaceKey = 0x7f;
  231666. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  231667. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  231668. const int KeyPress::upKey = NSUpArrowFunctionKey;
  231669. const int KeyPress::downKey = NSDownArrowFunctionKey;
  231670. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  231671. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  231672. const int KeyPress::endKey = NSEndFunctionKey;
  231673. const int KeyPress::homeKey = NSHomeFunctionKey;
  231674. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  231675. const int KeyPress::insertKey = -1;
  231676. const int KeyPress::tabKey = 9;
  231677. const int KeyPress::F1Key = NSF1FunctionKey;
  231678. const int KeyPress::F2Key = NSF2FunctionKey;
  231679. const int KeyPress::F3Key = NSF3FunctionKey;
  231680. const int KeyPress::F4Key = NSF4FunctionKey;
  231681. const int KeyPress::F5Key = NSF5FunctionKey;
  231682. const int KeyPress::F6Key = NSF6FunctionKey;
  231683. const int KeyPress::F7Key = NSF7FunctionKey;
  231684. const int KeyPress::F8Key = NSF8FunctionKey;
  231685. const int KeyPress::F9Key = NSF9FunctionKey;
  231686. const int KeyPress::F10Key = NSF10FunctionKey;
  231687. const int KeyPress::F11Key = NSF1FunctionKey;
  231688. const int KeyPress::F12Key = NSF12FunctionKey;
  231689. const int KeyPress::F13Key = NSF13FunctionKey;
  231690. const int KeyPress::F14Key = NSF14FunctionKey;
  231691. const int KeyPress::F15Key = NSF15FunctionKey;
  231692. const int KeyPress::F16Key = NSF16FunctionKey;
  231693. const int KeyPress::numberPad0 = 0x30020;
  231694. const int KeyPress::numberPad1 = 0x30021;
  231695. const int KeyPress::numberPad2 = 0x30022;
  231696. const int KeyPress::numberPad3 = 0x30023;
  231697. const int KeyPress::numberPad4 = 0x30024;
  231698. const int KeyPress::numberPad5 = 0x30025;
  231699. const int KeyPress::numberPad6 = 0x30026;
  231700. const int KeyPress::numberPad7 = 0x30027;
  231701. const int KeyPress::numberPad8 = 0x30028;
  231702. const int KeyPress::numberPad9 = 0x30029;
  231703. const int KeyPress::numberPadAdd = 0x3002a;
  231704. const int KeyPress::numberPadSubtract = 0x3002b;
  231705. const int KeyPress::numberPadMultiply = 0x3002c;
  231706. const int KeyPress::numberPadDivide = 0x3002d;
  231707. const int KeyPress::numberPadSeparator = 0x3002e;
  231708. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  231709. const int KeyPress::numberPadEquals = 0x30030;
  231710. const int KeyPress::numberPadDelete = 0x30031;
  231711. const int KeyPress::playKey = 0x30000;
  231712. const int KeyPress::stopKey = 0x30001;
  231713. const int KeyPress::fastForwardKey = 0x30002;
  231714. const int KeyPress::rewindKey = 0x30003;
  231715. #endif
  231716. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  231717. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  231718. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231719. // compiled on its own).
  231720. #if JUCE_INCLUDED_FILE
  231721. #if JUCE_MAC
  231722. namespace MouseCursorHelpers
  231723. {
  231724. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  231725. {
  231726. NSImage* im = CoreGraphicsImage::createNSImage (image);
  231727. NSCursor* c = [[NSCursor alloc] initWithImage: im
  231728. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  231729. [im release];
  231730. return c;
  231731. }
  231732. static void* fromWebKitFile (const char* filename, float hx, float hy)
  231733. {
  231734. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  231735. BufferedInputStream buf (fileStream, 4096);
  231736. PNGImageFormat pngFormat;
  231737. Image im (pngFormat.decodeImage (buf));
  231738. if (im.isValid())
  231739. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  231740. jassertfalse;
  231741. return 0;
  231742. }
  231743. }
  231744. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  231745. {
  231746. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  231747. }
  231748. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  231749. {
  231750. const ScopedAutoReleasePool pool;
  231751. NSCursor* c = 0;
  231752. switch (type)
  231753. {
  231754. case NormalCursor: c = [NSCursor arrowCursor]; break;
  231755. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  231756. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  231757. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  231758. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  231759. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  231760. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  231761. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  231762. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  231763. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  231764. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  231765. case UpDownResizeCursor:
  231766. case TopEdgeResizeCursor:
  231767. case BottomEdgeResizeCursor:
  231768. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  231769. case TopLeftCornerResizeCursor:
  231770. case BottomRightCornerResizeCursor:
  231771. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  231772. case TopRightCornerResizeCursor:
  231773. case BottomLeftCornerResizeCursor:
  231774. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  231775. case UpDownLeftRightResizeCursor:
  231776. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  231777. default:
  231778. jassertfalse;
  231779. break;
  231780. }
  231781. [c retain];
  231782. return c;
  231783. }
  231784. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  231785. {
  231786. [((NSCursor*) cursorHandle) release];
  231787. }
  231788. void MouseCursor::showInAllWindows() const
  231789. {
  231790. showInWindow (0);
  231791. }
  231792. void MouseCursor::showInWindow (ComponentPeer*) const
  231793. {
  231794. NSCursor* c = (NSCursor*) getHandle();
  231795. if (c == 0)
  231796. c = [NSCursor arrowCursor];
  231797. [c set];
  231798. }
  231799. #else
  231800. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  231801. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  231802. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  231803. void MouseCursor::showInAllWindows() const {}
  231804. void MouseCursor::showInWindow (ComponentPeer*) const {}
  231805. #endif
  231806. #endif
  231807. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  231808. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  231809. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231810. // compiled on its own).
  231811. #if JUCE_INCLUDED_FILE
  231812. class NSViewComponentInternal : public ComponentMovementWatcher
  231813. {
  231814. public:
  231815. NSViewComponentInternal (NSView* const view_, Component& owner_)
  231816. : ComponentMovementWatcher (&owner_),
  231817. owner (owner_),
  231818. currentPeer (0),
  231819. view (view_)
  231820. {
  231821. [view_ retain];
  231822. if (owner.isShowing())
  231823. componentPeerChanged();
  231824. }
  231825. ~NSViewComponentInternal()
  231826. {
  231827. [view removeFromSuperview];
  231828. [view release];
  231829. }
  231830. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  231831. {
  231832. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  231833. // The ComponentMovementWatcher version of this method avoids calling
  231834. // us when the top-level comp is resized, but for an NSView we need to know this
  231835. // because with inverted co-ords, we need to update the position even if the
  231836. // top-left pos hasn't changed
  231837. if (comp.isOnDesktop() && wasResized)
  231838. componentMovedOrResized (wasMoved, wasResized);
  231839. }
  231840. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  231841. {
  231842. Component* const topComp = owner.getTopLevelComponent();
  231843. if (topComp->getPeer() != 0)
  231844. {
  231845. const Point<int> pos (topComp->getLocalPoint (&owner, Point<int>()));
  231846. NSRect r = NSMakeRect ((float) pos.getX(), (float) pos.getY(), (float) owner.getWidth(), (float) owner.getHeight());
  231847. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231848. [view setFrame: r];
  231849. }
  231850. }
  231851. void componentPeerChanged()
  231852. {
  231853. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner.getPeer());
  231854. if (currentPeer != peer)
  231855. {
  231856. if ([view superview] != nil)
  231857. [view removeFromSuperview]; // Must be careful not to call this unless it's required - e.g. some Apple AU views
  231858. // override the call and use it as a sign that they're being deleted, which breaks everything..
  231859. currentPeer = peer;
  231860. if (peer != 0)
  231861. {
  231862. [peer->view addSubview: view];
  231863. componentMovedOrResized (false, false);
  231864. }
  231865. }
  231866. [view setHidden: ! owner.isShowing()];
  231867. }
  231868. void componentVisibilityChanged()
  231869. {
  231870. componentPeerChanged();
  231871. }
  231872. const Rectangle<int> getViewBounds() const
  231873. {
  231874. NSRect r = [view frame];
  231875. return Rectangle<int> (0, 0, (int) r.size.width, (int) r.size.height);
  231876. }
  231877. private:
  231878. Component& owner;
  231879. NSViewComponentPeer* currentPeer;
  231880. public:
  231881. NSView* const view;
  231882. private:
  231883. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentInternal);
  231884. };
  231885. NSViewComponent::NSViewComponent()
  231886. {
  231887. }
  231888. NSViewComponent::~NSViewComponent()
  231889. {
  231890. }
  231891. void NSViewComponent::setView (void* view)
  231892. {
  231893. if (view != getView())
  231894. {
  231895. if (view != 0)
  231896. info = new NSViewComponentInternal ((NSView*) view, *this);
  231897. else
  231898. info = 0;
  231899. }
  231900. }
  231901. void* NSViewComponent::getView() const
  231902. {
  231903. return info == 0 ? 0 : info->view;
  231904. }
  231905. void NSViewComponent::resizeToFitView()
  231906. {
  231907. if (info != 0)
  231908. setBounds (info->getViewBounds());
  231909. }
  231910. void NSViewComponent::paint (Graphics&)
  231911. {
  231912. }
  231913. #endif
  231914. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  231915. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  231916. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231917. // compiled on its own).
  231918. #if JUCE_INCLUDED_FILE
  231919. AppleRemoteDevice::AppleRemoteDevice()
  231920. : device (0),
  231921. queue (0),
  231922. remoteId (0)
  231923. {
  231924. }
  231925. AppleRemoteDevice::~AppleRemoteDevice()
  231926. {
  231927. stop();
  231928. }
  231929. namespace
  231930. {
  231931. io_object_t getAppleRemoteDevice()
  231932. {
  231933. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  231934. io_iterator_t iter = 0;
  231935. io_object_t iod = 0;
  231936. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  231937. && iter != 0)
  231938. {
  231939. iod = IOIteratorNext (iter);
  231940. }
  231941. IOObjectRelease (iter);
  231942. return iod;
  231943. }
  231944. bool createAppleRemoteInterface (io_object_t iod, void** device)
  231945. {
  231946. jassert (*device == 0);
  231947. io_name_t classname;
  231948. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  231949. {
  231950. IOCFPlugInInterface** cfPlugInInterface = 0;
  231951. SInt32 score = 0;
  231952. if (IOCreatePlugInInterfaceForService (iod,
  231953. kIOHIDDeviceUserClientTypeID,
  231954. kIOCFPlugInInterfaceID,
  231955. &cfPlugInInterface,
  231956. &score) == kIOReturnSuccess)
  231957. {
  231958. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  231959. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  231960. device);
  231961. (void) hr;
  231962. (*cfPlugInInterface)->Release (cfPlugInInterface);
  231963. }
  231964. }
  231965. return *device != 0;
  231966. }
  231967. void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  231968. {
  231969. if (result == kIOReturnSuccess)
  231970. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  231971. }
  231972. }
  231973. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  231974. {
  231975. if (queue != 0)
  231976. return true;
  231977. stop();
  231978. bool result = false;
  231979. io_object_t iod = getAppleRemoteDevice();
  231980. if (iod != 0)
  231981. {
  231982. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  231983. result = true;
  231984. else
  231985. stop();
  231986. IOObjectRelease (iod);
  231987. }
  231988. return result;
  231989. }
  231990. void AppleRemoteDevice::stop()
  231991. {
  231992. if (queue != 0)
  231993. {
  231994. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  231995. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  231996. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  231997. queue = 0;
  231998. }
  231999. if (device != 0)
  232000. {
  232001. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  232002. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  232003. device = 0;
  232004. }
  232005. }
  232006. bool AppleRemoteDevice::isActive() const
  232007. {
  232008. return queue != 0;
  232009. }
  232010. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  232011. {
  232012. Array <int> cookies;
  232013. CFArrayRef elements;
  232014. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  232015. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  232016. return false;
  232017. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  232018. {
  232019. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  232020. // get the cookie
  232021. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  232022. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  232023. continue;
  232024. long number;
  232025. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  232026. continue;
  232027. cookies.add ((int) number);
  232028. }
  232029. CFRelease (elements);
  232030. if ((*(IOHIDDeviceInterface**) device)
  232031. ->open ((IOHIDDeviceInterface**) device,
  232032. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  232033. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  232034. {
  232035. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  232036. if (queue != 0)
  232037. {
  232038. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  232039. for (int i = 0; i < cookies.size(); ++i)
  232040. {
  232041. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  232042. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  232043. }
  232044. CFRunLoopSourceRef eventSource;
  232045. if ((*(IOHIDQueueInterface**) queue)
  232046. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  232047. {
  232048. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  232049. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  232050. {
  232051. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  232052. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  232053. return true;
  232054. }
  232055. }
  232056. }
  232057. }
  232058. return false;
  232059. }
  232060. void AppleRemoteDevice::handleCallbackInternal()
  232061. {
  232062. int totalValues = 0;
  232063. AbsoluteTime nullTime = { 0, 0 };
  232064. char cookies [12];
  232065. int numCookies = 0;
  232066. while (numCookies < numElementsInArray (cookies))
  232067. {
  232068. IOHIDEventStruct e;
  232069. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  232070. break;
  232071. if ((int) e.elementCookie == 19)
  232072. {
  232073. remoteId = e.value;
  232074. buttonPressed (switched, false);
  232075. }
  232076. else
  232077. {
  232078. totalValues += e.value;
  232079. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  232080. }
  232081. }
  232082. cookies [numCookies++] = 0;
  232083. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  232084. static const char buttonPatterns[] =
  232085. {
  232086. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  232087. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  232088. 0x1f, 0x1d, 0x1c, 0x12, 0,
  232089. 0x1f, 0x1e, 0x1c, 0x12, 0,
  232090. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  232091. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  232092. 0x1f, 0x12, 0x04, 0x02, 0,
  232093. 0x1f, 0x12, 0x03, 0x02, 0,
  232094. 0x1f, 0x12, 0x1f, 0x12, 0,
  232095. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  232096. 19, 0
  232097. };
  232098. int buttonNum = (int) menuButton;
  232099. int i = 0;
  232100. while (i < numElementsInArray (buttonPatterns))
  232101. {
  232102. if (strcmp (cookies, buttonPatterns + i) == 0)
  232103. {
  232104. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  232105. break;
  232106. }
  232107. i += (int) strlen (buttonPatterns + i) + 1;
  232108. ++buttonNum;
  232109. }
  232110. }
  232111. #endif
  232112. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  232113. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  232114. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232115. // compiled on its own).
  232116. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  232117. #if JUCE_MAC
  232118. END_JUCE_NAMESPACE
  232119. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  232120. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  232121. {
  232122. CriticalSection* contextLock;
  232123. bool needsUpdate;
  232124. }
  232125. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  232126. - (bool) makeActive;
  232127. - (void) makeInactive;
  232128. - (void) reshape;
  232129. - (void) rightMouseDown: (NSEvent*) ev;
  232130. - (void) rightMouseUp: (NSEvent*) ev;
  232131. @end
  232132. @implementation ThreadSafeNSOpenGLView
  232133. - (id) initWithFrame: (NSRect) frameRect
  232134. pixelFormat: (NSOpenGLPixelFormat*) format
  232135. {
  232136. contextLock = new CriticalSection();
  232137. self = [super initWithFrame: frameRect pixelFormat: format];
  232138. if (self != nil)
  232139. [[NSNotificationCenter defaultCenter] addObserver: self
  232140. selector: @selector (_surfaceNeedsUpdate:)
  232141. name: NSViewGlobalFrameDidChangeNotification
  232142. object: self];
  232143. return self;
  232144. }
  232145. - (void) dealloc
  232146. {
  232147. [[NSNotificationCenter defaultCenter] removeObserver: self];
  232148. delete contextLock;
  232149. [super dealloc];
  232150. }
  232151. - (bool) makeActive
  232152. {
  232153. const ScopedLock sl (*contextLock);
  232154. if ([self openGLContext] == 0)
  232155. return false;
  232156. [[self openGLContext] makeCurrentContext];
  232157. if (needsUpdate)
  232158. {
  232159. [super update];
  232160. needsUpdate = false;
  232161. }
  232162. return true;
  232163. }
  232164. - (void) makeInactive
  232165. {
  232166. const ScopedLock sl (*contextLock);
  232167. [NSOpenGLContext clearCurrentContext];
  232168. }
  232169. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  232170. {
  232171. (void) notification;
  232172. const ScopedLock sl (*contextLock);
  232173. needsUpdate = true;
  232174. }
  232175. - (void) update
  232176. {
  232177. const ScopedLock sl (*contextLock);
  232178. needsUpdate = true;
  232179. }
  232180. - (void) reshape
  232181. {
  232182. const ScopedLock sl (*contextLock);
  232183. needsUpdate = true;
  232184. }
  232185. - (void) rightMouseDown: (NSEvent*) ev
  232186. {
  232187. [[self superview] rightMouseDown: ev];
  232188. }
  232189. - (void) rightMouseUp: (NSEvent*) ev
  232190. {
  232191. [[self superview] rightMouseUp: ev];
  232192. }
  232193. @end
  232194. BEGIN_JUCE_NAMESPACE
  232195. class WindowedGLContext : public OpenGLContext
  232196. {
  232197. public:
  232198. WindowedGLContext (Component& component,
  232199. const OpenGLPixelFormat& pixelFormat_,
  232200. NSOpenGLContext* sharedContext)
  232201. : renderContext (0),
  232202. pixelFormat (pixelFormat_)
  232203. {
  232204. NSOpenGLPixelFormatAttribute attribs [64];
  232205. int n = 0;
  232206. attribs[n++] = NSOpenGLPFADoubleBuffer;
  232207. attribs[n++] = NSOpenGLPFAAccelerated;
  232208. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  232209. attribs[n++] = NSOpenGLPFAColorSize;
  232210. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  232211. pixelFormat.greenBits,
  232212. pixelFormat.blueBits);
  232213. attribs[n++] = NSOpenGLPFAAlphaSize;
  232214. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  232215. attribs[n++] = NSOpenGLPFADepthSize;
  232216. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  232217. attribs[n++] = NSOpenGLPFAStencilSize;
  232218. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  232219. attribs[n++] = NSOpenGLPFAAccumSize;
  232220. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  232221. pixelFormat.accumulationBufferGreenBits,
  232222. pixelFormat.accumulationBufferBlueBits,
  232223. pixelFormat.accumulationBufferAlphaBits);
  232224. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  232225. attribs[n++] = NSOpenGLPFASampleBuffers;
  232226. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  232227. attribs[n++] = NSOpenGLPFAClosestPolicy;
  232228. attribs[n++] = NSOpenGLPFANoRecovery;
  232229. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  232230. NSOpenGLPixelFormat* format
  232231. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  232232. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  232233. pixelFormat: format];
  232234. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  232235. shareContext: sharedContext] autorelease];
  232236. const GLint swapInterval = 1;
  232237. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  232238. [view setOpenGLContext: renderContext];
  232239. [format release];
  232240. viewHolder = new NSViewComponentInternal (view, component);
  232241. }
  232242. ~WindowedGLContext()
  232243. {
  232244. deleteContext();
  232245. viewHolder = 0;
  232246. }
  232247. void deleteContext()
  232248. {
  232249. makeInactive();
  232250. [renderContext clearDrawable];
  232251. [renderContext setView: nil];
  232252. [view setOpenGLContext: nil];
  232253. renderContext = nil;
  232254. }
  232255. bool makeActive() const throw()
  232256. {
  232257. jassert (renderContext != 0);
  232258. if ([renderContext view] != view)
  232259. [renderContext setView: view];
  232260. [view makeActive];
  232261. return isActive();
  232262. }
  232263. bool makeInactive() const throw()
  232264. {
  232265. [view makeInactive];
  232266. return true;
  232267. }
  232268. bool isActive() const throw()
  232269. {
  232270. return [NSOpenGLContext currentContext] == renderContext;
  232271. }
  232272. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232273. void* getRawContext() const throw() { return renderContext; }
  232274. void updateWindowPosition (int /*x*/, int /*y*/, int /*w*/, int /*h*/, int /*outerWindowHeight*/)
  232275. {
  232276. }
  232277. void swapBuffers()
  232278. {
  232279. [renderContext flushBuffer];
  232280. }
  232281. bool setSwapInterval (const int numFramesPerSwap)
  232282. {
  232283. [renderContext setValues: (const GLint*) &numFramesPerSwap
  232284. forParameter: NSOpenGLCPSwapInterval];
  232285. return true;
  232286. }
  232287. int getSwapInterval() const
  232288. {
  232289. GLint numFrames = 0;
  232290. [renderContext getValues: &numFrames
  232291. forParameter: NSOpenGLCPSwapInterval];
  232292. return numFrames;
  232293. }
  232294. void repaint()
  232295. {
  232296. // we need to invalidate the juce view that holds this gl view, to make it
  232297. // cause a repaint callback
  232298. NSView* v = (NSView*) viewHolder->view;
  232299. NSRect r = [v frame];
  232300. // bit of a bodge here.. if we only invalidate the area of the gl component,
  232301. // it's completely covered by the NSOpenGLView, so the OS throws away the
  232302. // repaint message, thus never causing our paint() callback, and never repainting
  232303. // the comp. So invalidating just a little bit around the edge helps..
  232304. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  232305. }
  232306. void* getNativeWindowHandle() const { return viewHolder->view; }
  232307. NSOpenGLContext* renderContext;
  232308. ThreadSafeNSOpenGLView* view;
  232309. private:
  232310. OpenGLPixelFormat pixelFormat;
  232311. ScopedPointer <NSViewComponentInternal> viewHolder;
  232312. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  232313. };
  232314. OpenGLContext* OpenGLComponent::createContext()
  232315. {
  232316. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (*this, preferredPixelFormat,
  232317. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  232318. return (c->renderContext != 0) ? c.release() : 0;
  232319. }
  232320. void* OpenGLComponent::getNativeWindowHandle() const
  232321. {
  232322. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  232323. : 0;
  232324. }
  232325. void juce_glViewport (const int w, const int h)
  232326. {
  232327. glViewport (0, 0, w, h);
  232328. }
  232329. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232330. OwnedArray <OpenGLPixelFormat>& /*results*/)
  232331. {
  232332. /* GLint attribs [64];
  232333. int n = 0;
  232334. attribs[n++] = AGL_RGBA;
  232335. attribs[n++] = AGL_DOUBLEBUFFER;
  232336. attribs[n++] = AGL_ACCELERATED;
  232337. attribs[n++] = AGL_NO_RECOVERY;
  232338. attribs[n++] = AGL_NONE;
  232339. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  232340. while (p != 0)
  232341. {
  232342. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  232343. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  232344. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  232345. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  232346. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  232347. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  232348. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  232349. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  232350. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  232351. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  232352. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  232353. results.add (pf);
  232354. p = aglNextPixelFormat (p);
  232355. }*/
  232356. //jassertfalse // can't see how you do this in cocoa!
  232357. }
  232358. #else
  232359. END_JUCE_NAMESPACE
  232360. @interface JuceGLView : UIView
  232361. {
  232362. }
  232363. + (Class) layerClass;
  232364. @end
  232365. @implementation JuceGLView
  232366. + (Class) layerClass
  232367. {
  232368. return [CAEAGLLayer class];
  232369. }
  232370. @end
  232371. BEGIN_JUCE_NAMESPACE
  232372. class GLESContext : public OpenGLContext
  232373. {
  232374. public:
  232375. GLESContext (UIViewComponentPeer* peer,
  232376. Component* const component_,
  232377. const OpenGLPixelFormat& pixelFormat_,
  232378. const GLESContext* const sharedContext,
  232379. NSUInteger apiType)
  232380. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  232381. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  232382. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  232383. {
  232384. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  232385. view.opaque = YES;
  232386. view.hidden = NO;
  232387. view.backgroundColor = [UIColor blackColor];
  232388. view.userInteractionEnabled = NO;
  232389. glLayer = (CAEAGLLayer*) [view layer];
  232390. [peer->view addSubview: view];
  232391. if (sharedContext != 0)
  232392. context = [[EAGLContext alloc] initWithAPI: apiType
  232393. sharegroup: [sharedContext->context sharegroup]];
  232394. else
  232395. context = [[EAGLContext alloc] initWithAPI: apiType];
  232396. createGLBuffers();
  232397. }
  232398. ~GLESContext()
  232399. {
  232400. deleteContext();
  232401. [view removeFromSuperview];
  232402. [view release];
  232403. freeGLBuffers();
  232404. }
  232405. void deleteContext()
  232406. {
  232407. makeInactive();
  232408. [context release];
  232409. context = nil;
  232410. }
  232411. bool makeActive() const throw()
  232412. {
  232413. jassert (context != 0);
  232414. [EAGLContext setCurrentContext: context];
  232415. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  232416. return true;
  232417. }
  232418. void swapBuffers()
  232419. {
  232420. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232421. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  232422. }
  232423. bool makeInactive() const throw()
  232424. {
  232425. return [EAGLContext setCurrentContext: nil];
  232426. }
  232427. bool isActive() const throw()
  232428. {
  232429. return [EAGLContext currentContext] == context;
  232430. }
  232431. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232432. void* getRawContext() const throw() { return glLayer; }
  232433. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  232434. {
  232435. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  232436. if (lastWidth != w || lastHeight != h)
  232437. {
  232438. lastWidth = w;
  232439. lastHeight = h;
  232440. freeGLBuffers();
  232441. createGLBuffers();
  232442. }
  232443. }
  232444. bool setSwapInterval (const int numFramesPerSwap)
  232445. {
  232446. numFrames = numFramesPerSwap;
  232447. return true;
  232448. }
  232449. int getSwapInterval() const
  232450. {
  232451. return numFrames;
  232452. }
  232453. void repaint()
  232454. {
  232455. }
  232456. void createGLBuffers()
  232457. {
  232458. makeActive();
  232459. glGenFramebuffersOES (1, &frameBufferHandle);
  232460. glGenRenderbuffersOES (1, &colorBufferHandle);
  232461. glGenRenderbuffersOES (1, &depthBufferHandle);
  232462. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232463. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  232464. GLint width, height;
  232465. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  232466. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  232467. if (useDepthBuffer)
  232468. {
  232469. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  232470. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  232471. }
  232472. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232473. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  232474. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  232475. if (useDepthBuffer)
  232476. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  232477. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  232478. }
  232479. void freeGLBuffers()
  232480. {
  232481. if (frameBufferHandle != 0)
  232482. {
  232483. glDeleteFramebuffersOES (1, &frameBufferHandle);
  232484. frameBufferHandle = 0;
  232485. }
  232486. if (colorBufferHandle != 0)
  232487. {
  232488. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  232489. colorBufferHandle = 0;
  232490. }
  232491. if (depthBufferHandle != 0)
  232492. {
  232493. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  232494. depthBufferHandle = 0;
  232495. }
  232496. }
  232497. private:
  232498. WeakReference<Component> component;
  232499. OpenGLPixelFormat pixelFormat;
  232500. JuceGLView* view;
  232501. CAEAGLLayer* glLayer;
  232502. EAGLContext* context;
  232503. bool useDepthBuffer;
  232504. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  232505. int numFrames;
  232506. int lastWidth, lastHeight;
  232507. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  232508. };
  232509. OpenGLContext* OpenGLComponent::createContext()
  232510. {
  232511. ScopedAutoReleasePool pool;
  232512. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  232513. if (peer != 0)
  232514. return new GLESContext (peer, this, preferredPixelFormat,
  232515. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  232516. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  232517. return 0;
  232518. }
  232519. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232520. OwnedArray <OpenGLPixelFormat>& /*results*/)
  232521. {
  232522. }
  232523. void juce_glViewport (const int w, const int h)
  232524. {
  232525. glViewport (0, 0, w, h);
  232526. }
  232527. #endif
  232528. #endif
  232529. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  232530. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  232531. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232532. // compiled on its own).
  232533. #if JUCE_INCLUDED_FILE
  232534. class JuceMainMenuHandler;
  232535. END_JUCE_NAMESPACE
  232536. using namespace JUCE_NAMESPACE;
  232537. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  232538. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  232539. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  232540. #else
  232541. @interface JuceMenuCallback : NSObject
  232542. #endif
  232543. {
  232544. JuceMainMenuHandler* owner;
  232545. }
  232546. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  232547. - (void) dealloc;
  232548. - (void) menuItemInvoked: (id) menu;
  232549. - (void) menuNeedsUpdate: (NSMenu*) menu;
  232550. @end
  232551. BEGIN_JUCE_NAMESPACE
  232552. class JuceMainMenuHandler : private MenuBarModel::Listener,
  232553. private DeletedAtShutdown
  232554. {
  232555. public:
  232556. JuceMainMenuHandler()
  232557. : currentModel (0),
  232558. lastUpdateTime (0)
  232559. {
  232560. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  232561. }
  232562. ~JuceMainMenuHandler()
  232563. {
  232564. setMenu (0);
  232565. jassert (instance == this);
  232566. instance = 0;
  232567. [callback release];
  232568. }
  232569. void setMenu (MenuBarModel* const newMenuBarModel)
  232570. {
  232571. if (currentModel != newMenuBarModel)
  232572. {
  232573. if (currentModel != 0)
  232574. currentModel->removeListener (this);
  232575. currentModel = newMenuBarModel;
  232576. if (currentModel != 0)
  232577. currentModel->addListener (this);
  232578. menuBarItemsChanged (0);
  232579. }
  232580. }
  232581. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  232582. const String& name, const int menuId, const int tag)
  232583. {
  232584. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  232585. action: nil
  232586. keyEquivalent: @""];
  232587. [item setTag: tag];
  232588. NSMenu* sub = createMenu (child, name, menuId, tag);
  232589. [parent setSubmenu: sub forItem: item];
  232590. [sub setAutoenablesItems: false];
  232591. [sub release];
  232592. }
  232593. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  232594. const String& name, const int menuId, const int tag)
  232595. {
  232596. [parentItem setTag: tag];
  232597. NSMenu* menu = [parentItem submenu];
  232598. [menu setTitle: juceStringToNS (name)];
  232599. while ([menu numberOfItems] > 0)
  232600. [menu removeItemAtIndex: 0];
  232601. PopupMenu::MenuItemIterator iter (menuToCopy);
  232602. while (iter.next())
  232603. addMenuItem (iter, menu, menuId, tag);
  232604. [menu setAutoenablesItems: false];
  232605. [menu update];
  232606. }
  232607. void menuBarItemsChanged (MenuBarModel*)
  232608. {
  232609. lastUpdateTime = Time::getMillisecondCounter();
  232610. StringArray menuNames;
  232611. if (currentModel != 0)
  232612. menuNames = currentModel->getMenuBarNames();
  232613. NSMenu* menuBar = [NSApp mainMenu];
  232614. while ([menuBar numberOfItems] > 1 + menuNames.size())
  232615. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  232616. int menuId = 1;
  232617. for (int i = 0; i < menuNames.size(); ++i)
  232618. {
  232619. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  232620. if (i >= [menuBar numberOfItems] - 1)
  232621. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  232622. else
  232623. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  232624. }
  232625. }
  232626. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  232627. {
  232628. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  232629. if (item != 0)
  232630. flashMenuBar ([item menu]);
  232631. }
  232632. void updateMenus (NSMenu* menu)
  232633. {
  232634. if (PopupMenu::dismissAllActiveMenus())
  232635. {
  232636. // If we were running a juce menu, then we should let that modal loop finish before allowing
  232637. // the OS menus to start their own modal loop - so cancel the menu that was being opened..
  232638. if ([menu respondsToSelector: @selector (cancelTracking)])
  232639. [menu performSelector: @selector (cancelTracking)];
  232640. }
  232641. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  232642. menuBarItemsChanged (0);
  232643. }
  232644. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  232645. {
  232646. if (currentModel != 0)
  232647. {
  232648. if (commandManager != 0)
  232649. {
  232650. ApplicationCommandTarget::InvocationInfo info (commandId);
  232651. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  232652. commandManager->invoke (info, true);
  232653. }
  232654. currentModel->menuItemSelected (commandId, topLevelIndex);
  232655. }
  232656. }
  232657. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  232658. const int topLevelMenuId, const int topLevelIndex)
  232659. {
  232660. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  232661. if (text == 0)
  232662. text = @"";
  232663. if (iter.isSeparator)
  232664. {
  232665. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  232666. }
  232667. else if (iter.isSectionHeader)
  232668. {
  232669. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  232670. action: nil
  232671. keyEquivalent: @""];
  232672. [item setEnabled: false];
  232673. }
  232674. else if (iter.subMenu != 0)
  232675. {
  232676. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  232677. action: nil
  232678. keyEquivalent: @""];
  232679. [item setTag: iter.itemId];
  232680. [item setEnabled: iter.isEnabled];
  232681. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  232682. [sub setDelegate: nil];
  232683. [menuToAddTo setSubmenu: sub forItem: item];
  232684. [sub release];
  232685. }
  232686. else
  232687. {
  232688. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  232689. action: @selector (menuItemInvoked:)
  232690. keyEquivalent: @""];
  232691. [item setTag: iter.itemId];
  232692. [item setEnabled: iter.isEnabled];
  232693. [item setState: iter.isTicked ? NSOnState : NSOffState];
  232694. [item setTarget: (id) callback];
  232695. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  232696. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  232697. [item setRepresentedObject: info];
  232698. if (iter.commandManager != 0)
  232699. {
  232700. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  232701. ->getKeyPressesAssignedToCommand (iter.itemId));
  232702. if (keyPresses.size() > 0)
  232703. {
  232704. const KeyPress& kp = keyPresses.getReference(0);
  232705. if (kp.getKeyCode() != KeyPress::backspaceKey
  232706. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  232707. // every time you press the key while editing text)
  232708. {
  232709. juce_wchar key = kp.getTextCharacter();
  232710. if (kp.getKeyCode() == KeyPress::backspaceKey)
  232711. key = NSBackspaceCharacter;
  232712. else if (kp.getKeyCode() == KeyPress::deleteKey)
  232713. key = NSDeleteCharacter;
  232714. else if (key == 0)
  232715. key = (juce_wchar) kp.getKeyCode();
  232716. unsigned int mods = 0;
  232717. if (kp.getModifiers().isShiftDown())
  232718. mods |= NSShiftKeyMask;
  232719. if (kp.getModifiers().isCtrlDown())
  232720. mods |= NSControlKeyMask;
  232721. if (kp.getModifiers().isAltDown())
  232722. mods |= NSAlternateKeyMask;
  232723. if (kp.getModifiers().isCommandDown())
  232724. mods |= NSCommandKeyMask;
  232725. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  232726. [item setKeyEquivalentModifierMask: mods];
  232727. }
  232728. }
  232729. }
  232730. }
  232731. }
  232732. static JuceMainMenuHandler* instance;
  232733. MenuBarModel* currentModel;
  232734. uint32 lastUpdateTime;
  232735. JuceMenuCallback* callback;
  232736. private:
  232737. NSMenu* createMenu (const PopupMenu menu,
  232738. const String& menuName,
  232739. const int topLevelMenuId,
  232740. const int topLevelIndex)
  232741. {
  232742. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  232743. [m setAutoenablesItems: false];
  232744. [m setDelegate: callback];
  232745. PopupMenu::MenuItemIterator iter (menu);
  232746. while (iter.next())
  232747. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  232748. [m update];
  232749. return m;
  232750. }
  232751. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  232752. {
  232753. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  232754. {
  232755. NSMenuItem* m = [menu itemAtIndex: i];
  232756. if ([m tag] == info.commandID)
  232757. return m;
  232758. if ([m submenu] != 0)
  232759. {
  232760. NSMenuItem* found = findMenuItem ([m submenu], info);
  232761. if (found != 0)
  232762. return found;
  232763. }
  232764. }
  232765. return 0;
  232766. }
  232767. static void flashMenuBar (NSMenu* menu)
  232768. {
  232769. if ([[menu title] isEqualToString: @"Apple"])
  232770. return;
  232771. [menu retain];
  232772. const unichar f35Key = NSF35FunctionKey;
  232773. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  232774. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  232775. action: nil
  232776. keyEquivalent: f35String];
  232777. [item setTarget: nil];
  232778. [menu insertItem: item atIndex: [menu numberOfItems]];
  232779. [item release];
  232780. if ([menu indexOfItem: item] >= 0)
  232781. {
  232782. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  232783. location: NSZeroPoint
  232784. modifierFlags: NSCommandKeyMask
  232785. timestamp: 0
  232786. windowNumber: 0
  232787. context: [NSGraphicsContext currentContext]
  232788. characters: f35String
  232789. charactersIgnoringModifiers: f35String
  232790. isARepeat: NO
  232791. keyCode: 0];
  232792. [menu performKeyEquivalent: f35Event];
  232793. if ([menu indexOfItem: item] >= 0)
  232794. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  232795. }
  232796. [menu release];
  232797. }
  232798. };
  232799. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  232800. END_JUCE_NAMESPACE
  232801. @implementation JuceMenuCallback
  232802. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  232803. {
  232804. [super init];
  232805. owner = owner_;
  232806. return self;
  232807. }
  232808. - (void) dealloc
  232809. {
  232810. [super dealloc];
  232811. }
  232812. - (void) menuItemInvoked: (id) menu
  232813. {
  232814. NSMenuItem* item = (NSMenuItem*) menu;
  232815. if ([[item representedObject] isKindOfClass: [NSArray class]])
  232816. {
  232817. // 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
  232818. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  232819. // into the focused component and let it trigger the menu item indirectly.
  232820. NSEvent* e = [NSApp currentEvent];
  232821. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  232822. {
  232823. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  232824. {
  232825. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  232826. if (peer != 0)
  232827. {
  232828. if ([e type] == NSKeyDown)
  232829. peer->redirectKeyDown (e);
  232830. else
  232831. peer->redirectKeyUp (e);
  232832. return;
  232833. }
  232834. }
  232835. }
  232836. NSArray* info = (NSArray*) [item representedObject];
  232837. owner->invoke ((int) [item tag],
  232838. (ApplicationCommandManager*) (pointer_sized_int)
  232839. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  232840. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  232841. }
  232842. }
  232843. - (void) menuNeedsUpdate: (NSMenu*) menu;
  232844. {
  232845. if (JuceMainMenuHandler::instance != 0)
  232846. JuceMainMenuHandler::instance->updateMenus (menu);
  232847. }
  232848. @end
  232849. BEGIN_JUCE_NAMESPACE
  232850. namespace MainMenuHelpers
  232851. {
  232852. NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
  232853. {
  232854. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  232855. {
  232856. PopupMenu::MenuItemIterator iter (*extraItems);
  232857. while (iter.next())
  232858. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  232859. [menu addItem: [NSMenuItem separatorItem]];
  232860. }
  232861. NSMenuItem* item;
  232862. // Services...
  232863. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  232864. action: nil keyEquivalent: @""];
  232865. [menu addItem: item];
  232866. [item release];
  232867. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  232868. [menu setSubmenu: servicesMenu forItem: item];
  232869. [NSApp setServicesMenu: servicesMenu];
  232870. [servicesMenu release];
  232871. [menu addItem: [NSMenuItem separatorItem]];
  232872. // Hide + Show stuff...
  232873. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  232874. action: @selector (hide:) keyEquivalent: @"h"];
  232875. [item setTarget: NSApp];
  232876. [menu addItem: item];
  232877. [item release];
  232878. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  232879. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  232880. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  232881. [item setTarget: NSApp];
  232882. [menu addItem: item];
  232883. [item release];
  232884. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  232885. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  232886. [item setTarget: NSApp];
  232887. [menu addItem: item];
  232888. [item release];
  232889. [menu addItem: [NSMenuItem separatorItem]];
  232890. // Quit item....
  232891. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  232892. action: @selector (terminate:) keyEquivalent: @"q"];
  232893. [item setTarget: NSApp];
  232894. [menu addItem: item];
  232895. [item release];
  232896. return menu;
  232897. }
  232898. // Since our app has no NIB, this initialises a standard app menu...
  232899. void rebuildMainMenu (const PopupMenu* extraItems)
  232900. {
  232901. // this can't be used in a plugin!
  232902. jassert (JUCEApplication::isStandaloneApp());
  232903. if (JUCEApplication::getInstance() != 0)
  232904. {
  232905. const ScopedAutoReleasePool pool;
  232906. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  232907. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  232908. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  232909. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  232910. [mainMenu setSubmenu: appMenu forItem: item];
  232911. [NSApp setMainMenu: mainMenu];
  232912. MainMenuHelpers::createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  232913. [appMenu release];
  232914. [mainMenu release];
  232915. }
  232916. }
  232917. }
  232918. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  232919. const PopupMenu* extraAppleMenuItems)
  232920. {
  232921. if (getMacMainMenu() != newMenuBarModel)
  232922. {
  232923. const ScopedAutoReleasePool pool;
  232924. if (newMenuBarModel == 0)
  232925. {
  232926. delete JuceMainMenuHandler::instance;
  232927. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  232928. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  232929. extraAppleMenuItems = 0;
  232930. }
  232931. else
  232932. {
  232933. if (JuceMainMenuHandler::instance == 0)
  232934. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  232935. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  232936. }
  232937. }
  232938. MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
  232939. if (newMenuBarModel != 0)
  232940. newMenuBarModel->menuItemsChanged();
  232941. }
  232942. MenuBarModel* MenuBarModel::getMacMainMenu()
  232943. {
  232944. return JuceMainMenuHandler::instance != 0
  232945. ? JuceMainMenuHandler::instance->currentModel : 0;
  232946. }
  232947. void juce_initialiseMacMainMenu()
  232948. {
  232949. if (JuceMainMenuHandler::instance == 0)
  232950. MainMenuHelpers::rebuildMainMenu (0);
  232951. }
  232952. #endif
  232953. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  232954. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  232955. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232956. // compiled on its own).
  232957. #if JUCE_INCLUDED_FILE
  232958. #if JUCE_MAC
  232959. END_JUCE_NAMESPACE
  232960. using namespace JUCE_NAMESPACE;
  232961. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  232962. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  232963. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  232964. #else
  232965. @interface JuceFileChooserDelegate : NSObject
  232966. #endif
  232967. {
  232968. StringArray* filters;
  232969. }
  232970. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  232971. - (void) dealloc;
  232972. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  232973. @end
  232974. @implementation JuceFileChooserDelegate
  232975. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  232976. {
  232977. [super init];
  232978. filters = filters_;
  232979. return self;
  232980. }
  232981. - (void) dealloc
  232982. {
  232983. delete filters;
  232984. [super dealloc];
  232985. }
  232986. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  232987. {
  232988. (void) sender;
  232989. const File f (nsStringToJuce (filename));
  232990. for (int i = filters->size(); --i >= 0;)
  232991. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  232992. return true;
  232993. return f.isDirectory();
  232994. }
  232995. @end
  232996. BEGIN_JUCE_NAMESPACE
  232997. void FileChooser::showPlatformDialog (Array<File>& results,
  232998. const String& title,
  232999. const File& currentFileOrDirectory,
  233000. const String& filter,
  233001. bool selectsDirectory,
  233002. bool selectsFiles,
  233003. bool isSaveDialogue,
  233004. bool /*warnAboutOverwritingExistingFiles*/,
  233005. bool selectMultipleFiles,
  233006. FilePreviewComponent* /*extraInfoComponent*/)
  233007. {
  233008. const ScopedAutoReleasePool pool;
  233009. StringArray* filters = new StringArray();
  233010. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  233011. filters->trim();
  233012. filters->removeEmptyStrings();
  233013. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  233014. [delegate autorelease];
  233015. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  233016. : [NSOpenPanel openPanel];
  233017. [panel setTitle: juceStringToNS (title)];
  233018. if (! isSaveDialogue)
  233019. {
  233020. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233021. [openPanel setCanChooseDirectories: selectsDirectory];
  233022. [openPanel setCanChooseFiles: selectsFiles];
  233023. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  233024. }
  233025. [panel setDelegate: delegate];
  233026. if (isSaveDialogue || selectsDirectory)
  233027. [panel setCanCreateDirectories: YES];
  233028. String directory, filename;
  233029. if (currentFileOrDirectory.isDirectory())
  233030. {
  233031. directory = currentFileOrDirectory.getFullPathName();
  233032. }
  233033. else
  233034. {
  233035. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  233036. filename = currentFileOrDirectory.getFileName();
  233037. }
  233038. if ([panel runModalForDirectory: juceStringToNS (directory)
  233039. file: juceStringToNS (filename)]
  233040. == NSOKButton)
  233041. {
  233042. if (isSaveDialogue)
  233043. {
  233044. results.add (File (nsStringToJuce ([panel filename])));
  233045. }
  233046. else
  233047. {
  233048. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233049. NSArray* urls = [openPanel filenames];
  233050. for (unsigned int i = 0; i < [urls count]; ++i)
  233051. {
  233052. NSString* f = [urls objectAtIndex: i];
  233053. results.add (File (nsStringToJuce (f)));
  233054. }
  233055. }
  233056. }
  233057. [panel setDelegate: nil];
  233058. }
  233059. #else
  233060. void FileChooser::showPlatformDialog (Array<File>& results,
  233061. const String& title,
  233062. const File& currentFileOrDirectory,
  233063. const String& filter,
  233064. bool selectsDirectory,
  233065. bool selectsFiles,
  233066. bool isSaveDialogue,
  233067. bool warnAboutOverwritingExistingFiles,
  233068. bool selectMultipleFiles,
  233069. FilePreviewComponent* extraInfoComponent)
  233070. {
  233071. const ScopedAutoReleasePool pool;
  233072. jassertfalse; //xxx to do
  233073. }
  233074. #endif
  233075. #endif
  233076. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  233077. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233078. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233079. // compiled on its own).
  233080. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  233081. END_JUCE_NAMESPACE
  233082. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  233083. @interface NonInterceptingQTMovieView : QTMovieView
  233084. {
  233085. }
  233086. - (id) initWithFrame: (NSRect) frame;
  233087. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  233088. - (NSView*) hitTest: (NSPoint) p;
  233089. @end
  233090. @implementation NonInterceptingQTMovieView
  233091. - (id) initWithFrame: (NSRect) frame
  233092. {
  233093. self = [super initWithFrame: frame];
  233094. [self setNextResponder: [self superview]];
  233095. return self;
  233096. }
  233097. - (void) dealloc
  233098. {
  233099. [super dealloc];
  233100. }
  233101. - (NSView*) hitTest: (NSPoint) point
  233102. {
  233103. return [self isControllerVisible] ? [super hitTest: point] : nil;
  233104. }
  233105. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  233106. {
  233107. return YES;
  233108. }
  233109. @end
  233110. BEGIN_JUCE_NAMESPACE
  233111. #define theMovie (static_cast <QTMovie*> (movie))
  233112. QuickTimeMovieComponent::QuickTimeMovieComponent()
  233113. : movie (0)
  233114. {
  233115. setOpaque (true);
  233116. setVisible (true);
  233117. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  233118. setView (view);
  233119. [view release];
  233120. }
  233121. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  233122. {
  233123. closeMovie();
  233124. setView (0);
  233125. }
  233126. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  233127. {
  233128. return true;
  233129. }
  233130. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  233131. {
  233132. // unfortunately, QTMovie objects can only be created on the main thread..
  233133. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233134. QTMovie* movie = 0;
  233135. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  233136. if (fin != 0)
  233137. {
  233138. movieFile = fin->getFile();
  233139. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  233140. error: nil];
  233141. }
  233142. else
  233143. {
  233144. MemoryBlock temp;
  233145. movieStream->readIntoMemoryBlock (temp);
  233146. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  233147. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  233148. {
  233149. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  233150. length: temp.getSize()]
  233151. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  233152. MIMEType: @""]
  233153. error: nil];
  233154. if (movie != 0)
  233155. break;
  233156. }
  233157. }
  233158. return movie;
  233159. }
  233160. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  233161. const bool isControllerVisible_)
  233162. {
  233163. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  233164. }
  233165. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  233166. const bool controllerVisible_)
  233167. {
  233168. closeMovie();
  233169. if (getPeer() == 0)
  233170. {
  233171. // To open a movie, this component must be visible inside a functioning window, so that
  233172. // the QT control can be assigned to the window.
  233173. jassertfalse;
  233174. return false;
  233175. }
  233176. movie = openMovieFromStream (movieStream, movieFile);
  233177. [theMovie retain];
  233178. QTMovieView* view = (QTMovieView*) getView();
  233179. [view setMovie: theMovie];
  233180. [view setControllerVisible: controllerVisible_];
  233181. setLooping (looping);
  233182. return movie != nil;
  233183. }
  233184. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  233185. const bool isControllerVisible_)
  233186. {
  233187. // unfortunately, QTMovie objects can only be created on the main thread..
  233188. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233189. closeMovie();
  233190. if (getPeer() == 0)
  233191. {
  233192. // To open a movie, this component must be visible inside a functioning window, so that
  233193. // the QT control can be assigned to the window.
  233194. jassertfalse;
  233195. return false;
  233196. }
  233197. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  233198. NSError* err;
  233199. if ([QTMovie canInitWithURL: url])
  233200. movie = [QTMovie movieWithURL: url error: &err];
  233201. [theMovie retain];
  233202. QTMovieView* view = (QTMovieView*) getView();
  233203. [view setMovie: theMovie];
  233204. [view setControllerVisible: controllerVisible];
  233205. setLooping (looping);
  233206. return movie != nil;
  233207. }
  233208. void QuickTimeMovieComponent::closeMovie()
  233209. {
  233210. stop();
  233211. QTMovieView* view = (QTMovieView*) getView();
  233212. [view setMovie: nil];
  233213. [theMovie release];
  233214. movie = 0;
  233215. movieFile = File::nonexistent;
  233216. }
  233217. bool QuickTimeMovieComponent::isMovieOpen() const
  233218. {
  233219. return movie != nil;
  233220. }
  233221. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  233222. {
  233223. return movieFile;
  233224. }
  233225. void QuickTimeMovieComponent::play()
  233226. {
  233227. [theMovie play];
  233228. }
  233229. void QuickTimeMovieComponent::stop()
  233230. {
  233231. [theMovie stop];
  233232. }
  233233. bool QuickTimeMovieComponent::isPlaying() const
  233234. {
  233235. return movie != 0 && [theMovie rate] != 0;
  233236. }
  233237. void QuickTimeMovieComponent::setPosition (const double seconds)
  233238. {
  233239. if (movie != 0)
  233240. {
  233241. QTTime t;
  233242. t.timeValue = (uint64) (100000.0 * seconds);
  233243. t.timeScale = 100000;
  233244. t.flags = 0;
  233245. [theMovie setCurrentTime: t];
  233246. }
  233247. }
  233248. double QuickTimeMovieComponent::getPosition() const
  233249. {
  233250. if (movie == 0)
  233251. return 0.0;
  233252. QTTime t = [theMovie currentTime];
  233253. return t.timeValue / (double) t.timeScale;
  233254. }
  233255. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  233256. {
  233257. [theMovie setRate: newSpeed];
  233258. }
  233259. double QuickTimeMovieComponent::getMovieDuration() const
  233260. {
  233261. if (movie == 0)
  233262. return 0.0;
  233263. QTTime t = [theMovie duration];
  233264. return t.timeValue / (double) t.timeScale;
  233265. }
  233266. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  233267. {
  233268. looping = shouldLoop;
  233269. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  233270. forKey: QTMovieLoopsAttribute];
  233271. }
  233272. bool QuickTimeMovieComponent::isLooping() const
  233273. {
  233274. return looping;
  233275. }
  233276. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  233277. {
  233278. [theMovie setVolume: newVolume];
  233279. }
  233280. float QuickTimeMovieComponent::getMovieVolume() const
  233281. {
  233282. return movie != 0 ? [theMovie volume] : 0.0f;
  233283. }
  233284. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  233285. {
  233286. width = 0;
  233287. height = 0;
  233288. if (movie != 0)
  233289. {
  233290. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  233291. width = (int) s.width;
  233292. height = (int) s.height;
  233293. }
  233294. }
  233295. void QuickTimeMovieComponent::paint (Graphics& g)
  233296. {
  233297. if (movie == 0)
  233298. g.fillAll (Colours::black);
  233299. }
  233300. bool QuickTimeMovieComponent::isControllerVisible() const
  233301. {
  233302. return controllerVisible;
  233303. }
  233304. void QuickTimeMovieComponent::goToStart()
  233305. {
  233306. setPosition (0.0);
  233307. }
  233308. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  233309. const RectanglePlacement& placement)
  233310. {
  233311. int normalWidth, normalHeight;
  233312. getMovieNormalSize (normalWidth, normalHeight);
  233313. const Rectangle<int> normalSize (0, 0, normalWidth, normalHeight);
  233314. if (! (spaceToFitWithin.isEmpty() || normalSize.isEmpty()))
  233315. setBounds (placement.appliedTo (normalSize, spaceToFitWithin));
  233316. else
  233317. setBounds (spaceToFitWithin);
  233318. }
  233319. #if ! (JUCE_MAC && JUCE_64BIT)
  233320. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  233321. {
  233322. if (movieStream == 0)
  233323. return false;
  233324. File file;
  233325. QTMovie* movie = openMovieFromStream (movieStream, file);
  233326. if (movie != nil)
  233327. result = [movie quickTimeMovie];
  233328. return movie != nil;
  233329. }
  233330. #endif
  233331. #endif
  233332. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233333. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  233334. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233335. // compiled on its own).
  233336. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  233337. const int kilobytesPerSecond1x = 176;
  233338. END_JUCE_NAMESPACE
  233339. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  233340. @interface OpenDiskDevice : NSObject
  233341. {
  233342. @public
  233343. DRDevice* device;
  233344. NSMutableArray* tracks;
  233345. bool underrunProtection;
  233346. }
  233347. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  233348. - (void) dealloc;
  233349. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  233350. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233351. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  233352. @end
  233353. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  233354. @interface AudioTrackProducer : NSObject
  233355. {
  233356. JUCE_NAMESPACE::AudioSource* source;
  233357. int readPosition, lengthInFrames;
  233358. }
  233359. - (AudioTrackProducer*) init: (int) lengthInFrames;
  233360. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  233361. - (void) dealloc;
  233362. - (void) setupTrackProperties: (DRTrack*) track;
  233363. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  233364. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  233365. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  233366. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  233367. toMedia:(NSDictionary*)mediaInfo;
  233368. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  233369. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  233370. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233371. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233372. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233373. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233374. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233375. ioFlags:(uint32_t*)flags;
  233376. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  233377. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233378. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233379. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233380. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233381. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233382. ioFlags:(uint32_t*)flags;
  233383. @end
  233384. @implementation OpenDiskDevice
  233385. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  233386. {
  233387. [super init];
  233388. device = device_;
  233389. tracks = [[NSMutableArray alloc] init];
  233390. underrunProtection = true;
  233391. return self;
  233392. }
  233393. - (void) dealloc
  233394. {
  233395. [tracks release];
  233396. [super dealloc];
  233397. }
  233398. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  233399. {
  233400. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  233401. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  233402. [p setupTrackProperties: t];
  233403. [tracks addObject: t];
  233404. [t release];
  233405. [p release];
  233406. }
  233407. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233408. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  233409. {
  233410. DRBurn* burn = [DRBurn burnForDevice: device];
  233411. if (! [device acquireExclusiveAccess])
  233412. {
  233413. *error = "Couldn't open or write to the CD device";
  233414. return;
  233415. }
  233416. [device acquireMediaReservation];
  233417. NSMutableDictionary* d = [[burn properties] mutableCopy];
  233418. [d autorelease];
  233419. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  233420. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  233421. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  233422. if (burnSpeed > 0)
  233423. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  233424. if (! underrunProtection)
  233425. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  233426. [burn setProperties: d];
  233427. [burn writeLayout: tracks];
  233428. for (;;)
  233429. {
  233430. JUCE_NAMESPACE::Thread::sleep (300);
  233431. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  233432. if (listener != 0 && listener->audioCDBurnProgress (progress))
  233433. {
  233434. [burn abort];
  233435. *error = "User cancelled the write operation";
  233436. break;
  233437. }
  233438. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  233439. {
  233440. *error = "Write operation failed";
  233441. break;
  233442. }
  233443. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  233444. {
  233445. break;
  233446. }
  233447. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  233448. objectForKey: DRErrorStatusErrorStringKey];
  233449. if ([err length] > 0)
  233450. {
  233451. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  233452. break;
  233453. }
  233454. }
  233455. [device releaseMediaReservation];
  233456. [device releaseExclusiveAccess];
  233457. }
  233458. @end
  233459. @implementation AudioTrackProducer
  233460. - (AudioTrackProducer*) init: (int) lengthInFrames_
  233461. {
  233462. lengthInFrames = lengthInFrames_;
  233463. readPosition = 0;
  233464. return self;
  233465. }
  233466. - (void) setupTrackProperties: (DRTrack*) track
  233467. {
  233468. NSMutableDictionary* p = [[track properties] mutableCopy];
  233469. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  233470. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  233471. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  233472. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  233473. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  233474. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  233475. [track setProperties: p];
  233476. [p release];
  233477. }
  233478. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  233479. {
  233480. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  233481. if (s != nil)
  233482. s->source = source_;
  233483. return s;
  233484. }
  233485. - (void) dealloc
  233486. {
  233487. if (source != 0)
  233488. {
  233489. source->releaseResources();
  233490. delete source;
  233491. }
  233492. [super dealloc];
  233493. }
  233494. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  233495. {
  233496. (void) track;
  233497. }
  233498. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  233499. {
  233500. (void) track;
  233501. return true;
  233502. }
  233503. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  233504. {
  233505. (void) track;
  233506. return lengthInFrames;
  233507. }
  233508. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  233509. toMedia: (NSDictionary*) mediaInfo
  233510. {
  233511. (void) track; (void) burn; (void) mediaInfo;
  233512. if (source != 0)
  233513. source->prepareToPlay (44100 / 75, 44100);
  233514. readPosition = 0;
  233515. return true;
  233516. }
  233517. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  233518. {
  233519. (void) track;
  233520. if (source != 0)
  233521. source->prepareToPlay (44100 / 75, 44100);
  233522. return true;
  233523. }
  233524. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  233525. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  233526. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  233527. {
  233528. (void) track; (void) address; (void) blockSize; (void) flags;
  233529. if (source != 0)
  233530. {
  233531. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  233532. if (numSamples > 0)
  233533. {
  233534. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  233535. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  233536. info.buffer = &tempBuffer;
  233537. info.startSample = 0;
  233538. info.numSamples = numSamples;
  233539. source->getNextAudioBlock (info);
  233540. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Int16,
  233541. JUCE_NAMESPACE::AudioData::LittleEndian,
  233542. JUCE_NAMESPACE::AudioData::Interleaved,
  233543. JUCE_NAMESPACE::AudioData::NonConst> CDSampleFormat;
  233544. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Float32,
  233545. JUCE_NAMESPACE::AudioData::NativeEndian,
  233546. JUCE_NAMESPACE::AudioData::NonInterleaved,
  233547. JUCE_NAMESPACE::AudioData::Const> SourceSampleFormat;
  233548. CDSampleFormat left (buffer, 2);
  233549. left.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (0)), numSamples);
  233550. CDSampleFormat right (buffer + 2, 2);
  233551. right.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (1)), numSamples);
  233552. readPosition += numSamples;
  233553. }
  233554. return numSamples * 4;
  233555. }
  233556. return 0;
  233557. }
  233558. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  233559. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  233560. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  233561. ioFlags: (uint32_t*) flags
  233562. {
  233563. (void) track; (void) address; (void) blockSize; (void) flags;
  233564. zeromem (buffer, bufferLength);
  233565. return bufferLength;
  233566. }
  233567. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  233568. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  233569. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  233570. {
  233571. (void) track; (void) buffer; (void) bufferLength; (void) address; (void) blockSize; (void) flags;
  233572. return true;
  233573. }
  233574. @end
  233575. BEGIN_JUCE_NAMESPACE
  233576. class AudioCDBurner::Pimpl : public Timer
  233577. {
  233578. public:
  233579. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  233580. : device (0), owner (owner_)
  233581. {
  233582. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  233583. if (dev != 0)
  233584. {
  233585. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  233586. lastState = getDiskState();
  233587. startTimer (1000);
  233588. }
  233589. }
  233590. ~Pimpl()
  233591. {
  233592. stopTimer();
  233593. [device release];
  233594. }
  233595. void timerCallback()
  233596. {
  233597. const DiskState state = getDiskState();
  233598. if (state != lastState)
  233599. {
  233600. lastState = state;
  233601. owner.sendChangeMessage();
  233602. }
  233603. }
  233604. DiskState getDiskState() const
  233605. {
  233606. if ([device->device isValid])
  233607. {
  233608. NSDictionary* status = [device->device status];
  233609. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  233610. if ([state isEqualTo: DRDeviceMediaStateNone])
  233611. {
  233612. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  233613. return trayOpen;
  233614. return noDisc;
  233615. }
  233616. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  233617. {
  233618. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  233619. return writableDiskPresent;
  233620. else
  233621. return readOnlyDiskPresent;
  233622. }
  233623. }
  233624. return unknown;
  233625. }
  233626. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  233627. const Array<int> getAvailableWriteSpeeds() const
  233628. {
  233629. Array<int> results;
  233630. if ([device->device isValid])
  233631. {
  233632. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  233633. for (unsigned int i = 0; i < [speeds count]; ++i)
  233634. {
  233635. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  233636. results.add (kbPerSec / kilobytesPerSecond1x);
  233637. }
  233638. }
  233639. return results;
  233640. }
  233641. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  233642. {
  233643. if ([device->device isValid])
  233644. {
  233645. device->underrunProtection = shouldBeEnabled;
  233646. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  233647. }
  233648. return false;
  233649. }
  233650. int getNumAvailableAudioBlocks() const
  233651. {
  233652. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  233653. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  233654. }
  233655. OpenDiskDevice* device;
  233656. private:
  233657. DiskState lastState;
  233658. AudioCDBurner& owner;
  233659. };
  233660. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  233661. {
  233662. pimpl = new Pimpl (*this, deviceIndex);
  233663. }
  233664. AudioCDBurner::~AudioCDBurner()
  233665. {
  233666. }
  233667. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  233668. {
  233669. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  233670. if (b->pimpl->device == 0)
  233671. b = 0;
  233672. return b.release();
  233673. }
  233674. namespace
  233675. {
  233676. NSArray* findDiskBurnerDevices()
  233677. {
  233678. NSMutableArray* results = [NSMutableArray array];
  233679. NSArray* devs = [DRDevice devices];
  233680. for (int i = 0; i < [devs count]; ++i)
  233681. {
  233682. NSDictionary* dic = [[devs objectAtIndex: i] info];
  233683. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  233684. if (name != nil)
  233685. [results addObject: name];
  233686. }
  233687. return results;
  233688. }
  233689. }
  233690. const StringArray AudioCDBurner::findAvailableDevices()
  233691. {
  233692. NSArray* names = findDiskBurnerDevices();
  233693. StringArray s;
  233694. for (unsigned int i = 0; i < [names count]; ++i)
  233695. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  233696. return s;
  233697. }
  233698. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  233699. {
  233700. return pimpl->getDiskState();
  233701. }
  233702. bool AudioCDBurner::isDiskPresent() const
  233703. {
  233704. return getDiskState() == writableDiskPresent;
  233705. }
  233706. bool AudioCDBurner::openTray()
  233707. {
  233708. return pimpl->openTray();
  233709. }
  233710. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  233711. {
  233712. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  233713. DiskState oldState = getDiskState();
  233714. DiskState newState = oldState;
  233715. while (newState == oldState && Time::currentTimeMillis() < timeout)
  233716. {
  233717. newState = getDiskState();
  233718. Thread::sleep (100);
  233719. }
  233720. return newState;
  233721. }
  233722. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  233723. {
  233724. return pimpl->getAvailableWriteSpeeds();
  233725. }
  233726. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  233727. {
  233728. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  233729. }
  233730. int AudioCDBurner::getNumAvailableAudioBlocks() const
  233731. {
  233732. return pimpl->getNumAvailableAudioBlocks();
  233733. }
  233734. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  233735. {
  233736. if ([pimpl->device->device isValid])
  233737. {
  233738. [pimpl->device addSourceTrack: source numSamples: numSamps];
  233739. return true;
  233740. }
  233741. return false;
  233742. }
  233743. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  233744. bool ejectDiscAfterwards,
  233745. bool performFakeBurnForTesting,
  233746. int writeSpeed)
  233747. {
  233748. String error ("Couldn't open or write to the CD device");
  233749. if ([pimpl->device->device isValid])
  233750. {
  233751. error = String::empty;
  233752. [pimpl->device burn: listener
  233753. errorString: &error
  233754. ejectAfterwards: ejectDiscAfterwards
  233755. isFake: performFakeBurnForTesting
  233756. speed: writeSpeed];
  233757. }
  233758. return error;
  233759. }
  233760. #endif
  233761. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  233762. void AudioCDReader::ejectDisk()
  233763. {
  233764. const ScopedAutoReleasePool p;
  233765. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  233766. }
  233767. #endif
  233768. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  233769. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  233770. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233771. // compiled on its own).
  233772. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  233773. namespace CDReaderHelpers
  233774. {
  233775. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  233776. {
  233777. forEachXmlChildElementWithTagName (xml, child, "key")
  233778. if (child->getAllSubText().trim() == key)
  233779. return child->getNextElement();
  233780. return 0;
  233781. }
  233782. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  233783. {
  233784. const XmlElement* const block = getElementForKey (xml, key);
  233785. return block != 0 ? block->getAllSubText().trim().getIntValue() : defaultValue;
  233786. }
  233787. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  233788. // Returns NULL on success, otherwise a const char* representing an error.
  233789. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  233790. {
  233791. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  233792. if (xml == 0)
  233793. return "Couldn't parse XML in file";
  233794. const XmlElement* const dict = xml->getChildByName ("dict");
  233795. if (dict == 0)
  233796. return "Couldn't get top level dictionary";
  233797. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  233798. if (sessions == 0)
  233799. return "Couldn't find sessions key";
  233800. const XmlElement* const session = sessions->getFirstChildElement();
  233801. if (session == 0)
  233802. return "Couldn't find first session";
  233803. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  233804. if (leadOut < 0)
  233805. return "Couldn't find Leadout Block";
  233806. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  233807. if (trackArray == 0)
  233808. return "Couldn't find Track Array";
  233809. forEachXmlChildElement (*trackArray, track)
  233810. {
  233811. const int trackValue = getIntValueForKey (*track, "Start Block");
  233812. if (trackValue < 0)
  233813. return "Couldn't find Start Block in the track";
  233814. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  233815. }
  233816. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  233817. return 0;
  233818. }
  233819. static void findDevices (Array<File>& cds)
  233820. {
  233821. File volumes ("/Volumes");
  233822. volumes.findChildFiles (cds, File::findDirectories, false);
  233823. for (int i = cds.size(); --i >= 0;)
  233824. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  233825. cds.remove (i);
  233826. }
  233827. struct TrackSorter
  233828. {
  233829. static int getCDTrackNumber (const File& file)
  233830. {
  233831. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  233832. }
  233833. static int compareElements (const File& first, const File& second)
  233834. {
  233835. const int firstTrack = getCDTrackNumber (first);
  233836. const int secondTrack = getCDTrackNumber (second);
  233837. jassert (firstTrack > 0 && secondTrack > 0);
  233838. return firstTrack - secondTrack;
  233839. }
  233840. };
  233841. }
  233842. const StringArray AudioCDReader::getAvailableCDNames()
  233843. {
  233844. Array<File> cds;
  233845. CDReaderHelpers::findDevices (cds);
  233846. StringArray names;
  233847. for (int i = 0; i < cds.size(); ++i)
  233848. names.add (cds.getReference(i).getFileName());
  233849. return names;
  233850. }
  233851. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  233852. {
  233853. Array<File> cds;
  233854. CDReaderHelpers::findDevices (cds);
  233855. if (cds[index].exists())
  233856. return new AudioCDReader (cds[index]);
  233857. return 0;
  233858. }
  233859. AudioCDReader::AudioCDReader (const File& volume)
  233860. : AudioFormatReader (0, "CD Audio"),
  233861. volumeDir (volume),
  233862. currentReaderTrack (-1),
  233863. reader (0)
  233864. {
  233865. sampleRate = 44100.0;
  233866. bitsPerSample = 16;
  233867. numChannels = 2;
  233868. usesFloatingPointData = false;
  233869. refreshTrackLengths();
  233870. }
  233871. AudioCDReader::~AudioCDReader()
  233872. {
  233873. }
  233874. void AudioCDReader::refreshTrackLengths()
  233875. {
  233876. tracks.clear();
  233877. trackStartSamples.clear();
  233878. lengthInSamples = 0;
  233879. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  233880. CDReaderHelpers::TrackSorter sorter;
  233881. tracks.sort (sorter);
  233882. const File toc (volumeDir.getChildFile (".TOC.plist"));
  233883. if (toc.exists())
  233884. {
  233885. XmlDocument doc (toc);
  233886. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  233887. (void) error; // could be logged..
  233888. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  233889. }
  233890. }
  233891. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  233892. int64 startSampleInFile, int numSamples)
  233893. {
  233894. while (numSamples > 0)
  233895. {
  233896. int track = -1;
  233897. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  233898. {
  233899. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  233900. {
  233901. track = i;
  233902. break;
  233903. }
  233904. }
  233905. if (track < 0)
  233906. return false;
  233907. if (track != currentReaderTrack)
  233908. {
  233909. reader = 0;
  233910. FileInputStream* const in = tracks [track].createInputStream();
  233911. if (in != 0)
  233912. {
  233913. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  233914. AiffAudioFormat format;
  233915. reader = format.createReaderFor (bin, true);
  233916. if (reader == 0)
  233917. currentReaderTrack = -1;
  233918. else
  233919. currentReaderTrack = track;
  233920. }
  233921. }
  233922. if (reader == 0)
  233923. return false;
  233924. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  233925. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  233926. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  233927. numSamples -= numAvailable;
  233928. startSampleInFile += numAvailable;
  233929. }
  233930. return true;
  233931. }
  233932. bool AudioCDReader::isCDStillPresent() const
  233933. {
  233934. return volumeDir.exists();
  233935. }
  233936. bool AudioCDReader::isTrackAudio (int trackNum) const
  233937. {
  233938. return tracks [trackNum].hasFileExtension (".aiff");
  233939. }
  233940. void AudioCDReader::enableIndexScanning (bool)
  233941. {
  233942. // any way to do this on a Mac??
  233943. }
  233944. int AudioCDReader::getLastIndex() const
  233945. {
  233946. return 0;
  233947. }
  233948. const Array <int> AudioCDReader::findIndexesInTrack (const int /*trackNumber*/)
  233949. {
  233950. return Array <int>();
  233951. }
  233952. #endif
  233953. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  233954. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  233955. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233956. // compiled on its own).
  233957. #if JUCE_INCLUDED_FILE
  233958. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  233959. for example having more than one juce plugin loaded into a host, then when a
  233960. method is called, the actual code that runs might actually be in a different module
  233961. than the one you expect... So any calls to library functions or statics that are
  233962. made inside obj-c methods will probably end up getting executed in a different DLL's
  233963. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  233964. To work around this insanity, I'm only allowing obj-c methods to make calls to
  233965. virtual methods of an object that's known to live inside the right module's space.
  233966. */
  233967. class AppDelegateRedirector
  233968. {
  233969. public:
  233970. AppDelegateRedirector()
  233971. {
  233972. }
  233973. virtual ~AppDelegateRedirector()
  233974. {
  233975. }
  233976. virtual NSApplicationTerminateReply shouldTerminate()
  233977. {
  233978. if (JUCEApplication::getInstance() != 0)
  233979. {
  233980. JUCEApplication::getInstance()->systemRequestedQuit();
  233981. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  233982. return NSTerminateCancel;
  233983. }
  233984. return NSTerminateNow;
  233985. }
  233986. virtual void willTerminate()
  233987. {
  233988. JUCEApplication::appWillTerminateByForce();
  233989. }
  233990. virtual BOOL openFile (NSString* filename)
  233991. {
  233992. if (JUCEApplication::getInstance() != 0)
  233993. {
  233994. JUCEApplication::getInstance()->anotherInstanceStarted (quotedIfContainsSpaces (filename));
  233995. return YES;
  233996. }
  233997. return NO;
  233998. }
  233999. virtual void openFiles (NSArray* filenames)
  234000. {
  234001. StringArray files;
  234002. for (unsigned int i = 0; i < [filenames count]; ++i)
  234003. files.add (quotedIfContainsSpaces ((NSString*) [filenames objectAtIndex: i]));
  234004. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  234005. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  234006. }
  234007. virtual void focusChanged()
  234008. {
  234009. juce_HandleProcessFocusChange();
  234010. }
  234011. struct CallbackMessagePayload
  234012. {
  234013. MessageCallbackFunction* function;
  234014. void* parameter;
  234015. void* volatile result;
  234016. bool volatile hasBeenExecuted;
  234017. };
  234018. virtual void performCallback (CallbackMessagePayload* pl)
  234019. {
  234020. pl->result = (*pl->function) (pl->parameter);
  234021. pl->hasBeenExecuted = true;
  234022. }
  234023. virtual void deleteSelf()
  234024. {
  234025. delete this;
  234026. }
  234027. void postMessage (Message* const m)
  234028. {
  234029. messageQueue.post (m);
  234030. }
  234031. private:
  234032. CFRunLoopRef runLoop;
  234033. CFRunLoopSourceRef runLoopSource;
  234034. MessageQueue messageQueue;
  234035. static const String quotedIfContainsSpaces (NSString* file)
  234036. {
  234037. String s (nsStringToJuce (file));
  234038. if (s.containsChar (' '))
  234039. s = s.quoted ('"');
  234040. return s;
  234041. }
  234042. };
  234043. END_JUCE_NAMESPACE
  234044. using namespace JUCE_NAMESPACE;
  234045. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  234046. @interface JuceAppDelegate : NSObject
  234047. {
  234048. @private
  234049. id oldDelegate;
  234050. @public
  234051. AppDelegateRedirector* redirector;
  234052. }
  234053. - (JuceAppDelegate*) init;
  234054. - (void) dealloc;
  234055. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  234056. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  234057. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  234058. - (void) applicationWillTerminate: (NSNotification*) aNotification;
  234059. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  234060. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  234061. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  234062. - (void) performCallback: (id) info;
  234063. - (void) dummyMethod;
  234064. @end
  234065. @implementation JuceAppDelegate
  234066. - (JuceAppDelegate*) init
  234067. {
  234068. [super init];
  234069. redirector = new AppDelegateRedirector();
  234070. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  234071. if (JUCEApplication::isStandaloneApp())
  234072. {
  234073. oldDelegate = [NSApp delegate];
  234074. [NSApp setDelegate: self];
  234075. }
  234076. else
  234077. {
  234078. oldDelegate = 0;
  234079. [center addObserver: self selector: @selector (applicationDidResignActive:)
  234080. name: NSApplicationDidResignActiveNotification object: NSApp];
  234081. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  234082. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  234083. [center addObserver: self selector: @selector (applicationWillUnhide:)
  234084. name: NSApplicationWillUnhideNotification object: NSApp];
  234085. }
  234086. return self;
  234087. }
  234088. - (void) dealloc
  234089. {
  234090. if (oldDelegate != 0)
  234091. [NSApp setDelegate: oldDelegate];
  234092. redirector->deleteSelf();
  234093. [super dealloc];
  234094. }
  234095. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  234096. {
  234097. (void) app;
  234098. return redirector->shouldTerminate();
  234099. }
  234100. - (void) applicationWillTerminate: (NSNotification*) aNotification
  234101. {
  234102. (void) aNotification;
  234103. redirector->willTerminate();
  234104. }
  234105. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  234106. {
  234107. (void) app;
  234108. return redirector->openFile (filename);
  234109. }
  234110. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  234111. {
  234112. (void) sender;
  234113. return redirector->openFiles (filenames);
  234114. }
  234115. - (void) applicationDidBecomeActive: (NSNotification*) notification
  234116. {
  234117. (void) notification;
  234118. redirector->focusChanged();
  234119. }
  234120. - (void) applicationDidResignActive: (NSNotification*) notification
  234121. {
  234122. (void) notification;
  234123. redirector->focusChanged();
  234124. }
  234125. - (void) applicationWillUnhide: (NSNotification*) notification
  234126. {
  234127. (void) notification;
  234128. redirector->focusChanged();
  234129. }
  234130. - (void) performCallback: (id) info
  234131. {
  234132. if ([info isKindOfClass: [NSData class]])
  234133. {
  234134. AppDelegateRedirector::CallbackMessagePayload* pl
  234135. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  234136. if (pl != 0)
  234137. redirector->performCallback (pl);
  234138. }
  234139. else
  234140. {
  234141. jassertfalse; // should never get here!
  234142. }
  234143. }
  234144. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  234145. @end
  234146. BEGIN_JUCE_NAMESPACE
  234147. static JuceAppDelegate* juceAppDelegate = 0;
  234148. void MessageManager::runDispatchLoop()
  234149. {
  234150. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  234151. {
  234152. const ScopedAutoReleasePool pool;
  234153. // must only be called by the message thread!
  234154. jassert (isThisTheMessageThread());
  234155. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  234156. @try
  234157. {
  234158. [NSApp run];
  234159. }
  234160. @catch (NSException* e)
  234161. {
  234162. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  234163. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  234164. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  234165. }
  234166. @finally
  234167. {
  234168. }
  234169. #else
  234170. [NSApp run];
  234171. #endif
  234172. }
  234173. }
  234174. void MessageManager::stopDispatchLoop()
  234175. {
  234176. quitMessagePosted = true;
  234177. [NSApp stop: nil];
  234178. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  234179. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  234180. }
  234181. namespace
  234182. {
  234183. bool isEventBlockedByModalComps (NSEvent* e)
  234184. {
  234185. if (Component::getNumCurrentlyModalComponents() == 0)
  234186. return false;
  234187. NSWindow* const w = [e window];
  234188. if (w == 0 || [w worksWhenModal])
  234189. return false;
  234190. bool isKey = false, isInputAttempt = false;
  234191. switch ([e type])
  234192. {
  234193. case NSKeyDown:
  234194. case NSKeyUp:
  234195. isKey = isInputAttempt = true;
  234196. break;
  234197. case NSLeftMouseDown:
  234198. case NSRightMouseDown:
  234199. case NSOtherMouseDown:
  234200. isInputAttempt = true;
  234201. break;
  234202. case NSLeftMouseDragged:
  234203. case NSRightMouseDragged:
  234204. case NSLeftMouseUp:
  234205. case NSRightMouseUp:
  234206. case NSOtherMouseUp:
  234207. case NSOtherMouseDragged:
  234208. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  234209. return false;
  234210. break;
  234211. case NSMouseMoved:
  234212. case NSMouseEntered:
  234213. case NSMouseExited:
  234214. case NSCursorUpdate:
  234215. case NSScrollWheel:
  234216. case NSTabletPoint:
  234217. case NSTabletProximity:
  234218. break;
  234219. default:
  234220. return false;
  234221. }
  234222. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  234223. {
  234224. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  234225. NSView* const compView = (NSView*) peer->getNativeHandle();
  234226. if ([compView window] == w)
  234227. {
  234228. if (isKey)
  234229. {
  234230. if (compView == [w firstResponder])
  234231. return false;
  234232. }
  234233. else
  234234. {
  234235. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  234236. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  234237. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  234238. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  234239. return false;
  234240. }
  234241. }
  234242. }
  234243. if (isInputAttempt)
  234244. {
  234245. if (! [NSApp isActive])
  234246. [NSApp activateIgnoringOtherApps: YES];
  234247. Component* const modal = Component::getCurrentlyModalComponent (0);
  234248. if (modal != 0)
  234249. modal->inputAttemptWhenModal();
  234250. }
  234251. return true;
  234252. }
  234253. }
  234254. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  234255. {
  234256. jassert (isThisTheMessageThread()); // must only be called by the message thread
  234257. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  234258. while (! quitMessagePosted)
  234259. {
  234260. const ScopedAutoReleasePool pool;
  234261. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  234262. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  234263. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  234264. inMode: NSDefaultRunLoopMode
  234265. dequeue: YES];
  234266. if (e != 0 && ! isEventBlockedByModalComps (e))
  234267. [NSApp sendEvent: e];
  234268. if (Time::getMillisecondCounter() >= endTime)
  234269. break;
  234270. }
  234271. return ! quitMessagePosted;
  234272. }
  234273. void MessageManager::doPlatformSpecificInitialisation()
  234274. {
  234275. if (juceAppDelegate == 0)
  234276. juceAppDelegate = [[JuceAppDelegate alloc] init];
  234277. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  234278. // correctly (needed prior to 10.5)
  234279. if (! [NSThread isMultiThreaded])
  234280. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  234281. toTarget: juceAppDelegate
  234282. withObject: nil];
  234283. }
  234284. void MessageManager::doPlatformSpecificShutdown()
  234285. {
  234286. if (juceAppDelegate != 0)
  234287. {
  234288. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  234289. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  234290. [juceAppDelegate release];
  234291. juceAppDelegate = 0;
  234292. }
  234293. }
  234294. bool juce_postMessageToSystemQueue (Message* message)
  234295. {
  234296. juceAppDelegate->redirector->postMessage (message);
  234297. return true;
  234298. }
  234299. void MessageManager::broadcastMessage (const String&)
  234300. {
  234301. }
  234302. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  234303. {
  234304. if (isThisTheMessageThread())
  234305. {
  234306. return (*callback) (data);
  234307. }
  234308. else
  234309. {
  234310. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  234311. // deadlock because the message manager is blocked from running, so can never
  234312. // call your function..
  234313. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  234314. const ScopedAutoReleasePool pool;
  234315. AppDelegateRedirector::CallbackMessagePayload cmp;
  234316. cmp.function = callback;
  234317. cmp.parameter = data;
  234318. cmp.result = 0;
  234319. cmp.hasBeenExecuted = false;
  234320. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  234321. withObject: [NSData dataWithBytesNoCopy: &cmp
  234322. length: sizeof (cmp)
  234323. freeWhenDone: NO]
  234324. waitUntilDone: YES];
  234325. return cmp.result;
  234326. }
  234327. }
  234328. #endif
  234329. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  234330. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234331. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234332. // compiled on its own).
  234333. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  234334. #if JUCE_MAC
  234335. END_JUCE_NAMESPACE
  234336. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  234337. @interface DownloadClickDetector : NSObject
  234338. {
  234339. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  234340. }
  234341. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  234342. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234343. request: (NSURLRequest*) request
  234344. frame: (WebFrame*) frame
  234345. decisionListener: (id<WebPolicyDecisionListener>) listener;
  234346. @end
  234347. @implementation DownloadClickDetector
  234348. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  234349. {
  234350. [super init];
  234351. ownerComponent = ownerComponent_;
  234352. return self;
  234353. }
  234354. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234355. request: (NSURLRequest*) request
  234356. frame: (WebFrame*) frame
  234357. decisionListener: (id <WebPolicyDecisionListener>) listener
  234358. {
  234359. (void) sender;
  234360. (void) request;
  234361. (void) frame;
  234362. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  234363. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  234364. [listener use];
  234365. else
  234366. [listener ignore];
  234367. }
  234368. @end
  234369. BEGIN_JUCE_NAMESPACE
  234370. class WebBrowserComponentInternal : public NSViewComponent
  234371. {
  234372. public:
  234373. WebBrowserComponentInternal (WebBrowserComponent* owner)
  234374. {
  234375. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  234376. frameName: @""
  234377. groupName: @""];
  234378. setView (webView);
  234379. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  234380. [webView setPolicyDelegate: clickListener];
  234381. }
  234382. ~WebBrowserComponentInternal()
  234383. {
  234384. [webView setPolicyDelegate: nil];
  234385. [clickListener release];
  234386. setView (0);
  234387. }
  234388. void goToURL (const String& url,
  234389. const StringArray* headers,
  234390. const MemoryBlock* postData)
  234391. {
  234392. NSMutableURLRequest* r
  234393. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  234394. cachePolicy: NSURLRequestUseProtocolCachePolicy
  234395. timeoutInterval: 30.0];
  234396. if (postData != 0 && postData->getSize() > 0)
  234397. {
  234398. [r setHTTPMethod: @"POST"];
  234399. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  234400. length: postData->getSize()]];
  234401. }
  234402. if (headers != 0)
  234403. {
  234404. for (int i = 0; i < headers->size(); ++i)
  234405. {
  234406. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  234407. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  234408. [r setValue: juceStringToNS (headerValue)
  234409. forHTTPHeaderField: juceStringToNS (headerName)];
  234410. }
  234411. }
  234412. stop();
  234413. [[webView mainFrame] loadRequest: r];
  234414. }
  234415. void goBack()
  234416. {
  234417. [webView goBack];
  234418. }
  234419. void goForward()
  234420. {
  234421. [webView goForward];
  234422. }
  234423. void stop()
  234424. {
  234425. [webView stopLoading: nil];
  234426. }
  234427. void refresh()
  234428. {
  234429. [webView reload: nil];
  234430. }
  234431. void mouseMove (const MouseEvent&)
  234432. {
  234433. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  234434. // them work is to push them via this non-public method..
  234435. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  234436. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  234437. }
  234438. private:
  234439. WebView* webView;
  234440. DownloadClickDetector* clickListener;
  234441. };
  234442. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  234443. : browser (0),
  234444. blankPageShown (false),
  234445. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  234446. {
  234447. setOpaque (true);
  234448. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  234449. }
  234450. WebBrowserComponent::~WebBrowserComponent()
  234451. {
  234452. deleteAndZero (browser);
  234453. }
  234454. void WebBrowserComponent::goToURL (const String& url,
  234455. const StringArray* headers,
  234456. const MemoryBlock* postData)
  234457. {
  234458. lastURL = url;
  234459. lastHeaders.clear();
  234460. if (headers != 0)
  234461. lastHeaders = *headers;
  234462. lastPostData.setSize (0);
  234463. if (postData != 0)
  234464. lastPostData = *postData;
  234465. blankPageShown = false;
  234466. browser->goToURL (url, headers, postData);
  234467. }
  234468. void WebBrowserComponent::stop()
  234469. {
  234470. browser->stop();
  234471. }
  234472. void WebBrowserComponent::goBack()
  234473. {
  234474. lastURL = String::empty;
  234475. blankPageShown = false;
  234476. browser->goBack();
  234477. }
  234478. void WebBrowserComponent::goForward()
  234479. {
  234480. lastURL = String::empty;
  234481. browser->goForward();
  234482. }
  234483. void WebBrowserComponent::refresh()
  234484. {
  234485. browser->refresh();
  234486. }
  234487. void WebBrowserComponent::paint (Graphics&)
  234488. {
  234489. }
  234490. void WebBrowserComponent::checkWindowAssociation()
  234491. {
  234492. if (isShowing())
  234493. {
  234494. if (blankPageShown)
  234495. goBack();
  234496. }
  234497. else
  234498. {
  234499. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  234500. {
  234501. // when the component becomes invisible, some stuff like flash
  234502. // carries on playing audio, so we need to force it onto a blank
  234503. // page to avoid this, (and send it back when it's made visible again).
  234504. blankPageShown = true;
  234505. browser->goToURL ("about:blank", 0, 0);
  234506. }
  234507. }
  234508. }
  234509. void WebBrowserComponent::reloadLastURL()
  234510. {
  234511. if (lastURL.isNotEmpty())
  234512. {
  234513. goToURL (lastURL, &lastHeaders, &lastPostData);
  234514. lastURL = String::empty;
  234515. }
  234516. }
  234517. void WebBrowserComponent::parentHierarchyChanged()
  234518. {
  234519. checkWindowAssociation();
  234520. }
  234521. void WebBrowserComponent::resized()
  234522. {
  234523. browser->setSize (getWidth(), getHeight());
  234524. }
  234525. void WebBrowserComponent::visibilityChanged()
  234526. {
  234527. checkWindowAssociation();
  234528. }
  234529. bool WebBrowserComponent::pageAboutToLoad (const String&)
  234530. {
  234531. return true;
  234532. }
  234533. #else
  234534. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  234535. {
  234536. }
  234537. WebBrowserComponent::~WebBrowserComponent()
  234538. {
  234539. }
  234540. void WebBrowserComponent::goToURL (const String& url,
  234541. const StringArray* headers,
  234542. const MemoryBlock* postData)
  234543. {
  234544. }
  234545. void WebBrowserComponent::stop()
  234546. {
  234547. }
  234548. void WebBrowserComponent::goBack()
  234549. {
  234550. }
  234551. void WebBrowserComponent::goForward()
  234552. {
  234553. }
  234554. void WebBrowserComponent::refresh()
  234555. {
  234556. }
  234557. void WebBrowserComponent::paint (Graphics& g)
  234558. {
  234559. }
  234560. void WebBrowserComponent::checkWindowAssociation()
  234561. {
  234562. }
  234563. void WebBrowserComponent::reloadLastURL()
  234564. {
  234565. }
  234566. void WebBrowserComponent::parentHierarchyChanged()
  234567. {
  234568. }
  234569. void WebBrowserComponent::resized()
  234570. {
  234571. }
  234572. void WebBrowserComponent::visibilityChanged()
  234573. {
  234574. }
  234575. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  234576. {
  234577. return true;
  234578. }
  234579. #endif
  234580. #endif
  234581. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234582. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  234583. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234584. // compiled on its own).
  234585. #if JUCE_INCLUDED_FILE
  234586. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  234587. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  234588. #endif
  234589. #undef log
  234590. #if JUCE_COREAUDIO_LOGGING_ENABLED
  234591. #define log(a) Logger::writeToLog (a)
  234592. #else
  234593. #define log(a)
  234594. #endif
  234595. #undef OK
  234596. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  234597. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  234598. {
  234599. if (err == noErr)
  234600. return true;
  234601. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  234602. jassertfalse;
  234603. return false;
  234604. }
  234605. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  234606. #else
  234607. #define OK(a) (a == noErr)
  234608. #endif
  234609. class CoreAudioInternal : public Timer
  234610. {
  234611. public:
  234612. CoreAudioInternal (AudioDeviceID id)
  234613. : inputLatency (0),
  234614. outputLatency (0),
  234615. callback (0),
  234616. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  234617. audioProcID (0),
  234618. #endif
  234619. isSlaveDevice (false),
  234620. deviceID (id),
  234621. started (false),
  234622. sampleRate (0),
  234623. bufferSize (512),
  234624. numInputChans (0),
  234625. numOutputChans (0),
  234626. callbacksAllowed (true),
  234627. numInputChannelInfos (0),
  234628. numOutputChannelInfos (0)
  234629. {
  234630. jassert (deviceID != 0);
  234631. updateDetailsFromDevice();
  234632. AudioObjectPropertyAddress pa;
  234633. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234634. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234635. pa.mElement = kAudioObjectPropertyElementWildcard;
  234636. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  234637. }
  234638. ~CoreAudioInternal()
  234639. {
  234640. AudioObjectPropertyAddress pa;
  234641. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234642. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234643. pa.mElement = kAudioObjectPropertyElementWildcard;
  234644. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  234645. stop (false);
  234646. }
  234647. void allocateTempBuffers()
  234648. {
  234649. const int tempBufSize = bufferSize + 4;
  234650. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  234651. tempInputBuffers.calloc (numInputChans + 2);
  234652. tempOutputBuffers.calloc (numOutputChans + 2);
  234653. int i, count = 0;
  234654. for (i = 0; i < numInputChans; ++i)
  234655. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  234656. for (i = 0; i < numOutputChans; ++i)
  234657. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  234658. }
  234659. // returns the number of actual available channels
  234660. void fillInChannelInfo (const bool input)
  234661. {
  234662. int chanNum = 0;
  234663. UInt32 size;
  234664. AudioObjectPropertyAddress pa;
  234665. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  234666. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234667. pa.mElement = kAudioObjectPropertyElementMaster;
  234668. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234669. {
  234670. HeapBlock <AudioBufferList> bufList;
  234671. bufList.calloc (size, 1);
  234672. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  234673. {
  234674. const int numStreams = bufList->mNumberBuffers;
  234675. for (int i = 0; i < numStreams; ++i)
  234676. {
  234677. const AudioBuffer& b = bufList->mBuffers[i];
  234678. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  234679. {
  234680. String name;
  234681. {
  234682. char channelName [256];
  234683. zerostruct (channelName);
  234684. UInt32 nameSize = sizeof (channelName);
  234685. UInt32 channelNum = chanNum + 1;
  234686. pa.mSelector = kAudioDevicePropertyChannelName;
  234687. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  234688. name = String::fromUTF8 (channelName, nameSize);
  234689. }
  234690. if (input)
  234691. {
  234692. if (activeInputChans[chanNum])
  234693. {
  234694. inputChannelInfo [numInputChannelInfos].streamNum = i;
  234695. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  234696. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  234697. ++numInputChannelInfos;
  234698. }
  234699. if (name.isEmpty())
  234700. name << "Input " << (chanNum + 1);
  234701. inChanNames.add (name);
  234702. }
  234703. else
  234704. {
  234705. if (activeOutputChans[chanNum])
  234706. {
  234707. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  234708. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  234709. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  234710. ++numOutputChannelInfos;
  234711. }
  234712. if (name.isEmpty())
  234713. name << "Output " << (chanNum + 1);
  234714. outChanNames.add (name);
  234715. }
  234716. ++chanNum;
  234717. }
  234718. }
  234719. }
  234720. }
  234721. }
  234722. void updateDetailsFromDevice()
  234723. {
  234724. stopTimer();
  234725. if (deviceID == 0)
  234726. return;
  234727. const ScopedLock sl (callbackLock);
  234728. Float64 sr;
  234729. UInt32 size = sizeof (Float64);
  234730. AudioObjectPropertyAddress pa;
  234731. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  234732. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234733. pa.mElement = kAudioObjectPropertyElementMaster;
  234734. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  234735. sampleRate = sr;
  234736. UInt32 framesPerBuf;
  234737. size = sizeof (framesPerBuf);
  234738. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  234739. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  234740. {
  234741. bufferSize = framesPerBuf;
  234742. allocateTempBuffers();
  234743. }
  234744. bufferSizes.clear();
  234745. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  234746. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234747. {
  234748. HeapBlock <AudioValueRange> ranges;
  234749. ranges.calloc (size, 1);
  234750. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  234751. {
  234752. bufferSizes.add ((int) ranges[0].mMinimum);
  234753. for (int i = 32; i < 2048; i += 32)
  234754. {
  234755. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  234756. {
  234757. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  234758. {
  234759. bufferSizes.addIfNotAlreadyThere (i);
  234760. break;
  234761. }
  234762. }
  234763. }
  234764. if (bufferSize > 0)
  234765. bufferSizes.addIfNotAlreadyThere (bufferSize);
  234766. }
  234767. }
  234768. if (bufferSizes.size() == 0 && bufferSize > 0)
  234769. bufferSizes.add (bufferSize);
  234770. sampleRates.clear();
  234771. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  234772. String rates;
  234773. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  234774. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234775. {
  234776. HeapBlock <AudioValueRange> ranges;
  234777. ranges.calloc (size, 1);
  234778. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  234779. {
  234780. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  234781. {
  234782. bool ok = false;
  234783. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  234784. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  234785. ok = true;
  234786. if (ok)
  234787. {
  234788. sampleRates.add (possibleRates[i]);
  234789. rates << possibleRates[i] << ' ';
  234790. }
  234791. }
  234792. }
  234793. }
  234794. if (sampleRates.size() == 0 && sampleRate > 0)
  234795. {
  234796. sampleRates.add (sampleRate);
  234797. rates << sampleRate;
  234798. }
  234799. log ("sr: " + rates);
  234800. inputLatency = 0;
  234801. outputLatency = 0;
  234802. UInt32 lat;
  234803. size = sizeof (lat);
  234804. pa.mSelector = kAudioDevicePropertyLatency;
  234805. pa.mScope = kAudioDevicePropertyScopeInput;
  234806. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  234807. inputLatency = (int) lat;
  234808. pa.mScope = kAudioDevicePropertyScopeOutput;
  234809. size = sizeof (lat);
  234810. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  234811. outputLatency = (int) lat;
  234812. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  234813. inChanNames.clear();
  234814. outChanNames.clear();
  234815. inputChannelInfo.calloc (numInputChans + 2);
  234816. numInputChannelInfos = 0;
  234817. outputChannelInfo.calloc (numOutputChans + 2);
  234818. numOutputChannelInfos = 0;
  234819. fillInChannelInfo (true);
  234820. fillInChannelInfo (false);
  234821. }
  234822. const StringArray getSources (bool input)
  234823. {
  234824. StringArray s;
  234825. HeapBlock <OSType> types;
  234826. const int num = getAllDataSourcesForDevice (deviceID, types);
  234827. for (int i = 0; i < num; ++i)
  234828. {
  234829. AudioValueTranslation avt;
  234830. char buffer[256];
  234831. avt.mInputData = &(types[i]);
  234832. avt.mInputDataSize = sizeof (UInt32);
  234833. avt.mOutputData = buffer;
  234834. avt.mOutputDataSize = 256;
  234835. UInt32 transSize = sizeof (avt);
  234836. AudioObjectPropertyAddress pa;
  234837. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  234838. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234839. pa.mElement = kAudioObjectPropertyElementMaster;
  234840. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  234841. {
  234842. DBG (buffer);
  234843. s.add (buffer);
  234844. }
  234845. }
  234846. return s;
  234847. }
  234848. int getCurrentSourceIndex (bool input) const
  234849. {
  234850. OSType currentSourceID = 0;
  234851. UInt32 size = sizeof (currentSourceID);
  234852. int result = -1;
  234853. AudioObjectPropertyAddress pa;
  234854. pa.mSelector = kAudioDevicePropertyDataSource;
  234855. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234856. pa.mElement = kAudioObjectPropertyElementMaster;
  234857. if (deviceID != 0)
  234858. {
  234859. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  234860. {
  234861. HeapBlock <OSType> types;
  234862. const int num = getAllDataSourcesForDevice (deviceID, types);
  234863. for (int i = 0; i < num; ++i)
  234864. {
  234865. if (types[num] == currentSourceID)
  234866. {
  234867. result = i;
  234868. break;
  234869. }
  234870. }
  234871. }
  234872. }
  234873. return result;
  234874. }
  234875. void setCurrentSourceIndex (int index, bool input)
  234876. {
  234877. if (deviceID != 0)
  234878. {
  234879. HeapBlock <OSType> types;
  234880. const int num = getAllDataSourcesForDevice (deviceID, types);
  234881. if (isPositiveAndBelow (index, num))
  234882. {
  234883. AudioObjectPropertyAddress pa;
  234884. pa.mSelector = kAudioDevicePropertyDataSource;
  234885. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234886. pa.mElement = kAudioObjectPropertyElementMaster;
  234887. OSType typeId = types[index];
  234888. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  234889. }
  234890. }
  234891. }
  234892. const String reopen (const BigInteger& inputChannels,
  234893. const BigInteger& outputChannels,
  234894. double newSampleRate,
  234895. int bufferSizeSamples)
  234896. {
  234897. String error;
  234898. log ("CoreAudio reopen");
  234899. callbacksAllowed = false;
  234900. stopTimer();
  234901. stop (false);
  234902. activeInputChans = inputChannels;
  234903. activeInputChans.setRange (inChanNames.size(),
  234904. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  234905. false);
  234906. activeOutputChans = outputChannels;
  234907. activeOutputChans.setRange (outChanNames.size(),
  234908. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  234909. false);
  234910. numInputChans = activeInputChans.countNumberOfSetBits();
  234911. numOutputChans = activeOutputChans.countNumberOfSetBits();
  234912. // set sample rate
  234913. AudioObjectPropertyAddress pa;
  234914. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  234915. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234916. pa.mElement = kAudioObjectPropertyElementMaster;
  234917. Float64 sr = newSampleRate;
  234918. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  234919. {
  234920. error = "Couldn't change sample rate";
  234921. }
  234922. else
  234923. {
  234924. // change buffer size
  234925. UInt32 framesPerBuf = bufferSizeSamples;
  234926. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  234927. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  234928. {
  234929. error = "Couldn't change buffer size";
  234930. }
  234931. else
  234932. {
  234933. // Annoyingly, after changing the rate and buffer size, some devices fail to
  234934. // correctly report their new settings until some random time in the future, so
  234935. // after calling updateDetailsFromDevice, we need to manually bodge these values
  234936. // to make sure we're using the correct numbers..
  234937. updateDetailsFromDevice();
  234938. sampleRate = newSampleRate;
  234939. bufferSize = bufferSizeSamples;
  234940. if (sampleRates.size() == 0)
  234941. error = "Device has no available sample-rates";
  234942. else if (bufferSizes.size() == 0)
  234943. error = "Device has no available buffer-sizes";
  234944. else if (inputDevice != 0)
  234945. error = inputDevice->reopen (inputChannels,
  234946. outputChannels,
  234947. newSampleRate,
  234948. bufferSizeSamples);
  234949. }
  234950. }
  234951. callbacksAllowed = true;
  234952. return error;
  234953. }
  234954. bool start (AudioIODeviceCallback* cb)
  234955. {
  234956. if (! started)
  234957. {
  234958. callback = 0;
  234959. if (deviceID != 0)
  234960. {
  234961. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234962. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  234963. #else
  234964. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  234965. #endif
  234966. {
  234967. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  234968. {
  234969. started = true;
  234970. }
  234971. else
  234972. {
  234973. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234974. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  234975. #else
  234976. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  234977. audioProcID = 0;
  234978. #endif
  234979. }
  234980. }
  234981. }
  234982. }
  234983. if (started)
  234984. {
  234985. const ScopedLock sl (callbackLock);
  234986. callback = cb;
  234987. }
  234988. if (inputDevice != 0)
  234989. return started && inputDevice->start (cb);
  234990. else
  234991. return started;
  234992. }
  234993. void stop (bool leaveInterruptRunning)
  234994. {
  234995. {
  234996. const ScopedLock sl (callbackLock);
  234997. callback = 0;
  234998. }
  234999. if (started
  235000. && (deviceID != 0)
  235001. && ! leaveInterruptRunning)
  235002. {
  235003. OK (AudioDeviceStop (deviceID, audioIOProc));
  235004. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235005. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235006. #else
  235007. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235008. audioProcID = 0;
  235009. #endif
  235010. started = false;
  235011. { const ScopedLock sl (callbackLock); }
  235012. // wait until it's definately stopped calling back..
  235013. for (int i = 40; --i >= 0;)
  235014. {
  235015. Thread::sleep (50);
  235016. UInt32 running = 0;
  235017. UInt32 size = sizeof (running);
  235018. AudioObjectPropertyAddress pa;
  235019. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  235020. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235021. pa.mElement = kAudioObjectPropertyElementMaster;
  235022. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  235023. if (running == 0)
  235024. break;
  235025. }
  235026. const ScopedLock sl (callbackLock);
  235027. }
  235028. if (inputDevice != 0)
  235029. inputDevice->stop (leaveInterruptRunning);
  235030. }
  235031. double getSampleRate() const
  235032. {
  235033. return sampleRate;
  235034. }
  235035. int getBufferSize() const
  235036. {
  235037. return bufferSize;
  235038. }
  235039. void audioCallback (const AudioBufferList* inInputData,
  235040. AudioBufferList* outOutputData)
  235041. {
  235042. int i;
  235043. const ScopedLock sl (callbackLock);
  235044. if (callback != 0)
  235045. {
  235046. if (inputDevice == 0)
  235047. {
  235048. for (i = numInputChans; --i >= 0;)
  235049. {
  235050. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  235051. float* dest = tempInputBuffers [i];
  235052. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  235053. + info.dataOffsetSamples;
  235054. const int stride = info.dataStrideSamples;
  235055. if (stride != 0) // if this is zero, info is invalid
  235056. {
  235057. for (int j = bufferSize; --j >= 0;)
  235058. {
  235059. *dest++ = *src;
  235060. src += stride;
  235061. }
  235062. }
  235063. }
  235064. }
  235065. if (! isSlaveDevice)
  235066. {
  235067. if (inputDevice == 0)
  235068. {
  235069. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  235070. numInputChans,
  235071. tempOutputBuffers,
  235072. numOutputChans,
  235073. bufferSize);
  235074. }
  235075. else
  235076. {
  235077. jassert (inputDevice->bufferSize == bufferSize);
  235078. // Sometimes the two linked devices seem to get their callbacks in
  235079. // parallel, so we need to lock both devices to stop the input data being
  235080. // changed while inside our callback..
  235081. const ScopedLock sl2 (inputDevice->callbackLock);
  235082. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  235083. inputDevice->numInputChans,
  235084. tempOutputBuffers,
  235085. numOutputChans,
  235086. bufferSize);
  235087. }
  235088. for (i = numOutputChans; --i >= 0;)
  235089. {
  235090. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235091. const float* src = tempOutputBuffers [i];
  235092. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235093. + info.dataOffsetSamples;
  235094. const int stride = info.dataStrideSamples;
  235095. if (stride != 0) // if this is zero, info is invalid
  235096. {
  235097. for (int j = bufferSize; --j >= 0;)
  235098. {
  235099. *dest = *src++;
  235100. dest += stride;
  235101. }
  235102. }
  235103. }
  235104. }
  235105. }
  235106. else
  235107. {
  235108. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  235109. {
  235110. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235111. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235112. + info.dataOffsetSamples;
  235113. const int stride = info.dataStrideSamples;
  235114. if (stride != 0) // if this is zero, info is invalid
  235115. {
  235116. for (int j = bufferSize; --j >= 0;)
  235117. {
  235118. *dest = 0.0f;
  235119. dest += stride;
  235120. }
  235121. }
  235122. }
  235123. }
  235124. }
  235125. // called by callbacks
  235126. void deviceDetailsChanged()
  235127. {
  235128. if (callbacksAllowed)
  235129. startTimer (100);
  235130. }
  235131. void timerCallback()
  235132. {
  235133. stopTimer();
  235134. log ("CoreAudio device changed callback");
  235135. const double oldSampleRate = sampleRate;
  235136. const int oldBufferSize = bufferSize;
  235137. updateDetailsFromDevice();
  235138. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  235139. {
  235140. callbacksAllowed = false;
  235141. stop (false);
  235142. updateDetailsFromDevice();
  235143. callbacksAllowed = true;
  235144. }
  235145. }
  235146. CoreAudioInternal* getRelatedDevice() const
  235147. {
  235148. UInt32 size = 0;
  235149. ScopedPointer <CoreAudioInternal> result;
  235150. AudioObjectPropertyAddress pa;
  235151. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  235152. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235153. pa.mElement = kAudioObjectPropertyElementMaster;
  235154. if (deviceID != 0
  235155. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  235156. && size > 0)
  235157. {
  235158. HeapBlock <AudioDeviceID> devs;
  235159. devs.calloc (size, 1);
  235160. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  235161. {
  235162. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  235163. {
  235164. if (devs[i] != deviceID && devs[i] != 0)
  235165. {
  235166. result = new CoreAudioInternal (devs[i]);
  235167. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  235168. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  235169. if (thisIsInput != otherIsInput
  235170. || (inChanNames.size() + outChanNames.size() == 0)
  235171. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  235172. break;
  235173. result = 0;
  235174. }
  235175. }
  235176. }
  235177. }
  235178. return result.release();
  235179. }
  235180. int inputLatency, outputLatency;
  235181. BigInteger activeInputChans, activeOutputChans;
  235182. StringArray inChanNames, outChanNames;
  235183. Array <double> sampleRates;
  235184. Array <int> bufferSizes;
  235185. AudioIODeviceCallback* callback;
  235186. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235187. AudioDeviceIOProcID audioProcID;
  235188. #endif
  235189. ScopedPointer<CoreAudioInternal> inputDevice;
  235190. bool isSlaveDevice;
  235191. private:
  235192. CriticalSection callbackLock;
  235193. AudioDeviceID deviceID;
  235194. bool started;
  235195. double sampleRate;
  235196. int bufferSize;
  235197. HeapBlock <float> audioBuffer;
  235198. int numInputChans, numOutputChans;
  235199. bool callbacksAllowed;
  235200. struct CallbackDetailsForChannel
  235201. {
  235202. int streamNum;
  235203. int dataOffsetSamples;
  235204. int dataStrideSamples;
  235205. };
  235206. int numInputChannelInfos, numOutputChannelInfos;
  235207. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  235208. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  235209. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  235210. const AudioTimeStamp* /*inNow*/,
  235211. const AudioBufferList* inInputData,
  235212. const AudioTimeStamp* /*inInputTime*/,
  235213. AudioBufferList* outOutputData,
  235214. const AudioTimeStamp* /*inOutputTime*/,
  235215. void* device)
  235216. {
  235217. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  235218. return noErr;
  235219. }
  235220. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235221. {
  235222. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235223. switch (pa->mSelector)
  235224. {
  235225. case kAudioDevicePropertyBufferSize:
  235226. case kAudioDevicePropertyBufferFrameSize:
  235227. case kAudioDevicePropertyNominalSampleRate:
  235228. case kAudioDevicePropertyStreamFormat:
  235229. case kAudioDevicePropertyDeviceIsAlive:
  235230. intern->deviceDetailsChanged();
  235231. break;
  235232. case kAudioDevicePropertyBufferSizeRange:
  235233. case kAudioDevicePropertyVolumeScalar:
  235234. case kAudioDevicePropertyMute:
  235235. case kAudioDevicePropertyPlayThru:
  235236. case kAudioDevicePropertyDataSource:
  235237. case kAudioDevicePropertyDeviceIsRunning:
  235238. break;
  235239. }
  235240. return noErr;
  235241. }
  235242. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  235243. {
  235244. AudioObjectPropertyAddress pa;
  235245. pa.mSelector = kAudioDevicePropertyDataSources;
  235246. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235247. pa.mElement = kAudioObjectPropertyElementMaster;
  235248. UInt32 size = 0;
  235249. if (deviceID != 0
  235250. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235251. {
  235252. types.calloc (size, 1);
  235253. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  235254. return size / (int) sizeof (OSType);
  235255. }
  235256. return 0;
  235257. }
  235258. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioInternal);
  235259. };
  235260. class CoreAudioIODevice : public AudioIODevice
  235261. {
  235262. public:
  235263. CoreAudioIODevice (const String& deviceName,
  235264. AudioDeviceID inputDeviceId,
  235265. const int inputIndex_,
  235266. AudioDeviceID outputDeviceId,
  235267. const int outputIndex_)
  235268. : AudioIODevice (deviceName, "CoreAudio"),
  235269. inputIndex (inputIndex_),
  235270. outputIndex (outputIndex_),
  235271. isOpen_ (false),
  235272. isStarted (false)
  235273. {
  235274. CoreAudioInternal* device = 0;
  235275. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  235276. {
  235277. jassert (inputDeviceId != 0);
  235278. device = new CoreAudioInternal (inputDeviceId);
  235279. }
  235280. else
  235281. {
  235282. device = new CoreAudioInternal (outputDeviceId);
  235283. if (inputDeviceId != 0)
  235284. {
  235285. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  235286. device->inputDevice = secondDevice;
  235287. secondDevice->isSlaveDevice = true;
  235288. }
  235289. }
  235290. internal = device;
  235291. AudioObjectPropertyAddress pa;
  235292. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235293. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235294. pa.mElement = kAudioObjectPropertyElementWildcard;
  235295. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235296. }
  235297. ~CoreAudioIODevice()
  235298. {
  235299. AudioObjectPropertyAddress pa;
  235300. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235301. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235302. pa.mElement = kAudioObjectPropertyElementWildcard;
  235303. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235304. }
  235305. const StringArray getOutputChannelNames()
  235306. {
  235307. return internal->outChanNames;
  235308. }
  235309. const StringArray getInputChannelNames()
  235310. {
  235311. if (internal->inputDevice != 0)
  235312. return internal->inputDevice->inChanNames;
  235313. else
  235314. return internal->inChanNames;
  235315. }
  235316. int getNumSampleRates()
  235317. {
  235318. return internal->sampleRates.size();
  235319. }
  235320. double getSampleRate (int index)
  235321. {
  235322. return internal->sampleRates [index];
  235323. }
  235324. int getNumBufferSizesAvailable()
  235325. {
  235326. return internal->bufferSizes.size();
  235327. }
  235328. int getBufferSizeSamples (int index)
  235329. {
  235330. return internal->bufferSizes [index];
  235331. }
  235332. int getDefaultBufferSize()
  235333. {
  235334. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  235335. if (getBufferSizeSamples(i) >= 512)
  235336. return getBufferSizeSamples(i);
  235337. return 512;
  235338. }
  235339. const String open (const BigInteger& inputChannels,
  235340. const BigInteger& outputChannels,
  235341. double sampleRate,
  235342. int bufferSizeSamples)
  235343. {
  235344. isOpen_ = true;
  235345. if (bufferSizeSamples <= 0)
  235346. bufferSizeSamples = getDefaultBufferSize();
  235347. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  235348. isOpen_ = lastError.isEmpty();
  235349. return lastError;
  235350. }
  235351. void close()
  235352. {
  235353. isOpen_ = false;
  235354. internal->stop (false);
  235355. }
  235356. bool isOpen()
  235357. {
  235358. return isOpen_;
  235359. }
  235360. int getCurrentBufferSizeSamples()
  235361. {
  235362. return internal != 0 ? internal->getBufferSize() : 512;
  235363. }
  235364. double getCurrentSampleRate()
  235365. {
  235366. return internal != 0 ? internal->getSampleRate() : 0;
  235367. }
  235368. int getCurrentBitDepth()
  235369. {
  235370. return 32; // no way to find out, so just assume it's high..
  235371. }
  235372. const BigInteger getActiveOutputChannels() const
  235373. {
  235374. return internal != 0 ? internal->activeOutputChans : BigInteger();
  235375. }
  235376. const BigInteger getActiveInputChannels() const
  235377. {
  235378. BigInteger chans;
  235379. if (internal != 0)
  235380. {
  235381. chans = internal->activeInputChans;
  235382. if (internal->inputDevice != 0)
  235383. chans |= internal->inputDevice->activeInputChans;
  235384. }
  235385. return chans;
  235386. }
  235387. int getOutputLatencyInSamples()
  235388. {
  235389. if (internal == 0)
  235390. return 0;
  235391. // this seems like a good guess at getting the latency right - comparing
  235392. // this with a round-trip measurement, it gets it to within a few millisecs
  235393. // for the built-in mac soundcard
  235394. return internal->outputLatency + internal->getBufferSize() * 2;
  235395. }
  235396. int getInputLatencyInSamples()
  235397. {
  235398. if (internal == 0)
  235399. return 0;
  235400. return internal->inputLatency + internal->getBufferSize() * 2;
  235401. }
  235402. void start (AudioIODeviceCallback* callback)
  235403. {
  235404. if (internal != 0 && ! isStarted)
  235405. {
  235406. if (callback != 0)
  235407. callback->audioDeviceAboutToStart (this);
  235408. isStarted = true;
  235409. internal->start (callback);
  235410. }
  235411. }
  235412. void stop()
  235413. {
  235414. if (isStarted && internal != 0)
  235415. {
  235416. AudioIODeviceCallback* const lastCallback = internal->callback;
  235417. isStarted = false;
  235418. internal->stop (true);
  235419. if (lastCallback != 0)
  235420. lastCallback->audioDeviceStopped();
  235421. }
  235422. }
  235423. bool isPlaying()
  235424. {
  235425. if (internal->callback == 0)
  235426. isStarted = false;
  235427. return isStarted;
  235428. }
  235429. const String getLastError()
  235430. {
  235431. return lastError;
  235432. }
  235433. int inputIndex, outputIndex;
  235434. private:
  235435. ScopedPointer<CoreAudioInternal> internal;
  235436. bool isOpen_, isStarted;
  235437. String lastError;
  235438. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235439. {
  235440. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235441. switch (pa->mSelector)
  235442. {
  235443. case kAudioHardwarePropertyDevices:
  235444. intern->deviceDetailsChanged();
  235445. break;
  235446. case kAudioHardwarePropertyDefaultOutputDevice:
  235447. case kAudioHardwarePropertyDefaultInputDevice:
  235448. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  235449. break;
  235450. }
  235451. return noErr;
  235452. }
  235453. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODevice);
  235454. };
  235455. class CoreAudioIODeviceType : public AudioIODeviceType
  235456. {
  235457. public:
  235458. CoreAudioIODeviceType()
  235459. : AudioIODeviceType ("CoreAudio"),
  235460. hasScanned (false)
  235461. {
  235462. }
  235463. ~CoreAudioIODeviceType()
  235464. {
  235465. }
  235466. void scanForDevices()
  235467. {
  235468. hasScanned = true;
  235469. inputDeviceNames.clear();
  235470. outputDeviceNames.clear();
  235471. inputIds.clear();
  235472. outputIds.clear();
  235473. UInt32 size;
  235474. AudioObjectPropertyAddress pa;
  235475. pa.mSelector = kAudioHardwarePropertyDevices;
  235476. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235477. pa.mElement = kAudioObjectPropertyElementMaster;
  235478. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  235479. {
  235480. HeapBlock <AudioDeviceID> devs;
  235481. devs.calloc (size, 1);
  235482. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  235483. {
  235484. const int num = size / (int) sizeof (AudioDeviceID);
  235485. for (int i = 0; i < num; ++i)
  235486. {
  235487. char name [1024];
  235488. size = sizeof (name);
  235489. pa.mSelector = kAudioDevicePropertyDeviceName;
  235490. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  235491. {
  235492. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  235493. const int numIns = getNumChannels (devs[i], true);
  235494. const int numOuts = getNumChannels (devs[i], false);
  235495. if (numIns > 0)
  235496. {
  235497. inputDeviceNames.add (nameString);
  235498. inputIds.add (devs[i]);
  235499. }
  235500. if (numOuts > 0)
  235501. {
  235502. outputDeviceNames.add (nameString);
  235503. outputIds.add (devs[i]);
  235504. }
  235505. }
  235506. }
  235507. }
  235508. }
  235509. inputDeviceNames.appendNumbersToDuplicates (false, true);
  235510. outputDeviceNames.appendNumbersToDuplicates (false, true);
  235511. }
  235512. const StringArray getDeviceNames (bool wantInputNames) const
  235513. {
  235514. jassert (hasScanned); // need to call scanForDevices() before doing this
  235515. if (wantInputNames)
  235516. return inputDeviceNames;
  235517. else
  235518. return outputDeviceNames;
  235519. }
  235520. int getDefaultDeviceIndex (bool forInput) const
  235521. {
  235522. jassert (hasScanned); // need to call scanForDevices() before doing this
  235523. AudioDeviceID deviceID;
  235524. UInt32 size = sizeof (deviceID);
  235525. // if they're asking for any input channels at all, use the default input, so we
  235526. // get the built-in mic rather than the built-in output with no inputs..
  235527. AudioObjectPropertyAddress pa;
  235528. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  235529. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235530. pa.mElement = kAudioObjectPropertyElementMaster;
  235531. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  235532. {
  235533. if (forInput)
  235534. {
  235535. for (int i = inputIds.size(); --i >= 0;)
  235536. if (inputIds[i] == deviceID)
  235537. return i;
  235538. }
  235539. else
  235540. {
  235541. for (int i = outputIds.size(); --i >= 0;)
  235542. if (outputIds[i] == deviceID)
  235543. return i;
  235544. }
  235545. }
  235546. return 0;
  235547. }
  235548. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  235549. {
  235550. jassert (hasScanned); // need to call scanForDevices() before doing this
  235551. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  235552. if (d == 0)
  235553. return -1;
  235554. return asInput ? d->inputIndex
  235555. : d->outputIndex;
  235556. }
  235557. bool hasSeparateInputsAndOutputs() const { return true; }
  235558. AudioIODevice* createDevice (const String& outputDeviceName,
  235559. const String& inputDeviceName)
  235560. {
  235561. jassert (hasScanned); // need to call scanForDevices() before doing this
  235562. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  235563. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  235564. String deviceName (outputDeviceName);
  235565. if (deviceName.isEmpty())
  235566. deviceName = inputDeviceName;
  235567. if (index >= 0)
  235568. return new CoreAudioIODevice (deviceName,
  235569. inputIds [inputIndex],
  235570. inputIndex,
  235571. outputIds [outputIndex],
  235572. outputIndex);
  235573. return 0;
  235574. }
  235575. private:
  235576. StringArray inputDeviceNames, outputDeviceNames;
  235577. Array <AudioDeviceID> inputIds, outputIds;
  235578. bool hasScanned;
  235579. static int getNumChannels (AudioDeviceID deviceID, bool input)
  235580. {
  235581. int total = 0;
  235582. UInt32 size;
  235583. AudioObjectPropertyAddress pa;
  235584. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235585. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235586. pa.mElement = kAudioObjectPropertyElementMaster;
  235587. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235588. {
  235589. HeapBlock <AudioBufferList> bufList;
  235590. bufList.calloc (size, 1);
  235591. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235592. {
  235593. const int numStreams = bufList->mNumberBuffers;
  235594. for (int i = 0; i < numStreams; ++i)
  235595. {
  235596. const AudioBuffer& b = bufList->mBuffers[i];
  235597. total += b.mNumberChannels;
  235598. }
  235599. }
  235600. }
  235601. return total;
  235602. }
  235603. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODeviceType);
  235604. };
  235605. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  235606. {
  235607. return new CoreAudioIODeviceType();
  235608. }
  235609. #undef log
  235610. #endif
  235611. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  235612. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  235613. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235614. // compiled on its own).
  235615. #if JUCE_INCLUDED_FILE
  235616. #if JUCE_MAC
  235617. namespace CoreMidiHelpers
  235618. {
  235619. bool logError (const OSStatus err, const int lineNum)
  235620. {
  235621. if (err == noErr)
  235622. return true;
  235623. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235624. jassertfalse;
  235625. return false;
  235626. }
  235627. #undef CHECK_ERROR
  235628. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  235629. const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  235630. {
  235631. String result;
  235632. CFStringRef str = 0;
  235633. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  235634. if (str != 0)
  235635. {
  235636. result = PlatformUtilities::cfStringToJuceString (str);
  235637. CFRelease (str);
  235638. str = 0;
  235639. }
  235640. MIDIEntityRef entity = 0;
  235641. MIDIEndpointGetEntity (endpoint, &entity);
  235642. if (entity == 0)
  235643. return result; // probably virtual
  235644. if (result.isEmpty())
  235645. {
  235646. // endpoint name has zero length - try the entity
  235647. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  235648. if (str != 0)
  235649. {
  235650. result += PlatformUtilities::cfStringToJuceString (str);
  235651. CFRelease (str);
  235652. str = 0;
  235653. }
  235654. }
  235655. // now consider the device's name
  235656. MIDIDeviceRef device = 0;
  235657. MIDIEntityGetDevice (entity, &device);
  235658. if (device == 0)
  235659. return result;
  235660. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  235661. if (str != 0)
  235662. {
  235663. const String s (PlatformUtilities::cfStringToJuceString (str));
  235664. CFRelease (str);
  235665. // if an external device has only one entity, throw away
  235666. // the endpoint name and just use the device name
  235667. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  235668. {
  235669. result = s;
  235670. }
  235671. else if (! result.startsWithIgnoreCase (s))
  235672. {
  235673. // prepend the device name to the entity name
  235674. result = (s + " " + result).trimEnd();
  235675. }
  235676. }
  235677. return result;
  235678. }
  235679. const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  235680. {
  235681. String result;
  235682. // Does the endpoint have connections?
  235683. CFDataRef connections = 0;
  235684. int numConnections = 0;
  235685. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  235686. if (connections != 0)
  235687. {
  235688. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  235689. if (numConnections > 0)
  235690. {
  235691. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  235692. for (int i = 0; i < numConnections; ++i, ++pid)
  235693. {
  235694. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  235695. MIDIObjectRef connObject;
  235696. MIDIObjectType connObjectType;
  235697. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  235698. if (err == noErr)
  235699. {
  235700. String s;
  235701. if (connObjectType == kMIDIObjectType_ExternalSource
  235702. || connObjectType == kMIDIObjectType_ExternalDestination)
  235703. {
  235704. // Connected to an external device's endpoint (10.3 and later).
  235705. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  235706. }
  235707. else
  235708. {
  235709. // Connected to an external device (10.2) (or something else, catch-all)
  235710. CFStringRef str = 0;
  235711. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  235712. if (str != 0)
  235713. {
  235714. s = PlatformUtilities::cfStringToJuceString (str);
  235715. CFRelease (str);
  235716. }
  235717. }
  235718. if (s.isNotEmpty())
  235719. {
  235720. if (result.isNotEmpty())
  235721. result += ", ";
  235722. result += s;
  235723. }
  235724. }
  235725. }
  235726. }
  235727. CFRelease (connections);
  235728. }
  235729. if (result.isNotEmpty())
  235730. return result;
  235731. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  235732. return getEndpointName (endpoint, false);
  235733. }
  235734. MIDIClientRef getGlobalMidiClient()
  235735. {
  235736. static MIDIClientRef globalMidiClient = 0;
  235737. if (globalMidiClient == 0)
  235738. {
  235739. String name ("JUCE");
  235740. if (JUCEApplication::getInstance() != 0)
  235741. name = JUCEApplication::getInstance()->getApplicationName();
  235742. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  235743. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  235744. CFRelease (appName);
  235745. }
  235746. return globalMidiClient;
  235747. }
  235748. class MidiPortAndEndpoint
  235749. {
  235750. public:
  235751. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  235752. : port (port_), endPoint (endPoint_)
  235753. {
  235754. }
  235755. ~MidiPortAndEndpoint()
  235756. {
  235757. if (port != 0)
  235758. MIDIPortDispose (port);
  235759. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  235760. MIDIEndpointDispose (endPoint);
  235761. }
  235762. void send (const MIDIPacketList* const packets)
  235763. {
  235764. if (port != 0)
  235765. MIDISend (port, endPoint, packets);
  235766. else
  235767. MIDIReceived (endPoint, packets);
  235768. }
  235769. MIDIPortRef port;
  235770. MIDIEndpointRef endPoint;
  235771. };
  235772. class MidiPortAndCallback;
  235773. CriticalSection callbackLock;
  235774. Array<MidiPortAndCallback*> activeCallbacks;
  235775. class MidiPortAndCallback
  235776. {
  235777. public:
  235778. MidiPortAndCallback (MidiInputCallback& callback_)
  235779. : input (0), active (false), callback (callback_), concatenator (2048)
  235780. {
  235781. }
  235782. ~MidiPortAndCallback()
  235783. {
  235784. active = false;
  235785. {
  235786. const ScopedLock sl (callbackLock);
  235787. activeCallbacks.removeValue (this);
  235788. }
  235789. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  235790. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  235791. }
  235792. void handlePackets (const MIDIPacketList* const pktlist)
  235793. {
  235794. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  235795. const ScopedLock sl (callbackLock);
  235796. if (activeCallbacks.contains (this) && active)
  235797. {
  235798. const MIDIPacket* packet = &pktlist->packet[0];
  235799. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  235800. {
  235801. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  235802. input, callback);
  235803. packet = MIDIPacketNext (packet);
  235804. }
  235805. }
  235806. }
  235807. MidiInput* input;
  235808. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  235809. volatile bool active;
  235810. private:
  235811. MidiInputCallback& callback;
  235812. MidiDataConcatenator concatenator;
  235813. };
  235814. void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  235815. {
  235816. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  235817. }
  235818. }
  235819. const StringArray MidiOutput::getDevices()
  235820. {
  235821. StringArray s;
  235822. const ItemCount num = MIDIGetNumberOfDestinations();
  235823. for (ItemCount i = 0; i < num; ++i)
  235824. {
  235825. MIDIEndpointRef dest = MIDIGetDestination (i);
  235826. if (dest != 0)
  235827. {
  235828. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  235829. if (name.isEmpty())
  235830. name = "<error>";
  235831. s.add (name);
  235832. }
  235833. else
  235834. {
  235835. s.add ("<error>");
  235836. }
  235837. }
  235838. return s;
  235839. }
  235840. int MidiOutput::getDefaultDeviceIndex()
  235841. {
  235842. return 0;
  235843. }
  235844. MidiOutput* MidiOutput::openDevice (int index)
  235845. {
  235846. MidiOutput* mo = 0;
  235847. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfDestinations()))
  235848. {
  235849. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  235850. CFStringRef pname;
  235851. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  235852. {
  235853. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  235854. MIDIPortRef port;
  235855. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  235856. {
  235857. mo = new MidiOutput();
  235858. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  235859. }
  235860. CFRelease (pname);
  235861. }
  235862. }
  235863. return mo;
  235864. }
  235865. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  235866. {
  235867. MidiOutput* mo = 0;
  235868. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  235869. MIDIEndpointRef endPoint;
  235870. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  235871. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  235872. {
  235873. mo = new MidiOutput();
  235874. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  235875. }
  235876. CFRelease (name);
  235877. return mo;
  235878. }
  235879. MidiOutput::~MidiOutput()
  235880. {
  235881. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  235882. }
  235883. void MidiOutput::reset()
  235884. {
  235885. }
  235886. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  235887. {
  235888. return false;
  235889. }
  235890. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  235891. {
  235892. }
  235893. void MidiOutput::sendMessageNow (const MidiMessage& message)
  235894. {
  235895. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  235896. if (message.isSysEx())
  235897. {
  235898. const int maxPacketSize = 256;
  235899. int pos = 0, bytesLeft = message.getRawDataSize();
  235900. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  235901. HeapBlock <MIDIPacketList> packets;
  235902. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  235903. packets->numPackets = numPackets;
  235904. MIDIPacket* p = packets->packet;
  235905. for (int i = 0; i < numPackets; ++i)
  235906. {
  235907. p->timeStamp = AudioGetCurrentHostTime();
  235908. p->length = jmin (maxPacketSize, bytesLeft);
  235909. memcpy (p->data, message.getRawData() + pos, p->length);
  235910. pos += p->length;
  235911. bytesLeft -= p->length;
  235912. p = MIDIPacketNext (p);
  235913. }
  235914. mpe->send (packets);
  235915. }
  235916. else
  235917. {
  235918. MIDIPacketList packets;
  235919. packets.numPackets = 1;
  235920. packets.packet[0].timeStamp = AudioGetCurrentHostTime();
  235921. packets.packet[0].length = message.getRawDataSize();
  235922. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  235923. mpe->send (&packets);
  235924. }
  235925. }
  235926. const StringArray MidiInput::getDevices()
  235927. {
  235928. StringArray s;
  235929. const ItemCount num = MIDIGetNumberOfSources();
  235930. for (ItemCount i = 0; i < num; ++i)
  235931. {
  235932. MIDIEndpointRef source = MIDIGetSource (i);
  235933. if (source != 0)
  235934. {
  235935. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  235936. if (name.isEmpty())
  235937. name = "<error>";
  235938. s.add (name);
  235939. }
  235940. else
  235941. {
  235942. s.add ("<error>");
  235943. }
  235944. }
  235945. return s;
  235946. }
  235947. int MidiInput::getDefaultDeviceIndex()
  235948. {
  235949. return 0;
  235950. }
  235951. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  235952. {
  235953. jassert (callback != 0);
  235954. using namespace CoreMidiHelpers;
  235955. MidiInput* newInput = 0;
  235956. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
  235957. {
  235958. MIDIEndpointRef endPoint = MIDIGetSource (index);
  235959. if (endPoint != 0)
  235960. {
  235961. CFStringRef name;
  235962. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  235963. {
  235964. MIDIClientRef client = getGlobalMidiClient();
  235965. if (client != 0)
  235966. {
  235967. MIDIPortRef port;
  235968. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  235969. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  235970. {
  235971. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  235972. {
  235973. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  235974. newInput = new MidiInput (getDevices() [index]);
  235975. mpc->input = newInput;
  235976. newInput->internal = mpc;
  235977. const ScopedLock sl (callbackLock);
  235978. activeCallbacks.add (mpc.release());
  235979. }
  235980. else
  235981. {
  235982. CHECK_ERROR (MIDIPortDispose (port));
  235983. }
  235984. }
  235985. }
  235986. }
  235987. CFRelease (name);
  235988. }
  235989. }
  235990. return newInput;
  235991. }
  235992. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  235993. {
  235994. jassert (callback != 0);
  235995. using namespace CoreMidiHelpers;
  235996. MidiInput* mi = 0;
  235997. MIDIClientRef client = getGlobalMidiClient();
  235998. if (client != 0)
  235999. {
  236000. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236001. mpc->active = false;
  236002. MIDIEndpointRef endPoint;
  236003. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  236004. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  236005. {
  236006. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  236007. mi = new MidiInput (deviceName);
  236008. mpc->input = mi;
  236009. mi->internal = mpc;
  236010. const ScopedLock sl (callbackLock);
  236011. activeCallbacks.add (mpc.release());
  236012. }
  236013. CFRelease (name);
  236014. }
  236015. return mi;
  236016. }
  236017. MidiInput::MidiInput (const String& name_)
  236018. : name (name_)
  236019. {
  236020. }
  236021. MidiInput::~MidiInput()
  236022. {
  236023. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  236024. }
  236025. void MidiInput::start()
  236026. {
  236027. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236028. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  236029. }
  236030. void MidiInput::stop()
  236031. {
  236032. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236033. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  236034. }
  236035. #undef CHECK_ERROR
  236036. #else // Stubs for iOS...
  236037. MidiOutput::~MidiOutput() {}
  236038. void MidiOutput::reset() {}
  236039. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  236040. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  236041. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  236042. const StringArray MidiOutput::getDevices() { return StringArray(); }
  236043. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  236044. const StringArray MidiInput::getDevices() { return StringArray(); }
  236045. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  236046. #endif
  236047. #endif
  236048. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  236049. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  236050. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236051. // compiled on its own).
  236052. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  236053. #if ! JUCE_QUICKTIME
  236054. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  236055. #endif
  236056. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  236057. class QTCameraDeviceInteral;
  236058. END_JUCE_NAMESPACE
  236059. @interface QTCaptureCallbackDelegate : NSObject
  236060. {
  236061. @public
  236062. CameraDevice* owner;
  236063. QTCameraDeviceInteral* internal;
  236064. int64 firstPresentationTime;
  236065. int64 averageTimeOffset;
  236066. }
  236067. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  236068. - (void) dealloc;
  236069. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236070. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236071. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236072. fromConnection: (QTCaptureConnection*) connection;
  236073. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236074. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236075. fromConnection: (QTCaptureConnection*) connection;
  236076. @end
  236077. BEGIN_JUCE_NAMESPACE
  236078. class QTCameraDeviceInteral
  236079. {
  236080. public:
  236081. QTCameraDeviceInteral (CameraDevice* owner, int index)
  236082. {
  236083. const ScopedAutoReleasePool pool;
  236084. session = [[QTCaptureSession alloc] init];
  236085. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236086. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  236087. input = 0;
  236088. audioInput = 0;
  236089. audioDevice = 0;
  236090. fileOutput = 0;
  236091. imageOutput = 0;
  236092. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  236093. internalDev: this];
  236094. NSError* err = 0;
  236095. [device retain];
  236096. [device open: &err];
  236097. if (err == 0)
  236098. {
  236099. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236100. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236101. [session addInput: input error: &err];
  236102. if (err == 0)
  236103. {
  236104. resetFile();
  236105. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  236106. [imageOutput setDelegate: callbackDelegate];
  236107. if (err == 0)
  236108. {
  236109. [session startRunning];
  236110. return;
  236111. }
  236112. }
  236113. }
  236114. openingError = nsStringToJuce ([err description]);
  236115. DBG (openingError);
  236116. }
  236117. ~QTCameraDeviceInteral()
  236118. {
  236119. [session stopRunning];
  236120. [session removeOutput: imageOutput];
  236121. [session release];
  236122. [input release];
  236123. [device release];
  236124. [audioDevice release];
  236125. [audioInput release];
  236126. [fileOutput release];
  236127. [imageOutput release];
  236128. [callbackDelegate release];
  236129. }
  236130. void resetFile()
  236131. {
  236132. [fileOutput recordToOutputFileURL: nil];
  236133. [session removeOutput: fileOutput];
  236134. [fileOutput release];
  236135. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  236136. [session removeInput: audioInput];
  236137. [audioInput release];
  236138. audioInput = 0;
  236139. [audioDevice release];
  236140. audioDevice = 0;
  236141. [fileOutput setDelegate: callbackDelegate];
  236142. }
  236143. void addDefaultAudioInput()
  236144. {
  236145. NSError* err = nil;
  236146. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  236147. if ([audioDevice open: &err])
  236148. [audioDevice retain];
  236149. else
  236150. audioDevice = nil;
  236151. if (audioDevice != 0)
  236152. {
  236153. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  236154. [session addInput: audioInput error: &err];
  236155. }
  236156. }
  236157. void addListener (CameraDevice::Listener* listenerToAdd)
  236158. {
  236159. const ScopedLock sl (listenerLock);
  236160. if (listeners.size() == 0)
  236161. [session addOutput: imageOutput error: nil];
  236162. listeners.addIfNotAlreadyThere (listenerToAdd);
  236163. }
  236164. void removeListener (CameraDevice::Listener* listenerToRemove)
  236165. {
  236166. const ScopedLock sl (listenerLock);
  236167. listeners.removeValue (listenerToRemove);
  236168. if (listeners.size() == 0)
  236169. [session removeOutput: imageOutput];
  236170. }
  236171. void callListeners (CIImage* frame, int w, int h)
  236172. {
  236173. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  236174. Image image (cgImage);
  236175. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  236176. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  236177. CGContextFlush (cgImage->context);
  236178. const ScopedLock sl (listenerLock);
  236179. for (int i = listeners.size(); --i >= 0;)
  236180. {
  236181. CameraDevice::Listener* const l = listeners[i];
  236182. if (l != 0)
  236183. l->imageReceived (image);
  236184. }
  236185. }
  236186. QTCaptureDevice* device;
  236187. QTCaptureDeviceInput* input;
  236188. QTCaptureDevice* audioDevice;
  236189. QTCaptureDeviceInput* audioInput;
  236190. QTCaptureSession* session;
  236191. QTCaptureMovieFileOutput* fileOutput;
  236192. QTCaptureDecompressedVideoOutput* imageOutput;
  236193. QTCaptureCallbackDelegate* callbackDelegate;
  236194. String openingError;
  236195. Array<CameraDevice::Listener*> listeners;
  236196. CriticalSection listenerLock;
  236197. };
  236198. END_JUCE_NAMESPACE
  236199. @implementation QTCaptureCallbackDelegate
  236200. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  236201. internalDev: (QTCameraDeviceInteral*) d
  236202. {
  236203. [super init];
  236204. owner = owner_;
  236205. internal = d;
  236206. firstPresentationTime = 0;
  236207. averageTimeOffset = 0;
  236208. return self;
  236209. }
  236210. - (void) dealloc
  236211. {
  236212. [super dealloc];
  236213. }
  236214. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236215. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236216. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236217. fromConnection: (QTCaptureConnection*) connection
  236218. {
  236219. if (internal->listeners.size() > 0)
  236220. {
  236221. const ScopedAutoReleasePool pool;
  236222. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  236223. CVPixelBufferGetWidth (videoFrame),
  236224. CVPixelBufferGetHeight (videoFrame));
  236225. }
  236226. }
  236227. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236228. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236229. fromConnection: (QTCaptureConnection*) connection
  236230. {
  236231. const Time now (Time::getCurrentTime());
  236232. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  236233. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  236234. #else
  236235. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  236236. #endif
  236237. int64 presentationTime = (hosttime != nil)
  236238. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  236239. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  236240. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  236241. if (firstPresentationTime == 0)
  236242. {
  236243. firstPresentationTime = presentationTime;
  236244. averageTimeOffset = timeDiff;
  236245. }
  236246. else
  236247. {
  236248. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  236249. }
  236250. }
  236251. @end
  236252. BEGIN_JUCE_NAMESPACE
  236253. class QTCaptureViewerComp : public NSViewComponent
  236254. {
  236255. public:
  236256. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  236257. {
  236258. const ScopedAutoReleasePool pool;
  236259. captureView = [[QTCaptureView alloc] init];
  236260. [captureView setCaptureSession: internal->session];
  236261. setSize (640, 480); // xxx need to somehow get the movie size - how?
  236262. setView (captureView);
  236263. }
  236264. ~QTCaptureViewerComp()
  236265. {
  236266. setView (0);
  236267. [captureView setCaptureSession: nil];
  236268. [captureView release];
  236269. }
  236270. QTCaptureView* captureView;
  236271. };
  236272. CameraDevice::CameraDevice (const String& name_, int index)
  236273. : name (name_)
  236274. {
  236275. isRecording = false;
  236276. internal = new QTCameraDeviceInteral (this, index);
  236277. }
  236278. CameraDevice::~CameraDevice()
  236279. {
  236280. stopRecording();
  236281. delete static_cast <QTCameraDeviceInteral*> (internal);
  236282. internal = 0;
  236283. }
  236284. Component* CameraDevice::createViewerComponent()
  236285. {
  236286. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  236287. }
  236288. const String CameraDevice::getFileExtension()
  236289. {
  236290. return ".mov";
  236291. }
  236292. void CameraDevice::startRecordingToFile (const File& file, int quality)
  236293. {
  236294. stopRecording();
  236295. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236296. d->callbackDelegate->firstPresentationTime = 0;
  236297. file.deleteFile();
  236298. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  236299. // out wrong, so we'll put some audio in there too..,
  236300. d->addDefaultAudioInput();
  236301. [d->session addOutput: d->fileOutput error: nil];
  236302. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  236303. for (;;)
  236304. {
  236305. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  236306. if (connection == 0)
  236307. break;
  236308. QTCompressionOptions* options = 0;
  236309. NSString* mediaType = [connection mediaType];
  236310. if ([mediaType isEqualToString: QTMediaTypeVideo])
  236311. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  236312. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  236313. : @"QTCompressionOptions240SizeH264Video"];
  236314. else if ([mediaType isEqualToString: QTMediaTypeSound])
  236315. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  236316. [d->fileOutput setCompressionOptions: options forConnection: connection];
  236317. }
  236318. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  236319. isRecording = true;
  236320. }
  236321. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  236322. {
  236323. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236324. if (d->callbackDelegate->firstPresentationTime != 0)
  236325. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  236326. return Time();
  236327. }
  236328. void CameraDevice::stopRecording()
  236329. {
  236330. if (isRecording)
  236331. {
  236332. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  236333. isRecording = false;
  236334. }
  236335. }
  236336. void CameraDevice::addListener (Listener* listenerToAdd)
  236337. {
  236338. if (listenerToAdd != 0)
  236339. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  236340. }
  236341. void CameraDevice::removeListener (Listener* listenerToRemove)
  236342. {
  236343. if (listenerToRemove != 0)
  236344. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  236345. }
  236346. const StringArray CameraDevice::getAvailableDevices()
  236347. {
  236348. const ScopedAutoReleasePool pool;
  236349. StringArray results;
  236350. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236351. for (int i = 0; i < (int) [devs count]; ++i)
  236352. {
  236353. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  236354. results.add (nsStringToJuce ([dev localizedDisplayName]));
  236355. }
  236356. return results;
  236357. }
  236358. CameraDevice* CameraDevice::openDevice (int index,
  236359. int minWidth, int minHeight,
  236360. int maxWidth, int maxHeight)
  236361. {
  236362. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  236363. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  236364. return d.release();
  236365. return 0;
  236366. }
  236367. #endif
  236368. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  236369. #endif
  236370. #endif
  236371. END_JUCE_NAMESPACE
  236372. #endif
  236373. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  236374. #elif JUCE_ANDROID
  236375. /*** Start of inlined file: juce_android_NativeCode.cpp ***/
  236376. /*
  236377. This file wraps together all the android-specific code, so that
  236378. we can include all the native headers just once, and compile all our
  236379. platform-specific stuff in one big lump, keeping it out of the way of
  236380. the rest of the codebase.
  236381. */
  236382. #if JUCE_ANDROID
  236383. #undef JUCE_BUILD_NATIVE
  236384. #define JUCE_BUILD_NATIVE 1
  236385. BEGIN_JUCE_NAMESPACE
  236386. #define JUCE_JNI_CALLBACK(className, methodName, returnType, params) \
  236387. extern "C" __attribute__ ((visibility("default"))) returnType Java_com_juce_ ## className ## _ ## methodName params
  236388. #define JUCE_JNI_CLASSES(JAVACLASS) \
  236389. JAVACLASS (activityClass, "com/juce/JuceAppActivity") \
  236390. JAVACLASS (componentPeerViewClass, "com/juce/ComponentPeerView") \
  236391. JAVACLASS (fileClass, "java/io/File") \
  236392. JAVACLASS (contextClass, "android/content/Context") \
  236393. JAVACLASS (canvasClass, "android/graphics/Canvas") \
  236394. JAVACLASS (paintClass, "android/graphics/Paint") \
  236395. #define JUCE_JNI_METHODS(METHOD, STATICMETHOD) \
  236396. \
  236397. STATICMETHOD (activityClass, printToConsole, "printToConsole", "(Ljava/lang/String;)V") \
  236398. METHOD (activityClass, createNewView, "createNewView", "()Lcom/juce/ComponentPeerView;") \
  236399. METHOD (activityClass, deleteView, "deleteView", "(Lcom/juce/ComponentPeerView;)V") \
  236400. \
  236401. METHOD (fileClass, fileExists, "exists", "()Z") \
  236402. \
  236403. METHOD (componentPeerViewClass, layout, "layout", "(IIII)V") \
  236404. \
  236405. METHOD (canvasClass, drawRect, "drawRect", "(FFFFLandroid/graphics/Paint;)V") \
  236406. \
  236407. METHOD (paintClass, paintClassConstructor, "<init>", "()V") \
  236408. METHOD (paintClass, setColor, "setColor", "(I)V") \
  236409. class GlobalRef
  236410. {
  236411. public:
  236412. GlobalRef()
  236413. : env (0), obj (0)
  236414. {
  236415. }
  236416. GlobalRef (JNIEnv* const env_, jobject obj_)
  236417. : env (env_),
  236418. obj (retain (env_, obj_))
  236419. {
  236420. }
  236421. GlobalRef (const GlobalRef& other)
  236422. : env (other.env),
  236423. obj (retain (other.env, other.obj))
  236424. {
  236425. }
  236426. ~GlobalRef()
  236427. {
  236428. release();
  236429. }
  236430. GlobalRef& operator= (const GlobalRef& other)
  236431. {
  236432. release();
  236433. env = other.env;
  236434. obj = retain (env, other.obj);
  236435. return *this;
  236436. }
  236437. GlobalRef& operator= (jobject newObj)
  236438. {
  236439. jassert (env != 0 || newObj == 0);
  236440. if (newObj != obj && env != 0)
  236441. {
  236442. release();
  236443. obj = retain (env, newObj);
  236444. }
  236445. }
  236446. inline operator jobject() const throw() { return obj; }
  236447. inline jobject get() const throw() { return obj; }
  236448. inline JNIEnv* getEnv() const throw() { return env; }
  236449. #define DECLARE_CALL_TYPE_METHOD(returnType, typeName) \
  236450. returnType call##typeName##Method (jmethodID methodID, ... ) \
  236451. { \
  236452. returnType result; \
  236453. va_list args; \
  236454. va_start (args, methodID); \
  236455. result = env->Call##typeName##MethodV (obj, methodID, args); \
  236456. va_end (args); \
  236457. return result; \
  236458. }
  236459. DECLARE_CALL_TYPE_METHOD (jobject, Object)
  236460. DECLARE_CALL_TYPE_METHOD (jboolean, Boolean)
  236461. DECLARE_CALL_TYPE_METHOD (jbyte, Byte)
  236462. DECLARE_CALL_TYPE_METHOD (jchar, Char)
  236463. DECLARE_CALL_TYPE_METHOD (jshort, Short)
  236464. DECLARE_CALL_TYPE_METHOD (jint, Int)
  236465. DECLARE_CALL_TYPE_METHOD (jlong, Long)
  236466. DECLARE_CALL_TYPE_METHOD (jfloat, Float)
  236467. DECLARE_CALL_TYPE_METHOD (jdouble, Double)
  236468. #undef DECLARE_CALL_TYPE_METHOD
  236469. void callVoidMethod (jmethodID methodID, ... )
  236470. {
  236471. va_list args;
  236472. va_start (args, methodID);
  236473. env->CallVoidMethodV (obj, methodID, args);
  236474. va_end (args);
  236475. }
  236476. private:
  236477. JNIEnv* env;
  236478. jobject obj;
  236479. void release()
  236480. {
  236481. if (env != 0)
  236482. env->DeleteGlobalRef (obj);
  236483. }
  236484. static jobject retain (JNIEnv* const env, jobject obj_)
  236485. {
  236486. return env == 0 ? 0 : env->NewGlobalRef (obj_);
  236487. }
  236488. };
  236489. class AndroidJavaCallbacks
  236490. {
  236491. public:
  236492. AndroidJavaCallbacks() : env (0)
  236493. {
  236494. }
  236495. void initialise (JNIEnv* env_, jobject activity_)
  236496. {
  236497. env = env_;
  236498. activity = GlobalRef (env, activity_);
  236499. #define CREATE_JNI_CLASS(className, path) \
  236500. className = (jclass) env->NewGlobalRef (env->FindClass (path)); \
  236501. jassert (className != 0);
  236502. JUCE_JNI_CLASSES (CREATE_JNI_CLASS);
  236503. #undef CREATE_JNI_CLASS
  236504. #define CREATE_JNI_METHOD(ownerClass, methodID, stringName, params) \
  236505. methodID = env->GetMethodID (ownerClass, stringName, params); \
  236506. jassert (methodID != 0);
  236507. #define CREATE_JNI_STATICMETHOD(ownerClass, methodID, stringName, params) \
  236508. methodID = env->GetStaticMethodID (ownerClass, stringName, params); \
  236509. jassert (methodID != 0);
  236510. JUCE_JNI_METHODS (CREATE_JNI_METHOD, CREATE_JNI_STATICMETHOD);
  236511. #undef CREATE_JNI_METHOD
  236512. }
  236513. void shutdown()
  236514. {
  236515. if (env != 0)
  236516. {
  236517. #define RELEASE_JNI_CLASS(className, path) env->DeleteGlobalRef (className);
  236518. JUCE_JNI_CLASSES (RELEASE_JNI_CLASS);
  236519. #undef RELEASE_JNI_CLASS
  236520. activity = 0;
  236521. env = 0;
  236522. }
  236523. }
  236524. const String juceString (jstring s) const
  236525. {
  236526. jboolean isCopy;
  236527. const char* const utf8 = env->GetStringUTFChars (s, &isCopy);
  236528. CharPointer_UTF8 utf8CP (utf8);
  236529. const String result (utf8CP);
  236530. env->ReleaseStringUTFChars (s, utf8);
  236531. return result;
  236532. }
  236533. jstring javaString (const String& s) const
  236534. {
  236535. return env->NewStringUTF (s.toUTF8());
  236536. }
  236537. JNIEnv* env;
  236538. GlobalRef activity;
  236539. #define DECLARE_JNI_CLASS(className, path) jclass className;
  236540. JUCE_JNI_CLASSES (DECLARE_JNI_CLASS);
  236541. #undef DECLARE_JNI_CLASS
  236542. #define DECLARE_JNI_METHOD(ownerClass, methodID, stringName, params) jmethodID methodID;
  236543. JUCE_JNI_METHODS (DECLARE_JNI_METHOD, DECLARE_JNI_METHOD);
  236544. #undef DECLARE_JNI_METHOD
  236545. };
  236546. static AndroidJavaCallbacks android;
  236547. #define JUCE_INCLUDED_FILE 1
  236548. // Now include the actual code files..
  236549. /*** Start of inlined file: juce_android_Misc.cpp ***/
  236550. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  236551. // compiled on its own).
  236552. #if JUCE_INCLUDED_FILE
  236553. END_JUCE_NAMESPACE
  236554. extern JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication(); // (from START_JUCE_APPLICATION)
  236555. BEGIN_JUCE_NAMESPACE
  236556. JUCE_JNI_CALLBACK (JuceAppActivity, launchApp, void, (JNIEnv* env, jobject activity))
  236557. {
  236558. android.initialise (env, activity);
  236559. JUCEApplication::createInstance = &juce_CreateApplication;
  236560. initialiseJuce_GUI();
  236561. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  236562. exit (0);
  236563. }
  236564. JUCE_JNI_CALLBACK (JuceAppActivity, quitApp, void, (JNIEnv* env, jobject activity))
  236565. {
  236566. JUCEApplication::appWillTerminateByForce();
  236567. android.shutdown();
  236568. }
  236569. void PlatformUtilities::beep()
  236570. {
  236571. // TODO
  236572. }
  236573. void Logger::outputDebugString (const String& text)
  236574. {
  236575. android.env->CallStaticVoidMethod (android.activityClass, android.printToConsole,
  236576. android.javaString (text));
  236577. }
  236578. void SystemClipboard::copyTextToClipboard (const String& text)
  236579. {
  236580. // TODO
  236581. }
  236582. const String SystemClipboard::getTextFromClipboard()
  236583. {
  236584. String result;
  236585. // TODO
  236586. return result;
  236587. }
  236588. #endif
  236589. /*** End of inlined file: juce_android_Misc.cpp ***/
  236590. /*** Start of inlined file: juce_android_SystemStats.cpp ***/
  236591. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  236592. // compiled on its own).
  236593. #if JUCE_INCLUDED_FILE
  236594. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  236595. {
  236596. return Android;
  236597. }
  236598. const String SystemStats::getOperatingSystemName()
  236599. {
  236600. return "Android";
  236601. }
  236602. bool SystemStats::isOperatingSystem64Bit()
  236603. {
  236604. #if JUCE_64BIT
  236605. return true;
  236606. #else
  236607. return false;
  236608. #endif
  236609. }
  236610. namespace AndroidStatsHelpers
  236611. {
  236612. // TODO
  236613. const String getCpuInfo (const char* const key)
  236614. {
  236615. StringArray lines;
  236616. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  236617. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  236618. if (lines[i].startsWithIgnoreCase (key))
  236619. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  236620. return String::empty;
  236621. }
  236622. }
  236623. const String SystemStats::getCpuVendor()
  236624. {
  236625. return AndroidStatsHelpers::getCpuInfo ("vendor_id");
  236626. }
  236627. int SystemStats::getCpuSpeedInMegaherz()
  236628. {
  236629. return roundToInt (AndroidStatsHelpers::getCpuInfo ("cpu MHz").getFloatValue());
  236630. }
  236631. int SystemStats::getMemorySizeInMegabytes()
  236632. {
  236633. // TODO
  236634. struct sysinfo sysi;
  236635. if (sysinfo (&sysi) == 0)
  236636. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  236637. return 0;
  236638. }
  236639. int SystemStats::getPageSize()
  236640. {
  236641. // TODO
  236642. return sysconf (_SC_PAGESIZE);
  236643. }
  236644. const String SystemStats::getLogonName()
  236645. {
  236646. // TODO
  236647. const char* user = getenv ("USER");
  236648. if (user == 0)
  236649. {
  236650. struct passwd* const pw = getpwuid (getuid());
  236651. if (pw != 0)
  236652. user = pw->pw_name;
  236653. }
  236654. return String::fromUTF8 (user);
  236655. }
  236656. const String SystemStats::getFullUserName()
  236657. {
  236658. return getLogonName();
  236659. }
  236660. void SystemStats::initialiseStats()
  236661. {
  236662. // TODO
  236663. const String flags (AndroidStatsHelpers::getCpuInfo ("flags"));
  236664. cpuFlags.hasMMX = flags.contains ("mmx");
  236665. cpuFlags.hasSSE = flags.contains ("sse");
  236666. cpuFlags.hasSSE2 = flags.contains ("sse2");
  236667. cpuFlags.has3DNow = flags.contains ("3dnow");
  236668. // TODO
  236669. cpuFlags.numCpus = AndroidStatsHelpers::getCpuInfo ("processor").getIntValue() + 1;
  236670. }
  236671. void PlatformUtilities::fpuReset() {}
  236672. uint32 juce_millisecondsSinceStartup() throw()
  236673. {
  236674. // TODO
  236675. timespec t;
  236676. clock_gettime (CLOCK_MONOTONIC, &t);
  236677. return t.tv_sec * 1000 + t.tv_nsec / 1000000;
  236678. }
  236679. int64 Time::getHighResolutionTicks() throw()
  236680. {
  236681. // TODO
  236682. timespec t;
  236683. clock_gettime (CLOCK_MONOTONIC, &t);
  236684. return (t.tv_sec * (int64) 1000000) + (t.tv_nsec / (int64) 1000);
  236685. }
  236686. int64 Time::getHighResolutionTicksPerSecond() throw()
  236687. {
  236688. // TODO
  236689. return 1000000; // (microseconds)
  236690. }
  236691. double Time::getMillisecondCounterHiRes() throw()
  236692. {
  236693. return getHighResolutionTicks() * 0.001;
  236694. }
  236695. bool Time::setSystemTimeToThisTime() const
  236696. {
  236697. jassertfalse;
  236698. return false;
  236699. }
  236700. #endif
  236701. /*** End of inlined file: juce_android_SystemStats.cpp ***/
  236702. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  236703. /*
  236704. This file contains posix routines that are common to both the Linux and Mac builds.
  236705. It gets included directly in the cpp files for these platforms.
  236706. */
  236707. CriticalSection::CriticalSection() throw()
  236708. {
  236709. pthread_mutexattr_t atts;
  236710. pthread_mutexattr_init (&atts);
  236711. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  236712. #if ! JUCE_ANDROID
  236713. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  236714. #endif
  236715. pthread_mutex_init (&internal, &atts);
  236716. }
  236717. CriticalSection::~CriticalSection() throw()
  236718. {
  236719. pthread_mutex_destroy (&internal);
  236720. }
  236721. void CriticalSection::enter() const throw()
  236722. {
  236723. pthread_mutex_lock (&internal);
  236724. }
  236725. bool CriticalSection::tryEnter() const throw()
  236726. {
  236727. return pthread_mutex_trylock (&internal) == 0;
  236728. }
  236729. void CriticalSection::exit() const throw()
  236730. {
  236731. pthread_mutex_unlock (&internal);
  236732. }
  236733. class WaitableEventImpl
  236734. {
  236735. public:
  236736. WaitableEventImpl (const bool manualReset_)
  236737. : triggered (false),
  236738. manualReset (manualReset_)
  236739. {
  236740. pthread_cond_init (&condition, 0);
  236741. pthread_mutexattr_t atts;
  236742. pthread_mutexattr_init (&atts);
  236743. #if ! JUCE_ANDROID
  236744. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  236745. #endif
  236746. pthread_mutex_init (&mutex, &atts);
  236747. }
  236748. ~WaitableEventImpl()
  236749. {
  236750. pthread_cond_destroy (&condition);
  236751. pthread_mutex_destroy (&mutex);
  236752. }
  236753. bool wait (const int timeOutMillisecs) throw()
  236754. {
  236755. pthread_mutex_lock (&mutex);
  236756. if (! triggered)
  236757. {
  236758. if (timeOutMillisecs < 0)
  236759. {
  236760. do
  236761. {
  236762. pthread_cond_wait (&condition, &mutex);
  236763. }
  236764. while (! triggered);
  236765. }
  236766. else
  236767. {
  236768. struct timeval now;
  236769. gettimeofday (&now, 0);
  236770. struct timespec time;
  236771. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  236772. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  236773. if (time.tv_nsec >= 1000000000)
  236774. {
  236775. time.tv_nsec -= 1000000000;
  236776. time.tv_sec++;
  236777. }
  236778. do
  236779. {
  236780. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  236781. {
  236782. pthread_mutex_unlock (&mutex);
  236783. return false;
  236784. }
  236785. }
  236786. while (! triggered);
  236787. }
  236788. }
  236789. if (! manualReset)
  236790. triggered = false;
  236791. pthread_mutex_unlock (&mutex);
  236792. return true;
  236793. }
  236794. void signal() throw()
  236795. {
  236796. pthread_mutex_lock (&mutex);
  236797. triggered = true;
  236798. pthread_cond_broadcast (&condition);
  236799. pthread_mutex_unlock (&mutex);
  236800. }
  236801. void reset() throw()
  236802. {
  236803. pthread_mutex_lock (&mutex);
  236804. triggered = false;
  236805. pthread_mutex_unlock (&mutex);
  236806. }
  236807. private:
  236808. pthread_cond_t condition;
  236809. pthread_mutex_t mutex;
  236810. bool triggered;
  236811. const bool manualReset;
  236812. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  236813. };
  236814. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  236815. : internal (new WaitableEventImpl (manualReset))
  236816. {
  236817. }
  236818. WaitableEvent::~WaitableEvent() throw()
  236819. {
  236820. delete static_cast <WaitableEventImpl*> (internal);
  236821. }
  236822. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  236823. {
  236824. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  236825. }
  236826. void WaitableEvent::signal() const throw()
  236827. {
  236828. static_cast <WaitableEventImpl*> (internal)->signal();
  236829. }
  236830. void WaitableEvent::reset() const throw()
  236831. {
  236832. static_cast <WaitableEventImpl*> (internal)->reset();
  236833. }
  236834. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  236835. {
  236836. struct timespec time;
  236837. time.tv_sec = millisecs / 1000;
  236838. time.tv_nsec = (millisecs % 1000) * 1000000;
  236839. nanosleep (&time, 0);
  236840. }
  236841. const juce_wchar File::separator = '/';
  236842. const String File::separatorString ("/");
  236843. const File File::getCurrentWorkingDirectory()
  236844. {
  236845. HeapBlock<char> heapBuffer;
  236846. char localBuffer [1024];
  236847. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  236848. int bufferSize = 4096;
  236849. while (cwd == 0 && errno == ERANGE)
  236850. {
  236851. heapBuffer.malloc (bufferSize);
  236852. cwd = getcwd (heapBuffer, bufferSize - 1);
  236853. bufferSize += 1024;
  236854. }
  236855. return File (String::fromUTF8 (cwd));
  236856. }
  236857. bool File::setAsCurrentWorkingDirectory() const
  236858. {
  236859. return chdir (getFullPathName().toUTF8()) == 0;
  236860. }
  236861. namespace
  236862. {
  236863. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  236864. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  236865. #else
  236866. typedef struct stat juce_statStruct;
  236867. #endif
  236868. bool juce_stat (const String& fileName, juce_statStruct& info)
  236869. {
  236870. return fileName.isNotEmpty()
  236871. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  236872. && (stat64 (fileName.toUTF8(), &info) == 0);
  236873. #else
  236874. && (stat (fileName.toUTF8(), &info) == 0);
  236875. #endif
  236876. }
  236877. // if this file doesn't exist, find a parent of it that does..
  236878. bool juce_doStatFS (File f, struct statfs& result)
  236879. {
  236880. for (int i = 5; --i >= 0;)
  236881. {
  236882. if (f.exists())
  236883. break;
  236884. f = f.getParentDirectory();
  236885. }
  236886. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  236887. }
  236888. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  236889. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  236890. {
  236891. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  236892. {
  236893. juce_statStruct info;
  236894. const bool statOk = juce_stat (path, info);
  236895. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  236896. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  236897. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  236898. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  236899. }
  236900. if (isReadOnly != 0)
  236901. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  236902. }
  236903. }
  236904. bool File::isDirectory() const
  236905. {
  236906. juce_statStruct info;
  236907. return fullPath.isEmpty()
  236908. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  236909. }
  236910. bool File::exists() const
  236911. {
  236912. juce_statStruct info;
  236913. return fullPath.isNotEmpty()
  236914. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  236915. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  236916. #else
  236917. && (lstat (fullPath.toUTF8(), &info) == 0);
  236918. #endif
  236919. }
  236920. bool File::existsAsFile() const
  236921. {
  236922. return exists() && ! isDirectory();
  236923. }
  236924. int64 File::getSize() const
  236925. {
  236926. juce_statStruct info;
  236927. return juce_stat (fullPath, info) ? info.st_size : 0;
  236928. }
  236929. bool File::hasWriteAccess() const
  236930. {
  236931. if (exists())
  236932. return access (fullPath.toUTF8(), W_OK) == 0;
  236933. if ((! isDirectory()) && fullPath.containsChar (separator))
  236934. return getParentDirectory().hasWriteAccess();
  236935. return false;
  236936. }
  236937. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  236938. {
  236939. juce_statStruct info;
  236940. if (! juce_stat (fullPath, info))
  236941. return false;
  236942. info.st_mode &= 0777; // Just permissions
  236943. if (shouldBeReadOnly)
  236944. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  236945. else
  236946. // Give everybody write permission?
  236947. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  236948. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  236949. }
  236950. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  236951. {
  236952. modificationTime = 0;
  236953. accessTime = 0;
  236954. creationTime = 0;
  236955. juce_statStruct info;
  236956. if (juce_stat (fullPath, info))
  236957. {
  236958. modificationTime = (int64) info.st_mtime * 1000;
  236959. accessTime = (int64) info.st_atime * 1000;
  236960. creationTime = (int64) info.st_ctime * 1000;
  236961. }
  236962. }
  236963. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  236964. {
  236965. juce_statStruct info;
  236966. if ((modificationTime != 0 || accessTime != 0) && juce_stat (fullPath, info))
  236967. {
  236968. struct utimbuf times;
  236969. times.actime = accessTime != 0 ? (time_t) (accessTime / 1000) : info.st_atime;
  236970. times.modtime = modificationTime != 0 ? (time_t) (modificationTime / 1000) : info.st_mtime;
  236971. return utime (fullPath.toUTF8(), &times) == 0;
  236972. }
  236973. return false;
  236974. }
  236975. bool File::deleteFile() const
  236976. {
  236977. if (! exists())
  236978. return true;
  236979. if (isDirectory())
  236980. return rmdir (fullPath.toUTF8()) == 0;
  236981. return remove (fullPath.toUTF8()) == 0;
  236982. }
  236983. bool File::moveInternal (const File& dest) const
  236984. {
  236985. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  236986. return true;
  236987. if (hasWriteAccess() && copyInternal (dest))
  236988. {
  236989. if (deleteFile())
  236990. return true;
  236991. dest.deleteFile();
  236992. }
  236993. return false;
  236994. }
  236995. void File::createDirectoryInternal (const String& fileName) const
  236996. {
  236997. mkdir (fileName.toUTF8(), 0777);
  236998. }
  236999. int64 juce_fileSetPosition (void* handle, int64 pos)
  237000. {
  237001. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  237002. return pos;
  237003. return -1;
  237004. }
  237005. void FileInputStream::openHandle()
  237006. {
  237007. totalSize = file.getSize();
  237008. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  237009. if (f != -1)
  237010. fileHandle = (void*) f;
  237011. }
  237012. void FileInputStream::closeHandle()
  237013. {
  237014. if (fileHandle != 0)
  237015. {
  237016. close ((int) (pointer_sized_int) fileHandle);
  237017. fileHandle = 0;
  237018. }
  237019. }
  237020. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  237021. {
  237022. if (fileHandle != 0)
  237023. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  237024. return 0;
  237025. }
  237026. void FileOutputStream::openHandle()
  237027. {
  237028. if (file.exists())
  237029. {
  237030. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  237031. if (f != -1)
  237032. {
  237033. currentPosition = lseek (f, 0, SEEK_END);
  237034. if (currentPosition >= 0)
  237035. fileHandle = (void*) f;
  237036. else
  237037. close (f);
  237038. }
  237039. }
  237040. else
  237041. {
  237042. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  237043. if (f != -1)
  237044. fileHandle = (void*) f;
  237045. }
  237046. }
  237047. void FileOutputStream::closeHandle()
  237048. {
  237049. if (fileHandle != 0)
  237050. {
  237051. close ((int) (pointer_sized_int) fileHandle);
  237052. fileHandle = 0;
  237053. }
  237054. }
  237055. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  237056. {
  237057. if (fileHandle != 0)
  237058. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  237059. return 0;
  237060. }
  237061. void FileOutputStream::flushInternal()
  237062. {
  237063. if (fileHandle != 0)
  237064. fsync ((int) (pointer_sized_int) fileHandle);
  237065. }
  237066. const File juce_getExecutableFile()
  237067. {
  237068. #if JUCE_ANDROID
  237069. // TODO
  237070. return File::nonexistent;
  237071. #else
  237072. Dl_info exeInfo;
  237073. dladdr ((void*) juce_getExecutableFile, &exeInfo); // (can't be a const void* on android)
  237074. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  237075. #endif
  237076. }
  237077. int64 File::getBytesFreeOnVolume() const
  237078. {
  237079. struct statfs buf;
  237080. if (juce_doStatFS (*this, buf))
  237081. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  237082. return 0;
  237083. }
  237084. int64 File::getVolumeTotalSize() const
  237085. {
  237086. struct statfs buf;
  237087. if (juce_doStatFS (*this, buf))
  237088. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  237089. return 0;
  237090. }
  237091. const String File::getVolumeLabel() const
  237092. {
  237093. #if JUCE_MAC
  237094. struct VolAttrBuf
  237095. {
  237096. u_int32_t length;
  237097. attrreference_t mountPointRef;
  237098. char mountPointSpace [MAXPATHLEN];
  237099. } attrBuf;
  237100. struct attrlist attrList;
  237101. zerostruct (attrList);
  237102. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  237103. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  237104. File f (*this);
  237105. for (;;)
  237106. {
  237107. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  237108. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  237109. (int) attrBuf.mountPointRef.attr_length);
  237110. const File parent (f.getParentDirectory());
  237111. if (f == parent)
  237112. break;
  237113. f = parent;
  237114. }
  237115. #endif
  237116. return String::empty;
  237117. }
  237118. int File::getVolumeSerialNumber() const
  237119. {
  237120. int result = 0;
  237121. /* int fd = open (getFullPathName().toUTF8(), O_RDONLY | O_NONBLOCK);
  237122. char info [512];
  237123. #ifndef HDIO_GET_IDENTITY
  237124. #define HDIO_GET_IDENTITY 0x030d
  237125. #endif
  237126. if (ioctl (fd, HDIO_GET_IDENTITY, info) == 0)
  237127. {
  237128. DBG (String (info + 20, 20));
  237129. result = String (info + 20, 20).trim().getIntValue();
  237130. }
  237131. close (fd);*/
  237132. return result;
  237133. }
  237134. void juce_runSystemCommand (const String& command)
  237135. {
  237136. int result = system (command.toUTF8());
  237137. (void) result;
  237138. }
  237139. const String juce_getOutputFromCommand (const String& command)
  237140. {
  237141. // slight bodge here, as we just pipe the output into a temp file and read it...
  237142. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  237143. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  237144. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  237145. String result (tempFile.loadFileAsString());
  237146. tempFile.deleteFile();
  237147. return result;
  237148. }
  237149. class InterProcessLock::Pimpl
  237150. {
  237151. public:
  237152. Pimpl (const String& name, const int timeOutMillisecs)
  237153. : handle (0), refCount (1)
  237154. {
  237155. #if JUCE_MAC
  237156. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  237157. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  237158. #else
  237159. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  237160. #endif
  237161. temp.create();
  237162. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  237163. if (handle != 0)
  237164. {
  237165. struct flock fl;
  237166. zerostruct (fl);
  237167. fl.l_whence = SEEK_SET;
  237168. fl.l_type = F_WRLCK;
  237169. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  237170. for (;;)
  237171. {
  237172. const int result = fcntl (handle, F_SETLK, &fl);
  237173. if (result >= 0)
  237174. return;
  237175. if (errno != EINTR)
  237176. {
  237177. if (timeOutMillisecs == 0
  237178. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  237179. break;
  237180. Thread::sleep (10);
  237181. }
  237182. }
  237183. }
  237184. closeFile();
  237185. }
  237186. ~Pimpl()
  237187. {
  237188. closeFile();
  237189. }
  237190. void closeFile()
  237191. {
  237192. if (handle != 0)
  237193. {
  237194. struct flock fl;
  237195. zerostruct (fl);
  237196. fl.l_whence = SEEK_SET;
  237197. fl.l_type = F_UNLCK;
  237198. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  237199. {}
  237200. close (handle);
  237201. handle = 0;
  237202. }
  237203. }
  237204. int handle, refCount;
  237205. };
  237206. InterProcessLock::InterProcessLock (const String& name_)
  237207. : name (name_)
  237208. {
  237209. }
  237210. InterProcessLock::~InterProcessLock()
  237211. {
  237212. }
  237213. bool InterProcessLock::enter (const int timeOutMillisecs)
  237214. {
  237215. const ScopedLock sl (lock);
  237216. if (pimpl == 0)
  237217. {
  237218. pimpl = new Pimpl (name, timeOutMillisecs);
  237219. if (pimpl->handle == 0)
  237220. pimpl = 0;
  237221. }
  237222. else
  237223. {
  237224. pimpl->refCount++;
  237225. }
  237226. return pimpl != 0;
  237227. }
  237228. void InterProcessLock::exit()
  237229. {
  237230. const ScopedLock sl (lock);
  237231. // Trying to release the lock too many times!
  237232. jassert (pimpl != 0);
  237233. if (pimpl != 0 && --(pimpl->refCount) == 0)
  237234. pimpl = 0;
  237235. }
  237236. void JUCE_API juce_threadEntryPoint (void*);
  237237. void* threadEntryProc (void* userData)
  237238. {
  237239. JUCE_AUTORELEASEPOOL
  237240. juce_threadEntryPoint (userData);
  237241. return 0;
  237242. }
  237243. void Thread::launchThread()
  237244. {
  237245. threadHandle_ = 0;
  237246. pthread_t handle = 0;
  237247. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  237248. {
  237249. pthread_detach (handle);
  237250. threadHandle_ = (void*) handle;
  237251. threadId_ = (ThreadID) threadHandle_;
  237252. }
  237253. }
  237254. void Thread::closeThreadHandle()
  237255. {
  237256. threadId_ = 0;
  237257. threadHandle_ = 0;
  237258. }
  237259. void Thread::killThread()
  237260. {
  237261. if (threadHandle_ != 0)
  237262. {
  237263. #if JUCE_ANDROID
  237264. jassertfalse; // pthread_cancel not available!
  237265. #else
  237266. pthread_cancel ((pthread_t) threadHandle_);
  237267. #endif
  237268. }
  237269. }
  237270. void Thread::setCurrentThreadName (const String& name)
  237271. {
  237272. #if JUCE_MAC
  237273. pthread_setname_np (name.toUTF8());
  237274. #elif JUCE_LINUX
  237275. prctl (PR_SET_NAME, name.toUTF8().getAddress(), 0, 0, 0);
  237276. #endif
  237277. }
  237278. bool Thread::setThreadPriority (void* handle, int priority)
  237279. {
  237280. struct sched_param param;
  237281. int policy;
  237282. priority = jlimit (0, 10, priority);
  237283. if (handle == 0)
  237284. handle = (void*) pthread_self();
  237285. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  237286. return false;
  237287. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  237288. const int minPriority = sched_get_priority_min (policy);
  237289. const int maxPriority = sched_get_priority_max (policy);
  237290. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  237291. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  237292. }
  237293. Thread::ThreadID Thread::getCurrentThreadId()
  237294. {
  237295. return (ThreadID) pthread_self();
  237296. }
  237297. void Thread::yield()
  237298. {
  237299. sched_yield();
  237300. }
  237301. /* Remove this macro if you're having problems compiling the cpu affinity
  237302. calls (the API for these has changed about quite a bit in various Linux
  237303. versions, and a lot of distros seem to ship with obsolete versions)
  237304. */
  237305. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  237306. #define SUPPORT_AFFINITIES 1
  237307. #endif
  237308. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  237309. {
  237310. #if SUPPORT_AFFINITIES
  237311. cpu_set_t affinity;
  237312. CPU_ZERO (&affinity);
  237313. for (int i = 0; i < 32; ++i)
  237314. if ((affinityMask & (1 << i)) != 0)
  237315. CPU_SET (i, &affinity);
  237316. /*
  237317. N.B. If this line causes a compile error, then you've probably not got the latest
  237318. version of glibc installed.
  237319. If you don't want to update your copy of glibc and don't care about cpu affinities,
  237320. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  237321. */
  237322. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  237323. sched_yield();
  237324. #else
  237325. /* affinities aren't supported because either the appropriate header files weren't found,
  237326. or the SUPPORT_AFFINITIES macro was turned off
  237327. */
  237328. jassertfalse;
  237329. (void) affinityMask;
  237330. #endif
  237331. }
  237332. /*** End of inlined file: juce_posix_SharedCode.h ***/
  237333. /*** Start of inlined file: juce_android_Files.cpp ***/
  237334. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237335. // compiled on its own).
  237336. #if JUCE_INCLUDED_FILE
  237337. bool File::copyInternal (const File& dest) const
  237338. {
  237339. // TODO
  237340. FileInputStream in (*this);
  237341. if (dest.deleteFile())
  237342. {
  237343. {
  237344. FileOutputStream out (dest);
  237345. if (out.failedToOpen())
  237346. return false;
  237347. if (out.writeFromInputStream (in, -1) == getSize())
  237348. return true;
  237349. }
  237350. dest.deleteFile();
  237351. }
  237352. return false;
  237353. }
  237354. void File::findFileSystemRoots (Array<File>& destArray)
  237355. {
  237356. // TODO
  237357. destArray.add (File ("/"));
  237358. }
  237359. bool File::isOnCDRomDrive() const
  237360. {
  237361. return false;
  237362. }
  237363. bool File::isOnHardDisk() const
  237364. {
  237365. return true;
  237366. }
  237367. bool File::isOnRemovableDrive() const
  237368. {
  237369. return false;
  237370. }
  237371. bool File::isHidden() const
  237372. {
  237373. // TODO
  237374. return getFileName().startsWithChar ('.');
  237375. }
  237376. namespace
  237377. {
  237378. const File juce_readlink (const String& file, const File& defaultFile)
  237379. {
  237380. const int size = 8192;
  237381. HeapBlock<char> buffer;
  237382. buffer.malloc (size + 4);
  237383. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  237384. if (numBytes > 0 && numBytes <= size)
  237385. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  237386. return defaultFile;
  237387. }
  237388. }
  237389. const File File::getLinkedTarget() const
  237390. {
  237391. // TODO
  237392. return juce_readlink (getFullPathName().toUTF8(), *this);
  237393. }
  237394. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  237395. const File File::getSpecialLocation (const SpecialLocationType type)
  237396. {
  237397. // TODO
  237398. switch (type)
  237399. {
  237400. case userHomeDirectory:
  237401. {
  237402. const char* homeDir = getenv ("HOME");
  237403. if (homeDir == 0)
  237404. {
  237405. struct passwd* const pw = getpwuid (getuid());
  237406. if (pw != 0)
  237407. homeDir = pw->pw_dir;
  237408. }
  237409. return File (String::fromUTF8 (homeDir));
  237410. }
  237411. case userDocumentsDirectory:
  237412. case userMusicDirectory:
  237413. case userMoviesDirectory:
  237414. case userApplicationDataDirectory:
  237415. return File ("~");
  237416. case userDesktopDirectory:
  237417. return File ("~/Desktop");
  237418. case commonApplicationDataDirectory:
  237419. return File ("/var");
  237420. case globalApplicationsDirectory:
  237421. return File ("/usr");
  237422. case tempDirectory:
  237423. {
  237424. File tmp ("/var/tmp");
  237425. if (! tmp.isDirectory())
  237426. {
  237427. tmp = "/tmp";
  237428. if (! tmp.isDirectory())
  237429. tmp = File::getCurrentWorkingDirectory();
  237430. }
  237431. return tmp;
  237432. }
  237433. case invokedExecutableFile:
  237434. if (juce_Argv0 != 0)
  237435. return File (String::fromUTF8 (juce_Argv0));
  237436. // deliberate fall-through...
  237437. case currentExecutableFile:
  237438. case currentApplicationFile:
  237439. return juce_getExecutableFile();
  237440. case hostApplicationPath:
  237441. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  237442. default:
  237443. jassertfalse; // unknown type?
  237444. break;
  237445. }
  237446. return File::nonexistent;
  237447. }
  237448. const String File::getVersion() const
  237449. {
  237450. return String::empty;
  237451. }
  237452. bool File::moveToTrash() const
  237453. {
  237454. if (! exists())
  237455. return true;
  237456. // TODO
  237457. return false;
  237458. }
  237459. class DirectoryIterator::NativeIterator::Pimpl
  237460. {
  237461. public:
  237462. Pimpl (const File& directory, const String& wildCard_)
  237463. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  237464. wildCard (wildCard_),
  237465. dir (opendir (directory.getFullPathName().toUTF8()))
  237466. {
  237467. wildcardUTF8 = wildCard.toUTF8();
  237468. }
  237469. ~Pimpl()
  237470. {
  237471. if (dir != 0)
  237472. closedir (dir);
  237473. }
  237474. bool next (String& filenameFound,
  237475. bool* const isDir, bool* const isHidden, int64* const fileSize,
  237476. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  237477. {
  237478. if (dir != 0)
  237479. {
  237480. for (;;)
  237481. {
  237482. struct dirent* const de = readdir (dir);
  237483. if (de == 0)
  237484. break;
  237485. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  237486. {
  237487. filenameFound = String::fromUTF8 (de->d_name);
  237488. updateStatInfoForFile (parentDir + filenameFound, isDir, fileSize, modTime, creationTime, isReadOnly);
  237489. if (isHidden != 0)
  237490. *isHidden = filenameFound.startsWithChar ('.');
  237491. return true;
  237492. }
  237493. }
  237494. }
  237495. return false;
  237496. }
  237497. private:
  237498. String parentDir, wildCard;
  237499. const char* wildcardUTF8;
  237500. DIR* dir;
  237501. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  237502. };
  237503. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  237504. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  237505. {
  237506. }
  237507. DirectoryIterator::NativeIterator::~NativeIterator()
  237508. {
  237509. }
  237510. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  237511. bool* const isDir, bool* const isHidden, int64* const fileSize,
  237512. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  237513. {
  237514. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  237515. }
  237516. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  237517. {
  237518. }
  237519. void File::revealToUser() const
  237520. {
  237521. }
  237522. #endif
  237523. /*** End of inlined file: juce_android_Files.cpp ***/
  237524. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  237525. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  237526. // compiled on its own).
  237527. #if JUCE_INCLUDED_FILE
  237528. struct NamedPipeInternal
  237529. {
  237530. String pipeInName, pipeOutName;
  237531. int pipeIn, pipeOut;
  237532. bool volatile createdPipe, blocked, stopReadOperation;
  237533. static void signalHandler (int) {}
  237534. };
  237535. void NamedPipe::cancelPendingReads()
  237536. {
  237537. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  237538. {
  237539. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  237540. intern->stopReadOperation = true;
  237541. char buffer [1] = { 0 };
  237542. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  237543. (void) bytesWritten;
  237544. int timeout = 2000;
  237545. while (intern->blocked && --timeout >= 0)
  237546. Thread::sleep (2);
  237547. intern->stopReadOperation = false;
  237548. }
  237549. }
  237550. void NamedPipe::close()
  237551. {
  237552. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  237553. if (intern != 0)
  237554. {
  237555. internal = 0;
  237556. if (intern->pipeIn != -1)
  237557. ::close (intern->pipeIn);
  237558. if (intern->pipeOut != -1)
  237559. ::close (intern->pipeOut);
  237560. if (intern->createdPipe)
  237561. {
  237562. unlink (intern->pipeInName.toUTF8());
  237563. unlink (intern->pipeOutName.toUTF8());
  237564. }
  237565. delete intern;
  237566. }
  237567. }
  237568. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  237569. {
  237570. close();
  237571. NamedPipeInternal* const intern = new NamedPipeInternal();
  237572. internal = intern;
  237573. intern->createdPipe = createPipe;
  237574. intern->blocked = false;
  237575. intern->stopReadOperation = false;
  237576. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  237577. siginterrupt (SIGPIPE, 1);
  237578. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  237579. intern->pipeInName = pipePath + "_in";
  237580. intern->pipeOutName = pipePath + "_out";
  237581. intern->pipeIn = -1;
  237582. intern->pipeOut = -1;
  237583. if (createPipe)
  237584. {
  237585. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  237586. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  237587. {
  237588. delete intern;
  237589. internal = 0;
  237590. return false;
  237591. }
  237592. }
  237593. return true;
  237594. }
  237595. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  237596. {
  237597. int bytesRead = -1;
  237598. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  237599. if (intern != 0)
  237600. {
  237601. intern->blocked = true;
  237602. if (intern->pipeIn == -1)
  237603. {
  237604. if (intern->createdPipe)
  237605. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  237606. else
  237607. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  237608. if (intern->pipeIn == -1)
  237609. {
  237610. intern->blocked = false;
  237611. return -1;
  237612. }
  237613. }
  237614. bytesRead = 0;
  237615. char* p = static_cast<char*> (destBuffer);
  237616. while (bytesRead < maxBytesToRead)
  237617. {
  237618. const int bytesThisTime = maxBytesToRead - bytesRead;
  237619. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  237620. if (numRead <= 0 || intern->stopReadOperation)
  237621. {
  237622. bytesRead = -1;
  237623. break;
  237624. }
  237625. bytesRead += numRead;
  237626. p += bytesRead;
  237627. }
  237628. intern->blocked = false;
  237629. }
  237630. return bytesRead;
  237631. }
  237632. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  237633. {
  237634. int bytesWritten = -1;
  237635. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  237636. if (intern != 0)
  237637. {
  237638. if (intern->pipeOut == -1)
  237639. {
  237640. if (intern->createdPipe)
  237641. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  237642. else
  237643. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  237644. if (intern->pipeOut == -1)
  237645. {
  237646. return -1;
  237647. }
  237648. }
  237649. const char* p = static_cast<const char*> (sourceBuffer);
  237650. bytesWritten = 0;
  237651. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  237652. while (bytesWritten < numBytesToWrite
  237653. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  237654. {
  237655. const int bytesThisTime = numBytesToWrite - bytesWritten;
  237656. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  237657. if (numWritten <= 0)
  237658. {
  237659. bytesWritten = -1;
  237660. break;
  237661. }
  237662. bytesWritten += numWritten;
  237663. p += bytesWritten;
  237664. }
  237665. }
  237666. return bytesWritten;
  237667. }
  237668. #endif
  237669. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  237670. /*** Start of inlined file: juce_android_Threads.cpp ***/
  237671. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237672. // compiled on its own).
  237673. #if JUCE_INCLUDED_FILE
  237674. /*
  237675. Note that a lot of methods that you'd expect to find in this file actually
  237676. live in juce_posix_SharedCode.h!
  237677. */
  237678. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  237679. void Process::setPriority (ProcessPriority prior)
  237680. {
  237681. // TODO
  237682. struct sched_param param;
  237683. int policy, maxp, minp;
  237684. const int p = (int) prior;
  237685. if (p <= 1)
  237686. policy = SCHED_OTHER;
  237687. else
  237688. policy = SCHED_RR;
  237689. minp = sched_get_priority_min (policy);
  237690. maxp = sched_get_priority_max (policy);
  237691. if (p < 2)
  237692. param.sched_priority = 0;
  237693. else if (p == 2 )
  237694. // Set to middle of lower realtime priority range
  237695. param.sched_priority = minp + (maxp - minp) / 4;
  237696. else
  237697. // Set to middle of higher realtime priority range
  237698. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  237699. pthread_setschedparam (pthread_self(), policy, &param);
  237700. }
  237701. void Process::terminate()
  237702. {
  237703. // TODO
  237704. exit (0);
  237705. }
  237706. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  237707. {
  237708. return false;
  237709. }
  237710. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  237711. {
  237712. return juce_isRunningUnderDebugger();
  237713. }
  237714. void Process::raisePrivilege() {}
  237715. void Process::lowerPrivilege() {}
  237716. #endif
  237717. /*** End of inlined file: juce_android_Threads.cpp ***/
  237718. /*** Start of inlined file: juce_android_Network.cpp ***/
  237719. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237720. // compiled on its own).
  237721. #if JUCE_INCLUDED_FILE
  237722. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  237723. {
  237724. // TODO
  237725. }
  237726. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  237727. const String& emailSubject,
  237728. const String& bodyText,
  237729. const StringArray& filesToAttach)
  237730. {
  237731. // TODO
  237732. return false;
  237733. }
  237734. class WebInputStream : public InputStream
  237735. {
  237736. public:
  237737. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  237738. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  237739. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  237740. {
  237741. // TODO
  237742. openedOk = false;
  237743. }
  237744. ~WebInputStream()
  237745. {
  237746. }
  237747. bool isExhausted()
  237748. {
  237749. return true; // TODO
  237750. }
  237751. int64 getPosition()
  237752. {
  237753. return 0; // TODO
  237754. }
  237755. int64 getTotalLength()
  237756. {
  237757. return -1; // TODO
  237758. }
  237759. int read (void* buffer, int bytesToRead)
  237760. {
  237761. // TODO
  237762. return 0;
  237763. }
  237764. bool setPosition (int64 wantedPos)
  237765. {
  237766. // TODO
  237767. return false;
  237768. }
  237769. bool openedOk;
  237770. private:
  237771. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  237772. };
  237773. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  237774. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  237775. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  237776. {
  237777. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  237778. progressCallback, progressCallbackContext,
  237779. headers, timeOutMs, responseHeaders));
  237780. return wi->openedOk ? wi.release() : 0;
  237781. }
  237782. #endif
  237783. /*** End of inlined file: juce_android_Network.cpp ***/
  237784. /*** Start of inlined file: juce_android_Messaging.cpp ***/
  237785. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237786. // compiled on its own).
  237787. #if JUCE_INCLUDED_FILE
  237788. void MessageManager::doPlatformSpecificInitialisation()
  237789. {
  237790. }
  237791. void MessageManager::doPlatformSpecificShutdown()
  237792. {
  237793. }
  237794. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  237795. {
  237796. // TODO
  237797. /*
  237798. The idea here is that this will check the system message queue, pull off a
  237799. message if there is one, deliver it, and return true if a message was delivered.
  237800. If the queue's empty, return false.
  237801. If the message is one of our special ones (i.e. a Message object being delivered,
  237802. this must call MessageManager::getInstance()->deliverMessage() to deliver it
  237803. */
  237804. return true;
  237805. }
  237806. bool juce_postMessageToSystemQueue (Message* message)
  237807. {
  237808. // TODO
  237809. return true;
  237810. }
  237811. class AsyncFunctionCaller : public AsyncUpdater
  237812. {
  237813. public:
  237814. static void* call (MessageCallbackFunction* func_, void* parameter_)
  237815. {
  237816. if (MessageManager::getInstance()->isThisTheMessageThread())
  237817. return func_ (parameter_);
  237818. AsyncFunctionCaller caller (func_, parameter_);
  237819. caller.triggerAsyncUpdate();
  237820. caller.finished.wait();
  237821. return caller.result;
  237822. }
  237823. void handleAsyncUpdate()
  237824. {
  237825. result = (*func) (parameter);
  237826. finished.signal();
  237827. }
  237828. private:
  237829. WaitableEvent finished;
  237830. MessageCallbackFunction* func;
  237831. void* parameter;
  237832. void* volatile result;
  237833. AsyncFunctionCaller (MessageCallbackFunction* func_, void* parameter_)
  237834. : result (0), func (func_), parameter (parameter_)
  237835. {}
  237836. JUCE_DECLARE_NON_COPYABLE (AsyncFunctionCaller);
  237837. };
  237838. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  237839. {
  237840. return AsyncFunctionCaller::call (func, parameter);
  237841. }
  237842. void MessageManager::broadcastMessage (const String&)
  237843. {
  237844. }
  237845. #endif
  237846. /*** End of inlined file: juce_android_Messaging.cpp ***/
  237847. /*** Start of inlined file: juce_android_Fonts.cpp ***/
  237848. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237849. // compiled on its own).
  237850. #if JUCE_INCLUDED_FILE
  237851. const StringArray Font::findAllTypefaceNames()
  237852. {
  237853. StringArray results;
  237854. // TODO
  237855. return results;
  237856. }
  237857. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  237858. {
  237859. // TODO
  237860. defaultSans = "Verdana";
  237861. defaultSerif = "Times";
  237862. defaultFixed = "Lucida Console";
  237863. defaultFallback = "Tahoma";
  237864. }
  237865. class AndroidTypeface : public Typeface
  237866. {
  237867. public:
  237868. AndroidTypeface (const Font& font)
  237869. : Typeface (font.getTypefaceName())
  237870. {
  237871. // TODO
  237872. }
  237873. float getAscent() const
  237874. {
  237875. return 0; // TODO
  237876. }
  237877. float getDescent() const
  237878. {
  237879. return 0; // TODO
  237880. }
  237881. float getStringWidth (const String& text)
  237882. {
  237883. // TODO
  237884. return 0;
  237885. }
  237886. void getGlyphPositions (const String& text, Array<int>& glyphs, Array<float>& xOffsets)
  237887. {
  237888. // TODO
  237889. }
  237890. bool getOutlineForGlyph (int glyphNumber, Path& destPath)
  237891. {
  237892. // TODO
  237893. return false;
  237894. }
  237895. private:
  237896. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidTypeface);
  237897. };
  237898. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  237899. {
  237900. return new AndroidTypeface (font);
  237901. }
  237902. #endif
  237903. /*** End of inlined file: juce_android_Fonts.cpp ***/
  237904. /*** Start of inlined file: juce_android_GraphicsContext.cpp ***/
  237905. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237906. // compiled on its own).
  237907. #if JUCE_INCLUDED_FILE
  237908. // TODO
  237909. class AndroidLowLevelGraphicsContext : public LowLevelGraphicsContext
  237910. {
  237911. public:
  237912. AndroidLowLevelGraphicsContext (const GlobalRef& canvas_)
  237913. : canvas (canvas_)
  237914. {
  237915. }
  237916. ~AndroidLowLevelGraphicsContext()
  237917. {
  237918. }
  237919. bool isVectorDevice() const { return false; }
  237920. void setOrigin (int x, int y)
  237921. {
  237922. }
  237923. void addTransform (const AffineTransform& transform)
  237924. {
  237925. }
  237926. float getScaleFactor()
  237927. {
  237928. return 1.0f;
  237929. }
  237930. bool clipToRectangle (const Rectangle<int>& r)
  237931. {
  237932. return true;
  237933. }
  237934. bool clipToRectangleList (const RectangleList& clipRegion)
  237935. {
  237936. return true;
  237937. }
  237938. void excludeClipRectangle (const Rectangle<int>& r)
  237939. {
  237940. }
  237941. void clipToPath (const Path& path, const AffineTransform& transform)
  237942. {
  237943. }
  237944. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  237945. {
  237946. }
  237947. bool clipRegionIntersects (const Rectangle<int>& r)
  237948. {
  237949. return true;
  237950. }
  237951. const Rectangle<int> getClipBounds() const
  237952. {
  237953. return Rectangle<int> (0, 0, 1000, 1000);
  237954. }
  237955. bool isClipEmpty() const
  237956. {
  237957. return false;
  237958. }
  237959. void saveState()
  237960. {
  237961. }
  237962. void restoreState()
  237963. {
  237964. }
  237965. void beginTransparencyLayer (float opacity)
  237966. {
  237967. }
  237968. void endTransparencyLayer()
  237969. {
  237970. }
  237971. void setFill (const FillType& fillType)
  237972. {
  237973. currentPaint = android.env->NewObject (android.paintClass, android.paintClassConstructor);
  237974. currentPaint.callVoidMethod (android.setColor, fillType.colour.getARGB());
  237975. }
  237976. void setOpacity (float newOpacity)
  237977. {
  237978. }
  237979. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  237980. {
  237981. }
  237982. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  237983. {
  237984. canvas.callVoidMethod (android.drawRect,
  237985. (float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom(),
  237986. currentPaint.get());
  237987. }
  237988. void fillPath (const Path& path, const AffineTransform& transform)
  237989. {
  237990. }
  237991. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles)
  237992. {
  237993. }
  237994. void drawLine (const Line <float>& line)
  237995. {
  237996. }
  237997. void drawVerticalLine (int x, float top, float bottom)
  237998. {
  237999. }
  238000. void drawHorizontalLine (int y, float left, float right)
  238001. {
  238002. }
  238003. void setFont (const Font& newFont)
  238004. {
  238005. }
  238006. const Font getFont()
  238007. {
  238008. return Font();
  238009. }
  238010. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  238011. {
  238012. }
  238013. private:
  238014. GlobalRef canvas, currentPaint;
  238015. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidLowLevelGraphicsContext);
  238016. };
  238017. #endif
  238018. /*** End of inlined file: juce_android_GraphicsContext.cpp ***/
  238019. /*** Start of inlined file: juce_android_Windowing.cpp ***/
  238020. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  238021. // compiled on its own).
  238022. #if JUCE_INCLUDED_FILE
  238023. class AndroidComponentPeer : public ComponentPeer
  238024. {
  238025. public:
  238026. AndroidComponentPeer (Component* const component, const int windowStyleFlags)
  238027. : ComponentPeer (component, windowStyleFlags)
  238028. {
  238029. view = GlobalRef (android.env, android.activity.callObjectMethod (android.createNewView));
  238030. }
  238031. ~AndroidComponentPeer()
  238032. {
  238033. android.activity.callVoidMethod (android.deleteView, view.get());
  238034. view = 0;
  238035. }
  238036. void* getNativeHandle() const
  238037. {
  238038. return 0; // TODO
  238039. }
  238040. void setVisible (bool shouldBeVisible)
  238041. {
  238042. }
  238043. void setTitle (const String& title)
  238044. {
  238045. }
  238046. void setPosition (int x, int y)
  238047. {
  238048. // TODO
  238049. }
  238050. void setSize (int w, int h)
  238051. {
  238052. }
  238053. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  238054. {
  238055. DBG ("Window size: " << x << " " << y << " " << w << " " << h);
  238056. view.callVoidMethod (android.layout, x, y, x + w, y + h);
  238057. }
  238058. const Rectangle<int> getBounds() const
  238059. {
  238060. // TODO
  238061. return Rectangle<int>();
  238062. }
  238063. const Point<int> getScreenPosition() const
  238064. {
  238065. // TODO
  238066. return Point<int>();
  238067. }
  238068. const Point<int> localToGlobal (const Point<int>& relativePosition)
  238069. {
  238070. // TODO
  238071. return relativePosition + getScreenPosition();
  238072. }
  238073. const Point<int> globalToLocal (const Point<int>& screenPosition)
  238074. {
  238075. // TODO
  238076. return screenPosition - getScreenPosition();
  238077. }
  238078. void setMinimised (bool shouldBeMinimised)
  238079. {
  238080. // TODO
  238081. }
  238082. bool isMinimised() const
  238083. {
  238084. }
  238085. void setFullScreen (bool shouldBeFullScreen)
  238086. {
  238087. // TODO
  238088. }
  238089. bool isFullScreen() const
  238090. {
  238091. // TODO
  238092. return false;
  238093. }
  238094. void setIcon (const Image& newIcon)
  238095. {
  238096. // TODO
  238097. }
  238098. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  238099. {
  238100. // TODO
  238101. return isPositiveAndBelow (position.getX(), component->getWidth())
  238102. && isPositiveAndBelow (position.getY(), component->getHeight());
  238103. }
  238104. const BorderSize<int> getFrameSize() const
  238105. {
  238106. // TODO
  238107. return BorderSize<int>();
  238108. }
  238109. bool setAlwaysOnTop (bool alwaysOnTop)
  238110. {
  238111. // TODO
  238112. return false;
  238113. }
  238114. void toFront (bool makeActive)
  238115. {
  238116. // TODO
  238117. }
  238118. void toBehind (ComponentPeer* other)
  238119. {
  238120. // TODO
  238121. }
  238122. bool isFocused() const
  238123. {
  238124. // TODO
  238125. return false;
  238126. }
  238127. void grabFocus()
  238128. {
  238129. // TODO
  238130. }
  238131. void textInputRequired (const Point<int>& position)
  238132. {
  238133. // TODO
  238134. }
  238135. void handlePaintCallback (JNIEnv* env, jobject canvas)
  238136. {
  238137. AndroidLowLevelGraphicsContext g (GlobalRef (env, canvas));
  238138. handlePaint (g);
  238139. }
  238140. void repaint (const Rectangle<int>& area)
  238141. {
  238142. // TODO
  238143. }
  238144. void performAnyPendingRepaintsNow()
  238145. {
  238146. // TODO
  238147. }
  238148. void setAlpha (float newAlpha)
  238149. {
  238150. // TODO
  238151. }
  238152. static AndroidComponentPeer* findPeerForJavaView (jobject viewToFind)
  238153. {
  238154. for (int i = getNumPeers(); --i >= 0;)
  238155. {
  238156. AndroidComponentPeer* const ap = static_cast <AndroidComponentPeer*> (getPeer(i));
  238157. jassert (dynamic_cast <AndroidComponentPeer*> (getPeer(i)) != 0);
  238158. if (ap->view == viewToFind)
  238159. return ap;
  238160. }
  238161. return 0;
  238162. }
  238163. private:
  238164. GlobalRef view;
  238165. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidComponentPeer);
  238166. };
  238167. #define JUCE_VIEW_CALLBACK(returnType, javaMethodName, params, juceMethodInvocation) \
  238168. JUCE_JNI_CALLBACK (ComponentPeerView, javaMethodName, returnType, params) \
  238169. { \
  238170. AndroidComponentPeer* const peer = AndroidComponentPeer::findPeerForJavaView (view); \
  238171. if (peer != 0) \
  238172. peer->juceMethodInvocation; \
  238173. }
  238174. JUCE_VIEW_CALLBACK (void, handlePaint, (JNIEnv* env, jobject view, jobject canvas),
  238175. handlePaintCallback (env, canvas))
  238176. ComponentPeer* Component::createNewPeer (int styleFlags, void*)
  238177. {
  238178. return new AndroidComponentPeer (this, styleFlags);
  238179. }
  238180. bool Desktop::canUseSemiTransparentWindows() throw()
  238181. {
  238182. return true; // TODO
  238183. }
  238184. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  238185. {
  238186. // TODO
  238187. return upright;
  238188. }
  238189. void Desktop::createMouseInputSources()
  238190. {
  238191. // This creates a mouse input source for each possible finger
  238192. for (int i = 0; i < 10; ++i)
  238193. mouseSources.add (new MouseInputSource (i, false));
  238194. }
  238195. const Point<int> MouseInputSource::getCurrentMousePosition()
  238196. {
  238197. // TODO
  238198. return Point<int>();
  238199. }
  238200. void Desktop::setMousePosition (const Point<int>& newPosition)
  238201. {
  238202. // not needed
  238203. }
  238204. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  238205. {
  238206. // TODO
  238207. return false;
  238208. }
  238209. void ModifierKeys::updateCurrentModifiers() throw()
  238210. {
  238211. // not needed
  238212. }
  238213. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  238214. {
  238215. // TODO
  238216. return ModifierKeys();
  238217. }
  238218. bool Process::isForegroundProcess()
  238219. {
  238220. return true; // TODO
  238221. }
  238222. bool AlertWindow::showNativeDialogBox (const String& title,
  238223. const String& bodyText,
  238224. bool isOkCancel)
  238225. {
  238226. // TODO
  238227. }
  238228. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  238229. {
  238230. return createSoftwareImage (format, width, height, clearImage);
  238231. }
  238232. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  238233. {
  238234. // TODO
  238235. }
  238236. bool Desktop::isScreenSaverEnabled()
  238237. {
  238238. return true;
  238239. }
  238240. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  238241. {
  238242. }
  238243. static int screenWidth = 0, screenHeight = 0;
  238244. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  238245. {
  238246. monitorCoords.add (Rectangle<int> (0, 0, screenWidth, screenHeight));
  238247. }
  238248. JUCE_JNI_CALLBACK (JuceAppActivity, setScreenSize, void, (JNIEnv* env, jobject activity, int w, int h))
  238249. {
  238250. screenWidth = w;
  238251. screenHeight = h;
  238252. }
  238253. const Image juce_createIconForFile (const File& file)
  238254. {
  238255. Image image;
  238256. // TODO
  238257. return image;
  238258. }
  238259. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  238260. {
  238261. return 0;
  238262. }
  238263. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  238264. {
  238265. }
  238266. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  238267. {
  238268. return 0;
  238269. }
  238270. void MouseCursor::showInWindow (ComponentPeer*) const {}
  238271. void MouseCursor::showInAllWindows() const {}
  238272. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  238273. {
  238274. return false;
  238275. }
  238276. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  238277. {
  238278. return false;
  238279. }
  238280. const int extendedKeyModifier = 0x10000;
  238281. const int KeyPress::spaceKey = ' ';
  238282. const int KeyPress::returnKey = 0x0d;
  238283. const int KeyPress::escapeKey = 0x1b;
  238284. const int KeyPress::backspaceKey = 0x7f;
  238285. const int KeyPress::leftKey = extendedKeyModifier + 1;
  238286. const int KeyPress::rightKey = extendedKeyModifier + 2;
  238287. const int KeyPress::upKey = extendedKeyModifier + 3;
  238288. const int KeyPress::downKey = extendedKeyModifier + 4;
  238289. const int KeyPress::pageUpKey = extendedKeyModifier + 5;
  238290. const int KeyPress::pageDownKey = extendedKeyModifier + 6;
  238291. const int KeyPress::endKey = extendedKeyModifier + 7;
  238292. const int KeyPress::homeKey = extendedKeyModifier + 8;
  238293. const int KeyPress::deleteKey = extendedKeyModifier + 9;
  238294. const int KeyPress::insertKey = -1;
  238295. const int KeyPress::tabKey = 9;
  238296. const int KeyPress::F1Key = extendedKeyModifier + 10;
  238297. const int KeyPress::F2Key = extendedKeyModifier + 11;
  238298. const int KeyPress::F3Key = extendedKeyModifier + 12;
  238299. const int KeyPress::F4Key = extendedKeyModifier + 13;
  238300. const int KeyPress::F5Key = extendedKeyModifier + 14;
  238301. const int KeyPress::F6Key = extendedKeyModifier + 16;
  238302. const int KeyPress::F7Key = extendedKeyModifier + 17;
  238303. const int KeyPress::F8Key = extendedKeyModifier + 18;
  238304. const int KeyPress::F9Key = extendedKeyModifier + 19;
  238305. const int KeyPress::F10Key = extendedKeyModifier + 20;
  238306. const int KeyPress::F11Key = extendedKeyModifier + 21;
  238307. const int KeyPress::F12Key = extendedKeyModifier + 22;
  238308. const int KeyPress::F13Key = extendedKeyModifier + 23;
  238309. const int KeyPress::F14Key = extendedKeyModifier + 24;
  238310. const int KeyPress::F15Key = extendedKeyModifier + 25;
  238311. const int KeyPress::F16Key = extendedKeyModifier + 26;
  238312. const int KeyPress::numberPad0 = extendedKeyModifier + 27;
  238313. const int KeyPress::numberPad1 = extendedKeyModifier + 28;
  238314. const int KeyPress::numberPad2 = extendedKeyModifier + 29;
  238315. const int KeyPress::numberPad3 = extendedKeyModifier + 30;
  238316. const int KeyPress::numberPad4 = extendedKeyModifier + 31;
  238317. const int KeyPress::numberPad5 = extendedKeyModifier + 32;
  238318. const int KeyPress::numberPad6 = extendedKeyModifier + 33;
  238319. const int KeyPress::numberPad7 = extendedKeyModifier + 34;
  238320. const int KeyPress::numberPad8 = extendedKeyModifier + 35;
  238321. const int KeyPress::numberPad9 = extendedKeyModifier + 36;
  238322. const int KeyPress::numberPadAdd = extendedKeyModifier + 37;
  238323. const int KeyPress::numberPadSubtract = extendedKeyModifier + 38;
  238324. const int KeyPress::numberPadMultiply = extendedKeyModifier + 39;
  238325. const int KeyPress::numberPadDivide = extendedKeyModifier + 40;
  238326. const int KeyPress::numberPadSeparator = extendedKeyModifier + 41;
  238327. const int KeyPress::numberPadDecimalPoint = extendedKeyModifier + 42;
  238328. const int KeyPress::numberPadEquals = extendedKeyModifier + 43;
  238329. const int KeyPress::numberPadDelete = extendedKeyModifier + 44;
  238330. const int KeyPress::playKey = extendedKeyModifier + 45;
  238331. const int KeyPress::stopKey = extendedKeyModifier + 46;
  238332. const int KeyPress::fastForwardKey = extendedKeyModifier + 47;
  238333. const int KeyPress::rewindKey = extendedKeyModifier + 48;
  238334. #endif
  238335. /*** End of inlined file: juce_android_Windowing.cpp ***/
  238336. /*** Start of inlined file: juce_android_FileChooser.cpp ***/
  238337. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238338. // compiled on its own).
  238339. #if JUCE_INCLUDED_FILE
  238340. void FileChooser::showPlatformDialog (Array<File>& results,
  238341. const String& title,
  238342. const File& currentFileOrDirectory,
  238343. const String& filter,
  238344. bool selectsDirectory,
  238345. bool selectsFiles,
  238346. bool isSaveDialogue,
  238347. bool warnAboutOverwritingExistingFiles,
  238348. bool selectMultipleFiles,
  238349. FilePreviewComponent* extraInfoComponent)
  238350. {
  238351. // TODO
  238352. }
  238353. #endif
  238354. /*** End of inlined file: juce_android_FileChooser.cpp ***/
  238355. /*** Start of inlined file: juce_android_WebBrowserComponent.cpp ***/
  238356. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238357. // compiled on its own).
  238358. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  238359. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  238360. : browser (0),
  238361. blankPageShown (false),
  238362. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  238363. {
  238364. setOpaque (true);
  238365. }
  238366. WebBrowserComponent::~WebBrowserComponent()
  238367. {
  238368. }
  238369. void WebBrowserComponent::goToURL (const String& url,
  238370. const StringArray* headers,
  238371. const MemoryBlock* postData)
  238372. {
  238373. lastURL = url;
  238374. lastHeaders.clear();
  238375. if (headers != 0)
  238376. lastHeaders = *headers;
  238377. lastPostData.setSize (0);
  238378. if (postData != 0)
  238379. lastPostData = *postData;
  238380. blankPageShown = false;
  238381. }
  238382. void WebBrowserComponent::stop()
  238383. {
  238384. }
  238385. void WebBrowserComponent::goBack()
  238386. {
  238387. lastURL = String::empty;
  238388. blankPageShown = false;
  238389. }
  238390. void WebBrowserComponent::goForward()
  238391. {
  238392. lastURL = String::empty;
  238393. }
  238394. void WebBrowserComponent::refresh()
  238395. {
  238396. }
  238397. void WebBrowserComponent::paint (Graphics& g)
  238398. {
  238399. g.fillAll (Colours::white);
  238400. }
  238401. void WebBrowserComponent::checkWindowAssociation()
  238402. {
  238403. }
  238404. void WebBrowserComponent::reloadLastURL()
  238405. {
  238406. if (lastURL.isNotEmpty())
  238407. {
  238408. goToURL (lastURL, &lastHeaders, &lastPostData);
  238409. lastURL = String::empty;
  238410. }
  238411. }
  238412. void WebBrowserComponent::parentHierarchyChanged()
  238413. {
  238414. checkWindowAssociation();
  238415. }
  238416. void WebBrowserComponent::resized()
  238417. {
  238418. }
  238419. void WebBrowserComponent::visibilityChanged()
  238420. {
  238421. checkWindowAssociation();
  238422. }
  238423. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  238424. {
  238425. return true;
  238426. }
  238427. #endif
  238428. /*** End of inlined file: juce_android_WebBrowserComponent.cpp ***/
  238429. /*** Start of inlined file: juce_android_OpenGLComponent.cpp ***/
  238430. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238431. // compiled on its own).
  238432. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  238433. // TODO
  238434. OpenGLContext* OpenGLComponent::createContext()
  238435. {
  238436. return 0;
  238437. }
  238438. void* OpenGLComponent::getNativeWindowHandle() const
  238439. {
  238440. return 0;
  238441. }
  238442. void juce_glViewport (const int w, const int h)
  238443. {
  238444. // glViewport (0, 0, w, h);
  238445. }
  238446. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  238447. OwnedArray <OpenGLPixelFormat>& results)
  238448. {
  238449. }
  238450. #endif
  238451. /*** End of inlined file: juce_android_OpenGLComponent.cpp ***/
  238452. /*** Start of inlined file: juce_android_Midi.cpp ***/
  238453. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238454. // compiled on its own).
  238455. #if JUCE_INCLUDED_FILE
  238456. const StringArray MidiOutput::getDevices()
  238457. {
  238458. StringArray devices;
  238459. return devices;
  238460. }
  238461. int MidiOutput::getDefaultDeviceIndex()
  238462. {
  238463. return 0;
  238464. }
  238465. MidiOutput* MidiOutput::openDevice (int index)
  238466. {
  238467. return 0;
  238468. }
  238469. MidiOutput::~MidiOutput()
  238470. {
  238471. }
  238472. void MidiOutput::reset()
  238473. {
  238474. }
  238475. bool MidiOutput::getVolume (float&, float&)
  238476. {
  238477. return false;
  238478. }
  238479. void MidiOutput::setVolume (float, float)
  238480. {
  238481. }
  238482. void MidiOutput::sendMessageNow (const MidiMessage&)
  238483. {
  238484. }
  238485. MidiInput::MidiInput (const String& name_)
  238486. : name (name_),
  238487. internal (0)
  238488. {
  238489. }
  238490. MidiInput::~MidiInput()
  238491. {
  238492. }
  238493. void MidiInput::start()
  238494. {
  238495. }
  238496. void MidiInput::stop()
  238497. {
  238498. }
  238499. int MidiInput::getDefaultDeviceIndex()
  238500. {
  238501. return 0;
  238502. }
  238503. const StringArray MidiInput::getDevices()
  238504. {
  238505. StringArray devs;
  238506. return devs;
  238507. }
  238508. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  238509. {
  238510. return 0;
  238511. }
  238512. #endif
  238513. /*** End of inlined file: juce_android_Midi.cpp ***/
  238514. /*** Start of inlined file: juce_android_Audio.cpp ***/
  238515. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238516. // compiled on its own).
  238517. #if JUCE_INCLUDED_FILE
  238518. class AndroidAudioIODevice : public AudioIODevice
  238519. {
  238520. public:
  238521. AndroidAudioIODevice (const String& deviceName)
  238522. : AudioIODevice (deviceName, "Audio"),
  238523. callback (0),
  238524. sampleRate (0),
  238525. numInputChannels (0),
  238526. numOutputChannels (0),
  238527. actualBufferSize (0),
  238528. isRunning (false)
  238529. {
  238530. numInputChannels = 2;
  238531. numOutputChannels = 2;
  238532. // TODO
  238533. }
  238534. ~AndroidAudioIODevice()
  238535. {
  238536. close();
  238537. }
  238538. const StringArray getOutputChannelNames()
  238539. {
  238540. StringArray s;
  238541. s.add ("Left"); // TODO
  238542. s.add ("Right");
  238543. return s;
  238544. }
  238545. const StringArray getInputChannelNames()
  238546. {
  238547. StringArray s;
  238548. s.add ("Left");
  238549. s.add ("Right");
  238550. return s;
  238551. }
  238552. int getNumSampleRates() { return 1;}
  238553. double getSampleRate (int index) { return sampleRate; }
  238554. int getNumBufferSizesAvailable() { return 1; }
  238555. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  238556. int getDefaultBufferSize() { return 1024; }
  238557. const String open (const BigInteger& inputChannels,
  238558. const BigInteger& outputChannels,
  238559. double sampleRate,
  238560. int bufferSize)
  238561. {
  238562. close();
  238563. lastError = String::empty;
  238564. int preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  238565. activeOutputChans = outputChannels;
  238566. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  238567. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  238568. activeInputChans = inputChannels;
  238569. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  238570. numInputChannels = activeInputChans.countNumberOfSetBits();
  238571. // TODO
  238572. actualBufferSize = 0; // whatever is possible based on preferredBufferSize
  238573. isRunning = true;
  238574. return lastError;
  238575. }
  238576. void close()
  238577. {
  238578. if (isRunning)
  238579. {
  238580. isRunning = false;
  238581. // TODO
  238582. }
  238583. }
  238584. int getOutputLatencyInSamples()
  238585. {
  238586. return 0; // TODO
  238587. }
  238588. int getInputLatencyInSamples()
  238589. {
  238590. return 0; // TODO
  238591. }
  238592. bool isOpen() { return isRunning; }
  238593. int getCurrentBufferSizeSamples() { return actualBufferSize; }
  238594. int getCurrentBitDepth() { return 16; }
  238595. double getCurrentSampleRate() { return sampleRate; }
  238596. const BigInteger getActiveOutputChannels() const { return activeOutputChans; }
  238597. const BigInteger getActiveInputChannels() const { return activeInputChans; }
  238598. const String getLastError() { return lastError; }
  238599. bool isPlaying() { return isRunning && callback != 0; }
  238600. // TODO
  238601. void start (AudioIODeviceCallback* newCallback)
  238602. {
  238603. if (isRunning && callback != newCallback)
  238604. {
  238605. if (newCallback != 0)
  238606. newCallback->audioDeviceAboutToStart (this);
  238607. const ScopedLock sl (callbackLock);
  238608. callback = newCallback;
  238609. }
  238610. }
  238611. void stop()
  238612. {
  238613. if (isRunning)
  238614. {
  238615. AudioIODeviceCallback* lastCallback;
  238616. {
  238617. const ScopedLock sl (callbackLock);
  238618. lastCallback = callback;
  238619. callback = 0;
  238620. }
  238621. if (lastCallback != 0)
  238622. lastCallback->audioDeviceStopped();
  238623. }
  238624. }
  238625. private:
  238626. CriticalSection callbackLock;
  238627. AudioIODeviceCallback* callback;
  238628. double sampleRate;
  238629. int numInputChannels, numOutputChannels;
  238630. int actualBufferSize;
  238631. bool isRunning;
  238632. String lastError;
  238633. BigInteger activeOutputChans, activeInputChans;
  238634. JUCE_DECLARE_NON_COPYABLE (AndroidAudioIODevice);
  238635. };
  238636. // TODO
  238637. class AndroidAudioIODeviceType : public AudioIODeviceType
  238638. {
  238639. public:
  238640. AndroidAudioIODeviceType()
  238641. : AudioIODeviceType ("Android Audio")
  238642. {
  238643. }
  238644. void scanForDevices()
  238645. {
  238646. }
  238647. const StringArray getDeviceNames (bool wantInputNames) const
  238648. {
  238649. StringArray s;
  238650. s.add ("Android Audio");
  238651. return s;
  238652. }
  238653. int getDefaultDeviceIndex (bool forInput) const
  238654. {
  238655. return 0;
  238656. }
  238657. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  238658. {
  238659. return device != 0 ? 0 : -1;
  238660. }
  238661. bool hasSeparateInputsAndOutputs() const { return false; }
  238662. AudioIODevice* createDevice (const String& outputDeviceName,
  238663. const String& inputDeviceName)
  238664. {
  238665. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  238666. return new AndroidAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  238667. : inputDeviceName);
  238668. return 0;
  238669. }
  238670. private:
  238671. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidAudioIODeviceType);
  238672. };
  238673. AudioIODeviceType* juce_createAudioIODeviceType_Android()
  238674. {
  238675. return new AndroidAudioIODeviceType();
  238676. }
  238677. #endif
  238678. /*** End of inlined file: juce_android_Audio.cpp ***/
  238679. /*** Start of inlined file: juce_android_CameraDevice.cpp ***/
  238680. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238681. // compiled on its own).
  238682. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  238683. // TODO
  238684. class AndroidCameraInternal
  238685. {
  238686. public:
  238687. AndroidCameraInternal()
  238688. {
  238689. }
  238690. ~AndroidCameraInternal()
  238691. {
  238692. }
  238693. private:
  238694. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidCameraInternal);
  238695. };
  238696. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  238697. : name (name_)
  238698. {
  238699. internal = new AndroidCameraInternal();
  238700. // TODO
  238701. }
  238702. CameraDevice::~CameraDevice()
  238703. {
  238704. stopRecording();
  238705. delete static_cast <AndroidCameraInternal*> (internal);
  238706. internal = 0;
  238707. }
  238708. Component* CameraDevice::createViewerComponent()
  238709. {
  238710. // TODO
  238711. return 0;
  238712. }
  238713. const String CameraDevice::getFileExtension()
  238714. {
  238715. return ".m4a"; // TODO correct?
  238716. }
  238717. void CameraDevice::startRecordingToFile (const File& file, int quality)
  238718. {
  238719. // TODO
  238720. }
  238721. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  238722. {
  238723. // TODO
  238724. return Time();
  238725. }
  238726. void CameraDevice::stopRecording()
  238727. {
  238728. // TODO
  238729. }
  238730. void CameraDevice::addListener (Listener* listenerToAdd)
  238731. {
  238732. // TODO
  238733. }
  238734. void CameraDevice::removeListener (Listener* listenerToRemove)
  238735. {
  238736. // TODO
  238737. }
  238738. const StringArray CameraDevice::getAvailableDevices()
  238739. {
  238740. StringArray devs;
  238741. // TODO
  238742. return devs;
  238743. }
  238744. CameraDevice* CameraDevice::openDevice (int index,
  238745. int minWidth, int minHeight,
  238746. int maxWidth, int maxHeight)
  238747. {
  238748. // TODO
  238749. return 0;
  238750. }
  238751. #endif
  238752. /*** End of inlined file: juce_android_CameraDevice.cpp ***/
  238753. END_JUCE_NAMESPACE
  238754. #endif
  238755. /*** End of inlined file: juce_android_NativeCode.cpp ***/
  238756. #endif
  238757. #endif